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