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