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