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