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