xref: /freebsd/sys/netpfil/ipfw/ip_fw2.c (revision 718cf2ccb9956613756ab15d7a0e28f2c8e91cab)
1 /*-
2  * Copyright (c) 2002-2009 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 
26 #include <sys/cdefs.h>
27 __FBSDID("$FreeBSD$");
28 
29 /*
30  * The FreeBSD IP packet firewall, main file
31  */
32 
33 #include "opt_ipfw.h"
34 #include "opt_ipdivert.h"
35 #include "opt_inet.h"
36 #ifndef INET
37 #error "IPFIREWALL requires INET"
38 #endif /* INET */
39 #include "opt_inet6.h"
40 
41 #include <sys/param.h>
42 #include <sys/systm.h>
43 #include <sys/condvar.h>
44 #include <sys/counter.h>
45 #include <sys/eventhandler.h>
46 #include <sys/malloc.h>
47 #include <sys/mbuf.h>
48 #include <sys/kernel.h>
49 #include <sys/lock.h>
50 #include <sys/jail.h>
51 #include <sys/module.h>
52 #include <sys/priv.h>
53 #include <sys/proc.h>
54 #include <sys/rwlock.h>
55 #include <sys/rmlock.h>
56 #include <sys/socket.h>
57 #include <sys/socketvar.h>
58 #include <sys/sysctl.h>
59 #include <sys/syslog.h>
60 #include <sys/ucred.h>
61 #include <net/ethernet.h> /* for ETHERTYPE_IP */
62 #include <net/if.h>
63 #include <net/if_var.h>
64 #include <net/route.h>
65 #include <net/pfil.h>
66 #include <net/vnet.h>
67 
68 #include <netpfil/pf/pf_mtag.h>
69 
70 #include <netinet/in.h>
71 #include <netinet/in_var.h>
72 #include <netinet/in_pcb.h>
73 #include <netinet/ip.h>
74 #include <netinet/ip_var.h>
75 #include <netinet/ip_icmp.h>
76 #include <netinet/ip_fw.h>
77 #include <netinet/ip_carp.h>
78 #include <netinet/pim.h>
79 #include <netinet/tcp_var.h>
80 #include <netinet/udp.h>
81 #include <netinet/udp_var.h>
82 #include <netinet/sctp.h>
83 #include <netinet/sctp_crc32.h>
84 #include <netinet/sctp_header.h>
85 
86 #include <netinet/ip6.h>
87 #include <netinet/icmp6.h>
88 #include <netinet/in_fib.h>
89 #ifdef INET6
90 #include <netinet6/in6_fib.h>
91 #include <netinet6/in6_pcb.h>
92 #include <netinet6/scope6_var.h>
93 #include <netinet6/ip6_var.h>
94 #endif
95 
96 #include <net/if_gre.h> /* for struct grehdr */
97 
98 #include <netpfil/ipfw/ip_fw_private.h>
99 
100 #include <machine/in_cksum.h>	/* XXX for in_cksum */
101 
102 #ifdef MAC
103 #include <security/mac/mac_framework.h>
104 #endif
105 
106 /*
107  * static variables followed by global ones.
108  * All ipfw global variables are here.
109  */
110 
111 static VNET_DEFINE(int, fw_deny_unknown_exthdrs);
112 #define	V_fw_deny_unknown_exthdrs	VNET(fw_deny_unknown_exthdrs)
113 
114 static VNET_DEFINE(int, fw_permit_single_frag6) = 1;
115 #define	V_fw_permit_single_frag6	VNET(fw_permit_single_frag6)
116 
117 #ifdef IPFIREWALL_DEFAULT_TO_ACCEPT
118 static int default_to_accept = 1;
119 #else
120 static int default_to_accept;
121 #endif
122 
123 VNET_DEFINE(int, autoinc_step);
124 VNET_DEFINE(int, fw_one_pass) = 1;
125 
126 VNET_DEFINE(unsigned int, fw_tables_max);
127 VNET_DEFINE(unsigned int, fw_tables_sets) = 0;	/* Don't use set-aware tables */
128 /* Use 128 tables by default */
129 static unsigned int default_fw_tables = IPFW_TABLES_DEFAULT;
130 
131 #ifndef LINEAR_SKIPTO
132 static int jump_fast(struct ip_fw_chain *chain, struct ip_fw *f, int num,
133     int tablearg, int jump_backwards);
134 #define	JUMP(ch, f, num, targ, back)	jump_fast(ch, f, num, targ, back)
135 #else
136 static int jump_linear(struct ip_fw_chain *chain, struct ip_fw *f, int num,
137     int tablearg, int jump_backwards);
138 #define	JUMP(ch, f, num, targ, back)	jump_linear(ch, f, num, targ, back)
139 #endif
140 
141 /*
142  * Each rule belongs to one of 32 different sets (0..31).
143  * The variable set_disable contains one bit per set.
144  * If the bit is set, all rules in the corresponding set
145  * are disabled. Set RESVD_SET(31) is reserved for the default rule
146  * and rules that are not deleted by the flush command,
147  * and CANNOT be disabled.
148  * Rules in set RESVD_SET can only be deleted individually.
149  */
150 VNET_DEFINE(u_int32_t, set_disable);
151 #define	V_set_disable			VNET(set_disable)
152 
153 VNET_DEFINE(int, fw_verbose);
154 /* counter for ipfw_log(NULL...) */
155 VNET_DEFINE(u_int64_t, norule_counter);
156 VNET_DEFINE(int, verbose_limit);
157 
158 /* layer3_chain contains the list of rules for layer 3 */
159 VNET_DEFINE(struct ip_fw_chain, layer3_chain);
160 
161 /* ipfw_vnet_ready controls when we are open for business */
162 VNET_DEFINE(int, ipfw_vnet_ready) = 0;
163 
164 VNET_DEFINE(int, ipfw_nat_ready) = 0;
165 
166 ipfw_nat_t *ipfw_nat_ptr = NULL;
167 struct cfg_nat *(*lookup_nat_ptr)(struct nat_list *, int);
168 ipfw_nat_cfg_t *ipfw_nat_cfg_ptr;
169 ipfw_nat_cfg_t *ipfw_nat_del_ptr;
170 ipfw_nat_cfg_t *ipfw_nat_get_cfg_ptr;
171 ipfw_nat_cfg_t *ipfw_nat_get_log_ptr;
172 
173 #ifdef SYSCTL_NODE
174 uint32_t dummy_def = IPFW_DEFAULT_RULE;
175 static int sysctl_ipfw_table_num(SYSCTL_HANDLER_ARGS);
176 static int sysctl_ipfw_tables_sets(SYSCTL_HANDLER_ARGS);
177 
178 SYSBEGIN(f3)
179 
180 SYSCTL_NODE(_net_inet_ip, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall");
181 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, one_pass,
182     CTLFLAG_VNET | CTLFLAG_RW | CTLFLAG_SECURE3, &VNET_NAME(fw_one_pass), 0,
183     "Only do a single pass through ipfw when using dummynet(4)");
184 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, autoinc_step,
185     CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(autoinc_step), 0,
186     "Rule number auto-increment step");
187 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose,
188     CTLFLAG_VNET | CTLFLAG_RW | CTLFLAG_SECURE3, &VNET_NAME(fw_verbose), 0,
189     "Log matches to ipfw rules");
190 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose_limit,
191     CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(verbose_limit), 0,
192     "Set upper limit of matches of ipfw rules logged");
193 SYSCTL_UINT(_net_inet_ip_fw, OID_AUTO, default_rule, CTLFLAG_RD,
194     &dummy_def, 0,
195     "The default/max possible rule number.");
196 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, tables_max,
197     CTLFLAG_VNET | CTLTYPE_UINT | CTLFLAG_RW, 0, 0, sysctl_ipfw_table_num, "IU",
198     "Maximum number of concurrently used tables");
199 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, tables_sets,
200     CTLFLAG_VNET | CTLTYPE_UINT | CTLFLAG_RW,
201     0, 0, sysctl_ipfw_tables_sets, "IU",
202     "Use per-set namespace for tables");
203 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, default_to_accept, CTLFLAG_RDTUN,
204     &default_to_accept, 0,
205     "Make the default rule accept all packets.");
206 TUNABLE_INT("net.inet.ip.fw.tables_max", (int *)&default_fw_tables);
207 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, static_count,
208     CTLFLAG_VNET | CTLFLAG_RD, &VNET_NAME(layer3_chain.n_rules), 0,
209     "Number of static rules");
210 
211 #ifdef INET6
212 SYSCTL_DECL(_net_inet6_ip6);
213 SYSCTL_NODE(_net_inet6_ip6, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall");
214 SYSCTL_INT(_net_inet6_ip6_fw, OID_AUTO, deny_unknown_exthdrs,
215     CTLFLAG_VNET | CTLFLAG_RW | CTLFLAG_SECURE,
216     &VNET_NAME(fw_deny_unknown_exthdrs), 0,
217     "Deny packets with unknown IPv6 Extension Headers");
218 SYSCTL_INT(_net_inet6_ip6_fw, OID_AUTO, permit_single_frag6,
219     CTLFLAG_VNET | CTLFLAG_RW | CTLFLAG_SECURE,
220     &VNET_NAME(fw_permit_single_frag6), 0,
221     "Permit single packet IPv6 fragments");
222 #endif /* INET6 */
223 
224 SYSEND
225 
226 #endif /* SYSCTL_NODE */
227 
228 
229 /*
230  * Some macros used in the various matching options.
231  * L3HDR maps an ipv4 pointer into a layer3 header pointer of type T
232  * Other macros just cast void * into the appropriate type
233  */
234 #define	L3HDR(T, ip)	((T *)((u_int32_t *)(ip) + (ip)->ip_hl))
235 #define	TCP(p)		((struct tcphdr *)(p))
236 #define	SCTP(p)		((struct sctphdr *)(p))
237 #define	UDP(p)		((struct udphdr *)(p))
238 #define	ICMP(p)		((struct icmphdr *)(p))
239 #define	ICMP6(p)	((struct icmp6_hdr *)(p))
240 
241 static __inline int
242 icmptype_match(struct icmphdr *icmp, ipfw_insn_u32 *cmd)
243 {
244 	int type = icmp->icmp_type;
245 
246 	return (type <= ICMP_MAXTYPE && (cmd->d[0] & (1<<type)) );
247 }
248 
249 #define TT	( (1 << ICMP_ECHO) | (1 << ICMP_ROUTERSOLICIT) | \
250     (1 << ICMP_TSTAMP) | (1 << ICMP_IREQ) | (1 << ICMP_MASKREQ) )
251 
252 static int
253 is_icmp_query(struct icmphdr *icmp)
254 {
255 	int type = icmp->icmp_type;
256 
257 	return (type <= ICMP_MAXTYPE && (TT & (1<<type)) );
258 }
259 #undef TT
260 
261 /*
262  * The following checks use two arrays of 8 or 16 bits to store the
263  * bits that we want set or clear, respectively. They are in the
264  * low and high half of cmd->arg1 or cmd->d[0].
265  *
266  * We scan options and store the bits we find set. We succeed if
267  *
268  *	(want_set & ~bits) == 0 && (want_clear & ~bits) == want_clear
269  *
270  * The code is sometimes optimized not to store additional variables.
271  */
272 
273 static int
274 flags_match(ipfw_insn *cmd, u_int8_t bits)
275 {
276 	u_char want_clear;
277 	bits = ~bits;
278 
279 	if ( ((cmd->arg1 & 0xff) & bits) != 0)
280 		return 0; /* some bits we want set were clear */
281 	want_clear = (cmd->arg1 >> 8) & 0xff;
282 	if ( (want_clear & bits) != want_clear)
283 		return 0; /* some bits we want clear were set */
284 	return 1;
285 }
286 
287 static int
288 ipopts_match(struct ip *ip, ipfw_insn *cmd)
289 {
290 	int optlen, bits = 0;
291 	u_char *cp = (u_char *)(ip + 1);
292 	int x = (ip->ip_hl << 2) - sizeof (struct ip);
293 
294 	for (; x > 0; x -= optlen, cp += optlen) {
295 		int opt = cp[IPOPT_OPTVAL];
296 
297 		if (opt == IPOPT_EOL)
298 			break;
299 		if (opt == IPOPT_NOP)
300 			optlen = 1;
301 		else {
302 			optlen = cp[IPOPT_OLEN];
303 			if (optlen <= 0 || optlen > x)
304 				return 0; /* invalid or truncated */
305 		}
306 		switch (opt) {
307 
308 		default:
309 			break;
310 
311 		case IPOPT_LSRR:
312 			bits |= IP_FW_IPOPT_LSRR;
313 			break;
314 
315 		case IPOPT_SSRR:
316 			bits |= IP_FW_IPOPT_SSRR;
317 			break;
318 
319 		case IPOPT_RR:
320 			bits |= IP_FW_IPOPT_RR;
321 			break;
322 
323 		case IPOPT_TS:
324 			bits |= IP_FW_IPOPT_TS;
325 			break;
326 		}
327 	}
328 	return (flags_match(cmd, bits));
329 }
330 
331 static int
332 tcpopts_match(struct tcphdr *tcp, ipfw_insn *cmd)
333 {
334 	int optlen, bits = 0;
335 	u_char *cp = (u_char *)(tcp + 1);
336 	int x = (tcp->th_off << 2) - sizeof(struct tcphdr);
337 
338 	for (; x > 0; x -= optlen, cp += optlen) {
339 		int opt = cp[0];
340 		if (opt == TCPOPT_EOL)
341 			break;
342 		if (opt == TCPOPT_NOP)
343 			optlen = 1;
344 		else {
345 			optlen = cp[1];
346 			if (optlen <= 0)
347 				break;
348 		}
349 
350 		switch (opt) {
351 
352 		default:
353 			break;
354 
355 		case TCPOPT_MAXSEG:
356 			bits |= IP_FW_TCPOPT_MSS;
357 			break;
358 
359 		case TCPOPT_WINDOW:
360 			bits |= IP_FW_TCPOPT_WINDOW;
361 			break;
362 
363 		case TCPOPT_SACK_PERMITTED:
364 		case TCPOPT_SACK:
365 			bits |= IP_FW_TCPOPT_SACK;
366 			break;
367 
368 		case TCPOPT_TIMESTAMP:
369 			bits |= IP_FW_TCPOPT_TS;
370 			break;
371 
372 		}
373 	}
374 	return (flags_match(cmd, bits));
375 }
376 
377 static int
378 iface_match(struct ifnet *ifp, ipfw_insn_if *cmd, struct ip_fw_chain *chain,
379     uint32_t *tablearg)
380 {
381 
382 	if (ifp == NULL)	/* no iface with this packet, match fails */
383 		return (0);
384 
385 	/* Check by name or by IP address */
386 	if (cmd->name[0] != '\0') { /* match by name */
387 		if (cmd->name[0] == '\1') /* use tablearg to match */
388 			return ipfw_lookup_table(chain, cmd->p.kidx, 0,
389 			    &ifp->if_index, tablearg);
390 		/* Check name */
391 		if (cmd->p.glob) {
392 			if (fnmatch(cmd->name, ifp->if_xname, 0) == 0)
393 				return(1);
394 		} else {
395 			if (strncmp(ifp->if_xname, cmd->name, IFNAMSIZ) == 0)
396 				return(1);
397 		}
398 	} else {
399 #if !defined(USERSPACE) && defined(__FreeBSD__)	/* and OSX too ? */
400 		struct ifaddr *ia;
401 
402 		if_addr_rlock(ifp);
403 		TAILQ_FOREACH(ia, &ifp->if_addrhead, ifa_link) {
404 			if (ia->ifa_addr->sa_family != AF_INET)
405 				continue;
406 			if (cmd->p.ip.s_addr == ((struct sockaddr_in *)
407 			    (ia->ifa_addr))->sin_addr.s_addr) {
408 				if_addr_runlock(ifp);
409 				return(1);	/* match */
410 			}
411 		}
412 		if_addr_runlock(ifp);
413 #endif /* __FreeBSD__ */
414 	}
415 	return(0);	/* no match, fail ... */
416 }
417 
418 /*
419  * The verify_path function checks if a route to the src exists and
420  * if it is reachable via ifp (when provided).
421  *
422  * The 'verrevpath' option checks that the interface that an IP packet
423  * arrives on is the same interface that traffic destined for the
424  * packet's source address would be routed out of.
425  * The 'versrcreach' option just checks that the source address is
426  * reachable via any route (except default) in the routing table.
427  * These two are a measure to block forged packets. This is also
428  * commonly known as "anti-spoofing" or Unicast Reverse Path
429  * Forwarding (Unicast RFP) in Cisco-ese. The name of the knobs
430  * is purposely reminiscent of the Cisco IOS command,
431  *
432  *   ip verify unicast reverse-path
433  *   ip verify unicast source reachable-via any
434  *
435  * which implements the same functionality. But note that the syntax
436  * is misleading, and the check may be performed on all IP packets
437  * whether unicast, multicast, or broadcast.
438  */
439 static int
440 verify_path(struct in_addr src, struct ifnet *ifp, u_int fib)
441 {
442 #if defined(USERSPACE) || !defined(__FreeBSD__)
443 	return 0;
444 #else
445 	struct nhop4_basic nh4;
446 
447 	if (fib4_lookup_nh_basic(fib, src, NHR_IFAIF, 0, &nh4) != 0)
448 		return (0);
449 
450 	/*
451 	 * If ifp is provided, check for equality with rtentry.
452 	 * We should use rt->rt_ifa->ifa_ifp, instead of rt->rt_ifp,
453 	 * in order to pass packets injected back by if_simloop():
454 	 * routing entry (via lo0) for our own address
455 	 * may exist, so we need to handle routing assymetry.
456 	 */
457 	if (ifp != NULL && ifp != nh4.nh_ifp)
458 		return (0);
459 
460 	/* if no ifp provided, check if rtentry is not default route */
461 	if (ifp == NULL && (nh4.nh_flags & NHF_DEFAULT) != 0)
462 		return (0);
463 
464 	/* or if this is a blackhole/reject route */
465 	if (ifp == NULL && (nh4.nh_flags & (NHF_REJECT|NHF_BLACKHOLE)) != 0)
466 		return (0);
467 
468 	/* found valid route */
469 	return 1;
470 #endif /* __FreeBSD__ */
471 }
472 
473 /*
474  * Generate an SCTP packet containing an ABORT chunk. The verification tag
475  * is given by vtag. The T-bit is set in the ABORT chunk if and only if
476  * reflected is not 0.
477  */
478 
479 static struct mbuf *
480 ipfw_send_abort(struct mbuf *replyto, struct ipfw_flow_id *id, u_int32_t vtag,
481     int reflected)
482 {
483 	struct mbuf *m;
484 	struct ip *ip;
485 #ifdef INET6
486 	struct ip6_hdr *ip6;
487 #endif
488 	struct sctphdr *sctp;
489 	struct sctp_chunkhdr *chunk;
490 	u_int16_t hlen, plen, tlen;
491 
492 	MGETHDR(m, M_NOWAIT, MT_DATA);
493 	if (m == NULL)
494 		return (NULL);
495 
496 	M_SETFIB(m, id->fib);
497 #ifdef MAC
498 	if (replyto != NULL)
499 		mac_netinet_firewall_reply(replyto, m);
500 	else
501 		mac_netinet_firewall_send(m);
502 #else
503 	(void)replyto;		/* don't warn about unused arg */
504 #endif
505 
506 	switch (id->addr_type) {
507 	case 4:
508 		hlen = sizeof(struct ip);
509 		break;
510 #ifdef INET6
511 	case 6:
512 		hlen = sizeof(struct ip6_hdr);
513 		break;
514 #endif
515 	default:
516 		/* XXX: log me?!? */
517 		FREE_PKT(m);
518 		return (NULL);
519 	}
520 	plen = sizeof(struct sctphdr) + sizeof(struct sctp_chunkhdr);
521 	tlen = hlen + plen;
522 	m->m_data += max_linkhdr;
523 	m->m_flags |= M_SKIP_FIREWALL;
524 	m->m_pkthdr.len = m->m_len = tlen;
525 	m->m_pkthdr.rcvif = NULL;
526 	bzero(m->m_data, tlen);
527 
528 	switch (id->addr_type) {
529 	case 4:
530 		ip = mtod(m, struct ip *);
531 
532 		ip->ip_v = 4;
533 		ip->ip_hl = sizeof(struct ip) >> 2;
534 		ip->ip_tos = IPTOS_LOWDELAY;
535 		ip->ip_len = htons(tlen);
536 		ip->ip_id = htons(0);
537 		ip->ip_off = htons(0);
538 		ip->ip_ttl = V_ip_defttl;
539 		ip->ip_p = IPPROTO_SCTP;
540 		ip->ip_sum = 0;
541 		ip->ip_src.s_addr = htonl(id->dst_ip);
542 		ip->ip_dst.s_addr = htonl(id->src_ip);
543 
544 		sctp = (struct sctphdr *)(ip + 1);
545 		break;
546 #ifdef INET6
547 	case 6:
548 		ip6 = mtod(m, struct ip6_hdr *);
549 
550 		ip6->ip6_vfc = IPV6_VERSION;
551 		ip6->ip6_plen = htons(plen);
552 		ip6->ip6_nxt = IPPROTO_SCTP;
553 		ip6->ip6_hlim = IPV6_DEFHLIM;
554 		ip6->ip6_src = id->dst_ip6;
555 		ip6->ip6_dst = id->src_ip6;
556 
557 		sctp = (struct sctphdr *)(ip6 + 1);
558 		break;
559 #endif
560 	}
561 
562 	sctp->src_port = htons(id->dst_port);
563 	sctp->dest_port = htons(id->src_port);
564 	sctp->v_tag = htonl(vtag);
565 	sctp->checksum = htonl(0);
566 
567 	chunk = (struct sctp_chunkhdr *)(sctp + 1);
568 	chunk->chunk_type = SCTP_ABORT_ASSOCIATION;
569 	chunk->chunk_flags = 0;
570 	if (reflected != 0) {
571 		chunk->chunk_flags |= SCTP_HAD_NO_TCB;
572 	}
573 	chunk->chunk_length = htons(sizeof(struct sctp_chunkhdr));
574 
575 	sctp->checksum = sctp_calculate_cksum(m, hlen);
576 
577 	return (m);
578 }
579 
580 /*
581  * Generate a TCP packet, containing either a RST or a keepalive.
582  * When flags & TH_RST, we are sending a RST packet, because of a
583  * "reset" action matched the packet.
584  * Otherwise we are sending a keepalive, and flags & TH_
585  * The 'replyto' mbuf is the mbuf being replied to, if any, and is required
586  * so that MAC can label the reply appropriately.
587  */
588 struct mbuf *
589 ipfw_send_pkt(struct mbuf *replyto, struct ipfw_flow_id *id, u_int32_t seq,
590     u_int32_t ack, int flags)
591 {
592 	struct mbuf *m = NULL;		/* stupid compiler */
593 	struct ip *h = NULL;		/* stupid compiler */
594 #ifdef INET6
595 	struct ip6_hdr *h6 = NULL;
596 #endif
597 	struct tcphdr *th = NULL;
598 	int len, dir;
599 
600 	MGETHDR(m, M_NOWAIT, MT_DATA);
601 	if (m == NULL)
602 		return (NULL);
603 
604 	M_SETFIB(m, id->fib);
605 #ifdef MAC
606 	if (replyto != NULL)
607 		mac_netinet_firewall_reply(replyto, m);
608 	else
609 		mac_netinet_firewall_send(m);
610 #else
611 	(void)replyto;		/* don't warn about unused arg */
612 #endif
613 
614 	switch (id->addr_type) {
615 	case 4:
616 		len = sizeof(struct ip) + sizeof(struct tcphdr);
617 		break;
618 #ifdef INET6
619 	case 6:
620 		len = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
621 		break;
622 #endif
623 	default:
624 		/* XXX: log me?!? */
625 		FREE_PKT(m);
626 		return (NULL);
627 	}
628 	dir = ((flags & (TH_SYN | TH_RST)) == TH_SYN);
629 
630 	m->m_data += max_linkhdr;
631 	m->m_flags |= M_SKIP_FIREWALL;
632 	m->m_pkthdr.len = m->m_len = len;
633 	m->m_pkthdr.rcvif = NULL;
634 	bzero(m->m_data, len);
635 
636 	switch (id->addr_type) {
637 	case 4:
638 		h = mtod(m, struct ip *);
639 
640 		/* prepare for checksum */
641 		h->ip_p = IPPROTO_TCP;
642 		h->ip_len = htons(sizeof(struct tcphdr));
643 		if (dir) {
644 			h->ip_src.s_addr = htonl(id->src_ip);
645 			h->ip_dst.s_addr = htonl(id->dst_ip);
646 		} else {
647 			h->ip_src.s_addr = htonl(id->dst_ip);
648 			h->ip_dst.s_addr = htonl(id->src_ip);
649 		}
650 
651 		th = (struct tcphdr *)(h + 1);
652 		break;
653 #ifdef INET6
654 	case 6:
655 		h6 = mtod(m, struct ip6_hdr *);
656 
657 		/* prepare for checksum */
658 		h6->ip6_nxt = IPPROTO_TCP;
659 		h6->ip6_plen = htons(sizeof(struct tcphdr));
660 		if (dir) {
661 			h6->ip6_src = id->src_ip6;
662 			h6->ip6_dst = id->dst_ip6;
663 		} else {
664 			h6->ip6_src = id->dst_ip6;
665 			h6->ip6_dst = id->src_ip6;
666 		}
667 
668 		th = (struct tcphdr *)(h6 + 1);
669 		break;
670 #endif
671 	}
672 
673 	if (dir) {
674 		th->th_sport = htons(id->src_port);
675 		th->th_dport = htons(id->dst_port);
676 	} else {
677 		th->th_sport = htons(id->dst_port);
678 		th->th_dport = htons(id->src_port);
679 	}
680 	th->th_off = sizeof(struct tcphdr) >> 2;
681 
682 	if (flags & TH_RST) {
683 		if (flags & TH_ACK) {
684 			th->th_seq = htonl(ack);
685 			th->th_flags = TH_RST;
686 		} else {
687 			if (flags & TH_SYN)
688 				seq++;
689 			th->th_ack = htonl(seq);
690 			th->th_flags = TH_RST | TH_ACK;
691 		}
692 	} else {
693 		/*
694 		 * Keepalive - use caller provided sequence numbers
695 		 */
696 		th->th_seq = htonl(seq);
697 		th->th_ack = htonl(ack);
698 		th->th_flags = TH_ACK;
699 	}
700 
701 	switch (id->addr_type) {
702 	case 4:
703 		th->th_sum = in_cksum(m, len);
704 
705 		/* finish the ip header */
706 		h->ip_v = 4;
707 		h->ip_hl = sizeof(*h) >> 2;
708 		h->ip_tos = IPTOS_LOWDELAY;
709 		h->ip_off = htons(0);
710 		h->ip_len = htons(len);
711 		h->ip_ttl = V_ip_defttl;
712 		h->ip_sum = 0;
713 		break;
714 #ifdef INET6
715 	case 6:
716 		th->th_sum = in6_cksum(m, IPPROTO_TCP, sizeof(*h6),
717 		    sizeof(struct tcphdr));
718 
719 		/* finish the ip6 header */
720 		h6->ip6_vfc |= IPV6_VERSION;
721 		h6->ip6_hlim = IPV6_DEFHLIM;
722 		break;
723 #endif
724 	}
725 
726 	return (m);
727 }
728 
729 #ifdef INET6
730 /*
731  * ipv6 specific rules here...
732  */
733 static __inline int
734 icmp6type_match (int type, ipfw_insn_u32 *cmd)
735 {
736 	return (type <= ICMP6_MAXTYPE && (cmd->d[type/32] & (1<<(type%32)) ) );
737 }
738 
739 static int
740 flow6id_match( int curr_flow, ipfw_insn_u32 *cmd )
741 {
742 	int i;
743 	for (i=0; i <= cmd->o.arg1; ++i )
744 		if (curr_flow == cmd->d[i] )
745 			return 1;
746 	return 0;
747 }
748 
749 /* support for IP6_*_ME opcodes */
750 static const struct in6_addr lla_mask = {{{
751 	0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff,
752 	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff
753 }}};
754 
755 static int
756 ipfw_localip6(struct in6_addr *in6)
757 {
758 	struct rm_priotracker in6_ifa_tracker;
759 	struct in6_ifaddr *ia;
760 
761 	if (IN6_IS_ADDR_MULTICAST(in6))
762 		return (0);
763 
764 	if (!IN6_IS_ADDR_LINKLOCAL(in6))
765 		return (in6_localip(in6));
766 
767 	IN6_IFADDR_RLOCK(&in6_ifa_tracker);
768 	TAILQ_FOREACH(ia, &V_in6_ifaddrhead, ia_link) {
769 		if (!IN6_IS_ADDR_LINKLOCAL(&ia->ia_addr.sin6_addr))
770 			continue;
771 		if (IN6_ARE_MASKED_ADDR_EQUAL(&ia->ia_addr.sin6_addr,
772 		    in6, &lla_mask)) {
773 			IN6_IFADDR_RUNLOCK(&in6_ifa_tracker);
774 			return (1);
775 		}
776 	}
777 	IN6_IFADDR_RUNLOCK(&in6_ifa_tracker);
778 	return (0);
779 }
780 
781 static int
782 verify_path6(struct in6_addr *src, struct ifnet *ifp, u_int fib)
783 {
784 	struct nhop6_basic nh6;
785 
786 	if (IN6_IS_SCOPE_LINKLOCAL(src))
787 		return (1);
788 
789 	if (fib6_lookup_nh_basic(fib, src, 0, NHR_IFAIF, 0, &nh6) != 0)
790 		return (0);
791 
792 	/* If ifp is provided, check for equality with route table. */
793 	if (ifp != NULL && ifp != nh6.nh_ifp)
794 		return (0);
795 
796 	/* if no ifp provided, check if rtentry is not default route */
797 	if (ifp == NULL && (nh6.nh_flags & NHF_DEFAULT) != 0)
798 		return (0);
799 
800 	/* or if this is a blackhole/reject route */
801 	if (ifp == NULL && (nh6.nh_flags & (NHF_REJECT|NHF_BLACKHOLE)) != 0)
802 		return (0);
803 
804 	/* found valid route */
805 	return 1;
806 }
807 
808 static int
809 is_icmp6_query(int icmp6_type)
810 {
811 	if ((icmp6_type <= ICMP6_MAXTYPE) &&
812 	    (icmp6_type == ICMP6_ECHO_REQUEST ||
813 	    icmp6_type == ICMP6_MEMBERSHIP_QUERY ||
814 	    icmp6_type == ICMP6_WRUREQUEST ||
815 	    icmp6_type == ICMP6_FQDN_QUERY ||
816 	    icmp6_type == ICMP6_NI_QUERY))
817 		return (1);
818 
819 	return (0);
820 }
821 
822 static void
823 send_reject6(struct ip_fw_args *args, int code, u_int hlen, struct ip6_hdr *ip6)
824 {
825 	struct mbuf *m;
826 
827 	m = args->m;
828 	if (code == ICMP6_UNREACH_RST && args->f_id.proto == IPPROTO_TCP) {
829 		struct tcphdr *tcp;
830 		tcp = (struct tcphdr *)((char *)ip6 + hlen);
831 
832 		if ((tcp->th_flags & TH_RST) == 0) {
833 			struct mbuf *m0;
834 			m0 = ipfw_send_pkt(args->m, &(args->f_id),
835 			    ntohl(tcp->th_seq), ntohl(tcp->th_ack),
836 			    tcp->th_flags | TH_RST);
837 			if (m0 != NULL)
838 				ip6_output(m0, NULL, NULL, 0, NULL, NULL,
839 				    NULL);
840 		}
841 		FREE_PKT(m);
842 	} else if (code == ICMP6_UNREACH_ABORT &&
843 	    args->f_id.proto == IPPROTO_SCTP) {
844 		struct mbuf *m0;
845 		struct sctphdr *sctp;
846 		u_int32_t v_tag;
847 		int reflected;
848 
849 		sctp = (struct sctphdr *)((char *)ip6 + hlen);
850 		reflected = 1;
851 		v_tag = ntohl(sctp->v_tag);
852 		/* Investigate the first chunk header if available */
853 		if (m->m_len >= hlen + sizeof(struct sctphdr) +
854 		    sizeof(struct sctp_chunkhdr)) {
855 			struct sctp_chunkhdr *chunk;
856 
857 			chunk = (struct sctp_chunkhdr *)(sctp + 1);
858 			switch (chunk->chunk_type) {
859 			case SCTP_INITIATION:
860 				/*
861 				 * Packets containing an INIT chunk MUST have
862 				 * a zero v-tag.
863 				 */
864 				if (v_tag != 0) {
865 					v_tag = 0;
866 					break;
867 				}
868 				/* INIT chunk MUST NOT be bundled */
869 				if (m->m_pkthdr.len >
870 				    hlen + sizeof(struct sctphdr) +
871 				    ntohs(chunk->chunk_length) + 3) {
872 					break;
873 				}
874 				/* Use the initiate tag if available */
875 				if ((m->m_len >= hlen + sizeof(struct sctphdr) +
876 				    sizeof(struct sctp_chunkhdr) +
877 				    offsetof(struct sctp_init, a_rwnd))) {
878 					struct sctp_init *init;
879 
880 					init = (struct sctp_init *)(chunk + 1);
881 					v_tag = ntohl(init->initiate_tag);
882 					reflected = 0;
883 				}
884 				break;
885 			case SCTP_ABORT_ASSOCIATION:
886 				/*
887 				 * If the packet contains an ABORT chunk, don't
888 				 * reply.
889 				 * XXX: We should search through all chunks,
890 				 *      but don't do to avoid attacks.
891 				 */
892 				v_tag = 0;
893 				break;
894 			}
895 		}
896 		if (v_tag == 0) {
897 			m0 = NULL;
898 		} else {
899 			m0 = ipfw_send_abort(args->m, &(args->f_id), v_tag,
900 			    reflected);
901 		}
902 		if (m0 != NULL)
903 			ip6_output(m0, NULL, NULL, 0, NULL, NULL, NULL);
904 		FREE_PKT(m);
905 	} else if (code != ICMP6_UNREACH_RST && code != ICMP6_UNREACH_ABORT) {
906 		/* Send an ICMPv6 unreach. */
907 #if 0
908 		/*
909 		 * Unlike above, the mbufs need to line up with the ip6 hdr,
910 		 * as the contents are read. We need to m_adj() the
911 		 * needed amount.
912 		 * The mbuf will however be thrown away so we can adjust it.
913 		 * Remember we did an m_pullup on it already so we
914 		 * can make some assumptions about contiguousness.
915 		 */
916 		if (args->L3offset)
917 			m_adj(m, args->L3offset);
918 #endif
919 		icmp6_error(m, ICMP6_DST_UNREACH, code, 0);
920 	} else
921 		FREE_PKT(m);
922 
923 	args->m = NULL;
924 }
925 
926 #endif /* INET6 */
927 
928 
929 /*
930  * sends a reject message, consuming the mbuf passed as an argument.
931  */
932 static void
933 send_reject(struct ip_fw_args *args, int code, int iplen, struct ip *ip)
934 {
935 
936 #if 0
937 	/* XXX When ip is not guaranteed to be at mtod() we will
938 	 * need to account for this */
939 	 * The mbuf will however be thrown away so we can adjust it.
940 	 * Remember we did an m_pullup on it already so we
941 	 * can make some assumptions about contiguousness.
942 	 */
943 	if (args->L3offset)
944 		m_adj(m, args->L3offset);
945 #endif
946 	if (code != ICMP_REJECT_RST && code != ICMP_REJECT_ABORT) {
947 		/* Send an ICMP unreach */
948 		icmp_error(args->m, ICMP_UNREACH, code, 0L, 0);
949 	} else if (code == ICMP_REJECT_RST && args->f_id.proto == IPPROTO_TCP) {
950 		struct tcphdr *const tcp =
951 		    L3HDR(struct tcphdr, mtod(args->m, struct ip *));
952 		if ( (tcp->th_flags & TH_RST) == 0) {
953 			struct mbuf *m;
954 			m = ipfw_send_pkt(args->m, &(args->f_id),
955 				ntohl(tcp->th_seq), ntohl(tcp->th_ack),
956 				tcp->th_flags | TH_RST);
957 			if (m != NULL)
958 				ip_output(m, NULL, NULL, 0, NULL, NULL);
959 		}
960 		FREE_PKT(args->m);
961 	} else if (code == ICMP_REJECT_ABORT &&
962 	    args->f_id.proto == IPPROTO_SCTP) {
963 		struct mbuf *m;
964 		struct sctphdr *sctp;
965 		struct sctp_chunkhdr *chunk;
966 		struct sctp_init *init;
967 		u_int32_t v_tag;
968 		int reflected;
969 
970 		sctp = L3HDR(struct sctphdr, mtod(args->m, struct ip *));
971 		reflected = 1;
972 		v_tag = ntohl(sctp->v_tag);
973 		if (iplen >= (ip->ip_hl << 2) + sizeof(struct sctphdr) +
974 		    sizeof(struct sctp_chunkhdr)) {
975 			/* Look at the first chunk header if available */
976 			chunk = (struct sctp_chunkhdr *)(sctp + 1);
977 			switch (chunk->chunk_type) {
978 			case SCTP_INITIATION:
979 				/*
980 				 * Packets containing an INIT chunk MUST have
981 				 * a zero v-tag.
982 				 */
983 				if (v_tag != 0) {
984 					v_tag = 0;
985 					break;
986 				}
987 				/* INIT chunk MUST NOT be bundled */
988 				if (iplen >
989 				    (ip->ip_hl << 2) + sizeof(struct sctphdr) +
990 				    ntohs(chunk->chunk_length) + 3) {
991 					break;
992 				}
993 				/* Use the initiate tag if available */
994 				if ((iplen >= (ip->ip_hl << 2) +
995 				    sizeof(struct sctphdr) +
996 				    sizeof(struct sctp_chunkhdr) +
997 				    offsetof(struct sctp_init, a_rwnd))) {
998 					init = (struct sctp_init *)(chunk + 1);
999 					v_tag = ntohl(init->initiate_tag);
1000 					reflected = 0;
1001 				}
1002 				break;
1003 			case SCTP_ABORT_ASSOCIATION:
1004 				/*
1005 				 * If the packet contains an ABORT chunk, don't
1006 				 * reply.
1007 				 * XXX: We should search through all chunks,
1008 				 * but don't do to avoid attacks.
1009 				 */
1010 				v_tag = 0;
1011 				break;
1012 			}
1013 		}
1014 		if (v_tag == 0) {
1015 			m = NULL;
1016 		} else {
1017 			m = ipfw_send_abort(args->m, &(args->f_id), v_tag,
1018 			    reflected);
1019 		}
1020 		if (m != NULL)
1021 			ip_output(m, NULL, NULL, 0, NULL, NULL);
1022 		FREE_PKT(args->m);
1023 	} else
1024 		FREE_PKT(args->m);
1025 	args->m = NULL;
1026 }
1027 
1028 /*
1029  * Support for uid/gid/jail lookup. These tests are expensive
1030  * (because we may need to look into the list of active sockets)
1031  * so we cache the results. ugid_lookupp is 0 if we have not
1032  * yet done a lookup, 1 if we succeeded, and -1 if we tried
1033  * and failed. The function always returns the match value.
1034  * We could actually spare the variable and use *uc, setting
1035  * it to '(void *)check_uidgid if we have no info, NULL if
1036  * we tried and failed, or any other value if successful.
1037  */
1038 static int
1039 check_uidgid(ipfw_insn_u32 *insn, struct ip_fw_args *args, int *ugid_lookupp,
1040     struct ucred **uc)
1041 {
1042 #if defined(USERSPACE)
1043 	return 0;	// not supported in userspace
1044 #else
1045 #ifndef __FreeBSD__
1046 	/* XXX */
1047 	return cred_check(insn, proto, oif,
1048 	    dst_ip, dst_port, src_ip, src_port,
1049 	    (struct bsd_ucred *)uc, ugid_lookupp, ((struct mbuf *)inp)->m_skb);
1050 #else  /* FreeBSD */
1051 	struct in_addr src_ip, dst_ip;
1052 	struct inpcbinfo *pi;
1053 	struct ipfw_flow_id *id;
1054 	struct inpcb *pcb, *inp;
1055 	struct ifnet *oif;
1056 	int lookupflags;
1057 	int match;
1058 
1059 	id = &args->f_id;
1060 	inp = args->inp;
1061 	oif = args->oif;
1062 
1063 	/*
1064 	 * Check to see if the UDP or TCP stack supplied us with
1065 	 * the PCB. If so, rather then holding a lock and looking
1066 	 * up the PCB, we can use the one that was supplied.
1067 	 */
1068 	if (inp && *ugid_lookupp == 0) {
1069 		INP_LOCK_ASSERT(inp);
1070 		if (inp->inp_socket != NULL) {
1071 			*uc = crhold(inp->inp_cred);
1072 			*ugid_lookupp = 1;
1073 		} else
1074 			*ugid_lookupp = -1;
1075 	}
1076 	/*
1077 	 * If we have already been here and the packet has no
1078 	 * PCB entry associated with it, then we can safely
1079 	 * assume that this is a no match.
1080 	 */
1081 	if (*ugid_lookupp == -1)
1082 		return (0);
1083 	if (id->proto == IPPROTO_TCP) {
1084 		lookupflags = 0;
1085 		pi = &V_tcbinfo;
1086 	} else if (id->proto == IPPROTO_UDP) {
1087 		lookupflags = INPLOOKUP_WILDCARD;
1088 		pi = &V_udbinfo;
1089 	} else
1090 		return 0;
1091 	lookupflags |= INPLOOKUP_RLOCKPCB;
1092 	match = 0;
1093 	if (*ugid_lookupp == 0) {
1094 		if (id->addr_type == 6) {
1095 #ifdef INET6
1096 			if (oif == NULL)
1097 				pcb = in6_pcblookup_mbuf(pi,
1098 				    &id->src_ip6, htons(id->src_port),
1099 				    &id->dst_ip6, htons(id->dst_port),
1100 				    lookupflags, oif, args->m);
1101 			else
1102 				pcb = in6_pcblookup_mbuf(pi,
1103 				    &id->dst_ip6, htons(id->dst_port),
1104 				    &id->src_ip6, htons(id->src_port),
1105 				    lookupflags, oif, args->m);
1106 #else
1107 			*ugid_lookupp = -1;
1108 			return (0);
1109 #endif
1110 		} else {
1111 			src_ip.s_addr = htonl(id->src_ip);
1112 			dst_ip.s_addr = htonl(id->dst_ip);
1113 			if (oif == NULL)
1114 				pcb = in_pcblookup_mbuf(pi,
1115 				    src_ip, htons(id->src_port),
1116 				    dst_ip, htons(id->dst_port),
1117 				    lookupflags, oif, args->m);
1118 			else
1119 				pcb = in_pcblookup_mbuf(pi,
1120 				    dst_ip, htons(id->dst_port),
1121 				    src_ip, htons(id->src_port),
1122 				    lookupflags, oif, args->m);
1123 		}
1124 		if (pcb != NULL) {
1125 			INP_RLOCK_ASSERT(pcb);
1126 			*uc = crhold(pcb->inp_cred);
1127 			*ugid_lookupp = 1;
1128 			INP_RUNLOCK(pcb);
1129 		}
1130 		if (*ugid_lookupp == 0) {
1131 			/*
1132 			 * We tried and failed, set the variable to -1
1133 			 * so we will not try again on this packet.
1134 			 */
1135 			*ugid_lookupp = -1;
1136 			return (0);
1137 		}
1138 	}
1139 	if (insn->o.opcode == O_UID)
1140 		match = ((*uc)->cr_uid == (uid_t)insn->d[0]);
1141 	else if (insn->o.opcode == O_GID)
1142 		match = groupmember((gid_t)insn->d[0], *uc);
1143 	else if (insn->o.opcode == O_JAIL)
1144 		match = ((*uc)->cr_prison->pr_id == (int)insn->d[0]);
1145 	return (match);
1146 #endif /* __FreeBSD__ */
1147 #endif /* not supported in userspace */
1148 }
1149 
1150 /*
1151  * Helper function to set args with info on the rule after the matching
1152  * one. slot is precise, whereas we guess rule_id as they are
1153  * assigned sequentially.
1154  */
1155 static inline void
1156 set_match(struct ip_fw_args *args, int slot,
1157 	struct ip_fw_chain *chain)
1158 {
1159 	args->rule.chain_id = chain->id;
1160 	args->rule.slot = slot + 1; /* we use 0 as a marker */
1161 	args->rule.rule_id = 1 + chain->map[slot]->id;
1162 	args->rule.rulenum = chain->map[slot]->rulenum;
1163 }
1164 
1165 #ifndef LINEAR_SKIPTO
1166 /*
1167  * Helper function to enable cached rule lookups using
1168  * cached_id and cached_pos fields in ipfw rule.
1169  */
1170 static int
1171 jump_fast(struct ip_fw_chain *chain, struct ip_fw *f, int num,
1172     int tablearg, int jump_backwards)
1173 {
1174 	int f_pos;
1175 
1176 	/* If possible use cached f_pos (in f->cached_pos),
1177 	 * whose version is written in f->cached_id
1178 	 * (horrible hacks to avoid changing the ABI).
1179 	 */
1180 	if (num != IP_FW_TARG && f->cached_id == chain->id)
1181 		f_pos = f->cached_pos;
1182 	else {
1183 		int i = IP_FW_ARG_TABLEARG(chain, num, skipto);
1184 		/* make sure we do not jump backward */
1185 		if (jump_backwards == 0 && i <= f->rulenum)
1186 			i = f->rulenum + 1;
1187 		if (chain->idxmap != NULL)
1188 			f_pos = chain->idxmap[i];
1189 		else
1190 			f_pos = ipfw_find_rule(chain, i, 0);
1191 		/* update the cache */
1192 		if (num != IP_FW_TARG) {
1193 			f->cached_id = chain->id;
1194 			f->cached_pos = f_pos;
1195 		}
1196 	}
1197 
1198 	return (f_pos);
1199 }
1200 #else
1201 /*
1202  * Helper function to enable real fast rule lookups.
1203  */
1204 static int
1205 jump_linear(struct ip_fw_chain *chain, struct ip_fw *f, int num,
1206     int tablearg, int jump_backwards)
1207 {
1208 	int f_pos;
1209 
1210 	num = IP_FW_ARG_TABLEARG(chain, num, skipto);
1211 	/* make sure we do not jump backward */
1212 	if (jump_backwards == 0 && num <= f->rulenum)
1213 		num = f->rulenum + 1;
1214 	f_pos = chain->idxmap[num];
1215 
1216 	return (f_pos);
1217 }
1218 #endif
1219 
1220 #define	TARG(k, f)	IP_FW_ARG_TABLEARG(chain, k, f)
1221 /*
1222  * The main check routine for the firewall.
1223  *
1224  * All arguments are in args so we can modify them and return them
1225  * back to the caller.
1226  *
1227  * Parameters:
1228  *
1229  *	args->m	(in/out) The packet; we set to NULL when/if we nuke it.
1230  *		Starts with the IP header.
1231  *	args->eh (in)	Mac header if present, NULL for layer3 packet.
1232  *	args->L3offset	Number of bytes bypassed if we came from L2.
1233  *			e.g. often sizeof(eh)  ** NOTYET **
1234  *	args->oif	Outgoing interface, NULL if packet is incoming.
1235  *		The incoming interface is in the mbuf. (in)
1236  *	args->divert_rule (in/out)
1237  *		Skip up to the first rule past this rule number;
1238  *		upon return, non-zero port number for divert or tee.
1239  *
1240  *	args->rule	Pointer to the last matching rule (in/out)
1241  *	args->next_hop	Socket we are forwarding to (out).
1242  *	args->next_hop6	IPv6 next hop we are forwarding to (out).
1243  *	args->f_id	Addresses grabbed from the packet (out)
1244  * 	args->rule.info	a cookie depending on rule action
1245  *
1246  * Return value:
1247  *
1248  *	IP_FW_PASS	the packet must be accepted
1249  *	IP_FW_DENY	the packet must be dropped
1250  *	IP_FW_DIVERT	divert packet, port in m_tag
1251  *	IP_FW_TEE	tee packet, port in m_tag
1252  *	IP_FW_DUMMYNET	to dummynet, pipe in args->cookie
1253  *	IP_FW_NETGRAPH	into netgraph, cookie args->cookie
1254  *		args->rule contains the matching rule,
1255  *		args->rule.info has additional information.
1256  *
1257  */
1258 int
1259 ipfw_chk(struct ip_fw_args *args)
1260 {
1261 
1262 	/*
1263 	 * Local variables holding state while processing a packet:
1264 	 *
1265 	 * IMPORTANT NOTE: to speed up the processing of rules, there
1266 	 * are some assumption on the values of the variables, which
1267 	 * are documented here. Should you change them, please check
1268 	 * the implementation of the various instructions to make sure
1269 	 * that they still work.
1270 	 *
1271 	 * args->eh	The MAC header. It is non-null for a layer2
1272 	 *	packet, it is NULL for a layer-3 packet.
1273 	 * **notyet**
1274 	 * args->L3offset Offset in the packet to the L3 (IP or equiv.) header.
1275 	 *
1276 	 * m | args->m	Pointer to the mbuf, as received from the caller.
1277 	 *	It may change if ipfw_chk() does an m_pullup, or if it
1278 	 *	consumes the packet because it calls send_reject().
1279 	 *	XXX This has to change, so that ipfw_chk() never modifies
1280 	 *	or consumes the buffer.
1281 	 * ip	is the beginning of the ip(4 or 6) header.
1282 	 *	Calculated by adding the L3offset to the start of data.
1283 	 *	(Until we start using L3offset, the packet is
1284 	 *	supposed to start with the ip header).
1285 	 */
1286 	struct mbuf *m = args->m;
1287 	struct ip *ip = mtod(m, struct ip *);
1288 
1289 	/*
1290 	 * For rules which contain uid/gid or jail constraints, cache
1291 	 * a copy of the users credentials after the pcb lookup has been
1292 	 * executed. This will speed up the processing of rules with
1293 	 * these types of constraints, as well as decrease contention
1294 	 * on pcb related locks.
1295 	 */
1296 #ifndef __FreeBSD__
1297 	struct bsd_ucred ucred_cache;
1298 #else
1299 	struct ucred *ucred_cache = NULL;
1300 #endif
1301 	int ucred_lookup = 0;
1302 
1303 	/*
1304 	 * oif | args->oif	If NULL, ipfw_chk has been called on the
1305 	 *	inbound path (ether_input, ip_input).
1306 	 *	If non-NULL, ipfw_chk has been called on the outbound path
1307 	 *	(ether_output, ip_output).
1308 	 */
1309 	struct ifnet *oif = args->oif;
1310 
1311 	int f_pos = 0;		/* index of current rule in the array */
1312 	int retval = 0;
1313 
1314 	/*
1315 	 * hlen	The length of the IP header.
1316 	 */
1317 	u_int hlen = 0;		/* hlen >0 means we have an IP pkt */
1318 
1319 	/*
1320 	 * offset	The offset of a fragment. offset != 0 means that
1321 	 *	we have a fragment at this offset of an IPv4 packet.
1322 	 *	offset == 0 means that (if this is an IPv4 packet)
1323 	 *	this is the first or only fragment.
1324 	 *	For IPv6 offset|ip6f_mf == 0 means there is no Fragment Header
1325 	 *	or there is a single packet fragment (fragment header added
1326 	 *	without needed).  We will treat a single packet fragment as if
1327 	 *	there was no fragment header (or log/block depending on the
1328 	 *	V_fw_permit_single_frag6 sysctl setting).
1329 	 */
1330 	u_short offset = 0;
1331 	u_short ip6f_mf = 0;
1332 
1333 	/*
1334 	 * Local copies of addresses. They are only valid if we have
1335 	 * an IP packet.
1336 	 *
1337 	 * proto	The protocol. Set to 0 for non-ip packets,
1338 	 *	or to the protocol read from the packet otherwise.
1339 	 *	proto != 0 means that we have an IPv4 packet.
1340 	 *
1341 	 * src_port, dst_port	port numbers, in HOST format. Only
1342 	 *	valid for TCP and UDP packets.
1343 	 *
1344 	 * src_ip, dst_ip	ip addresses, in NETWORK format.
1345 	 *	Only valid for IPv4 packets.
1346 	 */
1347 	uint8_t proto;
1348 	uint16_t src_port = 0, dst_port = 0;	/* NOTE: host format	*/
1349 	struct in_addr src_ip, dst_ip;		/* NOTE: network format	*/
1350 	int iplen = 0;
1351 	int pktlen;
1352 	uint16_t	etype = 0;	/* Host order stored ether type */
1353 
1354 	/*
1355 	 * dyn_dir = MATCH_UNKNOWN when rules unchecked,
1356 	 * 	MATCH_NONE when checked and not matched (q = NULL),
1357 	 *	MATCH_FORWARD or MATCH_REVERSE otherwise (q != NULL)
1358 	 */
1359 	int dyn_dir = MATCH_UNKNOWN;
1360 	uint16_t dyn_name = 0;
1361 	struct ip_fw *q = NULL;
1362 	struct ip_fw_chain *chain = &V_layer3_chain;
1363 
1364 	/*
1365 	 * We store in ulp a pointer to the upper layer protocol header.
1366 	 * In the ipv4 case this is easy to determine from the header,
1367 	 * but for ipv6 we might have some additional headers in the middle.
1368 	 * ulp is NULL if not found.
1369 	 */
1370 	void *ulp = NULL;		/* upper layer protocol pointer. */
1371 
1372 	/* XXX ipv6 variables */
1373 	int is_ipv6 = 0;
1374 	uint8_t	icmp6_type = 0;
1375 	uint16_t ext_hd = 0;	/* bits vector for extension header filtering */
1376 	/* end of ipv6 variables */
1377 
1378 	int is_ipv4 = 0;
1379 
1380 	int done = 0;		/* flag to exit the outer loop */
1381 
1382 	if (m->m_flags & M_SKIP_FIREWALL || (! V_ipfw_vnet_ready))
1383 		return (IP_FW_PASS);	/* accept */
1384 
1385 	dst_ip.s_addr = 0;		/* make sure it is initialized */
1386 	src_ip.s_addr = 0;		/* make sure it is initialized */
1387 	pktlen = m->m_pkthdr.len;
1388 	args->f_id.fib = M_GETFIB(m); /* note mbuf not altered) */
1389 	proto = args->f_id.proto = 0;	/* mark f_id invalid */
1390 		/* XXX 0 is a valid proto: IP/IPv6 Hop-by-Hop Option */
1391 
1392 /*
1393  * PULLUP_TO(len, p, T) makes sure that len + sizeof(T) is contiguous,
1394  * then it sets p to point at the offset "len" in the mbuf. WARNING: the
1395  * pointer might become stale after other pullups (but we never use it
1396  * this way).
1397  */
1398 #define PULLUP_TO(_len, p, T)	PULLUP_LEN(_len, p, sizeof(T))
1399 #define PULLUP_LEN(_len, p, T)					\
1400 do {								\
1401 	int x = (_len) + T;					\
1402 	if ((m)->m_len < x) {					\
1403 		args->m = m = m_pullup(m, x);			\
1404 		if (m == NULL)					\
1405 			goto pullup_failed;			\
1406 	}							\
1407 	p = (mtod(m, char *) + (_len));				\
1408 } while (0)
1409 
1410 	/*
1411 	 * if we have an ether header,
1412 	 */
1413 	if (args->eh)
1414 		etype = ntohs(args->eh->ether_type);
1415 
1416 	/* Identify IP packets and fill up variables. */
1417 	if (pktlen >= sizeof(struct ip6_hdr) &&
1418 	    (args->eh == NULL || etype == ETHERTYPE_IPV6) && ip->ip_v == 6) {
1419 		struct ip6_hdr *ip6 = (struct ip6_hdr *)ip;
1420 		is_ipv6 = 1;
1421 		args->f_id.addr_type = 6;
1422 		hlen = sizeof(struct ip6_hdr);
1423 		proto = ip6->ip6_nxt;
1424 
1425 		/* Search extension headers to find upper layer protocols */
1426 		while (ulp == NULL && offset == 0) {
1427 			switch (proto) {
1428 			case IPPROTO_ICMPV6:
1429 				PULLUP_TO(hlen, ulp, struct icmp6_hdr);
1430 				icmp6_type = ICMP6(ulp)->icmp6_type;
1431 				break;
1432 
1433 			case IPPROTO_TCP:
1434 				PULLUP_TO(hlen, ulp, struct tcphdr);
1435 				dst_port = TCP(ulp)->th_dport;
1436 				src_port = TCP(ulp)->th_sport;
1437 				/* save flags for dynamic rules */
1438 				args->f_id._flags = TCP(ulp)->th_flags;
1439 				break;
1440 
1441 			case IPPROTO_SCTP:
1442 				if (pktlen >= hlen + sizeof(struct sctphdr) +
1443 				    sizeof(struct sctp_chunkhdr) +
1444 				    offsetof(struct sctp_init, a_rwnd))
1445 					PULLUP_LEN(hlen, ulp,
1446 					    sizeof(struct sctphdr) +
1447 					    sizeof(struct sctp_chunkhdr) +
1448 					    offsetof(struct sctp_init, a_rwnd));
1449 				else if (pktlen >= hlen + sizeof(struct sctphdr))
1450 					PULLUP_LEN(hlen, ulp, pktlen - hlen);
1451 				else
1452 					PULLUP_LEN(hlen, ulp,
1453 					    sizeof(struct sctphdr));
1454 				src_port = SCTP(ulp)->src_port;
1455 				dst_port = SCTP(ulp)->dest_port;
1456 				break;
1457 
1458 			case IPPROTO_UDP:
1459 				PULLUP_TO(hlen, ulp, struct udphdr);
1460 				dst_port = UDP(ulp)->uh_dport;
1461 				src_port = UDP(ulp)->uh_sport;
1462 				break;
1463 
1464 			case IPPROTO_HOPOPTS:	/* RFC 2460 */
1465 				PULLUP_TO(hlen, ulp, struct ip6_hbh);
1466 				ext_hd |= EXT_HOPOPTS;
1467 				hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3;
1468 				proto = ((struct ip6_hbh *)ulp)->ip6h_nxt;
1469 				ulp = NULL;
1470 				break;
1471 
1472 			case IPPROTO_ROUTING:	/* RFC 2460 */
1473 				PULLUP_TO(hlen, ulp, struct ip6_rthdr);
1474 				switch (((struct ip6_rthdr *)ulp)->ip6r_type) {
1475 				case 0:
1476 					ext_hd |= EXT_RTHDR0;
1477 					break;
1478 				case 2:
1479 					ext_hd |= EXT_RTHDR2;
1480 					break;
1481 				default:
1482 					if (V_fw_verbose)
1483 						printf("IPFW2: IPV6 - Unknown "
1484 						    "Routing Header type(%d)\n",
1485 						    ((struct ip6_rthdr *)
1486 						    ulp)->ip6r_type);
1487 					if (V_fw_deny_unknown_exthdrs)
1488 					    return (IP_FW_DENY);
1489 					break;
1490 				}
1491 				ext_hd |= EXT_ROUTING;
1492 				hlen += (((struct ip6_rthdr *)ulp)->ip6r_len + 1) << 3;
1493 				proto = ((struct ip6_rthdr *)ulp)->ip6r_nxt;
1494 				ulp = NULL;
1495 				break;
1496 
1497 			case IPPROTO_FRAGMENT:	/* RFC 2460 */
1498 				PULLUP_TO(hlen, ulp, struct ip6_frag);
1499 				ext_hd |= EXT_FRAGMENT;
1500 				hlen += sizeof (struct ip6_frag);
1501 				proto = ((struct ip6_frag *)ulp)->ip6f_nxt;
1502 				offset = ((struct ip6_frag *)ulp)->ip6f_offlg &
1503 					IP6F_OFF_MASK;
1504 				ip6f_mf = ((struct ip6_frag *)ulp)->ip6f_offlg &
1505 					IP6F_MORE_FRAG;
1506 				if (V_fw_permit_single_frag6 == 0 &&
1507 				    offset == 0 && ip6f_mf == 0) {
1508 					if (V_fw_verbose)
1509 						printf("IPFW2: IPV6 - Invalid "
1510 						    "Fragment Header\n");
1511 					if (V_fw_deny_unknown_exthdrs)
1512 					    return (IP_FW_DENY);
1513 					break;
1514 				}
1515 				args->f_id.extra =
1516 				    ntohl(((struct ip6_frag *)ulp)->ip6f_ident);
1517 				ulp = NULL;
1518 				break;
1519 
1520 			case IPPROTO_DSTOPTS:	/* RFC 2460 */
1521 				PULLUP_TO(hlen, ulp, struct ip6_hbh);
1522 				ext_hd |= EXT_DSTOPTS;
1523 				hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3;
1524 				proto = ((struct ip6_hbh *)ulp)->ip6h_nxt;
1525 				ulp = NULL;
1526 				break;
1527 
1528 			case IPPROTO_AH:	/* RFC 2402 */
1529 				PULLUP_TO(hlen, ulp, struct ip6_ext);
1530 				ext_hd |= EXT_AH;
1531 				hlen += (((struct ip6_ext *)ulp)->ip6e_len + 2) << 2;
1532 				proto = ((struct ip6_ext *)ulp)->ip6e_nxt;
1533 				ulp = NULL;
1534 				break;
1535 
1536 			case IPPROTO_ESP:	/* RFC 2406 */
1537 				PULLUP_TO(hlen, ulp, uint32_t);	/* SPI, Seq# */
1538 				/* Anything past Seq# is variable length and
1539 				 * data past this ext. header is encrypted. */
1540 				ext_hd |= EXT_ESP;
1541 				break;
1542 
1543 			case IPPROTO_NONE:	/* RFC 2460 */
1544 				/*
1545 				 * Packet ends here, and IPv6 header has
1546 				 * already been pulled up. If ip6e_len!=0
1547 				 * then octets must be ignored.
1548 				 */
1549 				ulp = ip; /* non-NULL to get out of loop. */
1550 				break;
1551 
1552 			case IPPROTO_OSPFIGP:
1553 				/* XXX OSPF header check? */
1554 				PULLUP_TO(hlen, ulp, struct ip6_ext);
1555 				break;
1556 
1557 			case IPPROTO_PIM:
1558 				/* XXX PIM header check? */
1559 				PULLUP_TO(hlen, ulp, struct pim);
1560 				break;
1561 
1562 			case IPPROTO_GRE:	/* RFC 1701 */
1563 				/* XXX GRE header check? */
1564 				PULLUP_TO(hlen, ulp, struct grehdr);
1565 				break;
1566 
1567 			case IPPROTO_CARP:
1568 				PULLUP_TO(hlen, ulp, struct carp_header);
1569 				if (((struct carp_header *)ulp)->carp_version !=
1570 				    CARP_VERSION)
1571 					return (IP_FW_DENY);
1572 				if (((struct carp_header *)ulp)->carp_type !=
1573 				    CARP_ADVERTISEMENT)
1574 					return (IP_FW_DENY);
1575 				break;
1576 
1577 			case IPPROTO_IPV6:	/* RFC 2893 */
1578 				PULLUP_TO(hlen, ulp, struct ip6_hdr);
1579 				break;
1580 
1581 			case IPPROTO_IPV4:	/* RFC 2893 */
1582 				PULLUP_TO(hlen, ulp, struct ip);
1583 				break;
1584 
1585 			default:
1586 				if (V_fw_verbose)
1587 					printf("IPFW2: IPV6 - Unknown "
1588 					    "Extension Header(%d), ext_hd=%x\n",
1589 					     proto, ext_hd);
1590 				if (V_fw_deny_unknown_exthdrs)
1591 				    return (IP_FW_DENY);
1592 				PULLUP_TO(hlen, ulp, struct ip6_ext);
1593 				break;
1594 			} /*switch */
1595 		}
1596 		ip = mtod(m, struct ip *);
1597 		ip6 = (struct ip6_hdr *)ip;
1598 		args->f_id.src_ip6 = ip6->ip6_src;
1599 		args->f_id.dst_ip6 = ip6->ip6_dst;
1600 		args->f_id.src_ip = 0;
1601 		args->f_id.dst_ip = 0;
1602 		args->f_id.flow_id6 = ntohl(ip6->ip6_flow);
1603 		iplen = ntohs(ip6->ip6_plen) + sizeof(*ip6);
1604 	} else if (pktlen >= sizeof(struct ip) &&
1605 	    (args->eh == NULL || etype == ETHERTYPE_IP) && ip->ip_v == 4) {
1606 	    	is_ipv4 = 1;
1607 		hlen = ip->ip_hl << 2;
1608 		args->f_id.addr_type = 4;
1609 
1610 		/*
1611 		 * Collect parameters into local variables for faster matching.
1612 		 */
1613 		proto = ip->ip_p;
1614 		src_ip = ip->ip_src;
1615 		dst_ip = ip->ip_dst;
1616 		offset = ntohs(ip->ip_off) & IP_OFFMASK;
1617 		iplen = ntohs(ip->ip_len);
1618 
1619 		if (offset == 0) {
1620 			switch (proto) {
1621 			case IPPROTO_TCP:
1622 				PULLUP_TO(hlen, ulp, struct tcphdr);
1623 				dst_port = TCP(ulp)->th_dport;
1624 				src_port = TCP(ulp)->th_sport;
1625 				/* save flags for dynamic rules */
1626 				args->f_id._flags = TCP(ulp)->th_flags;
1627 				break;
1628 
1629 			case IPPROTO_SCTP:
1630 				if (pktlen >= hlen + sizeof(struct sctphdr) +
1631 				    sizeof(struct sctp_chunkhdr) +
1632 				    offsetof(struct sctp_init, a_rwnd))
1633 					PULLUP_LEN(hlen, ulp,
1634 					    sizeof(struct sctphdr) +
1635 					    sizeof(struct sctp_chunkhdr) +
1636 					    offsetof(struct sctp_init, a_rwnd));
1637 				else if (pktlen >= hlen + sizeof(struct sctphdr))
1638 					PULLUP_LEN(hlen, ulp, pktlen - hlen);
1639 				else
1640 					PULLUP_LEN(hlen, ulp,
1641 					    sizeof(struct sctphdr));
1642 				src_port = SCTP(ulp)->src_port;
1643 				dst_port = SCTP(ulp)->dest_port;
1644 				break;
1645 
1646 			case IPPROTO_UDP:
1647 				PULLUP_TO(hlen, ulp, struct udphdr);
1648 				dst_port = UDP(ulp)->uh_dport;
1649 				src_port = UDP(ulp)->uh_sport;
1650 				break;
1651 
1652 			case IPPROTO_ICMP:
1653 				PULLUP_TO(hlen, ulp, struct icmphdr);
1654 				//args->f_id.flags = ICMP(ulp)->icmp_type;
1655 				break;
1656 
1657 			default:
1658 				break;
1659 			}
1660 		}
1661 
1662 		ip = mtod(m, struct ip *);
1663 		args->f_id.src_ip = ntohl(src_ip.s_addr);
1664 		args->f_id.dst_ip = ntohl(dst_ip.s_addr);
1665 	}
1666 #undef PULLUP_TO
1667 	pktlen = iplen < pktlen ? iplen: pktlen;
1668 	if (proto) { /* we may have port numbers, store them */
1669 		args->f_id.proto = proto;
1670 		args->f_id.src_port = src_port = ntohs(src_port);
1671 		args->f_id.dst_port = dst_port = ntohs(dst_port);
1672 	}
1673 
1674 	IPFW_PF_RLOCK(chain);
1675 	if (! V_ipfw_vnet_ready) { /* shutting down, leave NOW. */
1676 		IPFW_PF_RUNLOCK(chain);
1677 		return (IP_FW_PASS);	/* accept */
1678 	}
1679 	if (args->rule.slot) {
1680 		/*
1681 		 * Packet has already been tagged as a result of a previous
1682 		 * match on rule args->rule aka args->rule_id (PIPE, QUEUE,
1683 		 * REASS, NETGRAPH, DIVERT/TEE...)
1684 		 * Validate the slot and continue from the next one
1685 		 * if still present, otherwise do a lookup.
1686 		 */
1687 		f_pos = (args->rule.chain_id == chain->id) ?
1688 		    args->rule.slot :
1689 		    ipfw_find_rule(chain, args->rule.rulenum,
1690 			args->rule.rule_id);
1691 	} else {
1692 		f_pos = 0;
1693 	}
1694 
1695 	/*
1696 	 * Now scan the rules, and parse microinstructions for each rule.
1697 	 * We have two nested loops and an inner switch. Sometimes we
1698 	 * need to break out of one or both loops, or re-enter one of
1699 	 * the loops with updated variables. Loop variables are:
1700 	 *
1701 	 *	f_pos (outer loop) points to the current rule.
1702 	 *		On output it points to the matching rule.
1703 	 *	done (outer loop) is used as a flag to break the loop.
1704 	 *	l (inner loop)	residual length of current rule.
1705 	 *		cmd points to the current microinstruction.
1706 	 *
1707 	 * We break the inner loop by setting l=0 and possibly
1708 	 * cmdlen=0 if we don't want to advance cmd.
1709 	 * We break the outer loop by setting done=1
1710 	 * We can restart the inner loop by setting l>0 and f_pos, f, cmd
1711 	 * as needed.
1712 	 */
1713 	for (; f_pos < chain->n_rules; f_pos++) {
1714 		ipfw_insn *cmd;
1715 		uint32_t tablearg = 0;
1716 		int l, cmdlen, skip_or; /* skip rest of OR block */
1717 		struct ip_fw *f;
1718 
1719 		f = chain->map[f_pos];
1720 		if (V_set_disable & (1 << f->set) )
1721 			continue;
1722 
1723 		skip_or = 0;
1724 		for (l = f->cmd_len, cmd = f->cmd ; l > 0 ;
1725 		    l -= cmdlen, cmd += cmdlen) {
1726 			int match;
1727 
1728 			/*
1729 			 * check_body is a jump target used when we find a
1730 			 * CHECK_STATE, and need to jump to the body of
1731 			 * the target rule.
1732 			 */
1733 
1734 /* check_body: */
1735 			cmdlen = F_LEN(cmd);
1736 			/*
1737 			 * An OR block (insn_1 || .. || insn_n) has the
1738 			 * F_OR bit set in all but the last instruction.
1739 			 * The first match will set "skip_or", and cause
1740 			 * the following instructions to be skipped until
1741 			 * past the one with the F_OR bit clear.
1742 			 */
1743 			if (skip_or) {		/* skip this instruction */
1744 				if ((cmd->len & F_OR) == 0)
1745 					skip_or = 0;	/* next one is good */
1746 				continue;
1747 			}
1748 			match = 0; /* set to 1 if we succeed */
1749 
1750 			switch (cmd->opcode) {
1751 			/*
1752 			 * The first set of opcodes compares the packet's
1753 			 * fields with some pattern, setting 'match' if a
1754 			 * match is found. At the end of the loop there is
1755 			 * logic to deal with F_NOT and F_OR flags associated
1756 			 * with the opcode.
1757 			 */
1758 			case O_NOP:
1759 				match = 1;
1760 				break;
1761 
1762 			case O_FORWARD_MAC:
1763 				printf("ipfw: opcode %d unimplemented\n",
1764 				    cmd->opcode);
1765 				break;
1766 
1767 			case O_GID:
1768 			case O_UID:
1769 			case O_JAIL:
1770 				/*
1771 				 * We only check offset == 0 && proto != 0,
1772 				 * as this ensures that we have a
1773 				 * packet with the ports info.
1774 				 */
1775 				if (offset != 0)
1776 					break;
1777 				if (proto == IPPROTO_TCP ||
1778 				    proto == IPPROTO_UDP)
1779 					match = check_uidgid(
1780 						    (ipfw_insn_u32 *)cmd,
1781 						    args, &ucred_lookup,
1782 #ifdef __FreeBSD__
1783 						    &ucred_cache);
1784 #else
1785 						    (void *)&ucred_cache);
1786 #endif
1787 				break;
1788 
1789 			case O_RECV:
1790 				match = iface_match(m->m_pkthdr.rcvif,
1791 				    (ipfw_insn_if *)cmd, chain, &tablearg);
1792 				break;
1793 
1794 			case O_XMIT:
1795 				match = iface_match(oif, (ipfw_insn_if *)cmd,
1796 				    chain, &tablearg);
1797 				break;
1798 
1799 			case O_VIA:
1800 				match = iface_match(oif ? oif :
1801 				    m->m_pkthdr.rcvif, (ipfw_insn_if *)cmd,
1802 				    chain, &tablearg);
1803 				break;
1804 
1805 			case O_MACADDR2:
1806 				if (args->eh != NULL) {	/* have MAC header */
1807 					u_int32_t *want = (u_int32_t *)
1808 						((ipfw_insn_mac *)cmd)->addr;
1809 					u_int32_t *mask = (u_int32_t *)
1810 						((ipfw_insn_mac *)cmd)->mask;
1811 					u_int32_t *hdr = (u_int32_t *)args->eh;
1812 
1813 					match =
1814 					    ( want[0] == (hdr[0] & mask[0]) &&
1815 					      want[1] == (hdr[1] & mask[1]) &&
1816 					      want[2] == (hdr[2] & mask[2]) );
1817 				}
1818 				break;
1819 
1820 			case O_MAC_TYPE:
1821 				if (args->eh != NULL) {
1822 					u_int16_t *p =
1823 					    ((ipfw_insn_u16 *)cmd)->ports;
1824 					int i;
1825 
1826 					for (i = cmdlen - 1; !match && i>0;
1827 					    i--, p += 2)
1828 						match = (etype >= p[0] &&
1829 						    etype <= p[1]);
1830 				}
1831 				break;
1832 
1833 			case O_FRAG:
1834 				match = (offset != 0);
1835 				break;
1836 
1837 			case O_IN:	/* "out" is "not in" */
1838 				match = (oif == NULL);
1839 				break;
1840 
1841 			case O_LAYER2:
1842 				match = (args->eh != NULL);
1843 				break;
1844 
1845 			case O_DIVERTED:
1846 			    {
1847 				/* For diverted packets, args->rule.info
1848 				 * contains the divert port (in host format)
1849 				 * reason and direction.
1850 				 */
1851 				uint32_t i = args->rule.info;
1852 				match = (i&IPFW_IS_MASK) == IPFW_IS_DIVERT &&
1853 				    cmd->arg1 & ((i & IPFW_INFO_IN) ? 1 : 2);
1854 			    }
1855 				break;
1856 
1857 			case O_PROTO:
1858 				/*
1859 				 * We do not allow an arg of 0 so the
1860 				 * check of "proto" only suffices.
1861 				 */
1862 				match = (proto == cmd->arg1);
1863 				break;
1864 
1865 			case O_IP_SRC:
1866 				match = is_ipv4 &&
1867 				    (((ipfw_insn_ip *)cmd)->addr.s_addr ==
1868 				    src_ip.s_addr);
1869 				break;
1870 
1871 			case O_IP_DST_LOOKUP:
1872 			{
1873 				void *pkey;
1874 				uint32_t vidx, key;
1875 				uint16_t keylen;
1876 
1877 				if (cmdlen > F_INSN_SIZE(ipfw_insn_u32)) {
1878 					/* Determine lookup key type */
1879 					vidx = ((ipfw_insn_u32 *)cmd)->d[1];
1880 					if (vidx != 4 /* uid */ &&
1881 					    vidx != 5 /* jail */ &&
1882 					    is_ipv6 == 0 && is_ipv4 == 0)
1883 						break;
1884 					/* Determine key length */
1885 					if (vidx == 0 /* dst-ip */ ||
1886 					    vidx == 1 /* src-ip */)
1887 						keylen = is_ipv6 ?
1888 						    sizeof(struct in6_addr):
1889 						    sizeof(in_addr_t);
1890 					else {
1891 						keylen = sizeof(key);
1892 						pkey = &key;
1893 					}
1894 					if (vidx == 0 /* dst-ip */)
1895 						pkey = is_ipv4 ? (void *)&dst_ip:
1896 						    (void *)&args->f_id.dst_ip6;
1897 					else if (vidx == 1 /* src-ip */)
1898 						pkey = is_ipv4 ? (void *)&src_ip:
1899 						    (void *)&args->f_id.src_ip6;
1900 					else if (vidx == 6 /* dscp */) {
1901 						if (is_ipv4)
1902 							key = ip->ip_tos >> 2;
1903 						else {
1904 							key = args->f_id.flow_id6;
1905 							key = (key & 0x0f) << 2 |
1906 							    (key & 0xf000) >> 14;
1907 						}
1908 						key &= 0x3f;
1909 					} else if (vidx == 2 /* dst-port */ ||
1910 					    vidx == 3 /* src-port */) {
1911 						/* Skip fragments */
1912 						if (offset != 0)
1913 							break;
1914 						/* Skip proto without ports */
1915 						if (proto != IPPROTO_TCP &&
1916 						    proto != IPPROTO_UDP &&
1917 						    proto != IPPROTO_SCTP)
1918 							break;
1919 						if (vidx == 2 /* dst-port */)
1920 							key = dst_port;
1921 						else
1922 							key = src_port;
1923 					}
1924 #ifndef USERSPACE
1925 					else if (vidx == 4 /* uid */ ||
1926 					    vidx == 5 /* jail */) {
1927 						check_uidgid(
1928 						    (ipfw_insn_u32 *)cmd,
1929 						    args, &ucred_lookup,
1930 #ifdef __FreeBSD__
1931 						    &ucred_cache);
1932 						if (vidx == 4 /* uid */)
1933 							key = ucred_cache->cr_uid;
1934 						else if (vidx == 5 /* jail */)
1935 							key = ucred_cache->cr_prison->pr_id;
1936 #else /* !__FreeBSD__ */
1937 						    (void *)&ucred_cache);
1938 						if (vidx == 4 /* uid */)
1939 							key = ucred_cache.uid;
1940 						else if (vidx == 5 /* jail */)
1941 							key = ucred_cache.xid;
1942 #endif /* !__FreeBSD__ */
1943 					}
1944 #endif /* !USERSPACE */
1945 					else
1946 						break;
1947 					match = ipfw_lookup_table(chain,
1948 					    cmd->arg1, keylen, pkey, &vidx);
1949 					if (!match)
1950 						break;
1951 					tablearg = vidx;
1952 					break;
1953 				}
1954 				/* cmdlen =< F_INSN_SIZE(ipfw_insn_u32) */
1955 				/* FALLTHROUGH */
1956 			}
1957 			case O_IP_SRC_LOOKUP:
1958 			{
1959 				void *pkey;
1960 				uint32_t vidx;
1961 				uint16_t keylen;
1962 
1963 				if (is_ipv4) {
1964 					keylen = sizeof(in_addr_t);
1965 					if (cmd->opcode == O_IP_DST_LOOKUP)
1966 						pkey = &dst_ip;
1967 					else
1968 						pkey = &src_ip;
1969 				} else if (is_ipv6) {
1970 					keylen = sizeof(struct in6_addr);
1971 					if (cmd->opcode == O_IP_DST_LOOKUP)
1972 						pkey = &args->f_id.dst_ip6;
1973 					else
1974 						pkey = &args->f_id.src_ip6;
1975 				} else
1976 					break;
1977 				match = ipfw_lookup_table(chain, cmd->arg1,
1978 				    keylen, pkey, &vidx);
1979 				if (!match)
1980 					break;
1981 				if (cmdlen == F_INSN_SIZE(ipfw_insn_u32)) {
1982 					match = ((ipfw_insn_u32 *)cmd)->d[0] ==
1983 					    TARG_VAL(chain, vidx, tag);
1984 					if (!match)
1985 						break;
1986 				}
1987 				tablearg = vidx;
1988 				break;
1989 			}
1990 
1991 			case O_IP_FLOW_LOOKUP:
1992 				{
1993 					uint32_t v = 0;
1994 					match = ipfw_lookup_table(chain,
1995 					    cmd->arg1, 0, &args->f_id, &v);
1996 					if (cmdlen == F_INSN_SIZE(ipfw_insn_u32))
1997 						match = ((ipfw_insn_u32 *)cmd)->d[0] ==
1998 						    TARG_VAL(chain, v, tag);
1999 					if (match)
2000 						tablearg = v;
2001 				}
2002 				break;
2003 			case O_IP_SRC_MASK:
2004 			case O_IP_DST_MASK:
2005 				if (is_ipv4) {
2006 				    uint32_t a =
2007 					(cmd->opcode == O_IP_DST_MASK) ?
2008 					    dst_ip.s_addr : src_ip.s_addr;
2009 				    uint32_t *p = ((ipfw_insn_u32 *)cmd)->d;
2010 				    int i = cmdlen-1;
2011 
2012 				    for (; !match && i>0; i-= 2, p+= 2)
2013 					match = (p[0] == (a & p[1]));
2014 				}
2015 				break;
2016 
2017 			case O_IP_SRC_ME:
2018 				if (is_ipv4) {
2019 					match = in_localip(src_ip);
2020 					break;
2021 				}
2022 #ifdef INET6
2023 				/* FALLTHROUGH */
2024 			case O_IP6_SRC_ME:
2025 				match= is_ipv6 && ipfw_localip6(&args->f_id.src_ip6);
2026 #endif
2027 				break;
2028 
2029 			case O_IP_DST_SET:
2030 			case O_IP_SRC_SET:
2031 				if (is_ipv4) {
2032 					u_int32_t *d = (u_int32_t *)(cmd+1);
2033 					u_int32_t addr =
2034 					    cmd->opcode == O_IP_DST_SET ?
2035 						args->f_id.dst_ip :
2036 						args->f_id.src_ip;
2037 
2038 					    if (addr < d[0])
2039 						    break;
2040 					    addr -= d[0]; /* subtract base */
2041 					    match = (addr < cmd->arg1) &&
2042 						( d[ 1 + (addr>>5)] &
2043 						  (1<<(addr & 0x1f)) );
2044 				}
2045 				break;
2046 
2047 			case O_IP_DST:
2048 				match = is_ipv4 &&
2049 				    (((ipfw_insn_ip *)cmd)->addr.s_addr ==
2050 				    dst_ip.s_addr);
2051 				break;
2052 
2053 			case O_IP_DST_ME:
2054 				if (is_ipv4) {
2055 					match = in_localip(dst_ip);
2056 					break;
2057 				}
2058 #ifdef INET6
2059 				/* FALLTHROUGH */
2060 			case O_IP6_DST_ME:
2061 				match= is_ipv6 && ipfw_localip6(&args->f_id.dst_ip6);
2062 #endif
2063 				break;
2064 
2065 
2066 			case O_IP_SRCPORT:
2067 			case O_IP_DSTPORT:
2068 				/*
2069 				 * offset == 0 && proto != 0 is enough
2070 				 * to guarantee that we have a
2071 				 * packet with port info.
2072 				 */
2073 				if ((proto==IPPROTO_UDP || proto==IPPROTO_TCP ||
2074 				    proto==IPPROTO_SCTP) && offset == 0) {
2075 					u_int16_t x =
2076 					    (cmd->opcode == O_IP_SRCPORT) ?
2077 						src_port : dst_port ;
2078 					u_int16_t *p =
2079 					    ((ipfw_insn_u16 *)cmd)->ports;
2080 					int i;
2081 
2082 					for (i = cmdlen - 1; !match && i>0;
2083 					    i--, p += 2)
2084 						match = (x>=p[0] && x<=p[1]);
2085 				}
2086 				break;
2087 
2088 			case O_ICMPTYPE:
2089 				match = (offset == 0 && proto==IPPROTO_ICMP &&
2090 				    icmptype_match(ICMP(ulp), (ipfw_insn_u32 *)cmd) );
2091 				break;
2092 
2093 #ifdef INET6
2094 			case O_ICMP6TYPE:
2095 				match = is_ipv6 && offset == 0 &&
2096 				    proto==IPPROTO_ICMPV6 &&
2097 				    icmp6type_match(
2098 					ICMP6(ulp)->icmp6_type,
2099 					(ipfw_insn_u32 *)cmd);
2100 				break;
2101 #endif /* INET6 */
2102 
2103 			case O_IPOPT:
2104 				match = (is_ipv4 &&
2105 				    ipopts_match(ip, cmd) );
2106 				break;
2107 
2108 			case O_IPVER:
2109 				match = (is_ipv4 &&
2110 				    cmd->arg1 == ip->ip_v);
2111 				break;
2112 
2113 			case O_IPID:
2114 			case O_IPLEN:
2115 			case O_IPTTL:
2116 				if (is_ipv4) {	/* only for IP packets */
2117 				    uint16_t x;
2118 				    uint16_t *p;
2119 				    int i;
2120 
2121 				    if (cmd->opcode == O_IPLEN)
2122 					x = iplen;
2123 				    else if (cmd->opcode == O_IPTTL)
2124 					x = ip->ip_ttl;
2125 				    else /* must be IPID */
2126 					x = ntohs(ip->ip_id);
2127 				    if (cmdlen == 1) {
2128 					match = (cmd->arg1 == x);
2129 					break;
2130 				    }
2131 				    /* otherwise we have ranges */
2132 				    p = ((ipfw_insn_u16 *)cmd)->ports;
2133 				    i = cmdlen - 1;
2134 				    for (; !match && i>0; i--, p += 2)
2135 					match = (x >= p[0] && x <= p[1]);
2136 				}
2137 				break;
2138 
2139 			case O_IPPRECEDENCE:
2140 				match = (is_ipv4 &&
2141 				    (cmd->arg1 == (ip->ip_tos & 0xe0)) );
2142 				break;
2143 
2144 			case O_IPTOS:
2145 				match = (is_ipv4 &&
2146 				    flags_match(cmd, ip->ip_tos));
2147 				break;
2148 
2149 			case O_DSCP:
2150 			    {
2151 				uint32_t *p;
2152 				uint16_t x;
2153 
2154 				p = ((ipfw_insn_u32 *)cmd)->d;
2155 
2156 				if (is_ipv4)
2157 					x = ip->ip_tos >> 2;
2158 				else if (is_ipv6) {
2159 					uint8_t *v;
2160 					v = &((struct ip6_hdr *)ip)->ip6_vfc;
2161 					x = (*v & 0x0F) << 2;
2162 					v++;
2163 					x |= *v >> 6;
2164 				} else
2165 					break;
2166 
2167 				/* DSCP bitmask is stored as low_u32 high_u32 */
2168 				if (x >= 32)
2169 					match = *(p + 1) & (1 << (x - 32));
2170 				else
2171 					match = *p & (1 << x);
2172 			    }
2173 				break;
2174 
2175 			case O_TCPDATALEN:
2176 				if (proto == IPPROTO_TCP && offset == 0) {
2177 				    struct tcphdr *tcp;
2178 				    uint16_t x;
2179 				    uint16_t *p;
2180 				    int i;
2181 #ifdef INET6
2182 				    if (is_ipv6) {
2183 					    struct ip6_hdr *ip6;
2184 
2185 					    ip6 = (struct ip6_hdr *)ip;
2186 					    if (ip6->ip6_plen == 0) {
2187 						    /*
2188 						     * Jumbo payload is not
2189 						     * supported by this
2190 						     * opcode.
2191 						     */
2192 						    break;
2193 					    }
2194 					    x = iplen - hlen;
2195 				    } else
2196 #endif /* INET6 */
2197 					    x = iplen - (ip->ip_hl << 2);
2198 				    tcp = TCP(ulp);
2199 				    x -= tcp->th_off << 2;
2200 				    if (cmdlen == 1) {
2201 					match = (cmd->arg1 == x);
2202 					break;
2203 				    }
2204 				    /* otherwise we have ranges */
2205 				    p = ((ipfw_insn_u16 *)cmd)->ports;
2206 				    i = cmdlen - 1;
2207 				    for (; !match && i>0; i--, p += 2)
2208 					match = (x >= p[0] && x <= p[1]);
2209 				}
2210 				break;
2211 
2212 			case O_TCPFLAGS:
2213 				match = (proto == IPPROTO_TCP && offset == 0 &&
2214 				    flags_match(cmd, TCP(ulp)->th_flags));
2215 				break;
2216 
2217 			case O_TCPOPTS:
2218 				if (proto == IPPROTO_TCP && offset == 0 && ulp){
2219 					PULLUP_LEN(hlen, ulp,
2220 					    (TCP(ulp)->th_off << 2));
2221 					match = tcpopts_match(TCP(ulp), cmd);
2222 				}
2223 				break;
2224 
2225 			case O_TCPSEQ:
2226 				match = (proto == IPPROTO_TCP && offset == 0 &&
2227 				    ((ipfw_insn_u32 *)cmd)->d[0] ==
2228 					TCP(ulp)->th_seq);
2229 				break;
2230 
2231 			case O_TCPACK:
2232 				match = (proto == IPPROTO_TCP && offset == 0 &&
2233 				    ((ipfw_insn_u32 *)cmd)->d[0] ==
2234 					TCP(ulp)->th_ack);
2235 				break;
2236 
2237 			case O_TCPWIN:
2238 				if (proto == IPPROTO_TCP && offset == 0) {
2239 				    uint16_t x;
2240 				    uint16_t *p;
2241 				    int i;
2242 
2243 				    x = ntohs(TCP(ulp)->th_win);
2244 				    if (cmdlen == 1) {
2245 					match = (cmd->arg1 == x);
2246 					break;
2247 				    }
2248 				    /* Otherwise we have ranges. */
2249 				    p = ((ipfw_insn_u16 *)cmd)->ports;
2250 				    i = cmdlen - 1;
2251 				    for (; !match && i > 0; i--, p += 2)
2252 					match = (x >= p[0] && x <= p[1]);
2253 				}
2254 				break;
2255 
2256 			case O_ESTAB:
2257 				/* reject packets which have SYN only */
2258 				/* XXX should i also check for TH_ACK ? */
2259 				match = (proto == IPPROTO_TCP && offset == 0 &&
2260 				    (TCP(ulp)->th_flags &
2261 				     (TH_RST | TH_ACK | TH_SYN)) != TH_SYN);
2262 				break;
2263 
2264 			case O_ALTQ: {
2265 				struct pf_mtag *at;
2266 				struct m_tag *mtag;
2267 				ipfw_insn_altq *altq = (ipfw_insn_altq *)cmd;
2268 
2269 				/*
2270 				 * ALTQ uses mbuf tags from another
2271 				 * packet filtering system - pf(4).
2272 				 * We allocate a tag in its format
2273 				 * and fill it in, pretending to be pf(4).
2274 				 */
2275 				match = 1;
2276 				at = pf_find_mtag(m);
2277 				if (at != NULL && at->qid != 0)
2278 					break;
2279 				mtag = m_tag_get(PACKET_TAG_PF,
2280 				    sizeof(struct pf_mtag), M_NOWAIT | M_ZERO);
2281 				if (mtag == NULL) {
2282 					/*
2283 					 * Let the packet fall back to the
2284 					 * default ALTQ.
2285 					 */
2286 					break;
2287 				}
2288 				m_tag_prepend(m, mtag);
2289 				at = (struct pf_mtag *)(mtag + 1);
2290 				at->qid = altq->qid;
2291 				at->hdr = ip;
2292 				break;
2293 			}
2294 
2295 			case O_LOG:
2296 				ipfw_log(chain, f, hlen, args, m,
2297 				    oif, offset | ip6f_mf, tablearg, ip);
2298 				match = 1;
2299 				break;
2300 
2301 			case O_PROB:
2302 				match = (random()<((ipfw_insn_u32 *)cmd)->d[0]);
2303 				break;
2304 
2305 			case O_VERREVPATH:
2306 				/* Outgoing packets automatically pass/match */
2307 				match = ((oif != NULL) ||
2308 				    (m->m_pkthdr.rcvif == NULL) ||
2309 				    (
2310 #ifdef INET6
2311 				    is_ipv6 ?
2312 					verify_path6(&(args->f_id.src_ip6),
2313 					    m->m_pkthdr.rcvif, args->f_id.fib) :
2314 #endif
2315 				    verify_path(src_ip, m->m_pkthdr.rcvif,
2316 				        args->f_id.fib)));
2317 				break;
2318 
2319 			case O_VERSRCREACH:
2320 				/* Outgoing packets automatically pass/match */
2321 				match = (hlen > 0 && ((oif != NULL) ||
2322 #ifdef INET6
2323 				    is_ipv6 ?
2324 				        verify_path6(&(args->f_id.src_ip6),
2325 				            NULL, args->f_id.fib) :
2326 #endif
2327 				    verify_path(src_ip, NULL, args->f_id.fib)));
2328 				break;
2329 
2330 			case O_ANTISPOOF:
2331 				/* Outgoing packets automatically pass/match */
2332 				if (oif == NULL && hlen > 0 &&
2333 				    (  (is_ipv4 && in_localaddr(src_ip))
2334 #ifdef INET6
2335 				    || (is_ipv6 &&
2336 				        in6_localaddr(&(args->f_id.src_ip6)))
2337 #endif
2338 				    ))
2339 					match =
2340 #ifdef INET6
2341 					    is_ipv6 ? verify_path6(
2342 					        &(args->f_id.src_ip6),
2343 					        m->m_pkthdr.rcvif,
2344 						args->f_id.fib) :
2345 #endif
2346 					    verify_path(src_ip,
2347 					    	m->m_pkthdr.rcvif,
2348 					        args->f_id.fib);
2349 				else
2350 					match = 1;
2351 				break;
2352 
2353 			case O_IPSEC:
2354 				match = (m_tag_find(m,
2355 				    PACKET_TAG_IPSEC_IN_DONE, NULL) != NULL);
2356 				/* otherwise no match */
2357 				break;
2358 
2359 #ifdef INET6
2360 			case O_IP6_SRC:
2361 				match = is_ipv6 &&
2362 				    IN6_ARE_ADDR_EQUAL(&args->f_id.src_ip6,
2363 				    &((ipfw_insn_ip6 *)cmd)->addr6);
2364 				break;
2365 
2366 			case O_IP6_DST:
2367 				match = is_ipv6 &&
2368 				IN6_ARE_ADDR_EQUAL(&args->f_id.dst_ip6,
2369 				    &((ipfw_insn_ip6 *)cmd)->addr6);
2370 				break;
2371 			case O_IP6_SRC_MASK:
2372 			case O_IP6_DST_MASK:
2373 				if (is_ipv6) {
2374 					int i = cmdlen - 1;
2375 					struct in6_addr p;
2376 					struct in6_addr *d =
2377 					    &((ipfw_insn_ip6 *)cmd)->addr6;
2378 
2379 					for (; !match && i > 0; d += 2,
2380 					    i -= F_INSN_SIZE(struct in6_addr)
2381 					    * 2) {
2382 						p = (cmd->opcode ==
2383 						    O_IP6_SRC_MASK) ?
2384 						    args->f_id.src_ip6:
2385 						    args->f_id.dst_ip6;
2386 						APPLY_MASK(&p, &d[1]);
2387 						match =
2388 						    IN6_ARE_ADDR_EQUAL(&d[0],
2389 						    &p);
2390 					}
2391 				}
2392 				break;
2393 
2394 			case O_FLOW6ID:
2395 				match = is_ipv6 &&
2396 				    flow6id_match(args->f_id.flow_id6,
2397 				    (ipfw_insn_u32 *) cmd);
2398 				break;
2399 
2400 			case O_EXT_HDR:
2401 				match = is_ipv6 &&
2402 				    (ext_hd & ((ipfw_insn *) cmd)->arg1);
2403 				break;
2404 
2405 			case O_IP6:
2406 				match = is_ipv6;
2407 				break;
2408 #endif
2409 
2410 			case O_IP4:
2411 				match = is_ipv4;
2412 				break;
2413 
2414 			case O_TAG: {
2415 				struct m_tag *mtag;
2416 				uint32_t tag = TARG(cmd->arg1, tag);
2417 
2418 				/* Packet is already tagged with this tag? */
2419 				mtag = m_tag_locate(m, MTAG_IPFW, tag, NULL);
2420 
2421 				/* We have `untag' action when F_NOT flag is
2422 				 * present. And we must remove this mtag from
2423 				 * mbuf and reset `match' to zero (`match' will
2424 				 * be inversed later).
2425 				 * Otherwise we should allocate new mtag and
2426 				 * push it into mbuf.
2427 				 */
2428 				if (cmd->len & F_NOT) { /* `untag' action */
2429 					if (mtag != NULL)
2430 						m_tag_delete(m, mtag);
2431 					match = 0;
2432 				} else {
2433 					if (mtag == NULL) {
2434 						mtag = m_tag_alloc( MTAG_IPFW,
2435 						    tag, 0, M_NOWAIT);
2436 						if (mtag != NULL)
2437 							m_tag_prepend(m, mtag);
2438 					}
2439 					match = 1;
2440 				}
2441 				break;
2442 			}
2443 
2444 			case O_FIB: /* try match the specified fib */
2445 				if (args->f_id.fib == cmd->arg1)
2446 					match = 1;
2447 				break;
2448 
2449 			case O_SOCKARG:	{
2450 #ifndef USERSPACE	/* not supported in userspace */
2451 				struct inpcb *inp = args->inp;
2452 				struct inpcbinfo *pi;
2453 
2454 				if (is_ipv6) /* XXX can we remove this ? */
2455 					break;
2456 
2457 				if (proto == IPPROTO_TCP)
2458 					pi = &V_tcbinfo;
2459 				else if (proto == IPPROTO_UDP)
2460 					pi = &V_udbinfo;
2461 				else
2462 					break;
2463 
2464 				/*
2465 				 * XXXRW: so_user_cookie should almost
2466 				 * certainly be inp_user_cookie?
2467 				 */
2468 
2469 				/* For incoming packet, lookup up the
2470 				inpcb using the src/dest ip/port tuple */
2471 				if (inp == NULL) {
2472 					inp = in_pcblookup(pi,
2473 						src_ip, htons(src_port),
2474 						dst_ip, htons(dst_port),
2475 						INPLOOKUP_RLOCKPCB, NULL);
2476 					if (inp != NULL) {
2477 						tablearg =
2478 						    inp->inp_socket->so_user_cookie;
2479 						if (tablearg)
2480 							match = 1;
2481 						INP_RUNLOCK(inp);
2482 					}
2483 				} else {
2484 					if (inp->inp_socket) {
2485 						tablearg =
2486 						    inp->inp_socket->so_user_cookie;
2487 						if (tablearg)
2488 							match = 1;
2489 					}
2490 				}
2491 #endif /* !USERSPACE */
2492 				break;
2493 			}
2494 
2495 			case O_TAGGED: {
2496 				struct m_tag *mtag;
2497 				uint32_t tag = TARG(cmd->arg1, tag);
2498 
2499 				if (cmdlen == 1) {
2500 					match = m_tag_locate(m, MTAG_IPFW,
2501 					    tag, NULL) != NULL;
2502 					break;
2503 				}
2504 
2505 				/* we have ranges */
2506 				for (mtag = m_tag_first(m);
2507 				    mtag != NULL && !match;
2508 				    mtag = m_tag_next(m, mtag)) {
2509 					uint16_t *p;
2510 					int i;
2511 
2512 					if (mtag->m_tag_cookie != MTAG_IPFW)
2513 						continue;
2514 
2515 					p = ((ipfw_insn_u16 *)cmd)->ports;
2516 					i = cmdlen - 1;
2517 					for(; !match && i > 0; i--, p += 2)
2518 						match =
2519 						    mtag->m_tag_id >= p[0] &&
2520 						    mtag->m_tag_id <= p[1];
2521 				}
2522 				break;
2523 			}
2524 
2525 			/*
2526 			 * The second set of opcodes represents 'actions',
2527 			 * i.e. the terminal part of a rule once the packet
2528 			 * matches all previous patterns.
2529 			 * Typically there is only one action for each rule,
2530 			 * and the opcode is stored at the end of the rule
2531 			 * (but there are exceptions -- see below).
2532 			 *
2533 			 * In general, here we set retval and terminate the
2534 			 * outer loop (would be a 'break 3' in some language,
2535 			 * but we need to set l=0, done=1)
2536 			 *
2537 			 * Exceptions:
2538 			 * O_COUNT and O_SKIPTO actions:
2539 			 *   instead of terminating, we jump to the next rule
2540 			 *   (setting l=0), or to the SKIPTO target (setting
2541 			 *   f/f_len, cmd and l as needed), respectively.
2542 			 *
2543 			 * O_TAG, O_LOG and O_ALTQ action parameters:
2544 			 *   perform some action and set match = 1;
2545 			 *
2546 			 * O_LIMIT and O_KEEP_STATE: these opcodes are
2547 			 *   not real 'actions', and are stored right
2548 			 *   before the 'action' part of the rule.
2549 			 *   These opcodes try to install an entry in the
2550 			 *   state tables; if successful, we continue with
2551 			 *   the next opcode (match=1; break;), otherwise
2552 			 *   the packet must be dropped (set retval,
2553 			 *   break loops with l=0, done=1)
2554 			 *
2555 			 * O_PROBE_STATE and O_CHECK_STATE: these opcodes
2556 			 *   cause a lookup of the state table, and a jump
2557 			 *   to the 'action' part of the parent rule
2558 			 *   if an entry is found, or
2559 			 *   (CHECK_STATE only) a jump to the next rule if
2560 			 *   the entry is not found.
2561 			 *   The result of the lookup is cached so that
2562 			 *   further instances of these opcodes become NOPs.
2563 			 *   The jump to the next rule is done by setting
2564 			 *   l=0, cmdlen=0.
2565 			 */
2566 			case O_LIMIT:
2567 			case O_KEEP_STATE:
2568 				if (ipfw_dyn_install_state(chain, f,
2569 				    (ipfw_insn_limit *)cmd, args, tablearg)) {
2570 					/* error or limit violation */
2571 					retval = IP_FW_DENY;
2572 					l = 0;	/* exit inner loop */
2573 					done = 1; /* exit outer loop */
2574 				}
2575 				match = 1;
2576 				break;
2577 
2578 			case O_PROBE_STATE:
2579 			case O_CHECK_STATE:
2580 				/*
2581 				 * dynamic rules are checked at the first
2582 				 * keep-state or check-state occurrence,
2583 				 * with the result being stored in dyn_dir
2584 				 * and dyn_name.
2585 				 * The compiler introduces a PROBE_STATE
2586 				 * instruction for us when we have a
2587 				 * KEEP_STATE (because PROBE_STATE needs
2588 				 * to be run first).
2589 				 *
2590 				 * (dyn_dir == MATCH_UNKNOWN) means this is
2591 				 * first lookup for such f_id. Do lookup.
2592 				 *
2593 				 * (dyn_dir != MATCH_UNKNOWN &&
2594 				 *  dyn_name != 0 && dyn_name != cmd->arg1)
2595 				 * means previous lookup didn't find dynamic
2596 				 * rule for specific state name and current
2597 				 * lookup will search rule with another state
2598 				 * name. Redo lookup.
2599 				 *
2600 				 * (dyn_dir != MATCH_UNKNOWN && dyn_name == 0)
2601 				 * means previous lookup was for `any' name
2602 				 * and it didn't find rule. No need to do
2603 				 * lookup again.
2604 				 */
2605 				if ((dyn_dir == MATCH_UNKNOWN ||
2606 				    (dyn_name != 0 &&
2607 				    dyn_name != cmd->arg1)) &&
2608 				    (q = ipfw_dyn_lookup_state(&args->f_id,
2609 				     ulp, pktlen, &dyn_dir,
2610 				     (dyn_name = cmd->arg1))) != NULL) {
2611 					/*
2612 					 * Found dynamic entry, jump to the
2613 					 * 'action' part of the parent rule
2614 					 * by setting f, cmd, l and clearing
2615 					 * cmdlen.
2616 					 */
2617 					f = q;
2618 					/* XXX we would like to have f_pos
2619 					 * readily accessible in the dynamic
2620 				         * rule, instead of having to
2621 					 * lookup q->rule.
2622 					 */
2623 					f_pos = ipfw_find_rule(chain,
2624 					    f->rulenum, f->id);
2625 					cmd = ACTION_PTR(f);
2626 					l = f->cmd_len - f->act_ofs;
2627 					cmdlen = 0;
2628 					match = 1;
2629 					break;
2630 				}
2631 				/*
2632 				 * Dynamic entry not found. If CHECK_STATE,
2633 				 * skip to next rule, if PROBE_STATE just
2634 				 * ignore and continue with next opcode.
2635 				 */
2636 				if (cmd->opcode == O_CHECK_STATE)
2637 					l = 0;	/* exit inner loop */
2638 				match = 1;
2639 				break;
2640 
2641 			case O_ACCEPT:
2642 				retval = 0;	/* accept */
2643 				l = 0;		/* exit inner loop */
2644 				done = 1;	/* exit outer loop */
2645 				break;
2646 
2647 			case O_PIPE:
2648 			case O_QUEUE:
2649 				set_match(args, f_pos, chain);
2650 				args->rule.info = TARG(cmd->arg1, pipe);
2651 				if (cmd->opcode == O_PIPE)
2652 					args->rule.info |= IPFW_IS_PIPE;
2653 				if (V_fw_one_pass)
2654 					args->rule.info |= IPFW_ONEPASS;
2655 				retval = IP_FW_DUMMYNET;
2656 				l = 0;          /* exit inner loop */
2657 				done = 1;       /* exit outer loop */
2658 				break;
2659 
2660 			case O_DIVERT:
2661 			case O_TEE:
2662 				if (args->eh) /* not on layer 2 */
2663 				    break;
2664 				/* otherwise this is terminal */
2665 				l = 0;		/* exit inner loop */
2666 				done = 1;	/* exit outer loop */
2667 				retval = (cmd->opcode == O_DIVERT) ?
2668 					IP_FW_DIVERT : IP_FW_TEE;
2669 				set_match(args, f_pos, chain);
2670 				args->rule.info = TARG(cmd->arg1, divert);
2671 				break;
2672 
2673 			case O_COUNT:
2674 				IPFW_INC_RULE_COUNTER(f, pktlen);
2675 				l = 0;		/* exit inner loop */
2676 				break;
2677 
2678 			case O_SKIPTO:
2679 			    IPFW_INC_RULE_COUNTER(f, pktlen);
2680 			    f_pos = JUMP(chain, f, cmd->arg1, tablearg, 0);
2681 			    /*
2682 			     * Skip disabled rules, and re-enter
2683 			     * the inner loop with the correct
2684 			     * f_pos, f, l and cmd.
2685 			     * Also clear cmdlen and skip_or
2686 			     */
2687 			    for (; f_pos < chain->n_rules - 1 &&
2688 				    (V_set_disable &
2689 				     (1 << chain->map[f_pos]->set));
2690 				    f_pos++)
2691 				;
2692 			    /* Re-enter the inner loop at the skipto rule. */
2693 			    f = chain->map[f_pos];
2694 			    l = f->cmd_len;
2695 			    cmd = f->cmd;
2696 			    match = 1;
2697 			    cmdlen = 0;
2698 			    skip_or = 0;
2699 			    continue;
2700 			    break;	/* not reached */
2701 
2702 			case O_CALLRETURN: {
2703 				/*
2704 				 * Implementation of `subroutine' call/return,
2705 				 * in the stack carried in an mbuf tag. This
2706 				 * is different from `skipto' in that any call
2707 				 * address is possible (`skipto' must prevent
2708 				 * backward jumps to avoid endless loops).
2709 				 * We have `return' action when F_NOT flag is
2710 				 * present. The `m_tag_id' field is used as
2711 				 * stack pointer.
2712 				 */
2713 				struct m_tag *mtag;
2714 				uint16_t jmpto, *stack;
2715 
2716 #define	IS_CALL		((cmd->len & F_NOT) == 0)
2717 #define	IS_RETURN	((cmd->len & F_NOT) != 0)
2718 				/*
2719 				 * Hand-rolled version of m_tag_locate() with
2720 				 * wildcard `type'.
2721 				 * If not already tagged, allocate new tag.
2722 				 */
2723 				mtag = m_tag_first(m);
2724 				while (mtag != NULL) {
2725 					if (mtag->m_tag_cookie ==
2726 					    MTAG_IPFW_CALL)
2727 						break;
2728 					mtag = m_tag_next(m, mtag);
2729 				}
2730 				if (mtag == NULL && IS_CALL) {
2731 					mtag = m_tag_alloc(MTAG_IPFW_CALL, 0,
2732 					    IPFW_CALLSTACK_SIZE *
2733 					    sizeof(uint16_t), M_NOWAIT);
2734 					if (mtag != NULL)
2735 						m_tag_prepend(m, mtag);
2736 				}
2737 
2738 				/*
2739 				 * On error both `call' and `return' just
2740 				 * continue with next rule.
2741 				 */
2742 				if (IS_RETURN && (mtag == NULL ||
2743 				    mtag->m_tag_id == 0)) {
2744 					l = 0;		/* exit inner loop */
2745 					break;
2746 				}
2747 				if (IS_CALL && (mtag == NULL ||
2748 				    mtag->m_tag_id >= IPFW_CALLSTACK_SIZE)) {
2749 					printf("ipfw: call stack error, "
2750 					    "go to next rule\n");
2751 					l = 0;		/* exit inner loop */
2752 					break;
2753 				}
2754 
2755 				IPFW_INC_RULE_COUNTER(f, pktlen);
2756 				stack = (uint16_t *)(mtag + 1);
2757 
2758 				/*
2759 				 * The `call' action may use cached f_pos
2760 				 * (in f->next_rule), whose version is written
2761 				 * in f->next_rule.
2762 				 * The `return' action, however, doesn't have
2763 				 * fixed jump address in cmd->arg1 and can't use
2764 				 * cache.
2765 				 */
2766 				if (IS_CALL) {
2767 					stack[mtag->m_tag_id] = f->rulenum;
2768 					mtag->m_tag_id++;
2769 			    		f_pos = JUMP(chain, f, cmd->arg1,
2770 					    tablearg, 1);
2771 				} else {	/* `return' action */
2772 					mtag->m_tag_id--;
2773 					jmpto = stack[mtag->m_tag_id] + 1;
2774 					f_pos = ipfw_find_rule(chain, jmpto, 0);
2775 				}
2776 
2777 				/*
2778 				 * Skip disabled rules, and re-enter
2779 				 * the inner loop with the correct
2780 				 * f_pos, f, l and cmd.
2781 				 * Also clear cmdlen and skip_or
2782 				 */
2783 				for (; f_pos < chain->n_rules - 1 &&
2784 				    (V_set_disable &
2785 				    (1 << chain->map[f_pos]->set)); f_pos++)
2786 					;
2787 				/* Re-enter the inner loop at the dest rule. */
2788 				f = chain->map[f_pos];
2789 				l = f->cmd_len;
2790 				cmd = f->cmd;
2791 				cmdlen = 0;
2792 				skip_or = 0;
2793 				continue;
2794 				break;	/* NOTREACHED */
2795 			}
2796 #undef IS_CALL
2797 #undef IS_RETURN
2798 
2799 			case O_REJECT:
2800 				/*
2801 				 * Drop the packet and send a reject notice
2802 				 * if the packet is not ICMP (or is an ICMP
2803 				 * query), and it is not multicast/broadcast.
2804 				 */
2805 				if (hlen > 0 && is_ipv4 && offset == 0 &&
2806 				    (proto != IPPROTO_ICMP ||
2807 				     is_icmp_query(ICMP(ulp))) &&
2808 				    !(m->m_flags & (M_BCAST|M_MCAST)) &&
2809 				    !IN_MULTICAST(ntohl(dst_ip.s_addr))) {
2810 					send_reject(args, cmd->arg1, iplen, ip);
2811 					m = args->m;
2812 				}
2813 				/* FALLTHROUGH */
2814 #ifdef INET6
2815 			case O_UNREACH6:
2816 				if (hlen > 0 && is_ipv6 &&
2817 				    ((offset & IP6F_OFF_MASK) == 0) &&
2818 				    (proto != IPPROTO_ICMPV6 ||
2819 				     (is_icmp6_query(icmp6_type) == 1)) &&
2820 				    !(m->m_flags & (M_BCAST|M_MCAST)) &&
2821 				    !IN6_IS_ADDR_MULTICAST(&args->f_id.dst_ip6)) {
2822 					send_reject6(
2823 					    args, cmd->arg1, hlen,
2824 					    (struct ip6_hdr *)ip);
2825 					m = args->m;
2826 				}
2827 				/* FALLTHROUGH */
2828 #endif
2829 			case O_DENY:
2830 				retval = IP_FW_DENY;
2831 				l = 0;		/* exit inner loop */
2832 				done = 1;	/* exit outer loop */
2833 				break;
2834 
2835 			case O_FORWARD_IP:
2836 				if (args->eh)	/* not valid on layer2 pkts */
2837 					break;
2838 				if (q != f || dyn_dir == MATCH_FORWARD) {
2839 				    struct sockaddr_in *sa;
2840 
2841 				    sa = &(((ipfw_insn_sa *)cmd)->sa);
2842 				    if (sa->sin_addr.s_addr == INADDR_ANY) {
2843 #ifdef INET6
2844 					/*
2845 					 * We use O_FORWARD_IP opcode for
2846 					 * fwd rule with tablearg, but tables
2847 					 * now support IPv6 addresses. And
2848 					 * when we are inspecting IPv6 packet,
2849 					 * we can use nh6 field from
2850 					 * table_value as next_hop6 address.
2851 					 */
2852 					if (is_ipv6) {
2853 						struct sockaddr_in6 *sa6;
2854 
2855 						sa6 = args->next_hop6 =
2856 						    &args->hopstore6;
2857 						sa6->sin6_family = AF_INET6;
2858 						sa6->sin6_len = sizeof(*sa6);
2859 						sa6->sin6_addr = TARG_VAL(
2860 						    chain, tablearg, nh6);
2861 						sa6->sin6_port = sa->sin_port;
2862 						/*
2863 						 * Set sin6_scope_id only for
2864 						 * link-local unicast addresses.
2865 						 */
2866 						if (IN6_IS_ADDR_LINKLOCAL(
2867 						    &sa6->sin6_addr))
2868 							sa6->sin6_scope_id =
2869 							    TARG_VAL(chain,
2870 								tablearg,
2871 								zoneid);
2872 					} else
2873 #endif
2874 					{
2875 						args->hopstore.sin_port =
2876 						    sa->sin_port;
2877 						sa = args->next_hop =
2878 						    &args->hopstore;
2879 						sa->sin_family = AF_INET;
2880 						sa->sin_len = sizeof(*sa);
2881 						sa->sin_addr.s_addr = htonl(
2882 						    TARG_VAL(chain, tablearg,
2883 						    nh4));
2884 					}
2885 				    } else {
2886 					args->next_hop = sa;
2887 				    }
2888 				}
2889 				retval = IP_FW_PASS;
2890 				l = 0;          /* exit inner loop */
2891 				done = 1;       /* exit outer loop */
2892 				break;
2893 
2894 #ifdef INET6
2895 			case O_FORWARD_IP6:
2896 				if (args->eh)	/* not valid on layer2 pkts */
2897 					break;
2898 				if (q != f || dyn_dir == MATCH_FORWARD) {
2899 					struct sockaddr_in6 *sin6;
2900 
2901 					sin6 = &(((ipfw_insn_sa6 *)cmd)->sa);
2902 					args->next_hop6 = sin6;
2903 				}
2904 				retval = IP_FW_PASS;
2905 				l = 0;		/* exit inner loop */
2906 				done = 1;	/* exit outer loop */
2907 				break;
2908 #endif
2909 
2910 			case O_NETGRAPH:
2911 			case O_NGTEE:
2912 				set_match(args, f_pos, chain);
2913 				args->rule.info = TARG(cmd->arg1, netgraph);
2914 				if (V_fw_one_pass)
2915 					args->rule.info |= IPFW_ONEPASS;
2916 				retval = (cmd->opcode == O_NETGRAPH) ?
2917 				    IP_FW_NETGRAPH : IP_FW_NGTEE;
2918 				l = 0;          /* exit inner loop */
2919 				done = 1;       /* exit outer loop */
2920 				break;
2921 
2922 			case O_SETFIB: {
2923 				uint32_t fib;
2924 
2925 				IPFW_INC_RULE_COUNTER(f, pktlen);
2926 				fib = TARG(cmd->arg1, fib) & 0x7FFF;
2927 				if (fib >= rt_numfibs)
2928 					fib = 0;
2929 				M_SETFIB(m, fib);
2930 				args->f_id.fib = fib;
2931 				l = 0;		/* exit inner loop */
2932 				break;
2933 		        }
2934 
2935 			case O_SETDSCP: {
2936 				uint16_t code;
2937 
2938 				code = TARG(cmd->arg1, dscp) & 0x3F;
2939 				l = 0;		/* exit inner loop */
2940 				if (is_ipv4) {
2941 					uint16_t old;
2942 
2943 					old = *(uint16_t *)ip;
2944 					ip->ip_tos = (code << 2) |
2945 					    (ip->ip_tos & 0x03);
2946 					ip->ip_sum = cksum_adjust(ip->ip_sum,
2947 					    old, *(uint16_t *)ip);
2948 				} else if (is_ipv6) {
2949 					uint8_t *v;
2950 
2951 					v = &((struct ip6_hdr *)ip)->ip6_vfc;
2952 					*v = (*v & 0xF0) | (code >> 2);
2953 					v++;
2954 					*v = (*v & 0x3F) | ((code & 0x03) << 6);
2955 				} else
2956 					break;
2957 
2958 				IPFW_INC_RULE_COUNTER(f, pktlen);
2959 				break;
2960 			}
2961 
2962 			case O_NAT:
2963 				l = 0;          /* exit inner loop */
2964 				done = 1;       /* exit outer loop */
2965 				/*
2966 				 * Ensure that we do not invoke NAT handler for
2967 				 * non IPv4 packets. Libalias expects only IPv4.
2968 				 */
2969 				if (!is_ipv4 || !IPFW_NAT_LOADED) {
2970 				    retval = IP_FW_DENY;
2971 				    break;
2972 				}
2973 
2974 				struct cfg_nat *t;
2975 				int nat_id;
2976 
2977 				set_match(args, f_pos, chain);
2978 				/* Check if this is 'global' nat rule */
2979 				if (cmd->arg1 == IP_FW_NAT44_GLOBAL) {
2980 					retval = ipfw_nat_ptr(args, NULL, m);
2981 					break;
2982 				}
2983 				t = ((ipfw_insn_nat *)cmd)->nat;
2984 				if (t == NULL) {
2985 					nat_id = TARG(cmd->arg1, nat);
2986 					t = (*lookup_nat_ptr)(&chain->nat, nat_id);
2987 
2988 					if (t == NULL) {
2989 					    retval = IP_FW_DENY;
2990 					    break;
2991 					}
2992 					if (cmd->arg1 != IP_FW_TARG)
2993 					    ((ipfw_insn_nat *)cmd)->nat = t;
2994 				}
2995 				retval = ipfw_nat_ptr(args, t, m);
2996 				break;
2997 
2998 			case O_REASS: {
2999 				int ip_off;
3000 
3001 				IPFW_INC_RULE_COUNTER(f, pktlen);
3002 				l = 0;	/* in any case exit inner loop */
3003 				ip_off = ntohs(ip->ip_off);
3004 
3005 				/* if not fragmented, go to next rule */
3006 				if ((ip_off & (IP_MF | IP_OFFMASK)) == 0)
3007 				    break;
3008 
3009 				args->m = m = ip_reass(m);
3010 
3011 				/*
3012 				 * do IP header checksum fixup.
3013 				 */
3014 				if (m == NULL) { /* fragment got swallowed */
3015 				    retval = IP_FW_DENY;
3016 				} else { /* good, packet complete */
3017 				    int hlen;
3018 
3019 				    ip = mtod(m, struct ip *);
3020 				    hlen = ip->ip_hl << 2;
3021 				    ip->ip_sum = 0;
3022 				    if (hlen == sizeof(struct ip))
3023 					ip->ip_sum = in_cksum_hdr(ip);
3024 				    else
3025 					ip->ip_sum = in_cksum(m, hlen);
3026 				    retval = IP_FW_REASS;
3027 				    set_match(args, f_pos, chain);
3028 				}
3029 				done = 1;	/* exit outer loop */
3030 				break;
3031 			}
3032 			case O_EXTERNAL_ACTION:
3033 				l = 0; /* in any case exit inner loop */
3034 				retval = ipfw_run_eaction(chain, args,
3035 				    cmd, &done);
3036 				/*
3037 				 * If both @retval and @done are zero,
3038 				 * consider this as rule matching and
3039 				 * update counters.
3040 				 */
3041 				if (retval == 0 && done == 0) {
3042 					IPFW_INC_RULE_COUNTER(f, pktlen);
3043 					/*
3044 					 * Reset the result of the last
3045 					 * dynamic state lookup.
3046 					 * External action can change
3047 					 * @args content, and it may be
3048 					 * used for new state lookup later.
3049 					 */
3050 					dyn_dir = MATCH_UNKNOWN;
3051 				}
3052 				break;
3053 
3054 			default:
3055 				panic("-- unknown opcode %d\n", cmd->opcode);
3056 			} /* end of switch() on opcodes */
3057 			/*
3058 			 * if we get here with l=0, then match is irrelevant.
3059 			 */
3060 
3061 			if (cmd->len & F_NOT)
3062 				match = !match;
3063 
3064 			if (match) {
3065 				if (cmd->len & F_OR)
3066 					skip_or = 1;
3067 			} else {
3068 				if (!(cmd->len & F_OR)) /* not an OR block, */
3069 					break;		/* try next rule    */
3070 			}
3071 
3072 		}	/* end of inner loop, scan opcodes */
3073 #undef PULLUP_LEN
3074 
3075 		if (done)
3076 			break;
3077 
3078 /* next_rule:; */	/* try next rule		*/
3079 
3080 	}		/* end of outer for, scan rules */
3081 
3082 	if (done) {
3083 		struct ip_fw *rule = chain->map[f_pos];
3084 		/* Update statistics */
3085 		IPFW_INC_RULE_COUNTER(rule, pktlen);
3086 	} else {
3087 		retval = IP_FW_DENY;
3088 		printf("ipfw: ouch!, skip past end of rules, denying packet\n");
3089 	}
3090 	IPFW_PF_RUNLOCK(chain);
3091 #ifdef __FreeBSD__
3092 	if (ucred_cache != NULL)
3093 		crfree(ucred_cache);
3094 #endif
3095 	return (retval);
3096 
3097 pullup_failed:
3098 	if (V_fw_verbose)
3099 		printf("ipfw: pullup failed\n");
3100 	return (IP_FW_DENY);
3101 }
3102 
3103 /*
3104  * Set maximum number of tables that can be used in given VNET ipfw instance.
3105  */
3106 #ifdef SYSCTL_NODE
3107 static int
3108 sysctl_ipfw_table_num(SYSCTL_HANDLER_ARGS)
3109 {
3110 	int error;
3111 	unsigned int ntables;
3112 
3113 	ntables = V_fw_tables_max;
3114 
3115 	error = sysctl_handle_int(oidp, &ntables, 0, req);
3116 	/* Read operation or some error */
3117 	if ((error != 0) || (req->newptr == NULL))
3118 		return (error);
3119 
3120 	return (ipfw_resize_tables(&V_layer3_chain, ntables));
3121 }
3122 
3123 /*
3124  * Switches table namespace between global and per-set.
3125  */
3126 static int
3127 sysctl_ipfw_tables_sets(SYSCTL_HANDLER_ARGS)
3128 {
3129 	int error;
3130 	unsigned int sets;
3131 
3132 	sets = V_fw_tables_sets;
3133 
3134 	error = sysctl_handle_int(oidp, &sets, 0, req);
3135 	/* Read operation or some error */
3136 	if ((error != 0) || (req->newptr == NULL))
3137 		return (error);
3138 
3139 	return (ipfw_switch_tables_namespace(&V_layer3_chain, sets));
3140 }
3141 #endif
3142 
3143 /*
3144  * Module and VNET glue
3145  */
3146 
3147 /*
3148  * Stuff that must be initialised only on boot or module load
3149  */
3150 static int
3151 ipfw_init(void)
3152 {
3153 	int error = 0;
3154 
3155 	/*
3156  	 * Only print out this stuff the first time around,
3157 	 * when called from the sysinit code.
3158 	 */
3159 	printf("ipfw2 "
3160 #ifdef INET6
3161 		"(+ipv6) "
3162 #endif
3163 		"initialized, divert %s, nat %s, "
3164 		"default to %s, logging ",
3165 #ifdef IPDIVERT
3166 		"enabled",
3167 #else
3168 		"loadable",
3169 #endif
3170 #ifdef IPFIREWALL_NAT
3171 		"enabled",
3172 #else
3173 		"loadable",
3174 #endif
3175 		default_to_accept ? "accept" : "deny");
3176 
3177 	/*
3178 	 * Note: V_xxx variables can be accessed here but the vnet specific
3179 	 * initializer may not have been called yet for the VIMAGE case.
3180 	 * Tuneables will have been processed. We will print out values for
3181 	 * the default vnet.
3182 	 * XXX This should all be rationalized AFTER 8.0
3183 	 */
3184 	if (V_fw_verbose == 0)
3185 		printf("disabled\n");
3186 	else if (V_verbose_limit == 0)
3187 		printf("unlimited\n");
3188 	else
3189 		printf("limited to %d packets/entry by default\n",
3190 		    V_verbose_limit);
3191 
3192 	/* Check user-supplied table count for validness */
3193 	if (default_fw_tables > IPFW_TABLES_MAX)
3194 	  default_fw_tables = IPFW_TABLES_MAX;
3195 
3196 	ipfw_init_sopt_handler();
3197 	ipfw_init_obj_rewriter();
3198 	ipfw_iface_init();
3199 	return (error);
3200 }
3201 
3202 /*
3203  * Called for the removal of the last instance only on module unload.
3204  */
3205 static void
3206 ipfw_destroy(void)
3207 {
3208 
3209 	ipfw_iface_destroy();
3210 	ipfw_destroy_sopt_handler();
3211 	ipfw_destroy_obj_rewriter();
3212 	printf("IP firewall unloaded\n");
3213 }
3214 
3215 /*
3216  * Stuff that must be initialized for every instance
3217  * (including the first of course).
3218  */
3219 static int
3220 vnet_ipfw_init(const void *unused)
3221 {
3222 	int error, first;
3223 	struct ip_fw *rule = NULL;
3224 	struct ip_fw_chain *chain;
3225 
3226 	chain = &V_layer3_chain;
3227 
3228 	first = IS_DEFAULT_VNET(curvnet) ? 1 : 0;
3229 
3230 	/* First set up some values that are compile time options */
3231 	V_autoinc_step = 100;	/* bounded to 1..1000 in add_rule() */
3232 	V_fw_deny_unknown_exthdrs = 1;
3233 #ifdef IPFIREWALL_VERBOSE
3234 	V_fw_verbose = 1;
3235 #endif
3236 #ifdef IPFIREWALL_VERBOSE_LIMIT
3237 	V_verbose_limit = IPFIREWALL_VERBOSE_LIMIT;
3238 #endif
3239 #ifdef IPFIREWALL_NAT
3240 	LIST_INIT(&chain->nat);
3241 #endif
3242 
3243 	/* Init shared services hash table */
3244 	ipfw_init_srv(chain);
3245 
3246 	ipfw_init_counters();
3247 	/* Set initial number of tables */
3248 	V_fw_tables_max = default_fw_tables;
3249 	error = ipfw_init_tables(chain, first);
3250 	if (error) {
3251 		printf("ipfw2: setting up tables failed\n");
3252 		free(chain->map, M_IPFW);
3253 		free(rule, M_IPFW);
3254 		return (ENOSPC);
3255 	}
3256 
3257 	IPFW_LOCK_INIT(chain);
3258 
3259 	/* fill and insert the default rule */
3260 	rule = ipfw_alloc_rule(chain, sizeof(struct ip_fw));
3261 	rule->cmd_len = 1;
3262 	rule->cmd[0].len = 1;
3263 	rule->cmd[0].opcode = default_to_accept ? O_ACCEPT : O_DENY;
3264 	chain->default_rule = rule;
3265 	ipfw_add_protected_rule(chain, rule, 0);
3266 
3267 	ipfw_dyn_init(chain);
3268 	ipfw_eaction_init(chain, first);
3269 #ifdef LINEAR_SKIPTO
3270 	ipfw_init_skipto_cache(chain);
3271 #endif
3272 	ipfw_bpf_init(first);
3273 
3274 	/* First set up some values that are compile time options */
3275 	V_ipfw_vnet_ready = 1;		/* Open for business */
3276 
3277 	/*
3278 	 * Hook the sockopt handler and pfil hooks for ipv4 and ipv6.
3279 	 * Even if the latter two fail we still keep the module alive
3280 	 * because the sockopt and layer2 paths are still useful.
3281 	 * ipfw[6]_hook return 0 on success, ENOENT on failure,
3282 	 * so we can ignore the exact return value and just set a flag.
3283 	 *
3284 	 * Note that V_fw[6]_enable are manipulated by a SYSCTL_PROC so
3285 	 * changes in the underlying (per-vnet) variables trigger
3286 	 * immediate hook()/unhook() calls.
3287 	 * In layer2 we have the same behaviour, except that V_ether_ipfw
3288 	 * is checked on each packet because there are no pfil hooks.
3289 	 */
3290 	V_ip_fw_ctl_ptr = ipfw_ctl3;
3291 	error = ipfw_attach_hooks(1);
3292 	return (error);
3293 }
3294 
3295 /*
3296  * Called for the removal of each instance.
3297  */
3298 static int
3299 vnet_ipfw_uninit(const void *unused)
3300 {
3301 	struct ip_fw *reap;
3302 	struct ip_fw_chain *chain = &V_layer3_chain;
3303 	int i, last;
3304 
3305 	V_ipfw_vnet_ready = 0; /* tell new callers to go away */
3306 	/*
3307 	 * disconnect from ipv4, ipv6, layer2 and sockopt.
3308 	 * Then grab, release and grab again the WLOCK so we make
3309 	 * sure the update is propagated and nobody will be in.
3310 	 */
3311 	(void)ipfw_attach_hooks(0 /* detach */);
3312 	V_ip_fw_ctl_ptr = NULL;
3313 
3314 	last = IS_DEFAULT_VNET(curvnet) ? 1 : 0;
3315 
3316 	IPFW_UH_WLOCK(chain);
3317 	IPFW_UH_WUNLOCK(chain);
3318 
3319 	ipfw_dyn_uninit(0);	/* run the callout_drain */
3320 
3321 	IPFW_UH_WLOCK(chain);
3322 
3323 	reap = NULL;
3324 	IPFW_WLOCK(chain);
3325 	for (i = 0; i < chain->n_rules; i++)
3326 		ipfw_reap_add(chain, &reap, chain->map[i]);
3327 	free(chain->map, M_IPFW);
3328 #ifdef LINEAR_SKIPTO
3329 	ipfw_destroy_skipto_cache(chain);
3330 #endif
3331 	IPFW_WUNLOCK(chain);
3332 	IPFW_UH_WUNLOCK(chain);
3333 	ipfw_destroy_tables(chain, last);
3334 	ipfw_eaction_uninit(chain, last);
3335 	if (reap != NULL)
3336 		ipfw_reap_rules(reap);
3337 	vnet_ipfw_iface_destroy(chain);
3338 	ipfw_destroy_srv(chain);
3339 	IPFW_LOCK_DESTROY(chain);
3340 	ipfw_dyn_uninit(1);	/* free the remaining parts */
3341 	ipfw_destroy_counters();
3342 	ipfw_bpf_uninit(last);
3343 	return (0);
3344 }
3345 
3346 /*
3347  * Module event handler.
3348  * In general we have the choice of handling most of these events by the
3349  * event handler or by the (VNET_)SYS(UN)INIT handlers. I have chosen to
3350  * use the SYSINIT handlers as they are more capable of expressing the
3351  * flow of control during module and vnet operations, so this is just
3352  * a skeleton. Note there is no SYSINIT equivalent of the module
3353  * SHUTDOWN handler, but we don't have anything to do in that case anyhow.
3354  */
3355 static int
3356 ipfw_modevent(module_t mod, int type, void *unused)
3357 {
3358 	int err = 0;
3359 
3360 	switch (type) {
3361 	case MOD_LOAD:
3362 		/* Called once at module load or
3363 	 	 * system boot if compiled in. */
3364 		break;
3365 	case MOD_QUIESCE:
3366 		/* Called before unload. May veto unloading. */
3367 		break;
3368 	case MOD_UNLOAD:
3369 		/* Called during unload. */
3370 		break;
3371 	case MOD_SHUTDOWN:
3372 		/* Called during system shutdown. */
3373 		break;
3374 	default:
3375 		err = EOPNOTSUPP;
3376 		break;
3377 	}
3378 	return err;
3379 }
3380 
3381 static moduledata_t ipfwmod = {
3382 	"ipfw",
3383 	ipfw_modevent,
3384 	0
3385 };
3386 
3387 /* Define startup order. */
3388 #define	IPFW_SI_SUB_FIREWALL	SI_SUB_PROTO_FIREWALL
3389 #define	IPFW_MODEVENT_ORDER	(SI_ORDER_ANY - 255) /* On boot slot in here. */
3390 #define	IPFW_MODULE_ORDER	(IPFW_MODEVENT_ORDER + 1) /* A little later. */
3391 #define	IPFW_VNET_ORDER		(IPFW_MODEVENT_ORDER + 2) /* Later still. */
3392 
3393 DECLARE_MODULE(ipfw, ipfwmod, IPFW_SI_SUB_FIREWALL, IPFW_MODEVENT_ORDER);
3394 FEATURE(ipfw_ctl3, "ipfw new sockopt calls");
3395 MODULE_VERSION(ipfw, 3);
3396 /* should declare some dependencies here */
3397 
3398 /*
3399  * Starting up. Done in order after ipfwmod() has been called.
3400  * VNET_SYSINIT is also called for each existing vnet and each new vnet.
3401  */
3402 SYSINIT(ipfw_init, IPFW_SI_SUB_FIREWALL, IPFW_MODULE_ORDER,
3403 	    ipfw_init, NULL);
3404 VNET_SYSINIT(vnet_ipfw_init, IPFW_SI_SUB_FIREWALL, IPFW_VNET_ORDER,
3405 	    vnet_ipfw_init, NULL);
3406 
3407 /*
3408  * Closing up shop. These are done in REVERSE ORDER, but still
3409  * after ipfwmod() has been called. Not called on reboot.
3410  * VNET_SYSUNINIT is also called for each exiting vnet as it exits.
3411  * or when the module is unloaded.
3412  */
3413 SYSUNINIT(ipfw_destroy, IPFW_SI_SUB_FIREWALL, IPFW_MODULE_ORDER,
3414 	    ipfw_destroy, NULL);
3415 VNET_SYSUNINIT(vnet_ipfw_uninit, IPFW_SI_SUB_FIREWALL, IPFW_VNET_ORDER,
3416 	    vnet_ipfw_uninit, NULL);
3417 /* end of file */
3418