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