2 * Copyright (c) 2002-2009 Luigi Rizzo, Universita` di Pisa
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
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.
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
26 #include <sys/cdefs.h>
27 __FBSDID("$FreeBSD$");
30 * The FreeBSD IP packet firewall, main file
34 #include "opt_ipdivert.h"
37 #error IPFIREWALL requires INET.
39 #include "opt_inet6.h"
40 #include "opt_ipsec.h"
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>
48 #include <sys/kernel.h>
51 #include <sys/module.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 */
62 #include <net/route.h>
63 #include <net/pf_mtag.h>
67 #include <netinet/in.h>
68 #include <netinet/in_var.h>
69 #include <netinet/in_pcb.h>
70 #include <netinet/ip.h>
71 #include <netinet/ip_var.h>
72 #include <netinet/ip_icmp.h>
73 #include <netinet/ip_fw.h>
74 #include <netinet/ip_carp.h>
75 #include <netinet/pim.h>
76 #include <netinet/tcp_var.h>
77 #include <netinet/udp.h>
78 #include <netinet/udp_var.h>
79 #include <netinet/sctp.h>
81 #include <netinet/ip6.h>
82 #include <netinet/icmp6.h>
84 #include <netinet6/in6_pcb.h>
85 #include <netinet6/scope6_var.h>
86 #include <netinet6/ip6_var.h>
89 #include <net/if_gre.h> /* for struct gre_h */
91 #include <netpfil/ipfw/ip_fw_private.h>
93 #include <machine/in_cksum.h> /* XXX for in_cksum */
96 #include <security/mac/mac_framework.h>
100 * static variables followed by global ones.
101 * All ipfw global variables are here.
104 /* ipfw_vnet_ready controls when we are open for business */
105 static VNET_DEFINE(int, ipfw_vnet_ready) = 0;
106 #define V_ipfw_vnet_ready VNET(ipfw_vnet_ready)
108 static VNET_DEFINE(int, fw_deny_unknown_exthdrs);
109 #define V_fw_deny_unknown_exthdrs VNET(fw_deny_unknown_exthdrs)
111 static VNET_DEFINE(int, fw_permit_single_frag6) = 1;
112 #define V_fw_permit_single_frag6 VNET(fw_permit_single_frag6)
114 #ifdef IPFIREWALL_DEFAULT_TO_ACCEPT
115 static int default_to_accept = 1;
117 static int default_to_accept;
120 VNET_DEFINE(int, autoinc_step);
121 VNET_DEFINE(int, fw_one_pass) = 1;
123 VNET_DEFINE(unsigned int, fw_tables_max);
124 /* Use 128 tables by default */
125 static unsigned int default_fw_tables = IPFW_TABLES_DEFAULT;
128 * Each rule belongs to one of 32 different sets (0..31).
129 * The variable set_disable contains one bit per set.
130 * If the bit is set, all rules in the corresponding set
131 * are disabled. Set RESVD_SET(31) is reserved for the default rule
132 * and rules that are not deleted by the flush command,
133 * and CANNOT be disabled.
134 * Rules in set RESVD_SET can only be deleted individually.
136 VNET_DEFINE(u_int32_t, set_disable);
137 #define V_set_disable VNET(set_disable)
139 VNET_DEFINE(int, fw_verbose);
140 /* counter for ipfw_log(NULL...) */
141 VNET_DEFINE(u_int64_t, norule_counter);
142 VNET_DEFINE(int, verbose_limit);
144 /* layer3_chain contains the list of rules for layer 3 */
145 VNET_DEFINE(struct ip_fw_chain, layer3_chain);
147 VNET_DEFINE(int, ipfw_nat_ready) = 0;
149 ipfw_nat_t *ipfw_nat_ptr = NULL;
150 struct cfg_nat *(*lookup_nat_ptr)(struct nat_list *, int);
151 ipfw_nat_cfg_t *ipfw_nat_cfg_ptr;
152 ipfw_nat_cfg_t *ipfw_nat_del_ptr;
153 ipfw_nat_cfg_t *ipfw_nat_get_cfg_ptr;
154 ipfw_nat_cfg_t *ipfw_nat_get_log_ptr;
157 uint32_t dummy_def = IPFW_DEFAULT_RULE;
158 static int sysctl_ipfw_table_num(SYSCTL_HANDLER_ARGS);
162 SYSCTL_NODE(_net_inet_ip, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall");
163 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, one_pass,
164 CTLFLAG_RW | CTLFLAG_SECURE3, &VNET_NAME(fw_one_pass), 0,
165 "Only do a single pass through ipfw when using dummynet(4)");
166 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, autoinc_step,
167 CTLFLAG_RW, &VNET_NAME(autoinc_step), 0,
168 "Rule number auto-increment step");
169 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, verbose,
170 CTLFLAG_RW | CTLFLAG_SECURE3, &VNET_NAME(fw_verbose), 0,
171 "Log matches to ipfw rules");
172 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, verbose_limit,
173 CTLFLAG_RW, &VNET_NAME(verbose_limit), 0,
174 "Set upper limit of matches of ipfw rules logged");
175 SYSCTL_UINT(_net_inet_ip_fw, OID_AUTO, default_rule, CTLFLAG_RD,
177 "The default/max possible rule number.");
178 SYSCTL_VNET_PROC(_net_inet_ip_fw, OID_AUTO, tables_max,
179 CTLTYPE_UINT|CTLFLAG_RW, 0, 0, sysctl_ipfw_table_num, "IU",
180 "Maximum number of tables");
181 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, default_to_accept, CTLFLAG_RDTUN,
182 &default_to_accept, 0,
183 "Make the default rule accept all packets.");
184 TUNABLE_INT("net.inet.ip.fw.default_to_accept", &default_to_accept);
185 TUNABLE_INT("net.inet.ip.fw.tables_max", &default_fw_tables);
186 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, static_count,
187 CTLFLAG_RD, &VNET_NAME(layer3_chain.n_rules), 0,
188 "Number of static rules");
191 SYSCTL_DECL(_net_inet6_ip6);
192 SYSCTL_NODE(_net_inet6_ip6, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall");
193 SYSCTL_VNET_INT(_net_inet6_ip6_fw, OID_AUTO, deny_unknown_exthdrs,
194 CTLFLAG_RW | CTLFLAG_SECURE, &VNET_NAME(fw_deny_unknown_exthdrs), 0,
195 "Deny packets with unknown IPv6 Extension Headers");
196 SYSCTL_VNET_INT(_net_inet6_ip6_fw, OID_AUTO, permit_single_frag6,
197 CTLFLAG_RW | CTLFLAG_SECURE, &VNET_NAME(fw_permit_single_frag6), 0,
198 "Permit single packet IPv6 fragments");
203 #endif /* SYSCTL_NODE */
207 * Some macros used in the various matching options.
208 * L3HDR maps an ipv4 pointer into a layer3 header pointer of type T
209 * Other macros just cast void * into the appropriate type
211 #define L3HDR(T, ip) ((T *)((u_int32_t *)(ip) + (ip)->ip_hl))
212 #define TCP(p) ((struct tcphdr *)(p))
213 #define SCTP(p) ((struct sctphdr *)(p))
214 #define UDP(p) ((struct udphdr *)(p))
215 #define ICMP(p) ((struct icmphdr *)(p))
216 #define ICMP6(p) ((struct icmp6_hdr *)(p))
219 icmptype_match(struct icmphdr *icmp, ipfw_insn_u32 *cmd)
221 int type = icmp->icmp_type;
223 return (type <= ICMP_MAXTYPE && (cmd->d[0] & (1<<type)) );
226 #define TT ( (1 << ICMP_ECHO) | (1 << ICMP_ROUTERSOLICIT) | \
227 (1 << ICMP_TSTAMP) | (1 << ICMP_IREQ) | (1 << ICMP_MASKREQ) )
230 is_icmp_query(struct icmphdr *icmp)
232 int type = icmp->icmp_type;
234 return (type <= ICMP_MAXTYPE && (TT & (1<<type)) );
239 * The following checks use two arrays of 8 or 16 bits to store the
240 * bits that we want set or clear, respectively. They are in the
241 * low and high half of cmd->arg1 or cmd->d[0].
243 * We scan options and store the bits we find set. We succeed if
245 * (want_set & ~bits) == 0 && (want_clear & ~bits) == want_clear
247 * The code is sometimes optimized not to store additional variables.
251 flags_match(ipfw_insn *cmd, u_int8_t bits)
256 if ( ((cmd->arg1 & 0xff) & bits) != 0)
257 return 0; /* some bits we want set were clear */
258 want_clear = (cmd->arg1 >> 8) & 0xff;
259 if ( (want_clear & bits) != want_clear)
260 return 0; /* some bits we want clear were set */
265 ipopts_match(struct ip *ip, ipfw_insn *cmd)
267 int optlen, bits = 0;
268 u_char *cp = (u_char *)(ip + 1);
269 int x = (ip->ip_hl << 2) - sizeof (struct ip);
271 for (; x > 0; x -= optlen, cp += optlen) {
272 int opt = cp[IPOPT_OPTVAL];
274 if (opt == IPOPT_EOL)
276 if (opt == IPOPT_NOP)
279 optlen = cp[IPOPT_OLEN];
280 if (optlen <= 0 || optlen > x)
281 return 0; /* invalid or truncated */
289 bits |= IP_FW_IPOPT_LSRR;
293 bits |= IP_FW_IPOPT_SSRR;
297 bits |= IP_FW_IPOPT_RR;
301 bits |= IP_FW_IPOPT_TS;
305 return (flags_match(cmd, bits));
309 tcpopts_match(struct tcphdr *tcp, ipfw_insn *cmd)
311 int optlen, bits = 0;
312 u_char *cp = (u_char *)(tcp + 1);
313 int x = (tcp->th_off << 2) - sizeof(struct tcphdr);
315 for (; x > 0; x -= optlen, cp += optlen) {
317 if (opt == TCPOPT_EOL)
319 if (opt == TCPOPT_NOP)
333 bits |= IP_FW_TCPOPT_MSS;
337 bits |= IP_FW_TCPOPT_WINDOW;
340 case TCPOPT_SACK_PERMITTED:
342 bits |= IP_FW_TCPOPT_SACK;
345 case TCPOPT_TIMESTAMP:
346 bits |= IP_FW_TCPOPT_TS;
351 return (flags_match(cmd, bits));
355 iface_match(struct ifnet *ifp, ipfw_insn_if *cmd, struct ip_fw_chain *chain, uint32_t *tablearg)
357 if (ifp == NULL) /* no iface with this packet, match fails */
359 /* Check by name or by IP address */
360 if (cmd->name[0] != '\0') { /* match by name */
361 if (cmd->name[0] == '\1') /* use tablearg to match */
362 return ipfw_lookup_table_extended(chain, cmd->p.glob,
363 ifp->if_xname, tablearg, IPFW_TABLE_INTERFACE);
366 if (fnmatch(cmd->name, ifp->if_xname, 0) == 0)
369 if (strncmp(ifp->if_xname, cmd->name, IFNAMSIZ) == 0)
373 #ifdef __FreeBSD__ /* and OSX too ? */
377 TAILQ_FOREACH(ia, &ifp->if_addrhead, ifa_link) {
378 if (ia->ifa_addr->sa_family != AF_INET)
380 if (cmd->p.ip.s_addr == ((struct sockaddr_in *)
381 (ia->ifa_addr))->sin_addr.s_addr) {
382 if_addr_runlock(ifp);
383 return(1); /* match */
386 if_addr_runlock(ifp);
387 #endif /* __FreeBSD__ */
389 return(0); /* no match, fail ... */
393 * The verify_path function checks if a route to the src exists and
394 * if it is reachable via ifp (when provided).
396 * The 'verrevpath' option checks that the interface that an IP packet
397 * arrives on is the same interface that traffic destined for the
398 * packet's source address would be routed out of.
399 * The 'versrcreach' option just checks that the source address is
400 * reachable via any route (except default) in the routing table.
401 * These two are a measure to block forged packets. This is also
402 * commonly known as "anti-spoofing" or Unicast Reverse Path
403 * Forwarding (Unicast RFP) in Cisco-ese. The name of the knobs
404 * is purposely reminiscent of the Cisco IOS command,
406 * ip verify unicast reverse-path
407 * ip verify unicast source reachable-via any
409 * which implements the same functionality. But note that the syntax
410 * is misleading, and the check may be performed on all IP packets
411 * whether unicast, multicast, or broadcast.
414 verify_path(struct in_addr src, struct ifnet *ifp, u_int fib)
420 struct sockaddr_in *dst;
422 bzero(&ro, sizeof(ro));
424 dst = (struct sockaddr_in *)&(ro.ro_dst);
425 dst->sin_family = AF_INET;
426 dst->sin_len = sizeof(*dst);
428 in_rtalloc_ign(&ro, 0, fib);
430 if (ro.ro_rt == NULL)
434 * If ifp is provided, check for equality with rtentry.
435 * We should use rt->rt_ifa->ifa_ifp, instead of rt->rt_ifp,
436 * in order to pass packets injected back by if_simloop():
437 * if useloopback == 1 routing entry (via lo0) for our own address
438 * may exist, so we need to handle routing assymetry.
440 if (ifp != NULL && ro.ro_rt->rt_ifa->ifa_ifp != ifp) {
445 /* if no ifp provided, check if rtentry is not default route */
447 satosin(rt_key(ro.ro_rt))->sin_addr.s_addr == INADDR_ANY) {
452 /* or if this is a blackhole/reject route */
453 if (ifp == NULL && ro.ro_rt->rt_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
458 /* found valid route */
461 #endif /* __FreeBSD__ */
466 * ipv6 specific rules here...
469 icmp6type_match (int type, ipfw_insn_u32 *cmd)
471 return (type <= ICMP6_MAXTYPE && (cmd->d[type/32] & (1<<(type%32)) ) );
475 flow6id_match( int curr_flow, ipfw_insn_u32 *cmd )
478 for (i=0; i <= cmd->o.arg1; ++i )
479 if (curr_flow == cmd->d[i] )
484 /* support for IP6_*_ME opcodes */
486 search_ip6_addr_net (struct in6_addr * ip6_addr)
490 struct in6_ifaddr *fdm;
491 struct in6_addr copia;
493 TAILQ_FOREACH(mdc, &V_ifnet, if_link) {
495 TAILQ_FOREACH(mdc2, &mdc->if_addrhead, ifa_link) {
496 if (mdc2->ifa_addr->sa_family == AF_INET6) {
497 fdm = (struct in6_ifaddr *)mdc2;
498 copia = fdm->ia_addr.sin6_addr;
499 /* need for leaving scope_id in the sock_addr */
500 in6_clearscope(&copia);
501 if (IN6_ARE_ADDR_EQUAL(ip6_addr, &copia)) {
502 if_addr_runlock(mdc);
507 if_addr_runlock(mdc);
513 verify_path6(struct in6_addr *src, struct ifnet *ifp, u_int fib)
516 struct sockaddr_in6 *dst;
518 bzero(&ro, sizeof(ro));
520 dst = (struct sockaddr_in6 * )&(ro.ro_dst);
521 dst->sin6_family = AF_INET6;
522 dst->sin6_len = sizeof(*dst);
523 dst->sin6_addr = *src;
525 in6_rtalloc_ign(&ro, 0, fib);
526 if (ro.ro_rt == NULL)
530 * if ifp is provided, check for equality with rtentry
531 * We should use rt->rt_ifa->ifa_ifp, instead of rt->rt_ifp,
532 * to support the case of sending packets to an address of our own.
533 * (where the former interface is the first argument of if_simloop()
534 * (=ifp), the latter is lo0)
536 if (ifp != NULL && ro.ro_rt->rt_ifa->ifa_ifp != ifp) {
541 /* if no ifp provided, check if rtentry is not default route */
543 IN6_IS_ADDR_UNSPECIFIED(&satosin6(rt_key(ro.ro_rt))->sin6_addr)) {
548 /* or if this is a blackhole/reject route */
549 if (ifp == NULL && ro.ro_rt->rt_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
554 /* found valid route */
561 is_icmp6_query(int icmp6_type)
563 if ((icmp6_type <= ICMP6_MAXTYPE) &&
564 (icmp6_type == ICMP6_ECHO_REQUEST ||
565 icmp6_type == ICMP6_MEMBERSHIP_QUERY ||
566 icmp6_type == ICMP6_WRUREQUEST ||
567 icmp6_type == ICMP6_FQDN_QUERY ||
568 icmp6_type == ICMP6_NI_QUERY))
575 send_reject6(struct ip_fw_args *args, int code, u_int hlen, struct ip6_hdr *ip6)
580 if (code == ICMP6_UNREACH_RST && args->f_id.proto == IPPROTO_TCP) {
582 tcp = (struct tcphdr *)((char *)ip6 + hlen);
584 if ((tcp->th_flags & TH_RST) == 0) {
586 m0 = ipfw_send_pkt(args->m, &(args->f_id),
587 ntohl(tcp->th_seq), ntohl(tcp->th_ack),
588 tcp->th_flags | TH_RST);
590 ip6_output(m0, NULL, NULL, 0, NULL, NULL,
594 } else if (code != ICMP6_UNREACH_RST) { /* Send an ICMPv6 unreach. */
597 * Unlike above, the mbufs need to line up with the ip6 hdr,
598 * as the contents are read. We need to m_adj() the
600 * The mbuf will however be thrown away so we can adjust it.
601 * Remember we did an m_pullup on it already so we
602 * can make some assumptions about contiguousness.
605 m_adj(m, args->L3offset);
607 icmp6_error(m, ICMP6_DST_UNREACH, code, 0);
618 * sends a reject message, consuming the mbuf passed as an argument.
621 send_reject(struct ip_fw_args *args, int code, int iplen, struct ip *ip)
625 /* XXX When ip is not guaranteed to be at mtod() we will
626 * need to account for this */
627 * The mbuf will however be thrown away so we can adjust it.
628 * Remember we did an m_pullup on it already so we
629 * can make some assumptions about contiguousness.
632 m_adj(m, args->L3offset);
634 if (code != ICMP_REJECT_RST) { /* Send an ICMP unreach */
635 /* We need the IP header in host order for icmp_error(). */
637 icmp_error(args->m, ICMP_UNREACH, code, 0L, 0);
638 } else if (args->f_id.proto == IPPROTO_TCP) {
639 struct tcphdr *const tcp =
640 L3HDR(struct tcphdr, mtod(args->m, struct ip *));
641 if ( (tcp->th_flags & TH_RST) == 0) {
643 m = ipfw_send_pkt(args->m, &(args->f_id),
644 ntohl(tcp->th_seq), ntohl(tcp->th_ack),
645 tcp->th_flags | TH_RST);
647 ip_output(m, NULL, NULL, 0, NULL, NULL);
656 * Support for uid/gid/jail lookup. These tests are expensive
657 * (because we may need to look into the list of active sockets)
658 * so we cache the results. ugid_lookupp is 0 if we have not
659 * yet done a lookup, 1 if we succeeded, and -1 if we tried
660 * and failed. The function always returns the match value.
661 * We could actually spare the variable and use *uc, setting
662 * it to '(void *)check_uidgid if we have no info, NULL if
663 * we tried and failed, or any other value if successful.
666 check_uidgid(ipfw_insn_u32 *insn, struct ip_fw_args *args, int *ugid_lookupp,
671 return cred_check(insn, proto, oif,
672 dst_ip, dst_port, src_ip, src_port,
673 (struct bsd_ucred *)uc, ugid_lookupp, ((struct mbuf *)inp)->m_skb);
675 struct in_addr src_ip, dst_ip;
676 struct inpcbinfo *pi;
677 struct ipfw_flow_id *id;
678 struct inpcb *pcb, *inp;
688 * Check to see if the UDP or TCP stack supplied us with
689 * the PCB. If so, rather then holding a lock and looking
690 * up the PCB, we can use the one that was supplied.
692 if (inp && *ugid_lookupp == 0) {
693 INP_LOCK_ASSERT(inp);
694 if (inp->inp_socket != NULL) {
695 *uc = crhold(inp->inp_cred);
701 * If we have already been here and the packet has no
702 * PCB entry associated with it, then we can safely
703 * assume that this is a no match.
705 if (*ugid_lookupp == -1)
707 if (id->proto == IPPROTO_TCP) {
710 } else if (id->proto == IPPROTO_UDP) {
711 lookupflags = INPLOOKUP_WILDCARD;
715 lookupflags |= INPLOOKUP_RLOCKPCB;
717 if (*ugid_lookupp == 0) {
718 if (id->addr_type == 6) {
721 pcb = in6_pcblookup_mbuf(pi,
722 &id->src_ip6, htons(id->src_port),
723 &id->dst_ip6, htons(id->dst_port),
724 lookupflags, oif, args->m);
726 pcb = in6_pcblookup_mbuf(pi,
727 &id->dst_ip6, htons(id->dst_port),
728 &id->src_ip6, htons(id->src_port),
729 lookupflags, oif, args->m);
735 src_ip.s_addr = htonl(id->src_ip);
736 dst_ip.s_addr = htonl(id->dst_ip);
738 pcb = in_pcblookup_mbuf(pi,
739 src_ip, htons(id->src_port),
740 dst_ip, htons(id->dst_port),
741 lookupflags, oif, args->m);
743 pcb = in_pcblookup_mbuf(pi,
744 dst_ip, htons(id->dst_port),
745 src_ip, htons(id->src_port),
746 lookupflags, oif, args->m);
749 INP_RLOCK_ASSERT(pcb);
750 *uc = crhold(pcb->inp_cred);
754 if (*ugid_lookupp == 0) {
756 * We tried and failed, set the variable to -1
757 * so we will not try again on this packet.
763 if (insn->o.opcode == O_UID)
764 match = ((*uc)->cr_uid == (uid_t)insn->d[0]);
765 else if (insn->o.opcode == O_GID)
766 match = groupmember((gid_t)insn->d[0], *uc);
767 else if (insn->o.opcode == O_JAIL)
768 match = ((*uc)->cr_prison->pr_id == (int)insn->d[0]);
770 #endif /* __FreeBSD__ */
774 * Helper function to set args with info on the rule after the matching
775 * one. slot is precise, whereas we guess rule_id as they are
776 * assigned sequentially.
779 set_match(struct ip_fw_args *args, int slot,
780 struct ip_fw_chain *chain)
782 args->rule.chain_id = chain->id;
783 args->rule.slot = slot + 1; /* we use 0 as a marker */
784 args->rule.rule_id = 1 + chain->map[slot]->id;
785 args->rule.rulenum = chain->map[slot]->rulenum;
789 * Helper function to enable cached rule lookups using
790 * x_next and next_rule fields in ipfw rule.
793 jump_fast(struct ip_fw_chain *chain, struct ip_fw *f, int num,
794 int tablearg, int jump_backwards)
798 /* If possible use cached f_pos (in f->next_rule),
799 * whose version is written in f->next_rule
800 * (horrible hacks to avoid changing the ABI).
802 if (num != IP_FW_TABLEARG && (uintptr_t)f->x_next == chain->id)
803 f_pos = (uintptr_t)f->next_rule;
805 int i = IP_FW_ARG_TABLEARG(num);
806 /* make sure we do not jump backward */
807 if (jump_backwards == 0 && i <= f->rulenum)
809 f_pos = ipfw_find_rule(chain, i, 0);
810 /* update the cache */
811 if (num != IP_FW_TABLEARG) {
812 f->next_rule = (void *)(uintptr_t)f_pos;
813 f->x_next = (void *)(uintptr_t)chain->id;
821 * The main check routine for the firewall.
823 * All arguments are in args so we can modify them and return them
824 * back to the caller.
828 * args->m (in/out) The packet; we set to NULL when/if we nuke it.
829 * Starts with the IP header.
830 * args->eh (in) Mac header if present, NULL for layer3 packet.
831 * args->L3offset Number of bytes bypassed if we came from L2.
832 * e.g. often sizeof(eh) ** NOTYET **
833 * args->oif Outgoing interface, NULL if packet is incoming.
834 * The incoming interface is in the mbuf. (in)
835 * args->divert_rule (in/out)
836 * Skip up to the first rule past this rule number;
837 * upon return, non-zero port number for divert or tee.
839 * args->rule Pointer to the last matching rule (in/out)
840 * args->next_hop Socket we are forwarding to (out).
841 * args->next_hop6 IPv6 next hop we are forwarding to (out).
842 * args->f_id Addresses grabbed from the packet (out)
843 * args->rule.info a cookie depending on rule action
847 * IP_FW_PASS the packet must be accepted
848 * IP_FW_DENY the packet must be dropped
849 * IP_FW_DIVERT divert packet, port in m_tag
850 * IP_FW_TEE tee packet, port in m_tag
851 * IP_FW_DUMMYNET to dummynet, pipe in args->cookie
852 * IP_FW_NETGRAPH into netgraph, cookie args->cookie
853 * args->rule contains the matching rule,
854 * args->rule.info has additional information.
858 ipfw_chk(struct ip_fw_args *args)
862 * Local variables holding state while processing a packet:
864 * IMPORTANT NOTE: to speed up the processing of rules, there
865 * are some assumption on the values of the variables, which
866 * are documented here. Should you change them, please check
867 * the implementation of the various instructions to make sure
868 * that they still work.
870 * args->eh The MAC header. It is non-null for a layer2
871 * packet, it is NULL for a layer-3 packet.
873 * args->L3offset Offset in the packet to the L3 (IP or equiv.) header.
875 * m | args->m Pointer to the mbuf, as received from the caller.
876 * It may change if ipfw_chk() does an m_pullup, or if it
877 * consumes the packet because it calls send_reject().
878 * XXX This has to change, so that ipfw_chk() never modifies
879 * or consumes the buffer.
880 * ip is the beginning of the ip(4 or 6) header.
881 * Calculated by adding the L3offset to the start of data.
882 * (Until we start using L3offset, the packet is
883 * supposed to start with the ip header).
885 struct mbuf *m = args->m;
886 struct ip *ip = mtod(m, struct ip *);
889 * For rules which contain uid/gid or jail constraints, cache
890 * a copy of the users credentials after the pcb lookup has been
891 * executed. This will speed up the processing of rules with
892 * these types of constraints, as well as decrease contention
893 * on pcb related locks.
896 struct bsd_ucred ucred_cache;
898 struct ucred *ucred_cache = NULL;
900 int ucred_lookup = 0;
903 * oif | args->oif If NULL, ipfw_chk has been called on the
904 * inbound path (ether_input, ip_input).
905 * If non-NULL, ipfw_chk has been called on the outbound path
906 * (ether_output, ip_output).
908 struct ifnet *oif = args->oif;
910 int f_pos = 0; /* index of current rule in the array */
914 * hlen The length of the IP header.
916 u_int hlen = 0; /* hlen >0 means we have an IP pkt */
919 * offset The offset of a fragment. offset != 0 means that
920 * we have a fragment at this offset of an IPv4 packet.
921 * offset == 0 means that (if this is an IPv4 packet)
922 * this is the first or only fragment.
923 * For IPv6 offset|ip6f_mf == 0 means there is no Fragment Header
924 * or there is a single packet fragement (fragement header added
925 * without needed). We will treat a single packet fragment as if
926 * there was no fragment header (or log/block depending on the
927 * V_fw_permit_single_frag6 sysctl setting).
933 * Local copies of addresses. They are only valid if we have
936 * proto The protocol. Set to 0 for non-ip packets,
937 * or to the protocol read from the packet otherwise.
938 * proto != 0 means that we have an IPv4 packet.
940 * src_port, dst_port port numbers, in HOST format. Only
941 * valid for TCP and UDP packets.
943 * src_ip, dst_ip ip addresses, in NETWORK format.
944 * Only valid for IPv4 packets.
947 uint16_t src_port = 0, dst_port = 0; /* NOTE: host format */
948 struct in_addr src_ip, dst_ip; /* NOTE: network format */
951 uint16_t etype = 0; /* Host order stored ether type */
954 * dyn_dir = MATCH_UNKNOWN when rules unchecked,
955 * MATCH_NONE when checked and not matched (q = NULL),
956 * MATCH_FORWARD or MATCH_REVERSE otherwise (q != NULL)
958 int dyn_dir = MATCH_UNKNOWN;
959 ipfw_dyn_rule *q = NULL;
960 struct ip_fw_chain *chain = &V_layer3_chain;
963 * We store in ulp a pointer to the upper layer protocol header.
964 * In the ipv4 case this is easy to determine from the header,
965 * but for ipv6 we might have some additional headers in the middle.
966 * ulp is NULL if not found.
968 void *ulp = NULL; /* upper layer protocol pointer. */
970 /* XXX ipv6 variables */
972 uint8_t icmp6_type = 0;
973 uint16_t ext_hd = 0; /* bits vector for extension header filtering */
974 /* end of ipv6 variables */
978 int done = 0; /* flag to exit the outer loop */
980 if (m->m_flags & M_SKIP_FIREWALL || (! V_ipfw_vnet_ready))
981 return (IP_FW_PASS); /* accept */
983 dst_ip.s_addr = 0; /* make sure it is initialized */
984 src_ip.s_addr = 0; /* make sure it is initialized */
985 pktlen = m->m_pkthdr.len;
986 args->f_id.fib = M_GETFIB(m); /* note mbuf not altered) */
987 proto = args->f_id.proto = 0; /* mark f_id invalid */
988 /* XXX 0 is a valid proto: IP/IPv6 Hop-by-Hop Option */
991 * PULLUP_TO(len, p, T) makes sure that len + sizeof(T) is contiguous,
992 * then it sets p to point at the offset "len" in the mbuf. WARNING: the
993 * pointer might become stale after other pullups (but we never use it
996 #define PULLUP_TO(_len, p, T) PULLUP_LEN(_len, p, sizeof(T))
997 #define PULLUP_LEN(_len, p, T) \
999 int x = (_len) + T; \
1000 if ((m)->m_len < x) { \
1001 args->m = m = m_pullup(m, x); \
1003 goto pullup_failed; \
1005 p = (mtod(m, char *) + (_len)); \
1009 * if we have an ether header,
1012 etype = ntohs(args->eh->ether_type);
1014 /* Identify IP packets and fill up variables. */
1015 if (pktlen >= sizeof(struct ip6_hdr) &&
1016 (args->eh == NULL || etype == ETHERTYPE_IPV6) && ip->ip_v == 6) {
1017 struct ip6_hdr *ip6 = (struct ip6_hdr *)ip;
1019 args->f_id.addr_type = 6;
1020 hlen = sizeof(struct ip6_hdr);
1021 proto = ip6->ip6_nxt;
1023 /* Search extension headers to find upper layer protocols */
1024 while (ulp == NULL && offset == 0) {
1026 case IPPROTO_ICMPV6:
1027 PULLUP_TO(hlen, ulp, struct icmp6_hdr);
1028 icmp6_type = ICMP6(ulp)->icmp6_type;
1032 PULLUP_TO(hlen, ulp, struct tcphdr);
1033 dst_port = TCP(ulp)->th_dport;
1034 src_port = TCP(ulp)->th_sport;
1035 /* save flags for dynamic rules */
1036 args->f_id._flags = TCP(ulp)->th_flags;
1040 PULLUP_TO(hlen, ulp, struct sctphdr);
1041 src_port = SCTP(ulp)->src_port;
1042 dst_port = SCTP(ulp)->dest_port;
1046 PULLUP_TO(hlen, ulp, struct udphdr);
1047 dst_port = UDP(ulp)->uh_dport;
1048 src_port = UDP(ulp)->uh_sport;
1051 case IPPROTO_HOPOPTS: /* RFC 2460 */
1052 PULLUP_TO(hlen, ulp, struct ip6_hbh);
1053 ext_hd |= EXT_HOPOPTS;
1054 hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3;
1055 proto = ((struct ip6_hbh *)ulp)->ip6h_nxt;
1059 case IPPROTO_ROUTING: /* RFC 2460 */
1060 PULLUP_TO(hlen, ulp, struct ip6_rthdr);
1061 switch (((struct ip6_rthdr *)ulp)->ip6r_type) {
1063 ext_hd |= EXT_RTHDR0;
1066 ext_hd |= EXT_RTHDR2;
1070 printf("IPFW2: IPV6 - Unknown "
1071 "Routing Header type(%d)\n",
1072 ((struct ip6_rthdr *)
1074 if (V_fw_deny_unknown_exthdrs)
1075 return (IP_FW_DENY);
1078 ext_hd |= EXT_ROUTING;
1079 hlen += (((struct ip6_rthdr *)ulp)->ip6r_len + 1) << 3;
1080 proto = ((struct ip6_rthdr *)ulp)->ip6r_nxt;
1084 case IPPROTO_FRAGMENT: /* RFC 2460 */
1085 PULLUP_TO(hlen, ulp, struct ip6_frag);
1086 ext_hd |= EXT_FRAGMENT;
1087 hlen += sizeof (struct ip6_frag);
1088 proto = ((struct ip6_frag *)ulp)->ip6f_nxt;
1089 offset = ((struct ip6_frag *)ulp)->ip6f_offlg &
1091 ip6f_mf = ((struct ip6_frag *)ulp)->ip6f_offlg &
1093 if (V_fw_permit_single_frag6 == 0 &&
1094 offset == 0 && ip6f_mf == 0) {
1096 printf("IPFW2: IPV6 - Invalid "
1097 "Fragment Header\n");
1098 if (V_fw_deny_unknown_exthdrs)
1099 return (IP_FW_DENY);
1103 ntohl(((struct ip6_frag *)ulp)->ip6f_ident);
1107 case IPPROTO_DSTOPTS: /* RFC 2460 */
1108 PULLUP_TO(hlen, ulp, struct ip6_hbh);
1109 ext_hd |= EXT_DSTOPTS;
1110 hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3;
1111 proto = ((struct ip6_hbh *)ulp)->ip6h_nxt;
1115 case IPPROTO_AH: /* RFC 2402 */
1116 PULLUP_TO(hlen, ulp, struct ip6_ext);
1118 hlen += (((struct ip6_ext *)ulp)->ip6e_len + 2) << 2;
1119 proto = ((struct ip6_ext *)ulp)->ip6e_nxt;
1123 case IPPROTO_ESP: /* RFC 2406 */
1124 PULLUP_TO(hlen, ulp, uint32_t); /* SPI, Seq# */
1125 /* Anything past Seq# is variable length and
1126 * data past this ext. header is encrypted. */
1130 case IPPROTO_NONE: /* RFC 2460 */
1132 * Packet ends here, and IPv6 header has
1133 * already been pulled up. If ip6e_len!=0
1134 * then octets must be ignored.
1136 ulp = ip; /* non-NULL to get out of loop. */
1139 case IPPROTO_OSPFIGP:
1140 /* XXX OSPF header check? */
1141 PULLUP_TO(hlen, ulp, struct ip6_ext);
1145 /* XXX PIM header check? */
1146 PULLUP_TO(hlen, ulp, struct pim);
1149 case IPPROTO_GRE: /* RFC 1701 */
1150 /* XXX GRE header check? */
1151 PULLUP_TO(hlen, ulp, struct gre_h);
1155 PULLUP_TO(hlen, ulp, struct carp_header);
1156 if (((struct carp_header *)ulp)->carp_version !=
1158 return (IP_FW_DENY);
1159 if (((struct carp_header *)ulp)->carp_type !=
1161 return (IP_FW_DENY);
1164 case IPPROTO_IPV6: /* RFC 2893 */
1165 PULLUP_TO(hlen, ulp, struct ip6_hdr);
1168 case IPPROTO_IPV4: /* RFC 2893 */
1169 PULLUP_TO(hlen, ulp, struct ip);
1174 printf("IPFW2: IPV6 - Unknown "
1175 "Extension Header(%d), ext_hd=%x\n",
1177 if (V_fw_deny_unknown_exthdrs)
1178 return (IP_FW_DENY);
1179 PULLUP_TO(hlen, ulp, struct ip6_ext);
1183 ip = mtod(m, struct ip *);
1184 ip6 = (struct ip6_hdr *)ip;
1185 args->f_id.src_ip6 = ip6->ip6_src;
1186 args->f_id.dst_ip6 = ip6->ip6_dst;
1187 args->f_id.src_ip = 0;
1188 args->f_id.dst_ip = 0;
1189 args->f_id.flow_id6 = ntohl(ip6->ip6_flow);
1190 } else if (pktlen >= sizeof(struct ip) &&
1191 (args->eh == NULL || etype == ETHERTYPE_IP) && ip->ip_v == 4) {
1193 hlen = ip->ip_hl << 2;
1194 args->f_id.addr_type = 4;
1197 * Collect parameters into local variables for faster matching.
1200 src_ip = ip->ip_src;
1201 dst_ip = ip->ip_dst;
1202 offset = ntohs(ip->ip_off) & IP_OFFMASK;
1203 iplen = ntohs(ip->ip_len);
1204 pktlen = iplen < pktlen ? iplen : pktlen;
1209 PULLUP_TO(hlen, ulp, struct tcphdr);
1210 dst_port = TCP(ulp)->th_dport;
1211 src_port = TCP(ulp)->th_sport;
1212 /* save flags for dynamic rules */
1213 args->f_id._flags = TCP(ulp)->th_flags;
1217 PULLUP_TO(hlen, ulp, struct sctphdr);
1218 src_port = SCTP(ulp)->src_port;
1219 dst_port = SCTP(ulp)->dest_port;
1223 PULLUP_TO(hlen, ulp, struct udphdr);
1224 dst_port = UDP(ulp)->uh_dport;
1225 src_port = UDP(ulp)->uh_sport;
1229 PULLUP_TO(hlen, ulp, struct icmphdr);
1230 //args->f_id.flags = ICMP(ulp)->icmp_type;
1238 ip = mtod(m, struct ip *);
1239 args->f_id.src_ip = ntohl(src_ip.s_addr);
1240 args->f_id.dst_ip = ntohl(dst_ip.s_addr);
1243 if (proto) { /* we may have port numbers, store them */
1244 args->f_id.proto = proto;
1245 args->f_id.src_port = src_port = ntohs(src_port);
1246 args->f_id.dst_port = dst_port = ntohs(dst_port);
1250 if (! V_ipfw_vnet_ready) { /* shutting down, leave NOW. */
1251 IPFW_RUNLOCK(chain);
1252 return (IP_FW_PASS); /* accept */
1254 if (args->rule.slot) {
1256 * Packet has already been tagged as a result of a previous
1257 * match on rule args->rule aka args->rule_id (PIPE, QUEUE,
1258 * REASS, NETGRAPH, DIVERT/TEE...)
1259 * Validate the slot and continue from the next one
1260 * if still present, otherwise do a lookup.
1262 f_pos = (args->rule.chain_id == chain->id) ?
1264 ipfw_find_rule(chain, args->rule.rulenum,
1265 args->rule.rule_id);
1271 * Now scan the rules, and parse microinstructions for each rule.
1272 * We have two nested loops and an inner switch. Sometimes we
1273 * need to break out of one or both loops, or re-enter one of
1274 * the loops with updated variables. Loop variables are:
1276 * f_pos (outer loop) points to the current rule.
1277 * On output it points to the matching rule.
1278 * done (outer loop) is used as a flag to break the loop.
1279 * l (inner loop) residual length of current rule.
1280 * cmd points to the current microinstruction.
1282 * We break the inner loop by setting l=0 and possibly
1283 * cmdlen=0 if we don't want to advance cmd.
1284 * We break the outer loop by setting done=1
1285 * We can restart the inner loop by setting l>0 and f_pos, f, cmd
1288 for (; f_pos < chain->n_rules; f_pos++) {
1290 uint32_t tablearg = 0;
1291 int l, cmdlen, skip_or; /* skip rest of OR block */
1294 f = chain->map[f_pos];
1295 if (V_set_disable & (1 << f->set) )
1299 for (l = f->cmd_len, cmd = f->cmd ; l > 0 ;
1300 l -= cmdlen, cmd += cmdlen) {
1304 * check_body is a jump target used when we find a
1305 * CHECK_STATE, and need to jump to the body of
1310 cmdlen = F_LEN(cmd);
1312 * An OR block (insn_1 || .. || insn_n) has the
1313 * F_OR bit set in all but the last instruction.
1314 * The first match will set "skip_or", and cause
1315 * the following instructions to be skipped until
1316 * past the one with the F_OR bit clear.
1318 if (skip_or) { /* skip this instruction */
1319 if ((cmd->len & F_OR) == 0)
1320 skip_or = 0; /* next one is good */
1323 match = 0; /* set to 1 if we succeed */
1325 switch (cmd->opcode) {
1327 * The first set of opcodes compares the packet's
1328 * fields with some pattern, setting 'match' if a
1329 * match is found. At the end of the loop there is
1330 * logic to deal with F_NOT and F_OR flags associated
1338 printf("ipfw: opcode %d unimplemented\n",
1346 * We only check offset == 0 && proto != 0,
1347 * as this ensures that we have a
1348 * packet with the ports info.
1352 if (proto == IPPROTO_TCP ||
1353 proto == IPPROTO_UDP)
1354 match = check_uidgid(
1355 (ipfw_insn_u32 *)cmd,
1356 args, &ucred_lookup,
1360 (void *)&ucred_cache);
1365 match = iface_match(m->m_pkthdr.rcvif,
1366 (ipfw_insn_if *)cmd, chain, &tablearg);
1370 match = iface_match(oif, (ipfw_insn_if *)cmd,
1375 match = iface_match(oif ? oif :
1376 m->m_pkthdr.rcvif, (ipfw_insn_if *)cmd,
1381 if (args->eh != NULL) { /* have MAC header */
1382 u_int32_t *want = (u_int32_t *)
1383 ((ipfw_insn_mac *)cmd)->addr;
1384 u_int32_t *mask = (u_int32_t *)
1385 ((ipfw_insn_mac *)cmd)->mask;
1386 u_int32_t *hdr = (u_int32_t *)args->eh;
1389 ( want[0] == (hdr[0] & mask[0]) &&
1390 want[1] == (hdr[1] & mask[1]) &&
1391 want[2] == (hdr[2] & mask[2]) );
1396 if (args->eh != NULL) {
1398 ((ipfw_insn_u16 *)cmd)->ports;
1401 for (i = cmdlen - 1; !match && i>0;
1403 match = (etype >= p[0] &&
1409 match = (offset != 0);
1412 case O_IN: /* "out" is "not in" */
1413 match = (oif == NULL);
1417 match = (args->eh != NULL);
1422 /* For diverted packets, args->rule.info
1423 * contains the divert port (in host format)
1424 * reason and direction.
1426 uint32_t i = args->rule.info;
1427 match = (i&IPFW_IS_MASK) == IPFW_IS_DIVERT &&
1428 cmd->arg1 & ((i & IPFW_INFO_IN) ? 1 : 2);
1434 * We do not allow an arg of 0 so the
1435 * check of "proto" only suffices.
1437 match = (proto == cmd->arg1);
1442 (((ipfw_insn_ip *)cmd)->addr.s_addr ==
1446 case O_IP_SRC_LOOKUP:
1447 case O_IP_DST_LOOKUP:
1450 (cmd->opcode == O_IP_DST_LOOKUP) ?
1451 dst_ip.s_addr : src_ip.s_addr;
1454 if (cmdlen > F_INSN_SIZE(ipfw_insn_u32)) {
1455 /* generic lookup. The key must be
1456 * in 32bit big-endian format.
1458 v = ((ipfw_insn_u32 *)cmd)->d[1];
1460 key = dst_ip.s_addr;
1462 key = src_ip.s_addr;
1463 else if (v == 6) /* dscp */
1464 key = (ip->ip_tos >> 2) & 0x3f;
1465 else if (offset != 0)
1467 else if (proto != IPPROTO_TCP &&
1468 proto != IPPROTO_UDP)
1471 key = htonl(dst_port);
1473 key = htonl(src_port);
1474 else if (v == 4 || v == 5) {
1476 (ipfw_insn_u32 *)cmd,
1477 args, &ucred_lookup,
1480 if (v == 4 /* O_UID */)
1481 key = ucred_cache->cr_uid;
1482 else if (v == 5 /* O_JAIL */)
1483 key = ucred_cache->cr_prison->pr_id;
1484 #else /* !__FreeBSD__ */
1485 (void *)&ucred_cache);
1486 if (v ==4 /* O_UID */)
1487 key = ucred_cache.uid;
1488 else if (v == 5 /* O_JAIL */)
1489 key = ucred_cache.xid;
1490 #endif /* !__FreeBSD__ */
1495 match = ipfw_lookup_table(chain,
1496 cmd->arg1, key, &v);
1499 if (cmdlen == F_INSN_SIZE(ipfw_insn_u32))
1501 ((ipfw_insn_u32 *)cmd)->d[0] == v;
1504 } else if (is_ipv6) {
1506 void *pkey = (cmd->opcode == O_IP_DST_LOOKUP) ?
1507 &args->f_id.dst_ip6: &args->f_id.src_ip6;
1508 match = ipfw_lookup_table_extended(chain,
1509 cmd->arg1, pkey, &v,
1511 if (cmdlen == F_INSN_SIZE(ipfw_insn_u32))
1512 match = ((ipfw_insn_u32 *)cmd)->d[0] == v;
1522 (cmd->opcode == O_IP_DST_MASK) ?
1523 dst_ip.s_addr : src_ip.s_addr;
1524 uint32_t *p = ((ipfw_insn_u32 *)cmd)->d;
1527 for (; !match && i>0; i-= 2, p+= 2)
1528 match = (p[0] == (a & p[1]));
1536 INADDR_TO_IFP(src_ip, tif);
1537 match = (tif != NULL);
1543 match= is_ipv6 && search_ip6_addr_net(&args->f_id.src_ip6);
1550 u_int32_t *d = (u_int32_t *)(cmd+1);
1552 cmd->opcode == O_IP_DST_SET ?
1558 addr -= d[0]; /* subtract base */
1559 match = (addr < cmd->arg1) &&
1560 ( d[ 1 + (addr>>5)] &
1561 (1<<(addr & 0x1f)) );
1567 (((ipfw_insn_ip *)cmd)->addr.s_addr ==
1575 INADDR_TO_IFP(dst_ip, tif);
1576 match = (tif != NULL);
1582 match= is_ipv6 && search_ip6_addr_net(&args->f_id.dst_ip6);
1590 * offset == 0 && proto != 0 is enough
1591 * to guarantee that we have a
1592 * packet with port info.
1594 if ((proto==IPPROTO_UDP || proto==IPPROTO_TCP)
1597 (cmd->opcode == O_IP_SRCPORT) ?
1598 src_port : dst_port ;
1600 ((ipfw_insn_u16 *)cmd)->ports;
1603 for (i = cmdlen - 1; !match && i>0;
1605 match = (x>=p[0] && x<=p[1]);
1610 match = (offset == 0 && proto==IPPROTO_ICMP &&
1611 icmptype_match(ICMP(ulp), (ipfw_insn_u32 *)cmd) );
1616 match = is_ipv6 && offset == 0 &&
1617 proto==IPPROTO_ICMPV6 &&
1619 ICMP6(ulp)->icmp6_type,
1620 (ipfw_insn_u32 *)cmd);
1626 ipopts_match(ip, cmd) );
1631 cmd->arg1 == ip->ip_v);
1637 if (is_ipv4) { /* only for IP packets */
1642 if (cmd->opcode == O_IPLEN)
1644 else if (cmd->opcode == O_IPTTL)
1646 else /* must be IPID */
1647 x = ntohs(ip->ip_id);
1649 match = (cmd->arg1 == x);
1652 /* otherwise we have ranges */
1653 p = ((ipfw_insn_u16 *)cmd)->ports;
1655 for (; !match && i>0; i--, p += 2)
1656 match = (x >= p[0] && x <= p[1]);
1660 case O_IPPRECEDENCE:
1662 (cmd->arg1 == (ip->ip_tos & 0xe0)) );
1667 flags_match(cmd, ip->ip_tos));
1675 p = ((ipfw_insn_u32 *)cmd)->d;
1678 x = ip->ip_tos >> 2;
1681 v = &((struct ip6_hdr *)ip)->ip6_vfc;
1682 x = (*v & 0x0F) << 2;
1688 /* DSCP bitmask is stored as low_u32 high_u32 */
1690 match = *(p + 1) & (1 << (x - 32));
1692 match = *p & (1 << x);
1697 if (proto == IPPROTO_TCP && offset == 0) {
1705 ((ip->ip_hl + tcp->th_off) << 2);
1707 match = (cmd->arg1 == x);
1710 /* otherwise we have ranges */
1711 p = ((ipfw_insn_u16 *)cmd)->ports;
1713 for (; !match && i>0; i--, p += 2)
1714 match = (x >= p[0] && x <= p[1]);
1719 match = (proto == IPPROTO_TCP && offset == 0 &&
1720 flags_match(cmd, TCP(ulp)->th_flags));
1724 PULLUP_LEN(hlen, ulp, (TCP(ulp)->th_off << 2));
1725 match = (proto == IPPROTO_TCP && offset == 0 &&
1726 tcpopts_match(TCP(ulp), cmd));
1730 match = (proto == IPPROTO_TCP && offset == 0 &&
1731 ((ipfw_insn_u32 *)cmd)->d[0] ==
1736 match = (proto == IPPROTO_TCP && offset == 0 &&
1737 ((ipfw_insn_u32 *)cmd)->d[0] ==
1742 if (proto == IPPROTO_TCP && offset == 0) {
1747 x = ntohs(TCP(ulp)->th_win);
1749 match = (cmd->arg1 == x);
1752 /* Otherwise we have ranges. */
1753 p = ((ipfw_insn_u16 *)cmd)->ports;
1755 for (; !match && i > 0; i--, p += 2)
1756 match = (x >= p[0] && x <= p[1]);
1761 /* reject packets which have SYN only */
1762 /* XXX should i also check for TH_ACK ? */
1763 match = (proto == IPPROTO_TCP && offset == 0 &&
1764 (TCP(ulp)->th_flags &
1765 (TH_RST | TH_ACK | TH_SYN)) != TH_SYN);
1770 ipfw_insn_altq *altq = (ipfw_insn_altq *)cmd;
1773 at = pf_find_mtag(m);
1774 if (at != NULL && at->qid != 0)
1776 at = pf_get_mtag(m);
1779 * Let the packet fall back to the
1784 at->qid = altq->qid;
1790 ipfw_log(f, hlen, args, m,
1791 oif, offset | ip6f_mf, tablearg, ip);
1796 match = (random()<((ipfw_insn_u32 *)cmd)->d[0]);
1800 /* Outgoing packets automatically pass/match */
1801 match = ((oif != NULL) ||
1802 (m->m_pkthdr.rcvif == NULL) ||
1806 verify_path6(&(args->f_id.src_ip6),
1807 m->m_pkthdr.rcvif, args->f_id.fib) :
1809 verify_path(src_ip, m->m_pkthdr.rcvif,
1814 /* Outgoing packets automatically pass/match */
1815 match = (hlen > 0 && ((oif != NULL) ||
1818 verify_path6(&(args->f_id.src_ip6),
1819 NULL, args->f_id.fib) :
1821 verify_path(src_ip, NULL, args->f_id.fib)));
1825 /* Outgoing packets automatically pass/match */
1826 if (oif == NULL && hlen > 0 &&
1827 ( (is_ipv4 && in_localaddr(src_ip))
1830 in6_localaddr(&(args->f_id.src_ip6)))
1835 is_ipv6 ? verify_path6(
1836 &(args->f_id.src_ip6),
1849 match = (m_tag_find(m,
1850 PACKET_TAG_IPSEC_IN_DONE, NULL) != NULL);
1852 /* otherwise no match */
1858 IN6_ARE_ADDR_EQUAL(&args->f_id.src_ip6,
1859 &((ipfw_insn_ip6 *)cmd)->addr6);
1864 IN6_ARE_ADDR_EQUAL(&args->f_id.dst_ip6,
1865 &((ipfw_insn_ip6 *)cmd)->addr6);
1867 case O_IP6_SRC_MASK:
1868 case O_IP6_DST_MASK:
1872 struct in6_addr *d =
1873 &((ipfw_insn_ip6 *)cmd)->addr6;
1875 for (; !match && i > 0; d += 2,
1876 i -= F_INSN_SIZE(struct in6_addr)
1882 APPLY_MASK(&p, &d[1]);
1884 IN6_ARE_ADDR_EQUAL(&d[0],
1892 flow6id_match(args->f_id.flow_id6,
1893 (ipfw_insn_u32 *) cmd);
1898 (ext_hd & ((ipfw_insn *) cmd)->arg1);
1912 uint32_t tag = IP_FW_ARG_TABLEARG(cmd->arg1);
1914 /* Packet is already tagged with this tag? */
1915 mtag = m_tag_locate(m, MTAG_IPFW, tag, NULL);
1917 /* We have `untag' action when F_NOT flag is
1918 * present. And we must remove this mtag from
1919 * mbuf and reset `match' to zero (`match' will
1920 * be inversed later).
1921 * Otherwise we should allocate new mtag and
1922 * push it into mbuf.
1924 if (cmd->len & F_NOT) { /* `untag' action */
1926 m_tag_delete(m, mtag);
1930 mtag = m_tag_alloc( MTAG_IPFW,
1933 m_tag_prepend(m, mtag);
1940 case O_FIB: /* try match the specified fib */
1941 if (args->f_id.fib == cmd->arg1)
1946 struct inpcb *inp = args->inp;
1947 struct inpcbinfo *pi;
1949 if (is_ipv6) /* XXX can we remove this ? */
1952 if (proto == IPPROTO_TCP)
1954 else if (proto == IPPROTO_UDP)
1960 * XXXRW: so_user_cookie should almost
1961 * certainly be inp_user_cookie?
1964 /* For incomming packet, lookup up the
1965 inpcb using the src/dest ip/port tuple */
1967 inp = in_pcblookup(pi,
1968 src_ip, htons(src_port),
1969 dst_ip, htons(dst_port),
1970 INPLOOKUP_RLOCKPCB, NULL);
1973 inp->inp_socket->so_user_cookie;
1979 if (inp->inp_socket) {
1981 inp->inp_socket->so_user_cookie;
1991 uint32_t tag = IP_FW_ARG_TABLEARG(cmd->arg1);
1994 match = m_tag_locate(m, MTAG_IPFW,
1999 /* we have ranges */
2000 for (mtag = m_tag_first(m);
2001 mtag != NULL && !match;
2002 mtag = m_tag_next(m, mtag)) {
2006 if (mtag->m_tag_cookie != MTAG_IPFW)
2009 p = ((ipfw_insn_u16 *)cmd)->ports;
2011 for(; !match && i > 0; i--, p += 2)
2013 mtag->m_tag_id >= p[0] &&
2014 mtag->m_tag_id <= p[1];
2020 * The second set of opcodes represents 'actions',
2021 * i.e. the terminal part of a rule once the packet
2022 * matches all previous patterns.
2023 * Typically there is only one action for each rule,
2024 * and the opcode is stored at the end of the rule
2025 * (but there are exceptions -- see below).
2027 * In general, here we set retval and terminate the
2028 * outer loop (would be a 'break 3' in some language,
2029 * but we need to set l=0, done=1)
2032 * O_COUNT and O_SKIPTO actions:
2033 * instead of terminating, we jump to the next rule
2034 * (setting l=0), or to the SKIPTO target (setting
2035 * f/f_len, cmd and l as needed), respectively.
2037 * O_TAG, O_LOG and O_ALTQ action parameters:
2038 * perform some action and set match = 1;
2040 * O_LIMIT and O_KEEP_STATE: these opcodes are
2041 * not real 'actions', and are stored right
2042 * before the 'action' part of the rule.
2043 * These opcodes try to install an entry in the
2044 * state tables; if successful, we continue with
2045 * the next opcode (match=1; break;), otherwise
2046 * the packet must be dropped (set retval,
2047 * break loops with l=0, done=1)
2049 * O_PROBE_STATE and O_CHECK_STATE: these opcodes
2050 * cause a lookup of the state table, and a jump
2051 * to the 'action' part of the parent rule
2052 * if an entry is found, or
2053 * (CHECK_STATE only) a jump to the next rule if
2054 * the entry is not found.
2055 * The result of the lookup is cached so that
2056 * further instances of these opcodes become NOPs.
2057 * The jump to the next rule is done by setting
2062 if (ipfw_install_state(f,
2063 (ipfw_insn_limit *)cmd, args, tablearg)) {
2064 /* error or limit violation */
2065 retval = IP_FW_DENY;
2066 l = 0; /* exit inner loop */
2067 done = 1; /* exit outer loop */
2075 * dynamic rules are checked at the first
2076 * keep-state or check-state occurrence,
2077 * with the result being stored in dyn_dir.
2078 * The compiler introduces a PROBE_STATE
2079 * instruction for us when we have a
2080 * KEEP_STATE (because PROBE_STATE needs
2083 if (dyn_dir == MATCH_UNKNOWN &&
2084 (q = ipfw_lookup_dyn_rule(&args->f_id,
2085 &dyn_dir, proto == IPPROTO_TCP ?
2089 * Found dynamic entry, update stats
2090 * and jump to the 'action' part of
2091 * the parent rule by setting
2092 * f, cmd, l and clearing cmdlen.
2094 IPFW_INC_DYN_COUNTER(q, pktlen);
2095 /* XXX we would like to have f_pos
2096 * readily accessible in the dynamic
2097 * rule, instead of having to
2101 f_pos = ipfw_find_rule(chain,
2103 cmd = ACTION_PTR(f);
2104 l = f->cmd_len - f->act_ofs;
2111 * Dynamic entry not found. If CHECK_STATE,
2112 * skip to next rule, if PROBE_STATE just
2113 * ignore and continue with next opcode.
2115 if (cmd->opcode == O_CHECK_STATE)
2116 l = 0; /* exit inner loop */
2121 retval = 0; /* accept */
2122 l = 0; /* exit inner loop */
2123 done = 1; /* exit outer loop */
2128 set_match(args, f_pos, chain);
2129 args->rule.info = IP_FW_ARG_TABLEARG(cmd->arg1);
2130 if (cmd->opcode == O_PIPE)
2131 args->rule.info |= IPFW_IS_PIPE;
2133 args->rule.info |= IPFW_ONEPASS;
2134 retval = IP_FW_DUMMYNET;
2135 l = 0; /* exit inner loop */
2136 done = 1; /* exit outer loop */
2141 if (args->eh) /* not on layer 2 */
2143 /* otherwise this is terminal */
2144 l = 0; /* exit inner loop */
2145 done = 1; /* exit outer loop */
2146 retval = (cmd->opcode == O_DIVERT) ?
2147 IP_FW_DIVERT : IP_FW_TEE;
2148 set_match(args, f_pos, chain);
2149 args->rule.info = IP_FW_ARG_TABLEARG(cmd->arg1);
2153 IPFW_INC_RULE_COUNTER(f, pktlen);
2154 l = 0; /* exit inner loop */
2158 IPFW_INC_RULE_COUNTER(f, pktlen);
2159 f_pos = jump_fast(chain, f, cmd->arg1, tablearg, 0);
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
2166 for (; f_pos < chain->n_rules - 1 &&
2168 (1 << chain->map[f_pos]->set));
2171 /* Re-enter the inner loop at the skipto rule. */
2172 f = chain->map[f_pos];
2179 break; /* not reached */
2181 case O_CALLRETURN: {
2183 * Implementation of `subroutine' call/return,
2184 * in the stack carried in an mbuf tag. This
2185 * is different from `skipto' in that any call
2186 * address is possible (`skipto' must prevent
2187 * backward jumps to avoid endless loops).
2188 * We have `return' action when F_NOT flag is
2189 * present. The `m_tag_id' field is used as
2193 uint16_t jmpto, *stack;
2195 #define IS_CALL ((cmd->len & F_NOT) == 0)
2196 #define IS_RETURN ((cmd->len & F_NOT) != 0)
2198 * Hand-rolled version of m_tag_locate() with
2200 * If not already tagged, allocate new tag.
2202 mtag = m_tag_first(m);
2203 while (mtag != NULL) {
2204 if (mtag->m_tag_cookie ==
2207 mtag = m_tag_next(m, mtag);
2209 if (mtag == NULL && IS_CALL) {
2210 mtag = m_tag_alloc(MTAG_IPFW_CALL, 0,
2211 IPFW_CALLSTACK_SIZE *
2212 sizeof(uint16_t), M_NOWAIT);
2214 m_tag_prepend(m, mtag);
2218 * On error both `call' and `return' just
2219 * continue with next rule.
2221 if (IS_RETURN && (mtag == NULL ||
2222 mtag->m_tag_id == 0)) {
2223 l = 0; /* exit inner loop */
2226 if (IS_CALL && (mtag == NULL ||
2227 mtag->m_tag_id >= IPFW_CALLSTACK_SIZE)) {
2228 printf("ipfw: call stack error, "
2229 "go to next rule\n");
2230 l = 0; /* exit inner loop */
2234 IPFW_INC_RULE_COUNTER(f, pktlen);
2235 stack = (uint16_t *)(mtag + 1);
2238 * The `call' action may use cached f_pos
2239 * (in f->next_rule), whose version is written
2241 * The `return' action, however, doesn't have
2242 * fixed jump address in cmd->arg1 and can't use
2246 stack[mtag->m_tag_id] = f->rulenum;
2248 f_pos = jump_fast(chain, f, cmd->arg1,
2250 } else { /* `return' action */
2252 jmpto = stack[mtag->m_tag_id] + 1;
2253 f_pos = ipfw_find_rule(chain, jmpto, 0);
2257 * Skip disabled rules, and re-enter
2258 * the inner loop with the correct
2259 * f_pos, f, l and cmd.
2260 * Also clear cmdlen and skip_or
2262 for (; f_pos < chain->n_rules - 1 &&
2264 (1 << chain->map[f_pos]->set)); f_pos++)
2266 /* Re-enter the inner loop at the dest rule. */
2267 f = chain->map[f_pos];
2273 break; /* NOTREACHED */
2280 * Drop the packet and send a reject notice
2281 * if the packet is not ICMP (or is an ICMP
2282 * query), and it is not multicast/broadcast.
2284 if (hlen > 0 && is_ipv4 && offset == 0 &&
2285 (proto != IPPROTO_ICMP ||
2286 is_icmp_query(ICMP(ulp))) &&
2287 !(m->m_flags & (M_BCAST|M_MCAST)) &&
2288 !IN_MULTICAST(ntohl(dst_ip.s_addr))) {
2289 send_reject(args, cmd->arg1, iplen, ip);
2295 if (hlen > 0 && is_ipv6 &&
2296 ((offset & IP6F_OFF_MASK) == 0) &&
2297 (proto != IPPROTO_ICMPV6 ||
2298 (is_icmp6_query(icmp6_type) == 1)) &&
2299 !(m->m_flags & (M_BCAST|M_MCAST)) &&
2300 !IN6_IS_ADDR_MULTICAST(&args->f_id.dst_ip6)) {
2302 args, cmd->arg1, hlen,
2303 (struct ip6_hdr *)ip);
2309 retval = IP_FW_DENY;
2310 l = 0; /* exit inner loop */
2311 done = 1; /* exit outer loop */
2315 if (args->eh) /* not valid on layer2 pkts */
2317 if (q == NULL || q->rule != f ||
2318 dyn_dir == MATCH_FORWARD) {
2319 struct sockaddr_in *sa;
2320 sa = &(((ipfw_insn_sa *)cmd)->sa);
2321 if (sa->sin_addr.s_addr == INADDR_ANY) {
2322 bcopy(sa, &args->hopstore,
2324 args->hopstore.sin_addr.s_addr =
2326 args->next_hop = &args->hopstore;
2328 args->next_hop = sa;
2331 retval = IP_FW_PASS;
2332 l = 0; /* exit inner loop */
2333 done = 1; /* exit outer loop */
2338 if (args->eh) /* not valid on layer2 pkts */
2340 if (q == NULL || q->rule != f ||
2341 dyn_dir == MATCH_FORWARD) {
2342 struct sockaddr_in6 *sin6;
2344 sin6 = &(((ipfw_insn_sa6 *)cmd)->sa);
2345 args->next_hop6 = sin6;
2347 retval = IP_FW_PASS;
2348 l = 0; /* exit inner loop */
2349 done = 1; /* exit outer loop */
2355 set_match(args, f_pos, chain);
2356 args->rule.info = IP_FW_ARG_TABLEARG(cmd->arg1);
2358 args->rule.info |= IPFW_ONEPASS;
2359 retval = (cmd->opcode == O_NETGRAPH) ?
2360 IP_FW_NETGRAPH : IP_FW_NGTEE;
2361 l = 0; /* exit inner loop */
2362 done = 1; /* exit outer loop */
2368 IPFW_INC_RULE_COUNTER(f, pktlen);
2369 fib = IP_FW_ARG_TABLEARG(cmd->arg1);
2370 if (fib >= rt_numfibs)
2373 args->f_id.fib = fib;
2374 l = 0; /* exit inner loop */
2381 code = IP_FW_ARG_TABLEARG(cmd->arg1) & 0x3F;
2382 l = 0; /* exit inner loop */
2387 ip->ip_tos = (code << 2) | (ip->ip_tos & 0x03);
2388 a += ntohs(ip->ip_sum) - ip->ip_tos;
2389 ip->ip_sum = htons(a);
2390 } else if (is_ipv6) {
2393 v = &((struct ip6_hdr *)ip)->ip6_vfc;
2394 *v = (*v & 0xF0) | (code >> 2);
2396 *v = (*v & 0x3F) | ((code & 0x03) << 6);
2400 IPFW_INC_RULE_COUNTER(f, pktlen);
2405 l = 0; /* exit inner loop */
2406 done = 1; /* exit outer loop */
2407 if (!IPFW_NAT_LOADED) {
2408 retval = IP_FW_DENY;
2415 set_match(args, f_pos, chain);
2416 /* Check if this is 'global' nat rule */
2417 if (cmd->arg1 == 0) {
2418 retval = ipfw_nat_ptr(args, NULL, m);
2421 t = ((ipfw_insn_nat *)cmd)->nat;
2423 nat_id = IP_FW_ARG_TABLEARG(cmd->arg1);
2424 t = (*lookup_nat_ptr)(&chain->nat, nat_id);
2427 retval = IP_FW_DENY;
2430 if (cmd->arg1 != IP_FW_TABLEARG)
2431 ((ipfw_insn_nat *)cmd)->nat = t;
2433 retval = ipfw_nat_ptr(args, t, m);
2439 IPFW_INC_RULE_COUNTER(f, pktlen);
2440 l = 0; /* in any case exit inner loop */
2441 ip_off = ntohs(ip->ip_off);
2443 /* if not fragmented, go to next rule */
2444 if ((ip_off & (IP_MF | IP_OFFMASK)) == 0)
2447 * ip_reass() expects len & off in host
2452 args->m = m = ip_reass(m);
2455 * do IP header checksum fixup.
2457 if (m == NULL) { /* fragment got swallowed */
2458 retval = IP_FW_DENY;
2459 } else { /* good, packet complete */
2462 ip = mtod(m, struct ip *);
2463 hlen = ip->ip_hl << 2;
2466 if (hlen == sizeof(struct ip))
2467 ip->ip_sum = in_cksum_hdr(ip);
2469 ip->ip_sum = in_cksum(m, hlen);
2470 retval = IP_FW_REASS;
2471 set_match(args, f_pos, chain);
2473 done = 1; /* exit outer loop */
2478 panic("-- unknown opcode %d\n", cmd->opcode);
2479 } /* end of switch() on opcodes */
2481 * if we get here with l=0, then match is irrelevant.
2484 if (cmd->len & F_NOT)
2488 if (cmd->len & F_OR)
2491 if (!(cmd->len & F_OR)) /* not an OR block, */
2492 break; /* try next rule */
2495 } /* end of inner loop, scan opcodes */
2501 /* next_rule:; */ /* try next rule */
2503 } /* end of outer for, scan rules */
2506 struct ip_fw *rule = chain->map[f_pos];
2507 /* Update statistics */
2508 IPFW_INC_RULE_COUNTER(rule, pktlen);
2510 retval = IP_FW_DENY;
2511 printf("ipfw: ouch!, skip past end of rules, denying packet\n");
2513 IPFW_RUNLOCK(chain);
2515 if (ucred_cache != NULL)
2516 crfree(ucred_cache);
2522 printf("ipfw: pullup failed\n");
2523 return (IP_FW_DENY);
2527 * Set maximum number of tables that can be used in given VNET ipfw instance.
2531 sysctl_ipfw_table_num(SYSCTL_HANDLER_ARGS)
2534 unsigned int ntables;
2536 ntables = V_fw_tables_max;
2538 error = sysctl_handle_int(oidp, &ntables, 0, req);
2539 /* Read operation or some error */
2540 if ((error != 0) || (req->newptr == NULL))
2543 return (ipfw_resize_tables(&V_layer3_chain, ntables));
2547 * Module and VNET glue
2551 * Stuff that must be initialised only on boot or module load
2559 * Only print out this stuff the first time around,
2560 * when called from the sysinit code.
2566 "initialized, divert %s, nat %s, "
2567 "default to %s, logging ",
2573 #ifdef IPFIREWALL_NAT
2578 default_to_accept ? "accept" : "deny");
2581 * Note: V_xxx variables can be accessed here but the vnet specific
2582 * initializer may not have been called yet for the VIMAGE case.
2583 * Tuneables will have been processed. We will print out values for
2585 * XXX This should all be rationalized AFTER 8.0
2587 if (V_fw_verbose == 0)
2588 printf("disabled\n");
2589 else if (V_verbose_limit == 0)
2590 printf("unlimited\n");
2592 printf("limited to %d packets/entry by default\n",
2595 /* Check user-supplied table count for validness */
2596 if (default_fw_tables > IPFW_TABLES_MAX)
2597 default_fw_tables = IPFW_TABLES_MAX;
2599 ipfw_log_bpf(1); /* init */
2604 * Called for the removal of the last instance only on module unload.
2610 ipfw_log_bpf(0); /* uninit */
2611 printf("IP firewall unloaded\n");
2615 * Stuff that must be initialized for every instance
2616 * (including the first of course).
2619 vnet_ipfw_init(const void *unused)
2622 struct ip_fw *rule = NULL;
2623 struct ip_fw_chain *chain;
2625 chain = &V_layer3_chain;
2627 /* First set up some values that are compile time options */
2628 V_autoinc_step = 100; /* bounded to 1..1000 in add_rule() */
2629 V_fw_deny_unknown_exthdrs = 1;
2630 #ifdef IPFIREWALL_VERBOSE
2633 #ifdef IPFIREWALL_VERBOSE_LIMIT
2634 V_verbose_limit = IPFIREWALL_VERBOSE_LIMIT;
2636 #ifdef IPFIREWALL_NAT
2637 LIST_INIT(&chain->nat);
2640 /* insert the default rule and create the initial map */
2642 chain->static_len = sizeof(struct ip_fw);
2643 chain->map = malloc(sizeof(struct ip_fw *), M_IPFW, M_WAITOK | M_ZERO);
2645 rule = malloc(chain->static_len, M_IPFW, M_WAITOK | M_ZERO);
2647 /* Set initial number of tables */
2648 V_fw_tables_max = default_fw_tables;
2649 error = ipfw_init_tables(chain);
2651 printf("ipfw2: setting up tables failed\n");
2652 free(chain->map, M_IPFW);
2657 /* fill and insert the default rule */
2659 rule->rulenum = IPFW_DEFAULT_RULE;
2661 rule->set = RESVD_SET;
2662 rule->cmd[0].len = 1;
2663 rule->cmd[0].opcode = default_to_accept ? O_ACCEPT : O_DENY;
2664 chain->default_rule = chain->map[0] = rule;
2665 chain->id = rule->id = 1;
2667 IPFW_LOCK_INIT(chain);
2668 ipfw_dyn_init(chain);
2670 /* First set up some values that are compile time options */
2671 V_ipfw_vnet_ready = 1; /* Open for business */
2674 * Hook the sockopt handler, and the layer2 (V_ip_fw_chk_ptr)
2675 * and pfil hooks for ipv4 and ipv6. Even if the latter two fail
2676 * we still keep the module alive because the sockopt and
2677 * layer2 paths are still useful.
2678 * ipfw[6]_hook return 0 on success, ENOENT on failure,
2679 * so we can ignore the exact return value and just set a flag.
2681 * Note that V_fw[6]_enable are manipulated by a SYSCTL_PROC so
2682 * changes in the underlying (per-vnet) variables trigger
2683 * immediate hook()/unhook() calls.
2684 * In layer2 we have the same behaviour, except that V_ether_ipfw
2685 * is checked on each packet because there are no pfil hooks.
2687 V_ip_fw_ctl_ptr = ipfw_ctl;
2688 V_ip_fw_chk_ptr = ipfw_chk;
2689 error = ipfw_attach_hooks(1);
2694 * Called for the removal of each instance.
2697 vnet_ipfw_uninit(const void *unused)
2699 struct ip_fw *reap, *rule;
2700 struct ip_fw_chain *chain = &V_layer3_chain;
2703 V_ipfw_vnet_ready = 0; /* tell new callers to go away */
2705 * disconnect from ipv4, ipv6, layer2 and sockopt.
2706 * Then grab, release and grab again the WLOCK so we make
2707 * sure the update is propagated and nobody will be in.
2709 (void)ipfw_attach_hooks(0 /* detach */);
2710 V_ip_fw_chk_ptr = NULL;
2711 V_ip_fw_ctl_ptr = NULL;
2712 IPFW_UH_WLOCK(chain);
2713 IPFW_UH_WUNLOCK(chain);
2714 IPFW_UH_WLOCK(chain);
2717 ipfw_dyn_uninit(0); /* run the callout_drain */
2718 IPFW_WUNLOCK(chain);
2720 ipfw_destroy_tables(chain);
2723 for (i = 0; i < chain->n_rules; i++) {
2724 rule = chain->map[i];
2725 rule->x_next = reap;
2729 free(chain->map, M_IPFW);
2730 IPFW_WUNLOCK(chain);
2731 IPFW_UH_WUNLOCK(chain);
2733 ipfw_reap_rules(reap);
2734 IPFW_LOCK_DESTROY(chain);
2735 ipfw_dyn_uninit(1); /* free the remaining parts */
2740 * Module event handler.
2741 * In general we have the choice of handling most of these events by the
2742 * event handler or by the (VNET_)SYS(UN)INIT handlers. I have chosen to
2743 * use the SYSINIT handlers as they are more capable of expressing the
2744 * flow of control during module and vnet operations, so this is just
2745 * a skeleton. Note there is no SYSINIT equivalent of the module
2746 * SHUTDOWN handler, but we don't have anything to do in that case anyhow.
2749 ipfw_modevent(module_t mod, int type, void *unused)
2755 /* Called once at module load or
2756 * system boot if compiled in. */
2759 /* Called before unload. May veto unloading. */
2762 /* Called during unload. */
2765 /* Called during system shutdown. */
2774 static moduledata_t ipfwmod = {
2780 /* Define startup order. */
2781 #define IPFW_SI_SUB_FIREWALL SI_SUB_PROTO_IFATTACHDOMAIN
2782 #define IPFW_MODEVENT_ORDER (SI_ORDER_ANY - 255) /* On boot slot in here. */
2783 #define IPFW_MODULE_ORDER (IPFW_MODEVENT_ORDER + 1) /* A little later. */
2784 #define IPFW_VNET_ORDER (IPFW_MODEVENT_ORDER + 2) /* Later still. */
2786 DECLARE_MODULE(ipfw, ipfwmod, IPFW_SI_SUB_FIREWALL, IPFW_MODEVENT_ORDER);
2787 MODULE_VERSION(ipfw, 2);
2788 /* should declare some dependencies here */
2791 * Starting up. Done in order after ipfwmod() has been called.
2792 * VNET_SYSINIT is also called for each existing vnet and each new vnet.
2794 SYSINIT(ipfw_init, IPFW_SI_SUB_FIREWALL, IPFW_MODULE_ORDER,
2796 VNET_SYSINIT(vnet_ipfw_init, IPFW_SI_SUB_FIREWALL, IPFW_VNET_ORDER,
2797 vnet_ipfw_init, NULL);
2800 * Closing up shop. These are done in REVERSE ORDER, but still
2801 * after ipfwmod() has been called. Not called on reboot.
2802 * VNET_SYSUNINIT is also called for each exiting vnet as it exits.
2803 * or when the module is unloaded.
2805 SYSUNINIT(ipfw_destroy, IPFW_SI_SUB_FIREWALL, IPFW_MODULE_ORDER,
2806 ipfw_destroy, NULL);
2807 VNET_SYSUNINIT(vnet_ipfw_uninit, IPFW_SI_SUB_FIREWALL, IPFW_VNET_ORDER,
2808 vnet_ipfw_uninit, NULL);