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