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>
66 #include <netpfil/pf/pf_mtag.h>
68 #include <netinet/in.h>
69 #include <netinet/in_var.h>
70 #include <netinet/in_pcb.h>
71 #include <netinet/ip.h>
72 #include <netinet/ip_var.h>
73 #include <netinet/ip_icmp.h>
74 #include <netinet/ip_fw.h>
75 #include <netinet/ip_carp.h>
76 #include <netinet/pim.h>
77 #include <netinet/tcp_var.h>
78 #include <netinet/udp.h>
79 #include <netinet/udp_var.h>
80 #include <netinet/sctp.h>
82 #include <netinet/ip6.h>
83 #include <netinet/icmp6.h>
85 #include <netinet6/in6_pcb.h>
86 #include <netinet6/scope6_var.h>
87 #include <netinet6/ip6_var.h>
90 #include <netpfil/ipfw/ip_fw_private.h>
92 #include <machine/in_cksum.h> /* XXX for in_cksum */
95 #include <security/mac/mac_framework.h>
99 * static variables followed by global ones.
100 * All ipfw global variables are here.
103 /* ipfw_vnet_ready controls when we are open for business */
104 static VNET_DEFINE(int, ipfw_vnet_ready) = 0;
105 #define V_ipfw_vnet_ready VNET(ipfw_vnet_ready)
107 static VNET_DEFINE(int, fw_deny_unknown_exthdrs);
108 #define V_fw_deny_unknown_exthdrs VNET(fw_deny_unknown_exthdrs)
110 static VNET_DEFINE(int, fw_permit_single_frag6) = 1;
111 #define V_fw_permit_single_frag6 VNET(fw_permit_single_frag6)
113 #ifdef IPFIREWALL_DEFAULT_TO_ACCEPT
114 static int default_to_accept = 1;
116 static int default_to_accept;
119 VNET_DEFINE(int, autoinc_step);
120 VNET_DEFINE(int, fw_one_pass) = 1;
122 VNET_DEFINE(unsigned int, fw_tables_max);
123 /* Use 128 tables by default */
124 static unsigned int default_fw_tables = IPFW_TABLES_DEFAULT;
127 * Each rule belongs to one of 32 different sets (0..31).
128 * The variable set_disable contains one bit per set.
129 * If the bit is set, all rules in the corresponding set
130 * are disabled. Set RESVD_SET(31) is reserved for the default rule
131 * and rules that are not deleted by the flush command,
132 * and CANNOT be disabled.
133 * Rules in set RESVD_SET can only be deleted individually.
135 VNET_DEFINE(u_int32_t, set_disable);
136 #define V_set_disable VNET(set_disable)
138 VNET_DEFINE(int, fw_verbose);
139 /* counter for ipfw_log(NULL...) */
140 VNET_DEFINE(u_int64_t, norule_counter);
141 VNET_DEFINE(int, verbose_limit);
143 /* layer3_chain contains the list of rules for layer 3 */
144 VNET_DEFINE(struct ip_fw_chain, layer3_chain);
146 VNET_DEFINE(int, ipfw_nat_ready) = 0;
148 ipfw_nat_t *ipfw_nat_ptr = NULL;
149 struct cfg_nat *(*lookup_nat_ptr)(struct nat_list *, int);
150 ipfw_nat_cfg_t *ipfw_nat_cfg_ptr;
151 ipfw_nat_cfg_t *ipfw_nat_del_ptr;
152 ipfw_nat_cfg_t *ipfw_nat_get_cfg_ptr;
153 ipfw_nat_cfg_t *ipfw_nat_get_log_ptr;
156 uint32_t dummy_def = IPFW_DEFAULT_RULE;
157 static int sysctl_ipfw_table_num(SYSCTL_HANDLER_ARGS);
161 SYSCTL_NODE(_net_inet_ip, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall");
162 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, one_pass,
163 CTLFLAG_RW | CTLFLAG_SECURE3, &VNET_NAME(fw_one_pass), 0,
164 "Only do a single pass through ipfw when using dummynet(4)");
165 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, autoinc_step,
166 CTLFLAG_RW, &VNET_NAME(autoinc_step), 0,
167 "Rule number auto-increment step");
168 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, verbose,
169 CTLFLAG_RW | CTLFLAG_SECURE3, &VNET_NAME(fw_verbose), 0,
170 "Log matches to ipfw rules");
171 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, verbose_limit,
172 CTLFLAG_RW, &VNET_NAME(verbose_limit), 0,
173 "Set upper limit of matches of ipfw rules logged");
174 SYSCTL_UINT(_net_inet_ip_fw, OID_AUTO, default_rule, CTLFLAG_RD,
176 "The default/max possible rule number.");
177 SYSCTL_VNET_PROC(_net_inet_ip_fw, OID_AUTO, tables_max,
178 CTLTYPE_UINT|CTLFLAG_RW, 0, 0, sysctl_ipfw_table_num, "IU",
179 "Maximum number of tables");
180 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, default_to_accept, CTLFLAG_RDTUN,
181 &default_to_accept, 0,
182 "Make the default rule accept all packets.");
183 TUNABLE_INT("net.inet.ip.fw.default_to_accept", &default_to_accept);
184 TUNABLE_INT("net.inet.ip.fw.tables_max", (int *)&default_fw_tables);
185 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, static_count,
186 CTLFLAG_RD, &VNET_NAME(layer3_chain.n_rules), 0,
187 "Number of static rules");
190 SYSCTL_DECL(_net_inet6_ip6);
191 SYSCTL_NODE(_net_inet6_ip6, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall");
192 SYSCTL_VNET_INT(_net_inet6_ip6_fw, OID_AUTO, deny_unknown_exthdrs,
193 CTLFLAG_RW | CTLFLAG_SECURE, &VNET_NAME(fw_deny_unknown_exthdrs), 0,
194 "Deny packets with unknown IPv6 Extension Headers");
195 SYSCTL_VNET_INT(_net_inet6_ip6_fw, OID_AUTO, permit_single_frag6,
196 CTLFLAG_RW | CTLFLAG_SECURE, &VNET_NAME(fw_permit_single_frag6), 0,
197 "Permit single packet IPv6 fragments");
202 #endif /* SYSCTL_NODE */
206 * Some macros used in the various matching options.
207 * L3HDR maps an ipv4 pointer into a layer3 header pointer of type T
208 * Other macros just cast void * into the appropriate type
210 #define L3HDR(T, ip) ((T *)((u_int32_t *)(ip) + (ip)->ip_hl))
211 #define TCP(p) ((struct tcphdr *)(p))
212 #define SCTP(p) ((struct sctphdr *)(p))
213 #define UDP(p) ((struct udphdr *)(p))
214 #define ICMP(p) ((struct icmphdr *)(p))
215 #define ICMP6(p) ((struct icmp6_hdr *)(p))
218 icmptype_match(struct icmphdr *icmp, ipfw_insn_u32 *cmd)
220 int type = icmp->icmp_type;
222 return (type <= ICMP_MAXTYPE && (cmd->d[0] & (1<<type)) );
225 #define TT ( (1 << ICMP_ECHO) | (1 << ICMP_ROUTERSOLICIT) | \
226 (1 << ICMP_TSTAMP) | (1 << ICMP_IREQ) | (1 << ICMP_MASKREQ) )
229 is_icmp_query(struct icmphdr *icmp)
231 int type = icmp->icmp_type;
233 return (type <= ICMP_MAXTYPE && (TT & (1<<type)) );
238 * The following checks use two arrays of 8 or 16 bits to store the
239 * bits that we want set or clear, respectively. They are in the
240 * low and high half of cmd->arg1 or cmd->d[0].
242 * We scan options and store the bits we find set. We succeed if
244 * (want_set & ~bits) == 0 && (want_clear & ~bits) == want_clear
246 * The code is sometimes optimized not to store additional variables.
250 flags_match(ipfw_insn *cmd, u_int8_t bits)
255 if ( ((cmd->arg1 & 0xff) & bits) != 0)
256 return 0; /* some bits we want set were clear */
257 want_clear = (cmd->arg1 >> 8) & 0xff;
258 if ( (want_clear & bits) != want_clear)
259 return 0; /* some bits we want clear were set */
264 ipopts_match(struct ip *ip, ipfw_insn *cmd)
266 int optlen, bits = 0;
267 u_char *cp = (u_char *)(ip + 1);
268 int x = (ip->ip_hl << 2) - sizeof (struct ip);
270 for (; x > 0; x -= optlen, cp += optlen) {
271 int opt = cp[IPOPT_OPTVAL];
273 if (opt == IPOPT_EOL)
275 if (opt == IPOPT_NOP)
278 optlen = cp[IPOPT_OLEN];
279 if (optlen <= 0 || optlen > x)
280 return 0; /* invalid or truncated */
288 bits |= IP_FW_IPOPT_LSRR;
292 bits |= IP_FW_IPOPT_SSRR;
296 bits |= IP_FW_IPOPT_RR;
300 bits |= IP_FW_IPOPT_TS;
304 return (flags_match(cmd, bits));
308 tcpopts_match(struct tcphdr *tcp, ipfw_insn *cmd)
310 int optlen, bits = 0;
311 u_char *cp = (u_char *)(tcp + 1);
312 int x = (tcp->th_off << 2) - sizeof(struct tcphdr);
314 for (; x > 0; x -= optlen, cp += optlen) {
316 if (opt == TCPOPT_EOL)
318 if (opt == TCPOPT_NOP)
332 bits |= IP_FW_TCPOPT_MSS;
336 bits |= IP_FW_TCPOPT_WINDOW;
339 case TCPOPT_SACK_PERMITTED:
341 bits |= IP_FW_TCPOPT_SACK;
344 case TCPOPT_TIMESTAMP:
345 bits |= IP_FW_TCPOPT_TS;
350 return (flags_match(cmd, bits));
354 iface_match(struct ifnet *ifp, ipfw_insn_if *cmd, struct ip_fw_chain *chain, uint32_t *tablearg)
356 if (ifp == NULL) /* no iface with this packet, match fails */
358 /* Check by name or by IP address */
359 if (cmd->name[0] != '\0') { /* match by name */
360 if (cmd->name[0] == '\1') /* use tablearg to match */
361 return ipfw_lookup_table_extended(chain, cmd->p.glob,
362 ifp->if_xname, tablearg, IPFW_TABLE_INTERFACE);
365 if (fnmatch(cmd->name, ifp->if_xname, 0) == 0)
368 if (strncmp(ifp->if_xname, cmd->name, IFNAMSIZ) == 0)
372 #ifdef __FreeBSD__ /* and OSX too ? */
376 TAILQ_FOREACH(ia, &ifp->if_addrhead, ifa_link) {
377 if (ia->ifa_addr->sa_family != AF_INET)
379 if (cmd->p.ip.s_addr == ((struct sockaddr_in *)
380 (ia->ifa_addr))->sin_addr.s_addr) {
381 if_addr_runlock(ifp);
382 return(1); /* match */
385 if_addr_runlock(ifp);
386 #endif /* __FreeBSD__ */
388 return(0); /* no match, fail ... */
392 * The verify_path function checks if a route to the src exists and
393 * if it is reachable via ifp (when provided).
395 * The 'verrevpath' option checks that the interface that an IP packet
396 * arrives on is the same interface that traffic destined for the
397 * packet's source address would be routed out of.
398 * The 'versrcreach' option just checks that the source address is
399 * reachable via any route (except default) in the routing table.
400 * These two are a measure to block forged packets. This is also
401 * commonly known as "anti-spoofing" or Unicast Reverse Path
402 * Forwarding (Unicast RFP) in Cisco-ese. The name of the knobs
403 * is purposely reminiscent of the Cisco IOS command,
405 * ip verify unicast reverse-path
406 * ip verify unicast source reachable-via any
408 * which implements the same functionality. But note that the syntax
409 * is misleading, and the check may be performed on all IP packets
410 * whether unicast, multicast, or broadcast.
413 verify_path(struct in_addr src, struct ifnet *ifp, u_int fib)
419 struct sockaddr_in *dst;
421 bzero(&ro, sizeof(ro));
423 dst = (struct sockaddr_in *)&(ro.ro_dst);
424 dst->sin_family = AF_INET;
425 dst->sin_len = sizeof(*dst);
427 in_rtalloc_ign(&ro, 0, fib);
429 if (ro.ro_rt == NULL)
433 * If ifp is provided, check for equality with rtentry.
434 * We should use rt->rt_ifa->ifa_ifp, instead of rt->rt_ifp,
435 * in order to pass packets injected back by if_simloop():
436 * if useloopback == 1 routing entry (via lo0) for our own address
437 * may exist, so we need to handle routing assymetry.
439 if (ifp != NULL && ro.ro_rt->rt_ifa->ifa_ifp != ifp) {
444 /* if no ifp provided, check if rtentry is not default route */
446 satosin(rt_key(ro.ro_rt))->sin_addr.s_addr == INADDR_ANY) {
451 /* or if this is a blackhole/reject route */
452 if (ifp == NULL && ro.ro_rt->rt_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
457 /* found valid route */
460 #endif /* __FreeBSD__ */
465 * ipv6 specific rules here...
468 icmp6type_match (int type, ipfw_insn_u32 *cmd)
470 return (type <= ICMP6_MAXTYPE && (cmd->d[type/32] & (1<<(type%32)) ) );
474 flow6id_match( int curr_flow, ipfw_insn_u32 *cmd )
477 for (i=0; i <= cmd->o.arg1; ++i )
478 if (curr_flow == cmd->d[i] )
483 /* support for IP6_*_ME opcodes */
485 search_ip6_addr_net (struct in6_addr * ip6_addr)
489 struct in6_ifaddr *fdm;
490 struct in6_addr copia;
492 TAILQ_FOREACH(mdc, &V_ifnet, if_link) {
494 TAILQ_FOREACH(mdc2, &mdc->if_addrhead, ifa_link) {
495 if (mdc2->ifa_addr->sa_family == AF_INET6) {
496 fdm = (struct in6_ifaddr *)mdc2;
497 copia = fdm->ia_addr.sin6_addr;
498 /* need for leaving scope_id in the sock_addr */
499 in6_clearscope(&copia);
500 if (IN6_ARE_ADDR_EQUAL(ip6_addr, &copia)) {
501 if_addr_runlock(mdc);
506 if_addr_runlock(mdc);
512 verify_path6(struct in6_addr *src, struct ifnet *ifp, u_int fib)
515 struct sockaddr_in6 *dst;
517 bzero(&ro, sizeof(ro));
519 dst = (struct sockaddr_in6 * )&(ro.ro_dst);
520 dst->sin6_family = AF_INET6;
521 dst->sin6_len = sizeof(*dst);
522 dst->sin6_addr = *src;
524 in6_rtalloc_ign(&ro, 0, fib);
525 if (ro.ro_rt == NULL)
529 * if ifp is provided, check for equality with rtentry
530 * We should use rt->rt_ifa->ifa_ifp, instead of rt->rt_ifp,
531 * to support the case of sending packets to an address of our own.
532 * (where the former interface is the first argument of if_simloop()
533 * (=ifp), the latter is lo0)
535 if (ifp != NULL && ro.ro_rt->rt_ifa->ifa_ifp != ifp) {
540 /* if no ifp provided, check if rtentry is not default route */
542 IN6_IS_ADDR_UNSPECIFIED(&satosin6(rt_key(ro.ro_rt))->sin6_addr)) {
547 /* or if this is a blackhole/reject route */
548 if (ifp == NULL && ro.ro_rt->rt_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
553 /* found valid route */
560 is_icmp6_query(int icmp6_type)
562 if ((icmp6_type <= ICMP6_MAXTYPE) &&
563 (icmp6_type == ICMP6_ECHO_REQUEST ||
564 icmp6_type == ICMP6_MEMBERSHIP_QUERY ||
565 icmp6_type == ICMP6_WRUREQUEST ||
566 icmp6_type == ICMP6_FQDN_QUERY ||
567 icmp6_type == ICMP6_NI_QUERY))
574 send_reject6(struct ip_fw_args *args, int code, u_int hlen, struct ip6_hdr *ip6)
579 if (code == ICMP6_UNREACH_RST && args->f_id.proto == IPPROTO_TCP) {
581 tcp = (struct tcphdr *)((char *)ip6 + hlen);
583 if ((tcp->th_flags & TH_RST) == 0) {
585 m0 = ipfw_send_pkt(args->m, &(args->f_id),
586 ntohl(tcp->th_seq), ntohl(tcp->th_ack),
587 tcp->th_flags | TH_RST);
589 ip6_output(m0, NULL, NULL, 0, NULL, NULL,
593 } else if (code != ICMP6_UNREACH_RST) { /* Send an ICMPv6 unreach. */
596 * Unlike above, the mbufs need to line up with the ip6 hdr,
597 * as the contents are read. We need to m_adj() the
599 * The mbuf will however be thrown away so we can adjust it.
600 * Remember we did an m_pullup on it already so we
601 * can make some assumptions about contiguousness.
604 m_adj(m, args->L3offset);
606 icmp6_error(m, ICMP6_DST_UNREACH, code, 0);
617 * sends a reject message, consuming the mbuf passed as an argument.
620 send_reject(struct ip_fw_args *args, int code, int iplen, struct ip *ip)
624 /* XXX When ip is not guaranteed to be at mtod() we will
625 * need to account for this */
626 * The mbuf will however be thrown away so we can adjust it.
627 * Remember we did an m_pullup on it already so we
628 * can make some assumptions about contiguousness.
631 m_adj(m, args->L3offset);
633 if (code != ICMP_REJECT_RST) { /* Send an ICMP unreach */
634 icmp_error(args->m, ICMP_UNREACH, code, 0L, 0);
635 } else if (args->f_id.proto == IPPROTO_TCP) {
636 struct tcphdr *const tcp =
637 L3HDR(struct tcphdr, mtod(args->m, struct ip *));
638 if ( (tcp->th_flags & TH_RST) == 0) {
640 m = ipfw_send_pkt(args->m, &(args->f_id),
641 ntohl(tcp->th_seq), ntohl(tcp->th_ack),
642 tcp->th_flags | TH_RST);
644 ip_output(m, NULL, NULL, 0, NULL, NULL);
653 * Support for uid/gid/jail lookup. These tests are expensive
654 * (because we may need to look into the list of active sockets)
655 * so we cache the results. ugid_lookupp is 0 if we have not
656 * yet done a lookup, 1 if we succeeded, and -1 if we tried
657 * and failed. The function always returns the match value.
658 * We could actually spare the variable and use *uc, setting
659 * it to '(void *)check_uidgid if we have no info, NULL if
660 * we tried and failed, or any other value if successful.
663 check_uidgid(ipfw_insn_u32 *insn, struct ip_fw_args *args, int *ugid_lookupp,
668 return cred_check(insn, proto, oif,
669 dst_ip, dst_port, src_ip, src_port,
670 (struct bsd_ucred *)uc, ugid_lookupp, ((struct mbuf *)inp)->m_skb);
672 struct in_addr src_ip, dst_ip;
673 struct inpcbinfo *pi;
674 struct ipfw_flow_id *id;
675 struct inpcb *pcb, *inp;
685 * Check to see if the UDP or TCP stack supplied us with
686 * the PCB. If so, rather then holding a lock and looking
687 * up the PCB, we can use the one that was supplied.
689 if (inp && *ugid_lookupp == 0) {
690 INP_LOCK_ASSERT(inp);
691 if (inp->inp_socket != NULL) {
692 *uc = crhold(inp->inp_cred);
698 * If we have already been here and the packet has no
699 * PCB entry associated with it, then we can safely
700 * assume that this is a no match.
702 if (*ugid_lookupp == -1)
704 if (id->proto == IPPROTO_TCP) {
707 } else if (id->proto == IPPROTO_UDP) {
708 lookupflags = INPLOOKUP_WILDCARD;
712 lookupflags |= INPLOOKUP_RLOCKPCB;
714 if (*ugid_lookupp == 0) {
715 if (id->addr_type == 6) {
718 pcb = in6_pcblookup_mbuf(pi,
719 &id->src_ip6, htons(id->src_port),
720 &id->dst_ip6, htons(id->dst_port),
721 lookupflags, oif, args->m);
723 pcb = in6_pcblookup_mbuf(pi,
724 &id->dst_ip6, htons(id->dst_port),
725 &id->src_ip6, htons(id->src_port),
726 lookupflags, oif, args->m);
732 src_ip.s_addr = htonl(id->src_ip);
733 dst_ip.s_addr = htonl(id->dst_ip);
735 pcb = in_pcblookup_mbuf(pi,
736 src_ip, htons(id->src_port),
737 dst_ip, htons(id->dst_port),
738 lookupflags, oif, args->m);
740 pcb = in_pcblookup_mbuf(pi,
741 dst_ip, htons(id->dst_port),
742 src_ip, htons(id->src_port),
743 lookupflags, oif, args->m);
746 INP_RLOCK_ASSERT(pcb);
747 *uc = crhold(pcb->inp_cred);
751 if (*ugid_lookupp == 0) {
753 * We tried and failed, set the variable to -1
754 * so we will not try again on this packet.
760 if (insn->o.opcode == O_UID)
761 match = ((*uc)->cr_uid == (uid_t)insn->d[0]);
762 else if (insn->o.opcode == O_GID)
763 match = groupmember((gid_t)insn->d[0], *uc);
764 else if (insn->o.opcode == O_JAIL)
765 match = ((*uc)->cr_prison->pr_id == (int)insn->d[0]);
767 #endif /* __FreeBSD__ */
771 * Helper function to set args with info on the rule after the matching
772 * one. slot is precise, whereas we guess rule_id as they are
773 * assigned sequentially.
776 set_match(struct ip_fw_args *args, int slot,
777 struct ip_fw_chain *chain)
779 args->rule.chain_id = chain->id;
780 args->rule.slot = slot + 1; /* we use 0 as a marker */
781 args->rule.rule_id = 1 + chain->map[slot]->id;
782 args->rule.rulenum = chain->map[slot]->rulenum;
786 * Helper function to enable cached rule lookups using
787 * x_next and next_rule fields in ipfw rule.
790 jump_fast(struct ip_fw_chain *chain, struct ip_fw *f, int num,
791 int tablearg, int jump_backwards)
795 /* If possible use cached f_pos (in f->next_rule),
796 * whose version is written in f->next_rule
797 * (horrible hacks to avoid changing the ABI).
799 if (num != IP_FW_TABLEARG && (uintptr_t)f->x_next == chain->id)
800 f_pos = (uintptr_t)f->next_rule;
802 int i = IP_FW_ARG_TABLEARG(num);
803 /* make sure we do not jump backward */
804 if (jump_backwards == 0 && i <= f->rulenum)
806 f_pos = ipfw_find_rule(chain, i, 0);
807 /* update the cache */
808 if (num != IP_FW_TABLEARG) {
809 f->next_rule = (void *)(uintptr_t)f_pos;
810 f->x_next = (void *)(uintptr_t)chain->id;
818 * The main check routine for the firewall.
820 * All arguments are in args so we can modify them and return them
821 * back to the caller.
825 * args->m (in/out) The packet; we set to NULL when/if we nuke it.
826 * Starts with the IP header.
827 * args->eh (in) Mac header if present, NULL for layer3 packet.
828 * args->L3offset Number of bytes bypassed if we came from L2.
829 * e.g. often sizeof(eh) ** NOTYET **
830 * args->oif Outgoing interface, NULL if packet is incoming.
831 * The incoming interface is in the mbuf. (in)
832 * args->divert_rule (in/out)
833 * Skip up to the first rule past this rule number;
834 * upon return, non-zero port number for divert or tee.
836 * args->rule Pointer to the last matching rule (in/out)
837 * args->next_hop Socket we are forwarding to (out).
838 * args->next_hop6 IPv6 next hop we are forwarding to (out).
839 * args->f_id Addresses grabbed from the packet (out)
840 * args->rule.info a cookie depending on rule action
844 * IP_FW_PASS the packet must be accepted
845 * IP_FW_DENY the packet must be dropped
846 * IP_FW_DIVERT divert packet, port in m_tag
847 * IP_FW_TEE tee packet, port in m_tag
848 * IP_FW_DUMMYNET to dummynet, pipe in args->cookie
849 * IP_FW_NETGRAPH into netgraph, cookie args->cookie
850 * args->rule contains the matching rule,
851 * args->rule.info has additional information.
855 ipfw_chk(struct ip_fw_args *args)
859 * Local variables holding state while processing a packet:
861 * IMPORTANT NOTE: to speed up the processing of rules, there
862 * are some assumption on the values of the variables, which
863 * are documented here. Should you change them, please check
864 * the implementation of the various instructions to make sure
865 * that they still work.
867 * args->eh The MAC header. It is non-null for a layer2
868 * packet, it is NULL for a layer-3 packet.
870 * args->L3offset Offset in the packet to the L3 (IP or equiv.) header.
872 * m | args->m Pointer to the mbuf, as received from the caller.
873 * It may change if ipfw_chk() does an m_pullup, or if it
874 * consumes the packet because it calls send_reject().
875 * XXX This has to change, so that ipfw_chk() never modifies
876 * or consumes the buffer.
877 * ip is the beginning of the ip(4 or 6) header.
878 * Calculated by adding the L3offset to the start of data.
879 * (Until we start using L3offset, the packet is
880 * supposed to start with the ip header).
882 struct mbuf *m = args->m;
883 struct ip *ip = mtod(m, struct ip *);
886 * For rules which contain uid/gid or jail constraints, cache
887 * a copy of the users credentials after the pcb lookup has been
888 * executed. This will speed up the processing of rules with
889 * these types of constraints, as well as decrease contention
890 * on pcb related locks.
893 struct bsd_ucred ucred_cache;
895 struct ucred *ucred_cache = NULL;
897 int ucred_lookup = 0;
900 * oif | args->oif If NULL, ipfw_chk has been called on the
901 * inbound path (ether_input, ip_input).
902 * If non-NULL, ipfw_chk has been called on the outbound path
903 * (ether_output, ip_output).
905 struct ifnet *oif = args->oif;
907 int f_pos = 0; /* index of current rule in the array */
911 * hlen The length of the IP header.
913 u_int hlen = 0; /* hlen >0 means we have an IP pkt */
916 * offset The offset of a fragment. offset != 0 means that
917 * we have a fragment at this offset of an IPv4 packet.
918 * offset == 0 means that (if this is an IPv4 packet)
919 * this is the first or only fragment.
920 * For IPv6 offset|ip6f_mf == 0 means there is no Fragment Header
921 * or there is a single packet fragement (fragement header added
922 * without needed). We will treat a single packet fragment as if
923 * there was no fragment header (or log/block depending on the
924 * V_fw_permit_single_frag6 sysctl setting).
930 * Local copies of addresses. They are only valid if we have
933 * proto The protocol. Set to 0 for non-ip packets,
934 * or to the protocol read from the packet otherwise.
935 * proto != 0 means that we have an IPv4 packet.
937 * src_port, dst_port port numbers, in HOST format. Only
938 * valid for TCP and UDP packets.
940 * src_ip, dst_ip ip addresses, in NETWORK format.
941 * Only valid for IPv4 packets.
944 uint16_t src_port = 0, dst_port = 0; /* NOTE: host format */
945 struct in_addr src_ip, dst_ip; /* NOTE: network format */
948 uint16_t etype = 0; /* Host order stored ether type */
951 * dyn_dir = MATCH_UNKNOWN when rules unchecked,
952 * MATCH_NONE when checked and not matched (q = NULL),
953 * MATCH_FORWARD or MATCH_REVERSE otherwise (q != NULL)
955 int dyn_dir = MATCH_UNKNOWN;
956 ipfw_dyn_rule *q = NULL;
957 struct ip_fw_chain *chain = &V_layer3_chain;
960 * We store in ulp a pointer to the upper layer protocol header.
961 * In the ipv4 case this is easy to determine from the header,
962 * but for ipv6 we might have some additional headers in the middle.
963 * ulp is NULL if not found.
965 void *ulp = NULL; /* upper layer protocol pointer. */
967 /* XXX ipv6 variables */
969 uint8_t icmp6_type = 0;
970 uint16_t ext_hd = 0; /* bits vector for extension header filtering */
971 /* end of ipv6 variables */
975 int done = 0; /* flag to exit the outer loop */
977 if (m->m_flags & M_SKIP_FIREWALL || (! V_ipfw_vnet_ready))
978 return (IP_FW_PASS); /* accept */
980 dst_ip.s_addr = 0; /* make sure it is initialized */
981 src_ip.s_addr = 0; /* make sure it is initialized */
982 pktlen = m->m_pkthdr.len;
983 args->f_id.fib = M_GETFIB(m); /* note mbuf not altered) */
984 proto = args->f_id.proto = 0; /* mark f_id invalid */
985 /* XXX 0 is a valid proto: IP/IPv6 Hop-by-Hop Option */
988 * PULLUP_TO(len, p, T) makes sure that len + sizeof(T) is contiguous,
989 * then it sets p to point at the offset "len" in the mbuf. WARNING: the
990 * pointer might become stale after other pullups (but we never use it
993 #define PULLUP_TO(_len, p, T) PULLUP_LEN(_len, p, sizeof(T))
994 #define PULLUP_LEN(_len, p, T) \
996 int x = (_len) + T; \
997 if ((m)->m_len < x) { \
998 args->m = m = m_pullup(m, x); \
1000 goto pullup_failed; \
1002 p = (mtod(m, char *) + (_len)); \
1006 * if we have an ether header,
1009 etype = ntohs(args->eh->ether_type);
1011 /* Identify IP packets and fill up variables. */
1012 if (pktlen >= sizeof(struct ip6_hdr) &&
1013 (args->eh == NULL || etype == ETHERTYPE_IPV6) && ip->ip_v == 6) {
1014 struct ip6_hdr *ip6 = (struct ip6_hdr *)ip;
1016 args->f_id.addr_type = 6;
1017 hlen = sizeof(struct ip6_hdr);
1018 proto = ip6->ip6_nxt;
1020 /* Search extension headers to find upper layer protocols */
1021 while (ulp == NULL && offset == 0) {
1023 case IPPROTO_ICMPV6:
1024 PULLUP_TO(hlen, ulp, struct icmp6_hdr);
1025 icmp6_type = ICMP6(ulp)->icmp6_type;
1029 PULLUP_TO(hlen, ulp, struct tcphdr);
1030 dst_port = TCP(ulp)->th_dport;
1031 src_port = TCP(ulp)->th_sport;
1032 /* save flags for dynamic rules */
1033 args->f_id._flags = TCP(ulp)->th_flags;
1037 PULLUP_TO(hlen, ulp, struct sctphdr);
1038 src_port = SCTP(ulp)->src_port;
1039 dst_port = SCTP(ulp)->dest_port;
1043 PULLUP_TO(hlen, ulp, struct udphdr);
1044 dst_port = UDP(ulp)->uh_dport;
1045 src_port = UDP(ulp)->uh_sport;
1048 case IPPROTO_HOPOPTS: /* RFC 2460 */
1049 PULLUP_TO(hlen, ulp, struct ip6_hbh);
1050 ext_hd |= EXT_HOPOPTS;
1051 hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3;
1052 proto = ((struct ip6_hbh *)ulp)->ip6h_nxt;
1056 case IPPROTO_ROUTING: /* RFC 2460 */
1057 PULLUP_TO(hlen, ulp, struct ip6_rthdr);
1058 switch (((struct ip6_rthdr *)ulp)->ip6r_type) {
1060 ext_hd |= EXT_RTHDR0;
1063 ext_hd |= EXT_RTHDR2;
1067 printf("IPFW2: IPV6 - Unknown "
1068 "Routing Header type(%d)\n",
1069 ((struct ip6_rthdr *)
1071 if (V_fw_deny_unknown_exthdrs)
1072 return (IP_FW_DENY);
1075 ext_hd |= EXT_ROUTING;
1076 hlen += (((struct ip6_rthdr *)ulp)->ip6r_len + 1) << 3;
1077 proto = ((struct ip6_rthdr *)ulp)->ip6r_nxt;
1081 case IPPROTO_FRAGMENT: /* RFC 2460 */
1082 PULLUP_TO(hlen, ulp, struct ip6_frag);
1083 ext_hd |= EXT_FRAGMENT;
1084 hlen += sizeof (struct ip6_frag);
1085 proto = ((struct ip6_frag *)ulp)->ip6f_nxt;
1086 offset = ((struct ip6_frag *)ulp)->ip6f_offlg &
1088 ip6f_mf = ((struct ip6_frag *)ulp)->ip6f_offlg &
1090 if (V_fw_permit_single_frag6 == 0 &&
1091 offset == 0 && ip6f_mf == 0) {
1093 printf("IPFW2: IPV6 - Invalid "
1094 "Fragment Header\n");
1095 if (V_fw_deny_unknown_exthdrs)
1096 return (IP_FW_DENY);
1100 ntohl(((struct ip6_frag *)ulp)->ip6f_ident);
1104 case IPPROTO_DSTOPTS: /* RFC 2460 */
1105 PULLUP_TO(hlen, ulp, struct ip6_hbh);
1106 ext_hd |= EXT_DSTOPTS;
1107 hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3;
1108 proto = ((struct ip6_hbh *)ulp)->ip6h_nxt;
1112 case IPPROTO_AH: /* RFC 2402 */
1113 PULLUP_TO(hlen, ulp, struct ip6_ext);
1115 hlen += (((struct ip6_ext *)ulp)->ip6e_len + 2) << 2;
1116 proto = ((struct ip6_ext *)ulp)->ip6e_nxt;
1120 case IPPROTO_ESP: /* RFC 2406 */
1121 PULLUP_TO(hlen, ulp, uint32_t); /* SPI, Seq# */
1122 /* Anything past Seq# is variable length and
1123 * data past this ext. header is encrypted. */
1127 case IPPROTO_NONE: /* RFC 2460 */
1129 * Packet ends here, and IPv6 header has
1130 * already been pulled up. If ip6e_len!=0
1131 * then octets must be ignored.
1133 ulp = ip; /* non-NULL to get out of loop. */
1136 case IPPROTO_OSPFIGP:
1137 /* XXX OSPF header check? */
1138 PULLUP_TO(hlen, ulp, struct ip6_ext);
1142 /* XXX PIM header check? */
1143 PULLUP_TO(hlen, ulp, struct pim);
1147 PULLUP_TO(hlen, ulp, struct carp_header);
1148 if (((struct carp_header *)ulp)->carp_version !=
1150 return (IP_FW_DENY);
1151 if (((struct carp_header *)ulp)->carp_type !=
1153 return (IP_FW_DENY);
1156 case IPPROTO_IPV6: /* RFC 2893 */
1157 PULLUP_TO(hlen, ulp, struct ip6_hdr);
1160 case IPPROTO_IPV4: /* RFC 2893 */
1161 PULLUP_TO(hlen, ulp, struct ip);
1166 printf("IPFW2: IPV6 - Unknown "
1167 "Extension Header(%d), ext_hd=%x\n",
1169 if (V_fw_deny_unknown_exthdrs)
1170 return (IP_FW_DENY);
1171 PULLUP_TO(hlen, ulp, struct ip6_ext);
1175 ip = mtod(m, struct ip *);
1176 ip6 = (struct ip6_hdr *)ip;
1177 args->f_id.src_ip6 = ip6->ip6_src;
1178 args->f_id.dst_ip6 = ip6->ip6_dst;
1179 args->f_id.src_ip = 0;
1180 args->f_id.dst_ip = 0;
1181 args->f_id.flow_id6 = ntohl(ip6->ip6_flow);
1182 } else if (pktlen >= sizeof(struct ip) &&
1183 (args->eh == NULL || etype == ETHERTYPE_IP) && ip->ip_v == 4) {
1185 hlen = ip->ip_hl << 2;
1186 args->f_id.addr_type = 4;
1189 * Collect parameters into local variables for faster matching.
1192 src_ip = ip->ip_src;
1193 dst_ip = ip->ip_dst;
1194 offset = ntohs(ip->ip_off) & IP_OFFMASK;
1195 iplen = ntohs(ip->ip_len);
1196 pktlen = iplen < pktlen ? iplen : pktlen;
1201 PULLUP_TO(hlen, ulp, struct tcphdr);
1202 dst_port = TCP(ulp)->th_dport;
1203 src_port = TCP(ulp)->th_sport;
1204 /* save flags for dynamic rules */
1205 args->f_id._flags = TCP(ulp)->th_flags;
1209 PULLUP_TO(hlen, ulp, struct sctphdr);
1210 src_port = SCTP(ulp)->src_port;
1211 dst_port = SCTP(ulp)->dest_port;
1215 PULLUP_TO(hlen, ulp, struct udphdr);
1216 dst_port = UDP(ulp)->uh_dport;
1217 src_port = UDP(ulp)->uh_sport;
1221 PULLUP_TO(hlen, ulp, struct icmphdr);
1222 //args->f_id.flags = ICMP(ulp)->icmp_type;
1230 ip = mtod(m, struct ip *);
1231 args->f_id.src_ip = ntohl(src_ip.s_addr);
1232 args->f_id.dst_ip = ntohl(dst_ip.s_addr);
1235 if (proto) { /* we may have port numbers, store them */
1236 args->f_id.proto = proto;
1237 args->f_id.src_port = src_port = ntohs(src_port);
1238 args->f_id.dst_port = dst_port = ntohs(dst_port);
1241 IPFW_PF_RLOCK(chain);
1242 if (! V_ipfw_vnet_ready) { /* shutting down, leave NOW. */
1243 IPFW_PF_RUNLOCK(chain);
1244 return (IP_FW_PASS); /* accept */
1246 if (args->rule.slot) {
1248 * Packet has already been tagged as a result of a previous
1249 * match on rule args->rule aka args->rule_id (PIPE, QUEUE,
1250 * REASS, NETGRAPH, DIVERT/TEE...)
1251 * Validate the slot and continue from the next one
1252 * if still present, otherwise do a lookup.
1254 f_pos = (args->rule.chain_id == chain->id) ?
1256 ipfw_find_rule(chain, args->rule.rulenum,
1257 args->rule.rule_id);
1263 * Now scan the rules, and parse microinstructions for each rule.
1264 * We have two nested loops and an inner switch. Sometimes we
1265 * need to break out of one or both loops, or re-enter one of
1266 * the loops with updated variables. Loop variables are:
1268 * f_pos (outer loop) points to the current rule.
1269 * On output it points to the matching rule.
1270 * done (outer loop) is used as a flag to break the loop.
1271 * l (inner loop) residual length of current rule.
1272 * cmd points to the current microinstruction.
1274 * We break the inner loop by setting l=0 and possibly
1275 * cmdlen=0 if we don't want to advance cmd.
1276 * We break the outer loop by setting done=1
1277 * We can restart the inner loop by setting l>0 and f_pos, f, cmd
1280 for (; f_pos < chain->n_rules; f_pos++) {
1282 uint32_t tablearg = 0;
1283 int l, cmdlen, skip_or; /* skip rest of OR block */
1286 f = chain->map[f_pos];
1287 if (V_set_disable & (1 << f->set) )
1291 for (l = f->cmd_len, cmd = f->cmd ; l > 0 ;
1292 l -= cmdlen, cmd += cmdlen) {
1296 * check_body is a jump target used when we find a
1297 * CHECK_STATE, and need to jump to the body of
1302 cmdlen = F_LEN(cmd);
1304 * An OR block (insn_1 || .. || insn_n) has the
1305 * F_OR bit set in all but the last instruction.
1306 * The first match will set "skip_or", and cause
1307 * the following instructions to be skipped until
1308 * past the one with the F_OR bit clear.
1310 if (skip_or) { /* skip this instruction */
1311 if ((cmd->len & F_OR) == 0)
1312 skip_or = 0; /* next one is good */
1315 match = 0; /* set to 1 if we succeed */
1317 switch (cmd->opcode) {
1319 * The first set of opcodes compares the packet's
1320 * fields with some pattern, setting 'match' if a
1321 * match is found. At the end of the loop there is
1322 * logic to deal with F_NOT and F_OR flags associated
1330 printf("ipfw: opcode %d unimplemented\n",
1338 * We only check offset == 0 && proto != 0,
1339 * as this ensures that we have a
1340 * packet with the ports info.
1344 if (proto == IPPROTO_TCP ||
1345 proto == IPPROTO_UDP)
1346 match = check_uidgid(
1347 (ipfw_insn_u32 *)cmd,
1348 args, &ucred_lookup,
1352 (void *)&ucred_cache);
1357 match = iface_match(m->m_pkthdr.rcvif,
1358 (ipfw_insn_if *)cmd, chain, &tablearg);
1362 match = iface_match(oif, (ipfw_insn_if *)cmd,
1367 match = iface_match(oif ? oif :
1368 m->m_pkthdr.rcvif, (ipfw_insn_if *)cmd,
1373 if (args->eh != NULL) { /* have MAC header */
1374 u_int32_t *want = (u_int32_t *)
1375 ((ipfw_insn_mac *)cmd)->addr;
1376 u_int32_t *mask = (u_int32_t *)
1377 ((ipfw_insn_mac *)cmd)->mask;
1378 u_int32_t *hdr = (u_int32_t *)args->eh;
1381 ( want[0] == (hdr[0] & mask[0]) &&
1382 want[1] == (hdr[1] & mask[1]) &&
1383 want[2] == (hdr[2] & mask[2]) );
1388 if (args->eh != NULL) {
1390 ((ipfw_insn_u16 *)cmd)->ports;
1393 for (i = cmdlen - 1; !match && i>0;
1395 match = (etype >= p[0] &&
1401 match = (offset != 0);
1404 case O_IN: /* "out" is "not in" */
1405 match = (oif == NULL);
1409 match = (args->eh != NULL);
1414 /* For diverted packets, args->rule.info
1415 * contains the divert port (in host format)
1416 * reason and direction.
1418 uint32_t i = args->rule.info;
1419 match = (i&IPFW_IS_MASK) == IPFW_IS_DIVERT &&
1420 cmd->arg1 & ((i & IPFW_INFO_IN) ? 1 : 2);
1426 * We do not allow an arg of 0 so the
1427 * check of "proto" only suffices.
1429 match = (proto == cmd->arg1);
1434 (((ipfw_insn_ip *)cmd)->addr.s_addr ==
1438 case O_IP_SRC_LOOKUP:
1439 case O_IP_DST_LOOKUP:
1442 (cmd->opcode == O_IP_DST_LOOKUP) ?
1443 dst_ip.s_addr : src_ip.s_addr;
1446 if (cmdlen > F_INSN_SIZE(ipfw_insn_u32)) {
1447 /* generic lookup. The key must be
1448 * in 32bit big-endian format.
1450 v = ((ipfw_insn_u32 *)cmd)->d[1];
1452 key = dst_ip.s_addr;
1454 key = src_ip.s_addr;
1455 else if (v == 6) /* dscp */
1456 key = (ip->ip_tos >> 2) & 0x3f;
1457 else if (offset != 0)
1459 else if (proto != IPPROTO_TCP &&
1460 proto != IPPROTO_UDP)
1463 key = htonl(dst_port);
1465 key = htonl(src_port);
1466 else if (v == 4 || v == 5) {
1468 (ipfw_insn_u32 *)cmd,
1469 args, &ucred_lookup,
1472 if (v == 4 /* O_UID */)
1473 key = ucred_cache->cr_uid;
1474 else if (v == 5 /* O_JAIL */)
1475 key = ucred_cache->cr_prison->pr_id;
1476 #else /* !__FreeBSD__ */
1477 (void *)&ucred_cache);
1478 if (v ==4 /* O_UID */)
1479 key = ucred_cache.uid;
1480 else if (v == 5 /* O_JAIL */)
1481 key = ucred_cache.xid;
1482 #endif /* !__FreeBSD__ */
1487 match = ipfw_lookup_table(chain,
1488 cmd->arg1, key, &v);
1491 if (cmdlen == F_INSN_SIZE(ipfw_insn_u32))
1493 ((ipfw_insn_u32 *)cmd)->d[0] == v;
1496 } else if (is_ipv6) {
1498 void *pkey = (cmd->opcode == O_IP_DST_LOOKUP) ?
1499 &args->f_id.dst_ip6: &args->f_id.src_ip6;
1500 match = ipfw_lookup_table_extended(chain,
1501 cmd->arg1, pkey, &v,
1503 if (cmdlen == F_INSN_SIZE(ipfw_insn_u32))
1504 match = ((ipfw_insn_u32 *)cmd)->d[0] == v;
1514 (cmd->opcode == O_IP_DST_MASK) ?
1515 dst_ip.s_addr : src_ip.s_addr;
1516 uint32_t *p = ((ipfw_insn_u32 *)cmd)->d;
1519 for (; !match && i>0; i-= 2, p+= 2)
1520 match = (p[0] == (a & p[1]));
1528 INADDR_TO_IFP(src_ip, tif);
1529 match = (tif != NULL);
1535 match= is_ipv6 && search_ip6_addr_net(&args->f_id.src_ip6);
1542 u_int32_t *d = (u_int32_t *)(cmd+1);
1544 cmd->opcode == O_IP_DST_SET ?
1550 addr -= d[0]; /* subtract base */
1551 match = (addr < cmd->arg1) &&
1552 ( d[ 1 + (addr>>5)] &
1553 (1<<(addr & 0x1f)) );
1559 (((ipfw_insn_ip *)cmd)->addr.s_addr ==
1567 INADDR_TO_IFP(dst_ip, tif);
1568 match = (tif != NULL);
1574 match= is_ipv6 && search_ip6_addr_net(&args->f_id.dst_ip6);
1582 * offset == 0 && proto != 0 is enough
1583 * to guarantee that we have a
1584 * packet with port info.
1586 if ((proto==IPPROTO_UDP || proto==IPPROTO_TCP)
1589 (cmd->opcode == O_IP_SRCPORT) ?
1590 src_port : dst_port ;
1592 ((ipfw_insn_u16 *)cmd)->ports;
1595 for (i = cmdlen - 1; !match && i>0;
1597 match = (x>=p[0] && x<=p[1]);
1602 match = (offset == 0 && proto==IPPROTO_ICMP &&
1603 icmptype_match(ICMP(ulp), (ipfw_insn_u32 *)cmd) );
1608 match = is_ipv6 && offset == 0 &&
1609 proto==IPPROTO_ICMPV6 &&
1611 ICMP6(ulp)->icmp6_type,
1612 (ipfw_insn_u32 *)cmd);
1618 ipopts_match(ip, cmd) );
1623 cmd->arg1 == ip->ip_v);
1629 if (is_ipv4) { /* only for IP packets */
1634 if (cmd->opcode == O_IPLEN)
1636 else if (cmd->opcode == O_IPTTL)
1638 else /* must be IPID */
1639 x = ntohs(ip->ip_id);
1641 match = (cmd->arg1 == x);
1644 /* otherwise we have ranges */
1645 p = ((ipfw_insn_u16 *)cmd)->ports;
1647 for (; !match && i>0; i--, p += 2)
1648 match = (x >= p[0] && x <= p[1]);
1652 case O_IPPRECEDENCE:
1654 (cmd->arg1 == (ip->ip_tos & 0xe0)) );
1659 flags_match(cmd, ip->ip_tos));
1667 p = ((ipfw_insn_u32 *)cmd)->d;
1670 x = ip->ip_tos >> 2;
1673 v = &((struct ip6_hdr *)ip)->ip6_vfc;
1674 x = (*v & 0x0F) << 2;
1680 /* DSCP bitmask is stored as low_u32 high_u32 */
1682 match = *(p + 1) & (1 << (x - 32));
1684 match = *p & (1 << x);
1689 if (proto == IPPROTO_TCP && offset == 0) {
1697 ((ip->ip_hl + tcp->th_off) << 2);
1699 match = (cmd->arg1 == x);
1702 /* otherwise we have ranges */
1703 p = ((ipfw_insn_u16 *)cmd)->ports;
1705 for (; !match && i>0; i--, p += 2)
1706 match = (x >= p[0] && x <= p[1]);
1711 match = (proto == IPPROTO_TCP && offset == 0 &&
1712 flags_match(cmd, TCP(ulp)->th_flags));
1716 PULLUP_LEN(hlen, ulp, (TCP(ulp)->th_off << 2));
1717 match = (proto == IPPROTO_TCP && offset == 0 &&
1718 tcpopts_match(TCP(ulp), cmd));
1722 match = (proto == IPPROTO_TCP && offset == 0 &&
1723 ((ipfw_insn_u32 *)cmd)->d[0] ==
1728 match = (proto == IPPROTO_TCP && offset == 0 &&
1729 ((ipfw_insn_u32 *)cmd)->d[0] ==
1734 if (proto == IPPROTO_TCP && offset == 0) {
1739 x = ntohs(TCP(ulp)->th_win);
1741 match = (cmd->arg1 == x);
1744 /* Otherwise we have ranges. */
1745 p = ((ipfw_insn_u16 *)cmd)->ports;
1747 for (; !match && i > 0; i--, p += 2)
1748 match = (x >= p[0] && x <= p[1]);
1753 /* reject packets which have SYN only */
1754 /* XXX should i also check for TH_ACK ? */
1755 match = (proto == IPPROTO_TCP && offset == 0 &&
1756 (TCP(ulp)->th_flags &
1757 (TH_RST | TH_ACK | TH_SYN)) != TH_SYN);
1763 ipfw_insn_altq *altq = (ipfw_insn_altq *)cmd;
1766 * ALTQ uses mbuf tags from another
1767 * packet filtering system - pf(4).
1768 * We allocate a tag in its format
1769 * and fill it in, pretending to be pf(4).
1772 at = pf_find_mtag(m);
1773 if (at != NULL && at->qid != 0)
1775 mtag = m_tag_get(PACKET_TAG_PF,
1776 sizeof(struct pf_mtag), M_NOWAIT | M_ZERO);
1779 * Let the packet fall back to the
1784 m_tag_prepend(m, mtag);
1785 at = (struct pf_mtag *)(mtag + 1);
1786 at->qid = altq->qid;
1792 ipfw_log(f, hlen, args, m,
1793 oif, offset | ip6f_mf, tablearg, ip);
1798 match = (random()<((ipfw_insn_u32 *)cmd)->d[0]);
1802 /* Outgoing packets automatically pass/match */
1803 match = ((oif != NULL) ||
1804 (m->m_pkthdr.rcvif == NULL) ||
1808 verify_path6(&(args->f_id.src_ip6),
1809 m->m_pkthdr.rcvif, args->f_id.fib) :
1811 verify_path(src_ip, m->m_pkthdr.rcvif,
1816 /* Outgoing packets automatically pass/match */
1817 match = (hlen > 0 && ((oif != NULL) ||
1820 verify_path6(&(args->f_id.src_ip6),
1821 NULL, args->f_id.fib) :
1823 verify_path(src_ip, NULL, args->f_id.fib)));
1827 /* Outgoing packets automatically pass/match */
1828 if (oif == NULL && hlen > 0 &&
1829 ( (is_ipv4 && in_localaddr(src_ip))
1832 in6_localaddr(&(args->f_id.src_ip6)))
1837 is_ipv6 ? verify_path6(
1838 &(args->f_id.src_ip6),
1851 match = (m_tag_find(m,
1852 PACKET_TAG_IPSEC_IN_DONE, NULL) != NULL);
1854 /* otherwise no match */
1860 IN6_ARE_ADDR_EQUAL(&args->f_id.src_ip6,
1861 &((ipfw_insn_ip6 *)cmd)->addr6);
1866 IN6_ARE_ADDR_EQUAL(&args->f_id.dst_ip6,
1867 &((ipfw_insn_ip6 *)cmd)->addr6);
1869 case O_IP6_SRC_MASK:
1870 case O_IP6_DST_MASK:
1874 struct in6_addr *d =
1875 &((ipfw_insn_ip6 *)cmd)->addr6;
1877 for (; !match && i > 0; d += 2,
1878 i -= F_INSN_SIZE(struct in6_addr)
1884 APPLY_MASK(&p, &d[1]);
1886 IN6_ARE_ADDR_EQUAL(&d[0],
1894 flow6id_match(args->f_id.flow_id6,
1895 (ipfw_insn_u32 *) cmd);
1900 (ext_hd & ((ipfw_insn *) cmd)->arg1);
1914 uint32_t tag = IP_FW_ARG_TABLEARG(cmd->arg1);
1916 /* Packet is already tagged with this tag? */
1917 mtag = m_tag_locate(m, MTAG_IPFW, tag, NULL);
1919 /* We have `untag' action when F_NOT flag is
1920 * present. And we must remove this mtag from
1921 * mbuf and reset `match' to zero (`match' will
1922 * be inversed later).
1923 * Otherwise we should allocate new mtag and
1924 * push it into mbuf.
1926 if (cmd->len & F_NOT) { /* `untag' action */
1928 m_tag_delete(m, mtag);
1932 mtag = m_tag_alloc( MTAG_IPFW,
1935 m_tag_prepend(m, mtag);
1942 case O_FIB: /* try match the specified fib */
1943 if (args->f_id.fib == cmd->arg1)
1948 struct inpcb *inp = args->inp;
1949 struct inpcbinfo *pi;
1951 if (is_ipv6) /* XXX can we remove this ? */
1954 if (proto == IPPROTO_TCP)
1956 else if (proto == IPPROTO_UDP)
1962 * XXXRW: so_user_cookie should almost
1963 * certainly be inp_user_cookie?
1966 /* For incomming packet, lookup up the
1967 inpcb using the src/dest ip/port tuple */
1969 inp = in_pcblookup(pi,
1970 src_ip, htons(src_port),
1971 dst_ip, htons(dst_port),
1972 INPLOOKUP_RLOCKPCB, NULL);
1975 inp->inp_socket->so_user_cookie;
1981 if (inp->inp_socket) {
1983 inp->inp_socket->so_user_cookie;
1993 uint32_t tag = IP_FW_ARG_TABLEARG(cmd->arg1);
1996 match = m_tag_locate(m, MTAG_IPFW,
2001 /* we have ranges */
2002 for (mtag = m_tag_first(m);
2003 mtag != NULL && !match;
2004 mtag = m_tag_next(m, mtag)) {
2008 if (mtag->m_tag_cookie != MTAG_IPFW)
2011 p = ((ipfw_insn_u16 *)cmd)->ports;
2013 for(; !match && i > 0; i--, p += 2)
2015 mtag->m_tag_id >= p[0] &&
2016 mtag->m_tag_id <= p[1];
2022 * The second set of opcodes represents 'actions',
2023 * i.e. the terminal part of a rule once the packet
2024 * matches all previous patterns.
2025 * Typically there is only one action for each rule,
2026 * and the opcode is stored at the end of the rule
2027 * (but there are exceptions -- see below).
2029 * In general, here we set retval and terminate the
2030 * outer loop (would be a 'break 3' in some language,
2031 * but we need to set l=0, done=1)
2034 * O_COUNT and O_SKIPTO actions:
2035 * instead of terminating, we jump to the next rule
2036 * (setting l=0), or to the SKIPTO target (setting
2037 * f/f_len, cmd and l as needed), respectively.
2039 * O_TAG, O_LOG and O_ALTQ action parameters:
2040 * perform some action and set match = 1;
2042 * O_LIMIT and O_KEEP_STATE: these opcodes are
2043 * not real 'actions', and are stored right
2044 * before the 'action' part of the rule.
2045 * These opcodes try to install an entry in the
2046 * state tables; if successful, we continue with
2047 * the next opcode (match=1; break;), otherwise
2048 * the packet must be dropped (set retval,
2049 * break loops with l=0, done=1)
2051 * O_PROBE_STATE and O_CHECK_STATE: these opcodes
2052 * cause a lookup of the state table, and a jump
2053 * to the 'action' part of the parent rule
2054 * if an entry is found, or
2055 * (CHECK_STATE only) a jump to the next rule if
2056 * the entry is not found.
2057 * The result of the lookup is cached so that
2058 * further instances of these opcodes become NOPs.
2059 * The jump to the next rule is done by setting
2064 if (ipfw_install_state(f,
2065 (ipfw_insn_limit *)cmd, args, tablearg)) {
2066 /* error or limit violation */
2067 retval = IP_FW_DENY;
2068 l = 0; /* exit inner loop */
2069 done = 1; /* exit outer loop */
2077 * dynamic rules are checked at the first
2078 * keep-state or check-state occurrence,
2079 * with the result being stored in dyn_dir.
2080 * The compiler introduces a PROBE_STATE
2081 * instruction for us when we have a
2082 * KEEP_STATE (because PROBE_STATE needs
2085 if (dyn_dir == MATCH_UNKNOWN &&
2086 (q = ipfw_lookup_dyn_rule(&args->f_id,
2087 &dyn_dir, proto == IPPROTO_TCP ?
2091 * Found dynamic entry, update stats
2092 * and jump to the 'action' part of
2093 * the parent rule by setting
2094 * f, cmd, l and clearing cmdlen.
2096 IPFW_INC_DYN_COUNTER(q, pktlen);
2097 /* XXX we would like to have f_pos
2098 * readily accessible in the dynamic
2099 * rule, instead of having to
2103 f_pos = ipfw_find_rule(chain,
2105 cmd = ACTION_PTR(f);
2106 l = f->cmd_len - f->act_ofs;
2113 * Dynamic entry not found. If CHECK_STATE,
2114 * skip to next rule, if PROBE_STATE just
2115 * ignore and continue with next opcode.
2117 if (cmd->opcode == O_CHECK_STATE)
2118 l = 0; /* exit inner loop */
2123 retval = 0; /* accept */
2124 l = 0; /* exit inner loop */
2125 done = 1; /* exit outer loop */
2130 set_match(args, f_pos, chain);
2131 args->rule.info = IP_FW_ARG_TABLEARG(cmd->arg1);
2132 if (cmd->opcode == O_PIPE)
2133 args->rule.info |= IPFW_IS_PIPE;
2135 args->rule.info |= IPFW_ONEPASS;
2136 retval = IP_FW_DUMMYNET;
2137 l = 0; /* exit inner loop */
2138 done = 1; /* exit outer loop */
2143 if (args->eh) /* not on layer 2 */
2145 /* otherwise this is terminal */
2146 l = 0; /* exit inner loop */
2147 done = 1; /* exit outer loop */
2148 retval = (cmd->opcode == O_DIVERT) ?
2149 IP_FW_DIVERT : IP_FW_TEE;
2150 set_match(args, f_pos, chain);
2151 args->rule.info = IP_FW_ARG_TABLEARG(cmd->arg1);
2155 IPFW_INC_RULE_COUNTER(f, pktlen);
2156 l = 0; /* exit inner loop */
2160 IPFW_INC_RULE_COUNTER(f, pktlen);
2161 f_pos = jump_fast(chain, f, cmd->arg1, tablearg, 0);
2163 * Skip disabled rules, and re-enter
2164 * the inner loop with the correct
2165 * f_pos, f, l and cmd.
2166 * Also clear cmdlen and skip_or
2168 for (; f_pos < chain->n_rules - 1 &&
2170 (1 << chain->map[f_pos]->set));
2173 /* Re-enter the inner loop at the skipto rule. */
2174 f = chain->map[f_pos];
2181 break; /* not reached */
2183 case O_CALLRETURN: {
2185 * Implementation of `subroutine' call/return,
2186 * in the stack carried in an mbuf tag. This
2187 * is different from `skipto' in that any call
2188 * address is possible (`skipto' must prevent
2189 * backward jumps to avoid endless loops).
2190 * We have `return' action when F_NOT flag is
2191 * present. The `m_tag_id' field is used as
2195 uint16_t jmpto, *stack;
2197 #define IS_CALL ((cmd->len & F_NOT) == 0)
2198 #define IS_RETURN ((cmd->len & F_NOT) != 0)
2200 * Hand-rolled version of m_tag_locate() with
2202 * If not already tagged, allocate new tag.
2204 mtag = m_tag_first(m);
2205 while (mtag != NULL) {
2206 if (mtag->m_tag_cookie ==
2209 mtag = m_tag_next(m, mtag);
2211 if (mtag == NULL && IS_CALL) {
2212 mtag = m_tag_alloc(MTAG_IPFW_CALL, 0,
2213 IPFW_CALLSTACK_SIZE *
2214 sizeof(uint16_t), M_NOWAIT);
2216 m_tag_prepend(m, mtag);
2220 * On error both `call' and `return' just
2221 * continue with next rule.
2223 if (IS_RETURN && (mtag == NULL ||
2224 mtag->m_tag_id == 0)) {
2225 l = 0; /* exit inner loop */
2228 if (IS_CALL && (mtag == NULL ||
2229 mtag->m_tag_id >= IPFW_CALLSTACK_SIZE)) {
2230 printf("ipfw: call stack error, "
2231 "go to next rule\n");
2232 l = 0; /* exit inner loop */
2236 IPFW_INC_RULE_COUNTER(f, pktlen);
2237 stack = (uint16_t *)(mtag + 1);
2240 * The `call' action may use cached f_pos
2241 * (in f->next_rule), whose version is written
2243 * The `return' action, however, doesn't have
2244 * fixed jump address in cmd->arg1 and can't use
2248 stack[mtag->m_tag_id] = f->rulenum;
2250 f_pos = jump_fast(chain, f, cmd->arg1,
2252 } else { /* `return' action */
2254 jmpto = stack[mtag->m_tag_id] + 1;
2255 f_pos = ipfw_find_rule(chain, jmpto, 0);
2259 * Skip disabled rules, and re-enter
2260 * the inner loop with the correct
2261 * f_pos, f, l and cmd.
2262 * Also clear cmdlen and skip_or
2264 for (; f_pos < chain->n_rules - 1 &&
2266 (1 << chain->map[f_pos]->set)); f_pos++)
2268 /* Re-enter the inner loop at the dest rule. */
2269 f = chain->map[f_pos];
2275 break; /* NOTREACHED */
2282 * Drop the packet and send a reject notice
2283 * if the packet is not ICMP (or is an ICMP
2284 * query), and it is not multicast/broadcast.
2286 if (hlen > 0 && is_ipv4 && offset == 0 &&
2287 (proto != IPPROTO_ICMP ||
2288 is_icmp_query(ICMP(ulp))) &&
2289 !(m->m_flags & (M_BCAST|M_MCAST)) &&
2290 !IN_MULTICAST(ntohl(dst_ip.s_addr))) {
2291 send_reject(args, cmd->arg1, iplen, ip);
2297 if (hlen > 0 && is_ipv6 &&
2298 ((offset & IP6F_OFF_MASK) == 0) &&
2299 (proto != IPPROTO_ICMPV6 ||
2300 (is_icmp6_query(icmp6_type) == 1)) &&
2301 !(m->m_flags & (M_BCAST|M_MCAST)) &&
2302 !IN6_IS_ADDR_MULTICAST(&args->f_id.dst_ip6)) {
2304 args, cmd->arg1, hlen,
2305 (struct ip6_hdr *)ip);
2311 retval = IP_FW_DENY;
2312 l = 0; /* exit inner loop */
2313 done = 1; /* exit outer loop */
2317 if (args->eh) /* not valid on layer2 pkts */
2319 if (q == NULL || q->rule != f ||
2320 dyn_dir == MATCH_FORWARD) {
2321 struct sockaddr_in *sa;
2322 sa = &(((ipfw_insn_sa *)cmd)->sa);
2323 if (sa->sin_addr.s_addr == INADDR_ANY) {
2324 bcopy(sa, &args->hopstore,
2326 args->hopstore.sin_addr.s_addr =
2328 args->next_hop = &args->hopstore;
2330 args->next_hop = sa;
2333 retval = IP_FW_PASS;
2334 l = 0; /* exit inner loop */
2335 done = 1; /* exit outer loop */
2340 if (args->eh) /* not valid on layer2 pkts */
2342 if (q == NULL || q->rule != f ||
2343 dyn_dir == MATCH_FORWARD) {
2344 struct sockaddr_in6 *sin6;
2346 sin6 = &(((ipfw_insn_sa6 *)cmd)->sa);
2347 args->next_hop6 = sin6;
2349 retval = IP_FW_PASS;
2350 l = 0; /* exit inner loop */
2351 done = 1; /* exit outer loop */
2357 set_match(args, f_pos, chain);
2358 args->rule.info = IP_FW_ARG_TABLEARG(cmd->arg1);
2360 args->rule.info |= IPFW_ONEPASS;
2361 retval = (cmd->opcode == O_NETGRAPH) ?
2362 IP_FW_NETGRAPH : IP_FW_NGTEE;
2363 l = 0; /* exit inner loop */
2364 done = 1; /* exit outer loop */
2370 IPFW_INC_RULE_COUNTER(f, pktlen);
2371 fib = IP_FW_ARG_TABLEARG(cmd->arg1);
2372 if (fib >= rt_numfibs)
2375 args->f_id.fib = fib;
2376 l = 0; /* exit inner loop */
2383 code = IP_FW_ARG_TABLEARG(cmd->arg1) & 0x3F;
2384 l = 0; /* exit inner loop */
2389 ip->ip_tos = (code << 2) | (ip->ip_tos & 0x03);
2390 a += ntohs(ip->ip_sum) - ip->ip_tos;
2391 ip->ip_sum = htons(a);
2392 } else if (is_ipv6) {
2395 v = &((struct ip6_hdr *)ip)->ip6_vfc;
2396 *v = (*v & 0xF0) | (code >> 2);
2398 *v = (*v & 0x3F) | ((code & 0x03) << 6);
2402 IPFW_INC_RULE_COUNTER(f, pktlen);
2407 l = 0; /* exit inner loop */
2408 done = 1; /* exit outer loop */
2409 if (!IPFW_NAT_LOADED) {
2410 retval = IP_FW_DENY;
2417 set_match(args, f_pos, chain);
2418 /* Check if this is 'global' nat rule */
2419 if (cmd->arg1 == 0) {
2420 retval = ipfw_nat_ptr(args, NULL, m);
2423 t = ((ipfw_insn_nat *)cmd)->nat;
2425 nat_id = IP_FW_ARG_TABLEARG(cmd->arg1);
2426 t = (*lookup_nat_ptr)(&chain->nat, nat_id);
2429 retval = IP_FW_DENY;
2432 if (cmd->arg1 != IP_FW_TABLEARG)
2433 ((ipfw_insn_nat *)cmd)->nat = t;
2435 retval = ipfw_nat_ptr(args, t, m);
2441 IPFW_INC_RULE_COUNTER(f, pktlen);
2442 l = 0; /* in any case exit inner loop */
2443 ip_off = ntohs(ip->ip_off);
2445 /* if not fragmented, go to next rule */
2446 if ((ip_off & (IP_MF | IP_OFFMASK)) == 0)
2449 args->m = m = ip_reass(m);
2452 * do IP header checksum fixup.
2454 if (m == NULL) { /* fragment got swallowed */
2455 retval = IP_FW_DENY;
2456 } else { /* good, packet complete */
2459 ip = mtod(m, struct ip *);
2460 hlen = ip->ip_hl << 2;
2462 if (hlen == sizeof(struct ip))
2463 ip->ip_sum = in_cksum_hdr(ip);
2465 ip->ip_sum = in_cksum(m, hlen);
2466 retval = IP_FW_REASS;
2467 set_match(args, f_pos, chain);
2469 done = 1; /* exit outer loop */
2474 panic("-- unknown opcode %d\n", cmd->opcode);
2475 } /* end of switch() on opcodes */
2477 * if we get here with l=0, then match is irrelevant.
2480 if (cmd->len & F_NOT)
2484 if (cmd->len & F_OR)
2487 if (!(cmd->len & F_OR)) /* not an OR block, */
2488 break; /* try next rule */
2491 } /* end of inner loop, scan opcodes */
2497 /* next_rule:; */ /* try next rule */
2499 } /* end of outer for, scan rules */
2502 struct ip_fw *rule = chain->map[f_pos];
2503 /* Update statistics */
2504 IPFW_INC_RULE_COUNTER(rule, pktlen);
2506 retval = IP_FW_DENY;
2507 printf("ipfw: ouch!, skip past end of rules, denying packet\n");
2509 IPFW_PF_RUNLOCK(chain);
2511 if (ucred_cache != NULL)
2512 crfree(ucred_cache);
2518 printf("ipfw: pullup failed\n");
2519 return (IP_FW_DENY);
2523 * Set maximum number of tables that can be used in given VNET ipfw instance.
2527 sysctl_ipfw_table_num(SYSCTL_HANDLER_ARGS)
2530 unsigned int ntables;
2532 ntables = V_fw_tables_max;
2534 error = sysctl_handle_int(oidp, &ntables, 0, req);
2535 /* Read operation or some error */
2536 if ((error != 0) || (req->newptr == NULL))
2539 return (ipfw_resize_tables(&V_layer3_chain, ntables));
2543 * Module and VNET glue
2547 * Stuff that must be initialised only on boot or module load
2555 * Only print out this stuff the first time around,
2556 * when called from the sysinit code.
2562 "initialized, divert %s, nat %s, "
2563 "default to %s, logging ",
2569 #ifdef IPFIREWALL_NAT
2574 default_to_accept ? "accept" : "deny");
2577 * Note: V_xxx variables can be accessed here but the vnet specific
2578 * initializer may not have been called yet for the VIMAGE case.
2579 * Tuneables will have been processed. We will print out values for
2581 * XXX This should all be rationalized AFTER 8.0
2583 if (V_fw_verbose == 0)
2584 printf("disabled\n");
2585 else if (V_verbose_limit == 0)
2586 printf("unlimited\n");
2588 printf("limited to %d packets/entry by default\n",
2591 /* Check user-supplied table count for validness */
2592 if (default_fw_tables > IPFW_TABLES_MAX)
2593 default_fw_tables = IPFW_TABLES_MAX;
2595 ipfw_log_bpf(1); /* init */
2600 * Called for the removal of the last instance only on module unload.
2606 ipfw_log_bpf(0); /* uninit */
2607 printf("IP firewall unloaded\n");
2611 * Stuff that must be initialized for every instance
2612 * (including the first of course).
2615 vnet_ipfw_init(const void *unused)
2618 struct ip_fw *rule = NULL;
2619 struct ip_fw_chain *chain;
2621 chain = &V_layer3_chain;
2623 /* First set up some values that are compile time options */
2624 V_autoinc_step = 100; /* bounded to 1..1000 in add_rule() */
2625 V_fw_deny_unknown_exthdrs = 1;
2626 #ifdef IPFIREWALL_VERBOSE
2629 #ifdef IPFIREWALL_VERBOSE_LIMIT
2630 V_verbose_limit = IPFIREWALL_VERBOSE_LIMIT;
2632 #ifdef IPFIREWALL_NAT
2633 LIST_INIT(&chain->nat);
2636 /* insert the default rule and create the initial map */
2638 chain->static_len = sizeof(struct ip_fw);
2639 chain->map = malloc(sizeof(struct ip_fw *), M_IPFW, M_WAITOK | M_ZERO);
2641 rule = malloc(chain->static_len, M_IPFW, M_WAITOK | M_ZERO);
2643 /* Set initial number of tables */
2644 V_fw_tables_max = default_fw_tables;
2645 error = ipfw_init_tables(chain);
2647 printf("ipfw2: setting up tables failed\n");
2648 free(chain->map, M_IPFW);
2653 /* fill and insert the default rule */
2655 rule->rulenum = IPFW_DEFAULT_RULE;
2657 rule->set = RESVD_SET;
2658 rule->cmd[0].len = 1;
2659 rule->cmd[0].opcode = default_to_accept ? O_ACCEPT : O_DENY;
2660 chain->default_rule = chain->map[0] = rule;
2661 chain->id = rule->id = 1;
2663 IPFW_LOCK_INIT(chain);
2664 ipfw_dyn_init(chain);
2666 /* First set up some values that are compile time options */
2667 V_ipfw_vnet_ready = 1; /* Open for business */
2670 * Hook the sockopt handler and pfil hooks for ipv4 and ipv6.
2671 * Even if the latter two fail we still keep the module alive
2672 * because the sockopt and layer2 paths are still useful.
2673 * ipfw[6]_hook return 0 on success, ENOENT on failure,
2674 * so we can ignore the exact return value and just set a flag.
2676 * Note that V_fw[6]_enable are manipulated by a SYSCTL_PROC so
2677 * changes in the underlying (per-vnet) variables trigger
2678 * immediate hook()/unhook() calls.
2679 * In layer2 we have the same behaviour, except that V_ether_ipfw
2680 * is checked on each packet because there are no pfil hooks.
2682 V_ip_fw_ctl_ptr = ipfw_ctl;
2683 error = ipfw_attach_hooks(1);
2688 * Called for the removal of each instance.
2691 vnet_ipfw_uninit(const void *unused)
2693 struct ip_fw *reap, *rule;
2694 struct ip_fw_chain *chain = &V_layer3_chain;
2697 V_ipfw_vnet_ready = 0; /* tell new callers to go away */
2699 * disconnect from ipv4, ipv6, layer2 and sockopt.
2700 * Then grab, release and grab again the WLOCK so we make
2701 * sure the update is propagated and nobody will be in.
2703 (void)ipfw_attach_hooks(0 /* detach */);
2704 V_ip_fw_ctl_ptr = NULL;
2705 IPFW_UH_WLOCK(chain);
2706 IPFW_UH_WUNLOCK(chain);
2707 IPFW_UH_WLOCK(chain);
2710 ipfw_dyn_uninit(0); /* run the callout_drain */
2711 IPFW_WUNLOCK(chain);
2713 ipfw_destroy_tables(chain);
2716 for (i = 0; i < chain->n_rules; i++) {
2717 rule = chain->map[i];
2718 rule->x_next = reap;
2722 free(chain->map, M_IPFW);
2723 IPFW_WUNLOCK(chain);
2724 IPFW_UH_WUNLOCK(chain);
2726 ipfw_reap_rules(reap);
2727 IPFW_LOCK_DESTROY(chain);
2728 ipfw_dyn_uninit(1); /* free the remaining parts */
2733 * Module event handler.
2734 * In general we have the choice of handling most of these events by the
2735 * event handler or by the (VNET_)SYS(UN)INIT handlers. I have chosen to
2736 * use the SYSINIT handlers as they are more capable of expressing the
2737 * flow of control during module and vnet operations, so this is just
2738 * a skeleton. Note there is no SYSINIT equivalent of the module
2739 * SHUTDOWN handler, but we don't have anything to do in that case anyhow.
2742 ipfw_modevent(module_t mod, int type, void *unused)
2748 /* Called once at module load or
2749 * system boot if compiled in. */
2752 /* Called before unload. May veto unloading. */
2755 /* Called during unload. */
2758 /* Called during system shutdown. */
2767 static moduledata_t ipfwmod = {
2773 /* Define startup order. */
2774 #define IPFW_SI_SUB_FIREWALL SI_SUB_PROTO_IFATTACHDOMAIN
2775 #define IPFW_MODEVENT_ORDER (SI_ORDER_ANY - 255) /* On boot slot in here. */
2776 #define IPFW_MODULE_ORDER (IPFW_MODEVENT_ORDER + 1) /* A little later. */
2777 #define IPFW_VNET_ORDER (IPFW_MODEVENT_ORDER + 2) /* Later still. */
2779 DECLARE_MODULE(ipfw, ipfwmod, IPFW_SI_SUB_FIREWALL, IPFW_MODEVENT_ORDER);
2780 MODULE_VERSION(ipfw, 2);
2781 /* should declare some dependencies here */
2784 * Starting up. Done in order after ipfwmod() has been called.
2785 * VNET_SYSINIT is also called for each existing vnet and each new vnet.
2787 SYSINIT(ipfw_init, IPFW_SI_SUB_FIREWALL, IPFW_MODULE_ORDER,
2789 VNET_SYSINIT(vnet_ipfw_init, IPFW_SI_SUB_FIREWALL, IPFW_VNET_ORDER,
2790 vnet_ipfw_init, NULL);
2793 * Closing up shop. These are done in REVERSE ORDER, but still
2794 * after ipfwmod() has been called. Not called on reboot.
2795 * VNET_SYSUNINIT is also called for each exiting vnet as it exits.
2796 * or when the module is unloaded.
2798 SYSUNINIT(ipfw_destroy, IPFW_SI_SUB_FIREWALL, IPFW_MODULE_ORDER,
2799 ipfw_destroy, NULL);
2800 VNET_SYSUNINIT(vnet_ipfw_uninit, IPFW_SI_SUB_FIREWALL, IPFW_VNET_ORDER,
2801 vnet_ipfw_uninit, NULL);