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