2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (c) 2002-2009 Luigi Rizzo, Universita` di Pisa
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD$");
32 * The FreeBSD IP packet firewall, main file
36 #include "opt_ipdivert.h"
39 #error "IPFIREWALL requires INET"
41 #include "opt_inet6.h"
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/condvar.h>
46 #include <sys/counter.h>
47 #include <sys/eventhandler.h>
48 #include <sys/malloc.h>
50 #include <sys/kernel.h>
53 #include <sys/module.h>
56 #include <sys/rwlock.h>
57 #include <sys/rmlock.h>
59 #include <sys/socket.h>
60 #include <sys/socketvar.h>
61 #include <sys/sysctl.h>
62 #include <sys/syslog.h>
63 #include <sys/ucred.h>
64 #include <net/ethernet.h> /* for ETHERTYPE_IP */
66 #include <net/if_var.h>
67 #include <net/route.h>
68 #include <net/route/nhop.h>
72 #include <netpfil/pf/pf_mtag.h>
74 #include <netinet/in.h>
75 #include <netinet/in_var.h>
76 #include <netinet/in_pcb.h>
77 #include <netinet/ip.h>
78 #include <netinet/ip_var.h>
79 #include <netinet/ip_icmp.h>
80 #include <netinet/ip_fw.h>
81 #include <netinet/ip_carp.h>
82 #include <netinet/pim.h>
83 #include <netinet/tcp_var.h>
84 #include <netinet/udp.h>
85 #include <netinet/udp_var.h>
86 #include <netinet/sctp.h>
87 #include <netinet/sctp_crc32.h>
88 #include <netinet/sctp_header.h>
90 #include <netinet/ip6.h>
91 #include <netinet/icmp6.h>
92 #include <netinet/in_fib.h>
94 #include <netinet6/in6_fib.h>
95 #include <netinet6/in6_pcb.h>
96 #include <netinet6/scope6_var.h>
97 #include <netinet6/ip6_var.h>
100 #include <net/if_gre.h> /* for struct grehdr */
102 #include <netpfil/ipfw/ip_fw_private.h>
104 #include <machine/in_cksum.h> /* XXX for in_cksum */
107 #include <security/mac/mac_framework.h>
110 #define IPFW_PROBE(probe, arg0, arg1, arg2, arg3, arg4, arg5) \
111 SDT_PROBE6(ipfw, , , probe, arg0, arg1, arg2, arg3, arg4, arg5)
113 SDT_PROVIDER_DEFINE(ipfw);
114 SDT_PROBE_DEFINE6(ipfw, , , rule__matched,
117 "void *", /* src addr */
118 "void *", /* dst addr */
119 "struct ip_fw_args *", /* args */
120 "struct ip_fw *" /* rule */);
123 * static variables followed by global ones.
124 * All ipfw global variables are here.
127 VNET_DEFINE_STATIC(int, fw_deny_unknown_exthdrs);
128 #define V_fw_deny_unknown_exthdrs VNET(fw_deny_unknown_exthdrs)
130 VNET_DEFINE_STATIC(int, fw_permit_single_frag6) = 1;
131 #define V_fw_permit_single_frag6 VNET(fw_permit_single_frag6)
133 #ifdef IPFIREWALL_DEFAULT_TO_ACCEPT
134 static int default_to_accept = 1;
136 static int default_to_accept;
139 VNET_DEFINE(int, autoinc_step);
140 VNET_DEFINE(int, fw_one_pass) = 1;
142 VNET_DEFINE(unsigned int, fw_tables_max);
143 VNET_DEFINE(unsigned int, fw_tables_sets) = 0; /* Don't use set-aware tables */
144 /* Use 128 tables by default */
145 static unsigned int default_fw_tables = IPFW_TABLES_DEFAULT;
147 static int jump_lookup_pos(struct ip_fw_chain *chain, struct ip_fw *f, int num,
148 int tablearg, int jump_backwards);
149 #ifndef LINEAR_SKIPTO
150 static int jump_cached(struct ip_fw_chain *chain, struct ip_fw *f, int num,
151 int tablearg, int jump_backwards);
152 #define JUMP(ch, f, num, targ, back) jump_cached(ch, f, num, targ, back)
154 #define JUMP(ch, f, num, targ, back) jump_lookup_pos(ch, f, num, targ, back)
158 * Each rule belongs to one of 32 different sets (0..31).
159 * The variable set_disable contains one bit per set.
160 * If the bit is set, all rules in the corresponding set
161 * are disabled. Set RESVD_SET(31) is reserved for the default rule
162 * and rules that are not deleted by the flush command,
163 * and CANNOT be disabled.
164 * Rules in set RESVD_SET can only be deleted individually.
166 VNET_DEFINE(u_int32_t, set_disable);
167 #define V_set_disable VNET(set_disable)
169 VNET_DEFINE(int, fw_verbose);
170 /* counter for ipfw_log(NULL...) */
171 VNET_DEFINE(u_int64_t, norule_counter);
172 VNET_DEFINE(int, verbose_limit);
174 /* layer3_chain contains the list of rules for layer 3 */
175 VNET_DEFINE(struct ip_fw_chain, layer3_chain);
177 /* ipfw_vnet_ready controls when we are open for business */
178 VNET_DEFINE(int, ipfw_vnet_ready) = 0;
180 VNET_DEFINE(int, ipfw_nat_ready) = 0;
182 ipfw_nat_t *ipfw_nat_ptr = NULL;
183 struct cfg_nat *(*lookup_nat_ptr)(struct nat_list *, int);
184 ipfw_nat_cfg_t *ipfw_nat_cfg_ptr;
185 ipfw_nat_cfg_t *ipfw_nat_del_ptr;
186 ipfw_nat_cfg_t *ipfw_nat_get_cfg_ptr;
187 ipfw_nat_cfg_t *ipfw_nat_get_log_ptr;
190 uint32_t dummy_def = IPFW_DEFAULT_RULE;
191 static int sysctl_ipfw_table_num(SYSCTL_HANDLER_ARGS);
192 static int sysctl_ipfw_tables_sets(SYSCTL_HANDLER_ARGS);
196 SYSCTL_NODE(_net_inet_ip, OID_AUTO, fw, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
198 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, one_pass,
199 CTLFLAG_VNET | CTLFLAG_RW | CTLFLAG_SECURE3, &VNET_NAME(fw_one_pass), 0,
200 "Only do a single pass through ipfw when using dummynet(4)");
201 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, autoinc_step,
202 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(autoinc_step), 0,
203 "Rule number auto-increment step");
204 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose,
205 CTLFLAG_VNET | CTLFLAG_RW | CTLFLAG_SECURE3, &VNET_NAME(fw_verbose), 0,
206 "Log matches to ipfw rules");
207 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose_limit,
208 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(verbose_limit), 0,
209 "Set upper limit of matches of ipfw rules logged");
210 SYSCTL_UINT(_net_inet_ip_fw, OID_AUTO, default_rule, CTLFLAG_RD,
212 "The default/max possible rule number.");
213 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, tables_max,
214 CTLFLAG_VNET | CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_MPSAFE,
215 0, 0, sysctl_ipfw_table_num, "IU",
216 "Maximum number of concurrently used tables");
217 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, tables_sets,
218 CTLFLAG_VNET | CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_MPSAFE,
219 0, 0, sysctl_ipfw_tables_sets, "IU",
220 "Use per-set namespace for tables");
221 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, default_to_accept, CTLFLAG_RDTUN,
222 &default_to_accept, 0,
223 "Make the default rule accept all packets.");
224 TUNABLE_INT("net.inet.ip.fw.tables_max", (int *)&default_fw_tables);
225 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, static_count,
226 CTLFLAG_VNET | CTLFLAG_RD, &VNET_NAME(layer3_chain.n_rules), 0,
227 "Number of static rules");
230 SYSCTL_DECL(_net_inet6_ip6);
231 SYSCTL_NODE(_net_inet6_ip6, OID_AUTO, fw, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
233 SYSCTL_INT(_net_inet6_ip6_fw, OID_AUTO, deny_unknown_exthdrs,
234 CTLFLAG_VNET | CTLFLAG_RW | CTLFLAG_SECURE,
235 &VNET_NAME(fw_deny_unknown_exthdrs), 0,
236 "Deny packets with unknown IPv6 Extension Headers");
237 SYSCTL_INT(_net_inet6_ip6_fw, OID_AUTO, permit_single_frag6,
238 CTLFLAG_VNET | CTLFLAG_RW | CTLFLAG_SECURE,
239 &VNET_NAME(fw_permit_single_frag6), 0,
240 "Permit single packet IPv6 fragments");
245 #endif /* SYSCTL_NODE */
248 * Some macros used in the various matching options.
249 * L3HDR maps an ipv4 pointer into a layer3 header pointer of type T
250 * Other macros just cast void * into the appropriate type
252 #define L3HDR(T, ip) ((T *)((u_int32_t *)(ip) + (ip)->ip_hl))
253 #define TCP(p) ((struct tcphdr *)(p))
254 #define SCTP(p) ((struct sctphdr *)(p))
255 #define UDP(p) ((struct udphdr *)(p))
256 #define ICMP(p) ((struct icmphdr *)(p))
257 #define ICMP6(p) ((struct icmp6_hdr *)(p))
260 icmptype_match(struct icmphdr *icmp, ipfw_insn_u32 *cmd)
262 int type = icmp->icmp_type;
264 return (type <= ICMP_MAXTYPE && (cmd->d[0] & (1<<type)) );
267 #define TT ( (1 << ICMP_ECHO) | (1 << ICMP_ROUTERSOLICIT) | \
268 (1 << ICMP_TSTAMP) | (1 << ICMP_IREQ) | (1 << ICMP_MASKREQ) )
271 is_icmp_query(struct icmphdr *icmp)
273 int type = icmp->icmp_type;
275 return (type <= ICMP_MAXTYPE && (TT & (1<<type)) );
280 * The following checks use two arrays of 8 or 16 bits to store the
281 * bits that we want set or clear, respectively. They are in the
282 * low and high half of cmd->arg1 or cmd->d[0].
284 * We scan options and store the bits we find set. We succeed if
286 * (want_set & ~bits) == 0 && (want_clear & ~bits) == want_clear
288 * The code is sometimes optimized not to store additional variables.
292 flags_match(ipfw_insn *cmd, u_int8_t bits)
297 if ( ((cmd->arg1 & 0xff) & bits) != 0)
298 return 0; /* some bits we want set were clear */
299 want_clear = (cmd->arg1 >> 8) & 0xff;
300 if ( (want_clear & bits) != want_clear)
301 return 0; /* some bits we want clear were set */
306 ipopts_match(struct ip *ip, ipfw_insn *cmd)
308 int optlen, bits = 0;
309 u_char *cp = (u_char *)(ip + 1);
310 int x = (ip->ip_hl << 2) - sizeof (struct ip);
312 for (; x > 0; x -= optlen, cp += optlen) {
313 int opt = cp[IPOPT_OPTVAL];
315 if (opt == IPOPT_EOL)
317 if (opt == IPOPT_NOP)
320 optlen = cp[IPOPT_OLEN];
321 if (optlen <= 0 || optlen > x)
322 return 0; /* invalid or truncated */
329 bits |= IP_FW_IPOPT_LSRR;
333 bits |= IP_FW_IPOPT_SSRR;
337 bits |= IP_FW_IPOPT_RR;
341 bits |= IP_FW_IPOPT_TS;
345 return (flags_match(cmd, bits));
349 * Parse TCP options. The logic copied from tcp_dooptions().
352 tcpopts_parse(const struct tcphdr *tcp, uint16_t *mss)
354 const u_char *cp = (const u_char *)(tcp + 1);
355 int optlen, bits = 0;
356 int cnt = (tcp->th_off << 2) - sizeof(struct tcphdr);
358 for (; cnt > 0; cnt -= optlen, cp += optlen) {
360 if (opt == TCPOPT_EOL)
362 if (opt == TCPOPT_NOP)
368 if (optlen < 2 || optlen > cnt)
377 if (optlen != TCPOLEN_MAXSEG)
379 bits |= IP_FW_TCPOPT_MSS;
381 *mss = be16dec(cp + 2);
385 if (optlen == TCPOLEN_WINDOW)
386 bits |= IP_FW_TCPOPT_WINDOW;
389 case TCPOPT_SACK_PERMITTED:
390 if (optlen == TCPOLEN_SACK_PERMITTED)
391 bits |= IP_FW_TCPOPT_SACK;
395 if (optlen > 2 && (optlen - 2) % TCPOLEN_SACK == 0)
396 bits |= IP_FW_TCPOPT_SACK;
399 case TCPOPT_TIMESTAMP:
400 if (optlen == TCPOLEN_TIMESTAMP)
401 bits |= IP_FW_TCPOPT_TS;
409 tcpopts_match(struct tcphdr *tcp, ipfw_insn *cmd)
412 return (flags_match(cmd, tcpopts_parse(tcp, NULL)));
416 iface_match(struct ifnet *ifp, ipfw_insn_if *cmd, struct ip_fw_chain *chain,
420 if (ifp == NULL) /* no iface with this packet, match fails */
423 /* Check by name or by IP address */
424 if (cmd->name[0] != '\0') { /* match by name */
425 if (cmd->name[0] == '\1') /* use tablearg to match */
426 return ipfw_lookup_table(chain, cmd->p.kidx, 0,
427 &ifp->if_index, tablearg);
430 if (fnmatch(cmd->name, ifp->if_xname, 0) == 0)
433 if (strncmp(ifp->if_xname, cmd->name, IFNAMSIZ) == 0)
437 #if !defined(USERSPACE) && defined(__FreeBSD__) /* and OSX too ? */
442 CK_STAILQ_FOREACH(ia, &ifp->if_addrhead, ifa_link) {
443 if (ia->ifa_addr->sa_family != AF_INET)
445 if (cmd->p.ip.s_addr == ((struct sockaddr_in *)
446 (ia->ifa_addr))->sin_addr.s_addr)
447 return (1); /* match */
449 #endif /* __FreeBSD__ */
451 return(0); /* no match, fail ... */
455 * The verify_path function checks if a route to the src exists and
456 * if it is reachable via ifp (when provided).
458 * The 'verrevpath' option checks that the interface that an IP packet
459 * arrives on is the same interface that traffic destined for the
460 * packet's source address would be routed out of.
461 * The 'versrcreach' option just checks that the source address is
462 * reachable via any route (except default) in the routing table.
463 * These two are a measure to block forged packets. This is also
464 * commonly known as "anti-spoofing" or Unicast Reverse Path
465 * Forwarding (Unicast RFP) in Cisco-ese. The name of the knobs
466 * is purposely reminiscent of the Cisco IOS command,
468 * ip verify unicast reverse-path
469 * ip verify unicast source reachable-via any
471 * which implements the same functionality. But note that the syntax
472 * is misleading, and the check may be performed on all IP packets
473 * whether unicast, multicast, or broadcast.
476 verify_path(struct in_addr src, struct ifnet *ifp, u_int fib)
478 #if defined(USERSPACE) || !defined(__FreeBSD__)
481 struct nhop_object *nh;
483 nh = fib4_lookup(fib, src, 0, NHR_NONE, 0);
488 * If ifp is provided, check for equality with rtentry.
489 * We should use rt->rt_ifa->ifa_ifp, instead of rt->rt_ifp,
490 * in order to pass packets injected back by if_simloop():
491 * routing entry (via lo0) for our own address
492 * may exist, so we need to handle routing assymetry.
494 if (ifp != NULL && ifp != nh->nh_aifp)
497 /* if no ifp provided, check if rtentry is not default route */
498 if (ifp == NULL && (nh->nh_flags & NHF_DEFAULT) != 0)
501 /* or if this is a blackhole/reject route */
502 if (ifp == NULL && (nh->nh_flags & (NHF_REJECT|NHF_BLACKHOLE)) != 0)
505 /* found valid route */
507 #endif /* __FreeBSD__ */
511 * Generate an SCTP packet containing an ABORT chunk. The verification tag
512 * is given by vtag. The T-bit is set in the ABORT chunk if and only if
513 * reflected is not 0.
517 ipfw_send_abort(struct mbuf *replyto, struct ipfw_flow_id *id, u_int32_t vtag,
525 struct sctphdr *sctp;
526 struct sctp_chunkhdr *chunk;
527 u_int16_t hlen, plen, tlen;
529 MGETHDR(m, M_NOWAIT, MT_DATA);
533 M_SETFIB(m, id->fib);
536 mac_netinet_firewall_reply(replyto, m);
538 mac_netinet_firewall_send(m);
540 (void)replyto; /* don't warn about unused arg */
543 switch (id->addr_type) {
545 hlen = sizeof(struct ip);
549 hlen = sizeof(struct ip6_hdr);
557 plen = sizeof(struct sctphdr) + sizeof(struct sctp_chunkhdr);
559 m->m_data += max_linkhdr;
560 m->m_flags |= M_SKIP_FIREWALL;
561 m->m_pkthdr.len = m->m_len = tlen;
562 m->m_pkthdr.rcvif = NULL;
563 bzero(m->m_data, tlen);
565 switch (id->addr_type) {
567 ip = mtod(m, struct ip *);
570 ip->ip_hl = sizeof(struct ip) >> 2;
571 ip->ip_tos = IPTOS_LOWDELAY;
572 ip->ip_len = htons(tlen);
573 ip->ip_id = htons(0);
574 ip->ip_off = htons(0);
575 ip->ip_ttl = V_ip_defttl;
576 ip->ip_p = IPPROTO_SCTP;
578 ip->ip_src.s_addr = htonl(id->dst_ip);
579 ip->ip_dst.s_addr = htonl(id->src_ip);
581 sctp = (struct sctphdr *)(ip + 1);
585 ip6 = mtod(m, struct ip6_hdr *);
587 ip6->ip6_vfc = IPV6_VERSION;
588 ip6->ip6_plen = htons(plen);
589 ip6->ip6_nxt = IPPROTO_SCTP;
590 ip6->ip6_hlim = IPV6_DEFHLIM;
591 ip6->ip6_src = id->dst_ip6;
592 ip6->ip6_dst = id->src_ip6;
594 sctp = (struct sctphdr *)(ip6 + 1);
599 sctp->src_port = htons(id->dst_port);
600 sctp->dest_port = htons(id->src_port);
601 sctp->v_tag = htonl(vtag);
602 sctp->checksum = htonl(0);
604 chunk = (struct sctp_chunkhdr *)(sctp + 1);
605 chunk->chunk_type = SCTP_ABORT_ASSOCIATION;
606 chunk->chunk_flags = 0;
607 if (reflected != 0) {
608 chunk->chunk_flags |= SCTP_HAD_NO_TCB;
610 chunk->chunk_length = htons(sizeof(struct sctp_chunkhdr));
612 sctp->checksum = sctp_calculate_cksum(m, hlen);
618 * Generate a TCP packet, containing either a RST or a keepalive.
619 * When flags & TH_RST, we are sending a RST packet, because of a
620 * "reset" action matched the packet.
621 * Otherwise we are sending a keepalive, and flags & TH_
622 * The 'replyto' mbuf is the mbuf being replied to, if any, and is required
623 * so that MAC can label the reply appropriately.
626 ipfw_send_pkt(struct mbuf *replyto, struct ipfw_flow_id *id, u_int32_t seq,
627 u_int32_t ack, int flags)
629 struct mbuf *m = NULL; /* stupid compiler */
630 struct ip *h = NULL; /* stupid compiler */
632 struct ip6_hdr *h6 = NULL;
634 struct tcphdr *th = NULL;
637 MGETHDR(m, M_NOWAIT, MT_DATA);
641 M_SETFIB(m, id->fib);
644 mac_netinet_firewall_reply(replyto, m);
646 mac_netinet_firewall_send(m);
648 (void)replyto; /* don't warn about unused arg */
651 switch (id->addr_type) {
653 len = sizeof(struct ip) + sizeof(struct tcphdr);
657 len = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
665 dir = ((flags & (TH_SYN | TH_RST)) == TH_SYN);
667 m->m_data += max_linkhdr;
668 m->m_flags |= M_SKIP_FIREWALL;
669 m->m_pkthdr.len = m->m_len = len;
670 m->m_pkthdr.rcvif = NULL;
671 bzero(m->m_data, len);
673 switch (id->addr_type) {
675 h = mtod(m, struct ip *);
677 /* prepare for checksum */
678 h->ip_p = IPPROTO_TCP;
679 h->ip_len = htons(sizeof(struct tcphdr));
681 h->ip_src.s_addr = htonl(id->src_ip);
682 h->ip_dst.s_addr = htonl(id->dst_ip);
684 h->ip_src.s_addr = htonl(id->dst_ip);
685 h->ip_dst.s_addr = htonl(id->src_ip);
688 th = (struct tcphdr *)(h + 1);
692 h6 = mtod(m, struct ip6_hdr *);
694 /* prepare for checksum */
695 h6->ip6_nxt = IPPROTO_TCP;
696 h6->ip6_plen = htons(sizeof(struct tcphdr));
698 h6->ip6_src = id->src_ip6;
699 h6->ip6_dst = id->dst_ip6;
701 h6->ip6_src = id->dst_ip6;
702 h6->ip6_dst = id->src_ip6;
705 th = (struct tcphdr *)(h6 + 1);
711 th->th_sport = htons(id->src_port);
712 th->th_dport = htons(id->dst_port);
714 th->th_sport = htons(id->dst_port);
715 th->th_dport = htons(id->src_port);
717 th->th_off = sizeof(struct tcphdr) >> 2;
719 if (flags & TH_RST) {
720 if (flags & TH_ACK) {
721 th->th_seq = htonl(ack);
722 th->th_flags = TH_RST;
726 th->th_ack = htonl(seq);
727 th->th_flags = TH_RST | TH_ACK;
731 * Keepalive - use caller provided sequence numbers
733 th->th_seq = htonl(seq);
734 th->th_ack = htonl(ack);
735 th->th_flags = TH_ACK;
738 switch (id->addr_type) {
740 th->th_sum = in_cksum(m, len);
742 /* finish the ip header */
744 h->ip_hl = sizeof(*h) >> 2;
745 h->ip_tos = IPTOS_LOWDELAY;
746 h->ip_off = htons(0);
747 h->ip_len = htons(len);
748 h->ip_ttl = V_ip_defttl;
753 th->th_sum = in6_cksum(m, IPPROTO_TCP, sizeof(*h6),
754 sizeof(struct tcphdr));
756 /* finish the ip6 header */
757 h6->ip6_vfc |= IPV6_VERSION;
758 h6->ip6_hlim = IPV6_DEFHLIM;
768 * ipv6 specific rules here...
771 icmp6type_match(int type, ipfw_insn_u32 *cmd)
773 return (type <= ICMP6_MAXTYPE && (cmd->d[type/32] & (1<<(type%32)) ) );
777 flow6id_match(int curr_flow, ipfw_insn_u32 *cmd)
780 for (i=0; i <= cmd->o.arg1; ++i)
781 if (curr_flow == cmd->d[i])
786 /* support for IP6_*_ME opcodes */
787 static const struct in6_addr lla_mask = {{{
788 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff,
789 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff
793 ipfw_localip6(struct in6_addr *in6)
795 struct rm_priotracker in6_ifa_tracker;
796 struct in6_ifaddr *ia;
798 if (IN6_IS_ADDR_MULTICAST(in6))
801 if (!IN6_IS_ADDR_LINKLOCAL(in6))
802 return (in6_localip(in6));
804 IN6_IFADDR_RLOCK(&in6_ifa_tracker);
805 CK_STAILQ_FOREACH(ia, &V_in6_ifaddrhead, ia_link) {
806 if (!IN6_IS_ADDR_LINKLOCAL(&ia->ia_addr.sin6_addr))
808 if (IN6_ARE_MASKED_ADDR_EQUAL(&ia->ia_addr.sin6_addr,
810 IN6_IFADDR_RUNLOCK(&in6_ifa_tracker);
814 IN6_IFADDR_RUNLOCK(&in6_ifa_tracker);
819 verify_path6(struct in6_addr *src, struct ifnet *ifp, u_int fib)
821 struct nhop_object *nh;
823 if (IN6_IS_SCOPE_LINKLOCAL(src))
826 nh = fib6_lookup(fib, src, 0, NHR_NONE, 0);
830 /* If ifp is provided, check for equality with route table. */
831 if (ifp != NULL && ifp != nh->nh_aifp)
834 /* if no ifp provided, check if rtentry is not default route */
835 if (ifp == NULL && (nh->nh_flags & NHF_DEFAULT) != 0)
838 /* or if this is a blackhole/reject route */
839 if (ifp == NULL && (nh->nh_flags & (NHF_REJECT|NHF_BLACKHOLE)) != 0)
842 /* found valid route */
847 is_icmp6_query(int icmp6_type)
849 if ((icmp6_type <= ICMP6_MAXTYPE) &&
850 (icmp6_type == ICMP6_ECHO_REQUEST ||
851 icmp6_type == ICMP6_MEMBERSHIP_QUERY ||
852 icmp6_type == ICMP6_WRUREQUEST ||
853 icmp6_type == ICMP6_FQDN_QUERY ||
854 icmp6_type == ICMP6_NI_QUERY))
861 map_icmp_unreach(int code)
866 case ICMP_UNREACH_NET:
867 case ICMP_UNREACH_HOST:
868 case ICMP_UNREACH_SRCFAIL:
869 case ICMP_UNREACH_NET_UNKNOWN:
870 case ICMP_UNREACH_HOST_UNKNOWN:
871 case ICMP_UNREACH_TOSNET:
872 case ICMP_UNREACH_TOSHOST:
873 return (ICMP6_DST_UNREACH_NOROUTE);
874 case ICMP_UNREACH_PORT:
875 return (ICMP6_DST_UNREACH_NOPORT);
878 * Map the rest of codes into admit prohibited.
879 * XXX: unreach proto should be mapped into ICMPv6
880 * parameter problem, but we use only unreach type.
882 return (ICMP6_DST_UNREACH_ADMIN);
887 send_reject6(struct ip_fw_args *args, int code, u_int hlen, struct ip6_hdr *ip6)
892 if (code == ICMP6_UNREACH_RST && args->f_id.proto == IPPROTO_TCP) {
894 tcp = (struct tcphdr *)((char *)ip6 + hlen);
896 if ((tcp->th_flags & TH_RST) == 0) {
898 m0 = ipfw_send_pkt(args->m, &(args->f_id),
899 ntohl(tcp->th_seq), ntohl(tcp->th_ack),
900 tcp->th_flags | TH_RST);
902 ip6_output(m0, NULL, NULL, 0, NULL, NULL,
906 } else if (code == ICMP6_UNREACH_ABORT &&
907 args->f_id.proto == IPPROTO_SCTP) {
909 struct sctphdr *sctp;
913 sctp = (struct sctphdr *)((char *)ip6 + hlen);
915 v_tag = ntohl(sctp->v_tag);
916 /* Investigate the first chunk header if available */
917 if (m->m_len >= hlen + sizeof(struct sctphdr) +
918 sizeof(struct sctp_chunkhdr)) {
919 struct sctp_chunkhdr *chunk;
921 chunk = (struct sctp_chunkhdr *)(sctp + 1);
922 switch (chunk->chunk_type) {
923 case SCTP_INITIATION:
925 * Packets containing an INIT chunk MUST have
932 /* INIT chunk MUST NOT be bundled */
933 if (m->m_pkthdr.len >
934 hlen + sizeof(struct sctphdr) +
935 ntohs(chunk->chunk_length) + 3) {
938 /* Use the initiate tag if available */
939 if ((m->m_len >= hlen + sizeof(struct sctphdr) +
940 sizeof(struct sctp_chunkhdr) +
941 offsetof(struct sctp_init, a_rwnd))) {
942 struct sctp_init *init;
944 init = (struct sctp_init *)(chunk + 1);
945 v_tag = ntohl(init->initiate_tag);
949 case SCTP_ABORT_ASSOCIATION:
951 * If the packet contains an ABORT chunk, don't
953 * XXX: We should search through all chunks,
954 * but do not do that to avoid attacks.
963 m0 = ipfw_send_abort(args->m, &(args->f_id), v_tag,
967 ip6_output(m0, NULL, NULL, 0, NULL, NULL, NULL);
969 } else if (code != ICMP6_UNREACH_RST && code != ICMP6_UNREACH_ABORT) {
970 /* Send an ICMPv6 unreach. */
973 * Unlike above, the mbufs need to line up with the ip6 hdr,
974 * as the contents are read. We need to m_adj() the
976 * The mbuf will however be thrown away so we can adjust it.
977 * Remember we did an m_pullup on it already so we
978 * can make some assumptions about contiguousness.
981 m_adj(m, args->L3offset);
983 icmp6_error(m, ICMP6_DST_UNREACH, code, 0);
993 * sends a reject message, consuming the mbuf passed as an argument.
996 send_reject(struct ip_fw_args *args, int code, int iplen, struct ip *ip)
1000 /* XXX When ip is not guaranteed to be at mtod() we will
1001 * need to account for this */
1002 * The mbuf will however be thrown away so we can adjust it.
1003 * Remember we did an m_pullup on it already so we
1004 * can make some assumptions about contiguousness.
1007 m_adj(m, args->L3offset);
1009 if (code != ICMP_REJECT_RST && code != ICMP_REJECT_ABORT) {
1010 /* Send an ICMP unreach */
1011 icmp_error(args->m, ICMP_UNREACH, code, 0L, 0);
1012 } else if (code == ICMP_REJECT_RST && args->f_id.proto == IPPROTO_TCP) {
1013 struct tcphdr *const tcp =
1014 L3HDR(struct tcphdr, mtod(args->m, struct ip *));
1015 if ( (tcp->th_flags & TH_RST) == 0) {
1017 m = ipfw_send_pkt(args->m, &(args->f_id),
1018 ntohl(tcp->th_seq), ntohl(tcp->th_ack),
1019 tcp->th_flags | TH_RST);
1021 ip_output(m, NULL, NULL, 0, NULL, NULL);
1024 } else if (code == ICMP_REJECT_ABORT &&
1025 args->f_id.proto == IPPROTO_SCTP) {
1027 struct sctphdr *sctp;
1028 struct sctp_chunkhdr *chunk;
1029 struct sctp_init *init;
1033 sctp = L3HDR(struct sctphdr, mtod(args->m, struct ip *));
1035 v_tag = ntohl(sctp->v_tag);
1036 if (iplen >= (ip->ip_hl << 2) + sizeof(struct sctphdr) +
1037 sizeof(struct sctp_chunkhdr)) {
1038 /* Look at the first chunk header if available */
1039 chunk = (struct sctp_chunkhdr *)(sctp + 1);
1040 switch (chunk->chunk_type) {
1041 case SCTP_INITIATION:
1043 * Packets containing an INIT chunk MUST have
1050 /* INIT chunk MUST NOT be bundled */
1052 (ip->ip_hl << 2) + sizeof(struct sctphdr) +
1053 ntohs(chunk->chunk_length) + 3) {
1056 /* Use the initiate tag if available */
1057 if ((iplen >= (ip->ip_hl << 2) +
1058 sizeof(struct sctphdr) +
1059 sizeof(struct sctp_chunkhdr) +
1060 offsetof(struct sctp_init, a_rwnd))) {
1061 init = (struct sctp_init *)(chunk + 1);
1062 v_tag = ntohl(init->initiate_tag);
1066 case SCTP_ABORT_ASSOCIATION:
1068 * If the packet contains an ABORT chunk, don't
1070 * XXX: We should search through all chunks,
1071 * but do not do that to avoid attacks.
1080 m = ipfw_send_abort(args->m, &(args->f_id), v_tag,
1084 ip_output(m, NULL, NULL, 0, NULL, NULL);
1092 * Support for uid/gid/jail lookup. These tests are expensive
1093 * (because we may need to look into the list of active sockets)
1094 * so we cache the results. ugid_lookupp is 0 if we have not
1095 * yet done a lookup, 1 if we succeeded, and -1 if we tried
1096 * and failed. The function always returns the match value.
1097 * We could actually spare the variable and use *uc, setting
1098 * it to '(void *)check_uidgid if we have no info, NULL if
1099 * we tried and failed, or any other value if successful.
1102 check_uidgid(ipfw_insn_u32 *insn, struct ip_fw_args *args, int *ugid_lookupp,
1105 #if defined(USERSPACE)
1106 return 0; // not supported in userspace
1110 return cred_check(insn, proto, oif,
1111 dst_ip, dst_port, src_ip, src_port,
1112 (struct bsd_ucred *)uc, ugid_lookupp, ((struct mbuf *)inp)->m_skb);
1114 struct in_addr src_ip, dst_ip;
1115 struct inpcbinfo *pi;
1116 struct ipfw_flow_id *id;
1117 struct inpcb *pcb, *inp;
1125 * Check to see if the UDP or TCP stack supplied us with
1126 * the PCB. If so, rather then holding a lock and looking
1127 * up the PCB, we can use the one that was supplied.
1129 if (inp && *ugid_lookupp == 0) {
1130 INP_LOCK_ASSERT(inp);
1131 if (inp->inp_socket != NULL) {
1132 *uc = crhold(inp->inp_cred);
1138 * If we have already been here and the packet has no
1139 * PCB entry associated with it, then we can safely
1140 * assume that this is a no match.
1142 if (*ugid_lookupp == -1)
1144 if (id->proto == IPPROTO_TCP) {
1147 } else if (id->proto == IPPROTO_UDP) {
1148 lookupflags = INPLOOKUP_WILDCARD;
1150 } else if (id->proto == IPPROTO_UDPLITE) {
1151 lookupflags = INPLOOKUP_WILDCARD;
1152 pi = &V_ulitecbinfo;
1155 lookupflags |= INPLOOKUP_RLOCKPCB;
1157 if (*ugid_lookupp == 0) {
1158 if (id->addr_type == 6) {
1160 if (args->flags & IPFW_ARGS_IN)
1161 pcb = in6_pcblookup_mbuf(pi,
1162 &id->src_ip6, htons(id->src_port),
1163 &id->dst_ip6, htons(id->dst_port),
1164 lookupflags, NULL, args->m);
1166 pcb = in6_pcblookup_mbuf(pi,
1167 &id->dst_ip6, htons(id->dst_port),
1168 &id->src_ip6, htons(id->src_port),
1169 lookupflags, args->ifp, args->m);
1175 src_ip.s_addr = htonl(id->src_ip);
1176 dst_ip.s_addr = htonl(id->dst_ip);
1177 if (args->flags & IPFW_ARGS_IN)
1178 pcb = in_pcblookup_mbuf(pi,
1179 src_ip, htons(id->src_port),
1180 dst_ip, htons(id->dst_port),
1181 lookupflags, NULL, args->m);
1183 pcb = in_pcblookup_mbuf(pi,
1184 dst_ip, htons(id->dst_port),
1185 src_ip, htons(id->src_port),
1186 lookupflags, args->ifp, args->m);
1189 INP_RLOCK_ASSERT(pcb);
1190 *uc = crhold(pcb->inp_cred);
1194 if (*ugid_lookupp == 0) {
1196 * We tried and failed, set the variable to -1
1197 * so we will not try again on this packet.
1203 if (insn->o.opcode == O_UID)
1204 match = ((*uc)->cr_uid == (uid_t)insn->d[0]);
1205 else if (insn->o.opcode == O_GID)
1206 match = groupmember((gid_t)insn->d[0], *uc);
1207 else if (insn->o.opcode == O_JAIL)
1208 match = ((*uc)->cr_prison->pr_id == (int)insn->d[0]);
1210 #endif /* __FreeBSD__ */
1211 #endif /* not supported in userspace */
1215 * Helper function to set args with info on the rule after the matching
1216 * one. slot is precise, whereas we guess rule_id as they are
1217 * assigned sequentially.
1220 set_match(struct ip_fw_args *args, int slot,
1221 struct ip_fw_chain *chain)
1223 args->rule.chain_id = chain->id;
1224 args->rule.slot = slot + 1; /* we use 0 as a marker */
1225 args->rule.rule_id = 1 + chain->map[slot]->id;
1226 args->rule.rulenum = chain->map[slot]->rulenum;
1227 args->flags |= IPFW_ARGS_REF;
1231 jump_lookup_pos(struct ip_fw_chain *chain, struct ip_fw *f, int num,
1232 int tablearg, int jump_backwards)
1236 i = IP_FW_ARG_TABLEARG(chain, num, skipto);
1237 /* make sure we do not jump backward */
1238 if (jump_backwards == 0 && i <= f->rulenum)
1241 #ifndef LINEAR_SKIPTO
1242 if (chain->idxmap != NULL)
1243 f_pos = chain->idxmap[i];
1245 f_pos = ipfw_find_rule(chain, i, 0);
1247 f_pos = chain->idxmap[i];
1248 #endif /* LINEAR_SKIPTO */
1254 #ifndef LINEAR_SKIPTO
1256 * Helper function to enable cached rule lookups using
1257 * cache.id and cache.pos fields in ipfw rule.
1260 jump_cached(struct ip_fw_chain *chain, struct ip_fw *f, int num,
1261 int tablearg, int jump_backwards)
1265 /* Can't use cache with IP_FW_TARG */
1266 if (num == IP_FW_TARG)
1267 return jump_lookup_pos(chain, f, num, tablearg, jump_backwards);
1270 * If possible use cached f_pos (in f->cache.pos),
1271 * whose version is written in f->cache.id (horrible hacks
1272 * to avoid changing the ABI).
1274 * Multiple threads can execute the same rule simultaneously,
1275 * we need to ensure that cache.pos is updated before cache.id.
1279 struct ip_fw_jump_cache cache;
1281 cache.raw_value = f->cache.raw_value;
1282 if (cache.id == chain->id)
1285 f_pos = jump_lookup_pos(chain, f, num, tablearg, jump_backwards);
1288 cache.id = chain->id;
1289 f->cache.raw_value = cache.raw_value;
1291 if (f->cache.id == chain->id) {
1292 /* Load pos after id */
1293 atomic_thread_fence_acq();
1294 return (f->cache.pos);
1297 f_pos = jump_lookup_pos(chain, f, num, tablearg, jump_backwards);
1299 f->cache.pos = f_pos;
1300 /* Store id after pos */
1301 atomic_thread_fence_rel();
1302 f->cache.id = chain->id;
1303 #endif /* !__LP64__ */
1306 #endif /* !LINEAR_SKIPTO */
1308 #define TARG(k, f) IP_FW_ARG_TABLEARG(chain, k, f)
1310 * The main check routine for the firewall.
1312 * All arguments are in args so we can modify them and return them
1313 * back to the caller.
1317 * args->m (in/out) The packet; we set to NULL when/if we nuke it.
1318 * Starts with the IP header.
1319 * args->L3offset Number of bytes bypassed if we came from L2.
1320 * e.g. often sizeof(eh) ** NOTYET **
1321 * args->ifp Incoming or outgoing interface.
1322 * args->divert_rule (in/out)
1323 * Skip up to the first rule past this rule number;
1324 * upon return, non-zero port number for divert or tee.
1326 * args->rule Pointer to the last matching rule (in/out)
1327 * args->next_hop Socket we are forwarding to (out).
1328 * args->next_hop6 IPv6 next hop we are forwarding to (out).
1329 * args->f_id Addresses grabbed from the packet (out)
1330 * args->rule.info a cookie depending on rule action
1334 * IP_FW_PASS the packet must be accepted
1335 * IP_FW_DENY the packet must be dropped
1336 * IP_FW_DIVERT divert packet, port in m_tag
1337 * IP_FW_TEE tee packet, port in m_tag
1338 * IP_FW_DUMMYNET to dummynet, pipe in args->cookie
1339 * IP_FW_NETGRAPH into netgraph, cookie args->cookie
1340 * args->rule contains the matching rule,
1341 * args->rule.info has additional information.
1345 ipfw_chk(struct ip_fw_args *args)
1349 * Local variables holding state while processing a packet:
1351 * IMPORTANT NOTE: to speed up the processing of rules, there
1352 * are some assumption on the values of the variables, which
1353 * are documented here. Should you change them, please check
1354 * the implementation of the various instructions to make sure
1355 * that they still work.
1357 * m | args->m Pointer to the mbuf, as received from the caller.
1358 * It may change if ipfw_chk() does an m_pullup, or if it
1359 * consumes the packet because it calls send_reject().
1360 * XXX This has to change, so that ipfw_chk() never modifies
1361 * or consumes the buffer.
1363 * args->mem Pointer to contigous memory chunk.
1364 * ip Is the beginning of the ip(4 or 6) header.
1365 * eh Ethernet header in case if input is Layer2.
1369 struct ether_header *eh;
1372 * For rules which contain uid/gid or jail constraints, cache
1373 * a copy of the users credentials after the pcb lookup has been
1374 * executed. This will speed up the processing of rules with
1375 * these types of constraints, as well as decrease contention
1376 * on pcb related locks.
1379 struct bsd_ucred ucred_cache;
1381 struct ucred *ucred_cache = NULL;
1383 int ucred_lookup = 0;
1384 int f_pos = 0; /* index of current rule in the array */
1386 struct ifnet *oif, *iif;
1389 * hlen The length of the IP header.
1391 u_int hlen = 0; /* hlen >0 means we have an IP pkt */
1394 * offset The offset of a fragment. offset != 0 means that
1395 * we have a fragment at this offset of an IPv4 packet.
1396 * offset == 0 means that (if this is an IPv4 packet)
1397 * this is the first or only fragment.
1398 * For IPv6 offset|ip6f_mf == 0 means there is no Fragment Header
1399 * or there is a single packet fragment (fragment header added
1400 * without needed). We will treat a single packet fragment as if
1401 * there was no fragment header (or log/block depending on the
1402 * V_fw_permit_single_frag6 sysctl setting).
1405 u_short ip6f_mf = 0;
1408 * Local copies of addresses. They are only valid if we have
1411 * proto The protocol. Set to 0 for non-ip packets,
1412 * or to the protocol read from the packet otherwise.
1413 * proto != 0 means that we have an IPv4 packet.
1415 * src_port, dst_port port numbers, in HOST format. Only
1416 * valid for TCP and UDP packets.
1418 * src_ip, dst_ip ip addresses, in NETWORK format.
1419 * Only valid for IPv4 packets.
1422 uint16_t src_port, dst_port; /* NOTE: host format */
1423 struct in_addr src_ip, dst_ip; /* NOTE: network format */
1427 struct ipfw_dyn_info dyn_info;
1428 struct ip_fw *q = NULL;
1429 struct ip_fw_chain *chain = &V_layer3_chain;
1432 * We store in ulp a pointer to the upper layer protocol header.
1433 * In the ipv4 case this is easy to determine from the header,
1434 * but for ipv6 we might have some additional headers in the middle.
1435 * ulp is NULL if not found.
1437 void *ulp = NULL; /* upper layer protocol pointer. */
1439 /* XXX ipv6 variables */
1441 uint8_t icmp6_type = 0;
1442 uint16_t ext_hd = 0; /* bits vector for extension header filtering */
1443 /* end of ipv6 variables */
1447 int done = 0; /* flag to exit the outer loop */
1451 if ((mem = (args->flags & IPFW_ARGS_LENMASK))) {
1452 if (args->flags & IPFW_ARGS_ETHER) {
1453 eh = (struct ether_header *)args->mem;
1454 if (eh->ether_type == htons(ETHERTYPE_VLAN))
1456 ((struct ether_vlan_header *)eh + 1);
1458 ip = (struct ip *)(eh + 1);
1461 ip = (struct ip *)args->mem;
1463 pktlen = IPFW_ARGS_LENGTH(args->flags);
1464 args->f_id.fib = args->ifp->if_fib; /* best guess */
1467 if (m->m_flags & M_SKIP_FIREWALL || (! V_ipfw_vnet_ready))
1468 return (IP_FW_PASS); /* accept */
1469 if (args->flags & IPFW_ARGS_ETHER) {
1470 /* We need some amount of data to be contiguous. */
1471 if (m->m_len < min(m->m_pkthdr.len, max_protohdr) &&
1472 (args->m = m = m_pullup(m, min(m->m_pkthdr.len,
1473 max_protohdr))) == NULL)
1475 eh = mtod(m, struct ether_header *);
1476 ip = (struct ip *)(eh + 1);
1479 ip = mtod(m, struct ip *);
1481 pktlen = m->m_pkthdr.len;
1482 args->f_id.fib = M_GETFIB(m); /* mbuf not altered */
1485 dst_ip.s_addr = 0; /* make sure it is initialized */
1486 src_ip.s_addr = 0; /* make sure it is initialized */
1487 src_port = dst_port = 0;
1489 DYN_INFO_INIT(&dyn_info);
1491 * PULLUP_TO(len, p, T) makes sure that len + sizeof(T) is contiguous,
1492 * then it sets p to point at the offset "len" in the mbuf. WARNING: the
1493 * pointer might become stale after other pullups (but we never use it
1496 #define PULLUP_TO(_len, p, T) PULLUP_LEN(_len, p, sizeof(T))
1497 #define EHLEN (eh != NULL ? ((char *)ip - (char *)eh) : 0)
1498 #define _PULLUP_LOCKED(_len, p, T, unlock) \
1500 int x = (_len) + T + EHLEN; \
1502 if (__predict_false(pktlen < x)) { \
1504 goto pullup_failed; \
1506 p = (char *)args->mem + (_len) + EHLEN; \
1508 if (__predict_false((m)->m_len < x)) { \
1509 args->m = m = m_pullup(m, x); \
1512 goto pullup_failed; \
1515 p = mtod(m, char *) + (_len) + EHLEN; \
1519 #define PULLUP_LEN(_len, p, T) _PULLUP_LOCKED(_len, p, T, )
1520 #define PULLUP_LEN_LOCKED(_len, p, T) \
1521 _PULLUP_LOCKED(_len, p, T, IPFW_PF_RUNLOCK(chain)); \
1524 * In case pointers got stale after pullups, update them.
1526 #define UPDATE_POINTERS() \
1530 eh = mtod(m, struct ether_header *); \
1531 ip = (struct ip *)(eh + 1); \
1533 ip = mtod(m, struct ip *); \
1538 /* Identify IP packets and fill up variables. */
1539 if (pktlen >= sizeof(struct ip6_hdr) &&
1540 (eh == NULL || eh->ether_type == htons(ETHERTYPE_IPV6)) &&
1542 struct ip6_hdr *ip6 = (struct ip6_hdr *)ip;
1545 args->flags |= IPFW_ARGS_IP6;
1546 hlen = sizeof(struct ip6_hdr);
1547 proto = ip6->ip6_nxt;
1548 /* Search extension headers to find upper layer protocols */
1549 while (ulp == NULL && offset == 0) {
1551 case IPPROTO_ICMPV6:
1552 PULLUP_TO(hlen, ulp, struct icmp6_hdr);
1553 icmp6_type = ICMP6(ulp)->icmp6_type;
1557 PULLUP_TO(hlen, ulp, struct tcphdr);
1558 dst_port = TCP(ulp)->th_dport;
1559 src_port = TCP(ulp)->th_sport;
1560 /* save flags for dynamic rules */
1561 args->f_id._flags = TCP(ulp)->th_flags;
1565 if (pktlen >= hlen + sizeof(struct sctphdr) +
1566 sizeof(struct sctp_chunkhdr) +
1567 offsetof(struct sctp_init, a_rwnd))
1568 PULLUP_LEN(hlen, ulp,
1569 sizeof(struct sctphdr) +
1570 sizeof(struct sctp_chunkhdr) +
1571 offsetof(struct sctp_init, a_rwnd));
1572 else if (pktlen >= hlen + sizeof(struct sctphdr))
1573 PULLUP_LEN(hlen, ulp, pktlen - hlen);
1575 PULLUP_LEN(hlen, ulp,
1576 sizeof(struct sctphdr));
1577 src_port = SCTP(ulp)->src_port;
1578 dst_port = SCTP(ulp)->dest_port;
1582 case IPPROTO_UDPLITE:
1583 PULLUP_TO(hlen, ulp, struct udphdr);
1584 dst_port = UDP(ulp)->uh_dport;
1585 src_port = UDP(ulp)->uh_sport;
1588 case IPPROTO_HOPOPTS: /* RFC 2460 */
1589 PULLUP_TO(hlen, ulp, struct ip6_hbh);
1590 ext_hd |= EXT_HOPOPTS;
1591 hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3;
1592 proto = ((struct ip6_hbh *)ulp)->ip6h_nxt;
1596 case IPPROTO_ROUTING: /* RFC 2460 */
1597 PULLUP_TO(hlen, ulp, struct ip6_rthdr);
1598 switch (((struct ip6_rthdr *)ulp)->ip6r_type) {
1600 ext_hd |= EXT_RTHDR0;
1603 ext_hd |= EXT_RTHDR2;
1607 printf("IPFW2: IPV6 - Unknown "
1608 "Routing Header type(%d)\n",
1609 ((struct ip6_rthdr *)
1611 if (V_fw_deny_unknown_exthdrs)
1612 return (IP_FW_DENY);
1615 ext_hd |= EXT_ROUTING;
1616 hlen += (((struct ip6_rthdr *)ulp)->ip6r_len + 1) << 3;
1617 proto = ((struct ip6_rthdr *)ulp)->ip6r_nxt;
1621 case IPPROTO_FRAGMENT: /* RFC 2460 */
1622 PULLUP_TO(hlen, ulp, struct ip6_frag);
1623 ext_hd |= EXT_FRAGMENT;
1624 hlen += sizeof (struct ip6_frag);
1625 proto = ((struct ip6_frag *)ulp)->ip6f_nxt;
1626 offset = ((struct ip6_frag *)ulp)->ip6f_offlg &
1628 ip6f_mf = ((struct ip6_frag *)ulp)->ip6f_offlg &
1630 if (V_fw_permit_single_frag6 == 0 &&
1631 offset == 0 && ip6f_mf == 0) {
1633 printf("IPFW2: IPV6 - Invalid "
1634 "Fragment Header\n");
1635 if (V_fw_deny_unknown_exthdrs)
1636 return (IP_FW_DENY);
1640 ntohl(((struct ip6_frag *)ulp)->ip6f_ident);
1644 case IPPROTO_DSTOPTS: /* RFC 2460 */
1645 PULLUP_TO(hlen, ulp, struct ip6_hbh);
1646 ext_hd |= EXT_DSTOPTS;
1647 hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3;
1648 proto = ((struct ip6_hbh *)ulp)->ip6h_nxt;
1652 case IPPROTO_AH: /* RFC 2402 */
1653 PULLUP_TO(hlen, ulp, struct ip6_ext);
1655 hlen += (((struct ip6_ext *)ulp)->ip6e_len + 2) << 2;
1656 proto = ((struct ip6_ext *)ulp)->ip6e_nxt;
1660 case IPPROTO_ESP: /* RFC 2406 */
1661 PULLUP_TO(hlen, ulp, uint32_t); /* SPI, Seq# */
1662 /* Anything past Seq# is variable length and
1663 * data past this ext. header is encrypted. */
1667 case IPPROTO_NONE: /* RFC 2460 */
1669 * Packet ends here, and IPv6 header has
1670 * already been pulled up. If ip6e_len!=0
1671 * then octets must be ignored.
1673 ulp = ip; /* non-NULL to get out of loop. */
1676 case IPPROTO_OSPFIGP:
1677 /* XXX OSPF header check? */
1678 PULLUP_TO(hlen, ulp, struct ip6_ext);
1682 /* XXX PIM header check? */
1683 PULLUP_TO(hlen, ulp, struct pim);
1686 case IPPROTO_GRE: /* RFC 1701 */
1687 /* XXX GRE header check? */
1688 PULLUP_TO(hlen, ulp, struct grehdr);
1692 PULLUP_TO(hlen, ulp, offsetof(
1693 struct carp_header, carp_counter));
1694 if (CARP_ADVERTISEMENT !=
1695 ((struct carp_header *)ulp)->carp_type)
1696 return (IP_FW_DENY);
1699 case IPPROTO_IPV6: /* RFC 2893 */
1700 PULLUP_TO(hlen, ulp, struct ip6_hdr);
1703 case IPPROTO_IPV4: /* RFC 2893 */
1704 PULLUP_TO(hlen, ulp, struct ip);
1709 printf("IPFW2: IPV6 - Unknown "
1710 "Extension Header(%d), ext_hd=%x\n",
1712 if (V_fw_deny_unknown_exthdrs)
1713 return (IP_FW_DENY);
1714 PULLUP_TO(hlen, ulp, struct ip6_ext);
1719 ip6 = (struct ip6_hdr *)ip;
1720 args->f_id.addr_type = 6;
1721 args->f_id.src_ip6 = ip6->ip6_src;
1722 args->f_id.dst_ip6 = ip6->ip6_dst;
1723 args->f_id.flow_id6 = ntohl(ip6->ip6_flow);
1724 iplen = ntohs(ip6->ip6_plen) + sizeof(*ip6);
1725 } else if (pktlen >= sizeof(struct ip) &&
1726 (eh == NULL || eh->ether_type == htons(ETHERTYPE_IP)) &&
1729 args->flags |= IPFW_ARGS_IP4;
1730 hlen = ip->ip_hl << 2;
1732 * Collect parameters into local variables for faster
1736 src_ip = ip->ip_src;
1737 dst_ip = ip->ip_dst;
1738 offset = ntohs(ip->ip_off) & IP_OFFMASK;
1739 iplen = ntohs(ip->ip_len);
1744 PULLUP_TO(hlen, ulp, struct tcphdr);
1745 dst_port = TCP(ulp)->th_dport;
1746 src_port = TCP(ulp)->th_sport;
1747 /* save flags for dynamic rules */
1748 args->f_id._flags = TCP(ulp)->th_flags;
1752 if (pktlen >= hlen + sizeof(struct sctphdr) +
1753 sizeof(struct sctp_chunkhdr) +
1754 offsetof(struct sctp_init, a_rwnd))
1755 PULLUP_LEN(hlen, ulp,
1756 sizeof(struct sctphdr) +
1757 sizeof(struct sctp_chunkhdr) +
1758 offsetof(struct sctp_init, a_rwnd));
1759 else if (pktlen >= hlen + sizeof(struct sctphdr))
1760 PULLUP_LEN(hlen, ulp, pktlen - hlen);
1762 PULLUP_LEN(hlen, ulp,
1763 sizeof(struct sctphdr));
1764 src_port = SCTP(ulp)->src_port;
1765 dst_port = SCTP(ulp)->dest_port;
1769 case IPPROTO_UDPLITE:
1770 PULLUP_TO(hlen, ulp, struct udphdr);
1771 dst_port = UDP(ulp)->uh_dport;
1772 src_port = UDP(ulp)->uh_sport;
1776 PULLUP_TO(hlen, ulp, struct icmphdr);
1777 //args->f_id.flags = ICMP(ulp)->icmp_type;
1784 if (offset == 1 && proto == IPPROTO_TCP) {
1791 args->f_id.addr_type = 4;
1792 args->f_id.src_ip = ntohl(src_ip.s_addr);
1793 args->f_id.dst_ip = ntohl(dst_ip.s_addr);
1796 dst_ip.s_addr = src_ip.s_addr = 0;
1798 args->f_id.addr_type = 1; /* XXX */
1801 pktlen = iplen < pktlen ? iplen: pktlen;
1803 /* Properly initialize the rest of f_id */
1804 args->f_id.proto = proto;
1805 args->f_id.src_port = src_port = ntohs(src_port);
1806 args->f_id.dst_port = dst_port = ntohs(dst_port);
1808 IPFW_PF_RLOCK(chain);
1809 if (! V_ipfw_vnet_ready) { /* shutting down, leave NOW. */
1810 IPFW_PF_RUNLOCK(chain);
1811 return (IP_FW_PASS); /* accept */
1813 if (args->flags & IPFW_ARGS_REF) {
1815 * Packet has already been tagged as a result of a previous
1816 * match on rule args->rule aka args->rule_id (PIPE, QUEUE,
1817 * REASS, NETGRAPH, DIVERT/TEE...)
1818 * Validate the slot and continue from the next one
1819 * if still present, otherwise do a lookup.
1821 f_pos = (args->rule.chain_id == chain->id) ?
1823 ipfw_find_rule(chain, args->rule.rulenum,
1824 args->rule.rule_id);
1829 if (args->flags & IPFW_ARGS_IN) {
1833 MPASS(args->flags & IPFW_ARGS_OUT);
1834 iif = mem ? NULL : m_rcvif(m);
1839 * Now scan the rules, and parse microinstructions for each rule.
1840 * We have two nested loops and an inner switch. Sometimes we
1841 * need to break out of one or both loops, or re-enter one of
1842 * the loops with updated variables. Loop variables are:
1844 * f_pos (outer loop) points to the current rule.
1845 * On output it points to the matching rule.
1846 * done (outer loop) is used as a flag to break the loop.
1847 * l (inner loop) residual length of current rule.
1848 * cmd points to the current microinstruction.
1850 * We break the inner loop by setting l=0 and possibly
1851 * cmdlen=0 if we don't want to advance cmd.
1852 * We break the outer loop by setting done=1
1853 * We can restart the inner loop by setting l>0 and f_pos, f, cmd
1856 for (; f_pos < chain->n_rules; f_pos++) {
1858 uint32_t tablearg = 0;
1859 int l, cmdlen, skip_or; /* skip rest of OR block */
1862 f = chain->map[f_pos];
1863 if (V_set_disable & (1 << f->set) )
1867 for (l = f->cmd_len, cmd = f->cmd ; l > 0 ;
1868 l -= cmdlen, cmd += cmdlen) {
1872 * check_body is a jump target used when we find a
1873 * CHECK_STATE, and need to jump to the body of
1878 cmdlen = F_LEN(cmd);
1880 * An OR block (insn_1 || .. || insn_n) has the
1881 * F_OR bit set in all but the last instruction.
1882 * The first match will set "skip_or", and cause
1883 * the following instructions to be skipped until
1884 * past the one with the F_OR bit clear.
1886 if (skip_or) { /* skip this instruction */
1887 if ((cmd->len & F_OR) == 0)
1888 skip_or = 0; /* next one is good */
1891 match = 0; /* set to 1 if we succeed */
1893 switch (cmd->opcode) {
1895 * The first set of opcodes compares the packet's
1896 * fields with some pattern, setting 'match' if a
1897 * match is found. At the end of the loop there is
1898 * logic to deal with F_NOT and F_OR flags associated
1906 printf("ipfw: opcode %d unimplemented\n",
1914 * We only check offset == 0 && proto != 0,
1915 * as this ensures that we have a
1916 * packet with the ports info.
1920 if (proto == IPPROTO_TCP ||
1921 proto == IPPROTO_UDP ||
1922 proto == IPPROTO_UDPLITE)
1923 match = check_uidgid(
1924 (ipfw_insn_u32 *)cmd,
1925 args, &ucred_lookup,
1929 (void *)&ucred_cache);
1934 match = iface_match(iif, (ipfw_insn_if *)cmd,
1939 match = iface_match(oif, (ipfw_insn_if *)cmd,
1944 match = iface_match(args->ifp,
1945 (ipfw_insn_if *)cmd, chain, &tablearg);
1949 if (args->flags & IPFW_ARGS_ETHER) {
1950 u_int32_t *want = (u_int32_t *)
1951 ((ipfw_insn_mac *)cmd)->addr;
1952 u_int32_t *mask = (u_int32_t *)
1953 ((ipfw_insn_mac *)cmd)->mask;
1954 u_int32_t *hdr = (u_int32_t *)eh;
1957 ( want[0] == (hdr[0] & mask[0]) &&
1958 want[1] == (hdr[1] & mask[1]) &&
1959 want[2] == (hdr[2] & mask[2]) );
1964 if (args->flags & IPFW_ARGS_ETHER) {
1966 ((ipfw_insn_u16 *)cmd)->ports;
1969 for (i = cmdlen - 1; !match && i>0;
1972 (ntohs(eh->ether_type) >=
1974 ntohs(eh->ether_type) <=
1982 * Since flags_match() works with
1983 * uint8_t we pack ip_off into 8 bits.
1984 * For this match offset is a boolean.
1986 match = flags_match(cmd,
1987 ((ntohs(ip->ip_off) & ~IP_OFFMASK)
1988 >> 8) | (offset != 0));
1991 * Compatiblity: historically bare
1992 * "frag" would match IPv6 fragments.
1994 match = (cmd->arg1 == 0x1 &&
1999 case O_IN: /* "out" is "not in" */
2000 match = (oif == NULL);
2004 match = (args->flags & IPFW_ARGS_ETHER);
2008 if ((args->flags & IPFW_ARGS_REF) == 0)
2011 * For diverted packets, args->rule.info
2012 * contains the divert port (in host format)
2013 * reason and direction.
2015 match = ((args->rule.info & IPFW_IS_MASK) ==
2016 IPFW_IS_DIVERT) && (
2017 ((args->rule.info & IPFW_INFO_IN) ?
2023 * We do not allow an arg of 0 so the
2024 * check of "proto" only suffices.
2026 match = (proto == cmd->arg1);
2031 (((ipfw_insn_ip *)cmd)->addr.s_addr ==
2035 case O_IP_DST_LOOKUP:
2041 if (cmdlen > F_INSN_SIZE(ipfw_insn_u32)) {
2042 /* Determine lookup key type */
2043 vidx = ((ipfw_insn_u32 *)cmd)->d[1];
2044 if (vidx != 4 /* uid */ &&
2045 vidx != 5 /* jail */ &&
2046 is_ipv6 == 0 && is_ipv4 == 0)
2048 /* Determine key length */
2049 if (vidx == 0 /* dst-ip */ ||
2050 vidx == 1 /* src-ip */)
2052 sizeof(struct in6_addr):
2055 keylen = sizeof(key);
2058 if (vidx == 0 /* dst-ip */)
2059 pkey = is_ipv4 ? (void *)&dst_ip:
2060 (void *)&args->f_id.dst_ip6;
2061 else if (vidx == 1 /* src-ip */)
2062 pkey = is_ipv4 ? (void *)&src_ip:
2063 (void *)&args->f_id.src_ip6;
2064 else if (vidx == 6 /* dscp */) {
2066 key = ip->ip_tos >> 2;
2068 key = args->f_id.flow_id6;
2069 key = (key & 0x0f) << 2 |
2070 (key & 0xf000) >> 14;
2073 } else if (vidx == 2 /* dst-port */ ||
2074 vidx == 3 /* src-port */) {
2075 /* Skip fragments */
2078 /* Skip proto without ports */
2079 if (proto != IPPROTO_TCP &&
2080 proto != IPPROTO_UDP &&
2081 proto != IPPROTO_UDPLITE &&
2082 proto != IPPROTO_SCTP)
2084 if (vidx == 2 /* dst-port */)
2090 else if (vidx == 4 /* uid */ ||
2091 vidx == 5 /* jail */) {
2093 (ipfw_insn_u32 *)cmd,
2094 args, &ucred_lookup,
2097 if (vidx == 4 /* uid */)
2098 key = ucred_cache->cr_uid;
2099 else if (vidx == 5 /* jail */)
2100 key = ucred_cache->cr_prison->pr_id;
2101 #else /* !__FreeBSD__ */
2102 (void *)&ucred_cache);
2103 if (vidx == 4 /* uid */)
2104 key = ucred_cache.uid;
2105 else if (vidx == 5 /* jail */)
2106 key = ucred_cache.xid;
2107 #endif /* !__FreeBSD__ */
2109 #endif /* !USERSPACE */
2112 match = ipfw_lookup_table(chain,
2113 cmd->arg1, keylen, pkey, &vidx);
2119 /* cmdlen =< F_INSN_SIZE(ipfw_insn_u32) */
2122 case O_IP_SRC_LOOKUP:
2129 keylen = sizeof(in_addr_t);
2130 if (cmd->opcode == O_IP_DST_LOOKUP)
2134 } else if (is_ipv6) {
2135 keylen = sizeof(struct in6_addr);
2136 if (cmd->opcode == O_IP_DST_LOOKUP)
2137 pkey = &args->f_id.dst_ip6;
2139 pkey = &args->f_id.src_ip6;
2142 match = ipfw_lookup_table(chain, cmd->arg1,
2143 keylen, pkey, &vidx);
2146 if (cmdlen == F_INSN_SIZE(ipfw_insn_u32)) {
2147 match = ((ipfw_insn_u32 *)cmd)->d[0] ==
2148 TARG_VAL(chain, vidx, tag);
2156 case O_IP_FLOW_LOOKUP:
2159 match = ipfw_lookup_table(chain,
2160 cmd->arg1, 0, &args->f_id, &v);
2163 if (cmdlen == F_INSN_SIZE(ipfw_insn_u32))
2164 match = ((ipfw_insn_u32 *)cmd)->d[0] ==
2165 TARG_VAL(chain, v, tag);
2174 (cmd->opcode == O_IP_DST_MASK) ?
2175 dst_ip.s_addr : src_ip.s_addr;
2176 uint32_t *p = ((ipfw_insn_u32 *)cmd)->d;
2179 for (; !match && i>0; i-= 2, p+= 2)
2180 match = (p[0] == (a & p[1]));
2186 match = in_localip(src_ip);
2193 ipfw_localip6(&args->f_id.src_ip6);
2200 u_int32_t *d = (u_int32_t *)(cmd+1);
2202 cmd->opcode == O_IP_DST_SET ?
2208 addr -= d[0]; /* subtract base */
2209 match = (addr < cmd->arg1) &&
2210 ( d[ 1 + (addr>>5)] &
2211 (1<<(addr & 0x1f)) );
2217 (((ipfw_insn_ip *)cmd)->addr.s_addr ==
2223 match = in_localip(dst_ip);
2230 ipfw_localip6(&args->f_id.dst_ip6);
2237 * offset == 0 && proto != 0 is enough
2238 * to guarantee that we have a
2239 * packet with port info.
2241 if ((proto == IPPROTO_UDP ||
2242 proto == IPPROTO_UDPLITE ||
2243 proto == IPPROTO_TCP ||
2244 proto == IPPROTO_SCTP) && offset == 0) {
2246 (cmd->opcode == O_IP_SRCPORT) ?
2247 src_port : dst_port ;
2249 ((ipfw_insn_u16 *)cmd)->ports;
2252 for (i = cmdlen - 1; !match && i>0;
2254 match = (x>=p[0] && x<=p[1]);
2259 match = (offset == 0 && proto==IPPROTO_ICMP &&
2260 icmptype_match(ICMP(ulp), (ipfw_insn_u32 *)cmd) );
2265 match = is_ipv6 && offset == 0 &&
2266 proto==IPPROTO_ICMPV6 &&
2268 ICMP6(ulp)->icmp6_type,
2269 (ipfw_insn_u32 *)cmd);
2275 ipopts_match(ip, cmd) );
2279 match = ((is_ipv4 || is_ipv6) &&
2280 cmd->arg1 == ip->ip_v);
2288 { /* only for IP packets */
2293 if (cmd->opcode == O_IPLEN)
2295 else if (cmd->opcode == O_IPTTL)
2297 else /* must be IPID */
2298 x = ntohs(ip->ip_id);
2300 match = (cmd->arg1 == x);
2303 /* otherwise we have ranges */
2304 p = ((ipfw_insn_u16 *)cmd)->ports;
2306 for (; !match && i>0; i--, p += 2)
2307 match = (x >= p[0] && x <= p[1]);
2311 case O_IPPRECEDENCE:
2313 (cmd->arg1 == (ip->ip_tos & 0xe0)) );
2318 flags_match(cmd, ip->ip_tos));
2326 p = ((ipfw_insn_u32 *)cmd)->d;
2329 x = ip->ip_tos >> 2;
2332 v = &((struct ip6_hdr *)ip)->ip6_vfc;
2333 x = (*v & 0x0F) << 2;
2339 /* DSCP bitmask is stored as low_u32 high_u32 */
2341 match = *(p + 1) & (1 << (x - 32));
2343 match = *p & (1 << x);
2348 if (proto == IPPROTO_TCP && offset == 0) {
2355 struct ip6_hdr *ip6;
2357 ip6 = (struct ip6_hdr *)ip;
2358 if (ip6->ip6_plen == 0) {
2360 * Jumbo payload is not
2369 x = iplen - (ip->ip_hl << 2);
2371 x -= tcp->th_off << 2;
2373 match = (cmd->arg1 == x);
2376 /* otherwise we have ranges */
2377 p = ((ipfw_insn_u16 *)cmd)->ports;
2379 for (; !match && i>0; i--, p += 2)
2380 match = (x >= p[0] && x <= p[1]);
2385 match = (proto == IPPROTO_TCP && offset == 0 &&
2386 flags_match(cmd, TCP(ulp)->th_flags));
2390 if (proto == IPPROTO_TCP && offset == 0 && ulp){
2391 PULLUP_LEN_LOCKED(hlen, ulp,
2392 (TCP(ulp)->th_off << 2));
2393 match = tcpopts_match(TCP(ulp), cmd);
2398 match = (proto == IPPROTO_TCP && offset == 0 &&
2399 ((ipfw_insn_u32 *)cmd)->d[0] ==
2404 match = (proto == IPPROTO_TCP && offset == 0 &&
2405 ((ipfw_insn_u32 *)cmd)->d[0] ==
2410 if (proto == IPPROTO_TCP &&
2411 (args->f_id._flags & TH_SYN) != 0 &&
2416 PULLUP_LEN_LOCKED(hlen, ulp,
2417 (TCP(ulp)->th_off << 2));
2418 if ((tcpopts_parse(TCP(ulp), &mss) &
2419 IP_FW_TCPOPT_MSS) == 0)
2422 match = (cmd->arg1 == mss);
2425 /* Otherwise we have ranges. */
2426 p = ((ipfw_insn_u16 *)cmd)->ports;
2428 for (; !match && i > 0; i--, p += 2)
2429 match = (mss >= p[0] &&
2435 if (proto == IPPROTO_TCP && offset == 0) {
2440 x = ntohs(TCP(ulp)->th_win);
2442 match = (cmd->arg1 == x);
2445 /* Otherwise we have ranges. */
2446 p = ((ipfw_insn_u16 *)cmd)->ports;
2448 for (; !match && i > 0; i--, p += 2)
2449 match = (x >= p[0] && x <= p[1]);
2454 /* reject packets which have SYN only */
2455 /* XXX should i also check for TH_ACK ? */
2456 match = (proto == IPPROTO_TCP && offset == 0 &&
2457 (TCP(ulp)->th_flags &
2458 (TH_RST | TH_ACK | TH_SYN)) != TH_SYN);
2464 ipfw_insn_altq *altq = (ipfw_insn_altq *)cmd;
2467 * ALTQ uses mbuf tags from another
2468 * packet filtering system - pf(4).
2469 * We allocate a tag in its format
2470 * and fill it in, pretending to be pf(4).
2473 at = pf_find_mtag(m);
2474 if (at != NULL && at->qid != 0)
2476 mtag = m_tag_get(PACKET_TAG_PF,
2477 sizeof(struct pf_mtag), M_NOWAIT | M_ZERO);
2480 * Let the packet fall back to the
2485 m_tag_prepend(m, mtag);
2486 at = (struct pf_mtag *)(mtag + 1);
2487 at->qid = altq->qid;
2493 ipfw_log(chain, f, hlen, args,
2494 offset | ip6f_mf, tablearg, ip);
2499 match = (random()<((ipfw_insn_u32 *)cmd)->d[0]);
2503 /* Outgoing packets automatically pass/match */
2504 match = (args->flags & IPFW_ARGS_OUT ||
2508 verify_path6(&(args->f_id.src_ip6),
2509 iif, args->f_id.fib) :
2511 verify_path(src_ip, iif, args->f_id.fib)));
2515 /* Outgoing packets automatically pass/match */
2516 match = (hlen > 0 && ((oif != NULL) || (
2519 verify_path6(&(args->f_id.src_ip6),
2520 NULL, args->f_id.fib) :
2522 verify_path(src_ip, NULL, args->f_id.fib))));
2526 /* Outgoing packets automatically pass/match */
2527 if (oif == NULL && hlen > 0 &&
2528 ( (is_ipv4 && in_localaddr(src_ip))
2531 in6_localaddr(&(args->f_id.src_ip6)))
2536 is_ipv6 ? verify_path6(
2537 &(args->f_id.src_ip6), iif,
2540 verify_path(src_ip, iif,
2547 match = (m_tag_find(m,
2548 PACKET_TAG_IPSEC_IN_DONE, NULL) != NULL);
2549 /* otherwise no match */
2555 IN6_ARE_ADDR_EQUAL(&args->f_id.src_ip6,
2556 &((ipfw_insn_ip6 *)cmd)->addr6);
2561 IN6_ARE_ADDR_EQUAL(&args->f_id.dst_ip6,
2562 &((ipfw_insn_ip6 *)cmd)->addr6);
2564 case O_IP6_SRC_MASK:
2565 case O_IP6_DST_MASK:
2569 struct in6_addr *d =
2570 &((ipfw_insn_ip6 *)cmd)->addr6;
2572 for (; !match && i > 0; d += 2,
2573 i -= F_INSN_SIZE(struct in6_addr)
2579 APPLY_MASK(&p, &d[1]);
2581 IN6_ARE_ADDR_EQUAL(&d[0],
2589 flow6id_match(args->f_id.flow_id6,
2590 (ipfw_insn_u32 *) cmd);
2595 (ext_hd & ((ipfw_insn *) cmd)->arg1);
2609 uint32_t tag = TARG(cmd->arg1, tag);
2611 /* Packet is already tagged with this tag? */
2612 mtag = m_tag_locate(m, MTAG_IPFW, tag, NULL);
2614 /* We have `untag' action when F_NOT flag is
2615 * present. And we must remove this mtag from
2616 * mbuf and reset `match' to zero (`match' will
2617 * be inversed later).
2618 * Otherwise we should allocate new mtag and
2619 * push it into mbuf.
2621 if (cmd->len & F_NOT) { /* `untag' action */
2623 m_tag_delete(m, mtag);
2627 mtag = m_tag_alloc( MTAG_IPFW,
2630 m_tag_prepend(m, mtag);
2637 case O_FIB: /* try match the specified fib */
2638 if (args->f_id.fib == cmd->arg1)
2643 #ifndef USERSPACE /* not supported in userspace */
2644 struct inpcb *inp = args->inp;
2645 struct inpcbinfo *pi;
2646 bool inp_locked = false;
2648 if (proto == IPPROTO_TCP)
2650 else if (proto == IPPROTO_UDP)
2652 else if (proto == IPPROTO_UDPLITE)
2653 pi = &V_ulitecbinfo;
2658 * XXXRW: so_user_cookie should almost
2659 * certainly be inp_user_cookie?
2663 * For incoming packet lookup the inpcb
2664 * using the src/dest ip/port tuple.
2666 if (is_ipv4 && inp == NULL) {
2667 inp = in_pcblookup(pi,
2668 src_ip, htons(src_port),
2669 dst_ip, htons(dst_port),
2670 INPLOOKUP_RLOCKPCB, NULL);
2674 if (is_ipv6 && inp == NULL) {
2675 inp = in6_pcblookup(pi,
2676 &args->f_id.src_ip6,
2678 &args->f_id.dst_ip6,
2680 INPLOOKUP_RLOCKPCB, NULL);
2685 if (inp->inp_socket) {
2687 inp->inp_socket->so_user_cookie;
2694 #endif /* !USERSPACE */
2700 uint32_t tag = TARG(cmd->arg1, tag);
2703 match = m_tag_locate(m, MTAG_IPFW,
2708 /* we have ranges */
2709 for (mtag = m_tag_first(m);
2710 mtag != NULL && !match;
2711 mtag = m_tag_next(m, mtag)) {
2715 if (mtag->m_tag_cookie != MTAG_IPFW)
2718 p = ((ipfw_insn_u16 *)cmd)->ports;
2720 for(; !match && i > 0; i--, p += 2)
2722 mtag->m_tag_id >= p[0] &&
2723 mtag->m_tag_id <= p[1];
2729 * The second set of opcodes represents 'actions',
2730 * i.e. the terminal part of a rule once the packet
2731 * matches all previous patterns.
2732 * Typically there is only one action for each rule,
2733 * and the opcode is stored at the end of the rule
2734 * (but there are exceptions -- see below).
2736 * In general, here we set retval and terminate the
2737 * outer loop (would be a 'break 3' in some language,
2738 * but we need to set l=0, done=1)
2741 * O_COUNT and O_SKIPTO actions:
2742 * instead of terminating, we jump to the next rule
2743 * (setting l=0), or to the SKIPTO target (setting
2744 * f/f_len, cmd and l as needed), respectively.
2746 * O_TAG, O_LOG and O_ALTQ action parameters:
2747 * perform some action and set match = 1;
2749 * O_LIMIT and O_KEEP_STATE: these opcodes are
2750 * not real 'actions', and are stored right
2751 * before the 'action' part of the rule (one
2752 * exception is O_SKIP_ACTION which could be
2753 * between these opcodes and 'action' one).
2754 * These opcodes try to install an entry in the
2755 * state tables; if successful, we continue with
2756 * the next opcode (match=1; break;), otherwise
2757 * the packet must be dropped (set retval,
2758 * break loops with l=0, done=1)
2760 * O_PROBE_STATE and O_CHECK_STATE: these opcodes
2761 * cause a lookup of the state table, and a jump
2762 * to the 'action' part of the parent rule
2763 * if an entry is found, or
2764 * (CHECK_STATE only) a jump to the next rule if
2765 * the entry is not found.
2766 * The result of the lookup is cached so that
2767 * further instances of these opcodes become NOPs.
2768 * The jump to the next rule is done by setting
2771 * O_SKIP_ACTION: this opcode is not a real 'action'
2772 * either, and is stored right before the 'action'
2773 * part of the rule, right after the O_KEEP_STATE
2774 * opcode. It causes match failure so the real
2775 * 'action' could be executed only if the rule
2776 * is checked via dynamic rule from the state
2777 * table, as in such case execution starts
2778 * from the true 'action' opcode directly.
2783 if (ipfw_dyn_install_state(chain, f,
2784 (ipfw_insn_limit *)cmd, args, ulp,
2785 pktlen, &dyn_info, tablearg)) {
2786 /* error or limit violation */
2787 retval = IP_FW_DENY;
2788 l = 0; /* exit inner loop */
2789 done = 1; /* exit outer loop */
2797 * dynamic rules are checked at the first
2798 * keep-state or check-state occurrence,
2799 * with the result being stored in dyn_info.
2800 * The compiler introduces a PROBE_STATE
2801 * instruction for us when we have a
2802 * KEEP_STATE (because PROBE_STATE needs
2805 if (DYN_LOOKUP_NEEDED(&dyn_info, cmd) &&
2806 (q = ipfw_dyn_lookup_state(args, ulp,
2807 pktlen, cmd, &dyn_info)) != NULL) {
2809 * Found dynamic entry, jump to the
2810 * 'action' part of the parent rule
2811 * by setting f, cmd, l and clearing
2815 f_pos = dyn_info.f_pos;
2816 cmd = ACTION_PTR(f);
2817 l = f->cmd_len - f->act_ofs;
2823 * Dynamic entry not found. If CHECK_STATE,
2824 * skip to next rule, if PROBE_STATE just
2825 * ignore and continue with next opcode.
2827 if (cmd->opcode == O_CHECK_STATE)
2828 l = 0; /* exit inner loop */
2833 match = 0; /* skip to the next rule */
2834 l = 0; /* exit inner loop */
2838 retval = 0; /* accept */
2839 l = 0; /* exit inner loop */
2840 done = 1; /* exit outer loop */
2845 set_match(args, f_pos, chain);
2846 args->rule.info = TARG(cmd->arg1, pipe);
2847 if (cmd->opcode == O_PIPE)
2848 args->rule.info |= IPFW_IS_PIPE;
2850 args->rule.info |= IPFW_ONEPASS;
2851 retval = IP_FW_DUMMYNET;
2852 l = 0; /* exit inner loop */
2853 done = 1; /* exit outer loop */
2858 if (args->flags & IPFW_ARGS_ETHER)
2859 break; /* not on layer 2 */
2860 /* otherwise this is terminal */
2861 l = 0; /* exit inner loop */
2862 done = 1; /* exit outer loop */
2863 retval = (cmd->opcode == O_DIVERT) ?
2864 IP_FW_DIVERT : IP_FW_TEE;
2865 set_match(args, f_pos, chain);
2866 args->rule.info = TARG(cmd->arg1, divert);
2870 IPFW_INC_RULE_COUNTER(f, pktlen);
2871 l = 0; /* exit inner loop */
2875 IPFW_INC_RULE_COUNTER(f, pktlen);
2876 f_pos = JUMP(chain, f, cmd->arg1, tablearg, 0);
2878 * Skip disabled rules, and re-enter
2879 * the inner loop with the correct
2880 * f_pos, f, l and cmd.
2881 * Also clear cmdlen and skip_or
2883 for (; f_pos < chain->n_rules - 1 &&
2885 (1 << chain->map[f_pos]->set));
2888 /* Re-enter the inner loop at the skipto rule. */
2889 f = chain->map[f_pos];
2896 break; /* not reached */
2898 case O_CALLRETURN: {
2900 * Implementation of `subroutine' call/return,
2901 * in the stack carried in an mbuf tag. This
2902 * is different from `skipto' in that any call
2903 * address is possible (`skipto' must prevent
2904 * backward jumps to avoid endless loops).
2905 * We have `return' action when F_NOT flag is
2906 * present. The `m_tag_id' field is used as
2910 uint16_t jmpto, *stack;
2912 #define IS_CALL ((cmd->len & F_NOT) == 0)
2913 #define IS_RETURN ((cmd->len & F_NOT) != 0)
2915 * Hand-rolled version of m_tag_locate() with
2917 * If not already tagged, allocate new tag.
2919 mtag = m_tag_first(m);
2920 while (mtag != NULL) {
2921 if (mtag->m_tag_cookie ==
2924 mtag = m_tag_next(m, mtag);
2926 if (mtag == NULL && IS_CALL) {
2927 mtag = m_tag_alloc(MTAG_IPFW_CALL, 0,
2928 IPFW_CALLSTACK_SIZE *
2929 sizeof(uint16_t), M_NOWAIT);
2931 m_tag_prepend(m, mtag);
2935 * On error both `call' and `return' just
2936 * continue with next rule.
2938 if (IS_RETURN && (mtag == NULL ||
2939 mtag->m_tag_id == 0)) {
2940 l = 0; /* exit inner loop */
2943 if (IS_CALL && (mtag == NULL ||
2944 mtag->m_tag_id >= IPFW_CALLSTACK_SIZE)) {
2945 printf("ipfw: call stack error, "
2946 "go to next rule\n");
2947 l = 0; /* exit inner loop */
2951 IPFW_INC_RULE_COUNTER(f, pktlen);
2952 stack = (uint16_t *)(mtag + 1);
2955 * The `call' action may use cached f_pos
2956 * (in f->next_rule), whose version is written
2958 * The `return' action, however, doesn't have
2959 * fixed jump address in cmd->arg1 and can't use
2963 stack[mtag->m_tag_id] = f->rulenum;
2965 f_pos = JUMP(chain, f, cmd->arg1,
2967 } else { /* `return' action */
2969 jmpto = stack[mtag->m_tag_id] + 1;
2970 f_pos = ipfw_find_rule(chain, jmpto, 0);
2974 * Skip disabled rules, and re-enter
2975 * the inner loop with the correct
2976 * f_pos, f, l and cmd.
2977 * Also clear cmdlen and skip_or
2979 for (; f_pos < chain->n_rules - 1 &&
2981 (1 << chain->map[f_pos]->set)); f_pos++)
2983 /* Re-enter the inner loop at the dest rule. */
2984 f = chain->map[f_pos];
2990 break; /* NOTREACHED */
2997 * Drop the packet and send a reject notice
2998 * if the packet is not ICMP (or is an ICMP
2999 * query), and it is not multicast/broadcast.
3001 if (hlen > 0 && is_ipv4 && offset == 0 &&
3002 (proto != IPPROTO_ICMP ||
3003 is_icmp_query(ICMP(ulp))) &&
3004 !(m->m_flags & (M_BCAST|M_MCAST)) &&
3005 !IN_MULTICAST(ntohl(dst_ip.s_addr))) {
3006 send_reject(args, cmd->arg1, iplen, ip);
3012 if (hlen > 0 && is_ipv6 &&
3013 ((offset & IP6F_OFF_MASK) == 0) &&
3014 (proto != IPPROTO_ICMPV6 ||
3015 (is_icmp6_query(icmp6_type) == 1)) &&
3016 !(m->m_flags & (M_BCAST|M_MCAST)) &&
3017 !IN6_IS_ADDR_MULTICAST(
3018 &args->f_id.dst_ip6)) {
3020 cmd->opcode == O_REJECT ?
3021 map_icmp_unreach(cmd->arg1):
3023 (struct ip6_hdr *)ip);
3029 retval = IP_FW_DENY;
3030 l = 0; /* exit inner loop */
3031 done = 1; /* exit outer loop */
3035 if (args->flags & IPFW_ARGS_ETHER)
3036 break; /* not valid on layer2 pkts */
3038 dyn_info.direction == MATCH_FORWARD) {
3039 struct sockaddr_in *sa;
3041 sa = &(((ipfw_insn_sa *)cmd)->sa);
3042 if (sa->sin_addr.s_addr == INADDR_ANY) {
3045 * We use O_FORWARD_IP opcode for
3046 * fwd rule with tablearg, but tables
3047 * now support IPv6 addresses. And
3048 * when we are inspecting IPv6 packet,
3049 * we can use nh6 field from
3050 * table_value as next_hop6 address.
3053 struct ip_fw_nh6 *nh6;
3055 args->flags |= IPFW_ARGS_NH6;
3056 nh6 = &args->hopstore6;
3057 nh6->sin6_addr = TARG_VAL(
3058 chain, tablearg, nh6);
3059 nh6->sin6_port = sa->sin_port;
3060 nh6->sin6_scope_id = TARG_VAL(
3061 chain, tablearg, zoneid);
3065 args->flags |= IPFW_ARGS_NH4;
3066 args->hopstore.sin_port =
3068 sa = &args->hopstore;
3069 sa->sin_family = AF_INET;
3070 sa->sin_len = sizeof(*sa);
3071 sa->sin_addr.s_addr = htonl(
3072 TARG_VAL(chain, tablearg,
3076 args->flags |= IPFW_ARGS_NH4PTR;
3077 args->next_hop = sa;
3080 retval = IP_FW_PASS;
3081 l = 0; /* exit inner loop */
3082 done = 1; /* exit outer loop */
3087 if (args->flags & IPFW_ARGS_ETHER)
3088 break; /* not valid on layer2 pkts */
3090 dyn_info.direction == MATCH_FORWARD) {
3091 struct sockaddr_in6 *sin6;
3093 sin6 = &(((ipfw_insn_sa6 *)cmd)->sa);
3094 args->flags |= IPFW_ARGS_NH6PTR;
3095 args->next_hop6 = sin6;
3097 retval = IP_FW_PASS;
3098 l = 0; /* exit inner loop */
3099 done = 1; /* exit outer loop */
3105 set_match(args, f_pos, chain);
3106 args->rule.info = TARG(cmd->arg1, netgraph);
3108 args->rule.info |= IPFW_ONEPASS;
3109 retval = (cmd->opcode == O_NETGRAPH) ?
3110 IP_FW_NETGRAPH : IP_FW_NGTEE;
3111 l = 0; /* exit inner loop */
3112 done = 1; /* exit outer loop */
3118 IPFW_INC_RULE_COUNTER(f, pktlen);
3119 fib = TARG(cmd->arg1, fib) & 0x7FFF;
3120 if (fib >= rt_numfibs)
3123 args->f_id.fib = fib; /* XXX */
3124 l = 0; /* exit inner loop */
3131 code = TARG(cmd->arg1, dscp) & 0x3F;
3132 l = 0; /* exit inner loop */
3136 old = *(uint16_t *)ip;
3137 ip->ip_tos = (code << 2) |
3138 (ip->ip_tos & 0x03);
3139 ip->ip_sum = cksum_adjust(ip->ip_sum,
3140 old, *(uint16_t *)ip);
3141 } else if (is_ipv6) {
3144 v = &((struct ip6_hdr *)ip)->ip6_vfc;
3145 *v = (*v & 0xF0) | (code >> 2);
3147 *v = (*v & 0x3F) | ((code & 0x03) << 6);
3151 IPFW_INC_RULE_COUNTER(f, pktlen);
3156 l = 0; /* exit inner loop */
3157 done = 1; /* exit outer loop */
3159 * Ensure that we do not invoke NAT handler for
3160 * non IPv4 packets. Libalias expects only IPv4.
3162 if (!is_ipv4 || !IPFW_NAT_LOADED) {
3163 retval = IP_FW_DENY;
3170 args->rule.info = 0;
3171 set_match(args, f_pos, chain);
3172 /* Check if this is 'global' nat rule */
3173 if (cmd->arg1 == IP_FW_NAT44_GLOBAL) {
3174 retval = ipfw_nat_ptr(args, NULL, m);
3177 t = ((ipfw_insn_nat *)cmd)->nat;
3179 nat_id = TARG(cmd->arg1, nat);
3180 t = (*lookup_nat_ptr)(&chain->nat, nat_id);
3183 retval = IP_FW_DENY;
3186 if (cmd->arg1 != IP_FW_TARG)
3187 ((ipfw_insn_nat *)cmd)->nat = t;
3189 retval = ipfw_nat_ptr(args, t, m);
3195 l = 0; /* in any case exit inner loop */
3196 if (is_ipv6) /* IPv6 is not supported yet */
3198 IPFW_INC_RULE_COUNTER(f, pktlen);
3199 ip_off = ntohs(ip->ip_off);
3201 /* if not fragmented, go to next rule */
3202 if ((ip_off & (IP_MF | IP_OFFMASK)) == 0)
3205 args->m = m = ip_reass(m);
3208 * do IP header checksum fixup.
3210 if (m == NULL) { /* fragment got swallowed */
3211 retval = IP_FW_DENY;
3212 } else { /* good, packet complete */
3215 ip = mtod(m, struct ip *);
3216 hlen = ip->ip_hl << 2;
3218 if (hlen == sizeof(struct ip))
3219 ip->ip_sum = in_cksum_hdr(ip);
3221 ip->ip_sum = in_cksum(m, hlen);
3222 retval = IP_FW_REASS;
3223 args->rule.info = 0;
3224 set_match(args, f_pos, chain);
3226 done = 1; /* exit outer loop */
3229 case O_EXTERNAL_ACTION:
3230 l = 0; /* in any case exit inner loop */
3231 retval = ipfw_run_eaction(chain, args,
3234 * If both @retval and @done are zero,
3235 * consider this as rule matching and
3238 if (retval == 0 && done == 0) {
3239 IPFW_INC_RULE_COUNTER(f, pktlen);
3241 * Reset the result of the last
3242 * dynamic state lookup.
3243 * External action can change
3244 * @args content, and it may be
3245 * used for new state lookup later.
3247 DYN_INFO_INIT(&dyn_info);
3252 panic("-- unknown opcode %d\n", cmd->opcode);
3253 } /* end of switch() on opcodes */
3255 * if we get here with l=0, then match is irrelevant.
3258 if (cmd->len & F_NOT)
3262 if (cmd->len & F_OR)
3265 if (!(cmd->len & F_OR)) /* not an OR block, */
3266 break; /* try next rule */
3269 } /* end of inner loop, scan opcodes */
3271 #undef PULLUP_LEN_LOCKED
3276 /* next_rule:; */ /* try next rule */
3278 } /* end of outer for, scan rules */
3281 struct ip_fw *rule = chain->map[f_pos];
3282 /* Update statistics */
3283 IPFW_INC_RULE_COUNTER(rule, pktlen);
3284 IPFW_PROBE(rule__matched, retval,
3285 is_ipv4 ? AF_INET : AF_INET6,
3286 is_ipv4 ? (uintptr_t)&src_ip :
3287 (uintptr_t)&args->f_id.src_ip6,
3288 is_ipv4 ? (uintptr_t)&dst_ip :
3289 (uintptr_t)&args->f_id.dst_ip6,
3292 retval = IP_FW_DENY;
3293 printf("ipfw: ouch!, skip past end of rules, denying packet\n");
3295 IPFW_PF_RUNLOCK(chain);
3297 if (ucred_cache != NULL)
3298 crfree(ucred_cache);
3304 printf("ipfw: pullup failed\n");
3305 return (IP_FW_DENY);
3309 * Set maximum number of tables that can be used in given VNET ipfw instance.
3313 sysctl_ipfw_table_num(SYSCTL_HANDLER_ARGS)
3316 unsigned int ntables;
3318 ntables = V_fw_tables_max;
3320 error = sysctl_handle_int(oidp, &ntables, 0, req);
3321 /* Read operation or some error */
3322 if ((error != 0) || (req->newptr == NULL))
3325 return (ipfw_resize_tables(&V_layer3_chain, ntables));
3329 * Switches table namespace between global and per-set.
3332 sysctl_ipfw_tables_sets(SYSCTL_HANDLER_ARGS)
3337 sets = V_fw_tables_sets;
3339 error = sysctl_handle_int(oidp, &sets, 0, req);
3340 /* Read operation or some error */
3341 if ((error != 0) || (req->newptr == NULL))
3344 return (ipfw_switch_tables_namespace(&V_layer3_chain, sets));
3349 * Module and VNET glue
3353 * Stuff that must be initialised only on boot or module load
3361 * Only print out this stuff the first time around,
3362 * when called from the sysinit code.
3368 "initialized, divert %s, nat %s, "
3369 "default to %s, logging ",
3375 #ifdef IPFIREWALL_NAT
3380 default_to_accept ? "accept" : "deny");
3383 * Note: V_xxx variables can be accessed here but the vnet specific
3384 * initializer may not have been called yet for the VIMAGE case.
3385 * Tuneables will have been processed. We will print out values for
3387 * XXX This should all be rationalized AFTER 8.0
3389 if (V_fw_verbose == 0)
3390 printf("disabled\n");
3391 else if (V_verbose_limit == 0)
3392 printf("unlimited\n");
3394 printf("limited to %d packets/entry by default\n",
3397 /* Check user-supplied table count for validness */
3398 if (default_fw_tables > IPFW_TABLES_MAX)
3399 default_fw_tables = IPFW_TABLES_MAX;
3401 ipfw_init_sopt_handler();
3402 ipfw_init_obj_rewriter();
3408 * Called for the removal of the last instance only on module unload.
3414 ipfw_iface_destroy();
3415 ipfw_destroy_sopt_handler();
3416 ipfw_destroy_obj_rewriter();
3417 printf("IP firewall unloaded\n");
3421 * Stuff that must be initialized for every instance
3422 * (including the first of course).
3425 vnet_ipfw_init(const void *unused)
3428 struct ip_fw *rule = NULL;
3429 struct ip_fw_chain *chain;
3431 chain = &V_layer3_chain;
3433 first = IS_DEFAULT_VNET(curvnet) ? 1 : 0;
3435 /* First set up some values that are compile time options */
3436 V_autoinc_step = 100; /* bounded to 1..1000 in add_rule() */
3437 V_fw_deny_unknown_exthdrs = 1;
3438 #ifdef IPFIREWALL_VERBOSE
3441 #ifdef IPFIREWALL_VERBOSE_LIMIT
3442 V_verbose_limit = IPFIREWALL_VERBOSE_LIMIT;
3444 #ifdef IPFIREWALL_NAT
3445 LIST_INIT(&chain->nat);
3448 /* Init shared services hash table */
3449 ipfw_init_srv(chain);
3451 ipfw_init_counters();
3452 /* Set initial number of tables */
3453 V_fw_tables_max = default_fw_tables;
3454 error = ipfw_init_tables(chain, first);
3456 printf("ipfw2: setting up tables failed\n");
3457 free(chain->map, M_IPFW);
3462 IPFW_LOCK_INIT(chain);
3464 /* fill and insert the default rule */
3465 rule = ipfw_alloc_rule(chain, sizeof(struct ip_fw));
3466 rule->flags |= IPFW_RULE_NOOPT;
3468 rule->cmd[0].len = 1;
3469 rule->cmd[0].opcode = default_to_accept ? O_ACCEPT : O_DENY;
3470 chain->default_rule = rule;
3471 ipfw_add_protected_rule(chain, rule, 0);
3473 ipfw_dyn_init(chain);
3474 ipfw_eaction_init(chain, first);
3475 #ifdef LINEAR_SKIPTO
3476 ipfw_init_skipto_cache(chain);
3478 ipfw_bpf_init(first);
3480 /* First set up some values that are compile time options */
3481 V_ipfw_vnet_ready = 1; /* Open for business */
3484 * Hook the sockopt handler and pfil hooks for ipv4 and ipv6.
3485 * Even if the latter two fail we still keep the module alive
3486 * because the sockopt and layer2 paths are still useful.
3487 * ipfw[6]_hook return 0 on success, ENOENT on failure,
3488 * so we can ignore the exact return value and just set a flag.
3490 * Note that V_fw[6]_enable are manipulated by a SYSCTL_PROC so
3491 * changes in the underlying (per-vnet) variables trigger
3492 * immediate hook()/unhook() calls.
3493 * In layer2 we have the same behaviour, except that V_ether_ipfw
3494 * is checked on each packet because there are no pfil hooks.
3496 V_ip_fw_ctl_ptr = ipfw_ctl3;
3497 error = ipfw_attach_hooks();
3502 * Called for the removal of each instance.
3505 vnet_ipfw_uninit(const void *unused)
3508 struct ip_fw_chain *chain = &V_layer3_chain;
3511 V_ipfw_vnet_ready = 0; /* tell new callers to go away */
3513 * disconnect from ipv4, ipv6, layer2 and sockopt.
3514 * Then grab, release and grab again the WLOCK so we make
3515 * sure the update is propagated and nobody will be in.
3517 ipfw_detach_hooks();
3518 V_ip_fw_ctl_ptr = NULL;
3520 last = IS_DEFAULT_VNET(curvnet) ? 1 : 0;
3522 IPFW_UH_WLOCK(chain);
3523 IPFW_UH_WUNLOCK(chain);
3525 ipfw_dyn_uninit(0); /* run the callout_drain */
3527 IPFW_UH_WLOCK(chain);
3531 for (i = 0; i < chain->n_rules; i++)
3532 ipfw_reap_add(chain, &reap, chain->map[i]);
3533 free(chain->map, M_IPFW);
3534 #ifdef LINEAR_SKIPTO
3535 ipfw_destroy_skipto_cache(chain);
3537 IPFW_WUNLOCK(chain);
3538 IPFW_UH_WUNLOCK(chain);
3539 ipfw_destroy_tables(chain, last);
3540 ipfw_eaction_uninit(chain, last);
3542 ipfw_reap_rules(reap);
3543 vnet_ipfw_iface_destroy(chain);
3544 ipfw_destroy_srv(chain);
3545 IPFW_LOCK_DESTROY(chain);
3546 ipfw_dyn_uninit(1); /* free the remaining parts */
3547 ipfw_destroy_counters();
3548 ipfw_bpf_uninit(last);
3553 * Module event handler.
3554 * In general we have the choice of handling most of these events by the
3555 * event handler or by the (VNET_)SYS(UN)INIT handlers. I have chosen to
3556 * use the SYSINIT handlers as they are more capable of expressing the
3557 * flow of control during module and vnet operations, so this is just
3558 * a skeleton. Note there is no SYSINIT equivalent of the module
3559 * SHUTDOWN handler, but we don't have anything to do in that case anyhow.
3562 ipfw_modevent(module_t mod, int type, void *unused)
3568 /* Called once at module load or
3569 * system boot if compiled in. */
3572 /* Called before unload. May veto unloading. */
3575 /* Called during unload. */
3578 /* Called during system shutdown. */
3587 static moduledata_t ipfwmod = {
3593 /* Define startup order. */
3594 #define IPFW_SI_SUB_FIREWALL SI_SUB_PROTO_FIREWALL
3595 #define IPFW_MODEVENT_ORDER (SI_ORDER_ANY - 255) /* On boot slot in here. */
3596 #define IPFW_MODULE_ORDER (IPFW_MODEVENT_ORDER + 1) /* A little later. */
3597 #define IPFW_VNET_ORDER (IPFW_MODEVENT_ORDER + 2) /* Later still. */
3599 DECLARE_MODULE(ipfw, ipfwmod, IPFW_SI_SUB_FIREWALL, IPFW_MODEVENT_ORDER);
3600 FEATURE(ipfw_ctl3, "ipfw new sockopt calls");
3601 MODULE_VERSION(ipfw, 3);
3602 /* should declare some dependencies here */
3605 * Starting up. Done in order after ipfwmod() has been called.
3606 * VNET_SYSINIT is also called for each existing vnet and each new vnet.
3608 SYSINIT(ipfw_init, IPFW_SI_SUB_FIREWALL, IPFW_MODULE_ORDER,
3610 VNET_SYSINIT(vnet_ipfw_init, IPFW_SI_SUB_FIREWALL, IPFW_VNET_ORDER,
3611 vnet_ipfw_init, NULL);
3614 * Closing up shop. These are done in REVERSE ORDER, but still
3615 * after ipfwmod() has been called. Not called on reboot.
3616 * VNET_SYSUNINIT is also called for each exiting vnet as it exits.
3617 * or when the module is unloaded.
3619 SYSUNINIT(ipfw_destroy, IPFW_SI_SUB_FIREWALL, IPFW_MODULE_ORDER,
3620 ipfw_destroy, NULL);
3621 VNET_SYSUNINIT(vnet_ipfw_uninit, IPFW_SI_SUB_FIREWALL, IPFW_VNET_ORDER,
3622 vnet_ipfw_uninit, NULL);