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