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