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/rmlock.h>
57 #include <sys/socket.h>
58 #include <sys/socketvar.h>
59 #include <sys/sysctl.h>
60 #include <sys/syslog.h>
61 #include <sys/ucred.h>
62 #include <net/ethernet.h> /* for ETHERTYPE_IP */
64 #include <net/if_var.h>
65 #include <net/route.h>
69 #include <netpfil/pf/pf_mtag.h>
71 #include <netinet/in.h>
72 #include <netinet/in_var.h>
73 #include <netinet/in_pcb.h>
74 #include <netinet/ip.h>
75 #include <netinet/ip_var.h>
76 #include <netinet/ip_icmp.h>
77 #include <netinet/ip_fw.h>
78 #include <netinet/ip_carp.h>
79 #include <netinet/pim.h>
80 #include <netinet/tcp_var.h>
81 #include <netinet/udp.h>
82 #include <netinet/udp_var.h>
83 #include <netinet/sctp.h>
85 #include <netinet/ip6.h>
86 #include <netinet/icmp6.h>
88 #include <netinet6/in6_pcb.h>
89 #include <netinet6/scope6_var.h>
90 #include <netinet6/ip6_var.h>
93 #include <netpfil/ipfw/ip_fw_private.h>
95 #include <machine/in_cksum.h> /* XXX for in_cksum */
98 #include <security/mac/mac_framework.h>
102 * static variables followed by global ones.
103 * All ipfw global variables are here.
106 static VNET_DEFINE(int, fw_deny_unknown_exthdrs);
107 #define V_fw_deny_unknown_exthdrs VNET(fw_deny_unknown_exthdrs)
109 static VNET_DEFINE(int, fw_permit_single_frag6) = 1;
110 #define V_fw_permit_single_frag6 VNET(fw_permit_single_frag6)
112 #ifdef IPFIREWALL_DEFAULT_TO_ACCEPT
113 static int default_to_accept = 1;
115 static int default_to_accept;
118 VNET_DEFINE(int, autoinc_step);
119 VNET_DEFINE(int, fw_one_pass) = 1;
121 VNET_DEFINE(unsigned int, fw_tables_max);
122 VNET_DEFINE(unsigned int, fw_tables_sets) = 0; /* Don't use set-aware tables */
123 /* Use 128 tables by default */
124 static unsigned int default_fw_tables = IPFW_TABLES_DEFAULT;
126 #ifndef LINEAR_SKIPTO
127 static int jump_fast(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)
131 static int jump_linear(struct ip_fw_chain *chain, struct ip_fw *f, int num,
132 int tablearg, int jump_backwards);
133 #define JUMP(ch, f, num, targ, back) jump_linear(ch, f, num, targ, back)
137 * Each rule belongs to one of 32 different sets (0..31).
138 * The variable set_disable contains one bit per set.
139 * If the bit is set, all rules in the corresponding set
140 * are disabled. Set RESVD_SET(31) is reserved for the default rule
141 * and rules that are not deleted by the flush command,
142 * and CANNOT be disabled.
143 * Rules in set RESVD_SET can only be deleted individually.
145 VNET_DEFINE(u_int32_t, set_disable);
146 #define V_set_disable VNET(set_disable)
148 VNET_DEFINE(int, fw_verbose);
149 /* counter for ipfw_log(NULL...) */
150 VNET_DEFINE(u_int64_t, norule_counter);
151 VNET_DEFINE(int, verbose_limit);
153 /* layer3_chain contains the list of rules for layer 3 */
154 VNET_DEFINE(struct ip_fw_chain, layer3_chain);
156 /* ipfw_vnet_ready controls when we are open for business */
157 VNET_DEFINE(int, ipfw_vnet_ready) = 0;
159 VNET_DEFINE(int, ipfw_nat_ready) = 0;
161 ipfw_nat_t *ipfw_nat_ptr = NULL;
162 struct cfg_nat *(*lookup_nat_ptr)(struct nat_list *, int);
163 ipfw_nat_cfg_t *ipfw_nat_cfg_ptr;
164 ipfw_nat_cfg_t *ipfw_nat_del_ptr;
165 ipfw_nat_cfg_t *ipfw_nat_get_cfg_ptr;
166 ipfw_nat_cfg_t *ipfw_nat_get_log_ptr;
169 uint32_t dummy_def = IPFW_DEFAULT_RULE;
170 static int sysctl_ipfw_table_num(SYSCTL_HANDLER_ARGS);
171 static int sysctl_ipfw_tables_sets(SYSCTL_HANDLER_ARGS);
175 SYSCTL_NODE(_net_inet_ip, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall");
176 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, one_pass,
177 CTLFLAG_VNET | CTLFLAG_RW | CTLFLAG_SECURE3, &VNET_NAME(fw_one_pass), 0,
178 "Only do a single pass through ipfw when using dummynet(4)");
179 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, autoinc_step,
180 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(autoinc_step), 0,
181 "Rule number auto-increment step");
182 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose,
183 CTLFLAG_VNET | CTLFLAG_RW | CTLFLAG_SECURE3, &VNET_NAME(fw_verbose), 0,
184 "Log matches to ipfw rules");
185 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose_limit,
186 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(verbose_limit), 0,
187 "Set upper limit of matches of ipfw rules logged");
188 SYSCTL_UINT(_net_inet_ip_fw, OID_AUTO, default_rule, CTLFLAG_RD,
190 "The default/max possible rule number.");
191 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, tables_max,
192 CTLFLAG_VNET | CTLTYPE_UINT | CTLFLAG_RW, 0, 0, sysctl_ipfw_table_num, "IU",
193 "Maximum number of concurrently used tables");
194 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, tables_sets,
195 CTLFLAG_VNET | CTLTYPE_UINT | CTLFLAG_RW,
196 0, 0, sysctl_ipfw_tables_sets, "IU",
197 "Use per-set namespace for tables");
198 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, default_to_accept, CTLFLAG_RDTUN,
199 &default_to_accept, 0,
200 "Make the default rule accept all packets.");
201 TUNABLE_INT("net.inet.ip.fw.tables_max", (int *)&default_fw_tables);
202 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, static_count,
203 CTLFLAG_VNET | CTLFLAG_RD, &VNET_NAME(layer3_chain.n_rules), 0,
204 "Number of static rules");
207 SYSCTL_DECL(_net_inet6_ip6);
208 SYSCTL_NODE(_net_inet6_ip6, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall");
209 SYSCTL_INT(_net_inet6_ip6_fw, OID_AUTO, deny_unknown_exthdrs,
210 CTLFLAG_VNET | CTLFLAG_RW | CTLFLAG_SECURE,
211 &VNET_NAME(fw_deny_unknown_exthdrs), 0,
212 "Deny packets with unknown IPv6 Extension Headers");
213 SYSCTL_INT(_net_inet6_ip6_fw, OID_AUTO, permit_single_frag6,
214 CTLFLAG_VNET | CTLFLAG_RW | CTLFLAG_SECURE,
215 &VNET_NAME(fw_permit_single_frag6), 0,
216 "Permit single packet IPv6 fragments");
221 #endif /* SYSCTL_NODE */
225 * Some macros used in the various matching options.
226 * L3HDR maps an ipv4 pointer into a layer3 header pointer of type T
227 * Other macros just cast void * into the appropriate type
229 #define L3HDR(T, ip) ((T *)((u_int32_t *)(ip) + (ip)->ip_hl))
230 #define TCP(p) ((struct tcphdr *)(p))
231 #define SCTP(p) ((struct sctphdr *)(p))
232 #define UDP(p) ((struct udphdr *)(p))
233 #define ICMP(p) ((struct icmphdr *)(p))
234 #define ICMP6(p) ((struct icmp6_hdr *)(p))
237 icmptype_match(struct icmphdr *icmp, ipfw_insn_u32 *cmd)
239 int type = icmp->icmp_type;
241 return (type <= ICMP_MAXTYPE && (cmd->d[0] & (1<<type)) );
244 #define TT ( (1 << ICMP_ECHO) | (1 << ICMP_ROUTERSOLICIT) | \
245 (1 << ICMP_TSTAMP) | (1 << ICMP_IREQ) | (1 << ICMP_MASKREQ) )
248 is_icmp_query(struct icmphdr *icmp)
250 int type = icmp->icmp_type;
252 return (type <= ICMP_MAXTYPE && (TT & (1<<type)) );
257 * The following checks use two arrays of 8 or 16 bits to store the
258 * bits that we want set or clear, respectively. They are in the
259 * low and high half of cmd->arg1 or cmd->d[0].
261 * We scan options and store the bits we find set. We succeed if
263 * (want_set & ~bits) == 0 && (want_clear & ~bits) == want_clear
265 * The code is sometimes optimized not to store additional variables.
269 flags_match(ipfw_insn *cmd, u_int8_t bits)
274 if ( ((cmd->arg1 & 0xff) & bits) != 0)
275 return 0; /* some bits we want set were clear */
276 want_clear = (cmd->arg1 >> 8) & 0xff;
277 if ( (want_clear & bits) != want_clear)
278 return 0; /* some bits we want clear were set */
283 ipopts_match(struct ip *ip, ipfw_insn *cmd)
285 int optlen, bits = 0;
286 u_char *cp = (u_char *)(ip + 1);
287 int x = (ip->ip_hl << 2) - sizeof (struct ip);
289 for (; x > 0; x -= optlen, cp += optlen) {
290 int opt = cp[IPOPT_OPTVAL];
292 if (opt == IPOPT_EOL)
294 if (opt == IPOPT_NOP)
297 optlen = cp[IPOPT_OLEN];
298 if (optlen <= 0 || optlen > x)
299 return 0; /* invalid or truncated */
307 bits |= IP_FW_IPOPT_LSRR;
311 bits |= IP_FW_IPOPT_SSRR;
315 bits |= IP_FW_IPOPT_RR;
319 bits |= IP_FW_IPOPT_TS;
323 return (flags_match(cmd, bits));
327 tcpopts_match(struct tcphdr *tcp, ipfw_insn *cmd)
329 int optlen, bits = 0;
330 u_char *cp = (u_char *)(tcp + 1);
331 int x = (tcp->th_off << 2) - sizeof(struct tcphdr);
333 for (; x > 0; x -= optlen, cp += optlen) {
335 if (opt == TCPOPT_EOL)
337 if (opt == TCPOPT_NOP)
351 bits |= IP_FW_TCPOPT_MSS;
355 bits |= IP_FW_TCPOPT_WINDOW;
358 case TCPOPT_SACK_PERMITTED:
360 bits |= IP_FW_TCPOPT_SACK;
363 case TCPOPT_TIMESTAMP:
364 bits |= IP_FW_TCPOPT_TS;
369 return (flags_match(cmd, bits));
373 iface_match(struct ifnet *ifp, ipfw_insn_if *cmd, struct ip_fw_chain *chain,
377 if (ifp == NULL) /* no iface with this packet, match fails */
380 /* Check by name or by IP address */
381 if (cmd->name[0] != '\0') { /* match by name */
382 if (cmd->name[0] == '\1') /* use tablearg to match */
383 return ipfw_lookup_table_extended(chain, cmd->p.kidx, 0,
384 &ifp->if_index, tablearg);
387 if (fnmatch(cmd->name, ifp->if_xname, 0) == 0)
390 if (strncmp(ifp->if_xname, cmd->name, IFNAMSIZ) == 0)
394 #if !defined(USERSPACE) && defined(__FreeBSD__) /* and OSX too ? */
398 TAILQ_FOREACH(ia, &ifp->if_addrhead, ifa_link) {
399 if (ia->ifa_addr->sa_family != AF_INET)
401 if (cmd->p.ip.s_addr == ((struct sockaddr_in *)
402 (ia->ifa_addr))->sin_addr.s_addr) {
403 if_addr_runlock(ifp);
404 return(1); /* match */
407 if_addr_runlock(ifp);
408 #endif /* __FreeBSD__ */
410 return(0); /* no match, fail ... */
414 * The verify_path function checks if a route to the src exists and
415 * if it is reachable via ifp (when provided).
417 * The 'verrevpath' option checks that the interface that an IP packet
418 * arrives on is the same interface that traffic destined for the
419 * packet's source address would be routed out of.
420 * The 'versrcreach' option just checks that the source address is
421 * reachable via any route (except default) in the routing table.
422 * These two are a measure to block forged packets. This is also
423 * commonly known as "anti-spoofing" or Unicast Reverse Path
424 * Forwarding (Unicast RFP) in Cisco-ese. The name of the knobs
425 * is purposely reminiscent of the Cisco IOS command,
427 * ip verify unicast reverse-path
428 * ip verify unicast source reachable-via any
430 * which implements the same functionality. But note that the syntax
431 * is misleading, and the check may be performed on all IP packets
432 * whether unicast, multicast, or broadcast.
435 verify_path(struct in_addr src, struct ifnet *ifp, u_int fib)
437 #if defined(USERSPACE) || !defined(__FreeBSD__)
441 struct sockaddr_in *dst;
443 bzero(&ro, sizeof(ro));
445 dst = (struct sockaddr_in *)&(ro.ro_dst);
446 dst->sin_family = AF_INET;
447 dst->sin_len = sizeof(*dst);
449 in_rtalloc_ign(&ro, 0, fib);
451 if (ro.ro_rt == NULL)
455 * If ifp is provided, check for equality with rtentry.
456 * We should use rt->rt_ifa->ifa_ifp, instead of rt->rt_ifp,
457 * in order to pass packets injected back by if_simloop():
458 * routing entry (via lo0) for our own address
459 * may exist, so we need to handle routing assymetry.
461 if (ifp != NULL && ro.ro_rt->rt_ifa->ifa_ifp != ifp) {
466 /* if no ifp provided, check if rtentry is not default route */
468 satosin(rt_key(ro.ro_rt))->sin_addr.s_addr == INADDR_ANY) {
473 /* or if this is a blackhole/reject route */
474 if (ifp == NULL && ro.ro_rt->rt_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
479 /* found valid route */
482 #endif /* __FreeBSD__ */
487 * ipv6 specific rules here...
490 icmp6type_match (int type, ipfw_insn_u32 *cmd)
492 return (type <= ICMP6_MAXTYPE && (cmd->d[type/32] & (1<<(type%32)) ) );
496 flow6id_match( int curr_flow, ipfw_insn_u32 *cmd )
499 for (i=0; i <= cmd->o.arg1; ++i )
500 if (curr_flow == cmd->d[i] )
505 /* support for IP6_*_ME opcodes */
507 search_ip6_addr_net (struct in6_addr * ip6_addr)
511 struct in6_ifaddr *fdm;
512 struct in6_addr copia;
514 TAILQ_FOREACH(mdc, &V_ifnet, if_link) {
516 TAILQ_FOREACH(mdc2, &mdc->if_addrhead, ifa_link) {
517 if (mdc2->ifa_addr->sa_family == AF_INET6) {
518 fdm = (struct in6_ifaddr *)mdc2;
519 copia = fdm->ia_addr.sin6_addr;
520 /* need for leaving scope_id in the sock_addr */
521 in6_clearscope(&copia);
522 if (IN6_ARE_ADDR_EQUAL(ip6_addr, &copia)) {
523 if_addr_runlock(mdc);
528 if_addr_runlock(mdc);
534 verify_path6(struct in6_addr *src, struct ifnet *ifp, u_int fib)
537 struct sockaddr_in6 *dst;
539 bzero(&ro, sizeof(ro));
541 dst = (struct sockaddr_in6 * )&(ro.ro_dst);
542 dst->sin6_family = AF_INET6;
543 dst->sin6_len = sizeof(*dst);
544 dst->sin6_addr = *src;
546 in6_rtalloc_ign(&ro, 0, fib);
547 if (ro.ro_rt == NULL)
551 * if ifp is provided, check for equality with rtentry
552 * We should use rt->rt_ifa->ifa_ifp, instead of rt->rt_ifp,
553 * to support the case of sending packets to an address of our own.
554 * (where the former interface is the first argument of if_simloop()
555 * (=ifp), the latter is lo0)
557 if (ifp != NULL && ro.ro_rt->rt_ifa->ifa_ifp != ifp) {
562 /* if no ifp provided, check if rtentry is not default route */
564 IN6_IS_ADDR_UNSPECIFIED(&satosin6(rt_key(ro.ro_rt))->sin6_addr)) {
569 /* or if this is a blackhole/reject route */
570 if (ifp == NULL && ro.ro_rt->rt_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
575 /* found valid route */
582 is_icmp6_query(int icmp6_type)
584 if ((icmp6_type <= ICMP6_MAXTYPE) &&
585 (icmp6_type == ICMP6_ECHO_REQUEST ||
586 icmp6_type == ICMP6_MEMBERSHIP_QUERY ||
587 icmp6_type == ICMP6_WRUREQUEST ||
588 icmp6_type == ICMP6_FQDN_QUERY ||
589 icmp6_type == ICMP6_NI_QUERY))
596 send_reject6(struct ip_fw_args *args, int code, u_int hlen, struct ip6_hdr *ip6)
601 if (code == ICMP6_UNREACH_RST && args->f_id.proto == IPPROTO_TCP) {
603 tcp = (struct tcphdr *)((char *)ip6 + hlen);
605 if ((tcp->th_flags & TH_RST) == 0) {
607 m0 = ipfw_send_pkt(args->m, &(args->f_id),
608 ntohl(tcp->th_seq), ntohl(tcp->th_ack),
609 tcp->th_flags | TH_RST);
611 ip6_output(m0, NULL, NULL, 0, NULL, NULL,
615 } else if (code != ICMP6_UNREACH_RST) { /* Send an ICMPv6 unreach. */
618 * Unlike above, the mbufs need to line up with the ip6 hdr,
619 * as the contents are read. We need to m_adj() the
621 * The mbuf will however be thrown away so we can adjust it.
622 * Remember we did an m_pullup on it already so we
623 * can make some assumptions about contiguousness.
626 m_adj(m, args->L3offset);
628 icmp6_error(m, ICMP6_DST_UNREACH, code, 0);
639 * sends a reject message, consuming the mbuf passed as an argument.
642 send_reject(struct ip_fw_args *args, int code, int iplen, struct ip *ip)
646 /* XXX When ip is not guaranteed to be at mtod() we will
647 * need to account for this */
648 * The mbuf will however be thrown away so we can adjust it.
649 * Remember we did an m_pullup on it already so we
650 * can make some assumptions about contiguousness.
653 m_adj(m, args->L3offset);
655 if (code != ICMP_REJECT_RST) { /* Send an ICMP unreach */
656 icmp_error(args->m, ICMP_UNREACH, code, 0L, 0);
657 } else if (args->f_id.proto == IPPROTO_TCP) {
658 struct tcphdr *const tcp =
659 L3HDR(struct tcphdr, mtod(args->m, struct ip *));
660 if ( (tcp->th_flags & TH_RST) == 0) {
662 m = ipfw_send_pkt(args->m, &(args->f_id),
663 ntohl(tcp->th_seq), ntohl(tcp->th_ack),
664 tcp->th_flags | TH_RST);
666 ip_output(m, NULL, NULL, 0, NULL, NULL);
675 * Support for uid/gid/jail lookup. These tests are expensive
676 * (because we may need to look into the list of active sockets)
677 * so we cache the results. ugid_lookupp is 0 if we have not
678 * yet done a lookup, 1 if we succeeded, and -1 if we tried
679 * and failed. The function always returns the match value.
680 * We could actually spare the variable and use *uc, setting
681 * it to '(void *)check_uidgid if we have no info, NULL if
682 * we tried and failed, or any other value if successful.
685 check_uidgid(ipfw_insn_u32 *insn, struct ip_fw_args *args, int *ugid_lookupp,
688 #if defined(USERSPACE)
689 return 0; // not supported in userspace
693 return cred_check(insn, proto, oif,
694 dst_ip, dst_port, src_ip, src_port,
695 (struct bsd_ucred *)uc, ugid_lookupp, ((struct mbuf *)inp)->m_skb);
697 struct in_addr src_ip, dst_ip;
698 struct inpcbinfo *pi;
699 struct ipfw_flow_id *id;
700 struct inpcb *pcb, *inp;
710 * Check to see if the UDP or TCP stack supplied us with
711 * the PCB. If so, rather then holding a lock and looking
712 * up the PCB, we can use the one that was supplied.
714 if (inp && *ugid_lookupp == 0) {
715 INP_LOCK_ASSERT(inp);
716 if (inp->inp_socket != NULL) {
717 *uc = crhold(inp->inp_cred);
723 * If we have already been here and the packet has no
724 * PCB entry associated with it, then we can safely
725 * assume that this is a no match.
727 if (*ugid_lookupp == -1)
729 if (id->proto == IPPROTO_TCP) {
732 } else if (id->proto == IPPROTO_UDP) {
733 lookupflags = INPLOOKUP_WILDCARD;
737 lookupflags |= INPLOOKUP_RLOCKPCB;
739 if (*ugid_lookupp == 0) {
740 if (id->addr_type == 6) {
743 pcb = in6_pcblookup_mbuf(pi,
744 &id->src_ip6, htons(id->src_port),
745 &id->dst_ip6, htons(id->dst_port),
746 lookupflags, oif, args->m);
748 pcb = in6_pcblookup_mbuf(pi,
749 &id->dst_ip6, htons(id->dst_port),
750 &id->src_ip6, htons(id->src_port),
751 lookupflags, oif, args->m);
757 src_ip.s_addr = htonl(id->src_ip);
758 dst_ip.s_addr = htonl(id->dst_ip);
760 pcb = in_pcblookup_mbuf(pi,
761 src_ip, htons(id->src_port),
762 dst_ip, htons(id->dst_port),
763 lookupflags, oif, args->m);
765 pcb = in_pcblookup_mbuf(pi,
766 dst_ip, htons(id->dst_port),
767 src_ip, htons(id->src_port),
768 lookupflags, oif, args->m);
771 INP_RLOCK_ASSERT(pcb);
772 *uc = crhold(pcb->inp_cred);
776 if (*ugid_lookupp == 0) {
778 * We tried and failed, set the variable to -1
779 * so we will not try again on this packet.
785 if (insn->o.opcode == O_UID)
786 match = ((*uc)->cr_uid == (uid_t)insn->d[0]);
787 else if (insn->o.opcode == O_GID)
788 match = groupmember((gid_t)insn->d[0], *uc);
789 else if (insn->o.opcode == O_JAIL)
790 match = ((*uc)->cr_prison->pr_id == (int)insn->d[0]);
792 #endif /* __FreeBSD__ */
793 #endif /* not supported in userspace */
797 * Helper function to set args with info on the rule after the matching
798 * one. slot is precise, whereas we guess rule_id as they are
799 * assigned sequentially.
802 set_match(struct ip_fw_args *args, int slot,
803 struct ip_fw_chain *chain)
805 args->rule.chain_id = chain->id;
806 args->rule.slot = slot + 1; /* we use 0 as a marker */
807 args->rule.rule_id = 1 + chain->map[slot]->id;
808 args->rule.rulenum = chain->map[slot]->rulenum;
811 #ifndef LINEAR_SKIPTO
813 * Helper function to enable cached rule lookups using
814 * cached_id and cached_pos fields in ipfw rule.
817 jump_fast(struct ip_fw_chain *chain, struct ip_fw *f, int num,
818 int tablearg, int jump_backwards)
822 /* If possible use cached f_pos (in f->cached_pos),
823 * whose version is written in f->cached_id
824 * (horrible hacks to avoid changing the ABI).
826 if (num != IP_FW_TARG && f->cached_id == chain->id)
827 f_pos = f->cached_pos;
829 int i = IP_FW_ARG_TABLEARG(chain, num, skipto);
830 /* make sure we do not jump backward */
831 if (jump_backwards == 0 && i <= f->rulenum)
833 if (chain->idxmap != NULL)
834 f_pos = chain->idxmap[i];
836 f_pos = ipfw_find_rule(chain, i, 0);
837 /* update the cache */
838 if (num != IP_FW_TARG) {
839 f->cached_id = chain->id;
840 f->cached_pos = f_pos;
848 * Helper function to enable real fast rule lookups.
851 jump_linear(struct ip_fw_chain *chain, struct ip_fw *f, int num,
852 int tablearg, int jump_backwards)
856 num = IP_FW_ARG_TABLEARG(chain, num, skipto);
857 /* make sure we do not jump backward */
858 if (jump_backwards == 0 && num <= f->rulenum)
859 num = f->rulenum + 1;
860 f_pos = chain->idxmap[num];
866 #define TARG(k, f) IP_FW_ARG_TABLEARG(chain, k, f)
868 * The main check routine for the firewall.
870 * All arguments are in args so we can modify them and return them
871 * back to the caller.
875 * args->m (in/out) The packet; we set to NULL when/if we nuke it.
876 * Starts with the IP header.
877 * args->eh (in) Mac header if present, NULL for layer3 packet.
878 * args->L3offset Number of bytes bypassed if we came from L2.
879 * e.g. often sizeof(eh) ** NOTYET **
880 * args->oif Outgoing interface, NULL if packet is incoming.
881 * The incoming interface is in the mbuf. (in)
882 * args->divert_rule (in/out)
883 * Skip up to the first rule past this rule number;
884 * upon return, non-zero port number for divert or tee.
886 * args->rule Pointer to the last matching rule (in/out)
887 * args->next_hop Socket we are forwarding to (out).
888 * args->next_hop6 IPv6 next hop we are forwarding to (out).
889 * args->f_id Addresses grabbed from the packet (out)
890 * args->rule.info a cookie depending on rule action
894 * IP_FW_PASS the packet must be accepted
895 * IP_FW_DENY the packet must be dropped
896 * IP_FW_DIVERT divert packet, port in m_tag
897 * IP_FW_TEE tee packet, port in m_tag
898 * IP_FW_DUMMYNET to dummynet, pipe in args->cookie
899 * IP_FW_NETGRAPH into netgraph, cookie args->cookie
900 * args->rule contains the matching rule,
901 * args->rule.info has additional information.
905 ipfw_chk(struct ip_fw_args *args)
909 * Local variables holding state while processing a packet:
911 * IMPORTANT NOTE: to speed up the processing of rules, there
912 * are some assumption on the values of the variables, which
913 * are documented here. Should you change them, please check
914 * the implementation of the various instructions to make sure
915 * that they still work.
917 * args->eh The MAC header. It is non-null for a layer2
918 * packet, it is NULL for a layer-3 packet.
920 * args->L3offset Offset in the packet to the L3 (IP or equiv.) header.
922 * m | args->m Pointer to the mbuf, as received from the caller.
923 * It may change if ipfw_chk() does an m_pullup, or if it
924 * consumes the packet because it calls send_reject().
925 * XXX This has to change, so that ipfw_chk() never modifies
926 * or consumes the buffer.
927 * ip is the beginning of the ip(4 or 6) header.
928 * Calculated by adding the L3offset to the start of data.
929 * (Until we start using L3offset, the packet is
930 * supposed to start with the ip header).
932 struct mbuf *m = args->m;
933 struct ip *ip = mtod(m, struct ip *);
936 * For rules which contain uid/gid or jail constraints, cache
937 * a copy of the users credentials after the pcb lookup has been
938 * executed. This will speed up the processing of rules with
939 * these types of constraints, as well as decrease contention
940 * on pcb related locks.
943 struct bsd_ucred ucred_cache;
945 struct ucred *ucred_cache = NULL;
947 int ucred_lookup = 0;
950 * oif | args->oif If NULL, ipfw_chk has been called on the
951 * inbound path (ether_input, ip_input).
952 * If non-NULL, ipfw_chk has been called on the outbound path
953 * (ether_output, ip_output).
955 struct ifnet *oif = args->oif;
957 int f_pos = 0; /* index of current rule in the array */
961 * hlen The length of the IP header.
963 u_int hlen = 0; /* hlen >0 means we have an IP pkt */
966 * offset The offset of a fragment. offset != 0 means that
967 * we have a fragment at this offset of an IPv4 packet.
968 * offset == 0 means that (if this is an IPv4 packet)
969 * this is the first or only fragment.
970 * For IPv6 offset|ip6f_mf == 0 means there is no Fragment Header
971 * or there is a single packet fragement (fragement header added
972 * without needed). We will treat a single packet fragment as if
973 * there was no fragment header (or log/block depending on the
974 * V_fw_permit_single_frag6 sysctl setting).
980 * Local copies of addresses. They are only valid if we have
983 * proto The protocol. Set to 0 for non-ip packets,
984 * or to the protocol read from the packet otherwise.
985 * proto != 0 means that we have an IPv4 packet.
987 * src_port, dst_port port numbers, in HOST format. Only
988 * valid for TCP and UDP packets.
990 * src_ip, dst_ip ip addresses, in NETWORK format.
991 * Only valid for IPv4 packets.
994 uint16_t src_port = 0, dst_port = 0; /* NOTE: host format */
995 struct in_addr src_ip, dst_ip; /* NOTE: network format */
998 uint16_t etype = 0; /* Host order stored ether type */
1001 * dyn_dir = MATCH_UNKNOWN when rules unchecked,
1002 * MATCH_NONE when checked and not matched (q = NULL),
1003 * MATCH_FORWARD or MATCH_REVERSE otherwise (q != NULL)
1005 int dyn_dir = MATCH_UNKNOWN;
1006 ipfw_dyn_rule *q = NULL;
1007 struct ip_fw_chain *chain = &V_layer3_chain;
1010 * We store in ulp a pointer to the upper layer protocol header.
1011 * In the ipv4 case this is easy to determine from the header,
1012 * but for ipv6 we might have some additional headers in the middle.
1013 * ulp is NULL if not found.
1015 void *ulp = NULL; /* upper layer protocol pointer. */
1017 /* XXX ipv6 variables */
1019 uint8_t icmp6_type = 0;
1020 uint16_t ext_hd = 0; /* bits vector for extension header filtering */
1021 /* end of ipv6 variables */
1025 int done = 0; /* flag to exit the outer loop */
1028 if (m->m_flags & M_SKIP_FIREWALL || (! V_ipfw_vnet_ready))
1029 return (IP_FW_PASS); /* accept */
1031 dst_ip.s_addr = 0; /* make sure it is initialized */
1032 src_ip.s_addr = 0; /* make sure it is initialized */
1033 pktlen = m->m_pkthdr.len;
1034 args->f_id.fib = M_GETFIB(m); /* note mbuf not altered) */
1035 proto = args->f_id.proto = 0; /* mark f_id invalid */
1036 /* XXX 0 is a valid proto: IP/IPv6 Hop-by-Hop Option */
1039 * PULLUP_TO(len, p, T) makes sure that len + sizeof(T) is contiguous,
1040 * then it sets p to point at the offset "len" in the mbuf. WARNING: the
1041 * pointer might become stale after other pullups (but we never use it
1044 #define PULLUP_TO(_len, p, T) PULLUP_LEN(_len, p, sizeof(T))
1045 #define PULLUP_LEN(_len, p, T) \
1047 int x = (_len) + T; \
1048 if ((m)->m_len < x) { \
1049 args->m = m = m_pullup(m, x); \
1051 goto pullup_failed; \
1053 p = (mtod(m, char *) + (_len)); \
1057 * if we have an ether header,
1060 etype = ntohs(args->eh->ether_type);
1062 /* Identify IP packets and fill up variables. */
1063 if (pktlen >= sizeof(struct ip6_hdr) &&
1064 (args->eh == NULL || etype == ETHERTYPE_IPV6) && ip->ip_v == 6) {
1065 struct ip6_hdr *ip6 = (struct ip6_hdr *)ip;
1067 args->f_id.addr_type = 6;
1068 hlen = sizeof(struct ip6_hdr);
1069 proto = ip6->ip6_nxt;
1071 /* Search extension headers to find upper layer protocols */
1072 while (ulp == NULL && offset == 0) {
1074 case IPPROTO_ICMPV6:
1075 PULLUP_TO(hlen, ulp, struct icmp6_hdr);
1076 icmp6_type = ICMP6(ulp)->icmp6_type;
1080 PULLUP_TO(hlen, ulp, struct tcphdr);
1081 dst_port = TCP(ulp)->th_dport;
1082 src_port = TCP(ulp)->th_sport;
1083 /* save flags for dynamic rules */
1084 args->f_id._flags = TCP(ulp)->th_flags;
1088 PULLUP_TO(hlen, ulp, struct sctphdr);
1089 src_port = SCTP(ulp)->src_port;
1090 dst_port = SCTP(ulp)->dest_port;
1094 PULLUP_TO(hlen, ulp, struct udphdr);
1095 dst_port = UDP(ulp)->uh_dport;
1096 src_port = UDP(ulp)->uh_sport;
1099 case IPPROTO_HOPOPTS: /* RFC 2460 */
1100 PULLUP_TO(hlen, ulp, struct ip6_hbh);
1101 ext_hd |= EXT_HOPOPTS;
1102 hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3;
1103 proto = ((struct ip6_hbh *)ulp)->ip6h_nxt;
1107 case IPPROTO_ROUTING: /* RFC 2460 */
1108 PULLUP_TO(hlen, ulp, struct ip6_rthdr);
1109 switch (((struct ip6_rthdr *)ulp)->ip6r_type) {
1111 ext_hd |= EXT_RTHDR0;
1114 ext_hd |= EXT_RTHDR2;
1118 printf("IPFW2: IPV6 - Unknown "
1119 "Routing Header type(%d)\n",
1120 ((struct ip6_rthdr *)
1122 if (V_fw_deny_unknown_exthdrs)
1123 return (IP_FW_DENY);
1126 ext_hd |= EXT_ROUTING;
1127 hlen += (((struct ip6_rthdr *)ulp)->ip6r_len + 1) << 3;
1128 proto = ((struct ip6_rthdr *)ulp)->ip6r_nxt;
1132 case IPPROTO_FRAGMENT: /* RFC 2460 */
1133 PULLUP_TO(hlen, ulp, struct ip6_frag);
1134 ext_hd |= EXT_FRAGMENT;
1135 hlen += sizeof (struct ip6_frag);
1136 proto = ((struct ip6_frag *)ulp)->ip6f_nxt;
1137 offset = ((struct ip6_frag *)ulp)->ip6f_offlg &
1139 ip6f_mf = ((struct ip6_frag *)ulp)->ip6f_offlg &
1141 if (V_fw_permit_single_frag6 == 0 &&
1142 offset == 0 && ip6f_mf == 0) {
1144 printf("IPFW2: IPV6 - Invalid "
1145 "Fragment Header\n");
1146 if (V_fw_deny_unknown_exthdrs)
1147 return (IP_FW_DENY);
1151 ntohl(((struct ip6_frag *)ulp)->ip6f_ident);
1155 case IPPROTO_DSTOPTS: /* RFC 2460 */
1156 PULLUP_TO(hlen, ulp, struct ip6_hbh);
1157 ext_hd |= EXT_DSTOPTS;
1158 hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3;
1159 proto = ((struct ip6_hbh *)ulp)->ip6h_nxt;
1163 case IPPROTO_AH: /* RFC 2402 */
1164 PULLUP_TO(hlen, ulp, struct ip6_ext);
1166 hlen += (((struct ip6_ext *)ulp)->ip6e_len + 2) << 2;
1167 proto = ((struct ip6_ext *)ulp)->ip6e_nxt;
1171 case IPPROTO_ESP: /* RFC 2406 */
1172 PULLUP_TO(hlen, ulp, uint32_t); /* SPI, Seq# */
1173 /* Anything past Seq# is variable length and
1174 * data past this ext. header is encrypted. */
1178 case IPPROTO_NONE: /* RFC 2460 */
1180 * Packet ends here, and IPv6 header has
1181 * already been pulled up. If ip6e_len!=0
1182 * then octets must be ignored.
1184 ulp = ip; /* non-NULL to get out of loop. */
1187 case IPPROTO_OSPFIGP:
1188 /* XXX OSPF header check? */
1189 PULLUP_TO(hlen, ulp, struct ip6_ext);
1193 /* XXX PIM header check? */
1194 PULLUP_TO(hlen, ulp, struct pim);
1198 PULLUP_TO(hlen, ulp, struct carp_header);
1199 if (((struct carp_header *)ulp)->carp_version !=
1201 return (IP_FW_DENY);
1202 if (((struct carp_header *)ulp)->carp_type !=
1204 return (IP_FW_DENY);
1207 case IPPROTO_IPV6: /* RFC 2893 */
1208 PULLUP_TO(hlen, ulp, struct ip6_hdr);
1211 case IPPROTO_IPV4: /* RFC 2893 */
1212 PULLUP_TO(hlen, ulp, struct ip);
1217 printf("IPFW2: IPV6 - Unknown "
1218 "Extension Header(%d), ext_hd=%x\n",
1220 if (V_fw_deny_unknown_exthdrs)
1221 return (IP_FW_DENY);
1222 PULLUP_TO(hlen, ulp, struct ip6_ext);
1226 ip = mtod(m, struct ip *);
1227 ip6 = (struct ip6_hdr *)ip;
1228 args->f_id.src_ip6 = ip6->ip6_src;
1229 args->f_id.dst_ip6 = ip6->ip6_dst;
1230 args->f_id.src_ip = 0;
1231 args->f_id.dst_ip = 0;
1232 args->f_id.flow_id6 = ntohl(ip6->ip6_flow);
1233 } else if (pktlen >= sizeof(struct ip) &&
1234 (args->eh == NULL || etype == ETHERTYPE_IP) && ip->ip_v == 4) {
1236 hlen = ip->ip_hl << 2;
1237 args->f_id.addr_type = 4;
1240 * Collect parameters into local variables for faster matching.
1243 src_ip = ip->ip_src;
1244 dst_ip = ip->ip_dst;
1245 offset = ntohs(ip->ip_off) & IP_OFFMASK;
1246 iplen = ntohs(ip->ip_len);
1247 pktlen = iplen < pktlen ? iplen : pktlen;
1252 PULLUP_TO(hlen, ulp, struct tcphdr);
1253 dst_port = TCP(ulp)->th_dport;
1254 src_port = TCP(ulp)->th_sport;
1255 /* save flags for dynamic rules */
1256 args->f_id._flags = TCP(ulp)->th_flags;
1260 PULLUP_TO(hlen, ulp, struct sctphdr);
1261 src_port = SCTP(ulp)->src_port;
1262 dst_port = SCTP(ulp)->dest_port;
1266 PULLUP_TO(hlen, ulp, struct udphdr);
1267 dst_port = UDP(ulp)->uh_dport;
1268 src_port = UDP(ulp)->uh_sport;
1272 PULLUP_TO(hlen, ulp, struct icmphdr);
1273 //args->f_id.flags = ICMP(ulp)->icmp_type;
1281 ip = mtod(m, struct ip *);
1282 args->f_id.src_ip = ntohl(src_ip.s_addr);
1283 args->f_id.dst_ip = ntohl(dst_ip.s_addr);
1286 if (proto) { /* we may have port numbers, store them */
1287 args->f_id.proto = proto;
1288 args->f_id.src_port = src_port = ntohs(src_port);
1289 args->f_id.dst_port = dst_port = ntohs(dst_port);
1292 IPFW_PF_RLOCK(chain);
1293 if (! V_ipfw_vnet_ready) { /* shutting down, leave NOW. */
1294 IPFW_PF_RUNLOCK(chain);
1295 return (IP_FW_PASS); /* accept */
1297 if (args->rule.slot) {
1299 * Packet has already been tagged as a result of a previous
1300 * match on rule args->rule aka args->rule_id (PIPE, QUEUE,
1301 * REASS, NETGRAPH, DIVERT/TEE...)
1302 * Validate the slot and continue from the next one
1303 * if still present, otherwise do a lookup.
1305 f_pos = (args->rule.chain_id == chain->id) ?
1307 ipfw_find_rule(chain, args->rule.rulenum,
1308 args->rule.rule_id);
1314 * Now scan the rules, and parse microinstructions for each rule.
1315 * We have two nested loops and an inner switch. Sometimes we
1316 * need to break out of one or both loops, or re-enter one of
1317 * the loops with updated variables. Loop variables are:
1319 * f_pos (outer loop) points to the current rule.
1320 * On output it points to the matching rule.
1321 * done (outer loop) is used as a flag to break the loop.
1322 * l (inner loop) residual length of current rule.
1323 * cmd points to the current microinstruction.
1325 * We break the inner loop by setting l=0 and possibly
1326 * cmdlen=0 if we don't want to advance cmd.
1327 * We break the outer loop by setting done=1
1328 * We can restart the inner loop by setting l>0 and f_pos, f, cmd
1331 for (; f_pos < chain->n_rules; f_pos++) {
1333 uint32_t tablearg = 0;
1334 int l, cmdlen, skip_or; /* skip rest of OR block */
1337 f = chain->map[f_pos];
1338 if (V_set_disable & (1 << f->set) )
1342 for (l = f->cmd_len, cmd = f->cmd ; l > 0 ;
1343 l -= cmdlen, cmd += cmdlen) {
1347 * check_body is a jump target used when we find a
1348 * CHECK_STATE, and need to jump to the body of
1353 cmdlen = F_LEN(cmd);
1355 * An OR block (insn_1 || .. || insn_n) has the
1356 * F_OR bit set in all but the last instruction.
1357 * The first match will set "skip_or", and cause
1358 * the following instructions to be skipped until
1359 * past the one with the F_OR bit clear.
1361 if (skip_or) { /* skip this instruction */
1362 if ((cmd->len & F_OR) == 0)
1363 skip_or = 0; /* next one is good */
1366 match = 0; /* set to 1 if we succeed */
1368 switch (cmd->opcode) {
1370 * The first set of opcodes compares the packet's
1371 * fields with some pattern, setting 'match' if a
1372 * match is found. At the end of the loop there is
1373 * logic to deal with F_NOT and F_OR flags associated
1381 printf("ipfw: opcode %d unimplemented\n",
1389 * We only check offset == 0 && proto != 0,
1390 * as this ensures that we have a
1391 * packet with the ports info.
1395 if (proto == IPPROTO_TCP ||
1396 proto == IPPROTO_UDP)
1397 match = check_uidgid(
1398 (ipfw_insn_u32 *)cmd,
1399 args, &ucred_lookup,
1403 (void *)&ucred_cache);
1408 match = iface_match(m->m_pkthdr.rcvif,
1409 (ipfw_insn_if *)cmd, chain, &tablearg);
1413 match = iface_match(oif, (ipfw_insn_if *)cmd,
1418 match = iface_match(oif ? oif :
1419 m->m_pkthdr.rcvif, (ipfw_insn_if *)cmd,
1424 if (args->eh != NULL) { /* have MAC header */
1425 u_int32_t *want = (u_int32_t *)
1426 ((ipfw_insn_mac *)cmd)->addr;
1427 u_int32_t *mask = (u_int32_t *)
1428 ((ipfw_insn_mac *)cmd)->mask;
1429 u_int32_t *hdr = (u_int32_t *)args->eh;
1432 ( want[0] == (hdr[0] & mask[0]) &&
1433 want[1] == (hdr[1] & mask[1]) &&
1434 want[2] == (hdr[2] & mask[2]) );
1439 if (args->eh != NULL) {
1441 ((ipfw_insn_u16 *)cmd)->ports;
1444 for (i = cmdlen - 1; !match && i>0;
1446 match = (etype >= p[0] &&
1452 match = (offset != 0);
1455 case O_IN: /* "out" is "not in" */
1456 match = (oif == NULL);
1460 match = (args->eh != NULL);
1465 /* For diverted packets, args->rule.info
1466 * contains the divert port (in host format)
1467 * reason and direction.
1469 uint32_t i = args->rule.info;
1470 match = (i&IPFW_IS_MASK) == IPFW_IS_DIVERT &&
1471 cmd->arg1 & ((i & IPFW_INFO_IN) ? 1 : 2);
1477 * We do not allow an arg of 0 so the
1478 * check of "proto" only suffices.
1480 match = (proto == cmd->arg1);
1485 (((ipfw_insn_ip *)cmd)->addr.s_addr ==
1489 case O_IP_SRC_LOOKUP:
1490 case O_IP_DST_LOOKUP:
1493 (cmd->opcode == O_IP_DST_LOOKUP) ?
1494 dst_ip.s_addr : src_ip.s_addr;
1497 if (cmdlen > F_INSN_SIZE(ipfw_insn_u32)) {
1498 /* generic lookup. The key must be
1499 * in 32bit big-endian format.
1501 v = ((ipfw_insn_u32 *)cmd)->d[1];
1503 key = dst_ip.s_addr;
1505 key = src_ip.s_addr;
1506 else if (v == 6) /* dscp */
1507 key = (ip->ip_tos >> 2) & 0x3f;
1508 else if (offset != 0)
1510 else if (proto != IPPROTO_TCP &&
1511 proto != IPPROTO_UDP)
1518 else if (v == 4 || v == 5) {
1520 (ipfw_insn_u32 *)cmd,
1521 args, &ucred_lookup,
1524 if (v == 4 /* O_UID */)
1525 key = ucred_cache->cr_uid;
1526 else if (v == 5 /* O_JAIL */)
1527 key = ucred_cache->cr_prison->pr_id;
1528 #else /* !__FreeBSD__ */
1529 (void *)&ucred_cache);
1530 if (v ==4 /* O_UID */)
1531 key = ucred_cache.uid;
1532 else if (v == 5 /* O_JAIL */)
1533 key = ucred_cache.xid;
1534 #endif /* !__FreeBSD__ */
1536 #endif /* !USERSPACE */
1539 match = ipfw_lookup_table(chain,
1540 cmd->arg1, key, &v);
1543 if (cmdlen == F_INSN_SIZE(ipfw_insn_u32))
1545 ((ipfw_insn_u32 *)cmd)->d[0] == v;
1548 } else if (is_ipv6) {
1550 void *pkey = (cmd->opcode == O_IP_DST_LOOKUP) ?
1551 &args->f_id.dst_ip6: &args->f_id.src_ip6;
1552 match = ipfw_lookup_table_extended(chain,
1554 sizeof(struct in6_addr),
1556 if (cmdlen == F_INSN_SIZE(ipfw_insn_u32))
1557 match = ((ipfw_insn_u32 *)cmd)->d[0] == v;
1563 case O_IP_FLOW_LOOKUP:
1566 match = ipfw_lookup_table_extended(chain,
1567 cmd->arg1, 0, &args->f_id, &v);
1568 if (cmdlen == F_INSN_SIZE(ipfw_insn_u32))
1569 match = ((ipfw_insn_u32 *)cmd)->d[0] == v;
1578 (cmd->opcode == O_IP_DST_MASK) ?
1579 dst_ip.s_addr : src_ip.s_addr;
1580 uint32_t *p = ((ipfw_insn_u32 *)cmd)->d;
1583 for (; !match && i>0; i-= 2, p+= 2)
1584 match = (p[0] == (a & p[1]));
1592 INADDR_TO_IFP(src_ip, tif);
1593 match = (tif != NULL);
1599 match= is_ipv6 && search_ip6_addr_net(&args->f_id.src_ip6);
1606 u_int32_t *d = (u_int32_t *)(cmd+1);
1608 cmd->opcode == O_IP_DST_SET ?
1614 addr -= d[0]; /* subtract base */
1615 match = (addr < cmd->arg1) &&
1616 ( d[ 1 + (addr>>5)] &
1617 (1<<(addr & 0x1f)) );
1623 (((ipfw_insn_ip *)cmd)->addr.s_addr ==
1631 INADDR_TO_IFP(dst_ip, tif);
1632 match = (tif != NULL);
1638 match= is_ipv6 && search_ip6_addr_net(&args->f_id.dst_ip6);
1646 * offset == 0 && proto != 0 is enough
1647 * to guarantee that we have a
1648 * packet with port info.
1650 if ((proto==IPPROTO_UDP || proto==IPPROTO_TCP)
1653 (cmd->opcode == O_IP_SRCPORT) ?
1654 src_port : dst_port ;
1656 ((ipfw_insn_u16 *)cmd)->ports;
1659 for (i = cmdlen - 1; !match && i>0;
1661 match = (x>=p[0] && x<=p[1]);
1666 match = (offset == 0 && proto==IPPROTO_ICMP &&
1667 icmptype_match(ICMP(ulp), (ipfw_insn_u32 *)cmd) );
1672 match = is_ipv6 && offset == 0 &&
1673 proto==IPPROTO_ICMPV6 &&
1675 ICMP6(ulp)->icmp6_type,
1676 (ipfw_insn_u32 *)cmd);
1682 ipopts_match(ip, cmd) );
1687 cmd->arg1 == ip->ip_v);
1693 if (is_ipv4) { /* only for IP packets */
1698 if (cmd->opcode == O_IPLEN)
1700 else if (cmd->opcode == O_IPTTL)
1702 else /* must be IPID */
1703 x = ntohs(ip->ip_id);
1705 match = (cmd->arg1 == x);
1708 /* otherwise we have ranges */
1709 p = ((ipfw_insn_u16 *)cmd)->ports;
1711 for (; !match && i>0; i--, p += 2)
1712 match = (x >= p[0] && x <= p[1]);
1716 case O_IPPRECEDENCE:
1718 (cmd->arg1 == (ip->ip_tos & 0xe0)) );
1723 flags_match(cmd, ip->ip_tos));
1731 p = ((ipfw_insn_u32 *)cmd)->d;
1734 x = ip->ip_tos >> 2;
1737 v = &((struct ip6_hdr *)ip)->ip6_vfc;
1738 x = (*v & 0x0F) << 2;
1744 /* DSCP bitmask is stored as low_u32 high_u32 */
1746 match = *(p + 1) & (1 << (x - 32));
1748 match = *p & (1 << x);
1753 if (proto == IPPROTO_TCP && offset == 0) {
1761 ((ip->ip_hl + tcp->th_off) << 2);
1763 match = (cmd->arg1 == x);
1766 /* otherwise we have ranges */
1767 p = ((ipfw_insn_u16 *)cmd)->ports;
1769 for (; !match && i>0; i--, p += 2)
1770 match = (x >= p[0] && x <= p[1]);
1775 match = (proto == IPPROTO_TCP && offset == 0 &&
1776 flags_match(cmd, TCP(ulp)->th_flags));
1780 if (proto == IPPROTO_TCP && offset == 0 && ulp){
1781 PULLUP_LEN(hlen, ulp,
1782 (TCP(ulp)->th_off << 2));
1783 match = tcpopts_match(TCP(ulp), cmd);
1788 match = (proto == IPPROTO_TCP && offset == 0 &&
1789 ((ipfw_insn_u32 *)cmd)->d[0] ==
1794 match = (proto == IPPROTO_TCP && offset == 0 &&
1795 ((ipfw_insn_u32 *)cmd)->d[0] ==
1800 if (proto == IPPROTO_TCP && offset == 0) {
1805 x = ntohs(TCP(ulp)->th_win);
1807 match = (cmd->arg1 == x);
1810 /* Otherwise we have ranges. */
1811 p = ((ipfw_insn_u16 *)cmd)->ports;
1813 for (; !match && i > 0; i--, p += 2)
1814 match = (x >= p[0] && x <= p[1]);
1819 /* reject packets which have SYN only */
1820 /* XXX should i also check for TH_ACK ? */
1821 match = (proto == IPPROTO_TCP && offset == 0 &&
1822 (TCP(ulp)->th_flags &
1823 (TH_RST | TH_ACK | TH_SYN)) != TH_SYN);
1829 ipfw_insn_altq *altq = (ipfw_insn_altq *)cmd;
1832 * ALTQ uses mbuf tags from another
1833 * packet filtering system - pf(4).
1834 * We allocate a tag in its format
1835 * and fill it in, pretending to be pf(4).
1838 at = pf_find_mtag(m);
1839 if (at != NULL && at->qid != 0)
1841 mtag = m_tag_get(PACKET_TAG_PF,
1842 sizeof(struct pf_mtag), M_NOWAIT | M_ZERO);
1845 * Let the packet fall back to the
1850 m_tag_prepend(m, mtag);
1851 at = (struct pf_mtag *)(mtag + 1);
1852 at->qid = altq->qid;
1858 ipfw_log(chain, f, hlen, args, m,
1859 oif, offset | ip6f_mf, tablearg, ip);
1864 match = (random()<((ipfw_insn_u32 *)cmd)->d[0]);
1868 /* Outgoing packets automatically pass/match */
1869 match = ((oif != NULL) ||
1870 (m->m_pkthdr.rcvif == NULL) ||
1874 verify_path6(&(args->f_id.src_ip6),
1875 m->m_pkthdr.rcvif, args->f_id.fib) :
1877 verify_path(src_ip, m->m_pkthdr.rcvif,
1882 /* Outgoing packets automatically pass/match */
1883 match = (hlen > 0 && ((oif != NULL) ||
1886 verify_path6(&(args->f_id.src_ip6),
1887 NULL, args->f_id.fib) :
1889 verify_path(src_ip, NULL, args->f_id.fib)));
1893 /* Outgoing packets automatically pass/match */
1894 if (oif == NULL && hlen > 0 &&
1895 ( (is_ipv4 && in_localaddr(src_ip))
1898 in6_localaddr(&(args->f_id.src_ip6)))
1903 is_ipv6 ? verify_path6(
1904 &(args->f_id.src_ip6),
1917 match = (m_tag_find(m,
1918 PACKET_TAG_IPSEC_IN_DONE, NULL) != NULL);
1920 /* otherwise no match */
1926 IN6_ARE_ADDR_EQUAL(&args->f_id.src_ip6,
1927 &((ipfw_insn_ip6 *)cmd)->addr6);
1932 IN6_ARE_ADDR_EQUAL(&args->f_id.dst_ip6,
1933 &((ipfw_insn_ip6 *)cmd)->addr6);
1935 case O_IP6_SRC_MASK:
1936 case O_IP6_DST_MASK:
1940 struct in6_addr *d =
1941 &((ipfw_insn_ip6 *)cmd)->addr6;
1943 for (; !match && i > 0; d += 2,
1944 i -= F_INSN_SIZE(struct in6_addr)
1950 APPLY_MASK(&p, &d[1]);
1952 IN6_ARE_ADDR_EQUAL(&d[0],
1960 flow6id_match(args->f_id.flow_id6,
1961 (ipfw_insn_u32 *) cmd);
1966 (ext_hd & ((ipfw_insn *) cmd)->arg1);
1980 uint32_t tag = TARG(cmd->arg1, tag);
1982 /* Packet is already tagged with this tag? */
1983 mtag = m_tag_locate(m, MTAG_IPFW, tag, NULL);
1985 /* We have `untag' action when F_NOT flag is
1986 * present. And we must remove this mtag from
1987 * mbuf and reset `match' to zero (`match' will
1988 * be inversed later).
1989 * Otherwise we should allocate new mtag and
1990 * push it into mbuf.
1992 if (cmd->len & F_NOT) { /* `untag' action */
1994 m_tag_delete(m, mtag);
1998 mtag = m_tag_alloc( MTAG_IPFW,
2001 m_tag_prepend(m, mtag);
2008 case O_FIB: /* try match the specified fib */
2009 if (args->f_id.fib == cmd->arg1)
2014 #ifndef USERSPACE /* not supported in userspace */
2015 struct inpcb *inp = args->inp;
2016 struct inpcbinfo *pi;
2018 if (is_ipv6) /* XXX can we remove this ? */
2021 if (proto == IPPROTO_TCP)
2023 else if (proto == IPPROTO_UDP)
2029 * XXXRW: so_user_cookie should almost
2030 * certainly be inp_user_cookie?
2033 /* For incomming packet, lookup up the
2034 inpcb using the src/dest ip/port tuple */
2036 inp = in_pcblookup(pi,
2037 src_ip, htons(src_port),
2038 dst_ip, htons(dst_port),
2039 INPLOOKUP_RLOCKPCB, NULL);
2042 inp->inp_socket->so_user_cookie;
2048 if (inp->inp_socket) {
2050 inp->inp_socket->so_user_cookie;
2055 #endif /* !USERSPACE */
2061 uint32_t tag = TARG(cmd->arg1, tag);
2064 match = m_tag_locate(m, MTAG_IPFW,
2069 /* we have ranges */
2070 for (mtag = m_tag_first(m);
2071 mtag != NULL && !match;
2072 mtag = m_tag_next(m, mtag)) {
2076 if (mtag->m_tag_cookie != MTAG_IPFW)
2079 p = ((ipfw_insn_u16 *)cmd)->ports;
2081 for(; !match && i > 0; i--, p += 2)
2083 mtag->m_tag_id >= p[0] &&
2084 mtag->m_tag_id <= p[1];
2090 * The second set of opcodes represents 'actions',
2091 * i.e. the terminal part of a rule once the packet
2092 * matches all previous patterns.
2093 * Typically there is only one action for each rule,
2094 * and the opcode is stored at the end of the rule
2095 * (but there are exceptions -- see below).
2097 * In general, here we set retval and terminate the
2098 * outer loop (would be a 'break 3' in some language,
2099 * but we need to set l=0, done=1)
2102 * O_COUNT and O_SKIPTO actions:
2103 * instead of terminating, we jump to the next rule
2104 * (setting l=0), or to the SKIPTO target (setting
2105 * f/f_len, cmd and l as needed), respectively.
2107 * O_TAG, O_LOG and O_ALTQ action parameters:
2108 * perform some action and set match = 1;
2110 * O_LIMIT and O_KEEP_STATE: these opcodes are
2111 * not real 'actions', and are stored right
2112 * before the 'action' part of the rule.
2113 * These opcodes try to install an entry in the
2114 * state tables; if successful, we continue with
2115 * the next opcode (match=1; break;), otherwise
2116 * the packet must be dropped (set retval,
2117 * break loops with l=0, done=1)
2119 * O_PROBE_STATE and O_CHECK_STATE: these opcodes
2120 * cause a lookup of the state table, and a jump
2121 * to the 'action' part of the parent rule
2122 * if an entry is found, or
2123 * (CHECK_STATE only) a jump to the next rule if
2124 * the entry is not found.
2125 * The result of the lookup is cached so that
2126 * further instances of these opcodes become NOPs.
2127 * The jump to the next rule is done by setting
2132 if (ipfw_install_state(chain, f,
2133 (ipfw_insn_limit *)cmd, args, tablearg)) {
2134 /* error or limit violation */
2135 retval = IP_FW_DENY;
2136 l = 0; /* exit inner loop */
2137 done = 1; /* exit outer loop */
2145 * dynamic rules are checked at the first
2146 * keep-state or check-state occurrence,
2147 * with the result being stored in dyn_dir.
2148 * The compiler introduces a PROBE_STATE
2149 * instruction for us when we have a
2150 * KEEP_STATE (because PROBE_STATE needs
2153 if (dyn_dir == MATCH_UNKNOWN &&
2154 (q = ipfw_lookup_dyn_rule(&args->f_id,
2155 &dyn_dir, proto == IPPROTO_TCP ?
2159 * Found dynamic entry, update stats
2160 * and jump to the 'action' part of
2161 * the parent rule by setting
2162 * f, cmd, l and clearing cmdlen.
2164 IPFW_INC_DYN_COUNTER(q, pktlen);
2165 /* XXX we would like to have f_pos
2166 * readily accessible in the dynamic
2167 * rule, instead of having to
2171 f_pos = ipfw_find_rule(chain,
2173 cmd = ACTION_PTR(f);
2174 l = f->cmd_len - f->act_ofs;
2181 * Dynamic entry not found. If CHECK_STATE,
2182 * skip to next rule, if PROBE_STATE just
2183 * ignore and continue with next opcode.
2185 if (cmd->opcode == O_CHECK_STATE)
2186 l = 0; /* exit inner loop */
2191 retval = 0; /* accept */
2192 l = 0; /* exit inner loop */
2193 done = 1; /* exit outer loop */
2198 set_match(args, f_pos, chain);
2199 args->rule.info = TARG(cmd->arg1, pipe);
2200 if (cmd->opcode == O_PIPE)
2201 args->rule.info |= IPFW_IS_PIPE;
2203 args->rule.info |= IPFW_ONEPASS;
2204 retval = IP_FW_DUMMYNET;
2205 l = 0; /* exit inner loop */
2206 done = 1; /* exit outer loop */
2211 if (args->eh) /* not on layer 2 */
2213 /* otherwise this is terminal */
2214 l = 0; /* exit inner loop */
2215 done = 1; /* exit outer loop */
2216 retval = (cmd->opcode == O_DIVERT) ?
2217 IP_FW_DIVERT : IP_FW_TEE;
2218 set_match(args, f_pos, chain);
2219 args->rule.info = TARG(cmd->arg1, divert);
2223 IPFW_INC_RULE_COUNTER(f, pktlen);
2224 l = 0; /* exit inner loop */
2228 IPFW_INC_RULE_COUNTER(f, pktlen);
2229 f_pos = JUMP(chain, f, cmd->arg1, tablearg, 0);
2231 * Skip disabled rules, and re-enter
2232 * the inner loop with the correct
2233 * f_pos, f, l and cmd.
2234 * Also clear cmdlen and skip_or
2236 for (; f_pos < chain->n_rules - 1 &&
2238 (1 << chain->map[f_pos]->set));
2241 /* Re-enter the inner loop at the skipto rule. */
2242 f = chain->map[f_pos];
2249 break; /* not reached */
2251 case O_CALLRETURN: {
2253 * Implementation of `subroutine' call/return,
2254 * in the stack carried in an mbuf tag. This
2255 * is different from `skipto' in that any call
2256 * address is possible (`skipto' must prevent
2257 * backward jumps to avoid endless loops).
2258 * We have `return' action when F_NOT flag is
2259 * present. The `m_tag_id' field is used as
2263 uint16_t jmpto, *stack;
2265 #define IS_CALL ((cmd->len & F_NOT) == 0)
2266 #define IS_RETURN ((cmd->len & F_NOT) != 0)
2268 * Hand-rolled version of m_tag_locate() with
2270 * If not already tagged, allocate new tag.
2272 mtag = m_tag_first(m);
2273 while (mtag != NULL) {
2274 if (mtag->m_tag_cookie ==
2277 mtag = m_tag_next(m, mtag);
2279 if (mtag == NULL && IS_CALL) {
2280 mtag = m_tag_alloc(MTAG_IPFW_CALL, 0,
2281 IPFW_CALLSTACK_SIZE *
2282 sizeof(uint16_t), M_NOWAIT);
2284 m_tag_prepend(m, mtag);
2288 * On error both `call' and `return' just
2289 * continue with next rule.
2291 if (IS_RETURN && (mtag == NULL ||
2292 mtag->m_tag_id == 0)) {
2293 l = 0; /* exit inner loop */
2296 if (IS_CALL && (mtag == NULL ||
2297 mtag->m_tag_id >= IPFW_CALLSTACK_SIZE)) {
2298 printf("ipfw: call stack error, "
2299 "go to next rule\n");
2300 l = 0; /* exit inner loop */
2304 IPFW_INC_RULE_COUNTER(f, pktlen);
2305 stack = (uint16_t *)(mtag + 1);
2308 * The `call' action may use cached f_pos
2309 * (in f->next_rule), whose version is written
2311 * The `return' action, however, doesn't have
2312 * fixed jump address in cmd->arg1 and can't use
2316 stack[mtag->m_tag_id] = f->rulenum;
2318 f_pos = JUMP(chain, f, cmd->arg1,
2320 } else { /* `return' action */
2322 jmpto = stack[mtag->m_tag_id] + 1;
2323 f_pos = ipfw_find_rule(chain, jmpto, 0);
2327 * Skip disabled rules, and re-enter
2328 * the inner loop with the correct
2329 * f_pos, f, l and cmd.
2330 * Also clear cmdlen and skip_or
2332 for (; f_pos < chain->n_rules - 1 &&
2334 (1 << chain->map[f_pos]->set)); f_pos++)
2336 /* Re-enter the inner loop at the dest rule. */
2337 f = chain->map[f_pos];
2343 break; /* NOTREACHED */
2350 * Drop the packet and send a reject notice
2351 * if the packet is not ICMP (or is an ICMP
2352 * query), and it is not multicast/broadcast.
2354 if (hlen > 0 && is_ipv4 && offset == 0 &&
2355 (proto != IPPROTO_ICMP ||
2356 is_icmp_query(ICMP(ulp))) &&
2357 !(m->m_flags & (M_BCAST|M_MCAST)) &&
2358 !IN_MULTICAST(ntohl(dst_ip.s_addr))) {
2359 send_reject(args, cmd->arg1, iplen, ip);
2365 if (hlen > 0 && is_ipv6 &&
2366 ((offset & IP6F_OFF_MASK) == 0) &&
2367 (proto != IPPROTO_ICMPV6 ||
2368 (is_icmp6_query(icmp6_type) == 1)) &&
2369 !(m->m_flags & (M_BCAST|M_MCAST)) &&
2370 !IN6_IS_ADDR_MULTICAST(&args->f_id.dst_ip6)) {
2372 args, cmd->arg1, hlen,
2373 (struct ip6_hdr *)ip);
2379 retval = IP_FW_DENY;
2380 l = 0; /* exit inner loop */
2381 done = 1; /* exit outer loop */
2385 if (args->eh) /* not valid on layer2 pkts */
2387 if (q == NULL || q->rule != f ||
2388 dyn_dir == MATCH_FORWARD) {
2389 struct sockaddr_in *sa;
2391 sa = &(((ipfw_insn_sa *)cmd)->sa);
2392 if (sa->sin_addr.s_addr == INADDR_ANY) {
2395 * We use O_FORWARD_IP opcode for
2396 * fwd rule with tablearg, but tables
2397 * now support IPv6 addresses. And
2398 * when we are inspecting IPv6 packet,
2399 * we can use nh6 field from
2400 * table_value as next_hop6 address.
2403 struct sockaddr_in6 *sa6;
2405 sa6 = args->next_hop6 =
2407 sa6->sin6_family = AF_INET6;
2408 sa6->sin6_len = sizeof(*sa6);
2409 sa6->sin6_addr = TARG_VAL(
2410 chain, tablearg, nh6);
2412 * Set sin6_scope_id only for
2413 * link-local unicast addresses.
2415 if (IN6_IS_ADDR_LINKLOCAL(
2417 sa6->sin6_scope_id =
2424 sa = args->next_hop =
2426 sa->sin_family = AF_INET;
2427 sa->sin_len = sizeof(*sa);
2428 sa->sin_addr.s_addr = htonl(
2429 TARG_VAL(chain, tablearg,
2433 args->next_hop = sa;
2436 retval = IP_FW_PASS;
2437 l = 0; /* exit inner loop */
2438 done = 1; /* exit outer loop */
2443 if (args->eh) /* not valid on layer2 pkts */
2445 if (q == NULL || q->rule != f ||
2446 dyn_dir == MATCH_FORWARD) {
2447 struct sockaddr_in6 *sin6;
2449 sin6 = &(((ipfw_insn_sa6 *)cmd)->sa);
2450 args->next_hop6 = sin6;
2452 retval = IP_FW_PASS;
2453 l = 0; /* exit inner loop */
2454 done = 1; /* exit outer loop */
2460 set_match(args, f_pos, chain);
2461 args->rule.info = TARG(cmd->arg1, netgraph);
2463 args->rule.info |= IPFW_ONEPASS;
2464 retval = (cmd->opcode == O_NETGRAPH) ?
2465 IP_FW_NETGRAPH : IP_FW_NGTEE;
2466 l = 0; /* exit inner loop */
2467 done = 1; /* exit outer loop */
2473 IPFW_INC_RULE_COUNTER(f, pktlen);
2474 fib = TARG(cmd->arg1, fib) & 0x7FFFF;
2475 if (fib >= rt_numfibs)
2478 args->f_id.fib = fib;
2479 l = 0; /* exit inner loop */
2486 code = TARG(cmd->arg1, dscp) & 0x3F;
2487 l = 0; /* exit inner loop */
2492 ip->ip_tos = (code << 2) | (ip->ip_tos & 0x03);
2493 a += ntohs(ip->ip_sum) - ip->ip_tos;
2494 ip->ip_sum = htons(a);
2495 } else if (is_ipv6) {
2498 v = &((struct ip6_hdr *)ip)->ip6_vfc;
2499 *v = (*v & 0xF0) | (code >> 2);
2501 *v = (*v & 0x3F) | ((code & 0x03) << 6);
2505 IPFW_INC_RULE_COUNTER(f, pktlen);
2510 l = 0; /* exit inner loop */
2511 done = 1; /* exit outer loop */
2512 if (!IPFW_NAT_LOADED) {
2513 retval = IP_FW_DENY;
2520 set_match(args, f_pos, chain);
2521 /* Check if this is 'global' nat rule */
2522 if (cmd->arg1 == 0) {
2523 retval = ipfw_nat_ptr(args, NULL, m);
2526 t = ((ipfw_insn_nat *)cmd)->nat;
2528 nat_id = TARG(cmd->arg1, nat);
2529 t = (*lookup_nat_ptr)(&chain->nat, nat_id);
2532 retval = IP_FW_DENY;
2535 if (cmd->arg1 != IP_FW_TARG)
2536 ((ipfw_insn_nat *)cmd)->nat = t;
2538 retval = ipfw_nat_ptr(args, t, m);
2544 IPFW_INC_RULE_COUNTER(f, pktlen);
2545 l = 0; /* in any case exit inner loop */
2546 ip_off = ntohs(ip->ip_off);
2548 /* if not fragmented, go to next rule */
2549 if ((ip_off & (IP_MF | IP_OFFMASK)) == 0)
2552 args->m = m = ip_reass(m);
2555 * do IP header checksum fixup.
2557 if (m == NULL) { /* fragment got swallowed */
2558 retval = IP_FW_DENY;
2559 } else { /* good, packet complete */
2562 ip = mtod(m, struct ip *);
2563 hlen = ip->ip_hl << 2;
2565 if (hlen == sizeof(struct ip))
2566 ip->ip_sum = in_cksum_hdr(ip);
2568 ip->ip_sum = in_cksum(m, hlen);
2569 retval = IP_FW_REASS;
2570 set_match(args, f_pos, chain);
2572 done = 1; /* exit outer loop */
2577 panic("-- unknown opcode %d\n", cmd->opcode);
2578 } /* end of switch() on opcodes */
2580 * if we get here with l=0, then match is irrelevant.
2583 if (cmd->len & F_NOT)
2587 if (cmd->len & F_OR)
2590 if (!(cmd->len & F_OR)) /* not an OR block, */
2591 break; /* try next rule */
2594 } /* end of inner loop, scan opcodes */
2600 /* next_rule:; */ /* try next rule */
2602 } /* end of outer for, scan rules */
2605 struct ip_fw *rule = chain->map[f_pos];
2606 /* Update statistics */
2607 IPFW_INC_RULE_COUNTER(rule, pktlen);
2609 retval = IP_FW_DENY;
2610 printf("ipfw: ouch!, skip past end of rules, denying packet\n");
2612 IPFW_PF_RUNLOCK(chain);
2614 if (ucred_cache != NULL)
2615 crfree(ucred_cache);
2621 printf("ipfw: pullup failed\n");
2622 return (IP_FW_DENY);
2626 * Set maximum number of tables that can be used in given VNET ipfw instance.
2630 sysctl_ipfw_table_num(SYSCTL_HANDLER_ARGS)
2633 unsigned int ntables;
2635 ntables = V_fw_tables_max;
2637 error = sysctl_handle_int(oidp, &ntables, 0, req);
2638 /* Read operation or some error */
2639 if ((error != 0) || (req->newptr == NULL))
2642 return (ipfw_resize_tables(&V_layer3_chain, ntables));
2646 * Switches table namespace between global and per-set.
2649 sysctl_ipfw_tables_sets(SYSCTL_HANDLER_ARGS)
2654 sets = V_fw_tables_sets;
2656 error = sysctl_handle_int(oidp, &sets, 0, req);
2657 /* Read operation or some error */
2658 if ((error != 0) || (req->newptr == NULL))
2661 return (ipfw_switch_tables_namespace(&V_layer3_chain, sets));
2666 * Module and VNET glue
2670 * Stuff that must be initialised only on boot or module load
2678 * Only print out this stuff the first time around,
2679 * when called from the sysinit code.
2685 "initialized, divert %s, nat %s, "
2686 "default to %s, logging ",
2692 #ifdef IPFIREWALL_NAT
2697 default_to_accept ? "accept" : "deny");
2700 * Note: V_xxx variables can be accessed here but the vnet specific
2701 * initializer may not have been called yet for the VIMAGE case.
2702 * Tuneables will have been processed. We will print out values for
2704 * XXX This should all be rationalized AFTER 8.0
2706 if (V_fw_verbose == 0)
2707 printf("disabled\n");
2708 else if (V_verbose_limit == 0)
2709 printf("unlimited\n");
2711 printf("limited to %d packets/entry by default\n",
2714 /* Check user-supplied table count for validness */
2715 if (default_fw_tables > IPFW_TABLES_MAX)
2716 default_fw_tables = IPFW_TABLES_MAX;
2718 ipfw_init_sopt_handler();
2719 ipfw_log_bpf(1); /* init */
2725 * Called for the removal of the last instance only on module unload.
2731 ipfw_iface_destroy();
2732 ipfw_log_bpf(0); /* uninit */
2733 ipfw_destroy_sopt_handler();
2734 printf("IP firewall unloaded\n");
2738 * Stuff that must be initialized for every instance
2739 * (including the first of course).
2742 vnet_ipfw_init(const void *unused)
2745 struct ip_fw *rule = NULL;
2746 struct ip_fw_chain *chain;
2748 chain = &V_layer3_chain;
2750 first = IS_DEFAULT_VNET(curvnet) ? 1 : 0;
2752 /* First set up some values that are compile time options */
2753 V_autoinc_step = 100; /* bounded to 1..1000 in add_rule() */
2754 V_fw_deny_unknown_exthdrs = 1;
2755 #ifdef IPFIREWALL_VERBOSE
2758 #ifdef IPFIREWALL_VERBOSE_LIMIT
2759 V_verbose_limit = IPFIREWALL_VERBOSE_LIMIT;
2761 #ifdef IPFIREWALL_NAT
2762 LIST_INIT(&chain->nat);
2765 ipfw_init_counters();
2766 /* insert the default rule and create the initial map */
2768 chain->map = malloc(sizeof(struct ip_fw *), M_IPFW, M_WAITOK | M_ZERO);
2769 rule = ipfw_alloc_rule(chain, sizeof(struct ip_fw));
2771 /* Set initial number of tables */
2772 V_fw_tables_max = default_fw_tables;
2773 error = ipfw_init_tables(chain, first);
2775 printf("ipfw2: setting up tables failed\n");
2776 free(chain->map, M_IPFW);
2781 /* fill and insert the default rule */
2783 rule->rulenum = IPFW_DEFAULT_RULE;
2785 rule->set = RESVD_SET;
2786 rule->cmd[0].len = 1;
2787 rule->cmd[0].opcode = default_to_accept ? O_ACCEPT : O_DENY;
2788 chain->default_rule = chain->map[0] = rule;
2789 chain->id = rule->id = 1;
2790 /* Pre-calculate rules length for legacy dump format */
2791 chain->static_len = sizeof(struct ip_fw_rule0);
2793 IPFW_LOCK_INIT(chain);
2794 ipfw_dyn_init(chain);
2795 #ifdef LINEAR_SKIPTO
2796 ipfw_init_skipto_cache(chain);
2799 /* First set up some values that are compile time options */
2800 V_ipfw_vnet_ready = 1; /* Open for business */
2803 * Hook the sockopt handler and pfil hooks for ipv4 and ipv6.
2804 * Even if the latter two fail we still keep the module alive
2805 * because the sockopt and layer2 paths are still useful.
2806 * ipfw[6]_hook return 0 on success, ENOENT on failure,
2807 * so we can ignore the exact return value and just set a flag.
2809 * Note that V_fw[6]_enable are manipulated by a SYSCTL_PROC so
2810 * changes in the underlying (per-vnet) variables trigger
2811 * immediate hook()/unhook() calls.
2812 * In layer2 we have the same behaviour, except that V_ether_ipfw
2813 * is checked on each packet because there are no pfil hooks.
2815 V_ip_fw_ctl_ptr = ipfw_ctl3;
2816 error = ipfw_attach_hooks(1);
2821 * Called for the removal of each instance.
2824 vnet_ipfw_uninit(const void *unused)
2827 struct ip_fw_chain *chain = &V_layer3_chain;
2830 V_ipfw_vnet_ready = 0; /* tell new callers to go away */
2832 * disconnect from ipv4, ipv6, layer2 and sockopt.
2833 * Then grab, release and grab again the WLOCK so we make
2834 * sure the update is propagated and nobody will be in.
2836 (void)ipfw_attach_hooks(0 /* detach */);
2837 V_ip_fw_ctl_ptr = NULL;
2839 last = IS_DEFAULT_VNET(curvnet) ? 1 : 0;
2841 IPFW_UH_WLOCK(chain);
2842 IPFW_UH_WUNLOCK(chain);
2843 IPFW_UH_WLOCK(chain);
2846 ipfw_dyn_uninit(0); /* run the callout_drain */
2847 IPFW_WUNLOCK(chain);
2851 for (i = 0; i < chain->n_rules; i++)
2852 ipfw_reap_add(chain, &reap, chain->map[i]);
2853 free(chain->map, M_IPFW);
2854 #ifdef LINEAR_SKIPTO
2855 ipfw_destroy_skipto_cache(chain);
2857 IPFW_WUNLOCK(chain);
2858 IPFW_UH_WUNLOCK(chain);
2859 ipfw_destroy_tables(chain, last);
2861 ipfw_reap_rules(reap);
2862 vnet_ipfw_iface_destroy(chain);
2863 IPFW_LOCK_DESTROY(chain);
2864 ipfw_dyn_uninit(1); /* free the remaining parts */
2865 ipfw_destroy_counters();
2870 * Module event handler.
2871 * In general we have the choice of handling most of these events by the
2872 * event handler or by the (VNET_)SYS(UN)INIT handlers. I have chosen to
2873 * use the SYSINIT handlers as they are more capable of expressing the
2874 * flow of control during module and vnet operations, so this is just
2875 * a skeleton. Note there is no SYSINIT equivalent of the module
2876 * SHUTDOWN handler, but we don't have anything to do in that case anyhow.
2879 ipfw_modevent(module_t mod, int type, void *unused)
2885 /* Called once at module load or
2886 * system boot if compiled in. */
2889 /* Called before unload. May veto unloading. */
2892 /* Called during unload. */
2895 /* Called during system shutdown. */
2904 static moduledata_t ipfwmod = {
2910 /* Define startup order. */
2911 #define IPFW_SI_SUB_FIREWALL SI_SUB_PROTO_IFATTACHDOMAIN
2912 #define IPFW_MODEVENT_ORDER (SI_ORDER_ANY - 255) /* On boot slot in here. */
2913 #define IPFW_MODULE_ORDER (IPFW_MODEVENT_ORDER + 1) /* A little later. */
2914 #define IPFW_VNET_ORDER (IPFW_MODEVENT_ORDER + 2) /* Later still. */
2916 DECLARE_MODULE(ipfw, ipfwmod, IPFW_SI_SUB_FIREWALL, IPFW_MODEVENT_ORDER);
2917 FEATURE(ipfw_ctl3, "ipfw new sockopt calls");
2918 MODULE_VERSION(ipfw, 3);
2919 /* should declare some dependencies here */
2922 * Starting up. Done in order after ipfwmod() has been called.
2923 * VNET_SYSINIT is also called for each existing vnet and each new vnet.
2925 SYSINIT(ipfw_init, IPFW_SI_SUB_FIREWALL, IPFW_MODULE_ORDER,
2927 VNET_SYSINIT(vnet_ipfw_init, IPFW_SI_SUB_FIREWALL, IPFW_VNET_ORDER,
2928 vnet_ipfw_init, NULL);
2931 * Closing up shop. These are done in REVERSE ORDER, but still
2932 * after ipfwmod() has been called. Not called on reboot.
2933 * VNET_SYSUNINIT is also called for each exiting vnet as it exits.
2934 * or when the module is unloaded.
2936 SYSUNINIT(ipfw_destroy, IPFW_SI_SUB_FIREWALL, IPFW_MODULE_ORDER,
2937 ipfw_destroy, NULL);
2938 VNET_SYSUNINIT(vnet_ipfw_uninit, IPFW_SI_SUB_FIREWALL, IPFW_VNET_ORDER,
2939 vnet_ipfw_uninit, NULL);