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