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>
87 #include <netinet/in_fib.h>
89 #include <netinet6/in6_fib.h>
90 #include <netinet6/in6_pcb.h>
91 #include <netinet6/scope6_var.h>
92 #include <netinet6/ip6_var.h>
95 #include <net/if_gre.h> /* for struct grehdr */
97 #include <netpfil/ipfw/ip_fw_private.h>
99 #include <machine/in_cksum.h> /* XXX for in_cksum */
102 #include <security/mac/mac_framework.h>
106 * static variables followed by global ones.
107 * All ipfw global variables are here.
110 static VNET_DEFINE(int, fw_deny_unknown_exthdrs);
111 #define V_fw_deny_unknown_exthdrs VNET(fw_deny_unknown_exthdrs)
113 static VNET_DEFINE(int, fw_permit_single_frag6) = 1;
114 #define V_fw_permit_single_frag6 VNET(fw_permit_single_frag6)
116 #ifdef IPFIREWALL_DEFAULT_TO_ACCEPT
117 static int default_to_accept = 1;
119 static int default_to_accept;
122 VNET_DEFINE(int, autoinc_step);
123 VNET_DEFINE(int, fw_one_pass) = 1;
125 VNET_DEFINE(unsigned int, fw_tables_max);
126 VNET_DEFINE(unsigned int, fw_tables_sets) = 0; /* Don't use set-aware tables */
127 /* Use 128 tables by default */
128 static unsigned int default_fw_tables = IPFW_TABLES_DEFAULT;
130 #ifndef LINEAR_SKIPTO
131 static int jump_fast(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_fast(ch, f, num, targ, back)
135 static int jump_linear(struct ip_fw_chain *chain, struct ip_fw *f, int num,
136 int tablearg, int jump_backwards);
137 #define JUMP(ch, f, num, targ, back) jump_linear(ch, f, num, targ, back)
141 * Each rule belongs to one of 32 different sets (0..31).
142 * The variable set_disable contains one bit per set.
143 * If the bit is set, all rules in the corresponding set
144 * are disabled. Set RESVD_SET(31) is reserved for the default rule
145 * and rules that are not deleted by the flush command,
146 * and CANNOT be disabled.
147 * Rules in set RESVD_SET can only be deleted individually.
149 VNET_DEFINE(u_int32_t, set_disable);
150 #define V_set_disable VNET(set_disable)
152 VNET_DEFINE(int, fw_verbose);
153 /* counter for ipfw_log(NULL...) */
154 VNET_DEFINE(u_int64_t, norule_counter);
155 VNET_DEFINE(int, verbose_limit);
157 /* layer3_chain contains the list of rules for layer 3 */
158 VNET_DEFINE(struct ip_fw_chain, layer3_chain);
160 /* ipfw_vnet_ready controls when we are open for business */
161 VNET_DEFINE(int, ipfw_vnet_ready) = 0;
163 VNET_DEFINE(int, ipfw_nat_ready) = 0;
165 ipfw_nat_t *ipfw_nat_ptr = NULL;
166 struct cfg_nat *(*lookup_nat_ptr)(struct nat_list *, int);
167 ipfw_nat_cfg_t *ipfw_nat_cfg_ptr;
168 ipfw_nat_cfg_t *ipfw_nat_del_ptr;
169 ipfw_nat_cfg_t *ipfw_nat_get_cfg_ptr;
170 ipfw_nat_cfg_t *ipfw_nat_get_log_ptr;
173 uint32_t dummy_def = IPFW_DEFAULT_RULE;
174 static int sysctl_ipfw_table_num(SYSCTL_HANDLER_ARGS);
175 static int sysctl_ipfw_tables_sets(SYSCTL_HANDLER_ARGS);
179 SYSCTL_NODE(_net_inet_ip, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall");
180 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, one_pass,
181 CTLFLAG_VNET | CTLFLAG_RW | CTLFLAG_SECURE3, &VNET_NAME(fw_one_pass), 0,
182 "Only do a single pass through ipfw when using dummynet(4)");
183 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, autoinc_step,
184 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(autoinc_step), 0,
185 "Rule number auto-increment step");
186 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose,
187 CTLFLAG_VNET | CTLFLAG_RW | CTLFLAG_SECURE3, &VNET_NAME(fw_verbose), 0,
188 "Log matches to ipfw rules");
189 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose_limit,
190 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(verbose_limit), 0,
191 "Set upper limit of matches of ipfw rules logged");
192 SYSCTL_UINT(_net_inet_ip_fw, OID_AUTO, default_rule, CTLFLAG_RD,
194 "The default/max possible rule number.");
195 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, tables_max,
196 CTLFLAG_VNET | CTLTYPE_UINT | CTLFLAG_RW, 0, 0, sysctl_ipfw_table_num, "IU",
197 "Maximum number of concurrently used tables");
198 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, tables_sets,
199 CTLFLAG_VNET | CTLTYPE_UINT | CTLFLAG_RW,
200 0, 0, sysctl_ipfw_tables_sets, "IU",
201 "Use per-set namespace for tables");
202 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, default_to_accept, CTLFLAG_RDTUN,
203 &default_to_accept, 0,
204 "Make the default rule accept all packets.");
205 TUNABLE_INT("net.inet.ip.fw.tables_max", (int *)&default_fw_tables);
206 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, static_count,
207 CTLFLAG_VNET | CTLFLAG_RD, &VNET_NAME(layer3_chain.n_rules), 0,
208 "Number of static rules");
211 SYSCTL_DECL(_net_inet6_ip6);
212 SYSCTL_NODE(_net_inet6_ip6, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall");
213 SYSCTL_INT(_net_inet6_ip6_fw, OID_AUTO, deny_unknown_exthdrs,
214 CTLFLAG_VNET | CTLFLAG_RW | CTLFLAG_SECURE,
215 &VNET_NAME(fw_deny_unknown_exthdrs), 0,
216 "Deny packets with unknown IPv6 Extension Headers");
217 SYSCTL_INT(_net_inet6_ip6_fw, OID_AUTO, permit_single_frag6,
218 CTLFLAG_VNET | CTLFLAG_RW | CTLFLAG_SECURE,
219 &VNET_NAME(fw_permit_single_frag6), 0,
220 "Permit single packet IPv6 fragments");
225 #endif /* SYSCTL_NODE */
229 * Some macros used in the various matching options.
230 * L3HDR maps an ipv4 pointer into a layer3 header pointer of type T
231 * Other macros just cast void * into the appropriate type
233 #define L3HDR(T, ip) ((T *)((u_int32_t *)(ip) + (ip)->ip_hl))
234 #define TCP(p) ((struct tcphdr *)(p))
235 #define SCTP(p) ((struct sctphdr *)(p))
236 #define UDP(p) ((struct udphdr *)(p))
237 #define ICMP(p) ((struct icmphdr *)(p))
238 #define ICMP6(p) ((struct icmp6_hdr *)(p))
241 icmptype_match(struct icmphdr *icmp, ipfw_insn_u32 *cmd)
243 int type = icmp->icmp_type;
245 return (type <= ICMP_MAXTYPE && (cmd->d[0] & (1<<type)) );
248 #define TT ( (1 << ICMP_ECHO) | (1 << ICMP_ROUTERSOLICIT) | \
249 (1 << ICMP_TSTAMP) | (1 << ICMP_IREQ) | (1 << ICMP_MASKREQ) )
252 is_icmp_query(struct icmphdr *icmp)
254 int type = icmp->icmp_type;
256 return (type <= ICMP_MAXTYPE && (TT & (1<<type)) );
261 * The following checks use two arrays of 8 or 16 bits to store the
262 * bits that we want set or clear, respectively. They are in the
263 * low and high half of cmd->arg1 or cmd->d[0].
265 * We scan options and store the bits we find set. We succeed if
267 * (want_set & ~bits) == 0 && (want_clear & ~bits) == want_clear
269 * The code is sometimes optimized not to store additional variables.
273 flags_match(ipfw_insn *cmd, u_int8_t bits)
278 if ( ((cmd->arg1 & 0xff) & bits) != 0)
279 return 0; /* some bits we want set were clear */
280 want_clear = (cmd->arg1 >> 8) & 0xff;
281 if ( (want_clear & bits) != want_clear)
282 return 0; /* some bits we want clear were set */
287 ipopts_match(struct ip *ip, ipfw_insn *cmd)
289 int optlen, bits = 0;
290 u_char *cp = (u_char *)(ip + 1);
291 int x = (ip->ip_hl << 2) - sizeof (struct ip);
293 for (; x > 0; x -= optlen, cp += optlen) {
294 int opt = cp[IPOPT_OPTVAL];
296 if (opt == IPOPT_EOL)
298 if (opt == IPOPT_NOP)
301 optlen = cp[IPOPT_OLEN];
302 if (optlen <= 0 || optlen > x)
303 return 0; /* invalid or truncated */
311 bits |= IP_FW_IPOPT_LSRR;
315 bits |= IP_FW_IPOPT_SSRR;
319 bits |= IP_FW_IPOPT_RR;
323 bits |= IP_FW_IPOPT_TS;
327 return (flags_match(cmd, bits));
331 tcpopts_match(struct tcphdr *tcp, ipfw_insn *cmd)
333 int optlen, bits = 0;
334 u_char *cp = (u_char *)(tcp + 1);
335 int x = (tcp->th_off << 2) - sizeof(struct tcphdr);
337 for (; x > 0; x -= optlen, cp += optlen) {
339 if (opt == TCPOPT_EOL)
341 if (opt == TCPOPT_NOP)
355 bits |= IP_FW_TCPOPT_MSS;
359 bits |= IP_FW_TCPOPT_WINDOW;
362 case TCPOPT_SACK_PERMITTED:
364 bits |= IP_FW_TCPOPT_SACK;
367 case TCPOPT_TIMESTAMP:
368 bits |= IP_FW_TCPOPT_TS;
373 return (flags_match(cmd, bits));
377 iface_match(struct ifnet *ifp, ipfw_insn_if *cmd, struct ip_fw_chain *chain,
381 if (ifp == NULL) /* no iface with this packet, match fails */
384 /* Check by name or by IP address */
385 if (cmd->name[0] != '\0') { /* match by name */
386 if (cmd->name[0] == '\1') /* use tablearg to match */
387 return ipfw_lookup_table(chain, cmd->p.kidx, 0,
388 &ifp->if_index, tablearg);
391 if (fnmatch(cmd->name, ifp->if_xname, 0) == 0)
394 if (strncmp(ifp->if_xname, cmd->name, IFNAMSIZ) == 0)
398 #if !defined(USERSPACE) && defined(__FreeBSD__) /* and OSX too ? */
402 TAILQ_FOREACH(ia, &ifp->if_addrhead, ifa_link) {
403 if (ia->ifa_addr->sa_family != AF_INET)
405 if (cmd->p.ip.s_addr == ((struct sockaddr_in *)
406 (ia->ifa_addr))->sin_addr.s_addr) {
407 if_addr_runlock(ifp);
408 return(1); /* match */
411 if_addr_runlock(ifp);
412 #endif /* __FreeBSD__ */
414 return(0); /* no match, fail ... */
418 * The verify_path function checks if a route to the src exists and
419 * if it is reachable via ifp (when provided).
421 * The 'verrevpath' option checks that the interface that an IP packet
422 * arrives on is the same interface that traffic destined for the
423 * packet's source address would be routed out of.
424 * The 'versrcreach' option just checks that the source address is
425 * reachable via any route (except default) in the routing table.
426 * These two are a measure to block forged packets. This is also
427 * commonly known as "anti-spoofing" or Unicast Reverse Path
428 * Forwarding (Unicast RFP) in Cisco-ese. The name of the knobs
429 * is purposely reminiscent of the Cisco IOS command,
431 * ip verify unicast reverse-path
432 * ip verify unicast source reachable-via any
434 * which implements the same functionality. But note that the syntax
435 * is misleading, and the check may be performed on all IP packets
436 * whether unicast, multicast, or broadcast.
439 verify_path(struct in_addr src, struct ifnet *ifp, u_int fib)
441 #if defined(USERSPACE) || !defined(__FreeBSD__)
444 struct nhop4_basic nh4;
446 if (fib4_lookup_nh_basic(fib, src, NHR_IFAIF, 0, &nh4) != 0)
450 * If ifp is provided, check for equality with rtentry.
451 * We should use rt->rt_ifa->ifa_ifp, instead of rt->rt_ifp,
452 * in order to pass packets injected back by if_simloop():
453 * routing entry (via lo0) for our own address
454 * may exist, so we need to handle routing assymetry.
456 if (ifp != NULL && ifp != nh4.nh_ifp)
459 /* if no ifp provided, check if rtentry is not default route */
460 if (ifp == NULL && (nh4.nh_flags & NHF_DEFAULT) != 0)
463 /* or if this is a blackhole/reject route */
464 if (ifp == NULL && (nh4.nh_flags & (NHF_REJECT|NHF_BLACKHOLE)) != 0)
467 /* found valid route */
469 #endif /* __FreeBSD__ */
474 * ipv6 specific rules here...
477 icmp6type_match (int type, ipfw_insn_u32 *cmd)
479 return (type <= ICMP6_MAXTYPE && (cmd->d[type/32] & (1<<(type%32)) ) );
483 flow6id_match( int curr_flow, ipfw_insn_u32 *cmd )
486 for (i=0; i <= cmd->o.arg1; ++i )
487 if (curr_flow == cmd->d[i] )
492 /* support for IP6_*_ME opcodes */
493 static const struct in6_addr lla_mask = {{{
494 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff,
495 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff
499 ipfw_localip6(struct in6_addr *in6)
501 struct rm_priotracker in6_ifa_tracker;
502 struct in6_ifaddr *ia;
504 if (IN6_IS_ADDR_MULTICAST(in6))
507 if (!IN6_IS_ADDR_LINKLOCAL(in6))
508 return (in6_localip(in6));
510 IN6_IFADDR_RLOCK(&in6_ifa_tracker);
511 TAILQ_FOREACH(ia, &V_in6_ifaddrhead, ia_link) {
512 if (!IN6_IS_ADDR_LINKLOCAL(&ia->ia_addr.sin6_addr))
514 if (IN6_ARE_MASKED_ADDR_EQUAL(&ia->ia_addr.sin6_addr,
516 IN6_IFADDR_RUNLOCK(&in6_ifa_tracker);
520 IN6_IFADDR_RUNLOCK(&in6_ifa_tracker);
525 verify_path6(struct in6_addr *src, struct ifnet *ifp, u_int fib)
527 struct nhop6_basic nh6;
529 if (IN6_IS_SCOPE_LINKLOCAL(src))
532 if (fib6_lookup_nh_basic(fib, src, 0, NHR_IFAIF, 0, &nh6) != 0)
535 /* If ifp is provided, check for equality with route table. */
536 if (ifp != NULL && ifp != nh6.nh_ifp)
539 /* if no ifp provided, check if rtentry is not default route */
540 if (ifp == NULL && (nh6.nh_flags & NHF_DEFAULT) != 0)
543 /* or if this is a blackhole/reject route */
544 if (ifp == NULL && (nh6.nh_flags & (NHF_REJECT|NHF_BLACKHOLE)) != 0)
547 /* found valid route */
552 is_icmp6_query(int icmp6_type)
554 if ((icmp6_type <= ICMP6_MAXTYPE) &&
555 (icmp6_type == ICMP6_ECHO_REQUEST ||
556 icmp6_type == ICMP6_MEMBERSHIP_QUERY ||
557 icmp6_type == ICMP6_WRUREQUEST ||
558 icmp6_type == ICMP6_FQDN_QUERY ||
559 icmp6_type == ICMP6_NI_QUERY))
566 send_reject6(struct ip_fw_args *args, int code, u_int hlen, struct ip6_hdr *ip6)
571 if (code == ICMP6_UNREACH_RST && args->f_id.proto == IPPROTO_TCP) {
573 tcp = (struct tcphdr *)((char *)ip6 + hlen);
575 if ((tcp->th_flags & TH_RST) == 0) {
577 m0 = ipfw_send_pkt(args->m, &(args->f_id),
578 ntohl(tcp->th_seq), ntohl(tcp->th_ack),
579 tcp->th_flags | TH_RST);
581 ip6_output(m0, NULL, NULL, 0, NULL, NULL,
585 } else if (code != ICMP6_UNREACH_RST) { /* Send an ICMPv6 unreach. */
588 * Unlike above, the mbufs need to line up with the ip6 hdr,
589 * as the contents are read. We need to m_adj() the
591 * The mbuf will however be thrown away so we can adjust it.
592 * Remember we did an m_pullup on it already so we
593 * can make some assumptions about contiguousness.
596 m_adj(m, args->L3offset);
598 icmp6_error(m, ICMP6_DST_UNREACH, code, 0);
609 * sends a reject message, consuming the mbuf passed as an argument.
612 send_reject(struct ip_fw_args *args, int code, int iplen, struct ip *ip)
616 /* XXX When ip is not guaranteed to be at mtod() we will
617 * need to account for this */
618 * The mbuf will however be thrown away so we can adjust it.
619 * Remember we did an m_pullup on it already so we
620 * can make some assumptions about contiguousness.
623 m_adj(m, args->L3offset);
625 if (code != ICMP_REJECT_RST) { /* Send an ICMP unreach */
626 icmp_error(args->m, ICMP_UNREACH, code, 0L, 0);
627 } else if (args->f_id.proto == IPPROTO_TCP) {
628 struct tcphdr *const tcp =
629 L3HDR(struct tcphdr, mtod(args->m, struct ip *));
630 if ( (tcp->th_flags & TH_RST) == 0) {
632 m = ipfw_send_pkt(args->m, &(args->f_id),
633 ntohl(tcp->th_seq), ntohl(tcp->th_ack),
634 tcp->th_flags | TH_RST);
636 ip_output(m, NULL, NULL, 0, NULL, NULL);
645 * Support for uid/gid/jail lookup. These tests are expensive
646 * (because we may need to look into the list of active sockets)
647 * so we cache the results. ugid_lookupp is 0 if we have not
648 * yet done a lookup, 1 if we succeeded, and -1 if we tried
649 * and failed. The function always returns the match value.
650 * We could actually spare the variable and use *uc, setting
651 * it to '(void *)check_uidgid if we have no info, NULL if
652 * we tried and failed, or any other value if successful.
655 check_uidgid(ipfw_insn_u32 *insn, struct ip_fw_args *args, int *ugid_lookupp,
658 #if defined(USERSPACE)
659 return 0; // not supported in userspace
663 return cred_check(insn, proto, oif,
664 dst_ip, dst_port, src_ip, src_port,
665 (struct bsd_ucred *)uc, ugid_lookupp, ((struct mbuf *)inp)->m_skb);
667 struct in_addr src_ip, dst_ip;
668 struct inpcbinfo *pi;
669 struct ipfw_flow_id *id;
670 struct inpcb *pcb, *inp;
680 * Check to see if the UDP or TCP stack supplied us with
681 * the PCB. If so, rather then holding a lock and looking
682 * up the PCB, we can use the one that was supplied.
684 if (inp && *ugid_lookupp == 0) {
685 INP_LOCK_ASSERT(inp);
686 if (inp->inp_socket != NULL) {
687 *uc = crhold(inp->inp_cred);
693 * If we have already been here and the packet has no
694 * PCB entry associated with it, then we can safely
695 * assume that this is a no match.
697 if (*ugid_lookupp == -1)
699 if (id->proto == IPPROTO_TCP) {
702 } else if (id->proto == IPPROTO_UDP) {
703 lookupflags = INPLOOKUP_WILDCARD;
707 lookupflags |= INPLOOKUP_RLOCKPCB;
709 if (*ugid_lookupp == 0) {
710 if (id->addr_type == 6) {
713 pcb = in6_pcblookup_mbuf(pi,
714 &id->src_ip6, htons(id->src_port),
715 &id->dst_ip6, htons(id->dst_port),
716 lookupflags, oif, args->m);
718 pcb = in6_pcblookup_mbuf(pi,
719 &id->dst_ip6, htons(id->dst_port),
720 &id->src_ip6, htons(id->src_port),
721 lookupflags, oif, args->m);
727 src_ip.s_addr = htonl(id->src_ip);
728 dst_ip.s_addr = htonl(id->dst_ip);
730 pcb = in_pcblookup_mbuf(pi,
731 src_ip, htons(id->src_port),
732 dst_ip, htons(id->dst_port),
733 lookupflags, oif, args->m);
735 pcb = in_pcblookup_mbuf(pi,
736 dst_ip, htons(id->dst_port),
737 src_ip, htons(id->src_port),
738 lookupflags, oif, args->m);
741 INP_RLOCK_ASSERT(pcb);
742 *uc = crhold(pcb->inp_cred);
746 if (*ugid_lookupp == 0) {
748 * We tried and failed, set the variable to -1
749 * so we will not try again on this packet.
755 if (insn->o.opcode == O_UID)
756 match = ((*uc)->cr_uid == (uid_t)insn->d[0]);
757 else if (insn->o.opcode == O_GID)
758 match = groupmember((gid_t)insn->d[0], *uc);
759 else if (insn->o.opcode == O_JAIL)
760 match = ((*uc)->cr_prison->pr_id == (int)insn->d[0]);
762 #endif /* __FreeBSD__ */
763 #endif /* not supported in userspace */
767 * Helper function to set args with info on the rule after the matching
768 * one. slot is precise, whereas we guess rule_id as they are
769 * assigned sequentially.
772 set_match(struct ip_fw_args *args, int slot,
773 struct ip_fw_chain *chain)
775 args->rule.chain_id = chain->id;
776 args->rule.slot = slot + 1; /* we use 0 as a marker */
777 args->rule.rule_id = 1 + chain->map[slot]->id;
778 args->rule.rulenum = chain->map[slot]->rulenum;
781 #ifndef LINEAR_SKIPTO
783 * Helper function to enable cached rule lookups using
784 * cached_id and cached_pos fields in ipfw rule.
787 jump_fast(struct ip_fw_chain *chain, struct ip_fw *f, int num,
788 int tablearg, int jump_backwards)
792 /* If possible use cached f_pos (in f->cached_pos),
793 * whose version is written in f->cached_id
794 * (horrible hacks to avoid changing the ABI).
796 if (num != IP_FW_TARG && f->cached_id == chain->id)
797 f_pos = f->cached_pos;
799 int i = IP_FW_ARG_TABLEARG(chain, num, skipto);
800 /* make sure we do not jump backward */
801 if (jump_backwards == 0 && i <= f->rulenum)
803 if (chain->idxmap != NULL)
804 f_pos = chain->idxmap[i];
806 f_pos = ipfw_find_rule(chain, i, 0);
807 /* update the cache */
808 if (num != IP_FW_TARG) {
809 f->cached_id = chain->id;
810 f->cached_pos = f_pos;
818 * Helper function to enable real fast rule lookups.
821 jump_linear(struct ip_fw_chain *chain, struct ip_fw *f, int num,
822 int tablearg, int jump_backwards)
826 num = IP_FW_ARG_TABLEARG(chain, num, skipto);
827 /* make sure we do not jump backward */
828 if (jump_backwards == 0 && num <= f->rulenum)
829 num = f->rulenum + 1;
830 f_pos = chain->idxmap[num];
836 #define TARG(k, f) IP_FW_ARG_TABLEARG(chain, k, f)
838 * The main check routine for the firewall.
840 * All arguments are in args so we can modify them and return them
841 * back to the caller.
845 * args->m (in/out) The packet; we set to NULL when/if we nuke it.
846 * Starts with the IP header.
847 * args->eh (in) Mac header if present, NULL for layer3 packet.
848 * args->L3offset Number of bytes bypassed if we came from L2.
849 * e.g. often sizeof(eh) ** NOTYET **
850 * args->oif Outgoing interface, NULL if packet is incoming.
851 * The incoming interface is in the mbuf. (in)
852 * args->divert_rule (in/out)
853 * Skip up to the first rule past this rule number;
854 * upon return, non-zero port number for divert or tee.
856 * args->rule Pointer to the last matching rule (in/out)
857 * args->next_hop Socket we are forwarding to (out).
858 * args->next_hop6 IPv6 next hop we are forwarding to (out).
859 * args->f_id Addresses grabbed from the packet (out)
860 * args->rule.info a cookie depending on rule action
864 * IP_FW_PASS the packet must be accepted
865 * IP_FW_DENY the packet must be dropped
866 * IP_FW_DIVERT divert packet, port in m_tag
867 * IP_FW_TEE tee packet, port in m_tag
868 * IP_FW_DUMMYNET to dummynet, pipe in args->cookie
869 * IP_FW_NETGRAPH into netgraph, cookie args->cookie
870 * args->rule contains the matching rule,
871 * args->rule.info has additional information.
875 ipfw_chk(struct ip_fw_args *args)
879 * Local variables holding state while processing a packet:
881 * IMPORTANT NOTE: to speed up the processing of rules, there
882 * are some assumption on the values of the variables, which
883 * are documented here. Should you change them, please check
884 * the implementation of the various instructions to make sure
885 * that they still work.
887 * args->eh The MAC header. It is non-null for a layer2
888 * packet, it is NULL for a layer-3 packet.
890 * args->L3offset Offset in the packet to the L3 (IP or equiv.) header.
892 * m | args->m Pointer to the mbuf, as received from the caller.
893 * It may change if ipfw_chk() does an m_pullup, or if it
894 * consumes the packet because it calls send_reject().
895 * XXX This has to change, so that ipfw_chk() never modifies
896 * or consumes the buffer.
897 * ip is the beginning of the ip(4 or 6) header.
898 * Calculated by adding the L3offset to the start of data.
899 * (Until we start using L3offset, the packet is
900 * supposed to start with the ip header).
902 struct mbuf *m = args->m;
903 struct ip *ip = mtod(m, struct ip *);
906 * For rules which contain uid/gid or jail constraints, cache
907 * a copy of the users credentials after the pcb lookup has been
908 * executed. This will speed up the processing of rules with
909 * these types of constraints, as well as decrease contention
910 * on pcb related locks.
913 struct bsd_ucred ucred_cache;
915 struct ucred *ucred_cache = NULL;
917 int ucred_lookup = 0;
920 * oif | args->oif If NULL, ipfw_chk has been called on the
921 * inbound path (ether_input, ip_input).
922 * If non-NULL, ipfw_chk has been called on the outbound path
923 * (ether_output, ip_output).
925 struct ifnet *oif = args->oif;
927 int f_pos = 0; /* index of current rule in the array */
931 * hlen The length of the IP header.
933 u_int hlen = 0; /* hlen >0 means we have an IP pkt */
936 * offset The offset of a fragment. offset != 0 means that
937 * we have a fragment at this offset of an IPv4 packet.
938 * offset == 0 means that (if this is an IPv4 packet)
939 * this is the first or only fragment.
940 * For IPv6 offset|ip6f_mf == 0 means there is no Fragment Header
941 * or there is a single packet fragment (fragment header added
942 * without needed). We will treat a single packet fragment as if
943 * there was no fragment header (or log/block depending on the
944 * V_fw_permit_single_frag6 sysctl setting).
950 * Local copies of addresses. They are only valid if we have
953 * proto The protocol. Set to 0 for non-ip packets,
954 * or to the protocol read from the packet otherwise.
955 * proto != 0 means that we have an IPv4 packet.
957 * src_port, dst_port port numbers, in HOST format. Only
958 * valid for TCP and UDP packets.
960 * src_ip, dst_ip ip addresses, in NETWORK format.
961 * Only valid for IPv4 packets.
964 uint16_t src_port = 0, dst_port = 0; /* NOTE: host format */
965 struct in_addr src_ip, dst_ip; /* NOTE: network format */
968 uint16_t etype = 0; /* Host order stored ether type */
971 * dyn_dir = MATCH_UNKNOWN when rules unchecked,
972 * MATCH_NONE when checked and not matched (q = NULL),
973 * MATCH_FORWARD or MATCH_REVERSE otherwise (q != NULL)
975 int dyn_dir = MATCH_UNKNOWN;
976 uint16_t dyn_name = 0;
977 ipfw_dyn_rule *q = NULL;
978 struct ip_fw_chain *chain = &V_layer3_chain;
981 * We store in ulp a pointer to the upper layer protocol header.
982 * In the ipv4 case this is easy to determine from the header,
983 * but for ipv6 we might have some additional headers in the middle.
984 * ulp is NULL if not found.
986 void *ulp = NULL; /* upper layer protocol pointer. */
988 /* XXX ipv6 variables */
990 uint8_t icmp6_type = 0;
991 uint16_t ext_hd = 0; /* bits vector for extension header filtering */
992 /* end of ipv6 variables */
996 int done = 0; /* flag to exit the outer loop */
998 if (m->m_flags & M_SKIP_FIREWALL || (! V_ipfw_vnet_ready))
999 return (IP_FW_PASS); /* accept */
1001 dst_ip.s_addr = 0; /* make sure it is initialized */
1002 src_ip.s_addr = 0; /* make sure it is initialized */
1003 pktlen = m->m_pkthdr.len;
1004 args->f_id.fib = M_GETFIB(m); /* note mbuf not altered) */
1005 proto = args->f_id.proto = 0; /* mark f_id invalid */
1006 /* XXX 0 is a valid proto: IP/IPv6 Hop-by-Hop Option */
1009 * PULLUP_TO(len, p, T) makes sure that len + sizeof(T) is contiguous,
1010 * then it sets p to point at the offset "len" in the mbuf. WARNING: the
1011 * pointer might become stale after other pullups (but we never use it
1014 #define PULLUP_TO(_len, p, T) PULLUP_LEN(_len, p, sizeof(T))
1015 #define PULLUP_LEN(_len, p, T) \
1017 int x = (_len) + T; \
1018 if ((m)->m_len < x) { \
1019 args->m = m = m_pullup(m, x); \
1021 goto pullup_failed; \
1023 p = (mtod(m, char *) + (_len)); \
1027 * if we have an ether header,
1030 etype = ntohs(args->eh->ether_type);
1032 /* Identify IP packets and fill up variables. */
1033 if (pktlen >= sizeof(struct ip6_hdr) &&
1034 (args->eh == NULL || etype == ETHERTYPE_IPV6) && ip->ip_v == 6) {
1035 struct ip6_hdr *ip6 = (struct ip6_hdr *)ip;
1037 args->f_id.addr_type = 6;
1038 hlen = sizeof(struct ip6_hdr);
1039 proto = ip6->ip6_nxt;
1041 /* Search extension headers to find upper layer protocols */
1042 while (ulp == NULL && offset == 0) {
1044 case IPPROTO_ICMPV6:
1045 PULLUP_TO(hlen, ulp, struct icmp6_hdr);
1046 icmp6_type = ICMP6(ulp)->icmp6_type;
1050 PULLUP_TO(hlen, ulp, struct tcphdr);
1051 dst_port = TCP(ulp)->th_dport;
1052 src_port = TCP(ulp)->th_sport;
1053 /* save flags for dynamic rules */
1054 args->f_id._flags = TCP(ulp)->th_flags;
1058 PULLUP_TO(hlen, ulp, struct sctphdr);
1059 src_port = SCTP(ulp)->src_port;
1060 dst_port = SCTP(ulp)->dest_port;
1064 PULLUP_TO(hlen, ulp, struct udphdr);
1065 dst_port = UDP(ulp)->uh_dport;
1066 src_port = UDP(ulp)->uh_sport;
1069 case IPPROTO_HOPOPTS: /* RFC 2460 */
1070 PULLUP_TO(hlen, ulp, struct ip6_hbh);
1071 ext_hd |= EXT_HOPOPTS;
1072 hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3;
1073 proto = ((struct ip6_hbh *)ulp)->ip6h_nxt;
1077 case IPPROTO_ROUTING: /* RFC 2460 */
1078 PULLUP_TO(hlen, ulp, struct ip6_rthdr);
1079 switch (((struct ip6_rthdr *)ulp)->ip6r_type) {
1081 ext_hd |= EXT_RTHDR0;
1084 ext_hd |= EXT_RTHDR2;
1088 printf("IPFW2: IPV6 - Unknown "
1089 "Routing Header type(%d)\n",
1090 ((struct ip6_rthdr *)
1092 if (V_fw_deny_unknown_exthdrs)
1093 return (IP_FW_DENY);
1096 ext_hd |= EXT_ROUTING;
1097 hlen += (((struct ip6_rthdr *)ulp)->ip6r_len + 1) << 3;
1098 proto = ((struct ip6_rthdr *)ulp)->ip6r_nxt;
1102 case IPPROTO_FRAGMENT: /* RFC 2460 */
1103 PULLUP_TO(hlen, ulp, struct ip6_frag);
1104 ext_hd |= EXT_FRAGMENT;
1105 hlen += sizeof (struct ip6_frag);
1106 proto = ((struct ip6_frag *)ulp)->ip6f_nxt;
1107 offset = ((struct ip6_frag *)ulp)->ip6f_offlg &
1109 ip6f_mf = ((struct ip6_frag *)ulp)->ip6f_offlg &
1111 if (V_fw_permit_single_frag6 == 0 &&
1112 offset == 0 && ip6f_mf == 0) {
1114 printf("IPFW2: IPV6 - Invalid "
1115 "Fragment Header\n");
1116 if (V_fw_deny_unknown_exthdrs)
1117 return (IP_FW_DENY);
1121 ntohl(((struct ip6_frag *)ulp)->ip6f_ident);
1125 case IPPROTO_DSTOPTS: /* RFC 2460 */
1126 PULLUP_TO(hlen, ulp, struct ip6_hbh);
1127 ext_hd |= EXT_DSTOPTS;
1128 hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3;
1129 proto = ((struct ip6_hbh *)ulp)->ip6h_nxt;
1133 case IPPROTO_AH: /* RFC 2402 */
1134 PULLUP_TO(hlen, ulp, struct ip6_ext);
1136 hlen += (((struct ip6_ext *)ulp)->ip6e_len + 2) << 2;
1137 proto = ((struct ip6_ext *)ulp)->ip6e_nxt;
1141 case IPPROTO_ESP: /* RFC 2406 */
1142 PULLUP_TO(hlen, ulp, uint32_t); /* SPI, Seq# */
1143 /* Anything past Seq# is variable length and
1144 * data past this ext. header is encrypted. */
1148 case IPPROTO_NONE: /* RFC 2460 */
1150 * Packet ends here, and IPv6 header has
1151 * already been pulled up. If ip6e_len!=0
1152 * then octets must be ignored.
1154 ulp = ip; /* non-NULL to get out of loop. */
1157 case IPPROTO_OSPFIGP:
1158 /* XXX OSPF header check? */
1159 PULLUP_TO(hlen, ulp, struct ip6_ext);
1163 /* XXX PIM header check? */
1164 PULLUP_TO(hlen, ulp, struct pim);
1167 case IPPROTO_GRE: /* RFC 1701 */
1168 /* XXX GRE header check? */
1169 PULLUP_TO(hlen, ulp, struct grehdr);
1173 PULLUP_TO(hlen, ulp, struct carp_header);
1174 if (((struct carp_header *)ulp)->carp_version !=
1176 return (IP_FW_DENY);
1177 if (((struct carp_header *)ulp)->carp_type !=
1179 return (IP_FW_DENY);
1182 case IPPROTO_IPV6: /* RFC 2893 */
1183 PULLUP_TO(hlen, ulp, struct ip6_hdr);
1186 case IPPROTO_IPV4: /* RFC 2893 */
1187 PULLUP_TO(hlen, ulp, struct ip);
1192 printf("IPFW2: IPV6 - Unknown "
1193 "Extension Header(%d), ext_hd=%x\n",
1195 if (V_fw_deny_unknown_exthdrs)
1196 return (IP_FW_DENY);
1197 PULLUP_TO(hlen, ulp, struct ip6_ext);
1201 ip = mtod(m, struct ip *);
1202 ip6 = (struct ip6_hdr *)ip;
1203 args->f_id.src_ip6 = ip6->ip6_src;
1204 args->f_id.dst_ip6 = ip6->ip6_dst;
1205 args->f_id.src_ip = 0;
1206 args->f_id.dst_ip = 0;
1207 args->f_id.flow_id6 = ntohl(ip6->ip6_flow);
1208 iplen = ntohs(ip6->ip6_plen) + sizeof(*ip6);
1209 } else if (pktlen >= sizeof(struct ip) &&
1210 (args->eh == NULL || etype == ETHERTYPE_IP) && ip->ip_v == 4) {
1212 hlen = ip->ip_hl << 2;
1213 args->f_id.addr_type = 4;
1216 * Collect parameters into local variables for faster matching.
1219 src_ip = ip->ip_src;
1220 dst_ip = ip->ip_dst;
1221 offset = ntohs(ip->ip_off) & IP_OFFMASK;
1222 iplen = ntohs(ip->ip_len);
1227 PULLUP_TO(hlen, ulp, struct tcphdr);
1228 dst_port = TCP(ulp)->th_dport;
1229 src_port = TCP(ulp)->th_sport;
1230 /* save flags for dynamic rules */
1231 args->f_id._flags = TCP(ulp)->th_flags;
1235 PULLUP_TO(hlen, ulp, struct sctphdr);
1236 src_port = SCTP(ulp)->src_port;
1237 dst_port = SCTP(ulp)->dest_port;
1241 PULLUP_TO(hlen, ulp, struct udphdr);
1242 dst_port = UDP(ulp)->uh_dport;
1243 src_port = UDP(ulp)->uh_sport;
1247 PULLUP_TO(hlen, ulp, struct icmphdr);
1248 //args->f_id.flags = ICMP(ulp)->icmp_type;
1256 ip = mtod(m, struct ip *);
1257 args->f_id.src_ip = ntohl(src_ip.s_addr);
1258 args->f_id.dst_ip = ntohl(dst_ip.s_addr);
1261 pktlen = iplen < pktlen ? iplen: pktlen;
1262 if (proto) { /* we may have port numbers, store them */
1263 args->f_id.proto = proto;
1264 args->f_id.src_port = src_port = ntohs(src_port);
1265 args->f_id.dst_port = dst_port = ntohs(dst_port);
1268 IPFW_PF_RLOCK(chain);
1269 if (! V_ipfw_vnet_ready) { /* shutting down, leave NOW. */
1270 IPFW_PF_RUNLOCK(chain);
1271 return (IP_FW_PASS); /* accept */
1273 if (args->rule.slot) {
1275 * Packet has already been tagged as a result of a previous
1276 * match on rule args->rule aka args->rule_id (PIPE, QUEUE,
1277 * REASS, NETGRAPH, DIVERT/TEE...)
1278 * Validate the slot and continue from the next one
1279 * if still present, otherwise do a lookup.
1281 f_pos = (args->rule.chain_id == chain->id) ?
1283 ipfw_find_rule(chain, args->rule.rulenum,
1284 args->rule.rule_id);
1290 * Now scan the rules, and parse microinstructions for each rule.
1291 * We have two nested loops and an inner switch. Sometimes we
1292 * need to break out of one or both loops, or re-enter one of
1293 * the loops with updated variables. Loop variables are:
1295 * f_pos (outer loop) points to the current rule.
1296 * On output it points to the matching rule.
1297 * done (outer loop) is used as a flag to break the loop.
1298 * l (inner loop) residual length of current rule.
1299 * cmd points to the current microinstruction.
1301 * We break the inner loop by setting l=0 and possibly
1302 * cmdlen=0 if we don't want to advance cmd.
1303 * We break the outer loop by setting done=1
1304 * We can restart the inner loop by setting l>0 and f_pos, f, cmd
1307 for (; f_pos < chain->n_rules; f_pos++) {
1309 uint32_t tablearg = 0;
1310 int l, cmdlen, skip_or; /* skip rest of OR block */
1313 f = chain->map[f_pos];
1314 if (V_set_disable & (1 << f->set) )
1318 for (l = f->cmd_len, cmd = f->cmd ; l > 0 ;
1319 l -= cmdlen, cmd += cmdlen) {
1323 * check_body is a jump target used when we find a
1324 * CHECK_STATE, and need to jump to the body of
1329 cmdlen = F_LEN(cmd);
1331 * An OR block (insn_1 || .. || insn_n) has the
1332 * F_OR bit set in all but the last instruction.
1333 * The first match will set "skip_or", and cause
1334 * the following instructions to be skipped until
1335 * past the one with the F_OR bit clear.
1337 if (skip_or) { /* skip this instruction */
1338 if ((cmd->len & F_OR) == 0)
1339 skip_or = 0; /* next one is good */
1342 match = 0; /* set to 1 if we succeed */
1344 switch (cmd->opcode) {
1346 * The first set of opcodes compares the packet's
1347 * fields with some pattern, setting 'match' if a
1348 * match is found. At the end of the loop there is
1349 * logic to deal with F_NOT and F_OR flags associated
1357 printf("ipfw: opcode %d unimplemented\n",
1365 * We only check offset == 0 && proto != 0,
1366 * as this ensures that we have a
1367 * packet with the ports info.
1371 if (proto == IPPROTO_TCP ||
1372 proto == IPPROTO_UDP)
1373 match = check_uidgid(
1374 (ipfw_insn_u32 *)cmd,
1375 args, &ucred_lookup,
1379 (void *)&ucred_cache);
1384 match = iface_match(m->m_pkthdr.rcvif,
1385 (ipfw_insn_if *)cmd, chain, &tablearg);
1389 match = iface_match(oif, (ipfw_insn_if *)cmd,
1394 match = iface_match(oif ? oif :
1395 m->m_pkthdr.rcvif, (ipfw_insn_if *)cmd,
1400 if (args->eh != NULL) { /* have MAC header */
1401 u_int32_t *want = (u_int32_t *)
1402 ((ipfw_insn_mac *)cmd)->addr;
1403 u_int32_t *mask = (u_int32_t *)
1404 ((ipfw_insn_mac *)cmd)->mask;
1405 u_int32_t *hdr = (u_int32_t *)args->eh;
1408 ( want[0] == (hdr[0] & mask[0]) &&
1409 want[1] == (hdr[1] & mask[1]) &&
1410 want[2] == (hdr[2] & mask[2]) );
1415 if (args->eh != NULL) {
1417 ((ipfw_insn_u16 *)cmd)->ports;
1420 for (i = cmdlen - 1; !match && i>0;
1422 match = (etype >= p[0] &&
1428 match = (offset != 0);
1431 case O_IN: /* "out" is "not in" */
1432 match = (oif == NULL);
1436 match = (args->eh != NULL);
1441 /* For diverted packets, args->rule.info
1442 * contains the divert port (in host format)
1443 * reason and direction.
1445 uint32_t i = args->rule.info;
1446 match = (i&IPFW_IS_MASK) == IPFW_IS_DIVERT &&
1447 cmd->arg1 & ((i & IPFW_INFO_IN) ? 1 : 2);
1453 * We do not allow an arg of 0 so the
1454 * check of "proto" only suffices.
1456 match = (proto == cmd->arg1);
1461 (((ipfw_insn_ip *)cmd)->addr.s_addr ==
1465 case O_IP_DST_LOOKUP:
1471 if (cmdlen > F_INSN_SIZE(ipfw_insn_u32)) {
1472 /* Determine lookup key type */
1473 vidx = ((ipfw_insn_u32 *)cmd)->d[1];
1474 if (vidx != 4 /* uid */ &&
1475 vidx != 5 /* jail */ &&
1476 is_ipv6 == 0 && is_ipv4 == 0)
1478 /* Determine key length */
1479 if (vidx == 0 /* dst-ip */ ||
1480 vidx == 1 /* src-ip */)
1482 sizeof(struct in6_addr):
1485 keylen = sizeof(key);
1488 if (vidx == 0 /* dst-ip */)
1489 pkey = is_ipv4 ? (void *)&dst_ip:
1490 (void *)&args->f_id.dst_ip6;
1491 else if (vidx == 1 /* src-ip */)
1492 pkey = is_ipv4 ? (void *)&src_ip:
1493 (void *)&args->f_id.src_ip6;
1494 else if (vidx == 6 /* dscp */) {
1496 key = ip->ip_tos >> 2;
1498 key = args->f_id.flow_id6;
1499 key = (key & 0x0f) << 2 |
1500 (key & 0xf000) >> 14;
1503 } else if (vidx == 2 /* dst-port */ ||
1504 vidx == 3 /* src-port */) {
1505 /* Skip fragments */
1508 /* Skip proto without ports */
1509 if (proto != IPPROTO_TCP &&
1510 proto != IPPROTO_UDP &&
1511 proto != IPPROTO_SCTP)
1513 if (vidx == 2 /* dst-port */)
1519 else if (vidx == 4 /* uid */ ||
1520 vidx == 5 /* jail */) {
1522 (ipfw_insn_u32 *)cmd,
1523 args, &ucred_lookup,
1526 if (vidx == 4 /* uid */)
1527 key = ucred_cache->cr_uid;
1528 else if (vidx == 5 /* jail */)
1529 key = ucred_cache->cr_prison->pr_id;
1530 #else /* !__FreeBSD__ */
1531 (void *)&ucred_cache);
1532 if (vidx == 4 /* uid */)
1533 key = ucred_cache.uid;
1534 else if (vidx == 5 /* jail */)
1535 key = ucred_cache.xid;
1536 #endif /* !__FreeBSD__ */
1538 #endif /* !USERSPACE */
1541 match = ipfw_lookup_table(chain,
1542 cmd->arg1, keylen, pkey, &vidx);
1548 /* cmdlen =< F_INSN_SIZE(ipfw_insn_u32) */
1551 case O_IP_SRC_LOOKUP:
1558 keylen = sizeof(in_addr_t);
1559 if (cmd->opcode == O_IP_DST_LOOKUP)
1563 } else if (is_ipv6) {
1564 keylen = sizeof(struct in6_addr);
1565 if (cmd->opcode == O_IP_DST_LOOKUP)
1566 pkey = &args->f_id.dst_ip6;
1568 pkey = &args->f_id.src_ip6;
1571 match = ipfw_lookup_table(chain, cmd->arg1,
1572 keylen, pkey, &vidx);
1575 if (cmdlen == F_INSN_SIZE(ipfw_insn_u32)) {
1576 match = ((ipfw_insn_u32 *)cmd)->d[0] ==
1577 TARG_VAL(chain, vidx, tag);
1585 case O_IP_FLOW_LOOKUP:
1588 match = ipfw_lookup_table(chain,
1589 cmd->arg1, 0, &args->f_id, &v);
1590 if (cmdlen == F_INSN_SIZE(ipfw_insn_u32))
1591 match = ((ipfw_insn_u32 *)cmd)->d[0] ==
1592 TARG_VAL(chain, v, tag);
1601 (cmd->opcode == O_IP_DST_MASK) ?
1602 dst_ip.s_addr : src_ip.s_addr;
1603 uint32_t *p = ((ipfw_insn_u32 *)cmd)->d;
1606 for (; !match && i>0; i-= 2, p+= 2)
1607 match = (p[0] == (a & p[1]));
1613 match = in_localip(src_ip);
1619 match= is_ipv6 && ipfw_localip6(&args->f_id.src_ip6);
1626 u_int32_t *d = (u_int32_t *)(cmd+1);
1628 cmd->opcode == O_IP_DST_SET ?
1634 addr -= d[0]; /* subtract base */
1635 match = (addr < cmd->arg1) &&
1636 ( d[ 1 + (addr>>5)] &
1637 (1<<(addr & 0x1f)) );
1643 (((ipfw_insn_ip *)cmd)->addr.s_addr ==
1649 match = in_localip(dst_ip);
1655 match= is_ipv6 && ipfw_localip6(&args->f_id.dst_ip6);
1663 * offset == 0 && proto != 0 is enough
1664 * to guarantee that we have a
1665 * packet with port info.
1667 if ((proto==IPPROTO_UDP || proto==IPPROTO_TCP ||
1668 proto==IPPROTO_SCTP) && offset == 0) {
1670 (cmd->opcode == O_IP_SRCPORT) ?
1671 src_port : dst_port ;
1673 ((ipfw_insn_u16 *)cmd)->ports;
1676 for (i = cmdlen - 1; !match && i>0;
1678 match = (x>=p[0] && x<=p[1]);
1683 match = (offset == 0 && proto==IPPROTO_ICMP &&
1684 icmptype_match(ICMP(ulp), (ipfw_insn_u32 *)cmd) );
1689 match = is_ipv6 && offset == 0 &&
1690 proto==IPPROTO_ICMPV6 &&
1692 ICMP6(ulp)->icmp6_type,
1693 (ipfw_insn_u32 *)cmd);
1699 ipopts_match(ip, cmd) );
1704 cmd->arg1 == ip->ip_v);
1710 if (is_ipv4) { /* only for IP packets */
1715 if (cmd->opcode == O_IPLEN)
1717 else if (cmd->opcode == O_IPTTL)
1719 else /* must be IPID */
1720 x = ntohs(ip->ip_id);
1722 match = (cmd->arg1 == x);
1725 /* otherwise we have ranges */
1726 p = ((ipfw_insn_u16 *)cmd)->ports;
1728 for (; !match && i>0; i--, p += 2)
1729 match = (x >= p[0] && x <= p[1]);
1733 case O_IPPRECEDENCE:
1735 (cmd->arg1 == (ip->ip_tos & 0xe0)) );
1740 flags_match(cmd, ip->ip_tos));
1748 p = ((ipfw_insn_u32 *)cmd)->d;
1751 x = ip->ip_tos >> 2;
1754 v = &((struct ip6_hdr *)ip)->ip6_vfc;
1755 x = (*v & 0x0F) << 2;
1761 /* DSCP bitmask is stored as low_u32 high_u32 */
1763 match = *(p + 1) & (1 << (x - 32));
1765 match = *p & (1 << x);
1770 if (proto == IPPROTO_TCP && offset == 0) {
1777 struct ip6_hdr *ip6;
1779 ip6 = (struct ip6_hdr *)ip;
1780 if (ip6->ip6_plen == 0) {
1782 * Jumbo payload is not
1791 x = iplen - (ip->ip_hl << 2);
1793 x -= tcp->th_off << 2;
1795 match = (cmd->arg1 == x);
1798 /* otherwise we have ranges */
1799 p = ((ipfw_insn_u16 *)cmd)->ports;
1801 for (; !match && i>0; i--, p += 2)
1802 match = (x >= p[0] && x <= p[1]);
1807 match = (proto == IPPROTO_TCP && offset == 0 &&
1808 flags_match(cmd, TCP(ulp)->th_flags));
1812 if (proto == IPPROTO_TCP && offset == 0 && ulp){
1813 PULLUP_LEN(hlen, ulp,
1814 (TCP(ulp)->th_off << 2));
1815 match = tcpopts_match(TCP(ulp), cmd);
1820 match = (proto == IPPROTO_TCP && offset == 0 &&
1821 ((ipfw_insn_u32 *)cmd)->d[0] ==
1826 match = (proto == IPPROTO_TCP && offset == 0 &&
1827 ((ipfw_insn_u32 *)cmd)->d[0] ==
1832 if (proto == IPPROTO_TCP && offset == 0) {
1837 x = ntohs(TCP(ulp)->th_win);
1839 match = (cmd->arg1 == x);
1842 /* Otherwise we have ranges. */
1843 p = ((ipfw_insn_u16 *)cmd)->ports;
1845 for (; !match && i > 0; i--, p += 2)
1846 match = (x >= p[0] && x <= p[1]);
1851 /* reject packets which have SYN only */
1852 /* XXX should i also check for TH_ACK ? */
1853 match = (proto == IPPROTO_TCP && offset == 0 &&
1854 (TCP(ulp)->th_flags &
1855 (TH_RST | TH_ACK | TH_SYN)) != TH_SYN);
1861 ipfw_insn_altq *altq = (ipfw_insn_altq *)cmd;
1864 * ALTQ uses mbuf tags from another
1865 * packet filtering system - pf(4).
1866 * We allocate a tag in its format
1867 * and fill it in, pretending to be pf(4).
1870 at = pf_find_mtag(m);
1871 if (at != NULL && at->qid != 0)
1873 mtag = m_tag_get(PACKET_TAG_PF,
1874 sizeof(struct pf_mtag), M_NOWAIT | M_ZERO);
1877 * Let the packet fall back to the
1882 m_tag_prepend(m, mtag);
1883 at = (struct pf_mtag *)(mtag + 1);
1884 at->qid = altq->qid;
1890 ipfw_log(chain, f, hlen, args, m,
1891 oif, offset | ip6f_mf, tablearg, ip);
1896 match = (random()<((ipfw_insn_u32 *)cmd)->d[0]);
1900 /* Outgoing packets automatically pass/match */
1901 match = ((oif != NULL) ||
1902 (m->m_pkthdr.rcvif == NULL) ||
1906 verify_path6(&(args->f_id.src_ip6),
1907 m->m_pkthdr.rcvif, args->f_id.fib) :
1909 verify_path(src_ip, m->m_pkthdr.rcvif,
1914 /* Outgoing packets automatically pass/match */
1915 match = (hlen > 0 && ((oif != NULL) ||
1918 verify_path6(&(args->f_id.src_ip6),
1919 NULL, args->f_id.fib) :
1921 verify_path(src_ip, NULL, args->f_id.fib)));
1925 /* Outgoing packets automatically pass/match */
1926 if (oif == NULL && hlen > 0 &&
1927 ( (is_ipv4 && in_localaddr(src_ip))
1930 in6_localaddr(&(args->f_id.src_ip6)))
1935 is_ipv6 ? verify_path6(
1936 &(args->f_id.src_ip6),
1949 match = (m_tag_find(m,
1950 PACKET_TAG_IPSEC_IN_DONE, NULL) != NULL);
1952 /* otherwise no match */
1958 IN6_ARE_ADDR_EQUAL(&args->f_id.src_ip6,
1959 &((ipfw_insn_ip6 *)cmd)->addr6);
1964 IN6_ARE_ADDR_EQUAL(&args->f_id.dst_ip6,
1965 &((ipfw_insn_ip6 *)cmd)->addr6);
1967 case O_IP6_SRC_MASK:
1968 case O_IP6_DST_MASK:
1972 struct in6_addr *d =
1973 &((ipfw_insn_ip6 *)cmd)->addr6;
1975 for (; !match && i > 0; d += 2,
1976 i -= F_INSN_SIZE(struct in6_addr)
1982 APPLY_MASK(&p, &d[1]);
1984 IN6_ARE_ADDR_EQUAL(&d[0],
1992 flow6id_match(args->f_id.flow_id6,
1993 (ipfw_insn_u32 *) cmd);
1998 (ext_hd & ((ipfw_insn *) cmd)->arg1);
2012 uint32_t tag = TARG(cmd->arg1, tag);
2014 /* Packet is already tagged with this tag? */
2015 mtag = m_tag_locate(m, MTAG_IPFW, tag, NULL);
2017 /* We have `untag' action when F_NOT flag is
2018 * present. And we must remove this mtag from
2019 * mbuf and reset `match' to zero (`match' will
2020 * be inversed later).
2021 * Otherwise we should allocate new mtag and
2022 * push it into mbuf.
2024 if (cmd->len & F_NOT) { /* `untag' action */
2026 m_tag_delete(m, mtag);
2030 mtag = m_tag_alloc( MTAG_IPFW,
2033 m_tag_prepend(m, mtag);
2040 case O_FIB: /* try match the specified fib */
2041 if (args->f_id.fib == cmd->arg1)
2046 #ifndef USERSPACE /* not supported in userspace */
2047 struct inpcb *inp = args->inp;
2048 struct inpcbinfo *pi;
2050 if (is_ipv6) /* XXX can we remove this ? */
2053 if (proto == IPPROTO_TCP)
2055 else if (proto == IPPROTO_UDP)
2061 * XXXRW: so_user_cookie should almost
2062 * certainly be inp_user_cookie?
2065 /* For incoming packet, lookup up the
2066 inpcb using the src/dest ip/port tuple */
2068 inp = in_pcblookup(pi,
2069 src_ip, htons(src_port),
2070 dst_ip, htons(dst_port),
2071 INPLOOKUP_RLOCKPCB, NULL);
2074 inp->inp_socket->so_user_cookie;
2080 if (inp->inp_socket) {
2082 inp->inp_socket->so_user_cookie;
2087 #endif /* !USERSPACE */
2093 uint32_t tag = TARG(cmd->arg1, tag);
2096 match = m_tag_locate(m, MTAG_IPFW,
2101 /* we have ranges */
2102 for (mtag = m_tag_first(m);
2103 mtag != NULL && !match;
2104 mtag = m_tag_next(m, mtag)) {
2108 if (mtag->m_tag_cookie != MTAG_IPFW)
2111 p = ((ipfw_insn_u16 *)cmd)->ports;
2113 for(; !match && i > 0; i--, p += 2)
2115 mtag->m_tag_id >= p[0] &&
2116 mtag->m_tag_id <= p[1];
2122 * The second set of opcodes represents 'actions',
2123 * i.e. the terminal part of a rule once the packet
2124 * matches all previous patterns.
2125 * Typically there is only one action for each rule,
2126 * and the opcode is stored at the end of the rule
2127 * (but there are exceptions -- see below).
2129 * In general, here we set retval and terminate the
2130 * outer loop (would be a 'break 3' in some language,
2131 * but we need to set l=0, done=1)
2134 * O_COUNT and O_SKIPTO actions:
2135 * instead of terminating, we jump to the next rule
2136 * (setting l=0), or to the SKIPTO target (setting
2137 * f/f_len, cmd and l as needed), respectively.
2139 * O_TAG, O_LOG and O_ALTQ action parameters:
2140 * perform some action and set match = 1;
2142 * O_LIMIT and O_KEEP_STATE: these opcodes are
2143 * not real 'actions', and are stored right
2144 * before the 'action' part of the rule.
2145 * These opcodes try to install an entry in the
2146 * state tables; if successful, we continue with
2147 * the next opcode (match=1; break;), otherwise
2148 * the packet must be dropped (set retval,
2149 * break loops with l=0, done=1)
2151 * O_PROBE_STATE and O_CHECK_STATE: these opcodes
2152 * cause a lookup of the state table, and a jump
2153 * to the 'action' part of the parent rule
2154 * if an entry is found, or
2155 * (CHECK_STATE only) a jump to the next rule if
2156 * the entry is not found.
2157 * The result of the lookup is cached so that
2158 * further instances of these opcodes become NOPs.
2159 * The jump to the next rule is done by setting
2164 if (ipfw_install_state(chain, f,
2165 (ipfw_insn_limit *)cmd, args, tablearg)) {
2166 /* error or limit violation */
2167 retval = IP_FW_DENY;
2168 l = 0; /* exit inner loop */
2169 done = 1; /* exit outer loop */
2177 * dynamic rules are checked at the first
2178 * keep-state or check-state occurrence,
2179 * with the result being stored in dyn_dir
2181 * The compiler introduces a PROBE_STATE
2182 * instruction for us when we have a
2183 * KEEP_STATE (because PROBE_STATE needs
2186 * (dyn_dir == MATCH_UNKNOWN) means this is
2187 * first lookup for such f_id. Do lookup.
2189 * (dyn_dir != MATCH_UNKNOWN &&
2190 * dyn_name != 0 && dyn_name != cmd->arg1)
2191 * means previous lookup didn't find dynamic
2192 * rule for specific state name and current
2193 * lookup will search rule with another state
2194 * name. Redo lookup.
2196 * (dyn_dir != MATCH_UNKNOWN && dyn_name == 0)
2197 * means previous lookup was for `any' name
2198 * and it didn't find rule. No need to do
2201 if ((dyn_dir == MATCH_UNKNOWN ||
2203 dyn_name != cmd->arg1)) &&
2204 (q = ipfw_lookup_dyn_rule(&args->f_id,
2205 &dyn_dir, proto == IPPROTO_TCP ?
2207 (dyn_name = cmd->arg1))) != NULL) {
2209 * Found dynamic entry, update stats
2210 * and jump to the 'action' part of
2211 * the parent rule by setting
2212 * f, cmd, l and clearing cmdlen.
2214 IPFW_INC_DYN_COUNTER(q, pktlen);
2215 /* XXX we would like to have f_pos
2216 * readily accessible in the dynamic
2217 * rule, instead of having to
2221 f_pos = ipfw_find_rule(chain,
2223 cmd = ACTION_PTR(f);
2224 l = f->cmd_len - f->act_ofs;
2231 * Dynamic entry not found. If CHECK_STATE,
2232 * skip to next rule, if PROBE_STATE just
2233 * ignore and continue with next opcode.
2235 if (cmd->opcode == O_CHECK_STATE)
2236 l = 0; /* exit inner loop */
2241 retval = 0; /* accept */
2242 l = 0; /* exit inner loop */
2243 done = 1; /* exit outer loop */
2248 set_match(args, f_pos, chain);
2249 args->rule.info = TARG(cmd->arg1, pipe);
2250 if (cmd->opcode == O_PIPE)
2251 args->rule.info |= IPFW_IS_PIPE;
2253 args->rule.info |= IPFW_ONEPASS;
2254 retval = IP_FW_DUMMYNET;
2255 l = 0; /* exit inner loop */
2256 done = 1; /* exit outer loop */
2261 if (args->eh) /* not on layer 2 */
2263 /* otherwise this is terminal */
2264 l = 0; /* exit inner loop */
2265 done = 1; /* exit outer loop */
2266 retval = (cmd->opcode == O_DIVERT) ?
2267 IP_FW_DIVERT : IP_FW_TEE;
2268 set_match(args, f_pos, chain);
2269 args->rule.info = TARG(cmd->arg1, divert);
2273 IPFW_INC_RULE_COUNTER(f, pktlen);
2274 l = 0; /* exit inner loop */
2278 IPFW_INC_RULE_COUNTER(f, pktlen);
2279 f_pos = JUMP(chain, f, cmd->arg1, tablearg, 0);
2281 * Skip disabled rules, and re-enter
2282 * the inner loop with the correct
2283 * f_pos, f, l and cmd.
2284 * Also clear cmdlen and skip_or
2286 for (; f_pos < chain->n_rules - 1 &&
2288 (1 << chain->map[f_pos]->set));
2291 /* Re-enter the inner loop at the skipto rule. */
2292 f = chain->map[f_pos];
2299 break; /* not reached */
2301 case O_CALLRETURN: {
2303 * Implementation of `subroutine' call/return,
2304 * in the stack carried in an mbuf tag. This
2305 * is different from `skipto' in that any call
2306 * address is possible (`skipto' must prevent
2307 * backward jumps to avoid endless loops).
2308 * We have `return' action when F_NOT flag is
2309 * present. The `m_tag_id' field is used as
2313 uint16_t jmpto, *stack;
2315 #define IS_CALL ((cmd->len & F_NOT) == 0)
2316 #define IS_RETURN ((cmd->len & F_NOT) != 0)
2318 * Hand-rolled version of m_tag_locate() with
2320 * If not already tagged, allocate new tag.
2322 mtag = m_tag_first(m);
2323 while (mtag != NULL) {
2324 if (mtag->m_tag_cookie ==
2327 mtag = m_tag_next(m, mtag);
2329 if (mtag == NULL && IS_CALL) {
2330 mtag = m_tag_alloc(MTAG_IPFW_CALL, 0,
2331 IPFW_CALLSTACK_SIZE *
2332 sizeof(uint16_t), M_NOWAIT);
2334 m_tag_prepend(m, mtag);
2338 * On error both `call' and `return' just
2339 * continue with next rule.
2341 if (IS_RETURN && (mtag == NULL ||
2342 mtag->m_tag_id == 0)) {
2343 l = 0; /* exit inner loop */
2346 if (IS_CALL && (mtag == NULL ||
2347 mtag->m_tag_id >= IPFW_CALLSTACK_SIZE)) {
2348 printf("ipfw: call stack error, "
2349 "go to next rule\n");
2350 l = 0; /* exit inner loop */
2354 IPFW_INC_RULE_COUNTER(f, pktlen);
2355 stack = (uint16_t *)(mtag + 1);
2358 * The `call' action may use cached f_pos
2359 * (in f->next_rule), whose version is written
2361 * The `return' action, however, doesn't have
2362 * fixed jump address in cmd->arg1 and can't use
2366 stack[mtag->m_tag_id] = f->rulenum;
2368 f_pos = JUMP(chain, f, cmd->arg1,
2370 } else { /* `return' action */
2372 jmpto = stack[mtag->m_tag_id] + 1;
2373 f_pos = ipfw_find_rule(chain, jmpto, 0);
2377 * Skip disabled rules, and re-enter
2378 * the inner loop with the correct
2379 * f_pos, f, l and cmd.
2380 * Also clear cmdlen and skip_or
2382 for (; f_pos < chain->n_rules - 1 &&
2384 (1 << chain->map[f_pos]->set)); f_pos++)
2386 /* Re-enter the inner loop at the dest rule. */
2387 f = chain->map[f_pos];
2393 break; /* NOTREACHED */
2400 * Drop the packet and send a reject notice
2401 * if the packet is not ICMP (or is an ICMP
2402 * query), and it is not multicast/broadcast.
2404 if (hlen > 0 && is_ipv4 && offset == 0 &&
2405 (proto != IPPROTO_ICMP ||
2406 is_icmp_query(ICMP(ulp))) &&
2407 !(m->m_flags & (M_BCAST|M_MCAST)) &&
2408 !IN_MULTICAST(ntohl(dst_ip.s_addr))) {
2409 send_reject(args, cmd->arg1, iplen, ip);
2415 if (hlen > 0 && is_ipv6 &&
2416 ((offset & IP6F_OFF_MASK) == 0) &&
2417 (proto != IPPROTO_ICMPV6 ||
2418 (is_icmp6_query(icmp6_type) == 1)) &&
2419 !(m->m_flags & (M_BCAST|M_MCAST)) &&
2420 !IN6_IS_ADDR_MULTICAST(&args->f_id.dst_ip6)) {
2422 args, cmd->arg1, hlen,
2423 (struct ip6_hdr *)ip);
2429 retval = IP_FW_DENY;
2430 l = 0; /* exit inner loop */
2431 done = 1; /* exit outer loop */
2435 if (args->eh) /* not valid on layer2 pkts */
2437 if (q == NULL || q->rule != f ||
2438 dyn_dir == MATCH_FORWARD) {
2439 struct sockaddr_in *sa;
2441 sa = &(((ipfw_insn_sa *)cmd)->sa);
2442 if (sa->sin_addr.s_addr == INADDR_ANY) {
2445 * We use O_FORWARD_IP opcode for
2446 * fwd rule with tablearg, but tables
2447 * now support IPv6 addresses. And
2448 * when we are inspecting IPv6 packet,
2449 * we can use nh6 field from
2450 * table_value as next_hop6 address.
2453 struct sockaddr_in6 *sa6;
2455 sa6 = args->next_hop6 =
2457 sa6->sin6_family = AF_INET6;
2458 sa6->sin6_len = sizeof(*sa6);
2459 sa6->sin6_addr = TARG_VAL(
2460 chain, tablearg, nh6);
2461 sa6->sin6_port = sa->sin_port;
2463 * Set sin6_scope_id only for
2464 * link-local unicast addresses.
2466 if (IN6_IS_ADDR_LINKLOCAL(
2468 sa6->sin6_scope_id =
2475 args->hopstore.sin_port =
2477 sa = args->next_hop =
2479 sa->sin_family = AF_INET;
2480 sa->sin_len = sizeof(*sa);
2481 sa->sin_addr.s_addr = htonl(
2482 TARG_VAL(chain, tablearg,
2486 args->next_hop = sa;
2489 retval = IP_FW_PASS;
2490 l = 0; /* exit inner loop */
2491 done = 1; /* exit outer loop */
2496 if (args->eh) /* not valid on layer2 pkts */
2498 if (q == NULL || q->rule != f ||
2499 dyn_dir == MATCH_FORWARD) {
2500 struct sockaddr_in6 *sin6;
2502 sin6 = &(((ipfw_insn_sa6 *)cmd)->sa);
2503 args->next_hop6 = sin6;
2505 retval = IP_FW_PASS;
2506 l = 0; /* exit inner loop */
2507 done = 1; /* exit outer loop */
2513 set_match(args, f_pos, chain);
2514 args->rule.info = TARG(cmd->arg1, netgraph);
2516 args->rule.info |= IPFW_ONEPASS;
2517 retval = (cmd->opcode == O_NETGRAPH) ?
2518 IP_FW_NETGRAPH : IP_FW_NGTEE;
2519 l = 0; /* exit inner loop */
2520 done = 1; /* exit outer loop */
2526 IPFW_INC_RULE_COUNTER(f, pktlen);
2527 fib = TARG(cmd->arg1, fib) & 0x7FFF;
2528 if (fib >= rt_numfibs)
2531 args->f_id.fib = fib;
2532 l = 0; /* exit inner loop */
2539 code = TARG(cmd->arg1, dscp) & 0x3F;
2540 l = 0; /* exit inner loop */
2544 old = *(uint16_t *)ip;
2545 ip->ip_tos = (code << 2) |
2546 (ip->ip_tos & 0x03);
2547 ip->ip_sum = cksum_adjust(ip->ip_sum,
2548 old, *(uint16_t *)ip);
2549 } else if (is_ipv6) {
2552 v = &((struct ip6_hdr *)ip)->ip6_vfc;
2553 *v = (*v & 0xF0) | (code >> 2);
2555 *v = (*v & 0x3F) | ((code & 0x03) << 6);
2559 IPFW_INC_RULE_COUNTER(f, pktlen);
2564 l = 0; /* exit inner loop */
2565 done = 1; /* exit outer loop */
2566 if (!IPFW_NAT_LOADED) {
2567 retval = IP_FW_DENY;
2574 set_match(args, f_pos, chain);
2575 /* Check if this is 'global' nat rule */
2576 if (cmd->arg1 == IP_FW_NAT44_GLOBAL) {
2577 retval = ipfw_nat_ptr(args, NULL, m);
2580 t = ((ipfw_insn_nat *)cmd)->nat;
2582 nat_id = TARG(cmd->arg1, nat);
2583 t = (*lookup_nat_ptr)(&chain->nat, nat_id);
2586 retval = IP_FW_DENY;
2589 if (cmd->arg1 != IP_FW_TARG)
2590 ((ipfw_insn_nat *)cmd)->nat = t;
2592 retval = ipfw_nat_ptr(args, t, m);
2598 IPFW_INC_RULE_COUNTER(f, pktlen);
2599 l = 0; /* in any case exit inner loop */
2600 ip_off = ntohs(ip->ip_off);
2602 /* if not fragmented, go to next rule */
2603 if ((ip_off & (IP_MF | IP_OFFMASK)) == 0)
2606 args->m = m = ip_reass(m);
2609 * do IP header checksum fixup.
2611 if (m == NULL) { /* fragment got swallowed */
2612 retval = IP_FW_DENY;
2613 } else { /* good, packet complete */
2616 ip = mtod(m, struct ip *);
2617 hlen = ip->ip_hl << 2;
2619 if (hlen == sizeof(struct ip))
2620 ip->ip_sum = in_cksum_hdr(ip);
2622 ip->ip_sum = in_cksum(m, hlen);
2623 retval = IP_FW_REASS;
2624 set_match(args, f_pos, chain);
2626 done = 1; /* exit outer loop */
2629 case O_EXTERNAL_ACTION:
2630 l = 0; /* in any case exit inner loop */
2631 retval = ipfw_run_eaction(chain, args,
2634 * If both @retval and @done are zero,
2635 * consider this as rule matching and
2638 if (retval == 0 && done == 0) {
2639 IPFW_INC_RULE_COUNTER(f, pktlen);
2641 * Reset the result of the last
2642 * dynamic state lookup.
2643 * External action can change
2644 * @args content, and it may be
2645 * used for new state lookup later.
2647 dyn_dir = MATCH_UNKNOWN;
2652 panic("-- unknown opcode %d\n", cmd->opcode);
2653 } /* end of switch() on opcodes */
2655 * if we get here with l=0, then match is irrelevant.
2658 if (cmd->len & F_NOT)
2662 if (cmd->len & F_OR)
2665 if (!(cmd->len & F_OR)) /* not an OR block, */
2666 break; /* try next rule */
2669 } /* end of inner loop, scan opcodes */
2675 /* next_rule:; */ /* try next rule */
2677 } /* end of outer for, scan rules */
2680 struct ip_fw *rule = chain->map[f_pos];
2681 /* Update statistics */
2682 IPFW_INC_RULE_COUNTER(rule, pktlen);
2684 retval = IP_FW_DENY;
2685 printf("ipfw: ouch!, skip past end of rules, denying packet\n");
2687 IPFW_PF_RUNLOCK(chain);
2689 if (ucred_cache != NULL)
2690 crfree(ucred_cache);
2696 printf("ipfw: pullup failed\n");
2697 return (IP_FW_DENY);
2701 * Set maximum number of tables that can be used in given VNET ipfw instance.
2705 sysctl_ipfw_table_num(SYSCTL_HANDLER_ARGS)
2708 unsigned int ntables;
2710 ntables = V_fw_tables_max;
2712 error = sysctl_handle_int(oidp, &ntables, 0, req);
2713 /* Read operation or some error */
2714 if ((error != 0) || (req->newptr == NULL))
2717 return (ipfw_resize_tables(&V_layer3_chain, ntables));
2721 * Switches table namespace between global and per-set.
2724 sysctl_ipfw_tables_sets(SYSCTL_HANDLER_ARGS)
2729 sets = V_fw_tables_sets;
2731 error = sysctl_handle_int(oidp, &sets, 0, req);
2732 /* Read operation or some error */
2733 if ((error != 0) || (req->newptr == NULL))
2736 return (ipfw_switch_tables_namespace(&V_layer3_chain, sets));
2741 * Module and VNET glue
2745 * Stuff that must be initialised only on boot or module load
2753 * Only print out this stuff the first time around,
2754 * when called from the sysinit code.
2760 "initialized, divert %s, nat %s, "
2761 "default to %s, logging ",
2767 #ifdef IPFIREWALL_NAT
2772 default_to_accept ? "accept" : "deny");
2775 * Note: V_xxx variables can be accessed here but the vnet specific
2776 * initializer may not have been called yet for the VIMAGE case.
2777 * Tuneables will have been processed. We will print out values for
2779 * XXX This should all be rationalized AFTER 8.0
2781 if (V_fw_verbose == 0)
2782 printf("disabled\n");
2783 else if (V_verbose_limit == 0)
2784 printf("unlimited\n");
2786 printf("limited to %d packets/entry by default\n",
2789 /* Check user-supplied table count for validness */
2790 if (default_fw_tables > IPFW_TABLES_MAX)
2791 default_fw_tables = IPFW_TABLES_MAX;
2793 ipfw_init_sopt_handler();
2794 ipfw_init_obj_rewriter();
2800 * Called for the removal of the last instance only on module unload.
2806 ipfw_iface_destroy();
2807 ipfw_destroy_sopt_handler();
2808 ipfw_destroy_obj_rewriter();
2809 printf("IP firewall unloaded\n");
2813 * Stuff that must be initialized for every instance
2814 * (including the first of course).
2817 vnet_ipfw_init(const void *unused)
2820 struct ip_fw *rule = NULL;
2821 struct ip_fw_chain *chain;
2823 chain = &V_layer3_chain;
2825 first = IS_DEFAULT_VNET(curvnet) ? 1 : 0;
2827 /* First set up some values that are compile time options */
2828 V_autoinc_step = 100; /* bounded to 1..1000 in add_rule() */
2829 V_fw_deny_unknown_exthdrs = 1;
2830 #ifdef IPFIREWALL_VERBOSE
2833 #ifdef IPFIREWALL_VERBOSE_LIMIT
2834 V_verbose_limit = IPFIREWALL_VERBOSE_LIMIT;
2836 #ifdef IPFIREWALL_NAT
2837 LIST_INIT(&chain->nat);
2840 /* Init shared services hash table */
2841 ipfw_init_srv(chain);
2843 ipfw_init_counters();
2844 /* insert the default rule and create the initial map */
2846 chain->map = malloc(sizeof(struct ip_fw *), M_IPFW, M_WAITOK | M_ZERO);
2847 rule = ipfw_alloc_rule(chain, sizeof(struct ip_fw));
2849 /* Set initial number of tables */
2850 V_fw_tables_max = default_fw_tables;
2851 error = ipfw_init_tables(chain, first);
2853 printf("ipfw2: setting up tables failed\n");
2854 free(chain->map, M_IPFW);
2859 /* fill and insert the default rule */
2861 rule->rulenum = IPFW_DEFAULT_RULE;
2863 rule->set = RESVD_SET;
2864 rule->cmd[0].len = 1;
2865 rule->cmd[0].opcode = default_to_accept ? O_ACCEPT : O_DENY;
2866 chain->default_rule = chain->map[0] = rule;
2867 chain->id = rule->id = 1;
2868 /* Pre-calculate rules length for legacy dump format */
2869 chain->static_len = sizeof(struct ip_fw_rule0);
2871 IPFW_LOCK_INIT(chain);
2872 ipfw_dyn_init(chain);
2873 ipfw_eaction_init(chain, first);
2874 #ifdef LINEAR_SKIPTO
2875 ipfw_init_skipto_cache(chain);
2877 ipfw_bpf_init(first);
2879 /* First set up some values that are compile time options */
2880 V_ipfw_vnet_ready = 1; /* Open for business */
2883 * Hook the sockopt handler and pfil hooks for ipv4 and ipv6.
2884 * Even if the latter two fail we still keep the module alive
2885 * because the sockopt and layer2 paths are still useful.
2886 * ipfw[6]_hook return 0 on success, ENOENT on failure,
2887 * so we can ignore the exact return value and just set a flag.
2889 * Note that V_fw[6]_enable are manipulated by a SYSCTL_PROC so
2890 * changes in the underlying (per-vnet) variables trigger
2891 * immediate hook()/unhook() calls.
2892 * In layer2 we have the same behaviour, except that V_ether_ipfw
2893 * is checked on each packet because there are no pfil hooks.
2895 V_ip_fw_ctl_ptr = ipfw_ctl3;
2896 error = ipfw_attach_hooks(1);
2901 * Called for the removal of each instance.
2904 vnet_ipfw_uninit(const void *unused)
2907 struct ip_fw_chain *chain = &V_layer3_chain;
2910 V_ipfw_vnet_ready = 0; /* tell new callers to go away */
2912 * disconnect from ipv4, ipv6, layer2 and sockopt.
2913 * Then grab, release and grab again the WLOCK so we make
2914 * sure the update is propagated and nobody will be in.
2916 (void)ipfw_attach_hooks(0 /* detach */);
2917 V_ip_fw_ctl_ptr = NULL;
2919 last = IS_DEFAULT_VNET(curvnet) ? 1 : 0;
2921 IPFW_UH_WLOCK(chain);
2922 IPFW_UH_WUNLOCK(chain);
2924 ipfw_dyn_uninit(0); /* run the callout_drain */
2926 IPFW_UH_WLOCK(chain);
2930 for (i = 0; i < chain->n_rules; i++)
2931 ipfw_reap_add(chain, &reap, chain->map[i]);
2932 free(chain->map, M_IPFW);
2933 #ifdef LINEAR_SKIPTO
2934 ipfw_destroy_skipto_cache(chain);
2936 IPFW_WUNLOCK(chain);
2937 IPFW_UH_WUNLOCK(chain);
2938 ipfw_destroy_tables(chain, last);
2939 ipfw_eaction_uninit(chain, last);
2941 ipfw_reap_rules(reap);
2942 vnet_ipfw_iface_destroy(chain);
2943 ipfw_destroy_srv(chain);
2944 IPFW_LOCK_DESTROY(chain);
2945 ipfw_dyn_uninit(1); /* free the remaining parts */
2946 ipfw_destroy_counters();
2947 ipfw_bpf_uninit(last);
2952 * Module event handler.
2953 * In general we have the choice of handling most of these events by the
2954 * event handler or by the (VNET_)SYS(UN)INIT handlers. I have chosen to
2955 * use the SYSINIT handlers as they are more capable of expressing the
2956 * flow of control during module and vnet operations, so this is just
2957 * a skeleton. Note there is no SYSINIT equivalent of the module
2958 * SHUTDOWN handler, but we don't have anything to do in that case anyhow.
2961 ipfw_modevent(module_t mod, int type, void *unused)
2967 /* Called once at module load or
2968 * system boot if compiled in. */
2971 /* Called before unload. May veto unloading. */
2974 /* Called during unload. */
2977 /* Called during system shutdown. */
2986 static moduledata_t ipfwmod = {
2992 /* Define startup order. */
2993 #define IPFW_SI_SUB_FIREWALL SI_SUB_PROTO_FIREWALL
2994 #define IPFW_MODEVENT_ORDER (SI_ORDER_ANY - 255) /* On boot slot in here. */
2995 #define IPFW_MODULE_ORDER (IPFW_MODEVENT_ORDER + 1) /* A little later. */
2996 #define IPFW_VNET_ORDER (IPFW_MODEVENT_ORDER + 2) /* Later still. */
2998 DECLARE_MODULE(ipfw, ipfwmod, IPFW_SI_SUB_FIREWALL, IPFW_MODEVENT_ORDER);
2999 FEATURE(ipfw_ctl3, "ipfw new sockopt calls");
3000 MODULE_VERSION(ipfw, 3);
3001 /* should declare some dependencies here */
3004 * Starting up. Done in order after ipfwmod() has been called.
3005 * VNET_SYSINIT is also called for each existing vnet and each new vnet.
3007 SYSINIT(ipfw_init, IPFW_SI_SUB_FIREWALL, IPFW_MODULE_ORDER,
3009 VNET_SYSINIT(vnet_ipfw_init, IPFW_SI_SUB_FIREWALL, IPFW_VNET_ORDER,
3010 vnet_ipfw_init, NULL);
3013 * Closing up shop. These are done in REVERSE ORDER, but still
3014 * after ipfwmod() has been called. Not called on reboot.
3015 * VNET_SYSUNINIT is also called for each exiting vnet as it exits.
3016 * or when the module is unloaded.
3018 SYSUNINIT(ipfw_destroy, IPFW_SI_SUB_FIREWALL, IPFW_MODULE_ORDER,
3019 ipfw_destroy, NULL);
3020 VNET_SYSUNINIT(vnet_ipfw_uninit, IPFW_SI_SUB_FIREWALL, IPFW_VNET_ORDER,
3021 vnet_ipfw_uninit, NULL);