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