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