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