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