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