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
33 #if !defined(KLD_MODULE)
35 #include "opt_ipdivert.h"
39 #error IPFIREWALL requires INET.
42 #include "opt_inet6.h"
43 #include "opt_ipsec.h"
45 #include <sys/param.h>
46 #include <sys/systm.h>
47 #include <sys/condvar.h>
48 #include <sys/eventhandler.h>
49 #include <sys/malloc.h>
51 #include <sys/kernel.h>
54 #include <sys/module.h>
57 #include <sys/rwlock.h>
58 #include <sys/socket.h>
59 #include <sys/socketvar.h>
60 #include <sys/sysctl.h>
61 #include <sys/syslog.h>
62 #include <sys/ucred.h>
63 #include <net/ethernet.h> /* for ETHERTYPE_IP */
65 #include <net/route.h>
66 #include <net/pf_mtag.h>
69 #include <netinet/in.h>
70 #include <netinet/in_var.h>
71 #include <netinet/in_pcb.h>
72 #include <netinet/ip.h>
73 #include <netinet/ip_var.h>
74 #include <netinet/ip_icmp.h>
75 #include <netinet/ip_fw.h>
76 #include <netinet/ipfw/ip_fw_private.h>
77 #include <netinet/ip_carp.h>
78 #include <netinet/pim.h>
79 #include <netinet/tcp_var.h>
80 #include <netinet/udp.h>
81 #include <netinet/udp_var.h>
82 #include <netinet/sctp.h>
84 #include <netinet/ip6.h>
85 #include <netinet/icmp6.h>
87 #include <netinet6/scope6_var.h>
88 #include <netinet6/ip6_var.h>
91 #include <machine/in_cksum.h> /* XXX for in_cksum */
94 #include <security/mac/mac_framework.h>
98 * static variables followed by global ones.
99 * All ipfw global variables are here.
102 /* ipfw_vnet_ready controls when we are open for business */
103 static VNET_DEFINE(int, ipfw_vnet_ready) = 0;
104 #define V_ipfw_vnet_ready VNET(ipfw_vnet_ready)
106 static VNET_DEFINE(int, fw_deny_unknown_exthdrs);
107 #define V_fw_deny_unknown_exthdrs VNET(fw_deny_unknown_exthdrs)
109 #ifdef IPFIREWALL_DEFAULT_TO_ACCEPT
110 static int default_to_accept = 1;
112 static int default_to_accept;
115 VNET_DEFINE(int, autoinc_step);
118 * Each rule belongs to one of 32 different sets (0..31).
119 * The variable set_disable contains one bit per set.
120 * If the bit is set, all rules in the corresponding set
121 * are disabled. Set RESVD_SET(31) is reserved for the default rule
122 * and rules that are not deleted by the flush command,
123 * and CANNOT be disabled.
124 * Rules in set RESVD_SET can only be deleted individually.
126 VNET_DEFINE(u_int32_t, set_disable);
127 #define V_set_disable VNET(set_disable)
129 VNET_DEFINE(int, fw_verbose);
130 /* counter for ipfw_log(NULL...) */
131 VNET_DEFINE(u_int64_t, norule_counter);
132 VNET_DEFINE(int, verbose_limit);
134 /* layer3_chain contains the list of rules for layer 3 */
135 VNET_DEFINE(struct ip_fw_chain, layer3_chain);
137 ipfw_nat_t *ipfw_nat_ptr = NULL;
138 struct cfg_nat *(*lookup_nat_ptr)(struct nat_list *, int);
139 ipfw_nat_cfg_t *ipfw_nat_cfg_ptr;
140 ipfw_nat_cfg_t *ipfw_nat_del_ptr;
141 ipfw_nat_cfg_t *ipfw_nat_get_cfg_ptr;
142 ipfw_nat_cfg_t *ipfw_nat_get_log_ptr;
145 uint32_t dummy_def = IPFW_DEFAULT_RULE;
146 uint32_t dummy_tables_max = IPFW_TABLES_MAX;
150 SYSCTL_NODE(_net_inet_ip, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall");
151 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, one_pass,
152 CTLFLAG_RW | CTLFLAG_SECURE3, &VNET_NAME(fw_one_pass), 0,
153 "Only do a single pass through ipfw when using dummynet(4)");
154 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, autoinc_step,
155 CTLFLAG_RW, &VNET_NAME(autoinc_step), 0,
156 "Rule number auto-increment step");
157 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, verbose,
158 CTLFLAG_RW | CTLFLAG_SECURE3, &VNET_NAME(fw_verbose), 0,
159 "Log matches to ipfw rules");
160 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, verbose_limit,
161 CTLFLAG_RW, &VNET_NAME(verbose_limit), 0,
162 "Set upper limit of matches of ipfw rules logged");
163 SYSCTL_UINT(_net_inet_ip_fw, OID_AUTO, default_rule, CTLFLAG_RD,
165 "The default/max possible rule number.");
166 SYSCTL_UINT(_net_inet_ip_fw, OID_AUTO, tables_max, CTLFLAG_RD,
167 &dummy_tables_max, 0,
168 "The maximum number of tables.");
169 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, default_to_accept, CTLFLAG_RDTUN,
170 &default_to_accept, 0,
171 "Make the default rule accept all packets.");
172 TUNABLE_INT("net.inet.ip.fw.default_to_accept", &default_to_accept);
173 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, static_count,
174 CTLFLAG_RD, &VNET_NAME(layer3_chain.n_rules), 0,
175 "Number of static rules");
178 SYSCTL_DECL(_net_inet6_ip6);
179 SYSCTL_NODE(_net_inet6_ip6, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall");
180 SYSCTL_VNET_INT(_net_inet6_ip6_fw, OID_AUTO, deny_unknown_exthdrs,
181 CTLFLAG_RW | CTLFLAG_SECURE, &VNET_NAME(fw_deny_unknown_exthdrs), 0,
182 "Deny packets with unknown IPv6 Extension Headers");
187 #endif /* SYSCTL_NODE */
191 * Some macros used in the various matching options.
192 * L3HDR maps an ipv4 pointer into a layer3 header pointer of type T
193 * Other macros just cast void * into the appropriate type
195 #define L3HDR(T, ip) ((T *)((u_int32_t *)(ip) + (ip)->ip_hl))
196 #define TCP(p) ((struct tcphdr *)(p))
197 #define SCTP(p) ((struct sctphdr *)(p))
198 #define UDP(p) ((struct udphdr *)(p))
199 #define ICMP(p) ((struct icmphdr *)(p))
200 #define ICMP6(p) ((struct icmp6_hdr *)(p))
203 icmptype_match(struct icmphdr *icmp, ipfw_insn_u32 *cmd)
205 int type = icmp->icmp_type;
207 return (type <= ICMP_MAXTYPE && (cmd->d[0] & (1<<type)) );
210 #define TT ( (1 << ICMP_ECHO) | (1 << ICMP_ROUTERSOLICIT) | \
211 (1 << ICMP_TSTAMP) | (1 << ICMP_IREQ) | (1 << ICMP_MASKREQ) )
214 is_icmp_query(struct icmphdr *icmp)
216 int type = icmp->icmp_type;
218 return (type <= ICMP_MAXTYPE && (TT & (1<<type)) );
223 * The following checks use two arrays of 8 or 16 bits to store the
224 * bits that we want set or clear, respectively. They are in the
225 * low and high half of cmd->arg1 or cmd->d[0].
227 * We scan options and store the bits we find set. We succeed if
229 * (want_set & ~bits) == 0 && (want_clear & ~bits) == want_clear
231 * The code is sometimes optimized not to store additional variables.
235 flags_match(ipfw_insn *cmd, u_int8_t bits)
240 if ( ((cmd->arg1 & 0xff) & bits) != 0)
241 return 0; /* some bits we want set were clear */
242 want_clear = (cmd->arg1 >> 8) & 0xff;
243 if ( (want_clear & bits) != want_clear)
244 return 0; /* some bits we want clear were set */
249 ipopts_match(struct ip *ip, ipfw_insn *cmd)
251 int optlen, bits = 0;
252 u_char *cp = (u_char *)(ip + 1);
253 int x = (ip->ip_hl << 2) - sizeof (struct ip);
255 for (; x > 0; x -= optlen, cp += optlen) {
256 int opt = cp[IPOPT_OPTVAL];
258 if (opt == IPOPT_EOL)
260 if (opt == IPOPT_NOP)
263 optlen = cp[IPOPT_OLEN];
264 if (optlen <= 0 || optlen > x)
265 return 0; /* invalid or truncated */
273 bits |= IP_FW_IPOPT_LSRR;
277 bits |= IP_FW_IPOPT_SSRR;
281 bits |= IP_FW_IPOPT_RR;
285 bits |= IP_FW_IPOPT_TS;
289 return (flags_match(cmd, bits));
293 tcpopts_match(struct tcphdr *tcp, ipfw_insn *cmd)
295 int optlen, bits = 0;
296 u_char *cp = (u_char *)(tcp + 1);
297 int x = (tcp->th_off << 2) - sizeof(struct tcphdr);
299 for (; x > 0; x -= optlen, cp += optlen) {
301 if (opt == TCPOPT_EOL)
303 if (opt == TCPOPT_NOP)
317 bits |= IP_FW_TCPOPT_MSS;
321 bits |= IP_FW_TCPOPT_WINDOW;
324 case TCPOPT_SACK_PERMITTED:
326 bits |= IP_FW_TCPOPT_SACK;
329 case TCPOPT_TIMESTAMP:
330 bits |= IP_FW_TCPOPT_TS;
335 return (flags_match(cmd, bits));
339 iface_match(struct ifnet *ifp, ipfw_insn_if *cmd)
341 if (ifp == NULL) /* no iface with this packet, match fails */
343 /* Check by name or by IP address */
344 if (cmd->name[0] != '\0') { /* match by name */
347 if (fnmatch(cmd->name, ifp->if_xname, 0) == 0)
350 if (strncmp(ifp->if_xname, cmd->name, IFNAMSIZ) == 0)
354 #ifdef __FreeBSD__ /* and OSX too ? */
358 TAILQ_FOREACH(ia, &ifp->if_addrhead, ifa_link) {
359 if (ia->ifa_addr->sa_family != AF_INET)
361 if (cmd->p.ip.s_addr == ((struct sockaddr_in *)
362 (ia->ifa_addr))->sin_addr.s_addr) {
363 if_addr_runlock(ifp);
364 return(1); /* match */
367 if_addr_runlock(ifp);
368 #endif /* __FreeBSD__ */
370 return(0); /* no match, fail ... */
374 * The verify_path function checks if a route to the src exists and
375 * if it is reachable via ifp (when provided).
377 * The 'verrevpath' option checks that the interface that an IP packet
378 * arrives on is the same interface that traffic destined for the
379 * packet's source address would be routed out of.
380 * The 'versrcreach' option just checks that the source address is
381 * reachable via any route (except default) in the routing table.
382 * These two are a measure to block forged packets. This is also
383 * commonly known as "anti-spoofing" or Unicast Reverse Path
384 * Forwarding (Unicast RFP) in Cisco-ese. The name of the knobs
385 * is purposely reminiscent of the Cisco IOS command,
387 * ip verify unicast reverse-path
388 * ip verify unicast source reachable-via any
390 * which implements the same functionality. But note that the syntax
391 * is misleading, and the check may be performed on all IP packets
392 * whether unicast, multicast, or broadcast.
395 verify_path(struct in_addr src, struct ifnet *ifp, u_int fib)
401 struct sockaddr_in *dst;
403 bzero(&ro, sizeof(ro));
405 dst = (struct sockaddr_in *)&(ro.ro_dst);
406 dst->sin_family = AF_INET;
407 dst->sin_len = sizeof(*dst);
409 in_rtalloc_ign(&ro, 0, fib);
411 if (ro.ro_rt == NULL)
415 * If ifp is provided, check for equality with rtentry.
416 * We should use rt->rt_ifa->ifa_ifp, instead of rt->rt_ifp,
417 * in order to pass packets injected back by if_simloop():
418 * if useloopback == 1 routing entry (via lo0) for our own address
419 * may exist, so we need to handle routing assymetry.
421 if (ifp != NULL && ro.ro_rt->rt_ifa->ifa_ifp != ifp) {
426 /* if no ifp provided, check if rtentry is not default route */
428 satosin(rt_key(ro.ro_rt))->sin_addr.s_addr == INADDR_ANY) {
433 /* or if this is a blackhole/reject route */
434 if (ifp == NULL && ro.ro_rt->rt_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
439 /* found valid route */
442 #endif /* __FreeBSD__ */
447 * ipv6 specific rules here...
450 icmp6type_match (int type, ipfw_insn_u32 *cmd)
452 return (type <= ICMP6_MAXTYPE && (cmd->d[type/32] & (1<<(type%32)) ) );
456 flow6id_match( int curr_flow, ipfw_insn_u32 *cmd )
459 for (i=0; i <= cmd->o.arg1; ++i )
460 if (curr_flow == cmd->d[i] )
465 /* support for IP6_*_ME opcodes */
467 search_ip6_addr_net (struct in6_addr * ip6_addr)
471 struct in6_ifaddr *fdm;
472 struct in6_addr copia;
474 TAILQ_FOREACH(mdc, &V_ifnet, if_link) {
476 TAILQ_FOREACH(mdc2, &mdc->if_addrhead, ifa_link) {
477 if (mdc2->ifa_addr->sa_family == AF_INET6) {
478 fdm = (struct in6_ifaddr *)mdc2;
479 copia = fdm->ia_addr.sin6_addr;
480 /* need for leaving scope_id in the sock_addr */
481 in6_clearscope(&copia);
482 if (IN6_ARE_ADDR_EQUAL(ip6_addr, &copia)) {
483 if_addr_runlock(mdc);
488 if_addr_runlock(mdc);
494 verify_path6(struct in6_addr *src, struct ifnet *ifp)
497 struct sockaddr_in6 *dst;
499 bzero(&ro, sizeof(ro));
501 dst = (struct sockaddr_in6 * )&(ro.ro_dst);
502 dst->sin6_family = AF_INET6;
503 dst->sin6_len = sizeof(*dst);
504 dst->sin6_addr = *src;
505 /* XXX MRT 0 for ipv6 at this time */
506 rtalloc_ign((struct route *)&ro, 0);
508 if (ro.ro_rt == NULL)
512 * if ifp is provided, check for equality with rtentry
513 * We should use rt->rt_ifa->ifa_ifp, instead of rt->rt_ifp,
514 * to support the case of sending packets to an address of our own.
515 * (where the former interface is the first argument of if_simloop()
516 * (=ifp), the latter is lo0)
518 if (ifp != NULL && ro.ro_rt->rt_ifa->ifa_ifp != ifp) {
523 /* if no ifp provided, check if rtentry is not default route */
525 IN6_IS_ADDR_UNSPECIFIED(&satosin6(rt_key(ro.ro_rt))->sin6_addr)) {
530 /* or if this is a blackhole/reject route */
531 if (ifp == NULL && ro.ro_rt->rt_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
536 /* found valid route */
543 is_icmp6_query(int icmp6_type)
545 if ((icmp6_type <= ICMP6_MAXTYPE) &&
546 (icmp6_type == ICMP6_ECHO_REQUEST ||
547 icmp6_type == ICMP6_MEMBERSHIP_QUERY ||
548 icmp6_type == ICMP6_WRUREQUEST ||
549 icmp6_type == ICMP6_FQDN_QUERY ||
550 icmp6_type == ICMP6_NI_QUERY))
557 send_reject6(struct ip_fw_args *args, int code, u_int hlen, struct ip6_hdr *ip6)
562 if (code == ICMP6_UNREACH_RST && args->f_id.proto == IPPROTO_TCP) {
564 tcp = (struct tcphdr *)((char *)ip6 + hlen);
566 if ((tcp->th_flags & TH_RST) == 0) {
568 m0 = ipfw_send_pkt(args->m, &(args->f_id),
569 ntohl(tcp->th_seq), ntohl(tcp->th_ack),
570 tcp->th_flags | TH_RST);
572 ip6_output(m0, NULL, NULL, 0, NULL, NULL,
576 } else if (code != ICMP6_UNREACH_RST) { /* Send an ICMPv6 unreach. */
579 * Unlike above, the mbufs need to line up with the ip6 hdr,
580 * as the contents are read. We need to m_adj() the
582 * The mbuf will however be thrown away so we can adjust it.
583 * Remember we did an m_pullup on it already so we
584 * can make some assumptions about contiguousness.
587 m_adj(m, args->L3offset);
589 icmp6_error(m, ICMP6_DST_UNREACH, code, 0);
600 * sends a reject message, consuming the mbuf passed as an argument.
603 send_reject(struct ip_fw_args *args, int code, int iplen, struct ip *ip)
607 /* XXX When ip is not guaranteed to be at mtod() we will
608 * need to account for this */
609 * The mbuf will however be thrown away so we can adjust it.
610 * Remember we did an m_pullup on it already so we
611 * can make some assumptions about contiguousness.
614 m_adj(m, args->L3offset);
616 if (code != ICMP_REJECT_RST) { /* Send an ICMP unreach */
617 /* We need the IP header in host order for icmp_error(). */
619 icmp_error(args->m, ICMP_UNREACH, code, 0L, 0);
620 } else if (args->f_id.proto == IPPROTO_TCP) {
621 struct tcphdr *const tcp =
622 L3HDR(struct tcphdr, mtod(args->m, struct ip *));
623 if ( (tcp->th_flags & TH_RST) == 0) {
625 m = ipfw_send_pkt(args->m, &(args->f_id),
626 ntohl(tcp->th_seq), ntohl(tcp->th_ack),
627 tcp->th_flags | TH_RST);
629 ip_output(m, NULL, NULL, 0, NULL, NULL);
638 * Support for uid/gid/jail lookup. These tests are expensive
639 * (because we may need to look into the list of active sockets)
640 * so we cache the results. ugid_lookupp is 0 if we have not
641 * yet done a lookup, 1 if we succeeded, and -1 if we tried
642 * and failed. The function always returns the match value.
643 * We could actually spare the variable and use *uc, setting
644 * it to '(void *)check_uidgid if we have no info, NULL if
645 * we tried and failed, or any other value if successful.
648 check_uidgid(ipfw_insn_u32 *insn, int proto, struct ifnet *oif,
649 struct in_addr dst_ip, u_int16_t dst_port, struct in_addr src_ip,
650 u_int16_t src_port, int *ugid_lookupp,
651 struct ucred **uc, struct inpcb *inp)
654 return cred_check(insn, proto, oif,
655 dst_ip, dst_port, src_ip, src_port,
656 (struct bsd_ucred *)uc, ugid_lookupp, ((struct mbuf *)inp)->m_skb);
658 struct inpcbinfo *pi;
664 * Check to see if the UDP or TCP stack supplied us with
665 * the PCB. If so, rather then holding a lock and looking
666 * up the PCB, we can use the one that was supplied.
668 if (inp && *ugid_lookupp == 0) {
669 INP_LOCK_ASSERT(inp);
670 if (inp->inp_socket != NULL) {
671 *uc = crhold(inp->inp_cred);
677 * If we have already been here and the packet has no
678 * PCB entry associated with it, then we can safely
679 * assume that this is a no match.
681 if (*ugid_lookupp == -1)
683 if (proto == IPPROTO_TCP) {
686 } else if (proto == IPPROTO_UDP) {
687 wildcard = INPLOOKUP_WILDCARD;
692 if (*ugid_lookupp == 0) {
695 in_pcblookup_hash(pi,
696 dst_ip, htons(dst_port),
697 src_ip, htons(src_port),
699 in_pcblookup_hash(pi,
700 src_ip, htons(src_port),
701 dst_ip, htons(dst_port),
704 *uc = crhold(pcb->inp_cred);
707 INP_INFO_RUNLOCK(pi);
708 if (*ugid_lookupp == 0) {
710 * We tried and failed, set the variable to -1
711 * so we will not try again on this packet.
717 if (insn->o.opcode == O_UID)
718 match = ((*uc)->cr_uid == (uid_t)insn->d[0]);
719 else if (insn->o.opcode == O_GID)
720 match = groupmember((gid_t)insn->d[0], *uc);
721 else if (insn->o.opcode == O_JAIL)
722 match = ((*uc)->cr_prison->pr_id == (int)insn->d[0]);
724 #endif /* __FreeBSD__ */
728 * Helper function to set args with info on the rule after the matching
729 * one. slot is precise, whereas we guess rule_id as they are
730 * assigned sequentially.
733 set_match(struct ip_fw_args *args, int slot,
734 struct ip_fw_chain *chain)
736 args->rule.chain_id = chain->id;
737 args->rule.slot = slot + 1; /* we use 0 as a marker */
738 args->rule.rule_id = 1 + chain->map[slot]->id;
739 args->rule.rulenum = chain->map[slot]->rulenum;
743 * The main check routine for the firewall.
745 * All arguments are in args so we can modify them and return them
746 * back to the caller.
750 * args->m (in/out) The packet; we set to NULL when/if we nuke it.
751 * Starts with the IP header.
752 * args->eh (in) Mac header if present, NULL for layer3 packet.
753 * args->L3offset Number of bytes bypassed if we came from L2.
754 * e.g. often sizeof(eh) ** NOTYET **
755 * args->oif Outgoing interface, NULL if packet is incoming.
756 * The incoming interface is in the mbuf. (in)
757 * args->divert_rule (in/out)
758 * Skip up to the first rule past this rule number;
759 * upon return, non-zero port number for divert or tee.
761 * args->rule Pointer to the last matching rule (in/out)
762 * args->next_hop Socket we are forwarding to (out).
763 * args->f_id Addresses grabbed from the packet (out)
764 * args->rule.info a cookie depending on rule action
768 * IP_FW_PASS the packet must be accepted
769 * IP_FW_DENY the packet must be dropped
770 * IP_FW_DIVERT divert packet, port in m_tag
771 * IP_FW_TEE tee packet, port in m_tag
772 * IP_FW_DUMMYNET to dummynet, pipe in args->cookie
773 * IP_FW_NETGRAPH into netgraph, cookie args->cookie
774 * args->rule contains the matching rule,
775 * args->rule.info has additional information.
779 ipfw_chk(struct ip_fw_args *args)
783 * Local variables holding state while processing a packet:
785 * IMPORTANT NOTE: to speed up the processing of rules, there
786 * are some assumption on the values of the variables, which
787 * are documented here. Should you change them, please check
788 * the implementation of the various instructions to make sure
789 * that they still work.
791 * args->eh The MAC header. It is non-null for a layer2
792 * packet, it is NULL for a layer-3 packet.
794 * args->L3offset Offset in the packet to the L3 (IP or equiv.) header.
796 * m | args->m Pointer to the mbuf, as received from the caller.
797 * It may change if ipfw_chk() does an m_pullup, or if it
798 * consumes the packet because it calls send_reject().
799 * XXX This has to change, so that ipfw_chk() never modifies
800 * or consumes the buffer.
801 * ip is the beginning of the ip(4 or 6) header.
802 * Calculated by adding the L3offset to the start of data.
803 * (Until we start using L3offset, the packet is
804 * supposed to start with the ip header).
806 struct mbuf *m = args->m;
807 struct ip *ip = mtod(m, struct ip *);
810 * For rules which contain uid/gid or jail constraints, cache
811 * a copy of the users credentials after the pcb lookup has been
812 * executed. This will speed up the processing of rules with
813 * these types of constraints, as well as decrease contention
814 * on pcb related locks.
817 struct bsd_ucred ucred_cache;
819 struct ucred *ucred_cache = NULL;
821 int ucred_lookup = 0;
824 * oif | args->oif If NULL, ipfw_chk has been called on the
825 * inbound path (ether_input, ip_input).
826 * If non-NULL, ipfw_chk has been called on the outbound path
827 * (ether_output, ip_output).
829 struct ifnet *oif = args->oif;
831 int f_pos = 0; /* index of current rule in the array */
835 * hlen The length of the IP header.
837 u_int hlen = 0; /* hlen >0 means we have an IP pkt */
840 * offset The offset of a fragment. offset != 0 means that
841 * we have a fragment at this offset of an IPv4 packet.
842 * offset == 0 means that (if this is an IPv4 packet)
843 * this is the first or only fragment.
844 * For IPv6 offset == 0 means there is no Fragment Header.
845 * If offset != 0 for IPv6 always use correct mask to
846 * get the correct offset because we add IP6F_MORE_FRAG
847 * to be able to dectect the first fragment which would
848 * otherwise have offset = 0.
853 * Local copies of addresses. They are only valid if we have
856 * proto The protocol. Set to 0 for non-ip packets,
857 * or to the protocol read from the packet otherwise.
858 * proto != 0 means that we have an IPv4 packet.
860 * src_port, dst_port port numbers, in HOST format. Only
861 * valid for TCP and UDP packets.
863 * src_ip, dst_ip ip addresses, in NETWORK format.
864 * Only valid for IPv4 packets.
867 uint16_t src_port = 0, dst_port = 0; /* NOTE: host format */
868 struct in_addr src_ip, dst_ip; /* NOTE: network format */
871 uint16_t etype = 0; /* Host order stored ether type */
874 * dyn_dir = MATCH_UNKNOWN when rules unchecked,
875 * MATCH_NONE when checked and not matched (q = NULL),
876 * MATCH_FORWARD or MATCH_REVERSE otherwise (q != NULL)
878 int dyn_dir = MATCH_UNKNOWN;
879 ipfw_dyn_rule *q = NULL;
880 struct ip_fw_chain *chain = &V_layer3_chain;
883 * We store in ulp a pointer to the upper layer protocol header.
884 * In the ipv4 case this is easy to determine from the header,
885 * but for ipv6 we might have some additional headers in the middle.
886 * ulp is NULL if not found.
888 void *ulp = NULL; /* upper layer protocol pointer. */
890 /* XXX ipv6 variables */
892 uint8_t icmp6_type = 0;
893 uint16_t ext_hd = 0; /* bits vector for extension header filtering */
894 /* end of ipv6 variables */
898 int done = 0; /* flag to exit the outer loop */
900 if (m->m_flags & M_SKIP_FIREWALL || (! V_ipfw_vnet_ready))
901 return (IP_FW_PASS); /* accept */
903 dst_ip.s_addr = 0; /* make sure it is initialized */
904 src_ip.s_addr = 0; /* make sure it is initialized */
905 pktlen = m->m_pkthdr.len;
906 args->f_id.fib = M_GETFIB(m); /* note mbuf not altered) */
907 proto = args->f_id.proto = 0; /* mark f_id invalid */
908 /* XXX 0 is a valid proto: IP/IPv6 Hop-by-Hop Option */
911 * PULLUP_TO(len, p, T) makes sure that len + sizeof(T) is contiguous,
912 * then it sets p to point at the offset "len" in the mbuf. WARNING: the
913 * pointer might become stale after other pullups (but we never use it
916 #define PULLUP_TO(_len, p, T) PULLUP_LEN(_len, p, sizeof(T))
917 #define PULLUP_LEN(_len, p, T) \
919 int x = (_len) + T; \
920 if ((m)->m_len < x) { \
921 args->m = m = m_pullup(m, x); \
923 goto pullup_failed; \
925 p = (mtod(m, char *) + (_len)); \
929 * if we have an ether header,
932 etype = ntohs(args->eh->ether_type);
934 /* Identify IP packets and fill up variables. */
935 if (pktlen >= sizeof(struct ip6_hdr) &&
936 (args->eh == NULL || etype == ETHERTYPE_IPV6) && ip->ip_v == 6) {
937 struct ip6_hdr *ip6 = (struct ip6_hdr *)ip;
939 args->f_id.addr_type = 6;
940 hlen = sizeof(struct ip6_hdr);
941 proto = ip6->ip6_nxt;
943 /* Search extension headers to find upper layer protocols */
944 while (ulp == NULL) {
947 PULLUP_TO(hlen, ulp, struct icmp6_hdr);
948 icmp6_type = ICMP6(ulp)->icmp6_type;
952 PULLUP_TO(hlen, ulp, struct tcphdr);
953 dst_port = TCP(ulp)->th_dport;
954 src_port = TCP(ulp)->th_sport;
955 /* save flags for dynamic rules */
956 args->f_id._flags = TCP(ulp)->th_flags;
960 PULLUP_TO(hlen, ulp, struct sctphdr);
961 src_port = SCTP(ulp)->src_port;
962 dst_port = SCTP(ulp)->dest_port;
966 PULLUP_TO(hlen, ulp, struct udphdr);
967 dst_port = UDP(ulp)->uh_dport;
968 src_port = UDP(ulp)->uh_sport;
971 case IPPROTO_HOPOPTS: /* RFC 2460 */
972 PULLUP_TO(hlen, ulp, struct ip6_hbh);
973 ext_hd |= EXT_HOPOPTS;
974 hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3;
975 proto = ((struct ip6_hbh *)ulp)->ip6h_nxt;
979 case IPPROTO_ROUTING: /* RFC 2460 */
980 PULLUP_TO(hlen, ulp, struct ip6_rthdr);
981 switch (((struct ip6_rthdr *)ulp)->ip6r_type) {
983 ext_hd |= EXT_RTHDR0;
986 ext_hd |= EXT_RTHDR2;
989 printf("IPFW2: IPV6 - Unknown Routing "
991 ((struct ip6_rthdr *)ulp)->ip6r_type);
992 if (V_fw_deny_unknown_exthdrs)
996 ext_hd |= EXT_ROUTING;
997 hlen += (((struct ip6_rthdr *)ulp)->ip6r_len + 1) << 3;
998 proto = ((struct ip6_rthdr *)ulp)->ip6r_nxt;
1002 case IPPROTO_FRAGMENT: /* RFC 2460 */
1003 PULLUP_TO(hlen, ulp, struct ip6_frag);
1004 ext_hd |= EXT_FRAGMENT;
1005 hlen += sizeof (struct ip6_frag);
1006 proto = ((struct ip6_frag *)ulp)->ip6f_nxt;
1007 offset = ((struct ip6_frag *)ulp)->ip6f_offlg &
1009 /* Add IP6F_MORE_FRAG for offset of first
1010 * fragment to be != 0. */
1011 offset |= ((struct ip6_frag *)ulp)->ip6f_offlg &
1014 printf("IPFW2: IPV6 - Invalid Fragment "
1016 if (V_fw_deny_unknown_exthdrs)
1017 return (IP_FW_DENY);
1021 ntohl(((struct ip6_frag *)ulp)->ip6f_ident);
1025 case IPPROTO_DSTOPTS: /* RFC 2460 */
1026 PULLUP_TO(hlen, ulp, struct ip6_hbh);
1027 ext_hd |= EXT_DSTOPTS;
1028 hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3;
1029 proto = ((struct ip6_hbh *)ulp)->ip6h_nxt;
1033 case IPPROTO_AH: /* RFC 2402 */
1034 PULLUP_TO(hlen, ulp, struct ip6_ext);
1036 hlen += (((struct ip6_ext *)ulp)->ip6e_len + 2) << 2;
1037 proto = ((struct ip6_ext *)ulp)->ip6e_nxt;
1041 case IPPROTO_ESP: /* RFC 2406 */
1042 PULLUP_TO(hlen, ulp, uint32_t); /* SPI, Seq# */
1043 /* Anything past Seq# is variable length and
1044 * data past this ext. header is encrypted. */
1048 case IPPROTO_NONE: /* RFC 2460 */
1050 * Packet ends here, and IPv6 header has
1051 * already been pulled up. If ip6e_len!=0
1052 * then octets must be ignored.
1054 ulp = ip; /* non-NULL to get out of loop. */
1057 case IPPROTO_OSPFIGP:
1058 /* XXX OSPF header check? */
1059 PULLUP_TO(hlen, ulp, struct ip6_ext);
1063 /* XXX PIM header check? */
1064 PULLUP_TO(hlen, ulp, struct pim);
1068 PULLUP_TO(hlen, ulp, struct carp_header);
1069 if (((struct carp_header *)ulp)->carp_version !=
1071 return (IP_FW_DENY);
1072 if (((struct carp_header *)ulp)->carp_type !=
1074 return (IP_FW_DENY);
1077 case IPPROTO_IPV6: /* RFC 2893 */
1078 PULLUP_TO(hlen, ulp, struct ip6_hdr);
1081 case IPPROTO_IPV4: /* RFC 2893 */
1082 PULLUP_TO(hlen, ulp, struct ip);
1086 printf("IPFW2: IPV6 - Unknown Extension "
1087 "Header(%d), ext_hd=%x\n", proto, ext_hd);
1088 if (V_fw_deny_unknown_exthdrs)
1089 return (IP_FW_DENY);
1090 PULLUP_TO(hlen, ulp, struct ip6_ext);
1094 ip = mtod(m, struct ip *);
1095 ip6 = (struct ip6_hdr *)ip;
1096 args->f_id.src_ip6 = ip6->ip6_src;
1097 args->f_id.dst_ip6 = ip6->ip6_dst;
1098 args->f_id.src_ip = 0;
1099 args->f_id.dst_ip = 0;
1100 args->f_id.flow_id6 = ntohl(ip6->ip6_flow);
1101 } else if (pktlen >= sizeof(struct ip) &&
1102 (args->eh == NULL || etype == ETHERTYPE_IP) && ip->ip_v == 4) {
1104 hlen = ip->ip_hl << 2;
1105 args->f_id.addr_type = 4;
1108 * Collect parameters into local variables for faster matching.
1111 src_ip = ip->ip_src;
1112 dst_ip = ip->ip_dst;
1113 offset = ntohs(ip->ip_off) & IP_OFFMASK;
1114 iplen = ntohs(ip->ip_len);
1115 pktlen = iplen < pktlen ? iplen : pktlen;
1120 PULLUP_TO(hlen, ulp, struct tcphdr);
1121 dst_port = TCP(ulp)->th_dport;
1122 src_port = TCP(ulp)->th_sport;
1123 /* save flags for dynamic rules */
1124 args->f_id._flags = TCP(ulp)->th_flags;
1128 PULLUP_TO(hlen, ulp, struct sctphdr);
1129 src_port = SCTP(ulp)->src_port;
1130 dst_port = SCTP(ulp)->dest_port;
1134 PULLUP_TO(hlen, ulp, struct udphdr);
1135 dst_port = UDP(ulp)->uh_dport;
1136 src_port = UDP(ulp)->uh_sport;
1140 PULLUP_TO(hlen, ulp, struct icmphdr);
1141 //args->f_id.flags = ICMP(ulp)->icmp_type;
1149 ip = mtod(m, struct ip *);
1150 args->f_id.src_ip = ntohl(src_ip.s_addr);
1151 args->f_id.dst_ip = ntohl(dst_ip.s_addr);
1154 if (proto) { /* we may have port numbers, store them */
1155 args->f_id.proto = proto;
1156 args->f_id.src_port = src_port = ntohs(src_port);
1157 args->f_id.dst_port = dst_port = ntohs(dst_port);
1161 if (! V_ipfw_vnet_ready) { /* shutting down, leave NOW. */
1162 IPFW_RUNLOCK(chain);
1163 return (IP_FW_PASS); /* accept */
1165 if (args->rule.slot) {
1167 * Packet has already been tagged as a result of a previous
1168 * match on rule args->rule aka args->rule_id (PIPE, QUEUE,
1169 * REASS, NETGRAPH, DIVERT/TEE...)
1170 * Validate the slot and continue from the next one
1171 * if still present, otherwise do a lookup.
1173 f_pos = (args->rule.chain_id == chain->id) ?
1175 ipfw_find_rule(chain, args->rule.rulenum,
1176 args->rule.rule_id);
1182 * Now scan the rules, and parse microinstructions for each rule.
1183 * We have two nested loops and an inner switch. Sometimes we
1184 * need to break out of one or both loops, or re-enter one of
1185 * the loops with updated variables. Loop variables are:
1187 * f_pos (outer loop) points to the current rule.
1188 * On output it points to the matching rule.
1189 * done (outer loop) is used as a flag to break the loop.
1190 * l (inner loop) residual length of current rule.
1191 * cmd points to the current microinstruction.
1193 * We break the inner loop by setting l=0 and possibly
1194 * cmdlen=0 if we don't want to advance cmd.
1195 * We break the outer loop by setting done=1
1196 * We can restart the inner loop by setting l>0 and f_pos, f, cmd
1199 for (; f_pos < chain->n_rules; f_pos++) {
1201 uint32_t tablearg = 0;
1202 int l, cmdlen, skip_or; /* skip rest of OR block */
1205 f = chain->map[f_pos];
1206 if (V_set_disable & (1 << f->set) )
1210 for (l = f->cmd_len, cmd = f->cmd ; l > 0 ;
1211 l -= cmdlen, cmd += cmdlen) {
1215 * check_body is a jump target used when we find a
1216 * CHECK_STATE, and need to jump to the body of
1221 cmdlen = F_LEN(cmd);
1223 * An OR block (insn_1 || .. || insn_n) has the
1224 * F_OR bit set in all but the last instruction.
1225 * The first match will set "skip_or", and cause
1226 * the following instructions to be skipped until
1227 * past the one with the F_OR bit clear.
1229 if (skip_or) { /* skip this instruction */
1230 if ((cmd->len & F_OR) == 0)
1231 skip_or = 0; /* next one is good */
1234 match = 0; /* set to 1 if we succeed */
1236 switch (cmd->opcode) {
1238 * The first set of opcodes compares the packet's
1239 * fields with some pattern, setting 'match' if a
1240 * match is found. At the end of the loop there is
1241 * logic to deal with F_NOT and F_OR flags associated
1249 printf("ipfw: opcode %d unimplemented\n",
1257 * We only check offset == 0 && proto != 0,
1258 * as this ensures that we have a
1259 * packet with the ports info.
1263 if (is_ipv6) /* XXX to be fixed later */
1265 if (proto == IPPROTO_TCP ||
1266 proto == IPPROTO_UDP)
1267 match = check_uidgid(
1268 (ipfw_insn_u32 *)cmd,
1271 src_ip, src_port, &ucred_lookup,
1273 &ucred_cache, args->inp);
1275 (void *)&ucred_cache,
1276 (struct inpcb *)args->m);
1281 match = iface_match(m->m_pkthdr.rcvif,
1282 (ipfw_insn_if *)cmd);
1286 match = iface_match(oif, (ipfw_insn_if *)cmd);
1290 match = iface_match(oif ? oif :
1291 m->m_pkthdr.rcvif, (ipfw_insn_if *)cmd);
1295 if (args->eh != NULL) { /* have MAC header */
1296 u_int32_t *want = (u_int32_t *)
1297 ((ipfw_insn_mac *)cmd)->addr;
1298 u_int32_t *mask = (u_int32_t *)
1299 ((ipfw_insn_mac *)cmd)->mask;
1300 u_int32_t *hdr = (u_int32_t *)args->eh;
1303 ( want[0] == (hdr[0] & mask[0]) &&
1304 want[1] == (hdr[1] & mask[1]) &&
1305 want[2] == (hdr[2] & mask[2]) );
1310 if (args->eh != NULL) {
1312 ((ipfw_insn_u16 *)cmd)->ports;
1315 for (i = cmdlen - 1; !match && i>0;
1317 match = (etype >= p[0] &&
1323 match = (offset != 0);
1326 case O_IN: /* "out" is "not in" */
1327 match = (oif == NULL);
1331 match = (args->eh != NULL);
1336 /* For diverted packets, args->rule.info
1337 * contains the divert port (in host format)
1338 * reason and direction.
1340 uint32_t i = args->rule.info;
1341 match = (i&IPFW_IS_MASK) == IPFW_IS_DIVERT &&
1342 cmd->arg1 & ((i & IPFW_INFO_IN) ? 1 : 2);
1348 * We do not allow an arg of 0 so the
1349 * check of "proto" only suffices.
1351 match = (proto == cmd->arg1);
1356 (((ipfw_insn_ip *)cmd)->addr.s_addr ==
1360 case O_IP_SRC_LOOKUP:
1361 case O_IP_DST_LOOKUP:
1364 (cmd->opcode == O_IP_DST_LOOKUP) ?
1365 dst_ip.s_addr : src_ip.s_addr;
1368 if (cmdlen > F_INSN_SIZE(ipfw_insn_u32)) {
1369 /* generic lookup. The key must be
1370 * in 32bit big-endian format.
1372 v = ((ipfw_insn_u32 *)cmd)->d[1];
1374 key = dst_ip.s_addr;
1376 key = src_ip.s_addr;
1377 else if (v == 6) /* dscp */
1378 key = (ip->ip_tos >> 2) & 0x3f;
1379 else if (offset != 0)
1381 else if (proto != IPPROTO_TCP &&
1382 proto != IPPROTO_UDP)
1385 key = htonl(dst_port);
1387 key = htonl(src_port);
1388 else if (v == 4 || v == 5) {
1390 (ipfw_insn_u32 *)cmd,
1393 src_ip, src_port, &ucred_lookup,
1395 &ucred_cache, args->inp);
1396 if (v == 4 /* O_UID */)
1397 key = ucred_cache->cr_uid;
1398 else if (v == 5 /* O_JAIL */)
1399 key = ucred_cache->cr_prison->pr_id;
1400 #else /* !__FreeBSD__ */
1401 (void *)&ucred_cache,
1402 (struct inpcb *)args->m);
1403 if (v ==4 /* O_UID */)
1404 key = ucred_cache.uid;
1405 else if (v == 5 /* O_JAIL */)
1406 key = ucred_cache.xid;
1407 #endif /* !__FreeBSD__ */
1412 match = ipfw_lookup_table(chain,
1413 cmd->arg1, key, &v);
1416 if (cmdlen == F_INSN_SIZE(ipfw_insn_u32))
1418 ((ipfw_insn_u32 *)cmd)->d[0] == v;
1428 (cmd->opcode == O_IP_DST_MASK) ?
1429 dst_ip.s_addr : src_ip.s_addr;
1430 uint32_t *p = ((ipfw_insn_u32 *)cmd)->d;
1433 for (; !match && i>0; i-= 2, p+= 2)
1434 match = (p[0] == (a & p[1]));
1442 INADDR_TO_IFP(src_ip, tif);
1443 match = (tif != NULL);
1449 match= is_ipv6 && search_ip6_addr_net(&args->f_id.src_ip6);
1456 u_int32_t *d = (u_int32_t *)(cmd+1);
1458 cmd->opcode == O_IP_DST_SET ?
1464 addr -= d[0]; /* subtract base */
1465 match = (addr < cmd->arg1) &&
1466 ( d[ 1 + (addr>>5)] &
1467 (1<<(addr & 0x1f)) );
1473 (((ipfw_insn_ip *)cmd)->addr.s_addr ==
1481 INADDR_TO_IFP(dst_ip, tif);
1482 match = (tif != NULL);
1488 match= is_ipv6 && search_ip6_addr_net(&args->f_id.dst_ip6);
1496 * offset == 0 && proto != 0 is enough
1497 * to guarantee that we have a
1498 * packet with port info.
1500 if ((proto==IPPROTO_UDP || proto==IPPROTO_TCP)
1503 (cmd->opcode == O_IP_SRCPORT) ?
1504 src_port : dst_port ;
1506 ((ipfw_insn_u16 *)cmd)->ports;
1509 for (i = cmdlen - 1; !match && i>0;
1511 match = (x>=p[0] && x<=p[1]);
1516 match = (offset == 0 && proto==IPPROTO_ICMP &&
1517 icmptype_match(ICMP(ulp), (ipfw_insn_u32 *)cmd) );
1522 match = is_ipv6 && offset == 0 &&
1523 proto==IPPROTO_ICMPV6 &&
1525 ICMP6(ulp)->icmp6_type,
1526 (ipfw_insn_u32 *)cmd);
1532 ipopts_match(ip, cmd) );
1537 cmd->arg1 == ip->ip_v);
1543 if (is_ipv4) { /* only for IP packets */
1548 if (cmd->opcode == O_IPLEN)
1550 else if (cmd->opcode == O_IPTTL)
1552 else /* must be IPID */
1553 x = ntohs(ip->ip_id);
1555 match = (cmd->arg1 == x);
1558 /* otherwise we have ranges */
1559 p = ((ipfw_insn_u16 *)cmd)->ports;
1561 for (; !match && i>0; i--, p += 2)
1562 match = (x >= p[0] && x <= p[1]);
1566 case O_IPPRECEDENCE:
1568 (cmd->arg1 == (ip->ip_tos & 0xe0)) );
1573 flags_match(cmd, ip->ip_tos));
1577 if (proto == IPPROTO_TCP && offset == 0) {
1585 ((ip->ip_hl + tcp->th_off) << 2);
1587 match = (cmd->arg1 == x);
1590 /* otherwise we have ranges */
1591 p = ((ipfw_insn_u16 *)cmd)->ports;
1593 for (; !match && i>0; i--, p += 2)
1594 match = (x >= p[0] && x <= p[1]);
1599 match = (proto == IPPROTO_TCP && offset == 0 &&
1600 flags_match(cmd, TCP(ulp)->th_flags));
1604 PULLUP_LEN(hlen, ulp, (TCP(ulp)->th_off << 2));
1605 match = (proto == IPPROTO_TCP && offset == 0 &&
1606 tcpopts_match(TCP(ulp), cmd));
1610 match = (proto == IPPROTO_TCP && offset == 0 &&
1611 ((ipfw_insn_u32 *)cmd)->d[0] ==
1616 match = (proto == IPPROTO_TCP && offset == 0 &&
1617 ((ipfw_insn_u32 *)cmd)->d[0] ==
1622 match = (proto == IPPROTO_TCP && offset == 0 &&
1623 cmd->arg1 == TCP(ulp)->th_win);
1627 /* reject packets which have SYN only */
1628 /* XXX should i also check for TH_ACK ? */
1629 match = (proto == IPPROTO_TCP && offset == 0 &&
1630 (TCP(ulp)->th_flags &
1631 (TH_RST | TH_ACK | TH_SYN)) != TH_SYN);
1636 ipfw_insn_altq *altq = (ipfw_insn_altq *)cmd;
1639 at = pf_find_mtag(m);
1640 if (at != NULL && at->qid != 0)
1642 at = pf_get_mtag(m);
1645 * Let the packet fall back to the
1650 at->qid = altq->qid;
1660 ipfw_log(f, hlen, args, m,
1661 oif, offset, tablearg, ip);
1666 match = (random()<((ipfw_insn_u32 *)cmd)->d[0]);
1670 /* Outgoing packets automatically pass/match */
1671 match = ((oif != NULL) ||
1672 (m->m_pkthdr.rcvif == NULL) ||
1676 verify_path6(&(args->f_id.src_ip6),
1677 m->m_pkthdr.rcvif) :
1679 verify_path(src_ip, m->m_pkthdr.rcvif,
1684 /* Outgoing packets automatically pass/match */
1685 match = (hlen > 0 && ((oif != NULL) ||
1688 verify_path6(&(args->f_id.src_ip6),
1691 verify_path(src_ip, NULL, args->f_id.fib)));
1695 /* Outgoing packets automatically pass/match */
1696 if (oif == NULL && hlen > 0 &&
1697 ( (is_ipv4 && in_localaddr(src_ip))
1700 in6_localaddr(&(args->f_id.src_ip6)))
1705 is_ipv6 ? verify_path6(
1706 &(args->f_id.src_ip6),
1707 m->m_pkthdr.rcvif) :
1718 match = (m_tag_find(m,
1719 PACKET_TAG_IPSEC_IN_DONE, NULL) != NULL);
1721 /* otherwise no match */
1727 IN6_ARE_ADDR_EQUAL(&args->f_id.src_ip6,
1728 &((ipfw_insn_ip6 *)cmd)->addr6);
1733 IN6_ARE_ADDR_EQUAL(&args->f_id.dst_ip6,
1734 &((ipfw_insn_ip6 *)cmd)->addr6);
1736 case O_IP6_SRC_MASK:
1737 case O_IP6_DST_MASK:
1741 struct in6_addr *d =
1742 &((ipfw_insn_ip6 *)cmd)->addr6;
1744 for (; !match && i > 0; d += 2,
1745 i -= F_INSN_SIZE(struct in6_addr)
1751 APPLY_MASK(&p, &d[1]);
1753 IN6_ARE_ADDR_EQUAL(&d[0],
1761 flow6id_match(args->f_id.flow_id6,
1762 (ipfw_insn_u32 *) cmd);
1767 (ext_hd & ((ipfw_insn *) cmd)->arg1);
1781 uint32_t tag = (cmd->arg1 == IP_FW_TABLEARG) ?
1782 tablearg : cmd->arg1;
1784 /* Packet is already tagged with this tag? */
1785 mtag = m_tag_locate(m, MTAG_IPFW, tag, NULL);
1787 /* We have `untag' action when F_NOT flag is
1788 * present. And we must remove this mtag from
1789 * mbuf and reset `match' to zero (`match' will
1790 * be inversed later).
1791 * Otherwise we should allocate new mtag and
1792 * push it into mbuf.
1794 if (cmd->len & F_NOT) { /* `untag' action */
1796 m_tag_delete(m, mtag);
1800 mtag = m_tag_alloc( MTAG_IPFW,
1803 m_tag_prepend(m, mtag);
1810 case O_FIB: /* try match the specified fib */
1811 if (args->f_id.fib == cmd->arg1)
1817 uint32_t tag = (cmd->arg1 == IP_FW_TABLEARG) ?
1818 tablearg : cmd->arg1;
1821 match = m_tag_locate(m, MTAG_IPFW,
1826 /* we have ranges */
1827 for (mtag = m_tag_first(m);
1828 mtag != NULL && !match;
1829 mtag = m_tag_next(m, mtag)) {
1833 if (mtag->m_tag_cookie != MTAG_IPFW)
1836 p = ((ipfw_insn_u16 *)cmd)->ports;
1838 for(; !match && i > 0; i--, p += 2)
1840 mtag->m_tag_id >= p[0] &&
1841 mtag->m_tag_id <= p[1];
1847 * The second set of opcodes represents 'actions',
1848 * i.e. the terminal part of a rule once the packet
1849 * matches all previous patterns.
1850 * Typically there is only one action for each rule,
1851 * and the opcode is stored at the end of the rule
1852 * (but there are exceptions -- see below).
1854 * In general, here we set retval and terminate the
1855 * outer loop (would be a 'break 3' in some language,
1856 * but we need to set l=0, done=1)
1859 * O_COUNT and O_SKIPTO actions:
1860 * instead of terminating, we jump to the next rule
1861 * (setting l=0), or to the SKIPTO target (setting
1862 * f/f_len, cmd and l as needed), respectively.
1864 * O_TAG, O_LOG and O_ALTQ action parameters:
1865 * perform some action and set match = 1;
1867 * O_LIMIT and O_KEEP_STATE: these opcodes are
1868 * not real 'actions', and are stored right
1869 * before the 'action' part of the rule.
1870 * These opcodes try to install an entry in the
1871 * state tables; if successful, we continue with
1872 * the next opcode (match=1; break;), otherwise
1873 * the packet must be dropped (set retval,
1874 * break loops with l=0, done=1)
1876 * O_PROBE_STATE and O_CHECK_STATE: these opcodes
1877 * cause a lookup of the state table, and a jump
1878 * to the 'action' part of the parent rule
1879 * if an entry is found, or
1880 * (CHECK_STATE only) a jump to the next rule if
1881 * the entry is not found.
1882 * The result of the lookup is cached so that
1883 * further instances of these opcodes become NOPs.
1884 * The jump to the next rule is done by setting
1889 if (ipfw_install_state(f,
1890 (ipfw_insn_limit *)cmd, args, tablearg)) {
1891 /* error or limit violation */
1892 retval = IP_FW_DENY;
1893 l = 0; /* exit inner loop */
1894 done = 1; /* exit outer loop */
1902 * dynamic rules are checked at the first
1903 * keep-state or check-state occurrence,
1904 * with the result being stored in dyn_dir.
1905 * The compiler introduces a PROBE_STATE
1906 * instruction for us when we have a
1907 * KEEP_STATE (because PROBE_STATE needs
1910 if (dyn_dir == MATCH_UNKNOWN &&
1911 (q = ipfw_lookup_dyn_rule(&args->f_id,
1912 &dyn_dir, proto == IPPROTO_TCP ?
1916 * Found dynamic entry, update stats
1917 * and jump to the 'action' part of
1918 * the parent rule by setting
1919 * f, cmd, l and clearing cmdlen.
1923 /* XXX we would like to have f_pos
1924 * readily accessible in the dynamic
1925 * rule, instead of having to
1929 f_pos = ipfw_find_rule(chain,
1931 cmd = ACTION_PTR(f);
1932 l = f->cmd_len - f->act_ofs;
1939 * Dynamic entry not found. If CHECK_STATE,
1940 * skip to next rule, if PROBE_STATE just
1941 * ignore and continue with next opcode.
1943 if (cmd->opcode == O_CHECK_STATE)
1944 l = 0; /* exit inner loop */
1949 retval = 0; /* accept */
1950 l = 0; /* exit inner loop */
1951 done = 1; /* exit outer loop */
1956 set_match(args, f_pos, chain);
1957 args->rule.info = (cmd->arg1 == IP_FW_TABLEARG) ?
1958 tablearg : cmd->arg1;
1959 if (cmd->opcode == O_PIPE)
1960 args->rule.info |= IPFW_IS_PIPE;
1962 args->rule.info |= IPFW_ONEPASS;
1963 retval = IP_FW_DUMMYNET;
1964 l = 0; /* exit inner loop */
1965 done = 1; /* exit outer loop */
1970 if (args->eh) /* not on layer 2 */
1972 /* otherwise this is terminal */
1973 l = 0; /* exit inner loop */
1974 done = 1; /* exit outer loop */
1975 retval = (cmd->opcode == O_DIVERT) ?
1976 IP_FW_DIVERT : IP_FW_TEE;
1977 set_match(args, f_pos, chain);
1978 args->rule.info = (cmd->arg1 == IP_FW_TABLEARG) ?
1979 tablearg : cmd->arg1;
1983 f->pcnt++; /* update stats */
1985 f->timestamp = time_uptime;
1986 l = 0; /* exit inner loop */
1990 f->pcnt++; /* update stats */
1992 f->timestamp = time_uptime;
1993 /* If possible use cached f_pos (in f->next_rule),
1994 * whose version is written in f->next_rule
1995 * (horrible hacks to avoid changing the ABI).
1997 if (cmd->arg1 != IP_FW_TABLEARG &&
1998 (uintptr_t)f->x_next == chain->id) {
1999 f_pos = (uintptr_t)f->next_rule;
2001 int i = (cmd->arg1 == IP_FW_TABLEARG) ?
2002 tablearg : cmd->arg1;
2003 /* make sure we do not jump backward */
2004 if (i <= f->rulenum)
2006 f_pos = ipfw_find_rule(chain, i, 0);
2007 /* update the cache */
2008 if (cmd->arg1 != IP_FW_TABLEARG) {
2010 (void *)(uintptr_t)f_pos;
2012 (void *)(uintptr_t)chain->id;
2016 * Skip disabled rules, and re-enter
2017 * the inner loop with the correct
2018 * f_pos, f, l and cmd.
2019 * Also clear cmdlen and skip_or
2021 for (; f_pos < chain->n_rules - 1 &&
2023 (1 << chain->map[f_pos]->set));
2026 /* Re-enter the inner loop at the skipto rule. */
2027 f = chain->map[f_pos];
2034 break; /* not reached */
2038 * Drop the packet and send a reject notice
2039 * if the packet is not ICMP (or is an ICMP
2040 * query), and it is not multicast/broadcast.
2042 if (hlen > 0 && is_ipv4 && offset == 0 &&
2043 (proto != IPPROTO_ICMP ||
2044 is_icmp_query(ICMP(ulp))) &&
2045 !(m->m_flags & (M_BCAST|M_MCAST)) &&
2046 !IN_MULTICAST(ntohl(dst_ip.s_addr))) {
2047 send_reject(args, cmd->arg1, iplen, ip);
2053 if (hlen > 0 && is_ipv6 &&
2054 ((offset & IP6F_OFF_MASK) == 0) &&
2055 (proto != IPPROTO_ICMPV6 ||
2056 (is_icmp6_query(icmp6_type) == 1)) &&
2057 !(m->m_flags & (M_BCAST|M_MCAST)) &&
2058 !IN6_IS_ADDR_MULTICAST(&args->f_id.dst_ip6)) {
2060 args, cmd->arg1, hlen,
2061 (struct ip6_hdr *)ip);
2067 retval = IP_FW_DENY;
2068 l = 0; /* exit inner loop */
2069 done = 1; /* exit outer loop */
2073 if (args->eh) /* not valid on layer2 pkts */
2075 if (q == NULL || q->rule != f ||
2076 dyn_dir == MATCH_FORWARD) {
2077 struct sockaddr_in *sa;
2078 sa = &(((ipfw_insn_sa *)cmd)->sa);
2079 if (sa->sin_addr.s_addr == INADDR_ANY) {
2080 bcopy(sa, &args->hopstore,
2082 args->hopstore.sin_addr.s_addr =
2084 args->next_hop = &args->hopstore;
2086 args->next_hop = sa;
2089 retval = IP_FW_PASS;
2090 l = 0; /* exit inner loop */
2091 done = 1; /* exit outer loop */
2096 set_match(args, f_pos, chain);
2097 args->rule.info = (cmd->arg1 == IP_FW_TABLEARG) ?
2098 tablearg : cmd->arg1;
2100 args->rule.info |= IPFW_ONEPASS;
2101 retval = (cmd->opcode == O_NETGRAPH) ?
2102 IP_FW_NETGRAPH : IP_FW_NGTEE;
2103 l = 0; /* exit inner loop */
2104 done = 1; /* exit outer loop */
2110 f->pcnt++; /* update stats */
2112 f->timestamp = time_uptime;
2113 fib = (cmd->arg1 == IP_FW_TABLEARG) ? tablearg:
2115 if (fib >= rt_numfibs)
2118 args->f_id.fib = fib;
2119 l = 0; /* exit inner loop */
2124 if (!IPFW_NAT_LOADED) {
2125 retval = IP_FW_DENY;
2130 set_match(args, f_pos, chain);
2131 /* Check if this is 'global' nat rule */
2132 if (cmd->arg1 == 0) {
2133 retval = ipfw_nat_ptr(args, NULL, m);
2138 t = ((ipfw_insn_nat *)cmd)->nat;
2140 nat_id = (cmd->arg1 == IP_FW_TABLEARG) ?
2141 tablearg : cmd->arg1;
2142 t = (*lookup_nat_ptr)(&chain->nat, nat_id);
2145 retval = IP_FW_DENY;
2146 l = 0; /* exit inner loop */
2147 done = 1; /* exit outer loop */
2150 if (cmd->arg1 != IP_FW_TABLEARG)
2151 ((ipfw_insn_nat *)cmd)->nat = t;
2153 retval = ipfw_nat_ptr(args, t, m);
2155 l = 0; /* exit inner loop */
2156 done = 1; /* exit outer loop */
2164 l = 0; /* in any case exit inner loop */
2165 ip_off = ntohs(ip->ip_off);
2167 /* if not fragmented, go to next rule */
2168 if ((ip_off & (IP_MF | IP_OFFMASK)) == 0)
2171 * ip_reass() expects len & off in host
2176 args->m = m = ip_reass(m);
2179 * do IP header checksum fixup.
2181 if (m == NULL) { /* fragment got swallowed */
2182 retval = IP_FW_DENY;
2183 } else { /* good, packet complete */
2186 ip = mtod(m, struct ip *);
2187 hlen = ip->ip_hl << 2;
2190 if (hlen == sizeof(struct ip))
2191 ip->ip_sum = in_cksum_hdr(ip);
2193 ip->ip_sum = in_cksum(m, hlen);
2194 retval = IP_FW_REASS;
2195 set_match(args, f_pos, chain);
2197 done = 1; /* exit outer loop */
2202 panic("-- unknown opcode %d\n", cmd->opcode);
2203 } /* end of switch() on opcodes */
2205 * if we get here with l=0, then match is irrelevant.
2208 if (cmd->len & F_NOT)
2212 if (cmd->len & F_OR)
2215 if (!(cmd->len & F_OR)) /* not an OR block, */
2216 break; /* try next rule */
2219 } /* end of inner loop, scan opcodes */
2225 /* next_rule:; */ /* try next rule */
2227 } /* end of outer for, scan rules */
2230 struct ip_fw *rule = chain->map[f_pos];
2231 /* Update statistics */
2233 rule->bcnt += pktlen;
2234 rule->timestamp = time_uptime;
2236 retval = IP_FW_DENY;
2237 printf("ipfw: ouch!, skip past end of rules, denying packet\n");
2239 IPFW_RUNLOCK(chain);
2241 if (ucred_cache != NULL)
2242 crfree(ucred_cache);
2248 printf("ipfw: pullup failed\n");
2249 return (IP_FW_DENY);
2253 * Module and VNET glue
2257 * Stuff that must be initialised only on boot or module load
2266 * Only print out this stuff the first time around,
2267 * when called from the sysinit code.
2273 "initialized, divert %s, nat %s, "
2274 "rule-based forwarding "
2275 #ifdef IPFIREWALL_FORWARD
2280 "default to %s, logging ",
2286 #ifdef IPFIREWALL_NAT
2291 default_to_accept ? "accept" : "deny");
2294 * Note: V_xxx variables can be accessed here but the vnet specific
2295 * initializer may not have been called yet for the VIMAGE case.
2296 * Tuneables will have been processed. We will print out values for
2298 * XXX This should all be rationalized AFTER 8.0
2300 if (V_fw_verbose == 0)
2301 printf("disabled\n");
2302 else if (V_verbose_limit == 0)
2303 printf("unlimited\n");
2305 printf("limited to %d packets/entry by default\n",
2308 ipfw_log_bpf(1); /* init */
2313 * Called for the removal of the last instance only on module unload.
2319 ipfw_log_bpf(0); /* uninit */
2321 printf("IP firewall unloaded\n");
2325 * Stuff that must be initialized for every instance
2326 * (including the first of course).
2329 vnet_ipfw_init(const void *unused)
2332 struct ip_fw *rule = NULL;
2333 struct ip_fw_chain *chain;
2335 chain = &V_layer3_chain;
2337 /* First set up some values that are compile time options */
2338 V_autoinc_step = 100; /* bounded to 1..1000 in add_rule() */
2339 V_fw_deny_unknown_exthdrs = 1;
2340 #ifdef IPFIREWALL_VERBOSE
2343 #ifdef IPFIREWALL_VERBOSE_LIMIT
2344 V_verbose_limit = IPFIREWALL_VERBOSE_LIMIT;
2346 #ifdef IPFIREWALL_NAT
2347 LIST_INIT(&chain->nat);
2350 /* insert the default rule and create the initial map */
2352 chain->static_len = sizeof(struct ip_fw);
2353 chain->map = malloc(sizeof(struct ip_fw *), M_IPFW, M_NOWAIT | M_ZERO);
2355 rule = malloc(chain->static_len, M_IPFW, M_NOWAIT | M_ZERO);
2358 free(chain->map, M_IPFW);
2359 printf("ipfw2: ENOSPC initializing default rule "
2360 "(support disabled)\n");
2363 error = ipfw_init_tables(chain);
2365 panic("init_tables"); /* XXX Marko fix this ! */
2368 /* fill and insert the default rule */
2370 rule->rulenum = IPFW_DEFAULT_RULE;
2372 rule->set = RESVD_SET;
2373 rule->cmd[0].len = 1;
2374 rule->cmd[0].opcode = default_to_accept ? O_ACCEPT : O_DENY;
2375 chain->rules = chain->default_rule = chain->map[0] = rule;
2376 chain->id = rule->id = 1;
2378 IPFW_LOCK_INIT(chain);
2381 /* First set up some values that are compile time options */
2382 V_ipfw_vnet_ready = 1; /* Open for business */
2385 * Hook the sockopt handler, and the layer2 (V_ip_fw_chk_ptr)
2386 * and pfil hooks for ipv4 and ipv6. Even if the latter two fail
2387 * we still keep the module alive because the sockopt and
2388 * layer2 paths are still useful.
2389 * ipfw[6]_hook return 0 on success, ENOENT on failure,
2390 * so we can ignore the exact return value and just set a flag.
2392 * Note that V_fw[6]_enable are manipulated by a SYSCTL_PROC so
2393 * changes in the underlying (per-vnet) variables trigger
2394 * immediate hook()/unhook() calls.
2395 * In layer2 we have the same behaviour, except that V_ether_ipfw
2396 * is checked on each packet because there are no pfil hooks.
2398 V_ip_fw_ctl_ptr = ipfw_ctl;
2399 V_ip_fw_chk_ptr = ipfw_chk;
2400 error = ipfw_attach_hooks(1);
2405 * Called for the removal of each instance.
2408 vnet_ipfw_uninit(const void *unused)
2410 struct ip_fw *reap, *rule;
2411 struct ip_fw_chain *chain = &V_layer3_chain;
2414 V_ipfw_vnet_ready = 0; /* tell new callers to go away */
2416 * disconnect from ipv4, ipv6, layer2 and sockopt.
2417 * Then grab, release and grab again the WLOCK so we make
2418 * sure the update is propagated and nobody will be in.
2420 (void)ipfw_attach_hooks(0 /* detach */);
2421 V_ip_fw_chk_ptr = NULL;
2422 V_ip_fw_ctl_ptr = NULL;
2423 IPFW_UH_WLOCK(chain);
2424 IPFW_UH_WUNLOCK(chain);
2425 IPFW_UH_WLOCK(chain);
2428 IPFW_WUNLOCK(chain);
2431 ipfw_dyn_uninit(0); /* run the callout_drain */
2432 ipfw_destroy_tables(chain);
2434 for (i = 0; i < chain->n_rules; i++) {
2435 rule = chain->map[i];
2436 rule->x_next = reap;
2440 free(chain->map, M_IPFW);
2441 IPFW_WUNLOCK(chain);
2442 IPFW_UH_WUNLOCK(chain);
2444 ipfw_reap_rules(reap);
2445 IPFW_LOCK_DESTROY(chain);
2446 ipfw_dyn_uninit(1); /* free the remaining parts */
2451 * Module event handler.
2452 * In general we have the choice of handling most of these events by the
2453 * event handler or by the (VNET_)SYS(UN)INIT handlers. I have chosen to
2454 * use the SYSINIT handlers as they are more capable of expressing the
2455 * flow of control during module and vnet operations, so this is just
2456 * a skeleton. Note there is no SYSINIT equivalent of the module
2457 * SHUTDOWN handler, but we don't have anything to do in that case anyhow.
2460 ipfw_modevent(module_t mod, int type, void *unused)
2466 /* Called once at module load or
2467 * system boot if compiled in. */
2470 /* Called before unload. May veto unloading. */
2473 /* Called during unload. */
2476 /* Called during system shutdown. */
2485 static moduledata_t ipfwmod = {
2491 /* Define startup order. */
2492 #define IPFW_SI_SUB_FIREWALL SI_SUB_PROTO_IFATTACHDOMAIN
2493 #define IPFW_MODEVENT_ORDER (SI_ORDER_ANY - 255) /* On boot slot in here. */
2494 #define IPFW_MODULE_ORDER (IPFW_MODEVENT_ORDER + 1) /* A little later. */
2495 #define IPFW_VNET_ORDER (IPFW_MODEVENT_ORDER + 2) /* Later still. */
2497 DECLARE_MODULE(ipfw, ipfwmod, IPFW_SI_SUB_FIREWALL, IPFW_MODEVENT_ORDER);
2498 MODULE_VERSION(ipfw, 2);
2499 /* should declare some dependencies here */
2502 * Starting up. Done in order after ipfwmod() has been called.
2503 * VNET_SYSINIT is also called for each existing vnet and each new vnet.
2505 SYSINIT(ipfw_init, IPFW_SI_SUB_FIREWALL, IPFW_MODULE_ORDER,
2507 VNET_SYSINIT(vnet_ipfw_init, IPFW_SI_SUB_FIREWALL, IPFW_VNET_ORDER,
2508 vnet_ipfw_init, NULL);
2511 * Closing up shop. These are done in REVERSE ORDER, but still
2512 * after ipfwmod() has been called. Not called on reboot.
2513 * VNET_SYSUNINIT is also called for each exiting vnet as it exits.
2514 * or when the module is unloaded.
2516 SYSUNINIT(ipfw_destroy, IPFW_SI_SUB_FIREWALL, IPFW_MODULE_ORDER,
2517 ipfw_destroy, NULL);
2518 VNET_SYSUNINIT(vnet_ipfw_uninit, IPFW_SI_SUB_FIREWALL, IPFW_VNET_ORDER,
2519 vnet_ipfw_uninit, NULL);