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