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/counter.h>
46 #include <sys/eventhandler.h>
47 #include <sys/malloc.h>
49 #include <sys/kernel.h>
52 #include <sys/module.h>
55 #include <sys/rwlock.h>
56 #include <sys/socket.h>
57 #include <sys/socketvar.h>
58 #include <sys/sysctl.h>
59 #include <sys/syslog.h>
60 #include <sys/ucred.h>
61 #include <net/ethernet.h> /* for ETHERTYPE_IP */
63 #include <net/if_var.h>
64 #include <net/route.h>
68 #include <netpfil/pf/pf_mtag.h>
70 #include <netinet/in.h>
71 #include <netinet/in_var.h>
72 #include <netinet/in_pcb.h>
73 #include <netinet/ip.h>
74 #include <netinet/ip_var.h>
75 #include <netinet/ip_icmp.h>
76 #include <netinet/ip_fw.h>
77 #include <netinet/ip_carp.h>
78 #include <netinet/pim.h>
79 #include <netinet/tcp_var.h>
80 #include <netinet/udp.h>
81 #include <netinet/udp_var.h>
82 #include <netinet/sctp.h>
84 #include <netinet/ip6.h>
85 #include <netinet/icmp6.h>
87 #include <netinet6/in6_pcb.h>
88 #include <netinet6/scope6_var.h>
89 #include <netinet6/ip6_var.h>
92 #include <netpfil/ipfw/ip_fw_private.h>
94 #include <machine/in_cksum.h> /* XXX for in_cksum */
97 #include <security/mac/mac_framework.h>
101 * static variables followed by global ones.
102 * All ipfw global variables are here.
105 static VNET_DEFINE(int, fw_deny_unknown_exthdrs);
106 #define V_fw_deny_unknown_exthdrs VNET(fw_deny_unknown_exthdrs)
108 static VNET_DEFINE(int, fw_permit_single_frag6) = 1;
109 #define V_fw_permit_single_frag6 VNET(fw_permit_single_frag6)
111 #ifdef IPFIREWALL_DEFAULT_TO_ACCEPT
112 static int default_to_accept = 1;
114 static int default_to_accept;
117 VNET_DEFINE(int, autoinc_step);
118 VNET_DEFINE(int, fw_one_pass) = 1;
120 VNET_DEFINE(unsigned int, fw_tables_max);
121 VNET_DEFINE(unsigned int, fw_tables_sets) = 0; /* Don't use set-aware tables */
122 /* Use 128 tables by default */
123 static unsigned int default_fw_tables = IPFW_TABLES_DEFAULT;
125 static int jump_fast(struct ip_fw_chain *chain, struct ip_fw *f, int num,
126 int tablearg, int jump_backwards);
127 static int jump_linear(struct ip_fw_chain *chain, struct ip_fw *f, int num,
128 int tablearg, int jump_backwards);
129 #define JUMP(ch, f, num, targ, back) jump_fast(ch, f, num, targ, back)
132 * Each rule belongs to one of 32 different sets (0..31).
133 * The variable set_disable contains one bit per set.
134 * If the bit is set, all rules in the corresponding set
135 * are disabled. Set RESVD_SET(31) is reserved for the default rule
136 * and rules that are not deleted by the flush command,
137 * and CANNOT be disabled.
138 * Rules in set RESVD_SET can only be deleted individually.
140 VNET_DEFINE(u_int32_t, set_disable);
141 #define V_set_disable VNET(set_disable)
143 VNET_DEFINE(int, fw_verbose);
144 /* counter for ipfw_log(NULL...) */
145 VNET_DEFINE(u_int64_t, norule_counter);
146 VNET_DEFINE(int, verbose_limit);
148 /* layer3_chain contains the list of rules for layer 3 */
149 VNET_DEFINE(struct ip_fw_chain, layer3_chain);
151 /* ipfw_vnet_ready controls when we are open for business */
152 VNET_DEFINE(int, ipfw_vnet_ready) = 0;
154 VNET_DEFINE(int, ipfw_nat_ready) = 0;
156 ipfw_nat_t *ipfw_nat_ptr = NULL;
157 struct cfg_nat *(*lookup_nat_ptr)(struct nat_list *, int);
158 ipfw_nat_cfg_t *ipfw_nat_cfg_ptr;
159 ipfw_nat_cfg_t *ipfw_nat_del_ptr;
160 ipfw_nat_cfg_t *ipfw_nat_get_cfg_ptr;
161 ipfw_nat_cfg_t *ipfw_nat_get_log_ptr;
164 uint32_t dummy_def = IPFW_DEFAULT_RULE;
165 static int sysctl_ipfw_table_num(SYSCTL_HANDLER_ARGS);
166 static int sysctl_ipfw_tables_sets(SYSCTL_HANDLER_ARGS);
170 SYSCTL_NODE(_net_inet_ip, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall");
171 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, one_pass,
172 CTLFLAG_RW | CTLFLAG_SECURE3, &VNET_NAME(fw_one_pass), 0,
173 "Only do a single pass through ipfw when using dummynet(4)");
174 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, autoinc_step,
175 CTLFLAG_RW, &VNET_NAME(autoinc_step), 0,
176 "Rule number auto-increment step");
177 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, verbose,
178 CTLFLAG_RW | CTLFLAG_SECURE3, &VNET_NAME(fw_verbose), 0,
179 "Log matches to ipfw rules");
180 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, verbose_limit,
181 CTLFLAG_RW, &VNET_NAME(verbose_limit), 0,
182 "Set upper limit of matches of ipfw rules logged");
183 SYSCTL_UINT(_net_inet_ip_fw, OID_AUTO, default_rule, CTLFLAG_RD,
185 "The default/max possible rule number.");
186 SYSCTL_VNET_PROC(_net_inet_ip_fw, OID_AUTO, tables_max,
187 CTLTYPE_UINT|CTLFLAG_RW, 0, 0, sysctl_ipfw_table_num, "IU",
188 "Maximum number of concurrently used tables");
189 SYSCTL_VNET_PROC(_net_inet_ip_fw, OID_AUTO, tables_sets,
190 CTLTYPE_UINT|CTLFLAG_RW, 0, 0, sysctl_ipfw_tables_sets, "IU",
191 "Use per-set namespace for tables");
192 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, default_to_accept, CTLFLAG_RDTUN,
193 &default_to_accept, 0,
194 "Make the default rule accept all packets.");
195 TUNABLE_INT("net.inet.ip.fw.tables_max", (int *)&default_fw_tables);
196 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, static_count,
197 CTLFLAG_RD, &VNET_NAME(layer3_chain.n_rules), 0,
198 "Number of static rules");
201 SYSCTL_DECL(_net_inet6_ip6);
202 SYSCTL_NODE(_net_inet6_ip6, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall");
203 SYSCTL_VNET_INT(_net_inet6_ip6_fw, OID_AUTO, deny_unknown_exthdrs,
204 CTLFLAG_RW | CTLFLAG_SECURE, &VNET_NAME(fw_deny_unknown_exthdrs), 0,
205 "Deny packets with unknown IPv6 Extension Headers");
206 SYSCTL_VNET_INT(_net_inet6_ip6_fw, OID_AUTO, permit_single_frag6,
207 CTLFLAG_RW | CTLFLAG_SECURE, &VNET_NAME(fw_permit_single_frag6), 0,
208 "Permit single packet IPv6 fragments");
213 #endif /* SYSCTL_NODE */
217 * Some macros used in the various matching options.
218 * L3HDR maps an ipv4 pointer into a layer3 header pointer of type T
219 * Other macros just cast void * into the appropriate type
221 #define L3HDR(T, ip) ((T *)((u_int32_t *)(ip) + (ip)->ip_hl))
222 #define TCP(p) ((struct tcphdr *)(p))
223 #define SCTP(p) ((struct sctphdr *)(p))
224 #define UDP(p) ((struct udphdr *)(p))
225 #define ICMP(p) ((struct icmphdr *)(p))
226 #define ICMP6(p) ((struct icmp6_hdr *)(p))
229 icmptype_match(struct icmphdr *icmp, ipfw_insn_u32 *cmd)
231 int type = icmp->icmp_type;
233 return (type <= ICMP_MAXTYPE && (cmd->d[0] & (1<<type)) );
236 #define TT ( (1 << ICMP_ECHO) | (1 << ICMP_ROUTERSOLICIT) | \
237 (1 << ICMP_TSTAMP) | (1 << ICMP_IREQ) | (1 << ICMP_MASKREQ) )
240 is_icmp_query(struct icmphdr *icmp)
242 int type = icmp->icmp_type;
244 return (type <= ICMP_MAXTYPE && (TT & (1<<type)) );
249 * The following checks use two arrays of 8 or 16 bits to store the
250 * bits that we want set or clear, respectively. They are in the
251 * low and high half of cmd->arg1 or cmd->d[0].
253 * We scan options and store the bits we find set. We succeed if
255 * (want_set & ~bits) == 0 && (want_clear & ~bits) == want_clear
257 * The code is sometimes optimized not to store additional variables.
261 flags_match(ipfw_insn *cmd, u_int8_t bits)
266 if ( ((cmd->arg1 & 0xff) & bits) != 0)
267 return 0; /* some bits we want set were clear */
268 want_clear = (cmd->arg1 >> 8) & 0xff;
269 if ( (want_clear & bits) != want_clear)
270 return 0; /* some bits we want clear were set */
275 ipopts_match(struct ip *ip, ipfw_insn *cmd)
277 int optlen, bits = 0;
278 u_char *cp = (u_char *)(ip + 1);
279 int x = (ip->ip_hl << 2) - sizeof (struct ip);
281 for (; x > 0; x -= optlen, cp += optlen) {
282 int opt = cp[IPOPT_OPTVAL];
284 if (opt == IPOPT_EOL)
286 if (opt == IPOPT_NOP)
289 optlen = cp[IPOPT_OLEN];
290 if (optlen <= 0 || optlen > x)
291 return 0; /* invalid or truncated */
299 bits |= IP_FW_IPOPT_LSRR;
303 bits |= IP_FW_IPOPT_SSRR;
307 bits |= IP_FW_IPOPT_RR;
311 bits |= IP_FW_IPOPT_TS;
315 return (flags_match(cmd, bits));
319 tcpopts_match(struct tcphdr *tcp, ipfw_insn *cmd)
321 int optlen, bits = 0;
322 u_char *cp = (u_char *)(tcp + 1);
323 int x = (tcp->th_off << 2) - sizeof(struct tcphdr);
325 for (; x > 0; x -= optlen, cp += optlen) {
327 if (opt == TCPOPT_EOL)
329 if (opt == TCPOPT_NOP)
343 bits |= IP_FW_TCPOPT_MSS;
347 bits |= IP_FW_TCPOPT_WINDOW;
350 case TCPOPT_SACK_PERMITTED:
352 bits |= IP_FW_TCPOPT_SACK;
355 case TCPOPT_TIMESTAMP:
356 bits |= IP_FW_TCPOPT_TS;
361 return (flags_match(cmd, bits));
365 iface_match(struct ifnet *ifp, ipfw_insn_if *cmd, struct ip_fw_chain *chain,
369 if (ifp == NULL) /* no iface with this packet, match fails */
372 /* Check by name or by IP address */
373 if (cmd->name[0] != '\0') { /* match by name */
374 if (cmd->name[0] == '\1') /* use tablearg to match */
375 return ipfw_lookup_table_extended(chain, cmd->p.kidx, 0,
376 &ifp->if_index, tablearg);
379 if (fnmatch(cmd->name, ifp->if_xname, 0) == 0)
382 if (strncmp(ifp->if_xname, cmd->name, IFNAMSIZ) == 0)
386 #if !defined(USERSPACE) && defined(__FreeBSD__) /* and OSX too ? */
390 TAILQ_FOREACH(ia, &ifp->if_addrhead, ifa_link) {
391 if (ia->ifa_addr->sa_family != AF_INET)
393 if (cmd->p.ip.s_addr == ((struct sockaddr_in *)
394 (ia->ifa_addr))->sin_addr.s_addr) {
395 if_addr_runlock(ifp);
396 return(1); /* match */
399 if_addr_runlock(ifp);
400 #endif /* __FreeBSD__ */
402 return(0); /* no match, fail ... */
406 * The verify_path function checks if a route to the src exists and
407 * if it is reachable via ifp (when provided).
409 * The 'verrevpath' option checks that the interface that an IP packet
410 * arrives on is the same interface that traffic destined for the
411 * packet's source address would be routed out of.
412 * The 'versrcreach' option just checks that the source address is
413 * reachable via any route (except default) in the routing table.
414 * These two are a measure to block forged packets. This is also
415 * commonly known as "anti-spoofing" or Unicast Reverse Path
416 * Forwarding (Unicast RFP) in Cisco-ese. The name of the knobs
417 * is purposely reminiscent of the Cisco IOS command,
419 * ip verify unicast reverse-path
420 * ip verify unicast source reachable-via any
422 * which implements the same functionality. But note that the syntax
423 * is misleading, and the check may be performed on all IP packets
424 * whether unicast, multicast, or broadcast.
427 verify_path(struct in_addr src, struct ifnet *ifp, u_int fib)
429 #if defined(USERSPACE) || !defined(__FreeBSD__)
433 struct sockaddr_in *dst;
435 bzero(&ro, sizeof(ro));
437 dst = (struct sockaddr_in *)&(ro.ro_dst);
438 dst->sin_family = AF_INET;
439 dst->sin_len = sizeof(*dst);
441 in_rtalloc_ign(&ro, 0, fib);
443 if (ro.ro_rt == NULL)
447 * If ifp is provided, check for equality with rtentry.
448 * We should use rt->rt_ifa->ifa_ifp, instead of rt->rt_ifp,
449 * in order to pass packets injected back by if_simloop():
450 * routing entry (via lo0) for our own address
451 * may exist, so we need to handle routing assymetry.
453 if (ifp != NULL && ro.ro_rt->rt_ifa->ifa_ifp != ifp) {
458 /* if no ifp provided, check if rtentry is not default route */
460 satosin(rt_key(ro.ro_rt))->sin_addr.s_addr == INADDR_ANY) {
465 /* or if this is a blackhole/reject route */
466 if (ifp == NULL && ro.ro_rt->rt_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
471 /* found valid route */
474 #endif /* __FreeBSD__ */
479 * ipv6 specific rules here...
482 icmp6type_match (int type, ipfw_insn_u32 *cmd)
484 return (type <= ICMP6_MAXTYPE && (cmd->d[type/32] & (1<<(type%32)) ) );
488 flow6id_match( int curr_flow, ipfw_insn_u32 *cmd )
491 for (i=0; i <= cmd->o.arg1; ++i )
492 if (curr_flow == cmd->d[i] )
497 /* support for IP6_*_ME opcodes */
499 search_ip6_addr_net (struct in6_addr * ip6_addr)
503 struct in6_ifaddr *fdm;
504 struct in6_addr copia;
506 TAILQ_FOREACH(mdc, &V_ifnet, if_link) {
508 TAILQ_FOREACH(mdc2, &mdc->if_addrhead, ifa_link) {
509 if (mdc2->ifa_addr->sa_family == AF_INET6) {
510 fdm = (struct in6_ifaddr *)mdc2;
511 copia = fdm->ia_addr.sin6_addr;
512 /* need for leaving scope_id in the sock_addr */
513 in6_clearscope(&copia);
514 if (IN6_ARE_ADDR_EQUAL(ip6_addr, &copia)) {
515 if_addr_runlock(mdc);
520 if_addr_runlock(mdc);
526 verify_path6(struct in6_addr *src, struct ifnet *ifp, u_int fib)
529 struct sockaddr_in6 *dst;
531 bzero(&ro, sizeof(ro));
533 dst = (struct sockaddr_in6 * )&(ro.ro_dst);
534 dst->sin6_family = AF_INET6;
535 dst->sin6_len = sizeof(*dst);
536 dst->sin6_addr = *src;
538 in6_rtalloc_ign(&ro, 0, fib);
539 if (ro.ro_rt == NULL)
543 * if ifp is provided, check for equality with rtentry
544 * We should use rt->rt_ifa->ifa_ifp, instead of rt->rt_ifp,
545 * to support the case of sending packets to an address of our own.
546 * (where the former interface is the first argument of if_simloop()
547 * (=ifp), the latter is lo0)
549 if (ifp != NULL && ro.ro_rt->rt_ifa->ifa_ifp != ifp) {
554 /* if no ifp provided, check if rtentry is not default route */
556 IN6_IS_ADDR_UNSPECIFIED(&satosin6(rt_key(ro.ro_rt))->sin6_addr)) {
561 /* or if this is a blackhole/reject route */
562 if (ifp == NULL && ro.ro_rt->rt_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
567 /* found valid route */
574 is_icmp6_query(int icmp6_type)
576 if ((icmp6_type <= ICMP6_MAXTYPE) &&
577 (icmp6_type == ICMP6_ECHO_REQUEST ||
578 icmp6_type == ICMP6_MEMBERSHIP_QUERY ||
579 icmp6_type == ICMP6_WRUREQUEST ||
580 icmp6_type == ICMP6_FQDN_QUERY ||
581 icmp6_type == ICMP6_NI_QUERY))
588 send_reject6(struct ip_fw_args *args, int code, u_int hlen, struct ip6_hdr *ip6)
593 if (code == ICMP6_UNREACH_RST && args->f_id.proto == IPPROTO_TCP) {
595 tcp = (struct tcphdr *)((char *)ip6 + hlen);
597 if ((tcp->th_flags & TH_RST) == 0) {
599 m0 = ipfw_send_pkt(args->m, &(args->f_id),
600 ntohl(tcp->th_seq), ntohl(tcp->th_ack),
601 tcp->th_flags | TH_RST);
603 ip6_output(m0, NULL, NULL, 0, NULL, NULL,
607 } else if (code != ICMP6_UNREACH_RST) { /* Send an ICMPv6 unreach. */
610 * Unlike above, the mbufs need to line up with the ip6 hdr,
611 * as the contents are read. We need to m_adj() the
613 * The mbuf will however be thrown away so we can adjust it.
614 * Remember we did an m_pullup on it already so we
615 * can make some assumptions about contiguousness.
618 m_adj(m, args->L3offset);
620 icmp6_error(m, ICMP6_DST_UNREACH, code, 0);
631 * sends a reject message, consuming the mbuf passed as an argument.
634 send_reject(struct ip_fw_args *args, int code, int iplen, struct ip *ip)
638 /* XXX When ip is not guaranteed to be at mtod() we will
639 * need to account for this */
640 * The mbuf will however be thrown away so we can adjust it.
641 * Remember we did an m_pullup on it already so we
642 * can make some assumptions about contiguousness.
645 m_adj(m, args->L3offset);
647 if (code != ICMP_REJECT_RST) { /* Send an ICMP unreach */
648 icmp_error(args->m, ICMP_UNREACH, code, 0L, 0);
649 } else if (args->f_id.proto == IPPROTO_TCP) {
650 struct tcphdr *const tcp =
651 L3HDR(struct tcphdr, mtod(args->m, struct ip *));
652 if ( (tcp->th_flags & TH_RST) == 0) {
654 m = ipfw_send_pkt(args->m, &(args->f_id),
655 ntohl(tcp->th_seq), ntohl(tcp->th_ack),
656 tcp->th_flags | TH_RST);
658 ip_output(m, NULL, NULL, 0, NULL, NULL);
667 * Support for uid/gid/jail lookup. These tests are expensive
668 * (because we may need to look into the list of active sockets)
669 * so we cache the results. ugid_lookupp is 0 if we have not
670 * yet done a lookup, 1 if we succeeded, and -1 if we tried
671 * and failed. The function always returns the match value.
672 * We could actually spare the variable and use *uc, setting
673 * it to '(void *)check_uidgid if we have no info, NULL if
674 * we tried and failed, or any other value if successful.
677 check_uidgid(ipfw_insn_u32 *insn, struct ip_fw_args *args, int *ugid_lookupp,
680 #if defined(USERSPACE)
681 return 0; // not supported in userspace
685 return cred_check(insn, proto, oif,
686 dst_ip, dst_port, src_ip, src_port,
687 (struct bsd_ucred *)uc, ugid_lookupp, ((struct mbuf *)inp)->m_skb);
689 struct in_addr src_ip, dst_ip;
690 struct inpcbinfo *pi;
691 struct ipfw_flow_id *id;
692 struct inpcb *pcb, *inp;
702 * Check to see if the UDP or TCP stack supplied us with
703 * the PCB. If so, rather then holding a lock and looking
704 * up the PCB, we can use the one that was supplied.
706 if (inp && *ugid_lookupp == 0) {
707 INP_LOCK_ASSERT(inp);
708 if (inp->inp_socket != NULL) {
709 *uc = crhold(inp->inp_cred);
715 * If we have already been here and the packet has no
716 * PCB entry associated with it, then we can safely
717 * assume that this is a no match.
719 if (*ugid_lookupp == -1)
721 if (id->proto == IPPROTO_TCP) {
724 } else if (id->proto == IPPROTO_UDP) {
725 lookupflags = INPLOOKUP_WILDCARD;
729 lookupflags |= INPLOOKUP_RLOCKPCB;
731 if (*ugid_lookupp == 0) {
732 if (id->addr_type == 6) {
735 pcb = in6_pcblookup_mbuf(pi,
736 &id->src_ip6, htons(id->src_port),
737 &id->dst_ip6, htons(id->dst_port),
738 lookupflags, oif, args->m);
740 pcb = in6_pcblookup_mbuf(pi,
741 &id->dst_ip6, htons(id->dst_port),
742 &id->src_ip6, htons(id->src_port),
743 lookupflags, oif, args->m);
749 src_ip.s_addr = htonl(id->src_ip);
750 dst_ip.s_addr = htonl(id->dst_ip);
752 pcb = in_pcblookup_mbuf(pi,
753 src_ip, htons(id->src_port),
754 dst_ip, htons(id->dst_port),
755 lookupflags, oif, args->m);
757 pcb = in_pcblookup_mbuf(pi,
758 dst_ip, htons(id->dst_port),
759 src_ip, htons(id->src_port),
760 lookupflags, oif, args->m);
763 INP_RLOCK_ASSERT(pcb);
764 *uc = crhold(pcb->inp_cred);
768 if (*ugid_lookupp == 0) {
770 * We tried and failed, set the variable to -1
771 * so we will not try again on this packet.
777 if (insn->o.opcode == O_UID)
778 match = ((*uc)->cr_uid == (uid_t)insn->d[0]);
779 else if (insn->o.opcode == O_GID)
780 match = groupmember((gid_t)insn->d[0], *uc);
781 else if (insn->o.opcode == O_JAIL)
782 match = ((*uc)->cr_prison->pr_id == (int)insn->d[0]);
784 #endif /* __FreeBSD__ */
785 #endif /* not supported in userspace */
789 * Helper function to set args with info on the rule after the matching
790 * one. slot is precise, whereas we guess rule_id as they are
791 * assigned sequentially.
794 set_match(struct ip_fw_args *args, int slot,
795 struct ip_fw_chain *chain)
797 args->rule.chain_id = chain->id;
798 args->rule.slot = slot + 1; /* we use 0 as a marker */
799 args->rule.rule_id = 1 + chain->map[slot]->id;
800 args->rule.rulenum = chain->map[slot]->rulenum;
804 * Helper function to enable cached rule lookups using
805 * cached_id and cached_pos fields in ipfw rule.
808 jump_fast(struct ip_fw_chain *chain, struct ip_fw *f, int num,
809 int tablearg, int jump_backwards)
813 /* If possible use cached f_pos (in f->cached_pos),
814 * whose version is written in f->cached_id
815 * (horrible hacks to avoid changing the ABI).
817 if (num != IP_FW_TARG && f->cached_id == chain->id)
818 f_pos = f->cached_pos;
820 int i = IP_FW_ARG_TABLEARG(chain, num, skipto);
821 /* make sure we do not jump backward */
822 if (jump_backwards == 0 && i <= f->rulenum)
824 if (chain->idxmap != NULL)
825 f_pos = chain->idxmap[i];
827 f_pos = ipfw_find_rule(chain, i, 0);
828 /* update the cache */
829 if (num != IP_FW_TARG) {
830 f->cached_id = chain->id;
831 f->cached_pos = f_pos;
839 * Helper function to enable real fast rule lookups.
842 jump_linear(struct ip_fw_chain *chain, struct ip_fw *f, int num,
843 int tablearg, int jump_backwards)
847 num = IP_FW_ARG_TABLEARG(chain, num, skipto);
848 /* make sure we do not jump backward */
849 if (jump_backwards == 0 && num <= f->rulenum)
850 num = f->rulenum + 1;
851 f_pos = chain->idxmap[num];
856 #define TARG(k, f) IP_FW_ARG_TABLEARG(chain, k, f)
858 * The main check routine for the firewall.
860 * All arguments are in args so we can modify them and return them
861 * back to the caller.
865 * args->m (in/out) The packet; we set to NULL when/if we nuke it.
866 * Starts with the IP header.
867 * args->eh (in) Mac header if present, NULL for layer3 packet.
868 * args->L3offset Number of bytes bypassed if we came from L2.
869 * e.g. often sizeof(eh) ** NOTYET **
870 * args->oif Outgoing interface, NULL if packet is incoming.
871 * The incoming interface is in the mbuf. (in)
872 * args->divert_rule (in/out)
873 * Skip up to the first rule past this rule number;
874 * upon return, non-zero port number for divert or tee.
876 * args->rule Pointer to the last matching rule (in/out)
877 * args->next_hop Socket we are forwarding to (out).
878 * args->next_hop6 IPv6 next hop we are forwarding to (out).
879 * args->f_id Addresses grabbed from the packet (out)
880 * args->rule.info a cookie depending on rule action
884 * IP_FW_PASS the packet must be accepted
885 * IP_FW_DENY the packet must be dropped
886 * IP_FW_DIVERT divert packet, port in m_tag
887 * IP_FW_TEE tee packet, port in m_tag
888 * IP_FW_DUMMYNET to dummynet, pipe in args->cookie
889 * IP_FW_NETGRAPH into netgraph, cookie args->cookie
890 * args->rule contains the matching rule,
891 * args->rule.info has additional information.
895 ipfw_chk(struct ip_fw_args *args)
899 * Local variables holding state while processing a packet:
901 * IMPORTANT NOTE: to speed up the processing of rules, there
902 * are some assumption on the values of the variables, which
903 * are documented here. Should you change them, please check
904 * the implementation of the various instructions to make sure
905 * that they still work.
907 * args->eh The MAC header. It is non-null for a layer2
908 * packet, it is NULL for a layer-3 packet.
910 * args->L3offset Offset in the packet to the L3 (IP or equiv.) header.
912 * m | args->m Pointer to the mbuf, as received from the caller.
913 * It may change if ipfw_chk() does an m_pullup, or if it
914 * consumes the packet because it calls send_reject().
915 * XXX This has to change, so that ipfw_chk() never modifies
916 * or consumes the buffer.
917 * ip is the beginning of the ip(4 or 6) header.
918 * Calculated by adding the L3offset to the start of data.
919 * (Until we start using L3offset, the packet is
920 * supposed to start with the ip header).
922 struct mbuf *m = args->m;
923 struct ip *ip = mtod(m, struct ip *);
926 * For rules which contain uid/gid or jail constraints, cache
927 * a copy of the users credentials after the pcb lookup has been
928 * executed. This will speed up the processing of rules with
929 * these types of constraints, as well as decrease contention
930 * on pcb related locks.
933 struct bsd_ucred ucred_cache;
935 struct ucred *ucred_cache = NULL;
937 int ucred_lookup = 0;
940 * oif | args->oif If NULL, ipfw_chk has been called on the
941 * inbound path (ether_input, ip_input).
942 * If non-NULL, ipfw_chk has been called on the outbound path
943 * (ether_output, ip_output).
945 struct ifnet *oif = args->oif;
947 int f_pos = 0; /* index of current rule in the array */
951 * hlen The length of the IP header.
953 u_int hlen = 0; /* hlen >0 means we have an IP pkt */
956 * offset The offset of a fragment. offset != 0 means that
957 * we have a fragment at this offset of an IPv4 packet.
958 * offset == 0 means that (if this is an IPv4 packet)
959 * this is the first or only fragment.
960 * For IPv6 offset|ip6f_mf == 0 means there is no Fragment Header
961 * or there is a single packet fragement (fragement header added
962 * without needed). We will treat a single packet fragment as if
963 * there was no fragment header (or log/block depending on the
964 * V_fw_permit_single_frag6 sysctl setting).
970 * Local copies of addresses. They are only valid if we have
973 * proto The protocol. Set to 0 for non-ip packets,
974 * or to the protocol read from the packet otherwise.
975 * proto != 0 means that we have an IPv4 packet.
977 * src_port, dst_port port numbers, in HOST format. Only
978 * valid for TCP and UDP packets.
980 * src_ip, dst_ip ip addresses, in NETWORK format.
981 * Only valid for IPv4 packets.
984 uint16_t src_port = 0, dst_port = 0; /* NOTE: host format */
985 struct in_addr src_ip, dst_ip; /* NOTE: network format */
988 uint16_t etype = 0; /* Host order stored ether type */
991 * dyn_dir = MATCH_UNKNOWN when rules unchecked,
992 * MATCH_NONE when checked and not matched (q = NULL),
993 * MATCH_FORWARD or MATCH_REVERSE otherwise (q != NULL)
995 int dyn_dir = MATCH_UNKNOWN;
996 ipfw_dyn_rule *q = NULL;
997 struct ip_fw_chain *chain = &V_layer3_chain;
1000 * We store in ulp a pointer to the upper layer protocol header.
1001 * In the ipv4 case this is easy to determine from the header,
1002 * but for ipv6 we might have some additional headers in the middle.
1003 * ulp is NULL if not found.
1005 void *ulp = NULL; /* upper layer protocol pointer. */
1007 /* XXX ipv6 variables */
1009 uint8_t icmp6_type = 0;
1010 uint16_t ext_hd = 0; /* bits vector for extension header filtering */
1011 /* end of ipv6 variables */
1015 int done = 0; /* flag to exit the outer loop */
1017 if (m->m_flags & M_SKIP_FIREWALL || (! V_ipfw_vnet_ready))
1018 return (IP_FW_PASS); /* accept */
1020 dst_ip.s_addr = 0; /* make sure it is initialized */
1021 src_ip.s_addr = 0; /* make sure it is initialized */
1022 pktlen = m->m_pkthdr.len;
1023 args->f_id.fib = M_GETFIB(m); /* note mbuf not altered) */
1024 proto = args->f_id.proto = 0; /* mark f_id invalid */
1025 /* XXX 0 is a valid proto: IP/IPv6 Hop-by-Hop Option */
1028 * PULLUP_TO(len, p, T) makes sure that len + sizeof(T) is contiguous,
1029 * then it sets p to point at the offset "len" in the mbuf. WARNING: the
1030 * pointer might become stale after other pullups (but we never use it
1033 #define PULLUP_TO(_len, p, T) PULLUP_LEN(_len, p, sizeof(T))
1034 #define PULLUP_LEN(_len, p, T) \
1036 int x = (_len) + T; \
1037 if ((m)->m_len < x) { \
1038 args->m = m = m_pullup(m, x); \
1040 goto pullup_failed; \
1042 p = (mtod(m, char *) + (_len)); \
1046 * if we have an ether header,
1049 etype = ntohs(args->eh->ether_type);
1051 /* Identify IP packets and fill up variables. */
1052 if (pktlen >= sizeof(struct ip6_hdr) &&
1053 (args->eh == NULL || etype == ETHERTYPE_IPV6) && ip->ip_v == 6) {
1054 struct ip6_hdr *ip6 = (struct ip6_hdr *)ip;
1056 args->f_id.addr_type = 6;
1057 hlen = sizeof(struct ip6_hdr);
1058 proto = ip6->ip6_nxt;
1060 /* Search extension headers to find upper layer protocols */
1061 while (ulp == NULL && offset == 0) {
1063 case IPPROTO_ICMPV6:
1064 PULLUP_TO(hlen, ulp, struct icmp6_hdr);
1065 icmp6_type = ICMP6(ulp)->icmp6_type;
1069 PULLUP_TO(hlen, ulp, struct tcphdr);
1070 dst_port = TCP(ulp)->th_dport;
1071 src_port = TCP(ulp)->th_sport;
1072 /* save flags for dynamic rules */
1073 args->f_id._flags = TCP(ulp)->th_flags;
1077 PULLUP_TO(hlen, ulp, struct sctphdr);
1078 src_port = SCTP(ulp)->src_port;
1079 dst_port = SCTP(ulp)->dest_port;
1083 PULLUP_TO(hlen, ulp, struct udphdr);
1084 dst_port = UDP(ulp)->uh_dport;
1085 src_port = UDP(ulp)->uh_sport;
1088 case IPPROTO_HOPOPTS: /* RFC 2460 */
1089 PULLUP_TO(hlen, ulp, struct ip6_hbh);
1090 ext_hd |= EXT_HOPOPTS;
1091 hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3;
1092 proto = ((struct ip6_hbh *)ulp)->ip6h_nxt;
1096 case IPPROTO_ROUTING: /* RFC 2460 */
1097 PULLUP_TO(hlen, ulp, struct ip6_rthdr);
1098 switch (((struct ip6_rthdr *)ulp)->ip6r_type) {
1100 ext_hd |= EXT_RTHDR0;
1103 ext_hd |= EXT_RTHDR2;
1107 printf("IPFW2: IPV6 - Unknown "
1108 "Routing Header type(%d)\n",
1109 ((struct ip6_rthdr *)
1111 if (V_fw_deny_unknown_exthdrs)
1112 return (IP_FW_DENY);
1115 ext_hd |= EXT_ROUTING;
1116 hlen += (((struct ip6_rthdr *)ulp)->ip6r_len + 1) << 3;
1117 proto = ((struct ip6_rthdr *)ulp)->ip6r_nxt;
1121 case IPPROTO_FRAGMENT: /* RFC 2460 */
1122 PULLUP_TO(hlen, ulp, struct ip6_frag);
1123 ext_hd |= EXT_FRAGMENT;
1124 hlen += sizeof (struct ip6_frag);
1125 proto = ((struct ip6_frag *)ulp)->ip6f_nxt;
1126 offset = ((struct ip6_frag *)ulp)->ip6f_offlg &
1128 ip6f_mf = ((struct ip6_frag *)ulp)->ip6f_offlg &
1130 if (V_fw_permit_single_frag6 == 0 &&
1131 offset == 0 && ip6f_mf == 0) {
1133 printf("IPFW2: IPV6 - Invalid "
1134 "Fragment Header\n");
1135 if (V_fw_deny_unknown_exthdrs)
1136 return (IP_FW_DENY);
1140 ntohl(((struct ip6_frag *)ulp)->ip6f_ident);
1144 case IPPROTO_DSTOPTS: /* RFC 2460 */
1145 PULLUP_TO(hlen, ulp, struct ip6_hbh);
1146 ext_hd |= EXT_DSTOPTS;
1147 hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3;
1148 proto = ((struct ip6_hbh *)ulp)->ip6h_nxt;
1152 case IPPROTO_AH: /* RFC 2402 */
1153 PULLUP_TO(hlen, ulp, struct ip6_ext);
1155 hlen += (((struct ip6_ext *)ulp)->ip6e_len + 2) << 2;
1156 proto = ((struct ip6_ext *)ulp)->ip6e_nxt;
1160 case IPPROTO_ESP: /* RFC 2406 */
1161 PULLUP_TO(hlen, ulp, uint32_t); /* SPI, Seq# */
1162 /* Anything past Seq# is variable length and
1163 * data past this ext. header is encrypted. */
1167 case IPPROTO_NONE: /* RFC 2460 */
1169 * Packet ends here, and IPv6 header has
1170 * already been pulled up. If ip6e_len!=0
1171 * then octets must be ignored.
1173 ulp = ip; /* non-NULL to get out of loop. */
1176 case IPPROTO_OSPFIGP:
1177 /* XXX OSPF header check? */
1178 PULLUP_TO(hlen, ulp, struct ip6_ext);
1182 /* XXX PIM header check? */
1183 PULLUP_TO(hlen, ulp, struct pim);
1187 PULLUP_TO(hlen, ulp, struct carp_header);
1188 if (((struct carp_header *)ulp)->carp_version !=
1190 return (IP_FW_DENY);
1191 if (((struct carp_header *)ulp)->carp_type !=
1193 return (IP_FW_DENY);
1196 case IPPROTO_IPV6: /* RFC 2893 */
1197 PULLUP_TO(hlen, ulp, struct ip6_hdr);
1200 case IPPROTO_IPV4: /* RFC 2893 */
1201 PULLUP_TO(hlen, ulp, struct ip);
1206 printf("IPFW2: IPV6 - Unknown "
1207 "Extension Header(%d), ext_hd=%x\n",
1209 if (V_fw_deny_unknown_exthdrs)
1210 return (IP_FW_DENY);
1211 PULLUP_TO(hlen, ulp, struct ip6_ext);
1215 ip = mtod(m, struct ip *);
1216 ip6 = (struct ip6_hdr *)ip;
1217 args->f_id.src_ip6 = ip6->ip6_src;
1218 args->f_id.dst_ip6 = ip6->ip6_dst;
1219 args->f_id.src_ip = 0;
1220 args->f_id.dst_ip = 0;
1221 args->f_id.flow_id6 = ntohl(ip6->ip6_flow);
1222 } else if (pktlen >= sizeof(struct ip) &&
1223 (args->eh == NULL || etype == ETHERTYPE_IP) && ip->ip_v == 4) {
1225 hlen = ip->ip_hl << 2;
1226 args->f_id.addr_type = 4;
1229 * Collect parameters into local variables for faster matching.
1232 src_ip = ip->ip_src;
1233 dst_ip = ip->ip_dst;
1234 offset = ntohs(ip->ip_off) & IP_OFFMASK;
1235 iplen = ntohs(ip->ip_len);
1236 pktlen = iplen < pktlen ? iplen : pktlen;
1241 PULLUP_TO(hlen, ulp, struct tcphdr);
1242 dst_port = TCP(ulp)->th_dport;
1243 src_port = TCP(ulp)->th_sport;
1244 /* save flags for dynamic rules */
1245 args->f_id._flags = TCP(ulp)->th_flags;
1249 PULLUP_TO(hlen, ulp, struct sctphdr);
1250 src_port = SCTP(ulp)->src_port;
1251 dst_port = SCTP(ulp)->dest_port;
1255 PULLUP_TO(hlen, ulp, struct udphdr);
1256 dst_port = UDP(ulp)->uh_dport;
1257 src_port = UDP(ulp)->uh_sport;
1261 PULLUP_TO(hlen, ulp, struct icmphdr);
1262 //args->f_id.flags = ICMP(ulp)->icmp_type;
1270 ip = mtod(m, struct ip *);
1271 args->f_id.src_ip = ntohl(src_ip.s_addr);
1272 args->f_id.dst_ip = ntohl(dst_ip.s_addr);
1275 if (proto) { /* we may have port numbers, store them */
1276 args->f_id.proto = proto;
1277 args->f_id.src_port = src_port = ntohs(src_port);
1278 args->f_id.dst_port = dst_port = ntohs(dst_port);
1281 IPFW_PF_RLOCK(chain);
1282 if (! V_ipfw_vnet_ready) { /* shutting down, leave NOW. */
1283 IPFW_PF_RUNLOCK(chain);
1284 return (IP_FW_PASS); /* accept */
1286 if (args->rule.slot) {
1288 * Packet has already been tagged as a result of a previous
1289 * match on rule args->rule aka args->rule_id (PIPE, QUEUE,
1290 * REASS, NETGRAPH, DIVERT/TEE...)
1291 * Validate the slot and continue from the next one
1292 * if still present, otherwise do a lookup.
1294 f_pos = (args->rule.chain_id == chain->id) ?
1296 ipfw_find_rule(chain, args->rule.rulenum,
1297 args->rule.rule_id);
1303 * Now scan the rules, and parse microinstructions for each rule.
1304 * We have two nested loops and an inner switch. Sometimes we
1305 * need to break out of one or both loops, or re-enter one of
1306 * the loops with updated variables. Loop variables are:
1308 * f_pos (outer loop) points to the current rule.
1309 * On output it points to the matching rule.
1310 * done (outer loop) is used as a flag to break the loop.
1311 * l (inner loop) residual length of current rule.
1312 * cmd points to the current microinstruction.
1314 * We break the inner loop by setting l=0 and possibly
1315 * cmdlen=0 if we don't want to advance cmd.
1316 * We break the outer loop by setting done=1
1317 * We can restart the inner loop by setting l>0 and f_pos, f, cmd
1320 for (; f_pos < chain->n_rules; f_pos++) {
1322 uint32_t tablearg = 0;
1323 int l, cmdlen, skip_or; /* skip rest of OR block */
1326 f = chain->map[f_pos];
1327 if (V_set_disable & (1 << f->set) )
1331 for (l = f->cmd_len, cmd = f->cmd ; l > 0 ;
1332 l -= cmdlen, cmd += cmdlen) {
1336 * check_body is a jump target used when we find a
1337 * CHECK_STATE, and need to jump to the body of
1342 cmdlen = F_LEN(cmd);
1344 * An OR block (insn_1 || .. || insn_n) has the
1345 * F_OR bit set in all but the last instruction.
1346 * The first match will set "skip_or", and cause
1347 * the following instructions to be skipped until
1348 * past the one with the F_OR bit clear.
1350 if (skip_or) { /* skip this instruction */
1351 if ((cmd->len & F_OR) == 0)
1352 skip_or = 0; /* next one is good */
1355 match = 0; /* set to 1 if we succeed */
1357 switch (cmd->opcode) {
1359 * The first set of opcodes compares the packet's
1360 * fields with some pattern, setting 'match' if a
1361 * match is found. At the end of the loop there is
1362 * logic to deal with F_NOT and F_OR flags associated
1370 printf("ipfw: opcode %d unimplemented\n",
1378 * We only check offset == 0 && proto != 0,
1379 * as this ensures that we have a
1380 * packet with the ports info.
1384 if (proto == IPPROTO_TCP ||
1385 proto == IPPROTO_UDP)
1386 match = check_uidgid(
1387 (ipfw_insn_u32 *)cmd,
1388 args, &ucred_lookup,
1392 (void *)&ucred_cache);
1397 match = iface_match(m->m_pkthdr.rcvif,
1398 (ipfw_insn_if *)cmd, chain, &tablearg);
1402 match = iface_match(oif, (ipfw_insn_if *)cmd,
1407 match = iface_match(oif ? oif :
1408 m->m_pkthdr.rcvif, (ipfw_insn_if *)cmd,
1413 if (args->eh != NULL) { /* have MAC header */
1414 u_int32_t *want = (u_int32_t *)
1415 ((ipfw_insn_mac *)cmd)->addr;
1416 u_int32_t *mask = (u_int32_t *)
1417 ((ipfw_insn_mac *)cmd)->mask;
1418 u_int32_t *hdr = (u_int32_t *)args->eh;
1421 ( want[0] == (hdr[0] & mask[0]) &&
1422 want[1] == (hdr[1] & mask[1]) &&
1423 want[2] == (hdr[2] & mask[2]) );
1428 if (args->eh != NULL) {
1430 ((ipfw_insn_u16 *)cmd)->ports;
1433 for (i = cmdlen - 1; !match && i>0;
1435 match = (etype >= p[0] &&
1441 match = (offset != 0);
1444 case O_IN: /* "out" is "not in" */
1445 match = (oif == NULL);
1449 match = (args->eh != NULL);
1454 /* For diverted packets, args->rule.info
1455 * contains the divert port (in host format)
1456 * reason and direction.
1458 uint32_t i = args->rule.info;
1459 match = (i&IPFW_IS_MASK) == IPFW_IS_DIVERT &&
1460 cmd->arg1 & ((i & IPFW_INFO_IN) ? 1 : 2);
1466 * We do not allow an arg of 0 so the
1467 * check of "proto" only suffices.
1469 match = (proto == cmd->arg1);
1474 (((ipfw_insn_ip *)cmd)->addr.s_addr ==
1478 case O_IP_SRC_LOOKUP:
1479 case O_IP_DST_LOOKUP:
1482 (cmd->opcode == O_IP_DST_LOOKUP) ?
1483 dst_ip.s_addr : src_ip.s_addr;
1486 if (cmdlen > F_INSN_SIZE(ipfw_insn_u32)) {
1487 /* generic lookup. The key must be
1488 * in 32bit big-endian format.
1490 v = ((ipfw_insn_u32 *)cmd)->d[1];
1492 key = dst_ip.s_addr;
1494 key = src_ip.s_addr;
1495 else if (v == 6) /* dscp */
1496 key = (ip->ip_tos >> 2) & 0x3f;
1497 else if (offset != 0)
1499 else if (proto != IPPROTO_TCP &&
1500 proto != IPPROTO_UDP)
1507 else if (v == 4 || v == 5) {
1509 (ipfw_insn_u32 *)cmd,
1510 args, &ucred_lookup,
1513 if (v == 4 /* O_UID */)
1514 key = ucred_cache->cr_uid;
1515 else if (v == 5 /* O_JAIL */)
1516 key = ucred_cache->cr_prison->pr_id;
1517 #else /* !__FreeBSD__ */
1518 (void *)&ucred_cache);
1519 if (v ==4 /* O_UID */)
1520 key = ucred_cache.uid;
1521 else if (v == 5 /* O_JAIL */)
1522 key = ucred_cache.xid;
1523 #endif /* !__FreeBSD__ */
1525 #endif /* !USERSPACE */
1528 match = ipfw_lookup_table(chain,
1529 cmd->arg1, key, &v);
1532 if (cmdlen == F_INSN_SIZE(ipfw_insn_u32))
1534 ((ipfw_insn_u32 *)cmd)->d[0] == v;
1537 } else if (is_ipv6) {
1539 void *pkey = (cmd->opcode == O_IP_DST_LOOKUP) ?
1540 &args->f_id.dst_ip6: &args->f_id.src_ip6;
1541 match = ipfw_lookup_table_extended(chain,
1543 sizeof(struct in6_addr),
1545 if (cmdlen == F_INSN_SIZE(ipfw_insn_u32))
1546 match = ((ipfw_insn_u32 *)cmd)->d[0] == v;
1552 case O_IP_FLOW_LOOKUP:
1555 match = ipfw_lookup_table_extended(chain,
1556 cmd->arg1, 0, &args->f_id, &v);
1557 if (cmdlen == F_INSN_SIZE(ipfw_insn_u32))
1558 match = ((ipfw_insn_u32 *)cmd)->d[0] == v;
1567 (cmd->opcode == O_IP_DST_MASK) ?
1568 dst_ip.s_addr : src_ip.s_addr;
1569 uint32_t *p = ((ipfw_insn_u32 *)cmd)->d;
1572 for (; !match && i>0; i-= 2, p+= 2)
1573 match = (p[0] == (a & p[1]));
1581 INADDR_TO_IFP(src_ip, tif);
1582 match = (tif != NULL);
1588 match= is_ipv6 && search_ip6_addr_net(&args->f_id.src_ip6);
1595 u_int32_t *d = (u_int32_t *)(cmd+1);
1597 cmd->opcode == O_IP_DST_SET ?
1603 addr -= d[0]; /* subtract base */
1604 match = (addr < cmd->arg1) &&
1605 ( d[ 1 + (addr>>5)] &
1606 (1<<(addr & 0x1f)) );
1612 (((ipfw_insn_ip *)cmd)->addr.s_addr ==
1620 INADDR_TO_IFP(dst_ip, tif);
1621 match = (tif != NULL);
1627 match= is_ipv6 && search_ip6_addr_net(&args->f_id.dst_ip6);
1635 * offset == 0 && proto != 0 is enough
1636 * to guarantee that we have a
1637 * packet with port info.
1639 if ((proto==IPPROTO_UDP || proto==IPPROTO_TCP)
1642 (cmd->opcode == O_IP_SRCPORT) ?
1643 src_port : dst_port ;
1645 ((ipfw_insn_u16 *)cmd)->ports;
1648 for (i = cmdlen - 1; !match && i>0;
1650 match = (x>=p[0] && x<=p[1]);
1655 match = (offset == 0 && proto==IPPROTO_ICMP &&
1656 icmptype_match(ICMP(ulp), (ipfw_insn_u32 *)cmd) );
1661 match = is_ipv6 && offset == 0 &&
1662 proto==IPPROTO_ICMPV6 &&
1664 ICMP6(ulp)->icmp6_type,
1665 (ipfw_insn_u32 *)cmd);
1671 ipopts_match(ip, cmd) );
1676 cmd->arg1 == ip->ip_v);
1682 if (is_ipv4) { /* only for IP packets */
1687 if (cmd->opcode == O_IPLEN)
1689 else if (cmd->opcode == O_IPTTL)
1691 else /* must be IPID */
1692 x = ntohs(ip->ip_id);
1694 match = (cmd->arg1 == x);
1697 /* otherwise we have ranges */
1698 p = ((ipfw_insn_u16 *)cmd)->ports;
1700 for (; !match && i>0; i--, p += 2)
1701 match = (x >= p[0] && x <= p[1]);
1705 case O_IPPRECEDENCE:
1707 (cmd->arg1 == (ip->ip_tos & 0xe0)) );
1712 flags_match(cmd, ip->ip_tos));
1720 p = ((ipfw_insn_u32 *)cmd)->d;
1723 x = ip->ip_tos >> 2;
1726 v = &((struct ip6_hdr *)ip)->ip6_vfc;
1727 x = (*v & 0x0F) << 2;
1733 /* DSCP bitmask is stored as low_u32 high_u32 */
1735 match = *(p + 1) & (1 << (x - 32));
1737 match = *p & (1 << x);
1742 if (proto == IPPROTO_TCP && offset == 0) {
1750 ((ip->ip_hl + tcp->th_off) << 2);
1752 match = (cmd->arg1 == x);
1755 /* otherwise we have ranges */
1756 p = ((ipfw_insn_u16 *)cmd)->ports;
1758 for (; !match && i>0; i--, p += 2)
1759 match = (x >= p[0] && x <= p[1]);
1764 match = (proto == IPPROTO_TCP && offset == 0 &&
1765 flags_match(cmd, TCP(ulp)->th_flags));
1769 PULLUP_LEN(hlen, ulp, (TCP(ulp)->th_off << 2));
1770 match = (proto == IPPROTO_TCP && offset == 0 &&
1771 tcpopts_match(TCP(ulp), cmd));
1775 match = (proto == IPPROTO_TCP && offset == 0 &&
1776 ((ipfw_insn_u32 *)cmd)->d[0] ==
1781 match = (proto == IPPROTO_TCP && offset == 0 &&
1782 ((ipfw_insn_u32 *)cmd)->d[0] ==
1787 if (proto == IPPROTO_TCP && offset == 0) {
1792 x = ntohs(TCP(ulp)->th_win);
1794 match = (cmd->arg1 == x);
1797 /* Otherwise we have ranges. */
1798 p = ((ipfw_insn_u16 *)cmd)->ports;
1800 for (; !match && i > 0; i--, p += 2)
1801 match = (x >= p[0] && x <= p[1]);
1806 /* reject packets which have SYN only */
1807 /* XXX should i also check for TH_ACK ? */
1808 match = (proto == IPPROTO_TCP && offset == 0 &&
1809 (TCP(ulp)->th_flags &
1810 (TH_RST | TH_ACK | TH_SYN)) != TH_SYN);
1816 ipfw_insn_altq *altq = (ipfw_insn_altq *)cmd;
1819 * ALTQ uses mbuf tags from another
1820 * packet filtering system - pf(4).
1821 * We allocate a tag in its format
1822 * and fill it in, pretending to be pf(4).
1825 at = pf_find_mtag(m);
1826 if (at != NULL && at->qid != 0)
1828 mtag = m_tag_get(PACKET_TAG_PF,
1829 sizeof(struct pf_mtag), M_NOWAIT | M_ZERO);
1832 * Let the packet fall back to the
1837 m_tag_prepend(m, mtag);
1838 at = (struct pf_mtag *)(mtag + 1);
1839 at->qid = altq->qid;
1845 ipfw_log(chain, f, hlen, args, m,
1846 oif, offset | ip6f_mf, tablearg, ip);
1851 match = (random()<((ipfw_insn_u32 *)cmd)->d[0]);
1855 /* Outgoing packets automatically pass/match */
1856 match = ((oif != NULL) ||
1857 (m->m_pkthdr.rcvif == NULL) ||
1861 verify_path6(&(args->f_id.src_ip6),
1862 m->m_pkthdr.rcvif, args->f_id.fib) :
1864 verify_path(src_ip, m->m_pkthdr.rcvif,
1869 /* Outgoing packets automatically pass/match */
1870 match = (hlen > 0 && ((oif != NULL) ||
1873 verify_path6(&(args->f_id.src_ip6),
1874 NULL, args->f_id.fib) :
1876 verify_path(src_ip, NULL, args->f_id.fib)));
1880 /* Outgoing packets automatically pass/match */
1881 if (oif == NULL && hlen > 0 &&
1882 ( (is_ipv4 && in_localaddr(src_ip))
1885 in6_localaddr(&(args->f_id.src_ip6)))
1890 is_ipv6 ? verify_path6(
1891 &(args->f_id.src_ip6),
1904 match = (m_tag_find(m,
1905 PACKET_TAG_IPSEC_IN_DONE, NULL) != NULL);
1907 /* otherwise no match */
1913 IN6_ARE_ADDR_EQUAL(&args->f_id.src_ip6,
1914 &((ipfw_insn_ip6 *)cmd)->addr6);
1919 IN6_ARE_ADDR_EQUAL(&args->f_id.dst_ip6,
1920 &((ipfw_insn_ip6 *)cmd)->addr6);
1922 case O_IP6_SRC_MASK:
1923 case O_IP6_DST_MASK:
1927 struct in6_addr *d =
1928 &((ipfw_insn_ip6 *)cmd)->addr6;
1930 for (; !match && i > 0; d += 2,
1931 i -= F_INSN_SIZE(struct in6_addr)
1937 APPLY_MASK(&p, &d[1]);
1939 IN6_ARE_ADDR_EQUAL(&d[0],
1947 flow6id_match(args->f_id.flow_id6,
1948 (ipfw_insn_u32 *) cmd);
1953 (ext_hd & ((ipfw_insn *) cmd)->arg1);
1967 uint32_t tag = TARG(cmd->arg1, tag);
1969 /* Packet is already tagged with this tag? */
1970 mtag = m_tag_locate(m, MTAG_IPFW, tag, NULL);
1972 /* We have `untag' action when F_NOT flag is
1973 * present. And we must remove this mtag from
1974 * mbuf and reset `match' to zero (`match' will
1975 * be inversed later).
1976 * Otherwise we should allocate new mtag and
1977 * push it into mbuf.
1979 if (cmd->len & F_NOT) { /* `untag' action */
1981 m_tag_delete(m, mtag);
1985 mtag = m_tag_alloc( MTAG_IPFW,
1988 m_tag_prepend(m, mtag);
1995 case O_FIB: /* try match the specified fib */
1996 if (args->f_id.fib == cmd->arg1)
2001 #ifndef USERSPACE /* not supported in userspace */
2002 struct inpcb *inp = args->inp;
2003 struct inpcbinfo *pi;
2005 if (is_ipv6) /* XXX can we remove this ? */
2008 if (proto == IPPROTO_TCP)
2010 else if (proto == IPPROTO_UDP)
2016 * XXXRW: so_user_cookie should almost
2017 * certainly be inp_user_cookie?
2020 /* For incomming packet, lookup up the
2021 inpcb using the src/dest ip/port tuple */
2023 inp = in_pcblookup(pi,
2024 src_ip, htons(src_port),
2025 dst_ip, htons(dst_port),
2026 INPLOOKUP_RLOCKPCB, NULL);
2029 inp->inp_socket->so_user_cookie;
2035 if (inp->inp_socket) {
2037 inp->inp_socket->so_user_cookie;
2042 #endif /* !USERSPACE */
2048 uint32_t tag = TARG(cmd->arg1, tag);
2051 match = m_tag_locate(m, MTAG_IPFW,
2056 /* we have ranges */
2057 for (mtag = m_tag_first(m);
2058 mtag != NULL && !match;
2059 mtag = m_tag_next(m, mtag)) {
2063 if (mtag->m_tag_cookie != MTAG_IPFW)
2066 p = ((ipfw_insn_u16 *)cmd)->ports;
2068 for(; !match && i > 0; i--, p += 2)
2070 mtag->m_tag_id >= p[0] &&
2071 mtag->m_tag_id <= p[1];
2077 * The second set of opcodes represents 'actions',
2078 * i.e. the terminal part of a rule once the packet
2079 * matches all previous patterns.
2080 * Typically there is only one action for each rule,
2081 * and the opcode is stored at the end of the rule
2082 * (but there are exceptions -- see below).
2084 * In general, here we set retval and terminate the
2085 * outer loop (would be a 'break 3' in some language,
2086 * but we need to set l=0, done=1)
2089 * O_COUNT and O_SKIPTO actions:
2090 * instead of terminating, we jump to the next rule
2091 * (setting l=0), or to the SKIPTO target (setting
2092 * f/f_len, cmd and l as needed), respectively.
2094 * O_TAG, O_LOG and O_ALTQ action parameters:
2095 * perform some action and set match = 1;
2097 * O_LIMIT and O_KEEP_STATE: these opcodes are
2098 * not real 'actions', and are stored right
2099 * before the 'action' part of the rule.
2100 * These opcodes try to install an entry in the
2101 * state tables; if successful, we continue with
2102 * the next opcode (match=1; break;), otherwise
2103 * the packet must be dropped (set retval,
2104 * break loops with l=0, done=1)
2106 * O_PROBE_STATE and O_CHECK_STATE: these opcodes
2107 * cause a lookup of the state table, and a jump
2108 * to the 'action' part of the parent rule
2109 * if an entry is found, or
2110 * (CHECK_STATE only) a jump to the next rule if
2111 * the entry is not found.
2112 * The result of the lookup is cached so that
2113 * further instances of these opcodes become NOPs.
2114 * The jump to the next rule is done by setting
2119 if (ipfw_install_state(chain, f,
2120 (ipfw_insn_limit *)cmd, args, tablearg)) {
2121 /* error or limit violation */
2122 retval = IP_FW_DENY;
2123 l = 0; /* exit inner loop */
2124 done = 1; /* exit outer loop */
2132 * dynamic rules are checked at the first
2133 * keep-state or check-state occurrence,
2134 * with the result being stored in dyn_dir.
2135 * The compiler introduces a PROBE_STATE
2136 * instruction for us when we have a
2137 * KEEP_STATE (because PROBE_STATE needs
2140 if (dyn_dir == MATCH_UNKNOWN &&
2141 (q = ipfw_lookup_dyn_rule(&args->f_id,
2142 &dyn_dir, proto == IPPROTO_TCP ?
2146 * Found dynamic entry, update stats
2147 * and jump to the 'action' part of
2148 * the parent rule by setting
2149 * f, cmd, l and clearing cmdlen.
2151 IPFW_INC_DYN_COUNTER(q, pktlen);
2152 /* XXX we would like to have f_pos
2153 * readily accessible in the dynamic
2154 * rule, instead of having to
2158 f_pos = ipfw_find_rule(chain,
2160 cmd = ACTION_PTR(f);
2161 l = f->cmd_len - f->act_ofs;
2168 * Dynamic entry not found. If CHECK_STATE,
2169 * skip to next rule, if PROBE_STATE just
2170 * ignore and continue with next opcode.
2172 if (cmd->opcode == O_CHECK_STATE)
2173 l = 0; /* exit inner loop */
2178 retval = 0; /* accept */
2179 l = 0; /* exit inner loop */
2180 done = 1; /* exit outer loop */
2185 set_match(args, f_pos, chain);
2186 args->rule.info = TARG(cmd->arg1, pipe);
2187 if (cmd->opcode == O_PIPE)
2188 args->rule.info |= IPFW_IS_PIPE;
2190 args->rule.info |= IPFW_ONEPASS;
2191 retval = IP_FW_DUMMYNET;
2192 l = 0; /* exit inner loop */
2193 done = 1; /* exit outer loop */
2198 if (args->eh) /* not on layer 2 */
2200 /* otherwise this is terminal */
2201 l = 0; /* exit inner loop */
2202 done = 1; /* exit outer loop */
2203 retval = (cmd->opcode == O_DIVERT) ?
2204 IP_FW_DIVERT : IP_FW_TEE;
2205 set_match(args, f_pos, chain);
2206 args->rule.info = TARG(cmd->arg1, divert);
2210 IPFW_INC_RULE_COUNTER(f, pktlen);
2211 l = 0; /* exit inner loop */
2215 IPFW_INC_RULE_COUNTER(f, pktlen);
2216 f_pos = JUMP(chain, f, cmd->arg1, tablearg, 0);
2218 * Skip disabled rules, and re-enter
2219 * the inner loop with the correct
2220 * f_pos, f, l and cmd.
2221 * Also clear cmdlen and skip_or
2223 for (; f_pos < chain->n_rules - 1 &&
2225 (1 << chain->map[f_pos]->set));
2228 /* Re-enter the inner loop at the skipto rule. */
2229 f = chain->map[f_pos];
2236 break; /* not reached */
2238 case O_CALLRETURN: {
2240 * Implementation of `subroutine' call/return,
2241 * in the stack carried in an mbuf tag. This
2242 * is different from `skipto' in that any call
2243 * address is possible (`skipto' must prevent
2244 * backward jumps to avoid endless loops).
2245 * We have `return' action when F_NOT flag is
2246 * present. The `m_tag_id' field is used as
2250 uint16_t jmpto, *stack;
2252 #define IS_CALL ((cmd->len & F_NOT) == 0)
2253 #define IS_RETURN ((cmd->len & F_NOT) != 0)
2255 * Hand-rolled version of m_tag_locate() with
2257 * If not already tagged, allocate new tag.
2259 mtag = m_tag_first(m);
2260 while (mtag != NULL) {
2261 if (mtag->m_tag_cookie ==
2264 mtag = m_tag_next(m, mtag);
2266 if (mtag == NULL && IS_CALL) {
2267 mtag = m_tag_alloc(MTAG_IPFW_CALL, 0,
2268 IPFW_CALLSTACK_SIZE *
2269 sizeof(uint16_t), M_NOWAIT);
2271 m_tag_prepend(m, mtag);
2275 * On error both `call' and `return' just
2276 * continue with next rule.
2278 if (IS_RETURN && (mtag == NULL ||
2279 mtag->m_tag_id == 0)) {
2280 l = 0; /* exit inner loop */
2283 if (IS_CALL && (mtag == NULL ||
2284 mtag->m_tag_id >= IPFW_CALLSTACK_SIZE)) {
2285 printf("ipfw: call stack error, "
2286 "go to next rule\n");
2287 l = 0; /* exit inner loop */
2291 IPFW_INC_RULE_COUNTER(f, pktlen);
2292 stack = (uint16_t *)(mtag + 1);
2295 * The `call' action may use cached f_pos
2296 * (in f->next_rule), whose version is written
2298 * The `return' action, however, doesn't have
2299 * fixed jump address in cmd->arg1 and can't use
2303 stack[mtag->m_tag_id] = f->rulenum;
2305 f_pos = JUMP(chain, f, cmd->arg1,
2307 } else { /* `return' action */
2309 jmpto = stack[mtag->m_tag_id] + 1;
2310 f_pos = ipfw_find_rule(chain, jmpto, 0);
2314 * Skip disabled rules, and re-enter
2315 * the inner loop with the correct
2316 * f_pos, f, l and cmd.
2317 * Also clear cmdlen and skip_or
2319 for (; f_pos < chain->n_rules - 1 &&
2321 (1 << chain->map[f_pos]->set)); f_pos++)
2323 /* Re-enter the inner loop at the dest rule. */
2324 f = chain->map[f_pos];
2330 break; /* NOTREACHED */
2337 * Drop the packet and send a reject notice
2338 * if the packet is not ICMP (or is an ICMP
2339 * query), and it is not multicast/broadcast.
2341 if (hlen > 0 && is_ipv4 && offset == 0 &&
2342 (proto != IPPROTO_ICMP ||
2343 is_icmp_query(ICMP(ulp))) &&
2344 !(m->m_flags & (M_BCAST|M_MCAST)) &&
2345 !IN_MULTICAST(ntohl(dst_ip.s_addr))) {
2346 send_reject(args, cmd->arg1, iplen, ip);
2352 if (hlen > 0 && is_ipv6 &&
2353 ((offset & IP6F_OFF_MASK) == 0) &&
2354 (proto != IPPROTO_ICMPV6 ||
2355 (is_icmp6_query(icmp6_type) == 1)) &&
2356 !(m->m_flags & (M_BCAST|M_MCAST)) &&
2357 !IN6_IS_ADDR_MULTICAST(&args->f_id.dst_ip6)) {
2359 args, cmd->arg1, hlen,
2360 (struct ip6_hdr *)ip);
2366 retval = IP_FW_DENY;
2367 l = 0; /* exit inner loop */
2368 done = 1; /* exit outer loop */
2372 if (args->eh) /* not valid on layer2 pkts */
2374 if (q == NULL || q->rule != f ||
2375 dyn_dir == MATCH_FORWARD) {
2376 struct sockaddr_in *sa;
2377 sa = &(((ipfw_insn_sa *)cmd)->sa);
2378 if (sa->sin_addr.s_addr == INADDR_ANY) {
2379 bcopy(sa, &args->hopstore,
2381 args->hopstore.sin_addr.s_addr =
2383 args->next_hop = &args->hopstore;
2385 args->next_hop = sa;
2388 retval = IP_FW_PASS;
2389 l = 0; /* exit inner loop */
2390 done = 1; /* exit outer loop */
2395 if (args->eh) /* not valid on layer2 pkts */
2397 if (q == NULL || q->rule != f ||
2398 dyn_dir == MATCH_FORWARD) {
2399 struct sockaddr_in6 *sin6;
2401 sin6 = &(((ipfw_insn_sa6 *)cmd)->sa);
2402 args->next_hop6 = sin6;
2404 retval = IP_FW_PASS;
2405 l = 0; /* exit inner loop */
2406 done = 1; /* exit outer loop */
2412 set_match(args, f_pos, chain);
2413 args->rule.info = TARG(cmd->arg1, netgraph);
2415 args->rule.info |= IPFW_ONEPASS;
2416 retval = (cmd->opcode == O_NETGRAPH) ?
2417 IP_FW_NETGRAPH : IP_FW_NGTEE;
2418 l = 0; /* exit inner loop */
2419 done = 1; /* exit outer loop */
2425 IPFW_INC_RULE_COUNTER(f, pktlen);
2426 fib = TARG(cmd->arg1, fib) & 0x7FFFF;
2427 if (fib >= rt_numfibs)
2430 args->f_id.fib = fib;
2431 l = 0; /* exit inner loop */
2438 code = TARG(cmd->arg1, dscp) & 0x3F;
2439 l = 0; /* exit inner loop */
2444 ip->ip_tos = (code << 2) | (ip->ip_tos & 0x03);
2445 a += ntohs(ip->ip_sum) - ip->ip_tos;
2446 ip->ip_sum = htons(a);
2447 } else if (is_ipv6) {
2450 v = &((struct ip6_hdr *)ip)->ip6_vfc;
2451 *v = (*v & 0xF0) | (code >> 2);
2453 *v = (*v & 0x3F) | ((code & 0x03) << 6);
2457 IPFW_INC_RULE_COUNTER(f, pktlen);
2462 l = 0; /* exit inner loop */
2463 done = 1; /* exit outer loop */
2464 if (!IPFW_NAT_LOADED) {
2465 retval = IP_FW_DENY;
2472 set_match(args, f_pos, chain);
2473 /* Check if this is 'global' nat rule */
2474 if (cmd->arg1 == 0) {
2475 retval = ipfw_nat_ptr(args, NULL, m);
2478 t = ((ipfw_insn_nat *)cmd)->nat;
2480 nat_id = TARG(cmd->arg1, nat);
2481 t = (*lookup_nat_ptr)(&chain->nat, nat_id);
2484 retval = IP_FW_DENY;
2487 if (cmd->arg1 != IP_FW_TARG)
2488 ((ipfw_insn_nat *)cmd)->nat = t;
2490 retval = ipfw_nat_ptr(args, t, m);
2496 IPFW_INC_RULE_COUNTER(f, pktlen);
2497 l = 0; /* in any case exit inner loop */
2498 ip_off = ntohs(ip->ip_off);
2500 /* if not fragmented, go to next rule */
2501 if ((ip_off & (IP_MF | IP_OFFMASK)) == 0)
2504 args->m = m = ip_reass(m);
2507 * do IP header checksum fixup.
2509 if (m == NULL) { /* fragment got swallowed */
2510 retval = IP_FW_DENY;
2511 } else { /* good, packet complete */
2514 ip = mtod(m, struct ip *);
2515 hlen = ip->ip_hl << 2;
2517 if (hlen == sizeof(struct ip))
2518 ip->ip_sum = in_cksum_hdr(ip);
2520 ip->ip_sum = in_cksum(m, hlen);
2521 retval = IP_FW_REASS;
2522 set_match(args, f_pos, chain);
2524 done = 1; /* exit outer loop */
2529 panic("-- unknown opcode %d\n", cmd->opcode);
2530 } /* end of switch() on opcodes */
2532 * if we get here with l=0, then match is irrelevant.
2535 if (cmd->len & F_NOT)
2539 if (cmd->len & F_OR)
2542 if (!(cmd->len & F_OR)) /* not an OR block, */
2543 break; /* try next rule */
2546 } /* end of inner loop, scan opcodes */
2552 /* next_rule:; */ /* try next rule */
2554 } /* end of outer for, scan rules */
2557 struct ip_fw *rule = chain->map[f_pos];
2558 /* Update statistics */
2559 IPFW_INC_RULE_COUNTER(rule, pktlen);
2561 retval = IP_FW_DENY;
2562 printf("ipfw: ouch!, skip past end of rules, denying packet\n");
2564 IPFW_PF_RUNLOCK(chain);
2566 if (ucred_cache != NULL)
2567 crfree(ucred_cache);
2573 printf("ipfw: pullup failed\n");
2574 return (IP_FW_DENY);
2578 * Set maximum number of tables that can be used in given VNET ipfw instance.
2582 sysctl_ipfw_table_num(SYSCTL_HANDLER_ARGS)
2585 unsigned int ntables;
2587 ntables = V_fw_tables_max;
2589 error = sysctl_handle_int(oidp, &ntables, 0, req);
2590 /* Read operation or some error */
2591 if ((error != 0) || (req->newptr == NULL))
2594 return (ipfw_resize_tables(&V_layer3_chain, ntables));
2598 * Switches table namespace between global and per-set.
2601 sysctl_ipfw_tables_sets(SYSCTL_HANDLER_ARGS)
2606 sets = V_fw_tables_sets;
2608 error = sysctl_handle_int(oidp, &sets, 0, req);
2609 /* Read operation or some error */
2610 if ((error != 0) || (req->newptr == NULL))
2613 return (ipfw_switch_tables_namespace(&V_layer3_chain, sets));
2618 * Module and VNET glue
2622 * Stuff that must be initialised only on boot or module load
2630 * Only print out this stuff the first time around,
2631 * when called from the sysinit code.
2637 "initialized, divert %s, nat %s, "
2638 "default to %s, logging ",
2644 #ifdef IPFIREWALL_NAT
2649 default_to_accept ? "accept" : "deny");
2652 * Note: V_xxx variables can be accessed here but the vnet specific
2653 * initializer may not have been called yet for the VIMAGE case.
2654 * Tuneables will have been processed. We will print out values for
2656 * XXX This should all be rationalized AFTER 8.0
2658 if (V_fw_verbose == 0)
2659 printf("disabled\n");
2660 else if (V_verbose_limit == 0)
2661 printf("unlimited\n");
2663 printf("limited to %d packets/entry by default\n",
2666 /* Check user-supplied table count for validness */
2667 if (default_fw_tables > IPFW_TABLES_MAX)
2668 default_fw_tables = IPFW_TABLES_MAX;
2670 ipfw_init_sopt_handler();
2671 ipfw_log_bpf(1); /* init */
2677 * Called for the removal of the last instance only on module unload.
2683 ipfw_iface_destroy();
2684 ipfw_log_bpf(0); /* uninit */
2685 ipfw_destroy_sopt_handler();
2686 printf("IP firewall unloaded\n");
2690 * Stuff that must be initialized for every instance
2691 * (including the first of course).
2694 vnet_ipfw_init(const void *unused)
2697 struct ip_fw *rule = NULL;
2698 struct ip_fw_chain *chain;
2700 chain = &V_layer3_chain;
2702 first = IS_DEFAULT_VNET(curvnet) ? 1 : 0;
2704 /* First set up some values that are compile time options */
2705 V_autoinc_step = 100; /* bounded to 1..1000 in add_rule() */
2706 V_fw_deny_unknown_exthdrs = 1;
2707 #ifdef IPFIREWALL_VERBOSE
2710 #ifdef IPFIREWALL_VERBOSE_LIMIT
2711 V_verbose_limit = IPFIREWALL_VERBOSE_LIMIT;
2713 #ifdef IPFIREWALL_NAT
2714 LIST_INIT(&chain->nat);
2717 ipfw_init_counters();
2718 /* insert the default rule and create the initial map */
2720 chain->map = malloc(sizeof(struct ip_fw *), M_IPFW, M_WAITOK | M_ZERO);
2721 rule = ipfw_alloc_rule(chain, sizeof(struct ip_fw));
2723 /* Set initial number of tables */
2724 V_fw_tables_max = default_fw_tables;
2725 error = ipfw_init_tables(chain, first);
2727 printf("ipfw2: setting up tables failed\n");
2728 free(chain->map, M_IPFW);
2733 /* fill and insert the default rule */
2735 rule->rulenum = IPFW_DEFAULT_RULE;
2737 rule->set = RESVD_SET;
2738 rule->cmd[0].len = 1;
2739 rule->cmd[0].opcode = default_to_accept ? O_ACCEPT : O_DENY;
2740 chain->default_rule = chain->map[0] = rule;
2741 chain->id = rule->id = 1;
2742 /* Pre-calculate rules length for legacy dump format */
2743 chain->static_len = sizeof(struct ip_fw_rule0);
2745 IPFW_LOCK_INIT(chain);
2746 ipfw_dyn_init(chain);
2747 ipfw_init_skipto_cache(chain);
2749 /* First set up some values that are compile time options */
2750 V_ipfw_vnet_ready = 1; /* Open for business */
2753 * Hook the sockopt handler and pfil hooks for ipv4 and ipv6.
2754 * Even if the latter two fail we still keep the module alive
2755 * because the sockopt and layer2 paths are still useful.
2756 * ipfw[6]_hook return 0 on success, ENOENT on failure,
2757 * so we can ignore the exact return value and just set a flag.
2759 * Note that V_fw[6]_enable are manipulated by a SYSCTL_PROC so
2760 * changes in the underlying (per-vnet) variables trigger
2761 * immediate hook()/unhook() calls.
2762 * In layer2 we have the same behaviour, except that V_ether_ipfw
2763 * is checked on each packet because there are no pfil hooks.
2765 V_ip_fw_ctl_ptr = ipfw_ctl3;
2766 error = ipfw_attach_hooks(1);
2771 * Called for the removal of each instance.
2774 vnet_ipfw_uninit(const void *unused)
2777 struct ip_fw_chain *chain = &V_layer3_chain;
2780 V_ipfw_vnet_ready = 0; /* tell new callers to go away */
2782 * disconnect from ipv4, ipv6, layer2 and sockopt.
2783 * Then grab, release and grab again the WLOCK so we make
2784 * sure the update is propagated and nobody will be in.
2786 (void)ipfw_attach_hooks(0 /* detach */);
2787 V_ip_fw_ctl_ptr = NULL;
2789 last = IS_DEFAULT_VNET(curvnet) ? 1 : 0;
2791 IPFW_UH_WLOCK(chain);
2792 IPFW_UH_WUNLOCK(chain);
2793 IPFW_UH_WLOCK(chain);
2796 ipfw_dyn_uninit(0); /* run the callout_drain */
2797 IPFW_WUNLOCK(chain);
2801 for (i = 0; i < chain->n_rules; i++)
2802 ipfw_reap_add(chain, &reap, chain->map[i]);
2803 free(chain->map, M_IPFW);
2804 ipfw_destroy_skipto_cache(chain);
2805 IPFW_WUNLOCK(chain);
2806 IPFW_UH_WUNLOCK(chain);
2807 ipfw_destroy_tables(chain, last);
2809 ipfw_reap_rules(reap);
2810 vnet_ipfw_iface_destroy(chain);
2811 IPFW_LOCK_DESTROY(chain);
2812 ipfw_dyn_uninit(1); /* free the remaining parts */
2813 ipfw_destroy_counters();
2818 * Module event handler.
2819 * In general we have the choice of handling most of these events by the
2820 * event handler or by the (VNET_)SYS(UN)INIT handlers. I have chosen to
2821 * use the SYSINIT handlers as they are more capable of expressing the
2822 * flow of control during module and vnet operations, so this is just
2823 * a skeleton. Note there is no SYSINIT equivalent of the module
2824 * SHUTDOWN handler, but we don't have anything to do in that case anyhow.
2827 ipfw_modevent(module_t mod, int type, void *unused)
2833 /* Called once at module load or
2834 * system boot if compiled in. */
2837 /* Called before unload. May veto unloading. */
2840 /* Called during unload. */
2843 /* Called during system shutdown. */
2852 static moduledata_t ipfwmod = {
2858 /* Define startup order. */
2859 #define IPFW_SI_SUB_FIREWALL SI_SUB_PROTO_IFATTACHDOMAIN
2860 #define IPFW_MODEVENT_ORDER (SI_ORDER_ANY - 255) /* On boot slot in here. */
2861 #define IPFW_MODULE_ORDER (IPFW_MODEVENT_ORDER + 1) /* A little later. */
2862 #define IPFW_VNET_ORDER (IPFW_MODEVENT_ORDER + 2) /* Later still. */
2864 DECLARE_MODULE(ipfw, ipfwmod, IPFW_SI_SUB_FIREWALL, IPFW_MODEVENT_ORDER);
2865 MODULE_VERSION(ipfw, 2);
2866 /* should declare some dependencies here */
2869 * Starting up. Done in order after ipfwmod() has been called.
2870 * VNET_SYSINIT is also called for each existing vnet and each new vnet.
2872 SYSINIT(ipfw_init, IPFW_SI_SUB_FIREWALL, IPFW_MODULE_ORDER,
2874 VNET_SYSINIT(vnet_ipfw_init, IPFW_SI_SUB_FIREWALL, IPFW_VNET_ORDER,
2875 vnet_ipfw_init, NULL);
2878 * Closing up shop. These are done in REVERSE ORDER, but still
2879 * after ipfwmod() has been called. Not called on reboot.
2880 * VNET_SYSUNINIT is also called for each exiting vnet as it exits.
2881 * or when the module is unloaded.
2883 SYSUNINIT(ipfw_destroy, IPFW_SI_SUB_FIREWALL, IPFW_MODULE_ORDER,
2884 ipfw_destroy, NULL);
2885 VNET_SYSUNINIT(vnet_ipfw_uninit, IPFW_SI_SUB_FIREWALL, IPFW_VNET_ORDER,
2886 vnet_ipfw_uninit, NULL);