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