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