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