ip_fw2.c revision 112250
1/*
2 * Copyright (c) 2002 Luigi Rizzo, Universita` di Pisa
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 * 1. Redistributions of source code must retain the above copyright
8 *    notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 *    notice, this list of conditions and the following disclaimer in the
11 *    documentation and/or other materials provided with the distribution.
12 *
13 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
14 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
16 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
17 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
19 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
20 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
21 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23 * SUCH DAMAGE.
24 *
25 * $FreeBSD: head/sys/netinet/ip_fw2.c 112250 2003-03-15 01:13:00Z cjc $
26 */
27
28#define        DEB(x)
29#define        DDB(x) x
30
31/*
32 * Implement IP packet firewall (new version)
33 */
34
35#if !defined(KLD_MODULE)
36#include "opt_ipfw.h"
37#include "opt_ipdn.h"
38#include "opt_ipdivert.h"
39#include "opt_inet.h"
40#ifndef INET
41#error IPFIREWALL requires INET.
42#endif /* INET */
43#endif
44
45#define IPFW2	1
46#if IPFW2
47#include <sys/param.h>
48#include <sys/systm.h>
49#include <sys/malloc.h>
50#include <sys/mbuf.h>
51#include <sys/kernel.h>
52#include <sys/proc.h>
53#include <sys/socket.h>
54#include <sys/socketvar.h>
55#include <sys/sysctl.h>
56#include <sys/syslog.h>
57#include <sys/ucred.h>
58#include <net/if.h>
59#include <net/route.h>
60#include <netinet/in.h>
61#include <netinet/in_systm.h>
62#include <netinet/in_var.h>
63#include <netinet/in_pcb.h>
64#include <netinet/ip.h>
65#include <netinet/ip_var.h>
66#include <netinet/ip_icmp.h>
67#include <netinet/ip_fw.h>
68#include <netinet/ip_dummynet.h>
69#include <netinet/tcp.h>
70#include <netinet/tcp_timer.h>
71#include <netinet/tcp_var.h>
72#include <netinet/tcpip.h>
73#include <netinet/udp.h>
74#include <netinet/udp_var.h>
75
76#include <netinet/if_ether.h> /* XXX for ETHERTYPE_IP */
77
78#include <machine/in_cksum.h>	/* XXX for in_cksum */
79
80/*
81 * XXX This one should go in sys/mbuf.h. It is used to avoid that
82 * a firewall-generated packet loops forever through the firewall.
83 */
84#ifndef	M_SKIP_FIREWALL
85#define M_SKIP_FIREWALL         0x4000
86#endif
87
88/*
89 * set_disable contains one bit per set value (0..31).
90 * If the bit is set, all rules with the corresponding set
91 * are disabled. Set 31 is reserved for the default rule
92 * and CANNOT be disabled.
93 */
94static u_int32_t set_disable;
95
96static int fw_verbose;
97static int verbose_limit;
98
99static struct callout_handle ipfw_timeout_h;
100#define	IPFW_DEFAULT_RULE	65535
101
102/*
103 * list of rules for layer 3
104 */
105static struct ip_fw *layer3_chain;
106
107MALLOC_DEFINE(M_IPFW, "IpFw/IpAcct", "IpFw/IpAcct chain's");
108
109static int fw_debug = 1;
110static int autoinc_step = 100; /* bounded to 1..1000 in add_rule() */
111
112#ifdef SYSCTL_NODE
113SYSCTL_NODE(_net_inet_ip, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall");
114SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, enable,
115    CTLFLAG_RW | CTLFLAG_SECURE3,
116    &fw_enable, 0, "Enable ipfw");
117SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, autoinc_step, CTLFLAG_RW,
118    &autoinc_step, 0, "Rule number autincrement step");
119SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, one_pass,
120    CTLFLAG_RW | CTLFLAG_SECURE3,
121    &fw_one_pass, 0,
122    "Only do a single pass through ipfw when using dummynet(4)");
123SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, debug, CTLFLAG_RW,
124    &fw_debug, 0, "Enable printing of debug ip_fw statements");
125SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose,
126    CTLFLAG_RW | CTLFLAG_SECURE3,
127    &fw_verbose, 0, "Log matches to ipfw rules");
128SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose_limit, CTLFLAG_RW,
129    &verbose_limit, 0, "Set upper limit of matches of ipfw rules logged");
130
131/*
132 * Description of dynamic rules.
133 *
134 * Dynamic rules are stored in lists accessed through a hash table
135 * (ipfw_dyn_v) whose size is curr_dyn_buckets. This value can
136 * be modified through the sysctl variable dyn_buckets which is
137 * updated when the table becomes empty.
138 *
139 * XXX currently there is only one list, ipfw_dyn.
140 *
141 * When a packet is received, its address fields are first masked
142 * with the mask defined for the rule, then hashed, then matched
143 * against the entries in the corresponding list.
144 * Dynamic rules can be used for different purposes:
145 *  + stateful rules;
146 *  + enforcing limits on the number of sessions;
147 *  + in-kernel NAT (not implemented yet)
148 *
149 * The lifetime of dynamic rules is regulated by dyn_*_lifetime,
150 * measured in seconds and depending on the flags.
151 *
152 * The total number of dynamic rules is stored in dyn_count.
153 * The max number of dynamic rules is dyn_max. When we reach
154 * the maximum number of rules we do not create anymore. This is
155 * done to avoid consuming too much memory, but also too much
156 * time when searching on each packet (ideally, we should try instead
157 * to put a limit on the length of the list on each bucket...).
158 *
159 * Each dynamic rule holds a pointer to the parent ipfw rule so
160 * we know what action to perform. Dynamic rules are removed when
161 * the parent rule is deleted. XXX we should make them survive.
162 *
163 * There are some limitations with dynamic rules -- we do not
164 * obey the 'randomized match', and we do not do multiple
165 * passes through the firewall. XXX check the latter!!!
166 */
167static ipfw_dyn_rule **ipfw_dyn_v = NULL;
168static u_int32_t dyn_buckets = 256; /* must be power of 2 */
169static u_int32_t curr_dyn_buckets = 256; /* must be power of 2 */
170
171/*
172 * Timeouts for various events in handing dynamic rules.
173 */
174static u_int32_t dyn_ack_lifetime = 300;
175static u_int32_t dyn_syn_lifetime = 20;
176static u_int32_t dyn_fin_lifetime = 1;
177static u_int32_t dyn_rst_lifetime = 1;
178static u_int32_t dyn_udp_lifetime = 10;
179static u_int32_t dyn_short_lifetime = 5;
180
181/*
182 * Keepalives are sent if dyn_keepalive is set. They are sent every
183 * dyn_keepalive_period seconds, in the last dyn_keepalive_interval
184 * seconds of lifetime of a rule.
185 * dyn_rst_lifetime and dyn_fin_lifetime should be strictly lower
186 * than dyn_keepalive_period.
187 */
188
189static u_int32_t dyn_keepalive_interval = 20;
190static u_int32_t dyn_keepalive_period = 5;
191static u_int32_t dyn_keepalive = 1;	/* do send keepalives */
192
193static u_int32_t static_count;	/* # of static rules */
194static u_int32_t static_len;	/* size in bytes of static rules */
195static u_int32_t dyn_count;		/* # of dynamic rules */
196static u_int32_t dyn_max = 4096;	/* max # of dynamic rules */
197
198SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_buckets, CTLFLAG_RW,
199    &dyn_buckets, 0, "Number of dyn. buckets");
200SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, curr_dyn_buckets, CTLFLAG_RD,
201    &curr_dyn_buckets, 0, "Current Number of dyn. buckets");
202SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_count, CTLFLAG_RD,
203    &dyn_count, 0, "Number of dyn. rules");
204SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_max, CTLFLAG_RW,
205    &dyn_max, 0, "Max number of dyn. rules");
206SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, static_count, CTLFLAG_RD,
207    &static_count, 0, "Number of static rules");
208SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_ack_lifetime, CTLFLAG_RW,
209    &dyn_ack_lifetime, 0, "Lifetime of dyn. rules for acks");
210SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_syn_lifetime, CTLFLAG_RW,
211    &dyn_syn_lifetime, 0, "Lifetime of dyn. rules for syn");
212SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_fin_lifetime, CTLFLAG_RW,
213    &dyn_fin_lifetime, 0, "Lifetime of dyn. rules for fin");
214SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_rst_lifetime, CTLFLAG_RW,
215    &dyn_rst_lifetime, 0, "Lifetime of dyn. rules for rst");
216SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_udp_lifetime, CTLFLAG_RW,
217    &dyn_udp_lifetime, 0, "Lifetime of dyn. rules for UDP");
218SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_short_lifetime, CTLFLAG_RW,
219    &dyn_short_lifetime, 0, "Lifetime of dyn. rules for other situations");
220SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_keepalive, CTLFLAG_RW,
221    &dyn_keepalive, 0, "Enable keepalives for dyn. rules");
222
223#endif /* SYSCTL_NODE */
224
225
226static ip_fw_chk_t	ipfw_chk;
227
228ip_dn_ruledel_t *ip_dn_ruledel_ptr = NULL;	/* hook into dummynet */
229
230/*
231 * This macro maps an ip pointer into a layer3 header pointer of type T
232 */
233#define	L3HDR(T, ip) ((T *)((u_int32_t *)(ip) + (ip)->ip_hl))
234
235static __inline int
236icmptype_match(struct ip *ip, ipfw_insn_u32 *cmd)
237{
238	int type = L3HDR(struct icmp,ip)->icmp_type;
239
240	return (type <= ICMP_MAXTYPE && (cmd->d[0] & (1<<type)) );
241}
242
243#define TT	( (1 << ICMP_ECHO) | (1 << ICMP_ROUTERSOLICIT) | \
244    (1 << ICMP_TSTAMP) | (1 << ICMP_IREQ) | (1 << ICMP_MASKREQ) )
245
246static int
247is_icmp_query(struct ip *ip)
248{
249	int type = L3HDR(struct icmp, ip)->icmp_type;
250	return (type <= ICMP_MAXTYPE && (TT & (1<<type)) );
251}
252#undef TT
253
254/*
255 * The following checks use two arrays of 8 or 16 bits to store the
256 * bits that we want set or clear, respectively. They are in the
257 * low and high half of cmd->arg1 or cmd->d[0].
258 *
259 * We scan options and store the bits we find set. We succeed if
260 *
261 *	(want_set & ~bits) == 0 && (want_clear & ~bits) == want_clear
262 *
263 * The code is sometimes optimized not to store additional variables.
264 */
265
266static int
267flags_match(ipfw_insn *cmd, u_int8_t bits)
268{
269	u_char want_clear;
270	bits = ~bits;
271
272	if ( ((cmd->arg1 & 0xff) & bits) != 0)
273		return 0; /* some bits we want set were clear */
274	want_clear = (cmd->arg1 >> 8) & 0xff;
275	if ( (want_clear & bits) != want_clear)
276		return 0; /* some bits we want clear were set */
277	return 1;
278}
279
280static int
281ipopts_match(struct ip *ip, ipfw_insn *cmd)
282{
283	int optlen, bits = 0;
284	u_char *cp = (u_char *)(ip + 1);
285	int x = (ip->ip_hl << 2) - sizeof (struct ip);
286
287	for (; x > 0; x -= optlen, cp += optlen) {
288		int opt = cp[IPOPT_OPTVAL];
289
290		if (opt == IPOPT_EOL)
291			break;
292		if (opt == IPOPT_NOP)
293			optlen = 1;
294		else {
295			optlen = cp[IPOPT_OLEN];
296			if (optlen <= 0 || optlen > x)
297				return 0; /* invalid or truncated */
298		}
299		switch (opt) {
300
301		default:
302			break;
303
304		case IPOPT_LSRR:
305			bits |= IP_FW_IPOPT_LSRR;
306			break;
307
308		case IPOPT_SSRR:
309			bits |= IP_FW_IPOPT_SSRR;
310			break;
311
312		case IPOPT_RR:
313			bits |= IP_FW_IPOPT_RR;
314			break;
315
316		case IPOPT_TS:
317			bits |= IP_FW_IPOPT_TS;
318			break;
319		}
320	}
321	return (flags_match(cmd, bits));
322}
323
324static int
325tcpopts_match(struct ip *ip, ipfw_insn *cmd)
326{
327	int optlen, bits = 0;
328	struct tcphdr *tcp = L3HDR(struct tcphdr,ip);
329	u_char *cp = (u_char *)(tcp + 1);
330	int x = (tcp->th_off << 2) - sizeof(struct tcphdr);
331
332	for (; x > 0; x -= optlen, cp += optlen) {
333		int opt = cp[0];
334		if (opt == TCPOPT_EOL)
335			break;
336		if (opt == TCPOPT_NOP)
337			optlen = 1;
338		else {
339			optlen = cp[1];
340			if (optlen <= 0)
341				break;
342		}
343
344		switch (opt) {
345
346		default:
347			break;
348
349		case TCPOPT_MAXSEG:
350			bits |= IP_FW_TCPOPT_MSS;
351			break;
352
353		case TCPOPT_WINDOW:
354			bits |= IP_FW_TCPOPT_WINDOW;
355			break;
356
357		case TCPOPT_SACK_PERMITTED:
358		case TCPOPT_SACK:
359			bits |= IP_FW_TCPOPT_SACK;
360			break;
361
362		case TCPOPT_TIMESTAMP:
363			bits |= IP_FW_TCPOPT_TS;
364			break;
365
366		case TCPOPT_CC:
367		case TCPOPT_CCNEW:
368		case TCPOPT_CCECHO:
369			bits |= IP_FW_TCPOPT_CC;
370			break;
371		}
372	}
373	return (flags_match(cmd, bits));
374}
375
376static int
377iface_match(struct ifnet *ifp, ipfw_insn_if *cmd)
378{
379	if (ifp == NULL)	/* no iface with this packet, match fails */
380		return 0;
381	/* Check by name or by IP address */
382	if (cmd->name[0] != '\0') { /* match by name */
383		/* Check unit number (-1 is wildcard) */
384		if (cmd->p.unit != -1 && cmd->p.unit != ifp->if_unit)
385			return(0);
386		/* Check name */
387		if (!strncmp(ifp->if_name, cmd->name, IFNAMSIZ))
388			return(1);
389	} else {
390		struct ifaddr *ia;
391
392		TAILQ_FOREACH(ia, &ifp->if_addrhead, ifa_link) {
393			if (ia->ifa_addr == NULL)
394				continue;
395			if (ia->ifa_addr->sa_family != AF_INET)
396				continue;
397			if (cmd->p.ip.s_addr == ((struct sockaddr_in *)
398			    (ia->ifa_addr))->sin_addr.s_addr)
399				return(1);	/* match */
400		}
401	}
402	return(0);	/* no match, fail ... */
403}
404
405/*
406 * The 'verrevpath' option checks that the interface that an IP packet
407 * arrives on is the same interface that traffic destined for the
408 * packet's source address would be routed out of. This is a measure
409 * to block forged packets. This is also commonly known as "anti-spoofing"
410 * or Unicast Reverse Path Forwarding (Unicast RFP) in Cisco-ese. The
411 * name of the knob is purposely reminisent of the Cisco IOS command,
412 *
413 *   ip verify unicast reverse-path
414 *
415 * which implements the same functionality. But note that syntax is
416 * misleading. The check may be performed on all IP packets whether unicast,
417 * multicast, or broadcast.
418 */
419static int
420verify_rev_path(struct in_addr src, struct ifnet *ifp)
421{
422	static struct route ro;
423	struct sockaddr_in *dst;
424
425	dst = (struct sockaddr_in *)&(ro.ro_dst);
426
427	/* Check if we've cached the route from the previous call. */
428	if (src.s_addr != dst->sin_addr.s_addr) {
429		ro.ro_rt = NULL;
430
431		bzero(dst, sizeof(*dst));
432		dst->sin_family = AF_INET;
433		dst->sin_len = sizeof(*dst);
434		dst->sin_addr = src;
435
436		rtalloc_ign(&ro, RTF_CLONING|RTF_PRCLONING);
437	}
438
439	if ((ro.ro_rt == NULL) || (ifp == NULL) ||
440	    (ro.ro_rt->rt_ifp->if_index != ifp->if_index))
441		return 0;
442
443    	return 1;
444}
445
446
447static u_int64_t norule_counter;	/* counter for ipfw_log(NULL...) */
448
449#define SNPARGS(buf, len) buf + len, sizeof(buf) > len ? sizeof(buf) - len : 0
450#define SNP(buf) buf, sizeof(buf)
451
452/*
453 * We enter here when we have a rule with O_LOG.
454 * XXX this function alone takes about 2Kbytes of code!
455 */
456static void
457ipfw_log(struct ip_fw *f, u_int hlen, struct ether_header *eh,
458	struct mbuf *m, struct ifnet *oif)
459{
460	char *action;
461	int limit_reached = 0;
462	char action2[40], proto[48], fragment[28];
463
464	fragment[0] = '\0';
465	proto[0] = '\0';
466
467	if (f == NULL) {	/* bogus pkt */
468		if (verbose_limit != 0 && norule_counter >= verbose_limit)
469			return;
470		norule_counter++;
471		if (norule_counter == verbose_limit)
472			limit_reached = verbose_limit;
473		action = "Refuse";
474	} else {	/* O_LOG is the first action, find the real one */
475		ipfw_insn *cmd = ACTION_PTR(f);
476		ipfw_insn_log *l = (ipfw_insn_log *)cmd;
477
478		if (l->max_log != 0 && l->log_left == 0)
479			return;
480		l->log_left--;
481		if (l->log_left == 0)
482			limit_reached = l->max_log;
483		cmd += F_LEN(cmd);	/* point to first action */
484		if (cmd->opcode == O_PROB)
485			cmd += F_LEN(cmd);
486
487		action = action2;
488		switch (cmd->opcode) {
489		case O_DENY:
490			action = "Deny";
491			break;
492
493		case O_REJECT:
494			if (cmd->arg1==ICMP_REJECT_RST)
495				action = "Reset";
496			else if (cmd->arg1==ICMP_UNREACH_HOST)
497				action = "Reject";
498			else
499				snprintf(SNPARGS(action2, 0), "Unreach %d",
500					cmd->arg1);
501			break;
502
503		case O_ACCEPT:
504			action = "Accept";
505			break;
506		case O_COUNT:
507			action = "Count";
508			break;
509		case O_DIVERT:
510			snprintf(SNPARGS(action2, 0), "Divert %d",
511				cmd->arg1);
512			break;
513		case O_TEE:
514			snprintf(SNPARGS(action2, 0), "Tee %d",
515				cmd->arg1);
516			break;
517		case O_SKIPTO:
518			snprintf(SNPARGS(action2, 0), "SkipTo %d",
519				cmd->arg1);
520			break;
521		case O_PIPE:
522			snprintf(SNPARGS(action2, 0), "Pipe %d",
523				cmd->arg1);
524			break;
525		case O_QUEUE:
526			snprintf(SNPARGS(action2, 0), "Queue %d",
527				cmd->arg1);
528			break;
529		case O_FORWARD_IP: {
530			ipfw_insn_sa *sa = (ipfw_insn_sa *)cmd;
531			int len;
532
533			len = snprintf(SNPARGS(action2, 0), "Forward to %s",
534				inet_ntoa(sa->sa.sin_addr));
535			if (sa->sa.sin_port)
536				snprintf(SNPARGS(action2, len), ":%d",
537				    sa->sa.sin_port);
538			}
539			break;
540		default:
541			action = "UNKNOWN";
542			break;
543		}
544	}
545
546	if (hlen == 0) {	/* non-ip */
547		snprintf(SNPARGS(proto, 0), "MAC");
548	} else {
549		struct ip *ip = mtod(m, struct ip *);
550		/* these three are all aliases to the same thing */
551		struct icmp *const icmp = L3HDR(struct icmp, ip);
552		struct tcphdr *const tcp = (struct tcphdr *)icmp;
553		struct udphdr *const udp = (struct udphdr *)icmp;
554
555		int ip_off, offset, ip_len;
556
557		int len;
558
559		if (eh != NULL) { /* layer 2 packets are as on the wire */
560			ip_off = ntohs(ip->ip_off);
561			ip_len = ntohs(ip->ip_len);
562		} else {
563			ip_off = ip->ip_off;
564			ip_len = ip->ip_len;
565		}
566		offset = ip_off & IP_OFFMASK;
567		switch (ip->ip_p) {
568		case IPPROTO_TCP:
569			len = snprintf(SNPARGS(proto, 0), "TCP %s",
570			    inet_ntoa(ip->ip_src));
571			if (offset == 0)
572				snprintf(SNPARGS(proto, len), ":%d %s:%d",
573				    ntohs(tcp->th_sport),
574				    inet_ntoa(ip->ip_dst),
575				    ntohs(tcp->th_dport));
576			else
577				snprintf(SNPARGS(proto, len), " %s",
578				    inet_ntoa(ip->ip_dst));
579			break;
580
581		case IPPROTO_UDP:
582			len = snprintf(SNPARGS(proto, 0), "UDP %s",
583				inet_ntoa(ip->ip_src));
584			if (offset == 0)
585				snprintf(SNPARGS(proto, len), ":%d %s:%d",
586				    ntohs(udp->uh_sport),
587				    inet_ntoa(ip->ip_dst),
588				    ntohs(udp->uh_dport));
589			else
590				snprintf(SNPARGS(proto, len), " %s",
591				    inet_ntoa(ip->ip_dst));
592			break;
593
594		case IPPROTO_ICMP:
595			if (offset == 0)
596				len = snprintf(SNPARGS(proto, 0),
597				    "ICMP:%u.%u ",
598				    icmp->icmp_type, icmp->icmp_code);
599			else
600				len = snprintf(SNPARGS(proto, 0), "ICMP ");
601			len += snprintf(SNPARGS(proto, len), "%s",
602			    inet_ntoa(ip->ip_src));
603			snprintf(SNPARGS(proto, len), " %s",
604			    inet_ntoa(ip->ip_dst));
605			break;
606
607		default:
608			len = snprintf(SNPARGS(proto, 0), "P:%d %s", ip->ip_p,
609			    inet_ntoa(ip->ip_src));
610			snprintf(SNPARGS(proto, len), " %s",
611			    inet_ntoa(ip->ip_dst));
612			break;
613		}
614
615		if (ip_off & (IP_MF | IP_OFFMASK))
616			snprintf(SNPARGS(fragment, 0), " (frag %d:%d@%d%s)",
617			     ntohs(ip->ip_id), ip_len - (ip->ip_hl << 2),
618			     offset << 3,
619			     (ip_off & IP_MF) ? "+" : "");
620	}
621	if (oif || m->m_pkthdr.rcvif)
622		log(LOG_SECURITY | LOG_INFO,
623		    "ipfw: %d %s %s %s via %s%d%s\n",
624		    f ? f->rulenum : -1,
625		    action, proto, oif ? "out" : "in",
626		    oif ? oif->if_name : m->m_pkthdr.rcvif->if_name,
627		    oif ? oif->if_unit : m->m_pkthdr.rcvif->if_unit,
628		    fragment);
629	else
630		log(LOG_SECURITY | LOG_INFO,
631		    "ipfw: %d %s %s [no if info]%s\n",
632		    f ? f->rulenum : -1,
633		    action, proto, fragment);
634	if (limit_reached)
635		log(LOG_SECURITY | LOG_NOTICE,
636		    "ipfw: limit %d reached on entry %d\n",
637		    limit_reached, f ? f->rulenum : -1);
638}
639
640/*
641 * IMPORTANT: the hash function for dynamic rules must be commutative
642 * in source and destination (ip,port), because rules are bidirectional
643 * and we want to find both in the same bucket.
644 */
645static __inline int
646hash_packet(struct ipfw_flow_id *id)
647{
648	u_int32_t i;
649
650	i = (id->dst_ip) ^ (id->src_ip) ^ (id->dst_port) ^ (id->src_port);
651	i &= (curr_dyn_buckets - 1);
652	return i;
653}
654
655/**
656 * unlink a dynamic rule from a chain. prev is a pointer to
657 * the previous one, q is a pointer to the rule to delete,
658 * head is a pointer to the head of the queue.
659 * Modifies q and potentially also head.
660 */
661#define UNLINK_DYN_RULE(prev, head, q) {				\
662	ipfw_dyn_rule *old_q = q;					\
663									\
664	/* remove a refcount to the parent */				\
665	if (q->dyn_type == O_LIMIT)					\
666		q->parent->count--;					\
667	DEB(printf("ipfw: unlink entry 0x%08x %d -> 0x%08x %d, %d left\n",\
668		(q->id.src_ip), (q->id.src_port),			\
669		(q->id.dst_ip), (q->id.dst_port), dyn_count-1 ); )	\
670	if (prev != NULL)						\
671		prev->next = q = q->next;				\
672	else								\
673		head = q = q->next;					\
674	dyn_count--;							\
675	free(old_q, M_IPFW); }
676
677#define TIME_LEQ(a,b)       ((int)((a)-(b)) <= 0)
678
679/**
680 * Remove dynamic rules pointing to "rule", or all of them if rule == NULL.
681 *
682 * If keep_me == NULL, rules are deleted even if not expired,
683 * otherwise only expired rules are removed.
684 *
685 * The value of the second parameter is also used to point to identify
686 * a rule we absolutely do not want to remove (e.g. because we are
687 * holding a reference to it -- this is the case with O_LIMIT_PARENT
688 * rules). The pointer is only used for comparison, so any non-null
689 * value will do.
690 */
691static void
692remove_dyn_rule(struct ip_fw *rule, ipfw_dyn_rule *keep_me)
693{
694	static u_int32_t last_remove = 0;
695
696#define FORCE (keep_me == NULL)
697
698	ipfw_dyn_rule *prev, *q;
699	int i, pass = 0, max_pass = 0;
700
701	if (ipfw_dyn_v == NULL || dyn_count == 0)
702		return;
703	/* do not expire more than once per second, it is useless */
704	if (!FORCE && last_remove == time_second)
705		return;
706	last_remove = time_second;
707
708	/*
709	 * because O_LIMIT refer to parent rules, during the first pass only
710	 * remove child and mark any pending LIMIT_PARENT, and remove
711	 * them in a second pass.
712	 */
713next_pass:
714	for (i = 0 ; i < curr_dyn_buckets ; i++) {
715		for (prev=NULL, q = ipfw_dyn_v[i] ; q ; ) {
716			/*
717			 * Logic can become complex here, so we split tests.
718			 */
719			if (q == keep_me)
720				goto next;
721			if (rule != NULL && rule != q->rule)
722				goto next; /* not the one we are looking for */
723			if (q->dyn_type == O_LIMIT_PARENT) {
724				/*
725				 * handle parent in the second pass,
726				 * record we need one.
727				 */
728				max_pass = 1;
729				if (pass == 0)
730					goto next;
731				if (FORCE && q->count != 0 ) {
732					/* XXX should not happen! */
733					printf("ipfw: OUCH! cannot remove rule,"
734					     " count %d\n", q->count);
735				}
736			} else {
737				if (!FORCE &&
738				    !TIME_LEQ( q->expire, time_second ))
739					goto next;
740			}
741			UNLINK_DYN_RULE(prev, ipfw_dyn_v[i], q);
742			continue;
743next:
744			prev=q;
745			q=q->next;
746		}
747	}
748	if (pass++ < max_pass)
749		goto next_pass;
750}
751
752
753/**
754 * lookup a dynamic rule.
755 */
756static ipfw_dyn_rule *
757lookup_dyn_rule(struct ipfw_flow_id *pkt, int *match_direction,
758	struct tcphdr *tcp)
759{
760	/*
761	 * stateful ipfw extensions.
762	 * Lookup into dynamic session queue
763	 */
764#define MATCH_REVERSE	0
765#define MATCH_FORWARD	1
766#define MATCH_NONE	2
767#define MATCH_UNKNOWN	3
768	int i, dir = MATCH_NONE;
769	ipfw_dyn_rule *prev, *q=NULL;
770
771	if (ipfw_dyn_v == NULL)
772		goto done;	/* not found */
773	i = hash_packet( pkt );
774	for (prev=NULL, q = ipfw_dyn_v[i] ; q != NULL ; ) {
775		if (q->dyn_type == O_LIMIT_PARENT)
776			goto next;
777		if (TIME_LEQ( q->expire, time_second)) { /* expire entry */
778			UNLINK_DYN_RULE(prev, ipfw_dyn_v[i], q);
779			continue;
780		}
781		if ( pkt->proto == q->id.proto) {
782			if (pkt->src_ip == q->id.src_ip &&
783			    pkt->dst_ip == q->id.dst_ip &&
784			    pkt->src_port == q->id.src_port &&
785			    pkt->dst_port == q->id.dst_port ) {
786				dir = MATCH_FORWARD;
787				break;
788			}
789			if (pkt->src_ip == q->id.dst_ip &&
790			    pkt->dst_ip == q->id.src_ip &&
791			    pkt->src_port == q->id.dst_port &&
792			    pkt->dst_port == q->id.src_port ) {
793				dir = MATCH_REVERSE;
794				break;
795			}
796		}
797next:
798		prev = q;
799		q = q->next;
800	}
801	if (q == NULL)
802		goto done; /* q = NULL, not found */
803
804	if ( prev != NULL) { /* found and not in front */
805		prev->next = q->next;
806		q->next = ipfw_dyn_v[i];
807		ipfw_dyn_v[i] = q;
808	}
809	if (pkt->proto == IPPROTO_TCP) { /* update state according to flags */
810		u_char flags = pkt->flags & (TH_FIN|TH_SYN|TH_RST);
811
812#define BOTH_SYN	(TH_SYN | (TH_SYN << 8))
813#define BOTH_FIN	(TH_FIN | (TH_FIN << 8))
814		q->state |= (dir == MATCH_FORWARD ) ? flags : (flags << 8);
815		switch (q->state) {
816		case TH_SYN:				/* opening */
817			q->expire = time_second + dyn_syn_lifetime;
818			break;
819
820		case BOTH_SYN:			/* move to established */
821		case BOTH_SYN | TH_FIN :	/* one side tries to close */
822		case BOTH_SYN | (TH_FIN << 8) :
823 			if (tcp) {
824#define _SEQ_GE(a,b) ((int)(a) - (int)(b) >= 0)
825			    u_int32_t ack = ntohl(tcp->th_ack);
826			    if (dir == MATCH_FORWARD) {
827				if (q->ack_fwd == 0 || _SEQ_GE(ack, q->ack_fwd))
828				    q->ack_fwd = ack;
829				else { /* ignore out-of-sequence */
830				    break;
831				}
832			    } else {
833				if (q->ack_rev == 0 || _SEQ_GE(ack, q->ack_rev))
834				    q->ack_rev = ack;
835				else { /* ignore out-of-sequence */
836				    break;
837				}
838			    }
839			}
840			q->expire = time_second + dyn_ack_lifetime;
841			break;
842
843		case BOTH_SYN | BOTH_FIN:	/* both sides closed */
844			if (dyn_fin_lifetime >= dyn_keepalive_period)
845				dyn_fin_lifetime = dyn_keepalive_period - 1;
846			q->expire = time_second + dyn_fin_lifetime;
847			break;
848
849		default:
850#if 0
851			/*
852			 * reset or some invalid combination, but can also
853			 * occur if we use keep-state the wrong way.
854			 */
855			if ( (q->state & ((TH_RST << 8)|TH_RST)) == 0)
856				printf("invalid state: 0x%x\n", q->state);
857#endif
858			if (dyn_rst_lifetime >= dyn_keepalive_period)
859				dyn_rst_lifetime = dyn_keepalive_period - 1;
860			q->expire = time_second + dyn_rst_lifetime;
861			break;
862		}
863	} else if (pkt->proto == IPPROTO_UDP) {
864		q->expire = time_second + dyn_udp_lifetime;
865	} else {
866		/* other protocols */
867		q->expire = time_second + dyn_short_lifetime;
868	}
869done:
870	if (match_direction)
871		*match_direction = dir;
872	return q;
873}
874
875static void
876realloc_dynamic_table(void)
877{
878	/*
879	 * Try reallocation, make sure we have a power of 2 and do
880	 * not allow more than 64k entries. In case of overflow,
881	 * default to 1024.
882	 */
883
884	if (dyn_buckets > 65536)
885		dyn_buckets = 1024;
886	if ((dyn_buckets & (dyn_buckets-1)) != 0) { /* not a power of 2 */
887		dyn_buckets = curr_dyn_buckets; /* reset */
888		return;
889	}
890	curr_dyn_buckets = dyn_buckets;
891	if (ipfw_dyn_v != NULL)
892		free(ipfw_dyn_v, M_IPFW);
893	for (;;) {
894		ipfw_dyn_v = malloc(curr_dyn_buckets * sizeof(ipfw_dyn_rule *),
895		       M_IPFW, M_NOWAIT | M_ZERO);
896		if (ipfw_dyn_v != NULL || curr_dyn_buckets <= 2)
897			break;
898		curr_dyn_buckets /= 2;
899	}
900}
901
902/**
903 * Install state of type 'type' for a dynamic session.
904 * The hash table contains two type of rules:
905 * - regular rules (O_KEEP_STATE)
906 * - rules for sessions with limited number of sess per user
907 *   (O_LIMIT). When they are created, the parent is
908 *   increased by 1, and decreased on delete. In this case,
909 *   the third parameter is the parent rule and not the chain.
910 * - "parent" rules for the above (O_LIMIT_PARENT).
911 */
912static ipfw_dyn_rule *
913add_dyn_rule(struct ipfw_flow_id *id, u_int8_t dyn_type, struct ip_fw *rule)
914{
915	ipfw_dyn_rule *r;
916	int i;
917
918	if (ipfw_dyn_v == NULL ||
919	    (dyn_count == 0 && dyn_buckets != curr_dyn_buckets)) {
920		realloc_dynamic_table();
921		if (ipfw_dyn_v == NULL)
922			return NULL; /* failed ! */
923	}
924	i = hash_packet(id);
925
926	r = malloc(sizeof *r, M_IPFW, M_NOWAIT | M_ZERO);
927	if (r == NULL) {
928		printf ("ipfw: sorry cannot allocate state\n");
929		return NULL;
930	}
931
932	/* increase refcount on parent, and set pointer */
933	if (dyn_type == O_LIMIT) {
934		ipfw_dyn_rule *parent = (ipfw_dyn_rule *)rule;
935		if ( parent->dyn_type != O_LIMIT_PARENT)
936			panic("invalid parent");
937		parent->count++;
938		r->parent = parent;
939		rule = parent->rule;
940	}
941
942	r->id = *id;
943	r->expire = time_second + dyn_syn_lifetime;
944	r->rule = rule;
945	r->dyn_type = dyn_type;
946	r->pcnt = r->bcnt = 0;
947	r->count = 0;
948
949	r->bucket = i;
950	r->next = ipfw_dyn_v[i];
951	ipfw_dyn_v[i] = r;
952	dyn_count++;
953	DEB(printf("ipfw: add dyn entry ty %d 0x%08x %d -> 0x%08x %d, total %d\n",
954	   dyn_type,
955	   (r->id.src_ip), (r->id.src_port),
956	   (r->id.dst_ip), (r->id.dst_port),
957	   dyn_count ); )
958	return r;
959}
960
961/**
962 * lookup dynamic parent rule using pkt and rule as search keys.
963 * If the lookup fails, then install one.
964 */
965static ipfw_dyn_rule *
966lookup_dyn_parent(struct ipfw_flow_id *pkt, struct ip_fw *rule)
967{
968	ipfw_dyn_rule *q;
969	int i;
970
971	if (ipfw_dyn_v) {
972		i = hash_packet( pkt );
973		for (q = ipfw_dyn_v[i] ; q != NULL ; q=q->next)
974			if (q->dyn_type == O_LIMIT_PARENT &&
975			    rule== q->rule &&
976			    pkt->proto == q->id.proto &&
977			    pkt->src_ip == q->id.src_ip &&
978			    pkt->dst_ip == q->id.dst_ip &&
979			    pkt->src_port == q->id.src_port &&
980			    pkt->dst_port == q->id.dst_port) {
981				q->expire = time_second + dyn_short_lifetime;
982				DEB(printf("ipfw: lookup_dyn_parent found 0x%p\n",q);)
983				return q;
984			}
985	}
986	return add_dyn_rule(pkt, O_LIMIT_PARENT, rule);
987}
988
989/**
990 * Install dynamic state for rule type cmd->o.opcode
991 *
992 * Returns 1 (failure) if state is not installed because of errors or because
993 * session limitations are enforced.
994 */
995static int
996install_state(struct ip_fw *rule, ipfw_insn_limit *cmd,
997	struct ip_fw_args *args)
998{
999	static int last_log;
1000
1001	ipfw_dyn_rule *q;
1002
1003	DEB(printf("ipfw: install state type %d 0x%08x %u -> 0x%08x %u\n",
1004	    cmd->o.opcode,
1005	    (args->f_id.src_ip), (args->f_id.src_port),
1006	    (args->f_id.dst_ip), (args->f_id.dst_port) );)
1007
1008	q = lookup_dyn_rule(&args->f_id, NULL, NULL);
1009
1010	if (q != NULL) { /* should never occur */
1011		if (last_log != time_second) {
1012			last_log = time_second;
1013			printf("ipfw: install_state: entry already present, done\n");
1014		}
1015		return 0;
1016	}
1017
1018	if (dyn_count >= dyn_max)
1019		/*
1020		 * Run out of slots, try to remove any expired rule.
1021		 */
1022		remove_dyn_rule(NULL, (ipfw_dyn_rule *)1);
1023
1024	if (dyn_count >= dyn_max) {
1025		if (last_log != time_second) {
1026			last_log = time_second;
1027			printf("ipfw: install_state: Too many dynamic rules\n");
1028		}
1029		return 1; /* cannot install, notify caller */
1030	}
1031
1032	switch (cmd->o.opcode) {
1033	case O_KEEP_STATE: /* bidir rule */
1034		add_dyn_rule(&args->f_id, O_KEEP_STATE, rule);
1035		break;
1036
1037	case O_LIMIT: /* limit number of sessions */
1038	    {
1039		u_int16_t limit_mask = cmd->limit_mask;
1040		struct ipfw_flow_id id;
1041		ipfw_dyn_rule *parent;
1042
1043		DEB(printf("ipfw: installing dyn-limit rule %d\n",
1044		    cmd->conn_limit);)
1045
1046		id.dst_ip = id.src_ip = 0;
1047		id.dst_port = id.src_port = 0;
1048		id.proto = args->f_id.proto;
1049
1050		if (limit_mask & DYN_SRC_ADDR)
1051			id.src_ip = args->f_id.src_ip;
1052		if (limit_mask & DYN_DST_ADDR)
1053			id.dst_ip = args->f_id.dst_ip;
1054		if (limit_mask & DYN_SRC_PORT)
1055			id.src_port = args->f_id.src_port;
1056		if (limit_mask & DYN_DST_PORT)
1057			id.dst_port = args->f_id.dst_port;
1058		parent = lookup_dyn_parent(&id, rule);
1059		if (parent == NULL) {
1060			printf("ipfw: add parent failed\n");
1061			return 1;
1062		}
1063		if (parent->count >= cmd->conn_limit) {
1064			/*
1065			 * See if we can remove some expired rule.
1066			 */
1067			remove_dyn_rule(rule, parent);
1068			if (parent->count >= cmd->conn_limit) {
1069				if (fw_verbose && last_log != time_second) {
1070					last_log = time_second;
1071					log(LOG_SECURITY | LOG_DEBUG,
1072					    "drop session, too many entries\n");
1073				}
1074				return 1;
1075			}
1076		}
1077		add_dyn_rule(&args->f_id, O_LIMIT, (struct ip_fw *)parent);
1078	    }
1079		break;
1080	default:
1081		printf("ipfw: unknown dynamic rule type %u\n", cmd->o.opcode);
1082		return 1;
1083	}
1084	lookup_dyn_rule(&args->f_id, NULL, NULL); /* XXX just set lifetime */
1085	return 0;
1086}
1087
1088/*
1089 * Transmit a TCP packet, containing either a RST or a keepalive.
1090 * When flags & TH_RST, we are sending a RST packet, because of a
1091 * "reset" action matched the packet.
1092 * Otherwise we are sending a keepalive, and flags & TH_
1093 */
1094static void
1095send_pkt(struct ipfw_flow_id *id, u_int32_t seq, u_int32_t ack, int flags)
1096{
1097	struct mbuf *m;
1098	struct ip *ip;
1099	struct tcphdr *tcp;
1100	struct route sro;	/* fake route */
1101
1102	MGETHDR(m, M_DONTWAIT, MT_HEADER);
1103	if (m == 0)
1104		return;
1105	m->m_pkthdr.rcvif = (struct ifnet *)0;
1106	m->m_pkthdr.len = m->m_len = sizeof(struct ip) + sizeof(struct tcphdr);
1107	m->m_data += max_linkhdr;
1108
1109	ip = mtod(m, struct ip *);
1110	bzero(ip, m->m_len);
1111	tcp = (struct tcphdr *)(ip + 1); /* no IP options */
1112	ip->ip_p = IPPROTO_TCP;
1113	tcp->th_off = 5;
1114	/*
1115	 * Assume we are sending a RST (or a keepalive in the reverse
1116	 * direction), swap src and destination addresses and ports.
1117	 */
1118	ip->ip_src.s_addr = htonl(id->dst_ip);
1119	ip->ip_dst.s_addr = htonl(id->src_ip);
1120	tcp->th_sport = htons(id->dst_port);
1121	tcp->th_dport = htons(id->src_port);
1122	if (flags & TH_RST) {	/* we are sending a RST */
1123		if (flags & TH_ACK) {
1124			tcp->th_seq = htonl(ack);
1125			tcp->th_ack = htonl(0);
1126			tcp->th_flags = TH_RST;
1127		} else {
1128			if (flags & TH_SYN)
1129				seq++;
1130			tcp->th_seq = htonl(0);
1131			tcp->th_ack = htonl(seq);
1132			tcp->th_flags = TH_RST | TH_ACK;
1133		}
1134	} else {
1135		/*
1136		 * We are sending a keepalive. flags & TH_SYN determines
1137		 * the direction, forward if set, reverse if clear.
1138		 * NOTE: seq and ack are always assumed to be correct
1139		 * as set by the caller. This may be confusing...
1140		 */
1141		if (flags & TH_SYN) {
1142			/*
1143			 * we have to rewrite the correct addresses!
1144			 */
1145			ip->ip_dst.s_addr = htonl(id->dst_ip);
1146			ip->ip_src.s_addr = htonl(id->src_ip);
1147			tcp->th_dport = htons(id->dst_port);
1148			tcp->th_sport = htons(id->src_port);
1149		}
1150		tcp->th_seq = htonl(seq);
1151		tcp->th_ack = htonl(ack);
1152		tcp->th_flags = TH_ACK;
1153	}
1154	/*
1155	 * set ip_len to the payload size so we can compute
1156	 * the tcp checksum on the pseudoheader
1157	 * XXX check this, could save a couple of words ?
1158	 */
1159	ip->ip_len = htons(sizeof(struct tcphdr));
1160	tcp->th_sum = in_cksum(m, m->m_pkthdr.len);
1161	/*
1162	 * now fill fields left out earlier
1163	 */
1164	ip->ip_ttl = ip_defttl;
1165	ip->ip_len = m->m_pkthdr.len;
1166	bzero (&sro, sizeof (sro));
1167	ip_rtaddr(ip->ip_dst, &sro);
1168	m->m_flags |= M_SKIP_FIREWALL;
1169	ip_output(m, NULL, &sro, 0, NULL, NULL);
1170	if (sro.ro_rt)
1171		RTFREE(sro.ro_rt);
1172}
1173
1174/*
1175 * sends a reject message, consuming the mbuf passed as an argument.
1176 */
1177static void
1178send_reject(struct ip_fw_args *args, int code, int offset, int ip_len)
1179{
1180
1181	if (code != ICMP_REJECT_RST) { /* Send an ICMP unreach */
1182		/* We need the IP header in host order for icmp_error(). */
1183		if (args->eh != NULL) {
1184			struct ip *ip = mtod(args->m, struct ip *);
1185			ip->ip_len = ntohs(ip->ip_len);
1186			ip->ip_off = ntohs(ip->ip_off);
1187		}
1188		icmp_error(args->m, ICMP_UNREACH, code, 0L, 0);
1189	} else if (offset == 0 && args->f_id.proto == IPPROTO_TCP) {
1190		struct tcphdr *const tcp =
1191		    L3HDR(struct tcphdr, mtod(args->m, struct ip *));
1192		if ( (tcp->th_flags & TH_RST) == 0)
1193			send_pkt(&(args->f_id), ntohl(tcp->th_seq),
1194				ntohl(tcp->th_ack),
1195				tcp->th_flags | TH_RST);
1196		m_freem(args->m);
1197	} else
1198		m_freem(args->m);
1199	args->m = NULL;
1200}
1201
1202/**
1203 *
1204 * Given an ip_fw *, lookup_next_rule will return a pointer
1205 * to the next rule, which can be either the jump
1206 * target (for skipto instructions) or the next one in the list (in
1207 * all other cases including a missing jump target).
1208 * The result is also written in the "next_rule" field of the rule.
1209 * Backward jumps are not allowed, so start looking from the next
1210 * rule...
1211 *
1212 * This never returns NULL -- in case we do not have an exact match,
1213 * the next rule is returned. When the ruleset is changed,
1214 * pointers are flushed so we are always correct.
1215 */
1216
1217static struct ip_fw *
1218lookup_next_rule(struct ip_fw *me)
1219{
1220	struct ip_fw *rule = NULL;
1221	ipfw_insn *cmd;
1222
1223	/* look for action, in case it is a skipto */
1224	cmd = ACTION_PTR(me);
1225	if (cmd->opcode == O_LOG)
1226		cmd += F_LEN(cmd);
1227	if ( cmd->opcode == O_SKIPTO )
1228		for (rule = me->next; rule ; rule = rule->next)
1229			if (rule->rulenum >= cmd->arg1)
1230				break;
1231	if (rule == NULL)			/* failure or not a skipto */
1232		rule = me->next;
1233	me->next_rule = rule;
1234	return rule;
1235}
1236
1237/*
1238 * The main check routine for the firewall.
1239 *
1240 * All arguments are in args so we can modify them and return them
1241 * back to the caller.
1242 *
1243 * Parameters:
1244 *
1245 *	args->m	(in/out) The packet; we set to NULL when/if we nuke it.
1246 *		Starts with the IP header.
1247 *	args->eh (in)	Mac header if present, or NULL for layer3 packet.
1248 *	args->oif	Outgoing interface, or NULL if packet is incoming.
1249 *		The incoming interface is in the mbuf. (in)
1250 *	args->divert_rule (in/out)
1251 *		Skip up to the first rule past this rule number;
1252 *		upon return, non-zero port number for divert or tee.
1253 *
1254 *	args->rule	Pointer to the last matching rule (in/out)
1255 *	args->next_hop	Socket we are forwarding to (out).
1256 *	args->f_id	Addresses grabbed from the packet (out)
1257 *
1258 * Return value:
1259 *
1260 *	IP_FW_PORT_DENY_FLAG	the packet must be dropped.
1261 *	0	The packet is to be accepted and routed normally OR
1262 *      	the packet was denied/rejected and has been dropped;
1263 *		in the latter case, *m is equal to NULL upon return.
1264 *	port	Divert the packet to port, with these caveats:
1265 *
1266 *		- If IP_FW_PORT_TEE_FLAG is set, tee the packet instead
1267 *		  of diverting it (ie, 'ipfw tee').
1268 *
1269 *		- If IP_FW_PORT_DYNT_FLAG is set, interpret the lower
1270 *		  16 bits as a dummynet pipe number instead of diverting
1271 */
1272
1273static int
1274ipfw_chk(struct ip_fw_args *args)
1275{
1276	/*
1277	 * Local variables hold state during the processing of a packet.
1278	 *
1279	 * IMPORTANT NOTE: to speed up the processing of rules, there
1280	 * are some assumption on the values of the variables, which
1281	 * are documented here. Should you change them, please check
1282	 * the implementation of the various instructions to make sure
1283	 * that they still work.
1284	 *
1285	 * args->eh	The MAC header. It is non-null for a layer2
1286	 *	packet, it is NULL for a layer-3 packet.
1287	 *
1288	 * m | args->m	Pointer to the mbuf, as received from the caller.
1289	 *	It may change if ipfw_chk() does an m_pullup, or if it
1290	 *	consumes the packet because it calls send_reject().
1291	 *	XXX This has to change, so that ipfw_chk() never modifies
1292	 *	or consumes the buffer.
1293	 * ip	is simply an alias of the value of m, and it is kept
1294	 *	in sync with it (the packet is	supposed to start with
1295	 *	the ip header).
1296	 */
1297	struct mbuf *m = args->m;
1298	struct ip *ip = mtod(m, struct ip *);
1299
1300	/*
1301	 * oif | args->oif	If NULL, ipfw_chk has been called on the
1302	 *	inbound path (ether_input, bdg_forward, ip_input).
1303	 *	If non-NULL, ipfw_chk has been called on the outbound path
1304	 *	(ether_output, ip_output).
1305	 */
1306	struct ifnet *oif = args->oif;
1307
1308	struct ip_fw *f = NULL;		/* matching rule */
1309	int retval = 0;
1310
1311	/*
1312	 * hlen	The length of the IPv4 header.
1313	 *	hlen >0 means we have an IPv4 packet.
1314	 */
1315	u_int hlen = 0;		/* hlen >0 means we have an IP pkt */
1316
1317	/*
1318	 * offset	The offset of a fragment. offset != 0 means that
1319	 *	we have a fragment at this offset of an IPv4 packet.
1320	 *	offset == 0 means that (if this is an IPv4 packet)
1321	 *	this is the first or only fragment.
1322	 */
1323	u_short offset = 0;
1324
1325	/*
1326	 * Local copies of addresses. They are only valid if we have
1327	 * an IP packet.
1328	 *
1329	 * proto	The protocol. Set to 0 for non-ip packets,
1330	 *	or to the protocol read from the packet otherwise.
1331	 *	proto != 0 means that we have an IPv4 packet.
1332	 *
1333	 * src_port, dst_port	port numbers, in HOST format. Only
1334	 *	valid for TCP and UDP packets.
1335	 *
1336	 * src_ip, dst_ip	ip addresses, in NETWORK format.
1337	 *	Only valid for IPv4 packets.
1338	 */
1339	u_int8_t proto;
1340	u_int16_t src_port = 0, dst_port = 0;	/* NOTE: host format	*/
1341	struct in_addr src_ip, dst_ip;		/* NOTE: network format	*/
1342	u_int16_t ip_len=0;
1343	int dyn_dir = MATCH_UNKNOWN;
1344	ipfw_dyn_rule *q = NULL;
1345
1346	if (m->m_flags & M_SKIP_FIREWALL)
1347		return 0;	/* accept */
1348	/*
1349	 * dyn_dir = MATCH_UNKNOWN when rules unchecked,
1350	 * 	MATCH_NONE when checked and not matched (q = NULL),
1351	 *	MATCH_FORWARD or MATCH_REVERSE otherwise (q != NULL)
1352	 */
1353
1354	if (args->eh == NULL ||		/* layer 3 packet */
1355		( m->m_pkthdr.len >= sizeof(struct ip) &&
1356		    ntohs(args->eh->ether_type) == ETHERTYPE_IP))
1357			hlen = ip->ip_hl << 2;
1358
1359	/*
1360	 * Collect parameters into local variables for faster matching.
1361	 */
1362	if (hlen == 0) {	/* do not grab addresses for non-ip pkts */
1363		proto = args->f_id.proto = 0;	/* mark f_id invalid */
1364		goto after_ip_checks;
1365	}
1366
1367	proto = args->f_id.proto = ip->ip_p;
1368	src_ip = ip->ip_src;
1369	dst_ip = ip->ip_dst;
1370	if (args->eh != NULL) { /* layer 2 packets are as on the wire */
1371		offset = ntohs(ip->ip_off) & IP_OFFMASK;
1372		ip_len = ntohs(ip->ip_len);
1373	} else {
1374		offset = ip->ip_off & IP_OFFMASK;
1375		ip_len = ip->ip_len;
1376	}
1377
1378#define PULLUP_TO(len)						\
1379		do {						\
1380			if ((m)->m_len < (len)) {		\
1381			    args->m = m = m_pullup(m, (len));	\
1382			    if (m == 0)				\
1383				goto pullup_failed;		\
1384			    ip = mtod(m, struct ip *);		\
1385			}					\
1386		} while (0)
1387
1388	if (offset == 0) {
1389		switch (proto) {
1390		case IPPROTO_TCP:
1391		    {
1392			struct tcphdr *tcp;
1393
1394			PULLUP_TO(hlen + sizeof(struct tcphdr));
1395			tcp = L3HDR(struct tcphdr, ip);
1396			dst_port = tcp->th_dport;
1397			src_port = tcp->th_sport;
1398			args->f_id.flags = tcp->th_flags;
1399			}
1400			break;
1401
1402		case IPPROTO_UDP:
1403		    {
1404			struct udphdr *udp;
1405
1406			PULLUP_TO(hlen + sizeof(struct udphdr));
1407			udp = L3HDR(struct udphdr, ip);
1408			dst_port = udp->uh_dport;
1409			src_port = udp->uh_sport;
1410			}
1411			break;
1412
1413		case IPPROTO_ICMP:
1414			PULLUP_TO(hlen + 4);	/* type, code and checksum. */
1415			args->f_id.flags = L3HDR(struct icmp, ip)->icmp_type;
1416			break;
1417
1418		default:
1419			break;
1420		}
1421#undef PULLUP_TO
1422	}
1423
1424	args->f_id.src_ip = ntohl(src_ip.s_addr);
1425	args->f_id.dst_ip = ntohl(dst_ip.s_addr);
1426	args->f_id.src_port = src_port = ntohs(src_port);
1427	args->f_id.dst_port = dst_port = ntohs(dst_port);
1428
1429after_ip_checks:
1430	if (args->rule) {
1431		/*
1432		 * Packet has already been tagged. Look for the next rule
1433		 * to restart processing.
1434		 *
1435		 * If fw_one_pass != 0 then just accept it.
1436		 * XXX should not happen here, but optimized out in
1437		 * the caller.
1438		 */
1439		if (fw_one_pass)
1440			return 0;
1441
1442		f = args->rule->next_rule;
1443		if (f == NULL)
1444			f = lookup_next_rule(args->rule);
1445	} else {
1446		/*
1447		 * Find the starting rule. It can be either the first
1448		 * one, or the one after divert_rule if asked so.
1449		 */
1450		int skipto = args->divert_rule;
1451
1452		f = layer3_chain;
1453		if (args->eh == NULL && skipto != 0) {
1454			if (skipto >= IPFW_DEFAULT_RULE)
1455				return(IP_FW_PORT_DENY_FLAG); /* invalid */
1456			while (f && f->rulenum <= skipto)
1457				f = f->next;
1458			if (f == NULL)	/* drop packet */
1459				return(IP_FW_PORT_DENY_FLAG);
1460		}
1461	}
1462	args->divert_rule = 0;	/* reset to avoid confusion later */
1463
1464	/*
1465	 * Now scan the rules, and parse microinstructions for each rule.
1466	 */
1467	for (; f; f = f->next) {
1468		int l, cmdlen;
1469		ipfw_insn *cmd;
1470		int skip_or; /* skip rest of OR block */
1471
1472again:
1473		if (set_disable & (1 << f->set) )
1474			continue;
1475
1476		skip_or = 0;
1477		for (l = f->cmd_len, cmd = f->cmd ; l > 0 ;
1478		    l -= cmdlen, cmd += cmdlen) {
1479			int match;
1480
1481			/*
1482			 * check_body is a jump target used when we find a
1483			 * CHECK_STATE, and need to jump to the body of
1484			 * the target rule.
1485			 */
1486
1487check_body:
1488			cmdlen = F_LEN(cmd);
1489			/*
1490			 * An OR block (insn_1 || .. || insn_n) has the
1491			 * F_OR bit set in all but the last instruction.
1492			 * The first match will set "skip_or", and cause
1493			 * the following instructions to be skipped until
1494			 * past the one with the F_OR bit clear.
1495			 */
1496			if (skip_or) {		/* skip this instruction */
1497				if ((cmd->len & F_OR) == 0)
1498					skip_or = 0;	/* next one is good */
1499				continue;
1500			}
1501			match = 0; /* set to 1 if we succeed */
1502
1503			switch (cmd->opcode) {
1504			/*
1505			 * The first set of opcodes compares the packet's
1506			 * fields with some pattern, setting 'match' if a
1507			 * match is found. At the end of the loop there is
1508			 * logic to deal with F_NOT and F_OR flags associated
1509			 * with the opcode.
1510			 */
1511			case O_NOP:
1512				match = 1;
1513				break;
1514
1515			case O_FORWARD_MAC:
1516				printf("ipfw: opcode %d unimplemented\n",
1517				    cmd->opcode);
1518				break;
1519
1520			case O_GID:
1521			case O_UID:
1522				/*
1523				 * We only check offset == 0 && proto != 0,
1524				 * as this ensures that we have an IPv4
1525				 * packet with the ports info.
1526				 */
1527				if (offset!=0)
1528					break;
1529			    {
1530				struct inpcbinfo *pi;
1531				int wildcard;
1532				struct inpcb *pcb;
1533
1534				if (proto == IPPROTO_TCP) {
1535					wildcard = 0;
1536					pi = &tcbinfo;
1537				} else if (proto == IPPROTO_UDP) {
1538					wildcard = 1;
1539					pi = &udbinfo;
1540				} else
1541					break;
1542
1543				pcb =  (oif) ?
1544					in_pcblookup_hash(pi,
1545					    dst_ip, htons(dst_port),
1546					    src_ip, htons(src_port),
1547					    wildcard, oif) :
1548					in_pcblookup_hash(pi,
1549					    src_ip, htons(src_port),
1550					    dst_ip, htons(dst_port),
1551					    wildcard, NULL);
1552
1553				if (pcb == NULL || pcb->inp_socket == NULL)
1554					break;
1555#if __FreeBSD_version < 500034
1556#define socheckuid(a,b)	((a)->so_cred->cr_uid != (b))
1557#endif
1558				if (cmd->opcode == O_UID) {
1559					match =
1560					  !socheckuid(pcb->inp_socket,
1561					   (uid_t)((ipfw_insn_u32 *)cmd)->d[0]);
1562				} else  {
1563					match = groupmember(
1564					    (uid_t)((ipfw_insn_u32 *)cmd)->d[0],
1565					    pcb->inp_socket->so_cred);
1566				}
1567			    }
1568				break;
1569
1570			case O_RECV:
1571				match = iface_match(m->m_pkthdr.rcvif,
1572				    (ipfw_insn_if *)cmd);
1573				break;
1574
1575			case O_XMIT:
1576				match = iface_match(oif, (ipfw_insn_if *)cmd);
1577				break;
1578
1579			case O_VIA:
1580				match = iface_match(oif ? oif :
1581				    m->m_pkthdr.rcvif, (ipfw_insn_if *)cmd);
1582				break;
1583
1584			case O_MACADDR2:
1585				if (args->eh != NULL) {	/* have MAC header */
1586					u_int32_t *want = (u_int32_t *)
1587						((ipfw_insn_mac *)cmd)->addr;
1588					u_int32_t *mask = (u_int32_t *)
1589						((ipfw_insn_mac *)cmd)->mask;
1590					u_int32_t *hdr = (u_int32_t *)args->eh;
1591
1592					match =
1593					    ( want[0] == (hdr[0] & mask[0]) &&
1594					      want[1] == (hdr[1] & mask[1]) &&
1595					      want[2] == (hdr[2] & mask[2]) );
1596				}
1597				break;
1598
1599			case O_MAC_TYPE:
1600				if (args->eh != NULL) {
1601					u_int16_t t =
1602					    ntohs(args->eh->ether_type);
1603					u_int16_t *p =
1604					    ((ipfw_insn_u16 *)cmd)->ports;
1605					int i;
1606
1607					for (i = cmdlen - 1; !match && i>0;
1608					    i--, p += 2)
1609						match = (t>=p[0] && t<=p[1]);
1610				}
1611				break;
1612
1613			case O_FRAG:
1614				match = (hlen > 0 && offset != 0);
1615				break;
1616
1617			case O_IN:	/* "out" is "not in" */
1618				match = (oif == NULL);
1619				break;
1620
1621			case O_LAYER2:
1622				match = (args->eh != NULL);
1623				break;
1624
1625			case O_PROTO:
1626				/*
1627				 * We do not allow an arg of 0 so the
1628				 * check of "proto" only suffices.
1629				 */
1630				match = (proto == cmd->arg1);
1631				break;
1632
1633			case O_IP_SRC:
1634				match = (hlen > 0 &&
1635				    ((ipfw_insn_ip *)cmd)->addr.s_addr ==
1636				    src_ip.s_addr);
1637				break;
1638
1639			case O_IP_SRC_MASK:
1640				match = (hlen > 0 &&
1641				    ((ipfw_insn_ip *)cmd)->addr.s_addr ==
1642				     (src_ip.s_addr &
1643				     ((ipfw_insn_ip *)cmd)->mask.s_addr));
1644				break;
1645
1646			case O_IP_SRC_ME:
1647				if (hlen > 0) {
1648					struct ifnet *tif;
1649
1650					INADDR_TO_IFP(src_ip, tif);
1651					match = (tif != NULL);
1652				}
1653				break;
1654
1655			case O_IP_DST_SET:
1656			case O_IP_SRC_SET:
1657				if (hlen > 0) {
1658					u_int32_t *d = (u_int32_t *)(cmd+1);
1659					u_int32_t addr =
1660					    cmd->opcode == O_IP_DST_SET ?
1661						args->f_id.dst_ip :
1662						args->f_id.src_ip;
1663
1664					    if (addr < d[0])
1665						    break;
1666					    addr -= d[0]; /* subtract base */
1667					    match = (addr < cmd->arg1) &&
1668						( d[ 1 + (addr>>5)] &
1669						  (1<<(addr & 0x1f)) );
1670				}
1671				break;
1672
1673			case O_IP_DST:
1674				match = (hlen > 0 &&
1675				    ((ipfw_insn_ip *)cmd)->addr.s_addr ==
1676				    dst_ip.s_addr);
1677				break;
1678
1679			case O_IP_DST_MASK:
1680				match = (hlen > 0) &&
1681				    (((ipfw_insn_ip *)cmd)->addr.s_addr ==
1682				     (dst_ip.s_addr &
1683				     ((ipfw_insn_ip *)cmd)->mask.s_addr));
1684				break;
1685
1686			case O_IP_DST_ME:
1687				if (hlen > 0) {
1688					struct ifnet *tif;
1689
1690					INADDR_TO_IFP(dst_ip, tif);
1691					match = (tif != NULL);
1692				}
1693				break;
1694
1695			case O_IP_SRCPORT:
1696			case O_IP_DSTPORT:
1697				/*
1698				 * offset == 0 && proto != 0 is enough
1699				 * to guarantee that we have an IPv4
1700				 * packet with port info.
1701				 */
1702				if ((proto==IPPROTO_UDP || proto==IPPROTO_TCP)
1703				    && offset == 0) {
1704					u_int16_t x =
1705					    (cmd->opcode == O_IP_SRCPORT) ?
1706						src_port : dst_port ;
1707					u_int16_t *p =
1708					    ((ipfw_insn_u16 *)cmd)->ports;
1709					int i;
1710
1711					for (i = cmdlen - 1; !match && i>0;
1712					    i--, p += 2)
1713						match = (x>=p[0] && x<=p[1]);
1714				}
1715				break;
1716
1717			case O_ICMPTYPE:
1718				match = (offset == 0 && proto==IPPROTO_ICMP &&
1719				    icmptype_match(ip, (ipfw_insn_u32 *)cmd) );
1720				break;
1721
1722			case O_IPOPT:
1723				match = (hlen > 0 && ipopts_match(ip, cmd) );
1724				break;
1725
1726			case O_IPVER:
1727				match = (hlen > 0 && cmd->arg1 == ip->ip_v);
1728				break;
1729
1730			case O_IPTTL:
1731				match = (hlen > 0 && cmd->arg1 == ip->ip_ttl);
1732				break;
1733
1734			case O_IPID:
1735				match = (hlen > 0 &&
1736				    cmd->arg1 == ntohs(ip->ip_id));
1737				break;
1738
1739			case O_IPLEN:
1740				match = (hlen > 0 && cmd->arg1 == ip_len);
1741				break;
1742
1743			case O_IPPRECEDENCE:
1744				match = (hlen > 0 &&
1745				    (cmd->arg1 == (ip->ip_tos & 0xe0)) );
1746				break;
1747
1748			case O_IPTOS:
1749				match = (hlen > 0 &&
1750				    flags_match(cmd, ip->ip_tos));
1751				break;
1752
1753			case O_TCPFLAGS:
1754				match = (proto == IPPROTO_TCP && offset == 0 &&
1755				    flags_match(cmd,
1756					L3HDR(struct tcphdr,ip)->th_flags));
1757				break;
1758
1759			case O_TCPOPTS:
1760				match = (proto == IPPROTO_TCP && offset == 0 &&
1761				    tcpopts_match(ip, cmd));
1762				break;
1763
1764			case O_TCPSEQ:
1765				match = (proto == IPPROTO_TCP && offset == 0 &&
1766				    ((ipfw_insn_u32 *)cmd)->d[0] ==
1767					L3HDR(struct tcphdr,ip)->th_seq);
1768				break;
1769
1770			case O_TCPACK:
1771				match = (proto == IPPROTO_TCP && offset == 0 &&
1772				    ((ipfw_insn_u32 *)cmd)->d[0] ==
1773					L3HDR(struct tcphdr,ip)->th_ack);
1774				break;
1775
1776			case O_TCPWIN:
1777				match = (proto == IPPROTO_TCP && offset == 0 &&
1778				    cmd->arg1 ==
1779					L3HDR(struct tcphdr,ip)->th_win);
1780				break;
1781
1782			case O_ESTAB:
1783				/* reject packets which have SYN only */
1784				/* XXX should i also check for TH_ACK ? */
1785				match = (proto == IPPROTO_TCP && offset == 0 &&
1786				    (L3HDR(struct tcphdr,ip)->th_flags &
1787				     (TH_RST | TH_ACK | TH_SYN)) != TH_SYN);
1788				break;
1789
1790			case O_LOG:
1791				if (fw_verbose)
1792					ipfw_log(f, hlen, args->eh, m, oif);
1793				match = 1;
1794				break;
1795
1796			case O_PROB:
1797				match = (random()<((ipfw_insn_u32 *)cmd)->d[0]);
1798				break;
1799
1800			case O_VERREVPATH:
1801				/* Outgoing packets automatically pass/match */
1802				match = ((oif != NULL) ||
1803				    (m->m_pkthdr.rcvif == NULL) ||
1804				    verify_rev_path(src_ip, m->m_pkthdr.rcvif));
1805				break;
1806
1807			/*
1808			 * The second set of opcodes represents 'actions',
1809			 * i.e. the terminal part of a rule once the packet
1810			 * matches all previous patterns.
1811			 * Typically there is only one action for each rule,
1812			 * and the opcode is stored at the end of the rule
1813			 * (but there are exceptions -- see below).
1814			 *
1815			 * In general, here we set retval and terminate the
1816			 * outer loop (would be a 'break 3' in some language,
1817			 * but we need to do a 'goto done').
1818			 *
1819			 * Exceptions:
1820			 * O_COUNT and O_SKIPTO actions:
1821			 *   instead of terminating, we jump to the next rule
1822			 *   ('goto next_rule', equivalent to a 'break 2'),
1823			 *   or to the SKIPTO target ('goto again' after
1824			 *   having set f, cmd and l), respectively.
1825			 *
1826			 * O_LIMIT and O_KEEP_STATE: these opcodes are
1827			 *   not real 'actions', and are stored right
1828			 *   before the 'action' part of the rule.
1829			 *   These opcodes try to install an entry in the
1830			 *   state tables; if successful, we continue with
1831			 *   the next opcode (match=1; break;), otherwise
1832			 *   the packet *   must be dropped
1833			 *   ('goto done' after setting retval);
1834			 *
1835			 * O_PROBE_STATE and O_CHECK_STATE: these opcodes
1836			 *   cause a lookup of the state table, and a jump
1837			 *   to the 'action' part of the parent rule
1838			 *   ('goto check_body') if an entry is found, or
1839			 *   (CHECK_STATE only) a jump to the next rule if
1840			 *   the entry is not found ('goto next_rule').
1841			 *   The result of the lookup is cached to make
1842			 *   further instances of these opcodes are
1843			 *   effectively NOPs.
1844			 */
1845			case O_LIMIT:
1846			case O_KEEP_STATE:
1847				if (install_state(f,
1848				    (ipfw_insn_limit *)cmd, args)) {
1849					retval = IP_FW_PORT_DENY_FLAG;
1850					goto done; /* error/limit violation */
1851				}
1852				match = 1;
1853				break;
1854
1855			case O_PROBE_STATE:
1856			case O_CHECK_STATE:
1857				/*
1858				 * dynamic rules are checked at the first
1859				 * keep-state or check-state occurrence,
1860				 * with the result being stored in dyn_dir.
1861				 * The compiler introduces a PROBE_STATE
1862				 * instruction for us when we have a
1863				 * KEEP_STATE (because PROBE_STATE needs
1864				 * to be run first).
1865				 */
1866				if (dyn_dir == MATCH_UNKNOWN &&
1867				    (q = lookup_dyn_rule(&args->f_id,
1868				     &dyn_dir, proto == IPPROTO_TCP ?
1869					L3HDR(struct tcphdr, ip) : NULL))
1870					!= NULL) {
1871					/*
1872					 * Found dynamic entry, update stats
1873					 * and jump to the 'action' part of
1874					 * the parent rule.
1875					 */
1876					q->pcnt++;
1877					q->bcnt += ip_len;
1878					f = q->rule;
1879					cmd = ACTION_PTR(f);
1880					l = f->cmd_len - f->act_ofs;
1881					goto check_body;
1882				}
1883				/*
1884				 * Dynamic entry not found. If CHECK_STATE,
1885				 * skip to next rule, if PROBE_STATE just
1886				 * ignore and continue with next opcode.
1887				 */
1888				if (cmd->opcode == O_CHECK_STATE)
1889					goto next_rule;
1890				match = 1;
1891				break;
1892
1893			case O_ACCEPT:
1894				retval = 0;	/* accept */
1895				goto done;
1896
1897			case O_PIPE:
1898			case O_QUEUE:
1899				args->rule = f; /* report matching rule */
1900				retval = cmd->arg1 | IP_FW_PORT_DYNT_FLAG;
1901				goto done;
1902
1903			case O_DIVERT:
1904			case O_TEE:
1905				if (args->eh) /* not on layer 2 */
1906					break;
1907				args->divert_rule = f->rulenum;
1908				retval = (cmd->opcode == O_DIVERT) ?
1909				    cmd->arg1 :
1910				    cmd->arg1 | IP_FW_PORT_TEE_FLAG;
1911				goto done;
1912
1913			case O_COUNT:
1914			case O_SKIPTO:
1915				f->pcnt++;	/* update stats */
1916				f->bcnt += ip_len;
1917				f->timestamp = time_second;
1918				if (cmd->opcode == O_COUNT)
1919					goto next_rule;
1920				/* handle skipto */
1921				if (f->next_rule == NULL)
1922					lookup_next_rule(f);
1923				f = f->next_rule;
1924				goto again;
1925
1926			case O_REJECT:
1927				/*
1928				 * Drop the packet and send a reject notice
1929				 * if the packet is not ICMP (or is an ICMP
1930				 * query), and it is not multicast/broadcast.
1931				 */
1932				if (hlen > 0 &&
1933				    (proto != IPPROTO_ICMP ||
1934				     is_icmp_query(ip)) &&
1935				    !(m->m_flags & (M_BCAST|M_MCAST)) &&
1936				    !IN_MULTICAST(dst_ip.s_addr)) {
1937					send_reject(args, cmd->arg1,
1938					    offset,ip_len);
1939					m = args->m;
1940				}
1941				/* FALLTHROUGH */
1942			case O_DENY:
1943				retval = IP_FW_PORT_DENY_FLAG;
1944				goto done;
1945
1946			case O_FORWARD_IP:
1947				if (args->eh)	/* not valid on layer2 pkts */
1948					break;
1949				if (!q || dyn_dir == MATCH_FORWARD)
1950					args->next_hop =
1951					    &((ipfw_insn_sa *)cmd)->sa;
1952				retval = 0;
1953				goto done;
1954
1955			default:
1956				panic("-- unknown opcode %d\n", cmd->opcode);
1957			} /* end of switch() on opcodes */
1958
1959			if (cmd->len & F_NOT)
1960				match = !match;
1961
1962			if (match) {
1963				if (cmd->len & F_OR)
1964					skip_or = 1;
1965			} else {
1966				if (!(cmd->len & F_OR)) /* not an OR block, */
1967					break;		/* try next rule    */
1968			}
1969
1970		}	/* end of inner for, scan opcodes */
1971
1972next_rule:;		/* try next rule		*/
1973
1974	}		/* end of outer for, scan rules */
1975	printf("ipfw: ouch!, skip past end of rules, denying packet\n");
1976	return(IP_FW_PORT_DENY_FLAG);
1977
1978done:
1979	/* Update statistics */
1980	f->pcnt++;
1981	f->bcnt += ip_len;
1982	f->timestamp = time_second;
1983	return retval;
1984
1985pullup_failed:
1986	if (fw_verbose)
1987		printf("ipfw: pullup failed\n");
1988	return(IP_FW_PORT_DENY_FLAG);
1989}
1990
1991/*
1992 * When a rule is added/deleted, clear the next_rule pointers in all rules.
1993 * These will be reconstructed on the fly as packets are matched.
1994 * Must be called at splimp().
1995 */
1996static void
1997flush_rule_ptrs(void)
1998{
1999	struct ip_fw *rule;
2000
2001	for (rule = layer3_chain; rule; rule = rule->next)
2002		rule->next_rule = NULL;
2003}
2004
2005/*
2006 * When pipes/queues are deleted, clear the "pipe_ptr" pointer to a given
2007 * pipe/queue, or to all of them (match == NULL).
2008 * Must be called at splimp().
2009 */
2010void
2011flush_pipe_ptrs(struct dn_flow_set *match)
2012{
2013	struct ip_fw *rule;
2014
2015	for (rule = layer3_chain; rule; rule = rule->next) {
2016		ipfw_insn_pipe *cmd = (ipfw_insn_pipe *)ACTION_PTR(rule);
2017
2018		if (cmd->o.opcode != O_PIPE && cmd->o.opcode != O_QUEUE)
2019			continue;
2020		if (match == NULL || cmd->pipe_ptr == match)
2021			cmd->pipe_ptr = NULL;
2022	}
2023}
2024
2025/*
2026 * Add a new rule to the list. Copy the rule into a malloc'ed area, then
2027 * possibly create a rule number and add the rule to the list.
2028 * Update the rule_number in the input struct so the caller knows it as well.
2029 */
2030static int
2031add_rule(struct ip_fw **head, struct ip_fw *input_rule)
2032{
2033	struct ip_fw *rule, *f, *prev;
2034	int s;
2035	int l = RULESIZE(input_rule);
2036
2037	if (*head == NULL && input_rule->rulenum != IPFW_DEFAULT_RULE)
2038		return (EINVAL);
2039
2040	rule = malloc(l, M_IPFW, M_NOWAIT | M_ZERO);
2041	if (rule == NULL)
2042		return (ENOSPC);
2043
2044	bcopy(input_rule, rule, l);
2045
2046	rule->next = NULL;
2047	rule->next_rule = NULL;
2048
2049	rule->pcnt = 0;
2050	rule->bcnt = 0;
2051	rule->timestamp = 0;
2052
2053	s = splimp();
2054
2055	if (*head == NULL) {	/* default rule */
2056		*head = rule;
2057		goto done;
2058        }
2059
2060	/*
2061	 * If rulenum is 0, find highest numbered rule before the
2062	 * default rule, and add autoinc_step
2063	 */
2064	if (autoinc_step < 1)
2065		autoinc_step = 1;
2066	else if (autoinc_step > 1000)
2067		autoinc_step = 1000;
2068	if (rule->rulenum == 0) {
2069		/*
2070		 * locate the highest numbered rule before default
2071		 */
2072		for (f = *head; f; f = f->next) {
2073			if (f->rulenum == IPFW_DEFAULT_RULE)
2074				break;
2075			rule->rulenum = f->rulenum;
2076		}
2077		if (rule->rulenum < IPFW_DEFAULT_RULE - autoinc_step)
2078			rule->rulenum += autoinc_step;
2079		input_rule->rulenum = rule->rulenum;
2080	}
2081
2082	/*
2083	 * Now insert the new rule in the right place in the sorted list.
2084	 */
2085	for (prev = NULL, f = *head; f; prev = f, f = f->next) {
2086		if (f->rulenum > rule->rulenum) { /* found the location */
2087			if (prev) {
2088				rule->next = f;
2089				prev->next = rule;
2090			} else { /* head insert */
2091				rule->next = *head;
2092				*head = rule;
2093			}
2094			break;
2095		}
2096	}
2097	flush_rule_ptrs();
2098done:
2099	static_count++;
2100	static_len += l;
2101	splx(s);
2102	DEB(printf("ipfw: installed rule %d, static count now %d\n",
2103		rule->rulenum, static_count);)
2104	return (0);
2105}
2106
2107/**
2108 * Free storage associated with a static rule (including derived
2109 * dynamic rules).
2110 * The caller is in charge of clearing rule pointers to avoid
2111 * dangling pointers.
2112 * @return a pointer to the next entry.
2113 * Arguments are not checked, so they better be correct.
2114 * Must be called at splimp().
2115 */
2116static struct ip_fw *
2117delete_rule(struct ip_fw **head, struct ip_fw *prev, struct ip_fw *rule)
2118{
2119	struct ip_fw *n;
2120	int l = RULESIZE(rule);
2121
2122	n = rule->next;
2123	remove_dyn_rule(rule, NULL /* force removal */);
2124	if (prev == NULL)
2125		*head = n;
2126	else
2127		prev->next = n;
2128	static_count--;
2129	static_len -= l;
2130
2131	if (DUMMYNET_LOADED)
2132		ip_dn_ruledel_ptr(rule);
2133	free(rule, M_IPFW);
2134	return n;
2135}
2136
2137/*
2138 * Deletes all rules from a chain (including the default rule
2139 * if the second argument is set).
2140 * Must be called at splimp().
2141 */
2142static void
2143free_chain(struct ip_fw **chain, int kill_default)
2144{
2145	struct ip_fw *rule;
2146
2147	flush_rule_ptrs(); /* more efficient to do outside the loop */
2148
2149	while ( (rule = *chain) != NULL &&
2150	    (kill_default || rule->rulenum != IPFW_DEFAULT_RULE) )
2151		delete_rule(chain, NULL, rule);
2152}
2153
2154/**
2155 * Remove all rules with given number, and also do set manipulation.
2156 *
2157 * The argument is an u_int32_t. The low 16 bit are the rule or set number,
2158 * the next 8 bits are the new set, the top 8 bits are the command:
2159 *
2160 *	0	delete rules with given number
2161 *	1	delete rules with given set number
2162 *	2	move rules with given number to new set
2163 *	3	move rules with given set number to new set
2164 *	4	swap sets with given numbers
2165 */
2166static int
2167del_entry(struct ip_fw **chain, u_int32_t arg)
2168{
2169	struct ip_fw *prev, *rule;
2170	int s;
2171	u_int16_t rulenum;
2172	u_int8_t cmd, new_set;
2173
2174	rulenum = arg & 0xffff;
2175	cmd = (arg >> 24) & 0xff;
2176	new_set = (arg >> 16) & 0xff;
2177
2178	if (cmd > 4)
2179		return EINVAL;
2180	if (new_set > 30)
2181		return EINVAL;
2182	if (cmd == 0 || cmd == 2) {
2183		if (rulenum == IPFW_DEFAULT_RULE)
2184			return EINVAL;
2185	} else {
2186		if (rulenum > 30)
2187			return EINVAL;
2188	}
2189
2190	switch (cmd) {
2191	case 0:	/* delete rules with given number */
2192		/*
2193		 * locate first rule to delete
2194		 */
2195		for (prev = NULL, rule = *chain;
2196		    rule && rule->rulenum < rulenum;
2197		     prev = rule, rule = rule->next)
2198			;
2199		if (rule->rulenum != rulenum)
2200			return EINVAL;
2201
2202		s = splimp(); /* no access to rules while removing */
2203		/*
2204		 * flush pointers outside the loop, then delete all matching
2205		 * rules. prev remains the same throughout the cycle.
2206		 */
2207		flush_rule_ptrs();
2208		while (rule && rule->rulenum == rulenum)
2209			rule = delete_rule(chain, prev, rule);
2210		splx(s);
2211		break;
2212
2213	case 1:	/* delete all rules with given set number */
2214		s = splimp();
2215		flush_rule_ptrs();
2216		for (prev = NULL, rule = *chain; rule ; )
2217			if (rule->set == rulenum)
2218				rule = delete_rule(chain, prev, rule);
2219			else {
2220				prev = rule;
2221				rule = rule->next;
2222			}
2223		splx(s);
2224		break;
2225
2226	case 2:	/* move rules with given number to new set */
2227		s = splimp();
2228		for (rule = *chain; rule ; rule = rule->next)
2229			if (rule->rulenum == rulenum)
2230				rule->set = new_set;
2231		splx(s);
2232		break;
2233
2234	case 3: /* move rules with given set number to new set */
2235		s = splimp();
2236		for (rule = *chain; rule ; rule = rule->next)
2237			if (rule->set == rulenum)
2238				rule->set = new_set;
2239		splx(s);
2240		break;
2241
2242	case 4: /* swap two sets */
2243		s = splimp();
2244		for (rule = *chain; rule ; rule = rule->next)
2245			if (rule->set == rulenum)
2246				rule->set = new_set;
2247			else if (rule->set == new_set)
2248				rule->set = rulenum;
2249		splx(s);
2250		break;
2251	}
2252	return 0;
2253}
2254
2255/*
2256 * Clear counters for a specific rule.
2257 */
2258static void
2259clear_counters(struct ip_fw *rule, int log_only)
2260{
2261	ipfw_insn_log *l = (ipfw_insn_log *)ACTION_PTR(rule);
2262
2263	if (log_only == 0) {
2264		rule->bcnt = rule->pcnt = 0;
2265		rule->timestamp = 0;
2266	}
2267	if (l->o.opcode == O_LOG)
2268		l->log_left = l->max_log;
2269}
2270
2271/**
2272 * Reset some or all counters on firewall rules.
2273 * @arg frwl is null to clear all entries, or contains a specific
2274 * rule number.
2275 * @arg log_only is 1 if we only want to reset logs, zero otherwise.
2276 */
2277static int
2278zero_entry(int rulenum, int log_only)
2279{
2280	struct ip_fw *rule;
2281	int s;
2282	char *msg;
2283
2284	if (rulenum == 0) {
2285		s = splimp();
2286		norule_counter = 0;
2287		for (rule = layer3_chain; rule; rule = rule->next)
2288			clear_counters(rule, log_only);
2289		splx(s);
2290		msg = log_only ? "ipfw: All logging counts reset.\n" :
2291				"ipfw: Accounting cleared.\n";
2292	} else {
2293		int cleared = 0;
2294		/*
2295		 * We can have multiple rules with the same number, so we
2296		 * need to clear them all.
2297		 */
2298		for (rule = layer3_chain; rule; rule = rule->next)
2299			if (rule->rulenum == rulenum) {
2300				s = splimp();
2301				while (rule && rule->rulenum == rulenum) {
2302					clear_counters(rule, log_only);
2303					rule = rule->next;
2304				}
2305				splx(s);
2306				cleared = 1;
2307				break;
2308			}
2309		if (!cleared)	/* we did not find any matching rules */
2310			return (EINVAL);
2311		msg = log_only ? "ipfw: Entry %d logging count reset.\n" :
2312				"ipfw: Entry %d cleared.\n";
2313	}
2314	if (fw_verbose)
2315		log(LOG_SECURITY | LOG_NOTICE, msg, rulenum);
2316	return (0);
2317}
2318
2319/*
2320 * Check validity of the structure before insert.
2321 * Fortunately rules are simple, so this mostly need to check rule sizes.
2322 */
2323static int
2324check_ipfw_struct(struct ip_fw *rule, int size)
2325{
2326	int l, cmdlen = 0;
2327	int have_action=0;
2328	ipfw_insn *cmd;
2329
2330	if (size < sizeof(*rule)) {
2331		printf("ipfw: rule too short\n");
2332		return (EINVAL);
2333	}
2334	/* first, check for valid size */
2335	l = RULESIZE(rule);
2336	if (l != size) {
2337		printf("ipfw: size mismatch (have %d want %d)\n", size, l);
2338		return (EINVAL);
2339	}
2340	/*
2341	 * Now go for the individual checks. Very simple ones, basically only
2342	 * instruction sizes.
2343	 */
2344	for (l = rule->cmd_len, cmd = rule->cmd ;
2345			l > 0 ; l -= cmdlen, cmd += cmdlen) {
2346		cmdlen = F_LEN(cmd);
2347		if (cmdlen > l) {
2348			printf("ipfw: opcode %d size truncated\n",
2349			    cmd->opcode);
2350			return EINVAL;
2351		}
2352		DEB(printf("ipfw: opcode %d\n", cmd->opcode);)
2353		switch (cmd->opcode) {
2354		case O_NOP:
2355		case O_PROBE_STATE:
2356		case O_KEEP_STATE:
2357		case O_PROTO:
2358		case O_IP_SRC_ME:
2359		case O_IP_DST_ME:
2360		case O_LAYER2:
2361		case O_IN:
2362		case O_FRAG:
2363		case O_IPOPT:
2364		case O_IPLEN:
2365		case O_IPID:
2366		case O_IPTOS:
2367		case O_IPPRECEDENCE:
2368		case O_IPTTL:
2369		case O_IPVER:
2370		case O_TCPWIN:
2371		case O_TCPFLAGS:
2372		case O_TCPOPTS:
2373		case O_ESTAB:
2374		case O_VERREVPATH:
2375			if (cmdlen != F_INSN_SIZE(ipfw_insn))
2376				goto bad_size;
2377			break;
2378
2379		case O_UID:
2380		case O_GID:
2381		case O_IP_SRC:
2382		case O_IP_DST:
2383		case O_TCPSEQ:
2384		case O_TCPACK:
2385		case O_PROB:
2386		case O_ICMPTYPE:
2387			if (cmdlen != F_INSN_SIZE(ipfw_insn_u32))
2388				goto bad_size;
2389			break;
2390
2391		case O_LIMIT:
2392			if (cmdlen != F_INSN_SIZE(ipfw_insn_limit))
2393				goto bad_size;
2394			break;
2395
2396		case O_LOG:
2397			if (cmdlen != F_INSN_SIZE(ipfw_insn_log))
2398				goto bad_size;
2399
2400			((ipfw_insn_log *)cmd)->log_left =
2401			    ((ipfw_insn_log *)cmd)->max_log;
2402
2403			break;
2404
2405		case O_IP_SRC_MASK:
2406		case O_IP_DST_MASK:
2407			if (cmdlen != F_INSN_SIZE(ipfw_insn_ip))
2408				goto bad_size;
2409			if (((ipfw_insn_ip *)cmd)->mask.s_addr == 0) {
2410				printf("ipfw: opcode %d, useless rule\n",
2411					cmd->opcode);
2412				return EINVAL;
2413			}
2414			break;
2415
2416		case O_IP_SRC_SET:
2417		case O_IP_DST_SET:
2418			if (cmd->arg1 == 0 || cmd->arg1 > 256) {
2419				printf("ipfw: invalid set size %d\n",
2420					cmd->arg1);
2421				return EINVAL;
2422			}
2423			if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
2424			    (cmd->arg1+31)/32 )
2425				goto bad_size;
2426			break;
2427
2428		case O_MACADDR2:
2429			if (cmdlen != F_INSN_SIZE(ipfw_insn_mac))
2430				goto bad_size;
2431			break;
2432
2433		case O_MAC_TYPE:
2434		case O_IP_SRCPORT:
2435		case O_IP_DSTPORT: /* XXX artificial limit, 30 port pairs */
2436			if (cmdlen < 2 || cmdlen > 31)
2437				goto bad_size;
2438			break;
2439
2440		case O_RECV:
2441		case O_XMIT:
2442		case O_VIA:
2443			if (cmdlen != F_INSN_SIZE(ipfw_insn_if))
2444				goto bad_size;
2445			break;
2446
2447		case O_PIPE:
2448		case O_QUEUE:
2449			if (cmdlen != F_INSN_SIZE(ipfw_insn_pipe))
2450				goto bad_size;
2451			goto check_action;
2452
2453		case O_FORWARD_IP:
2454			if (cmdlen != F_INSN_SIZE(ipfw_insn_sa))
2455				goto bad_size;
2456			goto check_action;
2457
2458		case O_FORWARD_MAC: /* XXX not implemented yet */
2459		case O_CHECK_STATE:
2460		case O_COUNT:
2461		case O_ACCEPT:
2462		case O_DENY:
2463		case O_REJECT:
2464		case O_SKIPTO:
2465		case O_DIVERT:
2466		case O_TEE:
2467			if (cmdlen != F_INSN_SIZE(ipfw_insn))
2468				goto bad_size;
2469check_action:
2470			if (have_action) {
2471				printf("ipfw: opcode %d, multiple actions"
2472					" not allowed\n",
2473					cmd->opcode);
2474				return EINVAL;
2475			}
2476			have_action = 1;
2477			if (l != cmdlen) {
2478				printf("ipfw: opcode %d, action must be"
2479					" last opcode\n",
2480					cmd->opcode);
2481				return EINVAL;
2482			}
2483			break;
2484		default:
2485			printf("ipfw: opcode %d, unknown opcode\n",
2486				cmd->opcode);
2487			return EINVAL;
2488		}
2489	}
2490	if (have_action == 0) {
2491		printf("ipfw: missing action\n");
2492		return EINVAL;
2493	}
2494	return 0;
2495
2496bad_size:
2497	printf("ipfw: opcode %d size %d wrong\n",
2498		cmd->opcode, cmdlen);
2499	return EINVAL;
2500}
2501
2502
2503/**
2504 * {set|get}sockopt parser.
2505 */
2506static int
2507ipfw_ctl(struct sockopt *sopt)
2508{
2509	int error, s, rulenum;
2510	size_t size;
2511	struct ip_fw *bp , *buf, *rule;
2512
2513	static u_int32_t rule_buf[255];	/* we copy the data here */
2514
2515	/*
2516	 * Disallow modifications in really-really secure mode, but still allow
2517	 * the logging counters to be reset.
2518	 */
2519	if (sopt->sopt_name == IP_FW_ADD ||
2520	    (sopt->sopt_dir == SOPT_SET && sopt->sopt_name != IP_FW_RESETLOG)) {
2521#if __FreeBSD_version >= 500034
2522		error = securelevel_ge(sopt->sopt_td->td_ucred, 3);
2523		if (error)
2524			return (error);
2525#else /* FreeBSD 4.x */
2526		if (securelevel >= 3)
2527			return (EPERM);
2528#endif
2529	}
2530
2531	error = 0;
2532
2533	switch (sopt->sopt_name) {
2534	case IP_FW_GET:
2535		/*
2536		 * pass up a copy of the current rules. Static rules
2537		 * come first (the last of which has number IPFW_DEFAULT_RULE),
2538		 * followed by a possibly empty list of dynamic rule.
2539		 * The last dynamic rule has NULL in the "next" field.
2540		 */
2541		s = splimp();
2542		size = static_len;	/* size of static rules */
2543		if (ipfw_dyn_v)		/* add size of dyn.rules */
2544			size += (dyn_count * sizeof(ipfw_dyn_rule));
2545
2546		/*
2547		 * XXX todo: if the user passes a short length just to know
2548		 * how much room is needed, do not bother filling up the
2549		 * buffer, just jump to the sooptcopyout.
2550		 */
2551		buf = malloc(size, M_TEMP, M_WAITOK);
2552		if (buf == 0) {
2553			splx(s);
2554			error = ENOBUFS;
2555			break;
2556		}
2557
2558		bp = buf;
2559		for (rule = layer3_chain; rule ; rule = rule->next) {
2560			int i = RULESIZE(rule);
2561			bcopy(rule, bp, i);
2562			((struct ip_fw *)bp)->set_disable = set_disable;
2563			bp = (struct ip_fw *)((char *)bp + i);
2564		}
2565		if (ipfw_dyn_v) {
2566			int i;
2567			ipfw_dyn_rule *p, *dst, *last = NULL;
2568
2569			dst = (ipfw_dyn_rule *)bp;
2570			for (i = 0 ; i < curr_dyn_buckets ; i++ )
2571				for ( p = ipfw_dyn_v[i] ; p != NULL ;
2572				    p = p->next, dst++ ) {
2573					bcopy(p, dst, sizeof *p);
2574					dst->rulenum = p->rule->rulenum;
2575					/*
2576					 * store a non-null value in "next".
2577					 * The userland code will interpret a
2578					 * NULL here as a marker
2579					 * for the last dynamic rule.
2580					 */
2581					dst->next = dst ;
2582					last = dst ;
2583					dst->expire =
2584					    TIME_LEQ(dst->expire, time_second) ?
2585						0 : dst->expire - time_second ;
2586				}
2587			if (last != NULL) /* mark last dynamic rule */
2588				last->next = NULL;
2589		}
2590		splx(s);
2591
2592		error = sooptcopyout(sopt, buf, size);
2593		free(buf, M_TEMP);
2594		break;
2595
2596	case IP_FW_FLUSH:
2597		/*
2598		 * Normally we cannot release the lock on each iteration.
2599		 * We could do it here only because we start from the head all
2600		 * the times so there is no risk of missing some entries.
2601		 * On the other hand, the risk is that we end up with
2602		 * a very inconsistent ruleset, so better keep the lock
2603		 * around the whole cycle.
2604		 *
2605		 * XXX this code can be improved by resetting the head of
2606		 * the list to point to the default rule, and then freeing
2607		 * the old list without the need for a lock.
2608		 */
2609
2610		s = splimp();
2611		free_chain(&layer3_chain, 0 /* keep default rule */);
2612		splx(s);
2613		break;
2614
2615	case IP_FW_ADD:
2616		rule = (struct ip_fw *)rule_buf; /* XXX do a malloc */
2617		error = sooptcopyin(sopt, rule, sizeof(rule_buf),
2618			sizeof(struct ip_fw) );
2619		size = sopt->sopt_valsize;
2620		if (error || (error = check_ipfw_struct(rule, size)))
2621			break;
2622
2623		error = add_rule(&layer3_chain, rule);
2624		size = RULESIZE(rule);
2625		if (!error && sopt->sopt_dir == SOPT_GET)
2626			error = sooptcopyout(sopt, rule, size);
2627		break;
2628
2629	case IP_FW_DEL:
2630		/*
2631		 * IP_FW_DEL is used for deleting single rules or sets,
2632		 * and (ab)used to atomically manipulate sets. Argument size
2633		 * is used to distinguish between the two:
2634		 *    sizeof(u_int32_t)
2635		 *	delete single rule or set of rules,
2636		 *	or reassign rules (or sets) to a different set.
2637		 *    2*sizeof(u_int32_t)
2638		 *	atomic disable/enable sets.
2639		 *	first u_int32_t contains sets to be disabled,
2640		 *	second u_int32_t contains sets to be enabled.
2641		 */
2642		error = sooptcopyin(sopt, rule_buf,
2643			2*sizeof(u_int32_t), sizeof(u_int32_t));
2644		if (error)
2645			break;
2646		size = sopt->sopt_valsize;
2647		if (size == sizeof(u_int32_t))	/* delete or reassign */
2648			error = del_entry(&layer3_chain, rule_buf[0]);
2649		else if (size == 2*sizeof(u_int32_t)) /* set enable/disable */
2650			set_disable =
2651			    (set_disable | rule_buf[0]) & ~rule_buf[1] &
2652			    ~(1<<31); /* set 31 always enabled */
2653		else
2654			error = EINVAL;
2655		break;
2656
2657	case IP_FW_ZERO:
2658	case IP_FW_RESETLOG: /* argument is an int, the rule number */
2659		rulenum=0;
2660
2661		if (sopt->sopt_val != 0) {
2662		    error = sooptcopyin(sopt, &rulenum,
2663			    sizeof(int), sizeof(int));
2664		    if (error)
2665			break;
2666		}
2667		error = zero_entry(rulenum, sopt->sopt_name == IP_FW_RESETLOG);
2668		break;
2669
2670	default:
2671		printf("ipfw: ipfw_ctl invalid option %d\n", sopt->sopt_name);
2672		error = EINVAL;
2673	}
2674
2675	return (error);
2676}
2677
2678/**
2679 * dummynet needs a reference to the default rule, because rules can be
2680 * deleted while packets hold a reference to them. When this happens,
2681 * dummynet changes the reference to the default rule (it could well be a
2682 * NULL pointer, but this way we do not need to check for the special
2683 * case, plus here he have info on the default behaviour).
2684 */
2685struct ip_fw *ip_fw_default_rule;
2686
2687/*
2688 * This procedure is only used to handle keepalives. It is invoked
2689 * every dyn_keepalive_period
2690 */
2691static void
2692ipfw_tick(void * __unused unused)
2693{
2694	int i;
2695	int s;
2696	ipfw_dyn_rule *q;
2697
2698	if (dyn_keepalive == 0 || ipfw_dyn_v == NULL || dyn_count == 0)
2699		goto done;
2700
2701	s = splimp();
2702	for (i = 0 ; i < curr_dyn_buckets ; i++) {
2703		for (q = ipfw_dyn_v[i] ; q ; q = q->next ) {
2704			if (q->dyn_type == O_LIMIT_PARENT)
2705				continue;
2706			if (q->id.proto != IPPROTO_TCP)
2707				continue;
2708			if ( (q->state & BOTH_SYN) != BOTH_SYN)
2709				continue;
2710			if (TIME_LEQ( time_second+dyn_keepalive_interval,
2711			    q->expire))
2712				continue;	/* too early */
2713			if (TIME_LEQ(q->expire, time_second))
2714				continue;	/* too late, rule expired */
2715
2716			send_pkt(&(q->id), q->ack_rev - 1, q->ack_fwd, TH_SYN);
2717			send_pkt(&(q->id), q->ack_fwd - 1, q->ack_rev, 0);
2718		}
2719	}
2720	splx(s);
2721done:
2722	ipfw_timeout_h = timeout(ipfw_tick, NULL, dyn_keepalive_period*hz);
2723}
2724
2725static void
2726ipfw_init(void)
2727{
2728	struct ip_fw default_rule;
2729
2730	ip_fw_chk_ptr = ipfw_chk;
2731	ip_fw_ctl_ptr = ipfw_ctl;
2732	layer3_chain = NULL;
2733
2734	bzero(&default_rule, sizeof default_rule);
2735
2736	default_rule.act_ofs = 0;
2737	default_rule.rulenum = IPFW_DEFAULT_RULE;
2738	default_rule.cmd_len = 1;
2739	default_rule.set = 31;
2740
2741	default_rule.cmd[0].len = 1;
2742	default_rule.cmd[0].opcode =
2743#ifdef IPFIREWALL_DEFAULT_TO_ACCEPT
2744				1 ? O_ACCEPT :
2745#endif
2746				O_DENY;
2747
2748	add_rule(&layer3_chain, &default_rule);
2749
2750	ip_fw_default_rule = layer3_chain;
2751	printf("ipfw2 initialized, divert %s, "
2752		"rule-based forwarding enabled, default to %s, logging ",
2753#ifdef IPDIVERT
2754		"enabled",
2755#else
2756		"disabled",
2757#endif
2758		default_rule.cmd[0].opcode == O_ACCEPT ? "accept" : "deny");
2759
2760#ifdef IPFIREWALL_VERBOSE
2761	fw_verbose = 1;
2762#endif
2763#ifdef IPFIREWALL_VERBOSE_LIMIT
2764	verbose_limit = IPFIREWALL_VERBOSE_LIMIT;
2765#endif
2766	if (fw_verbose == 0)
2767		printf("disabled\n");
2768	else if (verbose_limit == 0)
2769		printf("unlimited\n");
2770	else
2771		printf("limited to %d packets/entry by default\n",
2772		    verbose_limit);
2773	bzero(&ipfw_timeout_h, sizeof(struct callout_handle));
2774	ipfw_timeout_h = timeout(ipfw_tick, NULL, hz);
2775}
2776
2777static int
2778ipfw_modevent(module_t mod, int type, void *unused)
2779{
2780	int s;
2781	int err = 0;
2782
2783	switch (type) {
2784	case MOD_LOAD:
2785		s = splimp();
2786		if (IPFW_LOADED) {
2787			splx(s);
2788			printf("IP firewall already loaded\n");
2789			err = EEXIST;
2790		} else {
2791			ipfw_init();
2792			splx(s);
2793		}
2794		break;
2795
2796	case MOD_UNLOAD:
2797#if !defined(KLD_MODULE)
2798		printf("ipfw statically compiled, cannot unload\n");
2799		err = EBUSY;
2800#else
2801                s = splimp();
2802		untimeout(ipfw_tick, NULL, ipfw_timeout_h);
2803		ip_fw_chk_ptr = NULL;
2804		ip_fw_ctl_ptr = NULL;
2805		free_chain(&layer3_chain, 1 /* kill default rule */);
2806		splx(s);
2807		printf("IP firewall unloaded\n");
2808#endif
2809		break;
2810	default:
2811		break;
2812	}
2813	return err;
2814}
2815
2816static moduledata_t ipfwmod = {
2817	"ipfw",
2818	ipfw_modevent,
2819	0
2820};
2821DECLARE_MODULE(ipfw, ipfwmod, SI_SUB_PSEUDO, SI_ORDER_ANY);
2822MODULE_VERSION(ipfw, 1);
2823#endif /* IPFW2 */
2824