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