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