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