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