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