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