ip_fw2.c revision 134022
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 134022 2004-08-19 17:38:47Z andre $
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#include "opt_ipsec.h"
41#ifndef INET
42#error IPFIREWALL requires INET.
43#endif /* INET */
44#endif
45
46#define IPFW2	1
47#if IPFW2
48#include <sys/param.h>
49#include <sys/systm.h>
50#include <sys/malloc.h>
51#include <sys/mbuf.h>
52#include <sys/kernel.h>
53#include <sys/jail.h>
54#include <sys/module.h>
55#include <sys/proc.h>
56#include <sys/socket.h>
57#include <sys/socketvar.h>
58#include <sys/sysctl.h>
59#include <sys/syslog.h>
60#include <sys/ucred.h>
61#include <net/if.h>
62#include <net/radix.h>
63#include <net/route.h>
64#include <netinet/in.h>
65#include <netinet/in_systm.h>
66#include <netinet/in_var.h>
67#include <netinet/in_pcb.h>
68#include <netinet/ip.h>
69#include <netinet/ip_var.h>
70#include <netinet/ip_icmp.h>
71#include <netinet/ip_fw.h>
72#include <netinet/ip_divert.h>
73#include <netinet/ip_dummynet.h>
74#include <netinet/tcp.h>
75#include <netinet/tcp_timer.h>
76#include <netinet/tcp_var.h>
77#include <netinet/tcpip.h>
78#include <netinet/udp.h>
79#include <netinet/udp_var.h>
80
81#ifdef IPSEC
82#include <netinet6/ipsec.h>
83#endif
84
85#include <netinet/if_ether.h> /* XXX for ETHERTYPE_IP */
86
87#include <machine/in_cksum.h>	/* XXX for in_cksum */
88
89/*
90 * set_disable contains one bit per set value (0..31).
91 * If the bit is set, all rules with the corresponding set
92 * are disabled. Set RESVD_SET(31) is reserved for the default rule
93 * and rules that are not deleted by the flush command,
94 * and CANNOT be disabled.
95 * Rules in set RESVD_SET can only be deleted explicitly.
96 */
97static u_int32_t set_disable;
98
99static int fw_verbose;
100static int verbose_limit;
101
102static struct callout ipfw_timeout;
103#define	IPFW_DEFAULT_RULE	65535
104
105/*
106 * Data structure to cache our ucred related
107 * information. This structure only gets used if
108 * the user specified UID/GID based constraints in
109 * a firewall rule.
110 */
111struct ip_fw_ugid {
112	gid_t		fw_groups[NGROUPS];
113	int		fw_ngroups;
114	uid_t		fw_uid;
115	int		fw_prid;
116};
117
118struct ip_fw_chain {
119	struct ip_fw	*rules;		/* list of rules */
120	struct ip_fw	*reap;		/* list of rules to reap */
121	struct mtx	mtx;		/* lock guarding rule list */
122};
123#define	IPFW_LOCK_INIT(_chain) \
124	mtx_init(&(_chain)->mtx, "IPFW static rules", NULL, \
125		MTX_DEF | MTX_RECURSE)
126#define	IPFW_LOCK_DESTROY(_chain)	mtx_destroy(&(_chain)->mtx)
127#define	IPFW_LOCK(_chain)	mtx_lock(&(_chain)->mtx)
128#define	IPFW_UNLOCK(_chain)	mtx_unlock(&(_chain)->mtx)
129#define	IPFW_LOCK_ASSERT(_chain)	do {				\
130	mtx_assert(&(_chain)->mtx, MA_OWNED);				\
131	NET_ASSERT_GIANT();						\
132} while (0)
133
134/*
135 * list of rules for layer 3
136 */
137static struct ip_fw_chain layer3_chain;
138
139MALLOC_DEFINE(M_IPFW, "IpFw/IpAcct", "IpFw/IpAcct chain's");
140MALLOC_DEFINE(M_IPFW_TBL, "ipfw_tbl", "IpFw tables");
141
142struct table_entry {
143	struct radix_node	rn[2];
144	struct sockaddr_in	addr, mask;
145	u_int32_t		value;
146};
147
148#define	IPFW_TABLES_MAX		128
149static struct {
150	struct radix_node_head	*rnh;
151	int			modified;
152} ipfw_tables[IPFW_TABLES_MAX];
153
154static int fw_debug = 1;
155static int autoinc_step = 100; /* bounded to 1..1000 in add_rule() */
156
157#ifdef SYSCTL_NODE
158SYSCTL_NODE(_net_inet_ip, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall");
159SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, enable,
160    CTLFLAG_RW | CTLFLAG_SECURE3,
161    &fw_enable, 0, "Enable ipfw");
162SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, autoinc_step, CTLFLAG_RW,
163    &autoinc_step, 0, "Rule number autincrement step");
164SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, one_pass,
165    CTLFLAG_RW | CTLFLAG_SECURE3,
166    &fw_one_pass, 0,
167    "Only do a single pass through ipfw when using dummynet(4)");
168SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, debug, CTLFLAG_RW,
169    &fw_debug, 0, "Enable printing of debug ip_fw statements");
170SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose,
171    CTLFLAG_RW | CTLFLAG_SECURE3,
172    &fw_verbose, 0, "Log matches to ipfw rules");
173SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose_limit, CTLFLAG_RW,
174    &verbose_limit, 0, "Set upper limit of matches of ipfw rules logged");
175
176/*
177 * Description of dynamic rules.
178 *
179 * Dynamic rules are stored in lists accessed through a hash table
180 * (ipfw_dyn_v) whose size is curr_dyn_buckets. This value can
181 * be modified through the sysctl variable dyn_buckets which is
182 * updated when the table becomes empty.
183 *
184 * XXX currently there is only one list, ipfw_dyn.
185 *
186 * When a packet is received, its address fields are first masked
187 * with the mask defined for the rule, then hashed, then matched
188 * against the entries in the corresponding list.
189 * Dynamic rules can be used for different purposes:
190 *  + stateful rules;
191 *  + enforcing limits on the number of sessions;
192 *  + in-kernel NAT (not implemented yet)
193 *
194 * The lifetime of dynamic rules is regulated by dyn_*_lifetime,
195 * measured in seconds and depending on the flags.
196 *
197 * The total number of dynamic rules is stored in dyn_count.
198 * The max number of dynamic rules is dyn_max. When we reach
199 * the maximum number of rules we do not create anymore. This is
200 * done to avoid consuming too much memory, but also too much
201 * time when searching on each packet (ideally, we should try instead
202 * to put a limit on the length of the list on each bucket...).
203 *
204 * Each dynamic rule holds a pointer to the parent ipfw rule so
205 * we know what action to perform. Dynamic rules are removed when
206 * the parent rule is deleted. XXX we should make them survive.
207 *
208 * There are some limitations with dynamic rules -- we do not
209 * obey the 'randomized match', and we do not do multiple
210 * passes through the firewall. XXX check the latter!!!
211 */
212static ipfw_dyn_rule **ipfw_dyn_v = NULL;
213static u_int32_t dyn_buckets = 256; /* must be power of 2 */
214static u_int32_t curr_dyn_buckets = 256; /* must be power of 2 */
215
216static struct mtx ipfw_dyn_mtx;		/* mutex guarding dynamic rules */
217#define	IPFW_DYN_LOCK_INIT() \
218	mtx_init(&ipfw_dyn_mtx, "IPFW dynamic rules", NULL, MTX_DEF)
219#define	IPFW_DYN_LOCK_DESTROY()	mtx_destroy(&ipfw_dyn_mtx)
220#define	IPFW_DYN_LOCK()		mtx_lock(&ipfw_dyn_mtx)
221#define	IPFW_DYN_UNLOCK()	mtx_unlock(&ipfw_dyn_mtx)
222#define	IPFW_DYN_LOCK_ASSERT()	mtx_assert(&ipfw_dyn_mtx, MA_OWNED)
223
224/*
225 * Timeouts for various events in handing dynamic rules.
226 */
227static u_int32_t dyn_ack_lifetime = 300;
228static u_int32_t dyn_syn_lifetime = 20;
229static u_int32_t dyn_fin_lifetime = 1;
230static u_int32_t dyn_rst_lifetime = 1;
231static u_int32_t dyn_udp_lifetime = 10;
232static u_int32_t dyn_short_lifetime = 5;
233
234/*
235 * Keepalives are sent if dyn_keepalive is set. They are sent every
236 * dyn_keepalive_period seconds, in the last dyn_keepalive_interval
237 * seconds of lifetime of a rule.
238 * dyn_rst_lifetime and dyn_fin_lifetime should be strictly lower
239 * than dyn_keepalive_period.
240 */
241
242static u_int32_t dyn_keepalive_interval = 20;
243static u_int32_t dyn_keepalive_period = 5;
244static u_int32_t dyn_keepalive = 1;	/* do send keepalives */
245
246static u_int32_t static_count;	/* # of static rules */
247static u_int32_t static_len;	/* size in bytes of static rules */
248static u_int32_t dyn_count;		/* # of dynamic rules */
249static u_int32_t dyn_max = 4096;	/* max # of dynamic rules */
250
251SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_buckets, CTLFLAG_RW,
252    &dyn_buckets, 0, "Number of dyn. buckets");
253SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, curr_dyn_buckets, CTLFLAG_RD,
254    &curr_dyn_buckets, 0, "Current Number of dyn. buckets");
255SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_count, CTLFLAG_RD,
256    &dyn_count, 0, "Number of dyn. rules");
257SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_max, CTLFLAG_RW,
258    &dyn_max, 0, "Max number of dyn. rules");
259SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, static_count, CTLFLAG_RD,
260    &static_count, 0, "Number of static rules");
261SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_ack_lifetime, CTLFLAG_RW,
262    &dyn_ack_lifetime, 0, "Lifetime of dyn. rules for acks");
263SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_syn_lifetime, CTLFLAG_RW,
264    &dyn_syn_lifetime, 0, "Lifetime of dyn. rules for syn");
265SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_fin_lifetime, CTLFLAG_RW,
266    &dyn_fin_lifetime, 0, "Lifetime of dyn. rules for fin");
267SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_rst_lifetime, CTLFLAG_RW,
268    &dyn_rst_lifetime, 0, "Lifetime of dyn. rules for rst");
269SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_udp_lifetime, CTLFLAG_RW,
270    &dyn_udp_lifetime, 0, "Lifetime of dyn. rules for UDP");
271SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_short_lifetime, CTLFLAG_RW,
272    &dyn_short_lifetime, 0, "Lifetime of dyn. rules for other situations");
273SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_keepalive, CTLFLAG_RW,
274    &dyn_keepalive, 0, "Enable keepalives for dyn. rules");
275
276#endif /* SYSCTL_NODE */
277
278
279/*
280 * This macro maps an ip pointer into a layer3 header pointer of type T
281 */
282#define	L3HDR(T, ip) ((T *)((u_int32_t *)(ip) + (ip)->ip_hl))
283
284static __inline int
285icmptype_match(struct ip *ip, ipfw_insn_u32 *cmd)
286{
287	int type = L3HDR(struct icmp,ip)->icmp_type;
288
289	return (type <= ICMP_MAXTYPE && (cmd->d[0] & (1<<type)) );
290}
291
292#define TT	( (1 << ICMP_ECHO) | (1 << ICMP_ROUTERSOLICIT) | \
293    (1 << ICMP_TSTAMP) | (1 << ICMP_IREQ) | (1 << ICMP_MASKREQ) )
294
295static int
296is_icmp_query(struct ip *ip)
297{
298	int type = L3HDR(struct icmp, ip)->icmp_type;
299	return (type <= ICMP_MAXTYPE && (TT & (1<<type)) );
300}
301#undef TT
302
303/*
304 * The following checks use two arrays of 8 or 16 bits to store the
305 * bits that we want set or clear, respectively. They are in the
306 * low and high half of cmd->arg1 or cmd->d[0].
307 *
308 * We scan options and store the bits we find set. We succeed if
309 *
310 *	(want_set & ~bits) == 0 && (want_clear & ~bits) == want_clear
311 *
312 * The code is sometimes optimized not to store additional variables.
313 */
314
315static int
316flags_match(ipfw_insn *cmd, u_int8_t bits)
317{
318	u_char want_clear;
319	bits = ~bits;
320
321	if ( ((cmd->arg1 & 0xff) & bits) != 0)
322		return 0; /* some bits we want set were clear */
323	want_clear = (cmd->arg1 >> 8) & 0xff;
324	if ( (want_clear & bits) != want_clear)
325		return 0; /* some bits we want clear were set */
326	return 1;
327}
328
329static int
330ipopts_match(struct ip *ip, ipfw_insn *cmd)
331{
332	int optlen, bits = 0;
333	u_char *cp = (u_char *)(ip + 1);
334	int x = (ip->ip_hl << 2) - sizeof (struct ip);
335
336	for (; x > 0; x -= optlen, cp += optlen) {
337		int opt = cp[IPOPT_OPTVAL];
338
339		if (opt == IPOPT_EOL)
340			break;
341		if (opt == IPOPT_NOP)
342			optlen = 1;
343		else {
344			optlen = cp[IPOPT_OLEN];
345			if (optlen <= 0 || optlen > x)
346				return 0; /* invalid or truncated */
347		}
348		switch (opt) {
349
350		default:
351			break;
352
353		case IPOPT_LSRR:
354			bits |= IP_FW_IPOPT_LSRR;
355			break;
356
357		case IPOPT_SSRR:
358			bits |= IP_FW_IPOPT_SSRR;
359			break;
360
361		case IPOPT_RR:
362			bits |= IP_FW_IPOPT_RR;
363			break;
364
365		case IPOPT_TS:
366			bits |= IP_FW_IPOPT_TS;
367			break;
368		}
369	}
370	return (flags_match(cmd, bits));
371}
372
373static int
374tcpopts_match(struct ip *ip, ipfw_insn *cmd)
375{
376	int optlen, bits = 0;
377	struct tcphdr *tcp = L3HDR(struct tcphdr,ip);
378	u_char *cp = (u_char *)(tcp + 1);
379	int x = (tcp->th_off << 2) - sizeof(struct tcphdr);
380
381	for (; x > 0; x -= optlen, cp += optlen) {
382		int opt = cp[0];
383		if (opt == TCPOPT_EOL)
384			break;
385		if (opt == TCPOPT_NOP)
386			optlen = 1;
387		else {
388			optlen = cp[1];
389			if (optlen <= 0)
390				break;
391		}
392
393		switch (opt) {
394
395		default:
396			break;
397
398		case TCPOPT_MAXSEG:
399			bits |= IP_FW_TCPOPT_MSS;
400			break;
401
402		case TCPOPT_WINDOW:
403			bits |= IP_FW_TCPOPT_WINDOW;
404			break;
405
406		case TCPOPT_SACK_PERMITTED:
407		case TCPOPT_SACK:
408			bits |= IP_FW_TCPOPT_SACK;
409			break;
410
411		case TCPOPT_TIMESTAMP:
412			bits |= IP_FW_TCPOPT_TS;
413			break;
414
415		case TCPOPT_CC:
416		case TCPOPT_CCNEW:
417		case TCPOPT_CCECHO:
418			bits |= IP_FW_TCPOPT_CC;
419			break;
420		}
421	}
422	return (flags_match(cmd, bits));
423}
424
425static int
426iface_match(struct ifnet *ifp, ipfw_insn_if *cmd)
427{
428	if (ifp == NULL)	/* no iface with this packet, match fails */
429		return 0;
430	/* Check by name or by IP address */
431	if (cmd->name[0] != '\0') { /* match by name */
432		/* Check name */
433		if (cmd->p.glob) {
434			if (fnmatch(cmd->name, ifp->if_xname, 0) == 0)
435				return(1);
436		} else {
437			if (strncmp(ifp->if_xname, cmd->name, IFNAMSIZ) == 0)
438				return(1);
439		}
440	} else {
441		struct ifaddr *ia;
442
443		/* XXX lock? */
444		TAILQ_FOREACH(ia, &ifp->if_addrhead, ifa_link) {
445			if (ia->ifa_addr == NULL)
446				continue;
447			if (ia->ifa_addr->sa_family != AF_INET)
448				continue;
449			if (cmd->p.ip.s_addr == ((struct sockaddr_in *)
450			    (ia->ifa_addr))->sin_addr.s_addr)
451				return(1);	/* match */
452		}
453	}
454	return(0);	/* no match, fail ... */
455}
456
457/*
458 * The verify_path function checks if a route to the src exists and
459 * if it is reachable via ifp (when provided).
460 *
461 * The 'verrevpath' option checks that the interface that an IP packet
462 * arrives on is the same interface that traffic destined for the
463 * packet's source address would be routed out of.  The 'versrcreach'
464 * option just checks that the source address is reachable via any route
465 * (except default) in the routing table.  These two are a measure to block
466 * forged packets.  This is also commonly known as "anti-spoofing" or Unicast
467 * Reverse Path Forwarding (Unicast RFP) in Cisco-ese. The name of the knobs
468 * is purposely reminiscent of the Cisco IOS command,
469 *
470 *   ip verify unicast reverse-path
471 *   ip verify unicast source reachable-via any
472 *
473 * which implements the same functionality. But note that syntax is
474 * misleading. The check may be performed on all IP packets whether unicast,
475 * multicast, or broadcast.
476 */
477static int
478verify_path(struct in_addr src, struct ifnet *ifp)
479{
480	struct route ro;
481	struct sockaddr_in *dst;
482
483	bzero(&ro, sizeof(ro));
484
485	dst = (struct sockaddr_in *)&(ro.ro_dst);
486	dst->sin_family = AF_INET;
487	dst->sin_len = sizeof(*dst);
488	dst->sin_addr = src;
489	rtalloc_ign(&ro, RTF_CLONING);
490
491	if (ro.ro_rt == NULL)
492		return 0;
493
494	/* if ifp is provided, check for equality with rtentry */
495	if (ifp != NULL && ro.ro_rt->rt_ifp != ifp) {
496		RTFREE(ro.ro_rt);
497		return 0;
498	}
499
500	/* if no ifp provided, check if rtentry is not default route */
501	if (ifp == NULL &&
502	     satosin(rt_key(ro.ro_rt))->sin_addr.s_addr == INADDR_ANY) {
503		RTFREE(ro.ro_rt);
504		return 0;
505	}
506
507	/* or if this is a blackhole/reject route */
508	if (ifp == NULL && ro.ro_rt->rt_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
509		RTFREE(ro.ro_rt);
510		return 0;
511	}
512
513	/* found valid route */
514	RTFREE(ro.ro_rt);
515	return 1;
516}
517
518
519static u_int64_t norule_counter;	/* counter for ipfw_log(NULL...) */
520
521#define SNPARGS(buf, len) buf + len, sizeof(buf) > len ? sizeof(buf) - len : 0
522#define SNP(buf) buf, sizeof(buf)
523
524/*
525 * We enter here when we have a rule with O_LOG.
526 * XXX this function alone takes about 2Kbytes of code!
527 */
528static void
529ipfw_log(struct ip_fw *f, u_int hlen, struct ether_header *eh,
530	struct mbuf *m, struct ifnet *oif)
531{
532	char *action;
533	int limit_reached = 0;
534	char action2[40], proto[48], fragment[28];
535
536	fragment[0] = '\0';
537	proto[0] = '\0';
538
539	if (f == NULL) {	/* bogus pkt */
540		if (verbose_limit != 0 && norule_counter >= verbose_limit)
541			return;
542		norule_counter++;
543		if (norule_counter == verbose_limit)
544			limit_reached = verbose_limit;
545		action = "Refuse";
546	} else {	/* O_LOG is the first action, find the real one */
547		ipfw_insn *cmd = ACTION_PTR(f);
548		ipfw_insn_log *l = (ipfw_insn_log *)cmd;
549
550		if (l->max_log != 0 && l->log_left == 0)
551			return;
552		l->log_left--;
553		if (l->log_left == 0)
554			limit_reached = l->max_log;
555		cmd += F_LEN(cmd);	/* point to first action */
556		if (cmd->opcode == O_PROB)
557			cmd += F_LEN(cmd);
558
559		action = action2;
560		switch (cmd->opcode) {
561		case O_DENY:
562			action = "Deny";
563			break;
564
565		case O_REJECT:
566			if (cmd->arg1==ICMP_REJECT_RST)
567				action = "Reset";
568			else if (cmd->arg1==ICMP_UNREACH_HOST)
569				action = "Reject";
570			else
571				snprintf(SNPARGS(action2, 0), "Unreach %d",
572					cmd->arg1);
573			break;
574
575		case O_ACCEPT:
576			action = "Accept";
577			break;
578		case O_COUNT:
579			action = "Count";
580			break;
581		case O_DIVERT:
582			snprintf(SNPARGS(action2, 0), "Divert %d",
583				cmd->arg1);
584			break;
585		case O_TEE:
586			snprintf(SNPARGS(action2, 0), "Tee %d",
587				cmd->arg1);
588			break;
589		case O_SKIPTO:
590			snprintf(SNPARGS(action2, 0), "SkipTo %d",
591				cmd->arg1);
592			break;
593		case O_PIPE:
594			snprintf(SNPARGS(action2, 0), "Pipe %d",
595				cmd->arg1);
596			break;
597		case O_QUEUE:
598			snprintf(SNPARGS(action2, 0), "Queue %d",
599				cmd->arg1);
600			break;
601		case O_FORWARD_IP: {
602			ipfw_insn_sa *sa = (ipfw_insn_sa *)cmd;
603			int len;
604
605			len = snprintf(SNPARGS(action2, 0), "Forward to %s",
606				inet_ntoa(sa->sa.sin_addr));
607			if (sa->sa.sin_port)
608				snprintf(SNPARGS(action2, len), ":%d",
609				    sa->sa.sin_port);
610			}
611			break;
612		default:
613			action = "UNKNOWN";
614			break;
615		}
616	}
617
618	if (hlen == 0) {	/* non-ip */
619		snprintf(SNPARGS(proto, 0), "MAC");
620	} else {
621		struct ip *ip = mtod(m, struct ip *);
622		/* these three are all aliases to the same thing */
623		struct icmp *const icmp = L3HDR(struct icmp, ip);
624		struct tcphdr *const tcp = (struct tcphdr *)icmp;
625		struct udphdr *const udp = (struct udphdr *)icmp;
626
627		int ip_off, offset, ip_len;
628
629		int len;
630
631		if (eh != NULL) { /* layer 2 packets are as on the wire */
632			ip_off = ntohs(ip->ip_off);
633			ip_len = ntohs(ip->ip_len);
634		} else {
635			ip_off = ip->ip_off;
636			ip_len = ip->ip_len;
637		}
638		offset = ip_off & IP_OFFMASK;
639		switch (ip->ip_p) {
640		case IPPROTO_TCP:
641			len = snprintf(SNPARGS(proto, 0), "TCP %s",
642			    inet_ntoa(ip->ip_src));
643			if (offset == 0)
644				snprintf(SNPARGS(proto, len), ":%d %s:%d",
645				    ntohs(tcp->th_sport),
646				    inet_ntoa(ip->ip_dst),
647				    ntohs(tcp->th_dport));
648			else
649				snprintf(SNPARGS(proto, len), " %s",
650				    inet_ntoa(ip->ip_dst));
651			break;
652
653		case IPPROTO_UDP:
654			len = snprintf(SNPARGS(proto, 0), "UDP %s",
655				inet_ntoa(ip->ip_src));
656			if (offset == 0)
657				snprintf(SNPARGS(proto, len), ":%d %s:%d",
658				    ntohs(udp->uh_sport),
659				    inet_ntoa(ip->ip_dst),
660				    ntohs(udp->uh_dport));
661			else
662				snprintf(SNPARGS(proto, len), " %s",
663				    inet_ntoa(ip->ip_dst));
664			break;
665
666		case IPPROTO_ICMP:
667			if (offset == 0)
668				len = snprintf(SNPARGS(proto, 0),
669				    "ICMP:%u.%u ",
670				    icmp->icmp_type, icmp->icmp_code);
671			else
672				len = snprintf(SNPARGS(proto, 0), "ICMP ");
673			len += snprintf(SNPARGS(proto, len), "%s",
674			    inet_ntoa(ip->ip_src));
675			snprintf(SNPARGS(proto, len), " %s",
676			    inet_ntoa(ip->ip_dst));
677			break;
678
679		default:
680			len = snprintf(SNPARGS(proto, 0), "P:%d %s", ip->ip_p,
681			    inet_ntoa(ip->ip_src));
682			snprintf(SNPARGS(proto, len), " %s",
683			    inet_ntoa(ip->ip_dst));
684			break;
685		}
686
687		if (ip_off & (IP_MF | IP_OFFMASK))
688			snprintf(SNPARGS(fragment, 0), " (frag %d:%d@%d%s)",
689			     ntohs(ip->ip_id), ip_len - (ip->ip_hl << 2),
690			     offset << 3,
691			     (ip_off & IP_MF) ? "+" : "");
692	}
693	if (oif || m->m_pkthdr.rcvif)
694		log(LOG_SECURITY | LOG_INFO,
695		    "ipfw: %d %s %s %s via %s%s\n",
696		    f ? f->rulenum : -1,
697		    action, proto, oif ? "out" : "in",
698		    oif ? oif->if_xname : m->m_pkthdr.rcvif->if_xname,
699		    fragment);
700	else
701		log(LOG_SECURITY | LOG_INFO,
702		    "ipfw: %d %s %s [no if info]%s\n",
703		    f ? f->rulenum : -1,
704		    action, proto, fragment);
705	if (limit_reached)
706		log(LOG_SECURITY | LOG_NOTICE,
707		    "ipfw: limit %d reached on entry %d\n",
708		    limit_reached, f ? f->rulenum : -1);
709}
710
711/*
712 * IMPORTANT: the hash function for dynamic rules must be commutative
713 * in source and destination (ip,port), because rules are bidirectional
714 * and we want to find both in the same bucket.
715 */
716static __inline int
717hash_packet(struct ipfw_flow_id *id)
718{
719	u_int32_t i;
720
721	i = (id->dst_ip) ^ (id->src_ip) ^ (id->dst_port) ^ (id->src_port);
722	i &= (curr_dyn_buckets - 1);
723	return i;
724}
725
726/**
727 * unlink a dynamic rule from a chain. prev is a pointer to
728 * the previous one, q is a pointer to the rule to delete,
729 * head is a pointer to the head of the queue.
730 * Modifies q and potentially also head.
731 */
732#define UNLINK_DYN_RULE(prev, head, q) {				\
733	ipfw_dyn_rule *old_q = q;					\
734									\
735	/* remove a refcount to the parent */				\
736	if (q->dyn_type == O_LIMIT)					\
737		q->parent->count--;					\
738	DEB(printf("ipfw: unlink entry 0x%08x %d -> 0x%08x %d, %d left\n",\
739		(q->id.src_ip), (q->id.src_port),			\
740		(q->id.dst_ip), (q->id.dst_port), dyn_count-1 ); )	\
741	if (prev != NULL)						\
742		prev->next = q = q->next;				\
743	else								\
744		head = q = q->next;					\
745	dyn_count--;							\
746	free(old_q, M_IPFW); }
747
748#define TIME_LEQ(a,b)       ((int)((a)-(b)) <= 0)
749
750/**
751 * Remove dynamic rules pointing to "rule", or all of them if rule == NULL.
752 *
753 * If keep_me == NULL, rules are deleted even if not expired,
754 * otherwise only expired rules are removed.
755 *
756 * The value of the second parameter is also used to point to identify
757 * a rule we absolutely do not want to remove (e.g. because we are
758 * holding a reference to it -- this is the case with O_LIMIT_PARENT
759 * rules). The pointer is only used for comparison, so any non-null
760 * value will do.
761 */
762static void
763remove_dyn_rule(struct ip_fw *rule, ipfw_dyn_rule *keep_me)
764{
765	static u_int32_t last_remove = 0;
766
767#define FORCE (keep_me == NULL)
768
769	ipfw_dyn_rule *prev, *q;
770	int i, pass = 0, max_pass = 0;
771
772	IPFW_DYN_LOCK_ASSERT();
773
774	if (ipfw_dyn_v == NULL || dyn_count == 0)
775		return;
776	/* do not expire more than once per second, it is useless */
777	if (!FORCE && last_remove == time_second)
778		return;
779	last_remove = time_second;
780
781	/*
782	 * because O_LIMIT refer to parent rules, during the first pass only
783	 * remove child and mark any pending LIMIT_PARENT, and remove
784	 * them in a second pass.
785	 */
786next_pass:
787	for (i = 0 ; i < curr_dyn_buckets ; i++) {
788		for (prev=NULL, q = ipfw_dyn_v[i] ; q ; ) {
789			/*
790			 * Logic can become complex here, so we split tests.
791			 */
792			if (q == keep_me)
793				goto next;
794			if (rule != NULL && rule != q->rule)
795				goto next; /* not the one we are looking for */
796			if (q->dyn_type == O_LIMIT_PARENT) {
797				/*
798				 * handle parent in the second pass,
799				 * record we need one.
800				 */
801				max_pass = 1;
802				if (pass == 0)
803					goto next;
804				if (FORCE && q->count != 0 ) {
805					/* XXX should not happen! */
806					printf("ipfw: OUCH! cannot remove rule,"
807					     " count %d\n", q->count);
808				}
809			} else {
810				if (!FORCE &&
811				    !TIME_LEQ( q->expire, time_second ))
812					goto next;
813			}
814             if (q->dyn_type != O_LIMIT_PARENT || !q->count) {
815                     UNLINK_DYN_RULE(prev, ipfw_dyn_v[i], q);
816                     continue;
817             }
818next:
819			prev=q;
820			q=q->next;
821		}
822	}
823	if (pass++ < max_pass)
824		goto next_pass;
825}
826
827
828/**
829 * lookup a dynamic rule.
830 */
831static ipfw_dyn_rule *
832lookup_dyn_rule_locked(struct ipfw_flow_id *pkt, int *match_direction,
833	struct tcphdr *tcp)
834{
835	/*
836	 * stateful ipfw extensions.
837	 * Lookup into dynamic session queue
838	 */
839#define MATCH_REVERSE	0
840#define MATCH_FORWARD	1
841#define MATCH_NONE	2
842#define MATCH_UNKNOWN	3
843	int i, dir = MATCH_NONE;
844	ipfw_dyn_rule *prev, *q=NULL;
845
846	IPFW_DYN_LOCK_ASSERT();
847
848	if (ipfw_dyn_v == NULL)
849		goto done;	/* not found */
850	i = hash_packet( pkt );
851	for (prev=NULL, q = ipfw_dyn_v[i] ; q != NULL ; ) {
852		if (q->dyn_type == O_LIMIT_PARENT && q->count)
853			goto next;
854		if (TIME_LEQ( q->expire, time_second)) { /* expire entry */
855			UNLINK_DYN_RULE(prev, ipfw_dyn_v[i], q);
856			continue;
857		}
858		if (pkt->proto == q->id.proto &&
859		    q->dyn_type != O_LIMIT_PARENT) {
860			if (pkt->src_ip == q->id.src_ip &&
861			    pkt->dst_ip == q->id.dst_ip &&
862			    pkt->src_port == q->id.src_port &&
863			    pkt->dst_port == q->id.dst_port ) {
864				dir = MATCH_FORWARD;
865				break;
866			}
867			if (pkt->src_ip == q->id.dst_ip &&
868			    pkt->dst_ip == q->id.src_ip &&
869			    pkt->src_port == q->id.dst_port &&
870			    pkt->dst_port == q->id.src_port ) {
871				dir = MATCH_REVERSE;
872				break;
873			}
874		}
875next:
876		prev = q;
877		q = q->next;
878	}
879	if (q == NULL)
880		goto done; /* q = NULL, not found */
881
882	if ( prev != NULL) { /* found and not in front */
883		prev->next = q->next;
884		q->next = ipfw_dyn_v[i];
885		ipfw_dyn_v[i] = q;
886	}
887	if (pkt->proto == IPPROTO_TCP) { /* update state according to flags */
888		u_char flags = pkt->flags & (TH_FIN|TH_SYN|TH_RST);
889
890#define BOTH_SYN	(TH_SYN | (TH_SYN << 8))
891#define BOTH_FIN	(TH_FIN | (TH_FIN << 8))
892		q->state |= (dir == MATCH_FORWARD ) ? flags : (flags << 8);
893		switch (q->state) {
894		case TH_SYN:				/* opening */
895			q->expire = time_second + dyn_syn_lifetime;
896			break;
897
898		case BOTH_SYN:			/* move to established */
899		case BOTH_SYN | TH_FIN :	/* one side tries to close */
900		case BOTH_SYN | (TH_FIN << 8) :
901 			if (tcp) {
902#define _SEQ_GE(a,b) ((int)(a) - (int)(b) >= 0)
903			    u_int32_t ack = ntohl(tcp->th_ack);
904			    if (dir == MATCH_FORWARD) {
905				if (q->ack_fwd == 0 || _SEQ_GE(ack, q->ack_fwd))
906				    q->ack_fwd = ack;
907				else { /* ignore out-of-sequence */
908				    break;
909				}
910			    } else {
911				if (q->ack_rev == 0 || _SEQ_GE(ack, q->ack_rev))
912				    q->ack_rev = ack;
913				else { /* ignore out-of-sequence */
914				    break;
915				}
916			    }
917			}
918			q->expire = time_second + dyn_ack_lifetime;
919			break;
920
921		case BOTH_SYN | BOTH_FIN:	/* both sides closed */
922			if (dyn_fin_lifetime >= dyn_keepalive_period)
923				dyn_fin_lifetime = dyn_keepalive_period - 1;
924			q->expire = time_second + dyn_fin_lifetime;
925			break;
926
927		default:
928#if 0
929			/*
930			 * reset or some invalid combination, but can also
931			 * occur if we use keep-state the wrong way.
932			 */
933			if ( (q->state & ((TH_RST << 8)|TH_RST)) == 0)
934				printf("invalid state: 0x%x\n", q->state);
935#endif
936			if (dyn_rst_lifetime >= dyn_keepalive_period)
937				dyn_rst_lifetime = dyn_keepalive_period - 1;
938			q->expire = time_second + dyn_rst_lifetime;
939			break;
940		}
941	} else if (pkt->proto == IPPROTO_UDP) {
942		q->expire = time_second + dyn_udp_lifetime;
943	} else {
944		/* other protocols */
945		q->expire = time_second + dyn_short_lifetime;
946	}
947done:
948	if (match_direction)
949		*match_direction = dir;
950	return q;
951}
952
953static ipfw_dyn_rule *
954lookup_dyn_rule(struct ipfw_flow_id *pkt, int *match_direction,
955	struct tcphdr *tcp)
956{
957	ipfw_dyn_rule *q;
958
959	IPFW_DYN_LOCK();
960	q = lookup_dyn_rule_locked(pkt, match_direction, tcp);
961	if (q == NULL)
962		IPFW_DYN_UNLOCK();
963	/* NB: return table locked when q is not NULL */
964	return q;
965}
966
967static void
968realloc_dynamic_table(void)
969{
970	IPFW_DYN_LOCK_ASSERT();
971
972	/*
973	 * Try reallocation, make sure we have a power of 2 and do
974	 * not allow more than 64k entries. In case of overflow,
975	 * default to 1024.
976	 */
977
978	if (dyn_buckets > 65536)
979		dyn_buckets = 1024;
980	if ((dyn_buckets & (dyn_buckets-1)) != 0) { /* not a power of 2 */
981		dyn_buckets = curr_dyn_buckets; /* reset */
982		return;
983	}
984	curr_dyn_buckets = dyn_buckets;
985	if (ipfw_dyn_v != NULL)
986		free(ipfw_dyn_v, M_IPFW);
987	for (;;) {
988		ipfw_dyn_v = malloc(curr_dyn_buckets * sizeof(ipfw_dyn_rule *),
989		       M_IPFW, M_NOWAIT | M_ZERO);
990		if (ipfw_dyn_v != NULL || curr_dyn_buckets <= 2)
991			break;
992		curr_dyn_buckets /= 2;
993	}
994}
995
996/**
997 * Install state of type 'type' for a dynamic session.
998 * The hash table contains two type of rules:
999 * - regular rules (O_KEEP_STATE)
1000 * - rules for sessions with limited number of sess per user
1001 *   (O_LIMIT). When they are created, the parent is
1002 *   increased by 1, and decreased on delete. In this case,
1003 *   the third parameter is the parent rule and not the chain.
1004 * - "parent" rules for the above (O_LIMIT_PARENT).
1005 */
1006static ipfw_dyn_rule *
1007add_dyn_rule(struct ipfw_flow_id *id, u_int8_t dyn_type, struct ip_fw *rule)
1008{
1009	ipfw_dyn_rule *r;
1010	int i;
1011
1012	IPFW_DYN_LOCK_ASSERT();
1013
1014	if (ipfw_dyn_v == NULL ||
1015	    (dyn_count == 0 && dyn_buckets != curr_dyn_buckets)) {
1016		realloc_dynamic_table();
1017		if (ipfw_dyn_v == NULL)
1018			return NULL; /* failed ! */
1019	}
1020	i = hash_packet(id);
1021
1022	r = malloc(sizeof *r, M_IPFW, M_NOWAIT | M_ZERO);
1023	if (r == NULL) {
1024		printf ("ipfw: sorry cannot allocate state\n");
1025		return NULL;
1026	}
1027
1028	/* increase refcount on parent, and set pointer */
1029	if (dyn_type == O_LIMIT) {
1030		ipfw_dyn_rule *parent = (ipfw_dyn_rule *)rule;
1031		if ( parent->dyn_type != O_LIMIT_PARENT)
1032			panic("invalid parent");
1033		parent->count++;
1034		r->parent = parent;
1035		rule = parent->rule;
1036	}
1037
1038	r->id = *id;
1039	r->expire = time_second + dyn_syn_lifetime;
1040	r->rule = rule;
1041	r->dyn_type = dyn_type;
1042	r->pcnt = r->bcnt = 0;
1043	r->count = 0;
1044
1045	r->bucket = i;
1046	r->next = ipfw_dyn_v[i];
1047	ipfw_dyn_v[i] = r;
1048	dyn_count++;
1049	DEB(printf("ipfw: add dyn entry ty %d 0x%08x %d -> 0x%08x %d, total %d\n",
1050	   dyn_type,
1051	   (r->id.src_ip), (r->id.src_port),
1052	   (r->id.dst_ip), (r->id.dst_port),
1053	   dyn_count ); )
1054	return r;
1055}
1056
1057/**
1058 * lookup dynamic parent rule using pkt and rule as search keys.
1059 * If the lookup fails, then install one.
1060 */
1061static ipfw_dyn_rule *
1062lookup_dyn_parent(struct ipfw_flow_id *pkt, struct ip_fw *rule)
1063{
1064	ipfw_dyn_rule *q;
1065	int i;
1066
1067	IPFW_DYN_LOCK_ASSERT();
1068
1069	if (ipfw_dyn_v) {
1070		i = hash_packet( pkt );
1071		for (q = ipfw_dyn_v[i] ; q != NULL ; q=q->next)
1072			if (q->dyn_type == O_LIMIT_PARENT &&
1073			    rule== q->rule &&
1074			    pkt->proto == q->id.proto &&
1075			    pkt->src_ip == q->id.src_ip &&
1076			    pkt->dst_ip == q->id.dst_ip &&
1077			    pkt->src_port == q->id.src_port &&
1078			    pkt->dst_port == q->id.dst_port) {
1079				q->expire = time_second + dyn_short_lifetime;
1080				DEB(printf("ipfw: lookup_dyn_parent found 0x%p\n",q);)
1081				return q;
1082			}
1083	}
1084	return add_dyn_rule(pkt, O_LIMIT_PARENT, rule);
1085}
1086
1087/**
1088 * Install dynamic state for rule type cmd->o.opcode
1089 *
1090 * Returns 1 (failure) if state is not installed because of errors or because
1091 * session limitations are enforced.
1092 */
1093static int
1094install_state(struct ip_fw *rule, ipfw_insn_limit *cmd,
1095	struct ip_fw_args *args)
1096{
1097	static int last_log;
1098
1099	ipfw_dyn_rule *q;
1100
1101	DEB(printf("ipfw: install state type %d 0x%08x %u -> 0x%08x %u\n",
1102	    cmd->o.opcode,
1103	    (args->f_id.src_ip), (args->f_id.src_port),
1104	    (args->f_id.dst_ip), (args->f_id.dst_port) );)
1105
1106	IPFW_DYN_LOCK();
1107
1108	q = lookup_dyn_rule_locked(&args->f_id, NULL, NULL);
1109
1110	if (q != NULL) { /* should never occur */
1111		if (last_log != time_second) {
1112			last_log = time_second;
1113			printf("ipfw: install_state: entry already present, done\n");
1114		}
1115		IPFW_DYN_UNLOCK();
1116		return 0;
1117	}
1118
1119	if (dyn_count >= dyn_max)
1120		/*
1121		 * Run out of slots, try to remove any expired rule.
1122		 */
1123		remove_dyn_rule(NULL, (ipfw_dyn_rule *)1);
1124
1125	if (dyn_count >= dyn_max) {
1126		if (last_log != time_second) {
1127			last_log = time_second;
1128			printf("ipfw: install_state: Too many dynamic rules\n");
1129		}
1130		IPFW_DYN_UNLOCK();
1131		return 1; /* cannot install, notify caller */
1132	}
1133
1134	switch (cmd->o.opcode) {
1135	case O_KEEP_STATE: /* bidir rule */
1136		add_dyn_rule(&args->f_id, O_KEEP_STATE, rule);
1137		break;
1138
1139	case O_LIMIT: /* limit number of sessions */
1140	    {
1141		u_int16_t limit_mask = cmd->limit_mask;
1142		struct ipfw_flow_id id;
1143		ipfw_dyn_rule *parent;
1144
1145		DEB(printf("ipfw: installing dyn-limit rule %d\n",
1146		    cmd->conn_limit);)
1147
1148		id.dst_ip = id.src_ip = 0;
1149		id.dst_port = id.src_port = 0;
1150		id.proto = args->f_id.proto;
1151
1152		if (limit_mask & DYN_SRC_ADDR)
1153			id.src_ip = args->f_id.src_ip;
1154		if (limit_mask & DYN_DST_ADDR)
1155			id.dst_ip = args->f_id.dst_ip;
1156		if (limit_mask & DYN_SRC_PORT)
1157			id.src_port = args->f_id.src_port;
1158		if (limit_mask & DYN_DST_PORT)
1159			id.dst_port = args->f_id.dst_port;
1160		parent = lookup_dyn_parent(&id, rule);
1161		if (parent == NULL) {
1162			printf("ipfw: add parent failed\n");
1163			return 1;
1164		}
1165		if (parent->count >= cmd->conn_limit) {
1166			/*
1167			 * See if we can remove some expired rule.
1168			 */
1169			remove_dyn_rule(rule, parent);
1170			if (parent->count >= cmd->conn_limit) {
1171				if (fw_verbose && last_log != time_second) {
1172					last_log = time_second;
1173					log(LOG_SECURITY | LOG_DEBUG,
1174					    "drop session, too many entries\n");
1175				}
1176				IPFW_DYN_UNLOCK();
1177				return 1;
1178			}
1179		}
1180		add_dyn_rule(&args->f_id, O_LIMIT, (struct ip_fw *)parent);
1181	    }
1182		break;
1183	default:
1184		printf("ipfw: unknown dynamic rule type %u\n", cmd->o.opcode);
1185		IPFW_DYN_UNLOCK();
1186		return 1;
1187	}
1188	lookup_dyn_rule_locked(&args->f_id, NULL, NULL); /* XXX just set lifetime */
1189	IPFW_DYN_UNLOCK();
1190	return 0;
1191}
1192
1193/*
1194 * Transmit a TCP packet, containing either a RST or a keepalive.
1195 * When flags & TH_RST, we are sending a RST packet, because of a
1196 * "reset" action matched the packet.
1197 * Otherwise we are sending a keepalive, and flags & TH_
1198 */
1199static void
1200send_pkt(struct ipfw_flow_id *id, u_int32_t seq, u_int32_t ack, int flags)
1201{
1202	struct mbuf *m;
1203	struct ip *ip;
1204	struct tcphdr *tcp;
1205
1206	MGETHDR(m, M_DONTWAIT, MT_HEADER);
1207	if (m == 0)
1208		return;
1209	m->m_pkthdr.rcvif = (struct ifnet *)0;
1210	m->m_pkthdr.len = m->m_len = sizeof(struct ip) + sizeof(struct tcphdr);
1211	m->m_data += max_linkhdr;
1212
1213	ip = mtod(m, struct ip *);
1214	bzero(ip, m->m_len);
1215	tcp = (struct tcphdr *)(ip + 1); /* no IP options */
1216	ip->ip_p = IPPROTO_TCP;
1217	tcp->th_off = 5;
1218	/*
1219	 * Assume we are sending a RST (or a keepalive in the reverse
1220	 * direction), swap src and destination addresses and ports.
1221	 */
1222	ip->ip_src.s_addr = htonl(id->dst_ip);
1223	ip->ip_dst.s_addr = htonl(id->src_ip);
1224	tcp->th_sport = htons(id->dst_port);
1225	tcp->th_dport = htons(id->src_port);
1226	if (flags & TH_RST) {	/* we are sending a RST */
1227		if (flags & TH_ACK) {
1228			tcp->th_seq = htonl(ack);
1229			tcp->th_ack = htonl(0);
1230			tcp->th_flags = TH_RST;
1231		} else {
1232			if (flags & TH_SYN)
1233				seq++;
1234			tcp->th_seq = htonl(0);
1235			tcp->th_ack = htonl(seq);
1236			tcp->th_flags = TH_RST | TH_ACK;
1237		}
1238	} else {
1239		/*
1240		 * We are sending a keepalive. flags & TH_SYN determines
1241		 * the direction, forward if set, reverse if clear.
1242		 * NOTE: seq and ack are always assumed to be correct
1243		 * as set by the caller. This may be confusing...
1244		 */
1245		if (flags & TH_SYN) {
1246			/*
1247			 * we have to rewrite the correct addresses!
1248			 */
1249			ip->ip_dst.s_addr = htonl(id->dst_ip);
1250			ip->ip_src.s_addr = htonl(id->src_ip);
1251			tcp->th_dport = htons(id->dst_port);
1252			tcp->th_sport = htons(id->src_port);
1253		}
1254		tcp->th_seq = htonl(seq);
1255		tcp->th_ack = htonl(ack);
1256		tcp->th_flags = TH_ACK;
1257	}
1258	/*
1259	 * set ip_len to the payload size so we can compute
1260	 * the tcp checksum on the pseudoheader
1261	 * XXX check this, could save a couple of words ?
1262	 */
1263	ip->ip_len = htons(sizeof(struct tcphdr));
1264	tcp->th_sum = in_cksum(m, m->m_pkthdr.len);
1265	/*
1266	 * now fill fields left out earlier
1267	 */
1268	ip->ip_ttl = ip_defttl;
1269	ip->ip_len = m->m_pkthdr.len;
1270	m->m_flags |= M_SKIP_FIREWALL;
1271	ip_output(m, NULL, NULL, 0, NULL, NULL);
1272}
1273
1274/*
1275 * sends a reject message, consuming the mbuf passed as an argument.
1276 */
1277static void
1278send_reject(struct ip_fw_args *args, int code, int offset, int ip_len)
1279{
1280
1281	if (code != ICMP_REJECT_RST) { /* Send an ICMP unreach */
1282		/* We need the IP header in host order for icmp_error(). */
1283		if (args->eh != NULL) {
1284			struct ip *ip = mtod(args->m, struct ip *);
1285			ip->ip_len = ntohs(ip->ip_len);
1286			ip->ip_off = ntohs(ip->ip_off);
1287		}
1288		icmp_error(args->m, ICMP_UNREACH, code, 0L, 0);
1289	} else if (offset == 0 && args->f_id.proto == IPPROTO_TCP) {
1290		struct tcphdr *const tcp =
1291		    L3HDR(struct tcphdr, mtod(args->m, struct ip *));
1292		if ( (tcp->th_flags & TH_RST) == 0)
1293			send_pkt(&(args->f_id), ntohl(tcp->th_seq),
1294				ntohl(tcp->th_ack),
1295				tcp->th_flags | TH_RST);
1296		m_freem(args->m);
1297	} else
1298		m_freem(args->m);
1299	args->m = NULL;
1300}
1301
1302/**
1303 *
1304 * Given an ip_fw *, lookup_next_rule will return a pointer
1305 * to the next rule, which can be either the jump
1306 * target (for skipto instructions) or the next one in the list (in
1307 * all other cases including a missing jump target).
1308 * The result is also written in the "next_rule" field of the rule.
1309 * Backward jumps are not allowed, so start looking from the next
1310 * rule...
1311 *
1312 * This never returns NULL -- in case we do not have an exact match,
1313 * the next rule is returned. When the ruleset is changed,
1314 * pointers are flushed so we are always correct.
1315 */
1316
1317static struct ip_fw *
1318lookup_next_rule(struct ip_fw *me)
1319{
1320	struct ip_fw *rule = NULL;
1321	ipfw_insn *cmd;
1322
1323	/* look for action, in case it is a skipto */
1324	cmd = ACTION_PTR(me);
1325	if (cmd->opcode == O_LOG)
1326		cmd += F_LEN(cmd);
1327	if ( cmd->opcode == O_SKIPTO )
1328		for (rule = me->next; rule ; rule = rule->next)
1329			if (rule->rulenum >= cmd->arg1)
1330				break;
1331	if (rule == NULL)			/* failure or not a skipto */
1332		rule = me->next;
1333	me->next_rule = rule;
1334	return rule;
1335}
1336
1337static void
1338init_tables(void)
1339{
1340	int i;
1341
1342	for (i = 0; i < IPFW_TABLES_MAX; i++) {
1343		rn_inithead((void **)&ipfw_tables[i].rnh, 32);
1344		ipfw_tables[i].modified = 1;
1345	}
1346}
1347
1348static int
1349add_table_entry(u_int16_t tbl, in_addr_t addr, u_int8_t mlen, u_int32_t value)
1350{
1351	struct radix_node_head *rnh;
1352	struct table_entry *ent;
1353
1354	if (tbl >= IPFW_TABLES_MAX)
1355		return (EINVAL);
1356	rnh = ipfw_tables[tbl].rnh;
1357	ent = malloc(sizeof(*ent), M_IPFW_TBL, M_NOWAIT | M_ZERO);
1358	if (ent == NULL)
1359		return (ENOMEM);
1360	ent->value = value;
1361	ent->addr.sin_len = ent->mask.sin_len = 8;
1362	ent->mask.sin_addr.s_addr = htonl(mlen ? ~((1 << (32 - mlen)) - 1) : 0);
1363	ent->addr.sin_addr.s_addr = addr & ent->mask.sin_addr.s_addr;
1364	RADIX_NODE_HEAD_LOCK(rnh);
1365	if (rnh->rnh_addaddr(&ent->addr, &ent->mask, rnh, (void *)ent) ==
1366	    NULL) {
1367		RADIX_NODE_HEAD_UNLOCK(rnh);
1368		free(ent, M_IPFW_TBL);
1369		return (EEXIST);
1370	}
1371	ipfw_tables[tbl].modified = 1;
1372	RADIX_NODE_HEAD_UNLOCK(rnh);
1373	return (0);
1374}
1375
1376static int
1377del_table_entry(u_int16_t tbl, in_addr_t addr, u_int8_t mlen)
1378{
1379	struct radix_node_head *rnh;
1380	struct table_entry *ent;
1381	struct sockaddr_in sa, mask;
1382
1383	if (tbl >= IPFW_TABLES_MAX)
1384		return (EINVAL);
1385	rnh = ipfw_tables[tbl].rnh;
1386	sa.sin_len = mask.sin_len = 8;
1387	mask.sin_addr.s_addr = htonl(mlen ? ~((1 << (32 - mlen)) - 1) : 0);
1388	sa.sin_addr.s_addr = addr & mask.sin_addr.s_addr;
1389	RADIX_NODE_HEAD_LOCK(rnh);
1390	ent = (struct table_entry *)rnh->rnh_deladdr(&sa, &mask, rnh);
1391	if (ent == NULL) {
1392		RADIX_NODE_HEAD_UNLOCK(rnh);
1393		return (ESRCH);
1394	}
1395	ipfw_tables[tbl].modified = 1;
1396	RADIX_NODE_HEAD_UNLOCK(rnh);
1397	free(ent, M_IPFW_TBL);
1398	return (0);
1399}
1400
1401static int
1402flush_table_entry(struct radix_node *rn, void *arg)
1403{
1404	struct radix_node_head * const rnh = arg;
1405	struct table_entry *ent;
1406
1407	ent = (struct table_entry *)
1408	    rnh->rnh_deladdr(rn->rn_key, rn->rn_mask, rnh);
1409	if (ent != NULL)
1410		free(ent, M_IPFW_TBL);
1411	return (0);
1412}
1413
1414static int
1415flush_table(u_int16_t tbl)
1416{
1417	struct radix_node_head *rnh;
1418
1419	if (tbl >= IPFW_TABLES_MAX)
1420		return (EINVAL);
1421	rnh = ipfw_tables[tbl].rnh;
1422	RADIX_NODE_HEAD_LOCK(rnh);
1423	rnh->rnh_walktree(rnh, flush_table_entry, rnh);
1424	ipfw_tables[tbl].modified = 1;
1425	RADIX_NODE_HEAD_UNLOCK(rnh);
1426	return (0);
1427}
1428
1429static void
1430flush_tables(void)
1431{
1432	u_int16_t tbl;
1433
1434	for (tbl = 0; tbl < IPFW_TABLES_MAX; tbl++)
1435		flush_table(tbl);
1436}
1437
1438static int
1439lookup_table(u_int16_t tbl, in_addr_t addr, u_int32_t *val)
1440{
1441	struct radix_node_head *rnh;
1442	struct table_entry *ent;
1443	struct sockaddr_in sa;
1444	static in_addr_t last_addr;
1445	static int last_tbl;
1446	static int last_match;
1447	static u_int32_t last_value;
1448
1449	if (tbl >= IPFW_TABLES_MAX)
1450		return (0);
1451	if (tbl == last_tbl && addr == last_addr &&
1452	    !ipfw_tables[tbl].modified) {
1453		if (last_match)
1454			*val = last_value;
1455		return (last_match);
1456	}
1457	rnh = ipfw_tables[tbl].rnh;
1458	sa.sin_len = 8;
1459	sa.sin_addr.s_addr = addr;
1460	RADIX_NODE_HEAD_LOCK(rnh);
1461	ipfw_tables[tbl].modified = 0;
1462	ent = (struct table_entry *)(rnh->rnh_lookup(&sa, NULL, rnh));
1463	RADIX_NODE_HEAD_UNLOCK(rnh);
1464	last_addr = addr;
1465	last_tbl = tbl;
1466	if (ent != NULL) {
1467		last_value = *val = ent->value;
1468		last_match = 1;
1469		return (1);
1470	}
1471	last_match = 0;
1472	return (0);
1473}
1474
1475static int
1476count_table_entry(struct radix_node *rn, void *arg)
1477{
1478	u_int32_t * const cnt = arg;
1479
1480	(*cnt)++;
1481	return (0);
1482}
1483
1484static int
1485count_table(u_int32_t tbl, u_int32_t *cnt)
1486{
1487	struct radix_node_head *rnh;
1488
1489	if (tbl >= IPFW_TABLES_MAX)
1490		return (EINVAL);
1491	rnh = ipfw_tables[tbl].rnh;
1492	*cnt = 0;
1493	RADIX_NODE_HEAD_LOCK(rnh);
1494	rnh->rnh_walktree(rnh, count_table_entry, cnt);
1495	RADIX_NODE_HEAD_UNLOCK(rnh);
1496	return (0);
1497}
1498
1499static int
1500dump_table_entry(struct radix_node *rn, void *arg)
1501{
1502	struct table_entry * const n = (struct table_entry *)rn;
1503	ipfw_table * const tbl = arg;
1504	ipfw_table_entry *ent;
1505
1506	if (tbl->cnt == tbl->size)
1507		return (1);
1508	ent = &tbl->ent[tbl->cnt];
1509	ent->tbl = tbl->tbl;
1510	if (in_nullhost(n->mask.sin_addr))
1511		ent->masklen = 0;
1512	else
1513		ent->masklen = 33 - ffs(ntohl(n->mask.sin_addr.s_addr));
1514	ent->addr = n->addr.sin_addr.s_addr;
1515	ent->value = n->value;
1516	tbl->cnt++;
1517	return (0);
1518}
1519
1520static int
1521dump_table(ipfw_table *tbl)
1522{
1523	struct radix_node_head *rnh;
1524
1525	if (tbl->tbl >= IPFW_TABLES_MAX)
1526		return (EINVAL);
1527	rnh = ipfw_tables[tbl->tbl].rnh;
1528	tbl->cnt = 0;
1529	RADIX_NODE_HEAD_LOCK(rnh);
1530	rnh->rnh_walktree(rnh, dump_table_entry, tbl);
1531	RADIX_NODE_HEAD_UNLOCK(rnh);
1532	return (0);
1533}
1534
1535static int
1536check_uidgid(ipfw_insn_u32 *insn,
1537	int proto, struct ifnet *oif,
1538	struct in_addr dst_ip, u_int16_t dst_port,
1539	struct in_addr src_ip, u_int16_t src_port,
1540	struct ip_fw_ugid *ugp, int *lookup)
1541{
1542	struct inpcbinfo *pi;
1543	int wildcard;
1544	struct inpcb *pcb;
1545	int match;
1546	struct ucred *cr;
1547	gid_t *gp;
1548
1549	/*
1550	 * If we have already been here and the packet has no
1551	 * PCB entry associated with it, then we can safely
1552	 * assume that this is a no match.
1553	 */
1554	if (*lookup == -1)
1555		return (0);
1556	if (proto == IPPROTO_TCP) {
1557		wildcard = 0;
1558		pi = &tcbinfo;
1559	} else if (proto == IPPROTO_UDP) {
1560		wildcard = 1;
1561		pi = &udbinfo;
1562	} else
1563		return 0;
1564	match = 0;
1565	if (*lookup == 0) {
1566		INP_INFO_RLOCK(pi);	/* XXX LOR with IPFW */
1567		pcb =  (oif) ?
1568			in_pcblookup_hash(pi,
1569				dst_ip, htons(dst_port),
1570				src_ip, htons(src_port),
1571				wildcard, oif) :
1572			in_pcblookup_hash(pi,
1573				src_ip, htons(src_port),
1574				dst_ip, htons(dst_port),
1575				wildcard, NULL);
1576		if (pcb != NULL) {
1577			INP_LOCK(pcb);
1578			if (pcb->inp_socket != NULL) {
1579				cr = pcb->inp_socket->so_cred;
1580				ugp->fw_prid = jailed(cr) ?
1581				    cr->cr_prison->pr_id : -1;
1582				ugp->fw_uid = cr->cr_uid;
1583				ugp->fw_ngroups = cr->cr_ngroups;
1584				bcopy(cr->cr_groups, ugp->fw_groups,
1585					sizeof(ugp->fw_groups));
1586				*lookup = 1;
1587			}
1588			INP_UNLOCK(pcb);
1589		}
1590		INP_INFO_RUNLOCK(pi);
1591		if (*lookup == 0) {
1592			/*
1593			 * If the lookup did not yield any results, there
1594			 * is no sense in coming back and trying again. So
1595			 * we can set lookup to -1 and ensure that we wont
1596			 * bother the pcb system again.
1597			 */
1598			*lookup = -1;
1599			return (0);
1600		}
1601	}
1602	if (insn->o.opcode == O_UID)
1603		match = (ugp->fw_uid == (uid_t)insn->d[0]);
1604	else if (insn->o.opcode == O_GID) {
1605		for (gp = ugp->fw_groups;
1606			gp < &ugp->fw_groups[ugp->fw_ngroups]; gp++)
1607			if (*gp == (gid_t)insn->d[0]) {
1608				match = 1;
1609				break;
1610			}
1611	} else if (insn->o.opcode == O_JAIL)
1612		match = (ugp->fw_prid == (int)insn->d[0]);
1613	return match;
1614}
1615
1616/*
1617 * The main check routine for the firewall.
1618 *
1619 * All arguments are in args so we can modify them and return them
1620 * back to the caller.
1621 *
1622 * Parameters:
1623 *
1624 *	args->m	(in/out) The packet; we set to NULL when/if we nuke it.
1625 *		Starts with the IP header.
1626 *	args->eh (in)	Mac header if present, or NULL for layer3 packet.
1627 *	args->oif	Outgoing interface, or NULL if packet is incoming.
1628 *		The incoming interface is in the mbuf. (in)
1629 *	args->divert_rule (in/out)
1630 *		Skip up to the first rule past this rule number;
1631 *		upon return, non-zero port number for divert or tee.
1632 *
1633 *	args->rule	Pointer to the last matching rule (in/out)
1634 *	args->next_hop	Socket we are forwarding to (out).
1635 *	args->f_id	Addresses grabbed from the packet (out)
1636 *
1637 * Return value:
1638 *
1639 *	IP_FW_PORT_DENY_FLAG	the packet must be dropped.
1640 *	0	The packet is to be accepted and routed normally OR
1641 *      	the packet was denied/rejected and has been dropped;
1642 *		in the latter case, *m is equal to NULL upon return.
1643 *	port	Divert the packet to port, with these caveats:
1644 *
1645 *		- If IP_FW_PORT_TEE_FLAG is set, tee the packet instead
1646 *		  of diverting it (ie, 'ipfw tee').
1647 *
1648 *		- If IP_FW_PORT_DYNT_FLAG is set, interpret the lower
1649 *		  16 bits as a dummynet pipe number instead of diverting
1650 */
1651
1652int
1653ipfw_chk(struct ip_fw_args *args)
1654{
1655	/*
1656	 * Local variables hold state during the processing of a packet.
1657	 *
1658	 * IMPORTANT NOTE: to speed up the processing of rules, there
1659	 * are some assumption on the values of the variables, which
1660	 * are documented here. Should you change them, please check
1661	 * the implementation of the various instructions to make sure
1662	 * that they still work.
1663	 *
1664	 * args->eh	The MAC header. It is non-null for a layer2
1665	 *	packet, it is NULL for a layer-3 packet.
1666	 *
1667	 * m | args->m	Pointer to the mbuf, as received from the caller.
1668	 *	It may change if ipfw_chk() does an m_pullup, or if it
1669	 *	consumes the packet because it calls send_reject().
1670	 *	XXX This has to change, so that ipfw_chk() never modifies
1671	 *	or consumes the buffer.
1672	 * ip	is simply an alias of the value of m, and it is kept
1673	 *	in sync with it (the packet is	supposed to start with
1674	 *	the ip header).
1675	 */
1676	struct mbuf *m = args->m;
1677	struct ip *ip = mtod(m, struct ip *);
1678
1679	/*
1680	 * For rules which contain uid/gid or jail constraints, cache
1681	 * a copy of the users credentials after the pcb lookup has been
1682	 * executed. This will speed up the processing of rules with
1683	 * these types of constraints, as well as decrease contention
1684	 * on pcb related locks.
1685	 */
1686	struct ip_fw_ugid fw_ugid_cache;
1687	int ugid_lookup = 0;
1688
1689	/*
1690	 * oif | args->oif	If NULL, ipfw_chk has been called on the
1691	 *	inbound path (ether_input, bdg_forward, ip_input).
1692	 *	If non-NULL, ipfw_chk has been called on the outbound path
1693	 *	(ether_output, ip_output).
1694	 */
1695	struct ifnet *oif = args->oif;
1696
1697	struct ip_fw *f = NULL;		/* matching rule */
1698	int retval = 0;
1699
1700	/*
1701	 * hlen	The length of the IPv4 header.
1702	 *	hlen >0 means we have an IPv4 packet.
1703	 */
1704	u_int hlen = 0;		/* hlen >0 means we have an IP pkt */
1705
1706	/*
1707	 * offset	The offset of a fragment. offset != 0 means that
1708	 *	we have a fragment at this offset of an IPv4 packet.
1709	 *	offset == 0 means that (if this is an IPv4 packet)
1710	 *	this is the first or only fragment.
1711	 */
1712	u_short offset = 0;
1713
1714	/*
1715	 * Local copies of addresses. They are only valid if we have
1716	 * an IP packet.
1717	 *
1718	 * proto	The protocol. Set to 0 for non-ip packets,
1719	 *	or to the protocol read from the packet otherwise.
1720	 *	proto != 0 means that we have an IPv4 packet.
1721	 *
1722	 * src_port, dst_port	port numbers, in HOST format. Only
1723	 *	valid for TCP and UDP packets.
1724	 *
1725	 * src_ip, dst_ip	ip addresses, in NETWORK format.
1726	 *	Only valid for IPv4 packets.
1727	 */
1728	u_int8_t proto;
1729	u_int16_t src_port = 0, dst_port = 0;	/* NOTE: host format	*/
1730	struct in_addr src_ip, dst_ip;		/* NOTE: network format	*/
1731	u_int16_t ip_len=0;
1732	int pktlen;
1733	int dyn_dir = MATCH_UNKNOWN;
1734	ipfw_dyn_rule *q = NULL;
1735	struct ip_fw_chain *chain = &layer3_chain;
1736	struct m_tag *mtag;
1737
1738	if (m->m_flags & M_SKIP_FIREWALL)
1739		return 0;	/* accept */
1740	/*
1741	 * dyn_dir = MATCH_UNKNOWN when rules unchecked,
1742	 * 	MATCH_NONE when checked and not matched (q = NULL),
1743	 *	MATCH_FORWARD or MATCH_REVERSE otherwise (q != NULL)
1744	 */
1745
1746	pktlen = m->m_pkthdr.len;
1747	if (args->eh == NULL ||		/* layer 3 packet */
1748		( m->m_pkthdr.len >= sizeof(struct ip) &&
1749		    ntohs(args->eh->ether_type) == ETHERTYPE_IP))
1750			hlen = ip->ip_hl << 2;
1751
1752	/*
1753	 * Collect parameters into local variables for faster matching.
1754	 */
1755	if (hlen == 0) {	/* do not grab addresses for non-ip pkts */
1756		proto = args->f_id.proto = 0;	/* mark f_id invalid */
1757		goto after_ip_checks;
1758	}
1759
1760	proto = args->f_id.proto = ip->ip_p;
1761	src_ip = ip->ip_src;
1762	dst_ip = ip->ip_dst;
1763	if (args->eh != NULL) { /* layer 2 packets are as on the wire */
1764		offset = ntohs(ip->ip_off) & IP_OFFMASK;
1765		ip_len = ntohs(ip->ip_len);
1766	} else {
1767		offset = ip->ip_off & IP_OFFMASK;
1768		ip_len = ip->ip_len;
1769	}
1770	pktlen = ip_len < pktlen ? ip_len : pktlen;
1771
1772#define PULLUP_TO(len)						\
1773		do {						\
1774			if ((m)->m_len < (len)) {		\
1775			    args->m = m = m_pullup(m, (len));	\
1776			    if (m == 0)				\
1777				goto pullup_failed;		\
1778			    ip = mtod(m, struct ip *);		\
1779			}					\
1780		} while (0)
1781
1782	if (offset == 0) {
1783		switch (proto) {
1784		case IPPROTO_TCP:
1785		    {
1786			struct tcphdr *tcp;
1787
1788			PULLUP_TO(hlen + sizeof(struct tcphdr));
1789			tcp = L3HDR(struct tcphdr, ip);
1790			dst_port = tcp->th_dport;
1791			src_port = tcp->th_sport;
1792			args->f_id.flags = tcp->th_flags;
1793			}
1794			break;
1795
1796		case IPPROTO_UDP:
1797		    {
1798			struct udphdr *udp;
1799
1800			PULLUP_TO(hlen + sizeof(struct udphdr));
1801			udp = L3HDR(struct udphdr, ip);
1802			dst_port = udp->uh_dport;
1803			src_port = udp->uh_sport;
1804			}
1805			break;
1806
1807		case IPPROTO_ICMP:
1808			PULLUP_TO(hlen + 4);	/* type, code and checksum. */
1809			args->f_id.flags = L3HDR(struct icmp, ip)->icmp_type;
1810			break;
1811
1812		default:
1813			break;
1814		}
1815#undef PULLUP_TO
1816	}
1817
1818	args->f_id.src_ip = ntohl(src_ip.s_addr);
1819	args->f_id.dst_ip = ntohl(dst_ip.s_addr);
1820	args->f_id.src_port = src_port = ntohs(src_port);
1821	args->f_id.dst_port = dst_port = ntohs(dst_port);
1822
1823after_ip_checks:
1824	IPFW_LOCK(chain);		/* XXX expensive? can we run lock free? */
1825	mtag = m_tag_find(m, PACKET_TAG_DIVERT, NULL);
1826	if (args->rule) {
1827		/*
1828		 * Packet has already been tagged. Look for the next rule
1829		 * to restart processing.
1830		 *
1831		 * If fw_one_pass != 0 then just accept it.
1832		 * XXX should not happen here, but optimized out in
1833		 * the caller.
1834		 */
1835		if (fw_one_pass) {
1836			IPFW_UNLOCK(chain);	/* XXX optimize */
1837			return 0;
1838		}
1839
1840		f = args->rule->next_rule;
1841		if (f == NULL)
1842			f = lookup_next_rule(args->rule);
1843	} else {
1844		/*
1845		 * Find the starting rule. It can be either the first
1846		 * one, or the one after divert_rule if asked so.
1847		 */
1848		int skipto = mtag ? divert_cookie(mtag) : 0;
1849
1850		f = chain->rules;
1851		if (args->eh == NULL && skipto != 0) {
1852			if (skipto >= IPFW_DEFAULT_RULE) {
1853				IPFW_UNLOCK(chain);
1854				return(IP_FW_PORT_DENY_FLAG); /* invalid */
1855			}
1856			while (f && f->rulenum <= skipto)
1857				f = f->next;
1858			if (f == NULL) {	/* drop packet */
1859				IPFW_UNLOCK(chain);
1860				return(IP_FW_PORT_DENY_FLAG);
1861			}
1862		}
1863	}
1864	/* reset divert rule to avoid confusion later */
1865	if (mtag)
1866		m_tag_delete(m, mtag);
1867
1868	/*
1869	 * Now scan the rules, and parse microinstructions for each rule.
1870	 */
1871	for (; f; f = f->next) {
1872		int l, cmdlen;
1873		ipfw_insn *cmd;
1874		int skip_or; /* skip rest of OR block */
1875
1876again:
1877		if (set_disable & (1 << f->set) )
1878			continue;
1879
1880		skip_or = 0;
1881		for (l = f->cmd_len, cmd = f->cmd ; l > 0 ;
1882		    l -= cmdlen, cmd += cmdlen) {
1883			int match;
1884
1885			/*
1886			 * check_body is a jump target used when we find a
1887			 * CHECK_STATE, and need to jump to the body of
1888			 * the target rule.
1889			 */
1890
1891check_body:
1892			cmdlen = F_LEN(cmd);
1893			/*
1894			 * An OR block (insn_1 || .. || insn_n) has the
1895			 * F_OR bit set in all but the last instruction.
1896			 * The first match will set "skip_or", and cause
1897			 * the following instructions to be skipped until
1898			 * past the one with the F_OR bit clear.
1899			 */
1900			if (skip_or) {		/* skip this instruction */
1901				if ((cmd->len & F_OR) == 0)
1902					skip_or = 0;	/* next one is good */
1903				continue;
1904			}
1905			match = 0; /* set to 1 if we succeed */
1906
1907			switch (cmd->opcode) {
1908			/*
1909			 * The first set of opcodes compares the packet's
1910			 * fields with some pattern, setting 'match' if a
1911			 * match is found. At the end of the loop there is
1912			 * logic to deal with F_NOT and F_OR flags associated
1913			 * with the opcode.
1914			 */
1915			case O_NOP:
1916				match = 1;
1917				break;
1918
1919			case O_FORWARD_MAC:
1920				printf("ipfw: opcode %d unimplemented\n",
1921				    cmd->opcode);
1922				break;
1923
1924			case O_GID:
1925			case O_UID:
1926			case O_JAIL:
1927				/*
1928				 * We only check offset == 0 && proto != 0,
1929				 * as this ensures that we have an IPv4
1930				 * packet with the ports info.
1931				 */
1932				if (offset!=0)
1933					break;
1934				if (proto == IPPROTO_TCP ||
1935				    proto == IPPROTO_UDP)
1936					match = check_uidgid(
1937						    (ipfw_insn_u32 *)cmd,
1938						    proto, oif,
1939						    dst_ip, dst_port,
1940						    src_ip, src_port, &fw_ugid_cache,
1941						    &ugid_lookup);
1942				break;
1943
1944			case O_RECV:
1945				match = iface_match(m->m_pkthdr.rcvif,
1946				    (ipfw_insn_if *)cmd);
1947				break;
1948
1949			case O_XMIT:
1950				match = iface_match(oif, (ipfw_insn_if *)cmd);
1951				break;
1952
1953			case O_VIA:
1954				match = iface_match(oif ? oif :
1955				    m->m_pkthdr.rcvif, (ipfw_insn_if *)cmd);
1956				break;
1957
1958			case O_MACADDR2:
1959				if (args->eh != NULL) {	/* have MAC header */
1960					u_int32_t *want = (u_int32_t *)
1961						((ipfw_insn_mac *)cmd)->addr;
1962					u_int32_t *mask = (u_int32_t *)
1963						((ipfw_insn_mac *)cmd)->mask;
1964					u_int32_t *hdr = (u_int32_t *)args->eh;
1965
1966					match =
1967					    ( want[0] == (hdr[0] & mask[0]) &&
1968					      want[1] == (hdr[1] & mask[1]) &&
1969					      want[2] == (hdr[2] & mask[2]) );
1970				}
1971				break;
1972
1973			case O_MAC_TYPE:
1974				if (args->eh != NULL) {
1975					u_int16_t t =
1976					    ntohs(args->eh->ether_type);
1977					u_int16_t *p =
1978					    ((ipfw_insn_u16 *)cmd)->ports;
1979					int i;
1980
1981					for (i = cmdlen - 1; !match && i>0;
1982					    i--, p += 2)
1983						match = (t>=p[0] && t<=p[1]);
1984				}
1985				break;
1986
1987			case O_FRAG:
1988				match = (hlen > 0 && offset != 0);
1989				break;
1990
1991			case O_IN:	/* "out" is "not in" */
1992				match = (oif == NULL);
1993				break;
1994
1995			case O_LAYER2:
1996				match = (args->eh != NULL);
1997				break;
1998
1999			case O_PROTO:
2000				/*
2001				 * We do not allow an arg of 0 so the
2002				 * check of "proto" only suffices.
2003				 */
2004				match = (proto == cmd->arg1);
2005				break;
2006
2007			case O_IP_SRC:
2008				match = (hlen > 0 &&
2009				    ((ipfw_insn_ip *)cmd)->addr.s_addr ==
2010				    src_ip.s_addr);
2011				break;
2012
2013			case O_IP_SRC_LOOKUP:
2014			case O_IP_DST_LOOKUP:
2015				if (hlen > 0) {
2016				    uint32_t a =
2017					(cmd->opcode == O_IP_DST_LOOKUP) ?
2018					    dst_ip.s_addr : src_ip.s_addr;
2019				    uint32_t v;
2020
2021				    match = lookup_table(cmd->arg1, a, &v);
2022				    if (!match)
2023					break;
2024				    if (cmdlen == F_INSN_SIZE(ipfw_insn_u32))
2025					match =
2026					    ((ipfw_insn_u32 *)cmd)->d[0] == v;
2027				}
2028				break;
2029
2030			case O_IP_SRC_MASK:
2031			case O_IP_DST_MASK:
2032				if (hlen > 0) {
2033				    uint32_t a =
2034					(cmd->opcode == O_IP_DST_MASK) ?
2035					    dst_ip.s_addr : src_ip.s_addr;
2036				    uint32_t *p = ((ipfw_insn_u32 *)cmd)->d;
2037				    int i = cmdlen-1;
2038
2039				    for (; !match && i>0; i-= 2, p+= 2)
2040					match = (p[0] == (a & p[1]));
2041				}
2042				break;
2043
2044			case O_IP_SRC_ME:
2045				if (hlen > 0) {
2046					struct ifnet *tif;
2047
2048					INADDR_TO_IFP(src_ip, tif);
2049					match = (tif != NULL);
2050				}
2051				break;
2052
2053			case O_IP_DST_SET:
2054			case O_IP_SRC_SET:
2055				if (hlen > 0) {
2056					u_int32_t *d = (u_int32_t *)(cmd+1);
2057					u_int32_t addr =
2058					    cmd->opcode == O_IP_DST_SET ?
2059						args->f_id.dst_ip :
2060						args->f_id.src_ip;
2061
2062					    if (addr < d[0])
2063						    break;
2064					    addr -= d[0]; /* subtract base */
2065					    match = (addr < cmd->arg1) &&
2066						( d[ 1 + (addr>>5)] &
2067						  (1<<(addr & 0x1f)) );
2068				}
2069				break;
2070
2071			case O_IP_DST:
2072				match = (hlen > 0 &&
2073				    ((ipfw_insn_ip *)cmd)->addr.s_addr ==
2074				    dst_ip.s_addr);
2075				break;
2076
2077			case O_IP_DST_ME:
2078				if (hlen > 0) {
2079					struct ifnet *tif;
2080
2081					INADDR_TO_IFP(dst_ip, tif);
2082					match = (tif != NULL);
2083				}
2084				break;
2085
2086			case O_IP_SRCPORT:
2087			case O_IP_DSTPORT:
2088				/*
2089				 * offset == 0 && proto != 0 is enough
2090				 * to guarantee that we have an IPv4
2091				 * packet with port info.
2092				 */
2093				if ((proto==IPPROTO_UDP || proto==IPPROTO_TCP)
2094				    && offset == 0) {
2095					u_int16_t x =
2096					    (cmd->opcode == O_IP_SRCPORT) ?
2097						src_port : dst_port ;
2098					u_int16_t *p =
2099					    ((ipfw_insn_u16 *)cmd)->ports;
2100					int i;
2101
2102					for (i = cmdlen - 1; !match && i>0;
2103					    i--, p += 2)
2104						match = (x>=p[0] && x<=p[1]);
2105				}
2106				break;
2107
2108			case O_ICMPTYPE:
2109				match = (offset == 0 && proto==IPPROTO_ICMP &&
2110				    icmptype_match(ip, (ipfw_insn_u32 *)cmd) );
2111				break;
2112
2113			case O_IPOPT:
2114				match = (hlen > 0 && ipopts_match(ip, cmd) );
2115				break;
2116
2117			case O_IPVER:
2118				match = (hlen > 0 && cmd->arg1 == ip->ip_v);
2119				break;
2120
2121			case O_IPID:
2122			case O_IPLEN:
2123			case O_IPTTL:
2124				if (hlen > 0) {	/* only for IP packets */
2125				    uint16_t x;
2126				    uint16_t *p;
2127				    int i;
2128
2129				    if (cmd->opcode == O_IPLEN)
2130					x = ip_len;
2131				    else if (cmd->opcode == O_IPTTL)
2132					x = ip->ip_ttl;
2133				    else /* must be IPID */
2134					x = ntohs(ip->ip_id);
2135				    if (cmdlen == 1) {
2136					match = (cmd->arg1 == x);
2137					break;
2138				    }
2139				    /* otherwise we have ranges */
2140				    p = ((ipfw_insn_u16 *)cmd)->ports;
2141				    i = cmdlen - 1;
2142				    for (; !match && i>0; i--, p += 2)
2143					match = (x >= p[0] && x <= p[1]);
2144				}
2145				break;
2146
2147			case O_IPPRECEDENCE:
2148				match = (hlen > 0 &&
2149				    (cmd->arg1 == (ip->ip_tos & 0xe0)) );
2150				break;
2151
2152			case O_IPTOS:
2153				match = (hlen > 0 &&
2154				    flags_match(cmd, ip->ip_tos));
2155				break;
2156
2157			case O_TCPFLAGS:
2158				match = (proto == IPPROTO_TCP && offset == 0 &&
2159				    flags_match(cmd,
2160					L3HDR(struct tcphdr,ip)->th_flags));
2161				break;
2162
2163			case O_TCPOPTS:
2164				match = (proto == IPPROTO_TCP && offset == 0 &&
2165				    tcpopts_match(ip, cmd));
2166				break;
2167
2168			case O_TCPSEQ:
2169				match = (proto == IPPROTO_TCP && offset == 0 &&
2170				    ((ipfw_insn_u32 *)cmd)->d[0] ==
2171					L3HDR(struct tcphdr,ip)->th_seq);
2172				break;
2173
2174			case O_TCPACK:
2175				match = (proto == IPPROTO_TCP && offset == 0 &&
2176				    ((ipfw_insn_u32 *)cmd)->d[0] ==
2177					L3HDR(struct tcphdr,ip)->th_ack);
2178				break;
2179
2180			case O_TCPWIN:
2181				match = (proto == IPPROTO_TCP && offset == 0 &&
2182				    cmd->arg1 ==
2183					L3HDR(struct tcphdr,ip)->th_win);
2184				break;
2185
2186			case O_ESTAB:
2187				/* reject packets which have SYN only */
2188				/* XXX should i also check for TH_ACK ? */
2189				match = (proto == IPPROTO_TCP && offset == 0 &&
2190				    (L3HDR(struct tcphdr,ip)->th_flags &
2191				     (TH_RST | TH_ACK | TH_SYN)) != TH_SYN);
2192				break;
2193
2194			case O_LOG:
2195				if (fw_verbose)
2196					ipfw_log(f, hlen, args->eh, m, oif);
2197				match = 1;
2198				break;
2199
2200			case O_PROB:
2201				match = (random()<((ipfw_insn_u32 *)cmd)->d[0]);
2202				break;
2203
2204			case O_VERREVPATH:
2205				/* Outgoing packets automatically pass/match */
2206				match = (hlen > 0 && ((oif != NULL) ||
2207				    (m->m_pkthdr.rcvif == NULL) ||
2208				    verify_path(src_ip, m->m_pkthdr.rcvif)));
2209				break;
2210
2211			case O_VERSRCREACH:
2212				/* Outgoing packets automatically pass/match */
2213				match = (hlen > 0 && ((oif != NULL) ||
2214				     verify_path(src_ip, NULL)));
2215				break;
2216
2217			case O_ANTISPOOF:
2218				/* Outgoing packets automatically pass/match */
2219				if (oif == NULL && hlen > 0 &&
2220				    in_localaddr(src_ip))
2221					match = verify_path(src_ip,
2222							m->m_pkthdr.rcvif);
2223				else
2224					match = 1;
2225				break;
2226
2227			case O_IPSEC:
2228#ifdef FAST_IPSEC
2229				match = (m_tag_find(m,
2230				    PACKET_TAG_IPSEC_IN_DONE, NULL) != NULL);
2231#endif
2232#ifdef IPSEC
2233				match = (ipsec_getnhist(m) != 0);
2234#endif
2235				/* otherwise no match */
2236				break;
2237
2238			/*
2239			 * The second set of opcodes represents 'actions',
2240			 * i.e. the terminal part of a rule once the packet
2241			 * matches all previous patterns.
2242			 * Typically there is only one action for each rule,
2243			 * and the opcode is stored at the end of the rule
2244			 * (but there are exceptions -- see below).
2245			 *
2246			 * In general, here we set retval and terminate the
2247			 * outer loop (would be a 'break 3' in some language,
2248			 * but we need to do a 'goto done').
2249			 *
2250			 * Exceptions:
2251			 * O_COUNT and O_SKIPTO actions:
2252			 *   instead of terminating, we jump to the next rule
2253			 *   ('goto next_rule', equivalent to a 'break 2'),
2254			 *   or to the SKIPTO target ('goto again' after
2255			 *   having set f, cmd and l), respectively.
2256			 *
2257			 * O_LIMIT and O_KEEP_STATE: these opcodes are
2258			 *   not real 'actions', and are stored right
2259			 *   before the 'action' part of the rule.
2260			 *   These opcodes try to install an entry in the
2261			 *   state tables; if successful, we continue with
2262			 *   the next opcode (match=1; break;), otherwise
2263			 *   the packet *   must be dropped
2264			 *   ('goto done' after setting retval);
2265			 *
2266			 * O_PROBE_STATE and O_CHECK_STATE: these opcodes
2267			 *   cause a lookup of the state table, and a jump
2268			 *   to the 'action' part of the parent rule
2269			 *   ('goto check_body') if an entry is found, or
2270			 *   (CHECK_STATE only) a jump to the next rule if
2271			 *   the entry is not found ('goto next_rule').
2272			 *   The result of the lookup is cached to make
2273			 *   further instances of these opcodes are
2274			 *   effectively NOPs.
2275			 */
2276			case O_LIMIT:
2277			case O_KEEP_STATE:
2278				if (install_state(f,
2279				    (ipfw_insn_limit *)cmd, args)) {
2280					retval = IP_FW_PORT_DENY_FLAG;
2281					goto done; /* error/limit violation */
2282				}
2283				match = 1;
2284				break;
2285
2286			case O_PROBE_STATE:
2287			case O_CHECK_STATE:
2288				/*
2289				 * dynamic rules are checked at the first
2290				 * keep-state or check-state occurrence,
2291				 * with the result being stored in dyn_dir.
2292				 * The compiler introduces a PROBE_STATE
2293				 * instruction for us when we have a
2294				 * KEEP_STATE (because PROBE_STATE needs
2295				 * to be run first).
2296				 */
2297				if (dyn_dir == MATCH_UNKNOWN &&
2298				    (q = lookup_dyn_rule(&args->f_id,
2299				     &dyn_dir, proto == IPPROTO_TCP ?
2300					L3HDR(struct tcphdr, ip) : NULL))
2301					!= NULL) {
2302					/*
2303					 * Found dynamic entry, update stats
2304					 * and jump to the 'action' part of
2305					 * the parent rule.
2306					 */
2307					q->pcnt++;
2308					q->bcnt += pktlen;
2309					f = q->rule;
2310					cmd = ACTION_PTR(f);
2311					l = f->cmd_len - f->act_ofs;
2312					IPFW_DYN_UNLOCK();
2313					goto check_body;
2314				}
2315				/*
2316				 * Dynamic entry not found. If CHECK_STATE,
2317				 * skip to next rule, if PROBE_STATE just
2318				 * ignore and continue with next opcode.
2319				 */
2320				if (cmd->opcode == O_CHECK_STATE)
2321					goto next_rule;
2322				match = 1;
2323				break;
2324
2325			case O_ACCEPT:
2326				retval = 0;	/* accept */
2327				goto done;
2328
2329			case O_PIPE:
2330			case O_QUEUE:
2331				args->rule = f; /* report matching rule */
2332				retval = cmd->arg1 | IP_FW_PORT_DYNT_FLAG;
2333				goto done;
2334
2335			case O_DIVERT:
2336			case O_TEE: {
2337				struct divert_tag *dt;
2338
2339				if (args->eh) /* not on layer 2 */
2340					break;
2341				mtag = m_tag_get(PACKET_TAG_DIVERT,
2342						sizeof(struct divert_tag),
2343						M_NOWAIT);
2344				if (mtag == NULL) {
2345					/* XXX statistic */
2346					/* drop packet */
2347					IPFW_UNLOCK(chain);
2348					return IP_FW_PORT_DENY_FLAG;
2349				}
2350				dt = (struct divert_tag *)(mtag+1);
2351				dt->cookie = f->rulenum;
2352				dt->info = (cmd->opcode == O_DIVERT) ?
2353				    cmd->arg1 :
2354				    cmd->arg1 | IP_FW_PORT_TEE_FLAG;
2355				m_tag_prepend(m, mtag);
2356				retval = dt->info;
2357				goto done;
2358			}
2359
2360			case O_COUNT:
2361			case O_SKIPTO:
2362				f->pcnt++;	/* update stats */
2363				f->bcnt += pktlen;
2364				f->timestamp = time_second;
2365				if (cmd->opcode == O_COUNT)
2366					goto next_rule;
2367				/* handle skipto */
2368				if (f->next_rule == NULL)
2369					lookup_next_rule(f);
2370				f = f->next_rule;
2371				goto again;
2372
2373			case O_REJECT:
2374				/*
2375				 * Drop the packet and send a reject notice
2376				 * if the packet is not ICMP (or is an ICMP
2377				 * query), and it is not multicast/broadcast.
2378				 */
2379				if (hlen > 0 &&
2380				    (proto != IPPROTO_ICMP ||
2381				     is_icmp_query(ip)) &&
2382				    !(m->m_flags & (M_BCAST|M_MCAST)) &&
2383				    !IN_MULTICAST(ntohl(dst_ip.s_addr))) {
2384					send_reject(args, cmd->arg1,
2385					    offset,ip_len);
2386					m = args->m;
2387				}
2388				/* FALLTHROUGH */
2389			case O_DENY:
2390				retval = IP_FW_PORT_DENY_FLAG;
2391				goto done;
2392
2393			case O_FORWARD_IP:
2394				if (args->eh)	/* not valid on layer2 pkts */
2395					break;
2396				if (!q || dyn_dir == MATCH_FORWARD)
2397					args->next_hop =
2398					    &((ipfw_insn_sa *)cmd)->sa;
2399				retval = 0;
2400				goto done;
2401
2402			default:
2403				panic("-- unknown opcode %d\n", cmd->opcode);
2404			} /* end of switch() on opcodes */
2405
2406			if (cmd->len & F_NOT)
2407				match = !match;
2408
2409			if (match) {
2410				if (cmd->len & F_OR)
2411					skip_or = 1;
2412			} else {
2413				if (!(cmd->len & F_OR)) /* not an OR block, */
2414					break;		/* try next rule    */
2415			}
2416
2417		}	/* end of inner for, scan opcodes */
2418
2419next_rule:;		/* try next rule		*/
2420
2421	}		/* end of outer for, scan rules */
2422	printf("ipfw: ouch!, skip past end of rules, denying packet\n");
2423	IPFW_UNLOCK(chain);
2424	return(IP_FW_PORT_DENY_FLAG);
2425
2426done:
2427	/* Update statistics */
2428	f->pcnt++;
2429	f->bcnt += pktlen;
2430	f->timestamp = time_second;
2431	IPFW_UNLOCK(chain);
2432	return retval;
2433
2434pullup_failed:
2435	if (fw_verbose)
2436		printf("ipfw: pullup failed\n");
2437	return(IP_FW_PORT_DENY_FLAG);
2438}
2439
2440/*
2441 * When a rule is added/deleted, clear the next_rule pointers in all rules.
2442 * These will be reconstructed on the fly as packets are matched.
2443 */
2444static void
2445flush_rule_ptrs(struct ip_fw_chain *chain)
2446{
2447	struct ip_fw *rule;
2448
2449	IPFW_LOCK_ASSERT(chain);
2450
2451	for (rule = chain->rules; rule; rule = rule->next)
2452		rule->next_rule = NULL;
2453}
2454
2455/*
2456 * When pipes/queues are deleted, clear the "pipe_ptr" pointer to a given
2457 * pipe/queue, or to all of them (match == NULL).
2458 */
2459void
2460flush_pipe_ptrs(struct dn_flow_set *match)
2461{
2462	struct ip_fw *rule;
2463
2464	IPFW_LOCK(&layer3_chain);
2465	for (rule = layer3_chain.rules; rule; rule = rule->next) {
2466		ipfw_insn_pipe *cmd = (ipfw_insn_pipe *)ACTION_PTR(rule);
2467
2468		if (cmd->o.opcode != O_PIPE && cmd->o.opcode != O_QUEUE)
2469			continue;
2470		/*
2471		 * XXX Use bcmp/bzero to handle pipe_ptr to overcome
2472		 * possible alignment problems on 64-bit architectures.
2473		 * This code is seldom used so we do not worry too
2474		 * much about efficiency.
2475		 */
2476		if (match == NULL ||
2477		    !bcmp(&cmd->pipe_ptr, &match, sizeof(match)) )
2478			bzero(&cmd->pipe_ptr, sizeof(cmd->pipe_ptr));
2479	}
2480	IPFW_UNLOCK(&layer3_chain);
2481}
2482
2483/*
2484 * Add a new rule to the list. Copy the rule into a malloc'ed area, then
2485 * possibly create a rule number and add the rule to the list.
2486 * Update the rule_number in the input struct so the caller knows it as well.
2487 */
2488static int
2489add_rule(struct ip_fw_chain *chain, struct ip_fw *input_rule)
2490{
2491	struct ip_fw *rule, *f, *prev;
2492	int l = RULESIZE(input_rule);
2493
2494	if (chain->rules == NULL && input_rule->rulenum != IPFW_DEFAULT_RULE)
2495		return (EINVAL);
2496
2497	rule = malloc(l, M_IPFW, M_NOWAIT | M_ZERO);
2498	if (rule == NULL)
2499		return (ENOSPC);
2500
2501	bcopy(input_rule, rule, l);
2502
2503	rule->next = NULL;
2504	rule->next_rule = NULL;
2505
2506	rule->pcnt = 0;
2507	rule->bcnt = 0;
2508	rule->timestamp = 0;
2509
2510	IPFW_LOCK(chain);
2511
2512	if (chain->rules == NULL) {	/* default rule */
2513		chain->rules = rule;
2514		goto done;
2515        }
2516
2517	/*
2518	 * If rulenum is 0, find highest numbered rule before the
2519	 * default rule, and add autoinc_step
2520	 */
2521	if (autoinc_step < 1)
2522		autoinc_step = 1;
2523	else if (autoinc_step > 1000)
2524		autoinc_step = 1000;
2525	if (rule->rulenum == 0) {
2526		/*
2527		 * locate the highest numbered rule before default
2528		 */
2529		for (f = chain->rules; f; f = f->next) {
2530			if (f->rulenum == IPFW_DEFAULT_RULE)
2531				break;
2532			rule->rulenum = f->rulenum;
2533		}
2534		if (rule->rulenum < IPFW_DEFAULT_RULE - autoinc_step)
2535			rule->rulenum += autoinc_step;
2536		input_rule->rulenum = rule->rulenum;
2537	}
2538
2539	/*
2540	 * Now insert the new rule in the right place in the sorted list.
2541	 */
2542	for (prev = NULL, f = chain->rules; f; prev = f, f = f->next) {
2543		if (f->rulenum > rule->rulenum) { /* found the location */
2544			if (prev) {
2545				rule->next = f;
2546				prev->next = rule;
2547			} else { /* head insert */
2548				rule->next = chain->rules;
2549				chain->rules = rule;
2550			}
2551			break;
2552		}
2553	}
2554	flush_rule_ptrs(chain);
2555done:
2556	static_count++;
2557	static_len += l;
2558	IPFW_UNLOCK(chain);
2559	DEB(printf("ipfw: installed rule %d, static count now %d\n",
2560		rule->rulenum, static_count);)
2561	return (0);
2562}
2563
2564/**
2565 * Remove a static rule (including derived * dynamic rules)
2566 * and place it on the ``reap list'' for later reclamation.
2567 * The caller is in charge of clearing rule pointers to avoid
2568 * dangling pointers.
2569 * @return a pointer to the next entry.
2570 * Arguments are not checked, so they better be correct.
2571 */
2572static struct ip_fw *
2573remove_rule(struct ip_fw_chain *chain, struct ip_fw *rule, struct ip_fw *prev)
2574{
2575	struct ip_fw *n;
2576	int l = RULESIZE(rule);
2577
2578	IPFW_LOCK_ASSERT(chain);
2579
2580	n = rule->next;
2581	IPFW_DYN_LOCK();
2582	remove_dyn_rule(rule, NULL /* force removal */);
2583	IPFW_DYN_UNLOCK();
2584	if (prev == NULL)
2585		chain->rules = n;
2586	else
2587		prev->next = n;
2588	static_count--;
2589	static_len -= l;
2590
2591	rule->next = chain->reap;
2592	chain->reap = rule;
2593
2594	return n;
2595}
2596
2597/**
2598 * Reclaim storage associated with a list of rules.  This is
2599 * typically the list created using remove_rule.
2600 */
2601static void
2602reap_rules(struct ip_fw *head)
2603{
2604	struct ip_fw *rule;
2605
2606	while ((rule = head) != NULL) {
2607		head = head->next;
2608		if (DUMMYNET_LOADED)
2609			ip_dn_ruledel_ptr(rule);
2610		free(rule, M_IPFW);
2611	}
2612}
2613
2614/*
2615 * Remove all rules from a chain (except rules in set RESVD_SET
2616 * unless kill_default = 1).  The caller is responsible for
2617 * reclaiming storage for the rules left in chain->reap.
2618 */
2619static void
2620free_chain(struct ip_fw_chain *chain, int kill_default)
2621{
2622	struct ip_fw *prev, *rule;
2623
2624	IPFW_LOCK_ASSERT(chain);
2625
2626	flush_rule_ptrs(chain); /* more efficient to do outside the loop */
2627	for (prev = NULL, rule = chain->rules; rule ; )
2628		if (kill_default || rule->set != RESVD_SET)
2629			rule = remove_rule(chain, rule, prev);
2630		else {
2631			prev = rule;
2632			rule = rule->next;
2633		}
2634}
2635
2636/**
2637 * Remove all rules with given number, and also do set manipulation.
2638 * Assumes chain != NULL && *chain != NULL.
2639 *
2640 * The argument is an u_int32_t. The low 16 bit are the rule or set number,
2641 * the next 8 bits are the new set, the top 8 bits are the command:
2642 *
2643 *	0	delete rules with given number
2644 *	1	delete rules with given set number
2645 *	2	move rules with given number to new set
2646 *	3	move rules with given set number to new set
2647 *	4	swap sets with given numbers
2648 */
2649static int
2650del_entry(struct ip_fw_chain *chain, u_int32_t arg)
2651{
2652	struct ip_fw *prev = NULL, *rule;
2653	u_int16_t rulenum;	/* rule or old_set */
2654	u_int8_t cmd, new_set;
2655
2656	rulenum = arg & 0xffff;
2657	cmd = (arg >> 24) & 0xff;
2658	new_set = (arg >> 16) & 0xff;
2659
2660	if (cmd > 4)
2661		return EINVAL;
2662	if (new_set > RESVD_SET)
2663		return EINVAL;
2664	if (cmd == 0 || cmd == 2) {
2665		if (rulenum >= IPFW_DEFAULT_RULE)
2666			return EINVAL;
2667	} else {
2668		if (rulenum > RESVD_SET)	/* old_set */
2669			return EINVAL;
2670	}
2671
2672	IPFW_LOCK(chain);
2673	rule = chain->rules;
2674	chain->reap = NULL;
2675	switch (cmd) {
2676	case 0:	/* delete rules with given number */
2677		/*
2678		 * locate first rule to delete
2679		 */
2680		for (; rule->rulenum < rulenum; prev = rule, rule = rule->next)
2681			;
2682		if (rule->rulenum != rulenum) {
2683			IPFW_UNLOCK(chain);
2684			return EINVAL;
2685		}
2686
2687		/*
2688		 * flush pointers outside the loop, then delete all matching
2689		 * rules. prev remains the same throughout the cycle.
2690		 */
2691		flush_rule_ptrs(chain);
2692		while (rule->rulenum == rulenum)
2693			rule = remove_rule(chain, rule, prev);
2694		break;
2695
2696	case 1:	/* delete all rules with given set number */
2697		flush_rule_ptrs(chain);
2698		rule = chain->rules;
2699		while (rule->rulenum < IPFW_DEFAULT_RULE)
2700			if (rule->set == rulenum)
2701				rule = remove_rule(chain, rule, prev);
2702			else {
2703				prev = rule;
2704				rule = rule->next;
2705			}
2706		break;
2707
2708	case 2:	/* move rules with given number to new set */
2709		rule = chain->rules;
2710		for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
2711			if (rule->rulenum == rulenum)
2712				rule->set = new_set;
2713		break;
2714
2715	case 3: /* move rules with given set number to new set */
2716		for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
2717			if (rule->set == rulenum)
2718				rule->set = new_set;
2719		break;
2720
2721	case 4: /* swap two sets */
2722		for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
2723			if (rule->set == rulenum)
2724				rule->set = new_set;
2725			else if (rule->set == new_set)
2726				rule->set = rulenum;
2727		break;
2728	}
2729	/*
2730	 * Look for rules to reclaim.  We grab the list before
2731	 * releasing the lock then reclaim them w/o the lock to
2732	 * avoid a LOR with dummynet.
2733	 */
2734	rule = chain->reap;
2735	chain->reap = NULL;
2736	IPFW_UNLOCK(chain);
2737	if (rule)
2738		reap_rules(rule);
2739	return 0;
2740}
2741
2742/*
2743 * Clear counters for a specific rule.
2744 * The enclosing "table" is assumed locked.
2745 */
2746static void
2747clear_counters(struct ip_fw *rule, int log_only)
2748{
2749	ipfw_insn_log *l = (ipfw_insn_log *)ACTION_PTR(rule);
2750
2751	if (log_only == 0) {
2752		rule->bcnt = rule->pcnt = 0;
2753		rule->timestamp = 0;
2754	}
2755	if (l->o.opcode == O_LOG)
2756		l->log_left = l->max_log;
2757}
2758
2759/**
2760 * Reset some or all counters on firewall rules.
2761 * @arg frwl is null to clear all entries, or contains a specific
2762 * rule number.
2763 * @arg log_only is 1 if we only want to reset logs, zero otherwise.
2764 */
2765static int
2766zero_entry(struct ip_fw_chain *chain, int rulenum, int log_only)
2767{
2768	struct ip_fw *rule;
2769	char *msg;
2770
2771	IPFW_LOCK(chain);
2772	if (rulenum == 0) {
2773		norule_counter = 0;
2774		for (rule = chain->rules; rule; rule = rule->next)
2775			clear_counters(rule, log_only);
2776		msg = log_only ? "ipfw: All logging counts reset.\n" :
2777				"ipfw: Accounting cleared.\n";
2778	} else {
2779		int cleared = 0;
2780		/*
2781		 * We can have multiple rules with the same number, so we
2782		 * need to clear them all.
2783		 */
2784		for (rule = chain->rules; rule; rule = rule->next)
2785			if (rule->rulenum == rulenum) {
2786				while (rule && rule->rulenum == rulenum) {
2787					clear_counters(rule, log_only);
2788					rule = rule->next;
2789				}
2790				cleared = 1;
2791				break;
2792			}
2793		if (!cleared) {	/* we did not find any matching rules */
2794			IPFW_UNLOCK(chain);
2795			return (EINVAL);
2796		}
2797		msg = log_only ? "ipfw: Entry %d logging count reset.\n" :
2798				"ipfw: Entry %d cleared.\n";
2799	}
2800	IPFW_UNLOCK(chain);
2801
2802	if (fw_verbose)
2803		log(LOG_SECURITY | LOG_NOTICE, msg, rulenum);
2804	return (0);
2805}
2806
2807/*
2808 * Check validity of the structure before insert.
2809 * Fortunately rules are simple, so this mostly need to check rule sizes.
2810 */
2811static int
2812check_ipfw_struct(struct ip_fw *rule, int size)
2813{
2814	int l, cmdlen = 0;
2815	int have_action=0;
2816	ipfw_insn *cmd;
2817
2818	if (size < sizeof(*rule)) {
2819		printf("ipfw: rule too short\n");
2820		return (EINVAL);
2821	}
2822	/* first, check for valid size */
2823	l = RULESIZE(rule);
2824	if (l != size) {
2825		printf("ipfw: size mismatch (have %d want %d)\n", size, l);
2826		return (EINVAL);
2827	}
2828	/*
2829	 * Now go for the individual checks. Very simple ones, basically only
2830	 * instruction sizes.
2831	 */
2832	for (l = rule->cmd_len, cmd = rule->cmd ;
2833			l > 0 ; l -= cmdlen, cmd += cmdlen) {
2834		cmdlen = F_LEN(cmd);
2835		if (cmdlen > l) {
2836			printf("ipfw: opcode %d size truncated\n",
2837			    cmd->opcode);
2838			return EINVAL;
2839		}
2840		DEB(printf("ipfw: opcode %d\n", cmd->opcode);)
2841		switch (cmd->opcode) {
2842		case O_PROBE_STATE:
2843		case O_KEEP_STATE:
2844		case O_PROTO:
2845		case O_IP_SRC_ME:
2846		case O_IP_DST_ME:
2847		case O_LAYER2:
2848		case O_IN:
2849		case O_FRAG:
2850		case O_IPOPT:
2851		case O_IPTOS:
2852		case O_IPPRECEDENCE:
2853		case O_IPVER:
2854		case O_TCPWIN:
2855		case O_TCPFLAGS:
2856		case O_TCPOPTS:
2857		case O_ESTAB:
2858		case O_VERREVPATH:
2859		case O_VERSRCREACH:
2860		case O_ANTISPOOF:
2861		case O_IPSEC:
2862			if (cmdlen != F_INSN_SIZE(ipfw_insn))
2863				goto bad_size;
2864			break;
2865
2866		case O_UID:
2867		case O_GID:
2868		case O_JAIL:
2869		case O_IP_SRC:
2870		case O_IP_DST:
2871		case O_TCPSEQ:
2872		case O_TCPACK:
2873		case O_PROB:
2874		case O_ICMPTYPE:
2875			if (cmdlen != F_INSN_SIZE(ipfw_insn_u32))
2876				goto bad_size;
2877			break;
2878
2879		case O_LIMIT:
2880			if (cmdlen != F_INSN_SIZE(ipfw_insn_limit))
2881				goto bad_size;
2882			break;
2883
2884		case O_LOG:
2885			if (cmdlen != F_INSN_SIZE(ipfw_insn_log))
2886				goto bad_size;
2887
2888			((ipfw_insn_log *)cmd)->log_left =
2889			    ((ipfw_insn_log *)cmd)->max_log;
2890
2891			break;
2892
2893		case O_IP_SRC_MASK:
2894		case O_IP_DST_MASK:
2895			/* only odd command lengths */
2896			if ( !(cmdlen & 1) || cmdlen > 31)
2897				goto bad_size;
2898			break;
2899
2900		case O_IP_SRC_SET:
2901		case O_IP_DST_SET:
2902			if (cmd->arg1 == 0 || cmd->arg1 > 256) {
2903				printf("ipfw: invalid set size %d\n",
2904					cmd->arg1);
2905				return EINVAL;
2906			}
2907			if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
2908			    (cmd->arg1+31)/32 )
2909				goto bad_size;
2910			break;
2911
2912		case O_IP_SRC_LOOKUP:
2913		case O_IP_DST_LOOKUP:
2914			if (cmd->arg1 >= IPFW_TABLES_MAX) {
2915				printf("ipfw: invalid table number %d\n",
2916				    cmd->arg1);
2917				return (EINVAL);
2918			}
2919			if (cmdlen != F_INSN_SIZE(ipfw_insn) &&
2920			    cmdlen != F_INSN_SIZE(ipfw_insn_u32))
2921				goto bad_size;
2922			break;
2923
2924		case O_MACADDR2:
2925			if (cmdlen != F_INSN_SIZE(ipfw_insn_mac))
2926				goto bad_size;
2927			break;
2928
2929		case O_NOP:
2930		case O_IPID:
2931		case O_IPTTL:
2932		case O_IPLEN:
2933			if (cmdlen < 1 || cmdlen > 31)
2934				goto bad_size;
2935			break;
2936
2937		case O_MAC_TYPE:
2938		case O_IP_SRCPORT:
2939		case O_IP_DSTPORT: /* XXX artificial limit, 30 port pairs */
2940			if (cmdlen < 2 || cmdlen > 31)
2941				goto bad_size;
2942			break;
2943
2944		case O_RECV:
2945		case O_XMIT:
2946		case O_VIA:
2947			if (cmdlen != F_INSN_SIZE(ipfw_insn_if))
2948				goto bad_size;
2949			break;
2950
2951		case O_PIPE:
2952		case O_QUEUE:
2953			if (cmdlen != F_INSN_SIZE(ipfw_insn_pipe))
2954				goto bad_size;
2955			goto check_action;
2956
2957		case O_FORWARD_IP:
2958			if (cmdlen != F_INSN_SIZE(ipfw_insn_sa))
2959				goto bad_size;
2960			goto check_action;
2961
2962		case O_FORWARD_MAC: /* XXX not implemented yet */
2963		case O_CHECK_STATE:
2964		case O_COUNT:
2965		case O_ACCEPT:
2966		case O_DENY:
2967		case O_REJECT:
2968		case O_SKIPTO:
2969		case O_DIVERT:
2970		case O_TEE:
2971			if (cmdlen != F_INSN_SIZE(ipfw_insn))
2972				goto bad_size;
2973check_action:
2974			if (have_action) {
2975				printf("ipfw: opcode %d, multiple actions"
2976					" not allowed\n",
2977					cmd->opcode);
2978				return EINVAL;
2979			}
2980			have_action = 1;
2981			if (l != cmdlen) {
2982				printf("ipfw: opcode %d, action must be"
2983					" last opcode\n",
2984					cmd->opcode);
2985				return EINVAL;
2986			}
2987			break;
2988		default:
2989			printf("ipfw: opcode %d, unknown opcode\n",
2990				cmd->opcode);
2991			return EINVAL;
2992		}
2993	}
2994	if (have_action == 0) {
2995		printf("ipfw: missing action\n");
2996		return EINVAL;
2997	}
2998	return 0;
2999
3000bad_size:
3001	printf("ipfw: opcode %d size %d wrong\n",
3002		cmd->opcode, cmdlen);
3003	return EINVAL;
3004}
3005
3006/*
3007 * Copy the static and dynamic rules to the supplied buffer
3008 * and return the amount of space actually used.
3009 */
3010static size_t
3011ipfw_getrules(struct ip_fw_chain *chain, void *buf, size_t space)
3012{
3013	char *bp = buf;
3014	char *ep = bp + space;
3015	struct ip_fw *rule;
3016	int i;
3017
3018	/* XXX this can take a long time and locking will block packet flow */
3019	IPFW_LOCK(chain);
3020	for (rule = chain->rules; rule ; rule = rule->next) {
3021		/*
3022		 * Verify the entry fits in the buffer in case the
3023		 * rules changed between calculating buffer space and
3024		 * now.  This would be better done using a generation
3025		 * number but should suffice for now.
3026		 */
3027		i = RULESIZE(rule);
3028		if (bp + i <= ep) {
3029			bcopy(rule, bp, i);
3030			bcopy(&set_disable, &(((struct ip_fw *)bp)->next_rule),
3031			    sizeof(set_disable));
3032			bp += i;
3033		}
3034	}
3035	IPFW_UNLOCK(chain);
3036	if (ipfw_dyn_v) {
3037		ipfw_dyn_rule *p, *last = NULL;
3038
3039		IPFW_DYN_LOCK();
3040		for (i = 0 ; i < curr_dyn_buckets; i++)
3041			for (p = ipfw_dyn_v[i] ; p != NULL; p = p->next) {
3042				if (bp + sizeof *p <= ep) {
3043					ipfw_dyn_rule *dst =
3044						(ipfw_dyn_rule *)bp;
3045					bcopy(p, dst, sizeof *p);
3046					bcopy(&(p->rule->rulenum), &(dst->rule),
3047					    sizeof(p->rule->rulenum));
3048					/*
3049					 * store a non-null value in "next".
3050					 * The userland code will interpret a
3051					 * NULL here as a marker
3052					 * for the last dynamic rule.
3053					 */
3054					bcopy(&dst, &dst->next, sizeof(dst));
3055					last = dst;
3056					dst->expire =
3057					    TIME_LEQ(dst->expire, time_second) ?
3058						0 : dst->expire - time_second ;
3059					bp += sizeof(ipfw_dyn_rule);
3060				}
3061			}
3062		IPFW_DYN_UNLOCK();
3063		if (last != NULL) /* mark last dynamic rule */
3064			bzero(&last->next, sizeof(last));
3065	}
3066	return (bp - (char *)buf);
3067}
3068
3069
3070/**
3071 * {set|get}sockopt parser.
3072 */
3073static int
3074ipfw_ctl(struct sockopt *sopt)
3075{
3076#define	RULE_MAXSIZE	(256*sizeof(u_int32_t))
3077	int error, rule_num;
3078	size_t size;
3079	struct ip_fw *buf, *rule;
3080	u_int32_t rulenum[2];
3081
3082	error = suser(sopt->sopt_td);
3083	if (error)
3084		return (error);
3085
3086	/*
3087	 * Disallow modifications in really-really secure mode, but still allow
3088	 * the logging counters to be reset.
3089	 */
3090	if (sopt->sopt_name == IP_FW_ADD ||
3091	    (sopt->sopt_dir == SOPT_SET && sopt->sopt_name != IP_FW_RESETLOG)) {
3092#if __FreeBSD_version >= 500034
3093		error = securelevel_ge(sopt->sopt_td->td_ucred, 3);
3094		if (error)
3095			return (error);
3096#else /* FreeBSD 4.x */
3097		if (securelevel >= 3)
3098			return (EPERM);
3099#endif
3100	}
3101
3102	error = 0;
3103
3104	switch (sopt->sopt_name) {
3105	case IP_FW_GET:
3106		/*
3107		 * pass up a copy of the current rules. Static rules
3108		 * come first (the last of which has number IPFW_DEFAULT_RULE),
3109		 * followed by a possibly empty list of dynamic rule.
3110		 * The last dynamic rule has NULL in the "next" field.
3111		 *
3112		 * Note that the calculated size is used to bound the
3113		 * amount of data returned to the user.  The rule set may
3114		 * change between calculating the size and returning the
3115		 * data in which case we'll just return what fits.
3116		 */
3117		size = static_len;	/* size of static rules */
3118		if (ipfw_dyn_v)		/* add size of dyn.rules */
3119			size += (dyn_count * sizeof(ipfw_dyn_rule));
3120
3121		/*
3122		 * XXX todo: if the user passes a short length just to know
3123		 * how much room is needed, do not bother filling up the
3124		 * buffer, just jump to the sooptcopyout.
3125		 */
3126		buf = malloc(size, M_TEMP, M_WAITOK);
3127		error = sooptcopyout(sopt, buf,
3128				ipfw_getrules(&layer3_chain, buf, size));
3129		free(buf, M_TEMP);
3130		break;
3131
3132	case IP_FW_FLUSH:
3133		/*
3134		 * Normally we cannot release the lock on each iteration.
3135		 * We could do it here only because we start from the head all
3136		 * the times so there is no risk of missing some entries.
3137		 * On the other hand, the risk is that we end up with
3138		 * a very inconsistent ruleset, so better keep the lock
3139		 * around the whole cycle.
3140		 *
3141		 * XXX this code can be improved by resetting the head of
3142		 * the list to point to the default rule, and then freeing
3143		 * the old list without the need for a lock.
3144		 */
3145
3146		IPFW_LOCK(&layer3_chain);
3147		layer3_chain.reap = NULL;
3148		free_chain(&layer3_chain, 0 /* keep default rule */);
3149		rule = layer3_chain.reap, layer3_chain.reap = NULL;
3150		IPFW_UNLOCK(&layer3_chain);
3151		if (layer3_chain.reap != NULL)
3152			reap_rules(rule);
3153		break;
3154
3155	case IP_FW_ADD:
3156		rule = malloc(RULE_MAXSIZE, M_TEMP, M_WAITOK);
3157		error = sooptcopyin(sopt, rule, RULE_MAXSIZE,
3158			sizeof(struct ip_fw) );
3159		if (error == 0)
3160			error = check_ipfw_struct(rule, sopt->sopt_valsize);
3161		if (error == 0) {
3162			error = add_rule(&layer3_chain, rule);
3163			size = RULESIZE(rule);
3164			if (!error && sopt->sopt_dir == SOPT_GET)
3165				error = sooptcopyout(sopt, rule, size);
3166		}
3167		free(rule, M_TEMP);
3168		break;
3169
3170	case IP_FW_DEL:
3171		/*
3172		 * IP_FW_DEL is used for deleting single rules or sets,
3173		 * and (ab)used to atomically manipulate sets. Argument size
3174		 * is used to distinguish between the two:
3175		 *    sizeof(u_int32_t)
3176		 *	delete single rule or set of rules,
3177		 *	or reassign rules (or sets) to a different set.
3178		 *    2*sizeof(u_int32_t)
3179		 *	atomic disable/enable sets.
3180		 *	first u_int32_t contains sets to be disabled,
3181		 *	second u_int32_t contains sets to be enabled.
3182		 */
3183		error = sooptcopyin(sopt, rulenum,
3184			2*sizeof(u_int32_t), sizeof(u_int32_t));
3185		if (error)
3186			break;
3187		size = sopt->sopt_valsize;
3188		if (size == sizeof(u_int32_t))	/* delete or reassign */
3189			error = del_entry(&layer3_chain, rulenum[0]);
3190		else if (size == 2*sizeof(u_int32_t)) /* set enable/disable */
3191			set_disable =
3192			    (set_disable | rulenum[0]) & ~rulenum[1] &
3193			    ~(1<<RESVD_SET); /* set RESVD_SET always enabled */
3194		else
3195			error = EINVAL;
3196		break;
3197
3198	case IP_FW_ZERO:
3199	case IP_FW_RESETLOG: /* argument is an int, the rule number */
3200		rule_num = 0;
3201		if (sopt->sopt_val != 0) {
3202		    error = sooptcopyin(sopt, &rule_num,
3203			    sizeof(int), sizeof(int));
3204		    if (error)
3205			break;
3206		}
3207		error = zero_entry(&layer3_chain, rule_num,
3208			sopt->sopt_name == IP_FW_RESETLOG);
3209		break;
3210
3211	case IP_FW_TABLE_ADD:
3212		{
3213			ipfw_table_entry ent;
3214
3215			error = sooptcopyin(sopt, &ent,
3216			    sizeof(ent), sizeof(ent));
3217			if (error)
3218				break;
3219			error = add_table_entry(ent.tbl, ent.addr,
3220			    ent.masklen, ent.value);
3221		}
3222		break;
3223
3224	case IP_FW_TABLE_DEL:
3225		{
3226			ipfw_table_entry ent;
3227
3228			error = sooptcopyin(sopt, &ent,
3229			    sizeof(ent), sizeof(ent));
3230			if (error)
3231				break;
3232			error = del_table_entry(ent.tbl, ent.addr, ent.masklen);
3233		}
3234		break;
3235
3236	case IP_FW_TABLE_FLUSH:
3237		{
3238			u_int16_t tbl;
3239
3240			error = sooptcopyin(sopt, &tbl,
3241			    sizeof(tbl), sizeof(tbl));
3242			if (error)
3243				break;
3244			error = flush_table(tbl);
3245		}
3246		break;
3247
3248	case IP_FW_TABLE_GETSIZE:
3249		{
3250			u_int32_t tbl, cnt;
3251
3252			if ((error = sooptcopyin(sopt, &tbl, sizeof(tbl),
3253			    sizeof(tbl))))
3254				break;
3255			if ((error = count_table(tbl, &cnt)))
3256				break;
3257			error = sooptcopyout(sopt, &cnt, sizeof(cnt));
3258		}
3259		break;
3260
3261	case IP_FW_TABLE_LIST:
3262		{
3263			ipfw_table *tbl;
3264
3265			if (sopt->sopt_valsize < sizeof(*tbl)) {
3266				error = EINVAL;
3267				break;
3268			}
3269			size = sopt->sopt_valsize;
3270			tbl = malloc(size, M_TEMP, M_WAITOK);
3271			if (tbl == NULL) {
3272				error = ENOMEM;
3273				break;
3274			}
3275			error = sooptcopyin(sopt, tbl, size, sizeof(*tbl));
3276			if (error) {
3277				free(tbl, M_TEMP);
3278				break;
3279			}
3280			tbl->size = (size - sizeof(*tbl)) /
3281			    sizeof(ipfw_table_entry);
3282			error = dump_table(tbl);
3283			if (error) {
3284				free(tbl, M_TEMP);
3285				break;
3286			}
3287			error = sooptcopyout(sopt, tbl, size);
3288			free(tbl, M_TEMP);
3289		}
3290		break;
3291
3292	default:
3293		printf("ipfw: ipfw_ctl invalid option %d\n", sopt->sopt_name);
3294		error = EINVAL;
3295	}
3296
3297	return (error);
3298#undef RULE_MAXSIZE
3299}
3300
3301/**
3302 * dummynet needs a reference to the default rule, because rules can be
3303 * deleted while packets hold a reference to them. When this happens,
3304 * dummynet changes the reference to the default rule (it could well be a
3305 * NULL pointer, but this way we do not need to check for the special
3306 * case, plus here he have info on the default behaviour).
3307 */
3308struct ip_fw *ip_fw_default_rule;
3309
3310/*
3311 * This procedure is only used to handle keepalives. It is invoked
3312 * every dyn_keepalive_period
3313 */
3314static void
3315ipfw_tick(void * __unused unused)
3316{
3317	int i;
3318	ipfw_dyn_rule *q;
3319
3320	if (dyn_keepalive == 0 || ipfw_dyn_v == NULL || dyn_count == 0)
3321		goto done;
3322
3323	IPFW_DYN_LOCK();
3324	for (i = 0 ; i < curr_dyn_buckets ; i++) {
3325		for (q = ipfw_dyn_v[i] ; q ; q = q->next ) {
3326			if (q->dyn_type == O_LIMIT_PARENT)
3327				continue;
3328			if (q->id.proto != IPPROTO_TCP)
3329				continue;
3330			if ( (q->state & BOTH_SYN) != BOTH_SYN)
3331				continue;
3332			if (TIME_LEQ( time_second+dyn_keepalive_interval,
3333			    q->expire))
3334				continue;	/* too early */
3335			if (TIME_LEQ(q->expire, time_second))
3336				continue;	/* too late, rule expired */
3337
3338			send_pkt(&(q->id), q->ack_rev - 1, q->ack_fwd, TH_SYN);
3339			send_pkt(&(q->id), q->ack_fwd - 1, q->ack_rev, 0);
3340		}
3341	}
3342	IPFW_DYN_UNLOCK();
3343done:
3344	callout_reset(&ipfw_timeout, dyn_keepalive_period*hz, ipfw_tick, NULL);
3345}
3346
3347int
3348ipfw_init(void)
3349{
3350	struct ip_fw default_rule;
3351	int error;
3352
3353	layer3_chain.rules = NULL;
3354	IPFW_LOCK_INIT(&layer3_chain);
3355	IPFW_DYN_LOCK_INIT();
3356	callout_init(&ipfw_timeout, debug_mpsafenet ? CALLOUT_MPSAFE : 0);
3357
3358	bzero(&default_rule, sizeof default_rule);
3359
3360	default_rule.act_ofs = 0;
3361	default_rule.rulenum = IPFW_DEFAULT_RULE;
3362	default_rule.cmd_len = 1;
3363	default_rule.set = RESVD_SET;
3364
3365	default_rule.cmd[0].len = 1;
3366	default_rule.cmd[0].opcode =
3367#ifdef IPFIREWALL_DEFAULT_TO_ACCEPT
3368				1 ? O_ACCEPT :
3369#endif
3370				O_DENY;
3371
3372	error = add_rule(&layer3_chain, &default_rule);
3373	if (error != 0) {
3374		printf("ipfw2: error %u initializing default rule "
3375			"(support disabled)\n", error);
3376		IPFW_DYN_LOCK_DESTROY();
3377		IPFW_LOCK_DESTROY(&layer3_chain);
3378		return (error);
3379	}
3380
3381	ip_fw_default_rule = layer3_chain.rules;
3382	printf("ipfw2 initialized, divert %s, "
3383		"rule-based forwarding "
3384#ifdef IPFIREWALL_FORWARD
3385		"enabled, "
3386#else
3387		"disabled, "
3388#endif
3389		"default to %s, logging ",
3390#ifdef IPDIVERT
3391		"enabled",
3392#else
3393		"disabled",
3394#endif
3395		default_rule.cmd[0].opcode == O_ACCEPT ? "accept" : "deny");
3396
3397#ifdef IPFIREWALL_VERBOSE
3398	fw_verbose = 1;
3399#endif
3400#ifdef IPFIREWALL_VERBOSE_LIMIT
3401	verbose_limit = IPFIREWALL_VERBOSE_LIMIT;
3402#endif
3403	if (fw_verbose == 0)
3404		printf("disabled\n");
3405	else if (verbose_limit == 0)
3406		printf("unlimited\n");
3407	else
3408		printf("limited to %d packets/entry by default\n",
3409		    verbose_limit);
3410
3411	init_tables();
3412	ip_fw_ctl_ptr = ipfw_ctl;
3413	ip_fw_chk_ptr = ipfw_chk;
3414	callout_reset(&ipfw_timeout, hz, ipfw_tick, NULL);
3415
3416	return (0);
3417}
3418
3419void
3420ipfw_destroy(void)
3421{
3422	struct ip_fw *reap;
3423
3424	ip_fw_chk_ptr = NULL;
3425	ip_fw_ctl_ptr = NULL;
3426	IPFW_LOCK(&layer3_chain);
3427	callout_stop(&ipfw_timeout);
3428	layer3_chain.reap = NULL;
3429	free_chain(&layer3_chain, 1 /* kill default rule */);
3430	reap = layer3_chain.reap, layer3_chain.reap = NULL;
3431	IPFW_UNLOCK(&layer3_chain);
3432	if (reap != NULL)
3433		reap_rules(reap);
3434	flush_tables();
3435	IPFW_DYN_LOCK_DESTROY();
3436	IPFW_LOCK_DESTROY(&layer3_chain);
3437	printf("IP firewall unloaded\n");
3438}
3439
3440#endif /* IPFW2 */
3441