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