2 * Copyright (c) 2002 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$");
33 * Implement IP packet firewall (new version)
36 #if !defined(KLD_MODULE)
38 #include "opt_ipdivert.h"
42 #error IPFIREWALL requires INET.
45 #include "opt_inet6.h"
46 #include "opt_ipsec.h"
49 #include <sys/param.h>
50 #include <sys/systm.h>
51 #include <sys/condvar.h>
52 #include <sys/eventhandler.h>
53 #include <sys/malloc.h>
55 #include <sys/kernel.h>
58 #include <sys/module.h>
61 #include <sys/rwlock.h>
62 #include <sys/socket.h>
63 #include <sys/socketvar.h>
64 #include <sys/sysctl.h>
65 #include <sys/syslog.h>
66 #include <sys/ucred.h>
67 #include <sys/vimage.h>
69 #include <net/radix.h>
70 #include <net/route.h>
71 #include <net/pf_mtag.h>
73 #define IPFW_INTERNAL /* Access to protected data structures in ip_fw.h. */
75 #include <netinet/in.h>
76 #include <netinet/in_systm.h>
77 #include <netinet/in_var.h>
78 #include <netinet/in_pcb.h>
79 #include <netinet/ip.h>
80 #include <netinet/ip_var.h>
81 #include <netinet/ip_icmp.h>
82 #include <netinet/ip_fw.h>
83 #include <netinet/ip_divert.h>
84 #include <netinet/ip_dummynet.h>
85 #include <netinet/ip_carp.h>
86 #include <netinet/pim.h>
87 #include <netinet/tcp.h>
88 #include <netinet/tcp_timer.h>
89 #include <netinet/tcp_var.h>
90 #include <netinet/tcpip.h>
91 #include <netinet/udp.h>
92 #include <netinet/udp_var.h>
93 #include <netinet/sctp.h>
94 #include <netgraph/ng_ipfw.h>
96 #include <altq/if_altq.h>
98 #include <netinet/ip6.h>
99 #include <netinet/icmp6.h>
101 #include <netinet6/scope6_var.h>
104 #include <netinet/if_ether.h> /* XXX for ETHERTYPE_IP */
106 #include <machine/in_cksum.h> /* XXX for in_cksum */
108 #include <security/mac/mac_framework.h>
111 * set_disable contains one bit per set value (0..31).
112 * If the bit is set, all rules with the corresponding set
113 * are disabled. Set RESVD_SET(31) is reserved for the default rule
114 * and rules that are not deleted by the flush command,
115 * and CANNOT be disabled.
116 * Rules in set RESVD_SET can only be deleted explicitly.
118 static u_int32_t set_disable;
120 static int fw_verbose;
121 static int verbose_limit;
123 static struct callout ipfw_timeout;
124 static uma_zone_t ipfw_dyn_rule_zone;
125 #define IPFW_DEFAULT_RULE 65535
128 * Data structure to cache our ucred related
129 * information. This structure only gets used if
130 * the user specified UID/GID based constraints in
134 gid_t fw_groups[NGROUPS];
141 * list of rules for layer 3
143 struct ip_fw_chain layer3_chain;
145 MALLOC_DEFINE(M_IPFW, "IpFw/IpAcct", "IpFw/IpAcct chain's");
146 MALLOC_DEFINE(M_IPFW_TBL, "ipfw_tbl", "IpFw tables");
147 #define IPFW_NAT_LOADED (ipfw_nat_ptr != NULL)
148 ipfw_nat_t *ipfw_nat_ptr = NULL;
149 ipfw_nat_cfg_t *ipfw_nat_cfg_ptr;
150 ipfw_nat_cfg_t *ipfw_nat_del_ptr;
151 ipfw_nat_cfg_t *ipfw_nat_get_cfg_ptr;
152 ipfw_nat_cfg_t *ipfw_nat_get_log_ptr;
155 struct radix_node rn[2];
156 struct sockaddr_in addr, mask;
160 static int fw_debug = 1;
161 static int autoinc_step = 100; /* bounded to 1..1000 in add_rule() */
163 extern int ipfw_chg_hook(SYSCTL_HANDLER_ARGS);
166 SYSCTL_NODE(_net_inet_ip, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall");
167 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, enable,
168 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE3, &fw_enable, 0,
169 ipfw_chg_hook, "I", "Enable ipfw");
170 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, autoinc_step, CTLFLAG_RW,
171 &autoinc_step, 0, "Rule number autincrement step");
172 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, one_pass,
173 CTLFLAG_RW | CTLFLAG_SECURE3,
175 "Only do a single pass through ipfw when using dummynet(4)");
176 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, debug, CTLFLAG_RW,
177 &fw_debug, 0, "Enable printing of debug ip_fw statements");
178 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose,
179 CTLFLAG_RW | CTLFLAG_SECURE3,
180 &fw_verbose, 0, "Log matches to ipfw rules");
181 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose_limit, CTLFLAG_RW,
182 &verbose_limit, 0, "Set upper limit of matches of ipfw rules logged");
185 * Description of dynamic rules.
187 * Dynamic rules are stored in lists accessed through a hash table
188 * (ipfw_dyn_v) whose size is curr_dyn_buckets. This value can
189 * be modified through the sysctl variable dyn_buckets which is
190 * updated when the table becomes empty.
192 * XXX currently there is only one list, ipfw_dyn.
194 * When a packet is received, its address fields are first masked
195 * with the mask defined for the rule, then hashed, then matched
196 * against the entries in the corresponding list.
197 * Dynamic rules can be used for different purposes:
199 * + enforcing limits on the number of sessions;
200 * + in-kernel NAT (not implemented yet)
202 * The lifetime of dynamic rules is regulated by dyn_*_lifetime,
203 * measured in seconds and depending on the flags.
205 * The total number of dynamic rules is stored in dyn_count.
206 * The max number of dynamic rules is dyn_max. When we reach
207 * the maximum number of rules we do not create anymore. This is
208 * done to avoid consuming too much memory, but also too much
209 * time when searching on each packet (ideally, we should try instead
210 * to put a limit on the length of the list on each bucket...).
212 * Each dynamic rule holds a pointer to the parent ipfw rule so
213 * we know what action to perform. Dynamic rules are removed when
214 * the parent rule is deleted. XXX we should make them survive.
216 * There are some limitations with dynamic rules -- we do not
217 * obey the 'randomized match', and we do not do multiple
218 * passes through the firewall. XXX check the latter!!!
220 static ipfw_dyn_rule **ipfw_dyn_v = NULL;
221 static u_int32_t dyn_buckets = 256; /* must be power of 2 */
222 static u_int32_t curr_dyn_buckets = 256; /* must be power of 2 */
224 static struct mtx ipfw_dyn_mtx; /* mutex guarding dynamic rules */
225 #define IPFW_DYN_LOCK_INIT() \
226 mtx_init(&ipfw_dyn_mtx, "IPFW dynamic rules", NULL, MTX_DEF)
227 #define IPFW_DYN_LOCK_DESTROY() mtx_destroy(&ipfw_dyn_mtx)
228 #define IPFW_DYN_LOCK() mtx_lock(&ipfw_dyn_mtx)
229 #define IPFW_DYN_UNLOCK() mtx_unlock(&ipfw_dyn_mtx)
230 #define IPFW_DYN_LOCK_ASSERT() mtx_assert(&ipfw_dyn_mtx, MA_OWNED)
233 * Timeouts for various events in handing dynamic rules.
235 static u_int32_t dyn_ack_lifetime = 300;
236 static u_int32_t dyn_syn_lifetime = 20;
237 static u_int32_t dyn_fin_lifetime = 1;
238 static u_int32_t dyn_rst_lifetime = 1;
239 static u_int32_t dyn_udp_lifetime = 10;
240 static u_int32_t dyn_short_lifetime = 5;
243 * Keepalives are sent if dyn_keepalive is set. They are sent every
244 * dyn_keepalive_period seconds, in the last dyn_keepalive_interval
245 * seconds of lifetime of a rule.
246 * dyn_rst_lifetime and dyn_fin_lifetime should be strictly lower
247 * than dyn_keepalive_period.
250 static u_int32_t dyn_keepalive_interval = 20;
251 static u_int32_t dyn_keepalive_period = 5;
252 static u_int32_t dyn_keepalive = 1; /* do send keepalives */
254 static u_int32_t static_count; /* # of static rules */
255 static u_int32_t static_len; /* size in bytes of static rules */
256 static u_int32_t dyn_count; /* # of dynamic rules */
257 static u_int32_t dyn_max = 4096; /* max # of dynamic rules */
259 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_buckets, CTLFLAG_RW,
260 &dyn_buckets, 0, "Number of dyn. buckets");
261 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, curr_dyn_buckets, CTLFLAG_RD,
262 &curr_dyn_buckets, 0, "Current Number of dyn. buckets");
263 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_count, CTLFLAG_RD,
264 &dyn_count, 0, "Number of dyn. rules");
265 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_max, CTLFLAG_RW,
266 &dyn_max, 0, "Max number of dyn. rules");
267 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, static_count, CTLFLAG_RD,
268 &static_count, 0, "Number of static rules");
269 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_ack_lifetime, CTLFLAG_RW,
270 &dyn_ack_lifetime, 0, "Lifetime of dyn. rules for acks");
271 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_syn_lifetime, CTLFLAG_RW,
272 &dyn_syn_lifetime, 0, "Lifetime of dyn. rules for syn");
273 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_fin_lifetime, CTLFLAG_RW,
274 &dyn_fin_lifetime, 0, "Lifetime of dyn. rules for fin");
275 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_rst_lifetime, CTLFLAG_RW,
276 &dyn_rst_lifetime, 0, "Lifetime of dyn. rules for rst");
277 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_udp_lifetime, CTLFLAG_RW,
278 &dyn_udp_lifetime, 0, "Lifetime of dyn. rules for UDP");
279 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_short_lifetime, CTLFLAG_RW,
280 &dyn_short_lifetime, 0, "Lifetime of dyn. rules for other situations");
281 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_keepalive, CTLFLAG_RW,
282 &dyn_keepalive, 0, "Enable keepalives for dyn. rules");
286 * IPv6 specific variables
288 SYSCTL_DECL(_net_inet6_ip6);
290 static struct sysctl_ctx_list ip6_fw_sysctl_ctx;
291 static struct sysctl_oid *ip6_fw_sysctl_tree;
293 #endif /* SYSCTL_NODE */
295 static int fw_deny_unknown_exthdrs = 1;
299 * L3HDR maps an ipv4 pointer into a layer3 header pointer of type T
300 * Other macros just cast void * into the appropriate type
302 #define L3HDR(T, ip) ((T *)((u_int32_t *)(ip) + (ip)->ip_hl))
303 #define TCP(p) ((struct tcphdr *)(p))
304 #define SCTP(p) ((struct sctphdr *)(p))
305 #define UDP(p) ((struct udphdr *)(p))
306 #define ICMP(p) ((struct icmphdr *)(p))
307 #define ICMP6(p) ((struct icmp6_hdr *)(p))
310 icmptype_match(struct icmphdr *icmp, ipfw_insn_u32 *cmd)
312 int type = icmp->icmp_type;
314 return (type <= ICMP_MAXTYPE && (cmd->d[0] & (1<<type)) );
317 #define TT ( (1 << ICMP_ECHO) | (1 << ICMP_ROUTERSOLICIT) | \
318 (1 << ICMP_TSTAMP) | (1 << ICMP_IREQ) | (1 << ICMP_MASKREQ) )
321 is_icmp_query(struct icmphdr *icmp)
323 int type = icmp->icmp_type;
325 return (type <= ICMP_MAXTYPE && (TT & (1<<type)) );
330 * The following checks use two arrays of 8 or 16 bits to store the
331 * bits that we want set or clear, respectively. They are in the
332 * low and high half of cmd->arg1 or cmd->d[0].
334 * We scan options and store the bits we find set. We succeed if
336 * (want_set & ~bits) == 0 && (want_clear & ~bits) == want_clear
338 * The code is sometimes optimized not to store additional variables.
342 flags_match(ipfw_insn *cmd, u_int8_t bits)
347 if ( ((cmd->arg1 & 0xff) & bits) != 0)
348 return 0; /* some bits we want set were clear */
349 want_clear = (cmd->arg1 >> 8) & 0xff;
350 if ( (want_clear & bits) != want_clear)
351 return 0; /* some bits we want clear were set */
356 ipopts_match(struct ip *ip, ipfw_insn *cmd)
358 int optlen, bits = 0;
359 u_char *cp = (u_char *)(ip + 1);
360 int x = (ip->ip_hl << 2) - sizeof (struct ip);
362 for (; x > 0; x -= optlen, cp += optlen) {
363 int opt = cp[IPOPT_OPTVAL];
365 if (opt == IPOPT_EOL)
367 if (opt == IPOPT_NOP)
370 optlen = cp[IPOPT_OLEN];
371 if (optlen <= 0 || optlen > x)
372 return 0; /* invalid or truncated */
380 bits |= IP_FW_IPOPT_LSRR;
384 bits |= IP_FW_IPOPT_SSRR;
388 bits |= IP_FW_IPOPT_RR;
392 bits |= IP_FW_IPOPT_TS;
396 return (flags_match(cmd, bits));
400 tcpopts_match(struct tcphdr *tcp, ipfw_insn *cmd)
402 int optlen, bits = 0;
403 u_char *cp = (u_char *)(tcp + 1);
404 int x = (tcp->th_off << 2) - sizeof(struct tcphdr);
406 for (; x > 0; x -= optlen, cp += optlen) {
408 if (opt == TCPOPT_EOL)
410 if (opt == TCPOPT_NOP)
424 bits |= IP_FW_TCPOPT_MSS;
428 bits |= IP_FW_TCPOPT_WINDOW;
431 case TCPOPT_SACK_PERMITTED:
433 bits |= IP_FW_TCPOPT_SACK;
436 case TCPOPT_TIMESTAMP:
437 bits |= IP_FW_TCPOPT_TS;
442 return (flags_match(cmd, bits));
446 iface_match(struct ifnet *ifp, ipfw_insn_if *cmd)
448 if (ifp == NULL) /* no iface with this packet, match fails */
450 /* Check by name or by IP address */
451 if (cmd->name[0] != '\0') { /* match by name */
454 if (fnmatch(cmd->name, ifp->if_xname, 0) == 0)
457 if (strncmp(ifp->if_xname, cmd->name, IFNAMSIZ) == 0)
464 TAILQ_FOREACH(ia, &ifp->if_addrhead, ifa_link) {
465 if (ia->ifa_addr->sa_family != AF_INET)
467 if (cmd->p.ip.s_addr == ((struct sockaddr_in *)
468 (ia->ifa_addr))->sin_addr.s_addr)
469 return(1); /* match */
472 return(0); /* no match, fail ... */
476 * The verify_path function checks if a route to the src exists and
477 * if it is reachable via ifp (when provided).
479 * The 'verrevpath' option checks that the interface that an IP packet
480 * arrives on is the same interface that traffic destined for the
481 * packet's source address would be routed out of. The 'versrcreach'
482 * option just checks that the source address is reachable via any route
483 * (except default) in the routing table. These two are a measure to block
484 * forged packets. This is also commonly known as "anti-spoofing" or Unicast
485 * Reverse Path Forwarding (Unicast RFP) in Cisco-ese. The name of the knobs
486 * is purposely reminiscent of the Cisco IOS command,
488 * ip verify unicast reverse-path
489 * ip verify unicast source reachable-via any
491 * which implements the same functionality. But note that syntax is
492 * misleading. The check may be performed on all IP packets whether unicast,
493 * multicast, or broadcast.
496 verify_path(struct in_addr src, struct ifnet *ifp, u_int fib)
499 struct sockaddr_in *dst;
501 bzero(&ro, sizeof(ro));
503 dst = (struct sockaddr_in *)&(ro.ro_dst);
504 dst->sin_family = AF_INET;
505 dst->sin_len = sizeof(*dst);
507 in_rtalloc_ign(&ro, RTF_CLONING, fib);
509 if (ro.ro_rt == NULL)
513 * If ifp is provided, check for equality with rtentry.
514 * We should use rt->rt_ifa->ifa_ifp, instead of rt->rt_ifp,
515 * in order to pass packets injected back by if_simloop():
516 * if useloopback == 1 routing entry (via lo0) for our own address
517 * may exist, so we need to handle routing assymetry.
519 if (ifp != NULL && ro.ro_rt->rt_ifa->ifa_ifp != ifp) {
524 /* if no ifp provided, check if rtentry is not default route */
526 satosin(rt_key(ro.ro_rt))->sin_addr.s_addr == INADDR_ANY) {
531 /* or if this is a blackhole/reject route */
532 if (ifp == NULL && ro.ro_rt->rt_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
537 /* found valid route */
544 * ipv6 specific rules here...
547 icmp6type_match (int type, ipfw_insn_u32 *cmd)
549 return (type <= ICMP6_MAXTYPE && (cmd->d[type/32] & (1<<(type%32)) ) );
553 flow6id_match( int curr_flow, ipfw_insn_u32 *cmd )
556 for (i=0; i <= cmd->o.arg1; ++i )
557 if (curr_flow == cmd->d[i] )
562 /* support for IP6_*_ME opcodes */
564 search_ip6_addr_net (struct in6_addr * ip6_addr)
568 struct in6_ifaddr *fdm;
569 struct in6_addr copia;
571 TAILQ_FOREACH(mdc, &V_ifnet, if_link)
572 TAILQ_FOREACH(mdc2, &mdc->if_addrlist, ifa_list) {
573 if (mdc2->ifa_addr->sa_family == AF_INET6) {
574 fdm = (struct in6_ifaddr *)mdc2;
575 copia = fdm->ia_addr.sin6_addr;
576 /* need for leaving scope_id in the sock_addr */
577 in6_clearscope(&copia);
578 if (IN6_ARE_ADDR_EQUAL(ip6_addr, &copia))
586 verify_path6(struct in6_addr *src, struct ifnet *ifp)
589 struct sockaddr_in6 *dst;
591 bzero(&ro, sizeof(ro));
593 dst = (struct sockaddr_in6 * )&(ro.ro_dst);
594 dst->sin6_family = AF_INET6;
595 dst->sin6_len = sizeof(*dst);
596 dst->sin6_addr = *src;
597 /* XXX MRT 0 for ipv6 at this time */
598 rtalloc_ign((struct route *)&ro, RTF_CLONING);
600 if (ro.ro_rt == NULL)
604 * if ifp is provided, check for equality with rtentry
605 * We should use rt->rt_ifa->ifa_ifp, instead of rt->rt_ifp,
606 * to support the case of sending packets to an address of our own.
607 * (where the former interface is the first argument of if_simloop()
608 * (=ifp), the latter is lo0)
610 if (ifp != NULL && ro.ro_rt->rt_ifa->ifa_ifp != ifp) {
615 /* if no ifp provided, check if rtentry is not default route */
617 IN6_IS_ADDR_UNSPECIFIED(&satosin6(rt_key(ro.ro_rt))->sin6_addr)) {
622 /* or if this is a blackhole/reject route */
623 if (ifp == NULL && ro.ro_rt->rt_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
628 /* found valid route */
634 hash_packet6(struct ipfw_flow_id *id)
637 i = (id->dst_ip6.__u6_addr.__u6_addr32[2]) ^
638 (id->dst_ip6.__u6_addr.__u6_addr32[3]) ^
639 (id->src_ip6.__u6_addr.__u6_addr32[2]) ^
640 (id->src_ip6.__u6_addr.__u6_addr32[3]) ^
641 (id->dst_port) ^ (id->src_port);
646 is_icmp6_query(int icmp6_type)
648 if ((icmp6_type <= ICMP6_MAXTYPE) &&
649 (icmp6_type == ICMP6_ECHO_REQUEST ||
650 icmp6_type == ICMP6_MEMBERSHIP_QUERY ||
651 icmp6_type == ICMP6_WRUREQUEST ||
652 icmp6_type == ICMP6_FQDN_QUERY ||
653 icmp6_type == ICMP6_NI_QUERY))
660 send_reject6(struct ip_fw_args *args, int code, u_int hlen, struct ip6_hdr *ip6)
665 if (code == ICMP6_UNREACH_RST && args->f_id.proto == IPPROTO_TCP) {
673 tcp = (struct tcphdr *)((char *)ip6 + hlen);
675 if ((tcp->th_flags & TH_RST) != 0) {
683 ti.th.th_seq = ntohl(ti.th.th_seq);
684 ti.th.th_ack = ntohl(ti.th.th_ack);
685 ti.ip6.ip6_nxt = IPPROTO_TCP;
687 if (ti.th.th_flags & TH_ACK) {
693 if ((m->m_flags & M_PKTHDR) != 0) {
695 * total new data to ACK is:
696 * total packet length,
697 * minus the header length,
698 * minus the tcp header length.
700 ack += m->m_pkthdr.len - hlen
701 - (ti.th.th_off << 2);
702 } else if (ip6->ip6_plen) {
703 ack += ntohs(ip6->ip6_plen) + sizeof(*ip6) -
704 hlen - (ti.th.th_off << 2);
709 if (tcp->th_flags & TH_SYN)
712 flags = TH_RST|TH_ACK;
714 bcopy(&ti, ip6, sizeof(ti));
716 * m is only used to recycle the mbuf
717 * The data in it is never read so we don't need
718 * to correct the offsets or anything
720 tcp_respond(NULL, ip6, tcp, m, ack, seq, flags);
721 } else if (code != ICMP6_UNREACH_RST) { /* Send an ICMPv6 unreach. */
724 * Unlike above, the mbufs need to line up with the ip6 hdr,
725 * as the contents are read. We need to m_adj() the
727 * The mbuf will however be thrown away so we can adjust it.
728 * Remember we did an m_pullup on it already so we
729 * can make some assumptions about contiguousness.
732 m_adj(m, args->L3offset);
734 icmp6_error(m, ICMP6_DST_UNREACH, code, 0);
743 static u_int64_t norule_counter; /* counter for ipfw_log(NULL...) */
745 #define SNPARGS(buf, len) buf + len, sizeof(buf) > len ? sizeof(buf) - len : 0
746 #define SNP(buf) buf, sizeof(buf)
749 * We enter here when we have a rule with O_LOG.
750 * XXX this function alone takes about 2Kbytes of code!
753 ipfw_log(struct ip_fw *f, u_int hlen, struct ip_fw_args *args,
754 struct mbuf *m, struct ifnet *oif, u_short offset, uint32_t tablearg,
757 struct ether_header *eh = args->eh;
759 int limit_reached = 0;
760 char action2[40], proto[128], fragment[32];
765 if (f == NULL) { /* bogus pkt */
766 if (V_verbose_limit != 0 && V_norule_counter >= V_verbose_limit)
769 if (V_norule_counter == V_verbose_limit)
770 limit_reached = V_verbose_limit;
772 } else { /* O_LOG is the first action, find the real one */
773 ipfw_insn *cmd = ACTION_PTR(f);
774 ipfw_insn_log *l = (ipfw_insn_log *)cmd;
776 if (l->max_log != 0 && l->log_left == 0)
779 if (l->log_left == 0)
780 limit_reached = l->max_log;
781 cmd += F_LEN(cmd); /* point to first action */
782 if (cmd->opcode == O_ALTQ) {
783 ipfw_insn_altq *altq = (ipfw_insn_altq *)cmd;
785 snprintf(SNPARGS(action2, 0), "Altq %d",
789 if (cmd->opcode == O_PROB)
792 if (cmd->opcode == O_TAG)
796 switch (cmd->opcode) {
802 if (cmd->arg1==ICMP_REJECT_RST)
804 else if (cmd->arg1==ICMP_UNREACH_HOST)
807 snprintf(SNPARGS(action2, 0), "Unreach %d",
812 if (cmd->arg1==ICMP6_UNREACH_RST)
815 snprintf(SNPARGS(action2, 0), "Unreach %d",
826 snprintf(SNPARGS(action2, 0), "Divert %d",
830 snprintf(SNPARGS(action2, 0), "Tee %d",
834 snprintf(SNPARGS(action2, 0), "SetFib %d",
838 snprintf(SNPARGS(action2, 0), "SkipTo %d",
842 snprintf(SNPARGS(action2, 0), "Pipe %d",
846 snprintf(SNPARGS(action2, 0), "Queue %d",
850 ipfw_insn_sa *sa = (ipfw_insn_sa *)cmd;
852 struct in_addr dummyaddr;
853 if (sa->sa.sin_addr.s_addr == INADDR_ANY)
854 dummyaddr.s_addr = htonl(tablearg);
856 dummyaddr.s_addr = sa->sa.sin_addr.s_addr;
858 len = snprintf(SNPARGS(action2, 0), "Forward to %s",
859 inet_ntoa(dummyaddr));
862 snprintf(SNPARGS(action2, len), ":%d",
867 snprintf(SNPARGS(action2, 0), "Netgraph %d",
871 snprintf(SNPARGS(action2, 0), "Ngtee %d",
883 if (hlen == 0) { /* non-ip */
884 snprintf(SNPARGS(proto, 0), "MAC");
888 char src[48], dst[48];
889 struct icmphdr *icmp;
893 struct ip6_hdr *ip6 = NULL;
894 struct icmp6_hdr *icmp6;
899 if (IS_IP6_FLOW_ID(&(args->f_id))) {
900 char ip6buf[INET6_ADDRSTRLEN];
901 snprintf(src, sizeof(src), "[%s]",
902 ip6_sprintf(ip6buf, &args->f_id.src_ip6));
903 snprintf(dst, sizeof(dst), "[%s]",
904 ip6_sprintf(ip6buf, &args->f_id.dst_ip6));
906 ip6 = (struct ip6_hdr *)ip;
907 tcp = (struct tcphdr *)(((char *)ip) + hlen);
908 udp = (struct udphdr *)(((char *)ip) + hlen);
912 tcp = L3HDR(struct tcphdr, ip);
913 udp = L3HDR(struct udphdr, ip);
915 inet_ntoa_r(ip->ip_src, src);
916 inet_ntoa_r(ip->ip_dst, dst);
919 switch (args->f_id.proto) {
921 len = snprintf(SNPARGS(proto, 0), "TCP %s", src);
923 snprintf(SNPARGS(proto, len), ":%d %s:%d",
924 ntohs(tcp->th_sport),
926 ntohs(tcp->th_dport));
928 snprintf(SNPARGS(proto, len), " %s", dst);
932 len = snprintf(SNPARGS(proto, 0), "UDP %s", src);
934 snprintf(SNPARGS(proto, len), ":%d %s:%d",
935 ntohs(udp->uh_sport),
937 ntohs(udp->uh_dport));
939 snprintf(SNPARGS(proto, len), " %s", dst);
943 icmp = L3HDR(struct icmphdr, ip);
945 len = snprintf(SNPARGS(proto, 0),
947 icmp->icmp_type, icmp->icmp_code);
949 len = snprintf(SNPARGS(proto, 0), "ICMP ");
950 len += snprintf(SNPARGS(proto, len), "%s", src);
951 snprintf(SNPARGS(proto, len), " %s", dst);
955 icmp6 = (struct icmp6_hdr *)(((char *)ip) + hlen);
957 len = snprintf(SNPARGS(proto, 0),
959 icmp6->icmp6_type, icmp6->icmp6_code);
961 len = snprintf(SNPARGS(proto, 0), "ICMPv6 ");
962 len += snprintf(SNPARGS(proto, len), "%s", src);
963 snprintf(SNPARGS(proto, len), " %s", dst);
967 len = snprintf(SNPARGS(proto, 0), "P:%d %s",
968 args->f_id.proto, src);
969 snprintf(SNPARGS(proto, len), " %s", dst);
974 if (IS_IP6_FLOW_ID(&(args->f_id))) {
975 if (offset & (IP6F_OFF_MASK | IP6F_MORE_FRAG))
976 snprintf(SNPARGS(fragment, 0),
977 " (frag %08x:%d@%d%s)",
979 ntohs(ip6->ip6_plen) - hlen,
980 ntohs(offset & IP6F_OFF_MASK) << 3,
981 (offset & IP6F_MORE_FRAG) ? "+" : "");
986 if (eh != NULL) { /* layer 2 packets are as on the wire */
987 ip_off = ntohs(ip->ip_off);
988 ip_len = ntohs(ip->ip_len);
993 if (ip_off & (IP_MF | IP_OFFMASK))
994 snprintf(SNPARGS(fragment, 0),
995 " (frag %d:%d@%d%s)",
996 ntohs(ip->ip_id), ip_len - (ip->ip_hl << 2),
998 (ip_off & IP_MF) ? "+" : "");
1001 if (oif || m->m_pkthdr.rcvif)
1002 log(LOG_SECURITY | LOG_INFO,
1003 "ipfw: %d %s %s %s via %s%s\n",
1004 f ? f->rulenum : -1,
1005 action, proto, oif ? "out" : "in",
1006 oif ? oif->if_xname : m->m_pkthdr.rcvif->if_xname,
1009 log(LOG_SECURITY | LOG_INFO,
1010 "ipfw: %d %s %s [no if info]%s\n",
1011 f ? f->rulenum : -1,
1012 action, proto, fragment);
1014 log(LOG_SECURITY | LOG_NOTICE,
1015 "ipfw: limit %d reached on entry %d\n",
1016 limit_reached, f ? f->rulenum : -1);
1020 * IMPORTANT: the hash function for dynamic rules must be commutative
1021 * in source and destination (ip,port), because rules are bidirectional
1022 * and we want to find both in the same bucket.
1025 hash_packet(struct ipfw_flow_id *id)
1030 if (IS_IP6_FLOW_ID(id))
1031 i = hash_packet6(id);
1034 i = (id->dst_ip) ^ (id->src_ip) ^ (id->dst_port) ^ (id->src_port);
1035 i &= (V_curr_dyn_buckets - 1);
1040 * unlink a dynamic rule from a chain. prev is a pointer to
1041 * the previous one, q is a pointer to the rule to delete,
1042 * head is a pointer to the head of the queue.
1043 * Modifies q and potentially also head.
1045 #define UNLINK_DYN_RULE(prev, head, q) { \
1046 ipfw_dyn_rule *old_q = q; \
1048 /* remove a refcount to the parent */ \
1049 if (q->dyn_type == O_LIMIT) \
1050 q->parent->count--; \
1051 DEB(printf("ipfw: unlink entry 0x%08x %d -> 0x%08x %d, %d left\n",\
1052 (q->id.src_ip), (q->id.src_port), \
1053 (q->id.dst_ip), (q->id.dst_port), V_dyn_count-1 ); ) \
1055 prev->next = q = q->next; \
1057 head = q = q->next; \
1059 uma_zfree(ipfw_dyn_rule_zone, old_q); }
1061 #define TIME_LEQ(a,b) ((int)((a)-(b)) <= 0)
1064 * Remove dynamic rules pointing to "rule", or all of them if rule == NULL.
1066 * If keep_me == NULL, rules are deleted even if not expired,
1067 * otherwise only expired rules are removed.
1069 * The value of the second parameter is also used to point to identify
1070 * a rule we absolutely do not want to remove (e.g. because we are
1071 * holding a reference to it -- this is the case with O_LIMIT_PARENT
1072 * rules). The pointer is only used for comparison, so any non-null
1076 remove_dyn_rule(struct ip_fw *rule, ipfw_dyn_rule *keep_me)
1078 static u_int32_t last_remove = 0;
1080 #define FORCE (keep_me == NULL)
1082 ipfw_dyn_rule *prev, *q;
1083 int i, pass = 0, max_pass = 0;
1085 IPFW_DYN_LOCK_ASSERT();
1087 if (V_ipfw_dyn_v == NULL || V_dyn_count == 0)
1089 /* do not expire more than once per second, it is useless */
1090 if (!FORCE && last_remove == time_uptime)
1092 last_remove = time_uptime;
1095 * because O_LIMIT refer to parent rules, during the first pass only
1096 * remove child and mark any pending LIMIT_PARENT, and remove
1097 * them in a second pass.
1100 for (i = 0 ; i < V_curr_dyn_buckets ; i++) {
1101 for (prev=NULL, q = V_ipfw_dyn_v[i] ; q ; ) {
1103 * Logic can become complex here, so we split tests.
1107 if (rule != NULL && rule != q->rule)
1108 goto next; /* not the one we are looking for */
1109 if (q->dyn_type == O_LIMIT_PARENT) {
1111 * handle parent in the second pass,
1112 * record we need one.
1117 if (FORCE && q->count != 0 ) {
1118 /* XXX should not happen! */
1119 printf("ipfw: OUCH! cannot remove rule,"
1120 " count %d\n", q->count);
1124 !TIME_LEQ( q->expire, time_uptime ))
1127 if (q->dyn_type != O_LIMIT_PARENT || !q->count) {
1128 UNLINK_DYN_RULE(prev, V_ipfw_dyn_v[i], q);
1136 if (pass++ < max_pass)
1142 * lookup a dynamic rule.
1144 static ipfw_dyn_rule *
1145 lookup_dyn_rule_locked(struct ipfw_flow_id *pkt, int *match_direction,
1149 * stateful ipfw extensions.
1150 * Lookup into dynamic session queue
1152 #define MATCH_REVERSE 0
1153 #define MATCH_FORWARD 1
1154 #define MATCH_NONE 2
1155 #define MATCH_UNKNOWN 3
1156 int i, dir = MATCH_NONE;
1157 ipfw_dyn_rule *prev, *q=NULL;
1159 IPFW_DYN_LOCK_ASSERT();
1161 if (V_ipfw_dyn_v == NULL)
1162 goto done; /* not found */
1163 i = hash_packet( pkt );
1164 for (prev=NULL, q = V_ipfw_dyn_v[i] ; q != NULL ; ) {
1165 if (q->dyn_type == O_LIMIT_PARENT && q->count)
1167 if (TIME_LEQ( q->expire, time_uptime)) { /* expire entry */
1168 UNLINK_DYN_RULE(prev, V_ipfw_dyn_v[i], q);
1171 if (pkt->proto == q->id.proto &&
1172 q->dyn_type != O_LIMIT_PARENT) {
1173 if (IS_IP6_FLOW_ID(pkt)) {
1174 if (IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
1175 &(q->id.src_ip6)) &&
1176 IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
1177 &(q->id.dst_ip6)) &&
1178 pkt->src_port == q->id.src_port &&
1179 pkt->dst_port == q->id.dst_port ) {
1180 dir = MATCH_FORWARD;
1183 if (IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
1184 &(q->id.dst_ip6)) &&
1185 IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
1186 &(q->id.src_ip6)) &&
1187 pkt->src_port == q->id.dst_port &&
1188 pkt->dst_port == q->id.src_port ) {
1189 dir = MATCH_REVERSE;
1193 if (pkt->src_ip == q->id.src_ip &&
1194 pkt->dst_ip == q->id.dst_ip &&
1195 pkt->src_port == q->id.src_port &&
1196 pkt->dst_port == q->id.dst_port ) {
1197 dir = MATCH_FORWARD;
1200 if (pkt->src_ip == q->id.dst_ip &&
1201 pkt->dst_ip == q->id.src_ip &&
1202 pkt->src_port == q->id.dst_port &&
1203 pkt->dst_port == q->id.src_port ) {
1204 dir = MATCH_REVERSE;
1214 goto done; /* q = NULL, not found */
1216 if ( prev != NULL) { /* found and not in front */
1217 prev->next = q->next;
1218 q->next = V_ipfw_dyn_v[i];
1219 V_ipfw_dyn_v[i] = q;
1221 if (pkt->proto == IPPROTO_TCP) { /* update state according to flags */
1222 u_char flags = pkt->flags & (TH_FIN|TH_SYN|TH_RST);
1224 #define BOTH_SYN (TH_SYN | (TH_SYN << 8))
1225 #define BOTH_FIN (TH_FIN | (TH_FIN << 8))
1226 q->state |= (dir == MATCH_FORWARD ) ? flags : (flags << 8);
1228 case TH_SYN: /* opening */
1229 q->expire = time_uptime + V_dyn_syn_lifetime;
1232 case BOTH_SYN: /* move to established */
1233 case BOTH_SYN | TH_FIN : /* one side tries to close */
1234 case BOTH_SYN | (TH_FIN << 8) :
1236 #define _SEQ_GE(a,b) ((int)(a) - (int)(b) >= 0)
1237 u_int32_t ack = ntohl(tcp->th_ack);
1238 if (dir == MATCH_FORWARD) {
1239 if (q->ack_fwd == 0 || _SEQ_GE(ack, q->ack_fwd))
1241 else { /* ignore out-of-sequence */
1245 if (q->ack_rev == 0 || _SEQ_GE(ack, q->ack_rev))
1247 else { /* ignore out-of-sequence */
1252 q->expire = time_uptime + V_dyn_ack_lifetime;
1255 case BOTH_SYN | BOTH_FIN: /* both sides closed */
1256 if (V_dyn_fin_lifetime >= V_dyn_keepalive_period)
1257 V_dyn_fin_lifetime = V_dyn_keepalive_period - 1;
1258 q->expire = time_uptime + V_dyn_fin_lifetime;
1264 * reset or some invalid combination, but can also
1265 * occur if we use keep-state the wrong way.
1267 if ( (q->state & ((TH_RST << 8)|TH_RST)) == 0)
1268 printf("invalid state: 0x%x\n", q->state);
1270 if (V_dyn_rst_lifetime >= V_dyn_keepalive_period)
1271 V_dyn_rst_lifetime = V_dyn_keepalive_period - 1;
1272 q->expire = time_uptime + V_dyn_rst_lifetime;
1275 } else if (pkt->proto == IPPROTO_UDP) {
1276 q->expire = time_uptime + V_dyn_udp_lifetime;
1278 /* other protocols */
1279 q->expire = time_uptime + V_dyn_short_lifetime;
1282 if (match_direction)
1283 *match_direction = dir;
1287 static ipfw_dyn_rule *
1288 lookup_dyn_rule(struct ipfw_flow_id *pkt, int *match_direction,
1294 q = lookup_dyn_rule_locked(pkt, match_direction, tcp);
1297 /* NB: return table locked when q is not NULL */
1302 realloc_dynamic_table(void)
1304 IPFW_DYN_LOCK_ASSERT();
1307 * Try reallocation, make sure we have a power of 2 and do
1308 * not allow more than 64k entries. In case of overflow,
1312 if (V_dyn_buckets > 65536)
1313 V_dyn_buckets = 1024;
1314 if ((V_dyn_buckets & (V_dyn_buckets-1)) != 0) { /* not a power of 2 */
1315 V_dyn_buckets = V_curr_dyn_buckets; /* reset */
1318 V_curr_dyn_buckets = V_dyn_buckets;
1319 if (V_ipfw_dyn_v != NULL)
1320 free(V_ipfw_dyn_v, M_IPFW);
1322 V_ipfw_dyn_v = malloc(V_curr_dyn_buckets * sizeof(ipfw_dyn_rule *),
1323 M_IPFW, M_NOWAIT | M_ZERO);
1324 if (V_ipfw_dyn_v != NULL || V_curr_dyn_buckets <= 2)
1326 V_curr_dyn_buckets /= 2;
1331 * Install state of type 'type' for a dynamic session.
1332 * The hash table contains two type of rules:
1333 * - regular rules (O_KEEP_STATE)
1334 * - rules for sessions with limited number of sess per user
1335 * (O_LIMIT). When they are created, the parent is
1336 * increased by 1, and decreased on delete. In this case,
1337 * the third parameter is the parent rule and not the chain.
1338 * - "parent" rules for the above (O_LIMIT_PARENT).
1340 static ipfw_dyn_rule *
1341 add_dyn_rule(struct ipfw_flow_id *id, u_int8_t dyn_type, struct ip_fw *rule)
1346 IPFW_DYN_LOCK_ASSERT();
1348 if (V_ipfw_dyn_v == NULL ||
1349 (V_dyn_count == 0 && V_dyn_buckets != V_curr_dyn_buckets)) {
1350 realloc_dynamic_table();
1351 if (V_ipfw_dyn_v == NULL)
1352 return NULL; /* failed ! */
1354 i = hash_packet(id);
1356 r = uma_zalloc(ipfw_dyn_rule_zone, M_NOWAIT | M_ZERO);
1358 printf ("ipfw: sorry cannot allocate state\n");
1362 /* increase refcount on parent, and set pointer */
1363 if (dyn_type == O_LIMIT) {
1364 ipfw_dyn_rule *parent = (ipfw_dyn_rule *)rule;
1365 if ( parent->dyn_type != O_LIMIT_PARENT)
1366 panic("invalid parent");
1369 rule = parent->rule;
1373 r->expire = time_uptime + V_dyn_syn_lifetime;
1375 r->dyn_type = dyn_type;
1376 r->pcnt = r->bcnt = 0;
1380 r->next = V_ipfw_dyn_v[i];
1381 V_ipfw_dyn_v[i] = r;
1383 DEB(printf("ipfw: add dyn entry ty %d 0x%08x %d -> 0x%08x %d, total %d\n",
1385 (r->id.src_ip), (r->id.src_port),
1386 (r->id.dst_ip), (r->id.dst_port),
1392 * lookup dynamic parent rule using pkt and rule as search keys.
1393 * If the lookup fails, then install one.
1395 static ipfw_dyn_rule *
1396 lookup_dyn_parent(struct ipfw_flow_id *pkt, struct ip_fw *rule)
1401 IPFW_DYN_LOCK_ASSERT();
1404 int is_v6 = IS_IP6_FLOW_ID(pkt);
1405 i = hash_packet( pkt );
1406 for (q = V_ipfw_dyn_v[i] ; q != NULL ; q=q->next)
1407 if (q->dyn_type == O_LIMIT_PARENT &&
1409 pkt->proto == q->id.proto &&
1410 pkt->src_port == q->id.src_port &&
1411 pkt->dst_port == q->id.dst_port &&
1414 IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
1415 &(q->id.src_ip6)) &&
1416 IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
1417 &(q->id.dst_ip6))) ||
1419 pkt->src_ip == q->id.src_ip &&
1420 pkt->dst_ip == q->id.dst_ip)
1423 q->expire = time_uptime + V_dyn_short_lifetime;
1424 DEB(printf("ipfw: lookup_dyn_parent found 0x%p\n",q);)
1428 return add_dyn_rule(pkt, O_LIMIT_PARENT, rule);
1432 * Install dynamic state for rule type cmd->o.opcode
1434 * Returns 1 (failure) if state is not installed because of errors or because
1435 * session limitations are enforced.
1438 install_state(struct ip_fw *rule, ipfw_insn_limit *cmd,
1439 struct ip_fw_args *args, uint32_t tablearg)
1441 static int last_log;
1444 char src[48], dst[48];
1450 printf("ipfw: %s: type %d 0x%08x %u -> 0x%08x %u\n",
1451 __func__, cmd->o.opcode,
1452 (args->f_id.src_ip), (args->f_id.src_port),
1453 (args->f_id.dst_ip), (args->f_id.dst_port));
1458 q = lookup_dyn_rule_locked(&args->f_id, NULL, NULL);
1460 if (q != NULL) { /* should never occur */
1461 if (last_log != time_uptime) {
1462 last_log = time_uptime;
1463 printf("ipfw: %s: entry already present, done\n",
1470 if (V_dyn_count >= V_dyn_max)
1471 /* Run out of slots, try to remove any expired rule. */
1472 remove_dyn_rule(NULL, (ipfw_dyn_rule *)1);
1474 if (V_dyn_count >= V_dyn_max) {
1475 if (last_log != time_uptime) {
1476 last_log = time_uptime;
1477 printf("ipfw: %s: Too many dynamic rules\n", __func__);
1480 return (1); /* cannot install, notify caller */
1483 switch (cmd->o.opcode) {
1484 case O_KEEP_STATE: /* bidir rule */
1485 add_dyn_rule(&args->f_id, O_KEEP_STATE, rule);
1488 case O_LIMIT: { /* limit number of sessions */
1489 struct ipfw_flow_id id;
1490 ipfw_dyn_rule *parent;
1491 uint32_t conn_limit;
1492 uint16_t limit_mask = cmd->limit_mask;
1494 conn_limit = (cmd->conn_limit == IP_FW_TABLEARG) ?
1495 tablearg : cmd->conn_limit;
1498 if (cmd->conn_limit == IP_FW_TABLEARG)
1499 printf("ipfw: %s: O_LIMIT rule, conn_limit: %u "
1500 "(tablearg)\n", __func__, conn_limit);
1502 printf("ipfw: %s: O_LIMIT rule, conn_limit: %u\n",
1503 __func__, conn_limit);
1506 id.dst_ip = id.src_ip = id.dst_port = id.src_port = 0;
1507 id.proto = args->f_id.proto;
1508 id.addr_type = args->f_id.addr_type;
1509 id.fib = M_GETFIB(args->m);
1511 if (IS_IP6_FLOW_ID (&(args->f_id))) {
1512 if (limit_mask & DYN_SRC_ADDR)
1513 id.src_ip6 = args->f_id.src_ip6;
1514 if (limit_mask & DYN_DST_ADDR)
1515 id.dst_ip6 = args->f_id.dst_ip6;
1517 if (limit_mask & DYN_SRC_ADDR)
1518 id.src_ip = args->f_id.src_ip;
1519 if (limit_mask & DYN_DST_ADDR)
1520 id.dst_ip = args->f_id.dst_ip;
1522 if (limit_mask & DYN_SRC_PORT)
1523 id.src_port = args->f_id.src_port;
1524 if (limit_mask & DYN_DST_PORT)
1525 id.dst_port = args->f_id.dst_port;
1526 if ((parent = lookup_dyn_parent(&id, rule)) == NULL) {
1527 printf("ipfw: %s: add parent failed\n", __func__);
1532 if (parent->count >= conn_limit) {
1533 /* See if we can remove some expired rule. */
1534 remove_dyn_rule(rule, parent);
1535 if (parent->count >= conn_limit) {
1536 if (V_fw_verbose && last_log != time_uptime) {
1537 last_log = time_uptime;
1540 * XXX IPv6 flows are not
1543 if (IS_IP6_FLOW_ID(&(args->f_id))) {
1544 char ip6buf[INET6_ADDRSTRLEN];
1545 snprintf(src, sizeof(src),
1546 "[%s]", ip6_sprintf(ip6buf,
1547 &args->f_id.src_ip6));
1548 snprintf(dst, sizeof(dst),
1549 "[%s]", ip6_sprintf(ip6buf,
1550 &args->f_id.dst_ip6));
1555 htonl(args->f_id.src_ip);
1556 inet_ntoa_r(da, src);
1558 htonl(args->f_id.dst_ip);
1559 inet_ntoa_r(da, dst);
1561 log(LOG_SECURITY | LOG_DEBUG,
1562 "ipfw: %d %s %s:%u -> %s:%u, %s\n",
1563 parent->rule->rulenum,
1565 src, (args->f_id.src_port),
1566 dst, (args->f_id.dst_port),
1567 "too many entries");
1573 add_dyn_rule(&args->f_id, O_LIMIT, (struct ip_fw *)parent);
1577 printf("ipfw: %s: unknown dynamic rule type %u\n",
1578 __func__, cmd->o.opcode);
1583 /* XXX just set lifetime */
1584 lookup_dyn_rule_locked(&args->f_id, NULL, NULL);
1591 * Generate a TCP packet, containing either a RST or a keepalive.
1592 * When flags & TH_RST, we are sending a RST packet, because of a
1593 * "reset" action matched the packet.
1594 * Otherwise we are sending a keepalive, and flags & TH_
1595 * The 'replyto' mbuf is the mbuf being replied to, if any, and is required
1596 * so that MAC can label the reply appropriately.
1598 static struct mbuf *
1599 send_pkt(struct mbuf *replyto, struct ipfw_flow_id *id, u_int32_t seq,
1600 u_int32_t ack, int flags)
1606 MGETHDR(m, M_DONTWAIT, MT_DATA);
1609 m->m_pkthdr.rcvif = (struct ifnet *)0;
1611 M_SETFIB(m, id->fib);
1613 if (replyto != NULL)
1614 mac_netinet_firewall_reply(replyto, m);
1616 mac_netinet_firewall_send(m);
1618 (void)replyto; /* don't warn about unused arg */
1621 m->m_pkthdr.len = m->m_len = sizeof(struct ip) + sizeof(struct tcphdr);
1622 m->m_data += max_linkhdr;
1624 ip = mtod(m, struct ip *);
1625 bzero(ip, m->m_len);
1626 tcp = (struct tcphdr *)(ip + 1); /* no IP options */
1627 ip->ip_p = IPPROTO_TCP;
1630 * Assume we are sending a RST (or a keepalive in the reverse
1631 * direction), swap src and destination addresses and ports.
1633 ip->ip_src.s_addr = htonl(id->dst_ip);
1634 ip->ip_dst.s_addr = htonl(id->src_ip);
1635 tcp->th_sport = htons(id->dst_port);
1636 tcp->th_dport = htons(id->src_port);
1637 if (flags & TH_RST) { /* we are sending a RST */
1638 if (flags & TH_ACK) {
1639 tcp->th_seq = htonl(ack);
1640 tcp->th_ack = htonl(0);
1641 tcp->th_flags = TH_RST;
1645 tcp->th_seq = htonl(0);
1646 tcp->th_ack = htonl(seq);
1647 tcp->th_flags = TH_RST | TH_ACK;
1651 * We are sending a keepalive. flags & TH_SYN determines
1652 * the direction, forward if set, reverse if clear.
1653 * NOTE: seq and ack are always assumed to be correct
1654 * as set by the caller. This may be confusing...
1656 if (flags & TH_SYN) {
1658 * we have to rewrite the correct addresses!
1660 ip->ip_dst.s_addr = htonl(id->dst_ip);
1661 ip->ip_src.s_addr = htonl(id->src_ip);
1662 tcp->th_dport = htons(id->dst_port);
1663 tcp->th_sport = htons(id->src_port);
1665 tcp->th_seq = htonl(seq);
1666 tcp->th_ack = htonl(ack);
1667 tcp->th_flags = TH_ACK;
1670 * set ip_len to the payload size so we can compute
1671 * the tcp checksum on the pseudoheader
1672 * XXX check this, could save a couple of words ?
1674 ip->ip_len = htons(sizeof(struct tcphdr));
1675 tcp->th_sum = in_cksum(m, m->m_pkthdr.len);
1677 * now fill fields left out earlier
1679 ip->ip_ttl = V_ip_defttl;
1680 ip->ip_len = m->m_pkthdr.len;
1681 m->m_flags |= M_SKIP_FIREWALL;
1686 * sends a reject message, consuming the mbuf passed as an argument.
1689 send_reject(struct ip_fw_args *args, int code, int ip_len, struct ip *ip)
1693 /* XXX When ip is not guaranteed to be at mtod() we will
1694 * need to account for this */
1695 * The mbuf will however be thrown away so we can adjust it.
1696 * Remember we did an m_pullup on it already so we
1697 * can make some assumptions about contiguousness.
1700 m_adj(m, args->L3offset);
1702 if (code != ICMP_REJECT_RST) { /* Send an ICMP unreach */
1703 /* We need the IP header in host order for icmp_error(). */
1704 if (args->eh != NULL) {
1705 ip->ip_len = ntohs(ip->ip_len);
1706 ip->ip_off = ntohs(ip->ip_off);
1708 icmp_error(args->m, ICMP_UNREACH, code, 0L, 0);
1709 } else if (args->f_id.proto == IPPROTO_TCP) {
1710 struct tcphdr *const tcp =
1711 L3HDR(struct tcphdr, mtod(args->m, struct ip *));
1712 if ( (tcp->th_flags & TH_RST) == 0) {
1714 m = send_pkt(args->m, &(args->f_id),
1715 ntohl(tcp->th_seq), ntohl(tcp->th_ack),
1716 tcp->th_flags | TH_RST);
1718 ip_output(m, NULL, NULL, 0, NULL, NULL);
1728 * Given an ip_fw *, lookup_next_rule will return a pointer
1729 * to the next rule, which can be either the jump
1730 * target (for skipto instructions) or the next one in the list (in
1731 * all other cases including a missing jump target).
1732 * The result is also written in the "next_rule" field of the rule.
1733 * Backward jumps are not allowed, so start looking from the next
1736 * This never returns NULL -- in case we do not have an exact match,
1737 * the next rule is returned. When the ruleset is changed,
1738 * pointers are flushed so we are always correct.
1741 static struct ip_fw *
1742 lookup_next_rule(struct ip_fw *me, u_int32_t tablearg)
1744 struct ip_fw *rule = NULL;
1748 /* look for action, in case it is a skipto */
1749 cmd = ACTION_PTR(me);
1750 if (cmd->opcode == O_LOG)
1752 if (cmd->opcode == O_ALTQ)
1754 if (cmd->opcode == O_TAG)
1756 if (cmd->opcode == O_SKIPTO ) {
1757 if (tablearg != 0) {
1758 rulenum = (u_int16_t)tablearg;
1760 rulenum = cmd->arg1;
1762 for (rule = me->next; rule ; rule = rule->next) {
1763 if (rule->rulenum >= rulenum) {
1768 if (rule == NULL) /* failure or not a skipto */
1770 me->next_rule = rule;
1775 add_table_entry(struct ip_fw_chain *ch, uint16_t tbl, in_addr_t addr,
1776 uint8_t mlen, uint32_t value)
1778 struct radix_node_head *rnh;
1779 struct table_entry *ent;
1781 if (tbl >= IPFW_TABLES_MAX)
1783 rnh = ch->tables[tbl];
1784 ent = malloc(sizeof(*ent), M_IPFW_TBL, M_NOWAIT | M_ZERO);
1788 ent->addr.sin_len = ent->mask.sin_len = 8;
1789 ent->mask.sin_addr.s_addr = htonl(mlen ? ~((1 << (32 - mlen)) - 1) : 0);
1790 ent->addr.sin_addr.s_addr = addr & ent->mask.sin_addr.s_addr;
1791 IPFW_WLOCK(&V_layer3_chain);
1792 if (rnh->rnh_addaddr(&ent->addr, &ent->mask, rnh, (void *)ent) ==
1794 IPFW_WUNLOCK(&V_layer3_chain);
1795 free(ent, M_IPFW_TBL);
1798 IPFW_WUNLOCK(&V_layer3_chain);
1803 del_table_entry(struct ip_fw_chain *ch, uint16_t tbl, in_addr_t addr,
1806 struct radix_node_head *rnh;
1807 struct table_entry *ent;
1808 struct sockaddr_in sa, mask;
1810 if (tbl >= IPFW_TABLES_MAX)
1812 rnh = ch->tables[tbl];
1813 sa.sin_len = mask.sin_len = 8;
1814 mask.sin_addr.s_addr = htonl(mlen ? ~((1 << (32 - mlen)) - 1) : 0);
1815 sa.sin_addr.s_addr = addr & mask.sin_addr.s_addr;
1817 ent = (struct table_entry *)rnh->rnh_deladdr(&sa, &mask, rnh);
1823 free(ent, M_IPFW_TBL);
1828 flush_table_entry(struct radix_node *rn, void *arg)
1830 struct radix_node_head * const rnh = arg;
1831 struct table_entry *ent;
1833 ent = (struct table_entry *)
1834 rnh->rnh_deladdr(rn->rn_key, rn->rn_mask, rnh);
1836 free(ent, M_IPFW_TBL);
1841 flush_table(struct ip_fw_chain *ch, uint16_t tbl)
1843 struct radix_node_head *rnh;
1845 IPFW_WLOCK_ASSERT(ch);
1847 if (tbl >= IPFW_TABLES_MAX)
1849 rnh = ch->tables[tbl];
1850 KASSERT(rnh != NULL, ("NULL IPFW table"));
1851 rnh->rnh_walktree(rnh, flush_table_entry, rnh);
1856 flush_tables(struct ip_fw_chain *ch)
1860 IPFW_WLOCK_ASSERT(ch);
1862 for (tbl = 0; tbl < IPFW_TABLES_MAX; tbl++)
1863 flush_table(ch, tbl);
1867 init_tables(struct ip_fw_chain *ch)
1872 for (i = 0; i < IPFW_TABLES_MAX; i++) {
1873 if (!rn_inithead((void **)&ch->tables[i], 32)) {
1874 for (j = 0; j < i; j++) {
1875 (void) flush_table(ch, j);
1884 lookup_table(struct ip_fw_chain *ch, uint16_t tbl, in_addr_t addr,
1887 struct radix_node_head *rnh;
1888 struct table_entry *ent;
1889 struct sockaddr_in sa;
1891 if (tbl >= IPFW_TABLES_MAX)
1893 rnh = ch->tables[tbl];
1895 sa.sin_addr.s_addr = addr;
1896 ent = (struct table_entry *)(rnh->rnh_lookup(&sa, NULL, rnh));
1905 count_table_entry(struct radix_node *rn, void *arg)
1907 u_int32_t * const cnt = arg;
1914 count_table(struct ip_fw_chain *ch, uint32_t tbl, uint32_t *cnt)
1916 struct radix_node_head *rnh;
1918 if (tbl >= IPFW_TABLES_MAX)
1920 rnh = ch->tables[tbl];
1922 rnh->rnh_walktree(rnh, count_table_entry, cnt);
1927 dump_table_entry(struct radix_node *rn, void *arg)
1929 struct table_entry * const n = (struct table_entry *)rn;
1930 ipfw_table * const tbl = arg;
1931 ipfw_table_entry *ent;
1933 if (tbl->cnt == tbl->size)
1935 ent = &tbl->ent[tbl->cnt];
1936 ent->tbl = tbl->tbl;
1937 if (in_nullhost(n->mask.sin_addr))
1940 ent->masklen = 33 - ffs(ntohl(n->mask.sin_addr.s_addr));
1941 ent->addr = n->addr.sin_addr.s_addr;
1942 ent->value = n->value;
1948 dump_table(struct ip_fw_chain *ch, ipfw_table *tbl)
1950 struct radix_node_head *rnh;
1952 if (tbl->tbl >= IPFW_TABLES_MAX)
1954 rnh = ch->tables[tbl->tbl];
1956 rnh->rnh_walktree(rnh, dump_table_entry, tbl);
1961 fill_ugid_cache(struct inpcb *inp, struct ip_fw_ugid *ugp)
1965 if (inp->inp_socket != NULL) {
1966 cr = inp->inp_socket->so_cred;
1967 ugp->fw_prid = jailed(cr) ?
1968 cr->cr_prison->pr_id : -1;
1969 ugp->fw_uid = cr->cr_uid;
1970 ugp->fw_ngroups = cr->cr_ngroups;
1971 bcopy(cr->cr_groups, ugp->fw_groups,
1972 sizeof(ugp->fw_groups));
1977 check_uidgid(ipfw_insn_u32 *insn, int proto, struct ifnet *oif,
1978 struct in_addr dst_ip, u_int16_t dst_port, struct in_addr src_ip,
1979 u_int16_t src_port, struct ip_fw_ugid *ugp, int *lookup,
1982 struct inpcbinfo *pi;
1989 * Check to see if the UDP or TCP stack supplied us with
1990 * the PCB. If so, rather then holding a lock and looking
1991 * up the PCB, we can use the one that was supplied.
1993 if (inp && *lookup == 0) {
1994 INP_LOCK_ASSERT(inp);
1995 if (inp->inp_socket != NULL) {
1996 fill_ugid_cache(inp, ugp);
2001 * If we have already been here and the packet has no
2002 * PCB entry associated with it, then we can safely
2003 * assume that this is a no match.
2007 if (proto == IPPROTO_TCP) {
2010 } else if (proto == IPPROTO_UDP) {
2011 wildcard = INPLOOKUP_WILDCARD;
2019 in_pcblookup_hash(pi,
2020 dst_ip, htons(dst_port),
2021 src_ip, htons(src_port),
2023 in_pcblookup_hash(pi,
2024 src_ip, htons(src_port),
2025 dst_ip, htons(dst_port),
2029 if (pcb->inp_socket != NULL) {
2030 fill_ugid_cache(pcb, ugp);
2035 INP_INFO_RUNLOCK(pi);
2038 * If the lookup did not yield any results, there
2039 * is no sense in coming back and trying again. So
2040 * we can set lookup to -1 and ensure that we wont
2041 * bother the pcb system again.
2047 if (insn->o.opcode == O_UID)
2048 match = (ugp->fw_uid == (uid_t)insn->d[0]);
2049 else if (insn->o.opcode == O_GID) {
2050 for (gp = ugp->fw_groups;
2051 gp < &ugp->fw_groups[ugp->fw_ngroups]; gp++)
2052 if (*gp == (gid_t)insn->d[0]) {
2056 } else if (insn->o.opcode == O_JAIL)
2057 match = (ugp->fw_prid == (int)insn->d[0]);
2062 * The main check routine for the firewall.
2064 * All arguments are in args so we can modify them and return them
2065 * back to the caller.
2069 * args->m (in/out) The packet; we set to NULL when/if we nuke it.
2070 * Starts with the IP header.
2071 * args->eh (in) Mac header if present, or NULL for layer3 packet.
2072 * args->L3offset Number of bytes bypassed if we came from L2.
2073 * e.g. often sizeof(eh) ** NOTYET **
2074 * args->oif Outgoing interface, or NULL if packet is incoming.
2075 * The incoming interface is in the mbuf. (in)
2076 * args->divert_rule (in/out)
2077 * Skip up to the first rule past this rule number;
2078 * upon return, non-zero port number for divert or tee.
2080 * args->rule Pointer to the last matching rule (in/out)
2081 * args->next_hop Socket we are forwarding to (out).
2082 * args->f_id Addresses grabbed from the packet (out)
2083 * args->cookie a cookie depending on rule action
2087 * IP_FW_PASS the packet must be accepted
2088 * IP_FW_DENY the packet must be dropped
2089 * IP_FW_DIVERT divert packet, port in m_tag
2090 * IP_FW_TEE tee packet, port in m_tag
2091 * IP_FW_DUMMYNET to dummynet, pipe in args->cookie
2092 * IP_FW_NETGRAPH into netgraph, cookie args->cookie
2096 ipfw_chk(struct ip_fw_args *args)
2099 * Local variables holding state during the processing of a packet:
2101 * IMPORTANT NOTE: to speed up the processing of rules, there
2102 * are some assumption on the values of the variables, which
2103 * are documented here. Should you change them, please check
2104 * the implementation of the various instructions to make sure
2105 * that they still work.
2107 * args->eh The MAC header. It is non-null for a layer2
2108 * packet, it is NULL for a layer-3 packet.
2110 * args->L3offset Offset in the packet to the L3 (IP or equiv.) header.
2112 * m | args->m Pointer to the mbuf, as received from the caller.
2113 * It may change if ipfw_chk() does an m_pullup, or if it
2114 * consumes the packet because it calls send_reject().
2115 * XXX This has to change, so that ipfw_chk() never modifies
2116 * or consumes the buffer.
2117 * ip is the beginning of the ip(4 or 6) header.
2118 * Calculated by adding the L3offset to the start of data.
2119 * (Until we start using L3offset, the packet is
2120 * supposed to start with the ip header).
2122 struct mbuf *m = args->m;
2123 struct ip *ip = mtod(m, struct ip *);
2126 * For rules which contain uid/gid or jail constraints, cache
2127 * a copy of the users credentials after the pcb lookup has been
2128 * executed. This will speed up the processing of rules with
2129 * these types of constraints, as well as decrease contention
2130 * on pcb related locks.
2132 struct ip_fw_ugid fw_ugid_cache;
2133 int ugid_lookup = 0;
2136 * divinput_flags If non-zero, set to the IP_FW_DIVERT_*_FLAG
2137 * associated with a packet input on a divert socket. This
2138 * will allow to distinguish traffic and its direction when
2139 * it originates from a divert socket.
2141 u_int divinput_flags = 0;
2144 * oif | args->oif If NULL, ipfw_chk has been called on the
2145 * inbound path (ether_input, ip_input).
2146 * If non-NULL, ipfw_chk has been called on the outbound path
2147 * (ether_output, ip_output).
2149 struct ifnet *oif = args->oif;
2151 struct ip_fw *f = NULL; /* matching rule */
2155 * hlen The length of the IP header.
2157 u_int hlen = 0; /* hlen >0 means we have an IP pkt */
2160 * offset The offset of a fragment. offset != 0 means that
2161 * we have a fragment at this offset of an IPv4 packet.
2162 * offset == 0 means that (if this is an IPv4 packet)
2163 * this is the first or only fragment.
2164 * For IPv6 offset == 0 means there is no Fragment Header.
2165 * If offset != 0 for IPv6 always use correct mask to
2166 * get the correct offset because we add IP6F_MORE_FRAG
2167 * to be able to dectect the first fragment which would
2168 * otherwise have offset = 0.
2173 * Local copies of addresses. They are only valid if we have
2176 * proto The protocol. Set to 0 for non-ip packets,
2177 * or to the protocol read from the packet otherwise.
2178 * proto != 0 means that we have an IPv4 packet.
2180 * src_port, dst_port port numbers, in HOST format. Only
2181 * valid for TCP and UDP packets.
2183 * src_ip, dst_ip ip addresses, in NETWORK format.
2184 * Only valid for IPv4 packets.
2187 u_int16_t src_port = 0, dst_port = 0; /* NOTE: host format */
2188 struct in_addr src_ip, dst_ip; /* NOTE: network format */
2191 u_int16_t etype = 0; /* Host order stored ether type */
2194 * dyn_dir = MATCH_UNKNOWN when rules unchecked,
2195 * MATCH_NONE when checked and not matched (q = NULL),
2196 * MATCH_FORWARD or MATCH_REVERSE otherwise (q != NULL)
2198 int dyn_dir = MATCH_UNKNOWN;
2199 ipfw_dyn_rule *q = NULL;
2200 struct ip_fw_chain *chain = &V_layer3_chain;
2204 * We store in ulp a pointer to the upper layer protocol header.
2205 * In the ipv4 case this is easy to determine from the header,
2206 * but for ipv6 we might have some additional headers in the middle.
2207 * ulp is NULL if not found.
2209 void *ulp = NULL; /* upper layer protocol pointer. */
2210 /* XXX ipv6 variables */
2212 u_int16_t ext_hd = 0; /* bits vector for extension header filtering */
2213 /* end of ipv6 variables */
2216 if (m->m_flags & M_SKIP_FIREWALL)
2217 return (IP_FW_PASS); /* accept */
2219 pktlen = m->m_pkthdr.len;
2220 args->f_id.fib = M_GETFIB(m); /* note mbuf not altered) */
2221 proto = args->f_id.proto = 0; /* mark f_id invalid */
2222 /* XXX 0 is a valid proto: IP/IPv6 Hop-by-Hop Option */
2225 * PULLUP_TO(len, p, T) makes sure that len + sizeof(T) is contiguous,
2226 * then it sets p to point at the offset "len" in the mbuf. WARNING: the
2227 * pointer might become stale after other pullups (but we never use it
2230 #define PULLUP_TO(len, p, T) \
2232 int x = (len) + sizeof(T); \
2233 if ((m)->m_len < x) { \
2234 args->m = m = m_pullup(m, x); \
2236 goto pullup_failed; \
2238 p = (mtod(m, char *) + (len)); \
2242 * if we have an ether header,
2245 etype = ntohs(args->eh->ether_type);
2247 /* Identify IP packets and fill up variables. */
2248 if (pktlen >= sizeof(struct ip6_hdr) &&
2249 (args->eh == NULL || etype == ETHERTYPE_IPV6) && ip->ip_v == 6) {
2250 struct ip6_hdr *ip6 = (struct ip6_hdr *)ip;
2252 args->f_id.addr_type = 6;
2253 hlen = sizeof(struct ip6_hdr);
2254 proto = ip6->ip6_nxt;
2256 /* Search extension headers to find upper layer protocols */
2257 while (ulp == NULL) {
2259 case IPPROTO_ICMPV6:
2260 PULLUP_TO(hlen, ulp, struct icmp6_hdr);
2261 args->f_id.flags = ICMP6(ulp)->icmp6_type;
2265 PULLUP_TO(hlen, ulp, struct tcphdr);
2266 dst_port = TCP(ulp)->th_dport;
2267 src_port = TCP(ulp)->th_sport;
2268 args->f_id.flags = TCP(ulp)->th_flags;
2272 PULLUP_TO(hlen, ulp, struct sctphdr);
2273 src_port = SCTP(ulp)->src_port;
2274 dst_port = SCTP(ulp)->dest_port;
2278 PULLUP_TO(hlen, ulp, struct udphdr);
2279 dst_port = UDP(ulp)->uh_dport;
2280 src_port = UDP(ulp)->uh_sport;
2283 case IPPROTO_HOPOPTS: /* RFC 2460 */
2284 PULLUP_TO(hlen, ulp, struct ip6_hbh);
2285 ext_hd |= EXT_HOPOPTS;
2286 hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3;
2287 proto = ((struct ip6_hbh *)ulp)->ip6h_nxt;
2291 case IPPROTO_ROUTING: /* RFC 2460 */
2292 PULLUP_TO(hlen, ulp, struct ip6_rthdr);
2293 switch (((struct ip6_rthdr *)ulp)->ip6r_type) {
2295 ext_hd |= EXT_RTHDR0;
2298 ext_hd |= EXT_RTHDR2;
2301 printf("IPFW2: IPV6 - Unknown Routing "
2302 "Header type(%d)\n",
2303 ((struct ip6_rthdr *)ulp)->ip6r_type);
2304 if (V_fw_deny_unknown_exthdrs)
2305 return (IP_FW_DENY);
2308 ext_hd |= EXT_ROUTING;
2309 hlen += (((struct ip6_rthdr *)ulp)->ip6r_len + 1) << 3;
2310 proto = ((struct ip6_rthdr *)ulp)->ip6r_nxt;
2314 case IPPROTO_FRAGMENT: /* RFC 2460 */
2315 PULLUP_TO(hlen, ulp, struct ip6_frag);
2316 ext_hd |= EXT_FRAGMENT;
2317 hlen += sizeof (struct ip6_frag);
2318 proto = ((struct ip6_frag *)ulp)->ip6f_nxt;
2319 offset = ((struct ip6_frag *)ulp)->ip6f_offlg &
2321 /* Add IP6F_MORE_FRAG for offset of first
2322 * fragment to be != 0. */
2323 offset |= ((struct ip6_frag *)ulp)->ip6f_offlg &
2326 printf("IPFW2: IPV6 - Invalid Fragment "
2328 if (V_fw_deny_unknown_exthdrs)
2329 return (IP_FW_DENY);
2332 args->f_id.frag_id6 =
2333 ntohl(((struct ip6_frag *)ulp)->ip6f_ident);
2337 case IPPROTO_DSTOPTS: /* RFC 2460 */
2338 PULLUP_TO(hlen, ulp, struct ip6_hbh);
2339 ext_hd |= EXT_DSTOPTS;
2340 hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3;
2341 proto = ((struct ip6_hbh *)ulp)->ip6h_nxt;
2345 case IPPROTO_AH: /* RFC 2402 */
2346 PULLUP_TO(hlen, ulp, struct ip6_ext);
2348 hlen += (((struct ip6_ext *)ulp)->ip6e_len + 2) << 2;
2349 proto = ((struct ip6_ext *)ulp)->ip6e_nxt;
2353 case IPPROTO_ESP: /* RFC 2406 */
2354 PULLUP_TO(hlen, ulp, uint32_t); /* SPI, Seq# */
2355 /* Anything past Seq# is variable length and
2356 * data past this ext. header is encrypted. */
2360 case IPPROTO_NONE: /* RFC 2460 */
2362 * Packet ends here, and IPv6 header has
2363 * already been pulled up. If ip6e_len!=0
2364 * then octets must be ignored.
2366 ulp = ip; /* non-NULL to get out of loop. */
2369 case IPPROTO_OSPFIGP:
2370 /* XXX OSPF header check? */
2371 PULLUP_TO(hlen, ulp, struct ip6_ext);
2375 /* XXX PIM header check? */
2376 PULLUP_TO(hlen, ulp, struct pim);
2380 PULLUP_TO(hlen, ulp, struct carp_header);
2381 if (((struct carp_header *)ulp)->carp_version !=
2383 return (IP_FW_DENY);
2384 if (((struct carp_header *)ulp)->carp_type !=
2386 return (IP_FW_DENY);
2389 case IPPROTO_IPV6: /* RFC 2893 */
2390 PULLUP_TO(hlen, ulp, struct ip6_hdr);
2393 case IPPROTO_IPV4: /* RFC 2893 */
2394 PULLUP_TO(hlen, ulp, struct ip);
2398 printf("IPFW2: IPV6 - Unknown Extension "
2399 "Header(%d), ext_hd=%x\n", proto, ext_hd);
2400 if (V_fw_deny_unknown_exthdrs)
2401 return (IP_FW_DENY);
2402 PULLUP_TO(hlen, ulp, struct ip6_ext);
2406 ip = mtod(m, struct ip *);
2407 ip6 = (struct ip6_hdr *)ip;
2408 args->f_id.src_ip6 = ip6->ip6_src;
2409 args->f_id.dst_ip6 = ip6->ip6_dst;
2410 args->f_id.src_ip = 0;
2411 args->f_id.dst_ip = 0;
2412 args->f_id.flow_id6 = ntohl(ip6->ip6_flow);
2413 } else if (pktlen >= sizeof(struct ip) &&
2414 (args->eh == NULL || etype == ETHERTYPE_IP) && ip->ip_v == 4) {
2416 hlen = ip->ip_hl << 2;
2417 args->f_id.addr_type = 4;
2420 * Collect parameters into local variables for faster matching.
2423 src_ip = ip->ip_src;
2424 dst_ip = ip->ip_dst;
2425 if (args->eh != NULL) { /* layer 2 packets are as on the wire */
2426 offset = ntohs(ip->ip_off) & IP_OFFMASK;
2427 ip_len = ntohs(ip->ip_len);
2429 offset = ip->ip_off & IP_OFFMASK;
2430 ip_len = ip->ip_len;
2432 pktlen = ip_len < pktlen ? ip_len : pktlen;
2437 PULLUP_TO(hlen, ulp, struct tcphdr);
2438 dst_port = TCP(ulp)->th_dport;
2439 src_port = TCP(ulp)->th_sport;
2440 args->f_id.flags = TCP(ulp)->th_flags;
2444 PULLUP_TO(hlen, ulp, struct udphdr);
2445 dst_port = UDP(ulp)->uh_dport;
2446 src_port = UDP(ulp)->uh_sport;
2450 PULLUP_TO(hlen, ulp, struct icmphdr);
2451 args->f_id.flags = ICMP(ulp)->icmp_type;
2459 ip = mtod(m, struct ip *);
2460 args->f_id.src_ip = ntohl(src_ip.s_addr);
2461 args->f_id.dst_ip = ntohl(dst_ip.s_addr);
2464 if (proto) { /* we may have port numbers, store them */
2465 args->f_id.proto = proto;
2466 args->f_id.src_port = src_port = ntohs(src_port);
2467 args->f_id.dst_port = dst_port = ntohs(dst_port);
2471 mtag = m_tag_find(m, PACKET_TAG_DIVERT, NULL);
2474 * Packet has already been tagged. Look for the next rule
2475 * to restart processing.
2477 * If fw_one_pass != 0 then just accept it.
2478 * XXX should not happen here, but optimized out in
2481 if (V_fw_one_pass) {
2482 IPFW_RUNLOCK(chain);
2483 return (IP_FW_PASS);
2486 f = args->rule->next_rule;
2488 f = lookup_next_rule(args->rule, 0);
2491 * Find the starting rule. It can be either the first
2492 * one, or the one after divert_rule if asked so.
2494 int skipto = mtag ? divert_cookie(mtag) : 0;
2497 if (args->eh == NULL && skipto != 0) {
2498 if (skipto >= IPFW_DEFAULT_RULE) {
2499 IPFW_RUNLOCK(chain);
2500 return (IP_FW_DENY); /* invalid */
2502 while (f && f->rulenum <= skipto)
2504 if (f == NULL) { /* drop packet */
2505 IPFW_RUNLOCK(chain);
2506 return (IP_FW_DENY);
2510 /* reset divert rule to avoid confusion later */
2512 divinput_flags = divert_info(mtag) &
2513 (IP_FW_DIVERT_OUTPUT_FLAG | IP_FW_DIVERT_LOOPBACK_FLAG);
2514 m_tag_delete(m, mtag);
2518 * Now scan the rules, and parse microinstructions for each rule.
2520 for (; f; f = f->next) {
2522 uint32_t tablearg = 0;
2523 int l, cmdlen, skip_or; /* skip rest of OR block */
2526 if (V_set_disable & (1 << f->set) )
2530 for (l = f->cmd_len, cmd = f->cmd ; l > 0 ;
2531 l -= cmdlen, cmd += cmdlen) {
2535 * check_body is a jump target used when we find a
2536 * CHECK_STATE, and need to jump to the body of
2541 cmdlen = F_LEN(cmd);
2543 * An OR block (insn_1 || .. || insn_n) has the
2544 * F_OR bit set in all but the last instruction.
2545 * The first match will set "skip_or", and cause
2546 * the following instructions to be skipped until
2547 * past the one with the F_OR bit clear.
2549 if (skip_or) { /* skip this instruction */
2550 if ((cmd->len & F_OR) == 0)
2551 skip_or = 0; /* next one is good */
2554 match = 0; /* set to 1 if we succeed */
2556 switch (cmd->opcode) {
2558 * The first set of opcodes compares the packet's
2559 * fields with some pattern, setting 'match' if a
2560 * match is found. At the end of the loop there is
2561 * logic to deal with F_NOT and F_OR flags associated
2569 printf("ipfw: opcode %d unimplemented\n",
2577 * We only check offset == 0 && proto != 0,
2578 * as this ensures that we have a
2579 * packet with the ports info.
2583 if (is_ipv6) /* XXX to be fixed later */
2585 if (proto == IPPROTO_TCP ||
2586 proto == IPPROTO_UDP)
2587 match = check_uidgid(
2588 (ipfw_insn_u32 *)cmd,
2591 src_ip, src_port, &fw_ugid_cache,
2592 &ugid_lookup, args->inp);
2596 match = iface_match(m->m_pkthdr.rcvif,
2597 (ipfw_insn_if *)cmd);
2601 match = iface_match(oif, (ipfw_insn_if *)cmd);
2605 match = iface_match(oif ? oif :
2606 m->m_pkthdr.rcvif, (ipfw_insn_if *)cmd);
2610 if (args->eh != NULL) { /* have MAC header */
2611 u_int32_t *want = (u_int32_t *)
2612 ((ipfw_insn_mac *)cmd)->addr;
2613 u_int32_t *mask = (u_int32_t *)
2614 ((ipfw_insn_mac *)cmd)->mask;
2615 u_int32_t *hdr = (u_int32_t *)args->eh;
2618 ( want[0] == (hdr[0] & mask[0]) &&
2619 want[1] == (hdr[1] & mask[1]) &&
2620 want[2] == (hdr[2] & mask[2]) );
2625 if (args->eh != NULL) {
2627 ((ipfw_insn_u16 *)cmd)->ports;
2630 for (i = cmdlen - 1; !match && i>0;
2632 match = (etype >= p[0] &&
2638 match = (offset != 0);
2641 case O_IN: /* "out" is "not in" */
2642 match = (oif == NULL);
2646 match = (args->eh != NULL);
2650 match = (cmd->arg1 & 1 && divinput_flags &
2651 IP_FW_DIVERT_LOOPBACK_FLAG) ||
2652 (cmd->arg1 & 2 && divinput_flags &
2653 IP_FW_DIVERT_OUTPUT_FLAG);
2658 * We do not allow an arg of 0 so the
2659 * check of "proto" only suffices.
2661 match = (proto == cmd->arg1);
2666 (((ipfw_insn_ip *)cmd)->addr.s_addr ==
2670 case O_IP_SRC_LOOKUP:
2671 case O_IP_DST_LOOKUP:
2674 (cmd->opcode == O_IP_DST_LOOKUP) ?
2675 dst_ip.s_addr : src_ip.s_addr;
2678 match = lookup_table(chain, cmd->arg1, a,
2682 if (cmdlen == F_INSN_SIZE(ipfw_insn_u32))
2684 ((ipfw_insn_u32 *)cmd)->d[0] == v;
2694 (cmd->opcode == O_IP_DST_MASK) ?
2695 dst_ip.s_addr : src_ip.s_addr;
2696 uint32_t *p = ((ipfw_insn_u32 *)cmd)->d;
2699 for (; !match && i>0; i-= 2, p+= 2)
2700 match = (p[0] == (a & p[1]));
2708 INADDR_TO_IFP(src_ip, tif);
2709 match = (tif != NULL);
2716 u_int32_t *d = (u_int32_t *)(cmd+1);
2718 cmd->opcode == O_IP_DST_SET ?
2724 addr -= d[0]; /* subtract base */
2725 match = (addr < cmd->arg1) &&
2726 ( d[ 1 + (addr>>5)] &
2727 (1<<(addr & 0x1f)) );
2733 (((ipfw_insn_ip *)cmd)->addr.s_addr ==
2741 INADDR_TO_IFP(dst_ip, tif);
2742 match = (tif != NULL);
2749 * offset == 0 && proto != 0 is enough
2750 * to guarantee that we have a
2751 * packet with port info.
2753 if ((proto==IPPROTO_UDP || proto==IPPROTO_TCP)
2756 (cmd->opcode == O_IP_SRCPORT) ?
2757 src_port : dst_port ;
2759 ((ipfw_insn_u16 *)cmd)->ports;
2762 for (i = cmdlen - 1; !match && i>0;
2764 match = (x>=p[0] && x<=p[1]);
2769 match = (offset == 0 && proto==IPPROTO_ICMP &&
2770 icmptype_match(ICMP(ulp), (ipfw_insn_u32 *)cmd) );
2775 match = is_ipv6 && offset == 0 &&
2776 proto==IPPROTO_ICMPV6 &&
2778 ICMP6(ulp)->icmp6_type,
2779 (ipfw_insn_u32 *)cmd);
2785 ipopts_match(ip, cmd) );
2790 cmd->arg1 == ip->ip_v);
2796 if (is_ipv4) { /* only for IP packets */
2801 if (cmd->opcode == O_IPLEN)
2803 else if (cmd->opcode == O_IPTTL)
2805 else /* must be IPID */
2806 x = ntohs(ip->ip_id);
2808 match = (cmd->arg1 == x);
2811 /* otherwise we have ranges */
2812 p = ((ipfw_insn_u16 *)cmd)->ports;
2814 for (; !match && i>0; i--, p += 2)
2815 match = (x >= p[0] && x <= p[1]);
2819 case O_IPPRECEDENCE:
2821 (cmd->arg1 == (ip->ip_tos & 0xe0)) );
2826 flags_match(cmd, ip->ip_tos));
2830 if (proto == IPPROTO_TCP && offset == 0) {
2838 ((ip->ip_hl + tcp->th_off) << 2);
2840 match = (cmd->arg1 == x);
2843 /* otherwise we have ranges */
2844 p = ((ipfw_insn_u16 *)cmd)->ports;
2846 for (; !match && i>0; i--, p += 2)
2847 match = (x >= p[0] && x <= p[1]);
2852 match = (proto == IPPROTO_TCP && offset == 0 &&
2853 flags_match(cmd, TCP(ulp)->th_flags));
2857 match = (proto == IPPROTO_TCP && offset == 0 &&
2858 tcpopts_match(TCP(ulp), cmd));
2862 match = (proto == IPPROTO_TCP && offset == 0 &&
2863 ((ipfw_insn_u32 *)cmd)->d[0] ==
2868 match = (proto == IPPROTO_TCP && offset == 0 &&
2869 ((ipfw_insn_u32 *)cmd)->d[0] ==
2874 match = (proto == IPPROTO_TCP && offset == 0 &&
2875 cmd->arg1 == TCP(ulp)->th_win);
2879 /* reject packets which have SYN only */
2880 /* XXX should i also check for TH_ACK ? */
2881 match = (proto == IPPROTO_TCP && offset == 0 &&
2882 (TCP(ulp)->th_flags &
2883 (TH_RST | TH_ACK | TH_SYN)) != TH_SYN);
2888 ipfw_insn_altq *altq = (ipfw_insn_altq *)cmd;
2891 at = pf_find_mtag(m);
2892 if (at != NULL && at->qid != 0)
2894 at = pf_get_mtag(m);
2897 * Let the packet fall back to the
2902 at->qid = altq->qid;
2913 ipfw_log(f, hlen, args, m,
2914 oif, offset, tablearg, ip);
2919 match = (random()<((ipfw_insn_u32 *)cmd)->d[0]);
2923 /* Outgoing packets automatically pass/match */
2924 match = ((oif != NULL) ||
2925 (m->m_pkthdr.rcvif == NULL) ||
2929 verify_path6(&(args->f_id.src_ip6),
2930 m->m_pkthdr.rcvif) :
2932 verify_path(src_ip, m->m_pkthdr.rcvif,
2937 /* Outgoing packets automatically pass/match */
2938 match = (hlen > 0 && ((oif != NULL) ||
2941 verify_path6(&(args->f_id.src_ip6),
2944 verify_path(src_ip, NULL, args->f_id.fib)));
2948 /* Outgoing packets automatically pass/match */
2949 if (oif == NULL && hlen > 0 &&
2950 ( (is_ipv4 && in_localaddr(src_ip))
2953 in6_localaddr(&(args->f_id.src_ip6)))
2958 is_ipv6 ? verify_path6(
2959 &(args->f_id.src_ip6),
2960 m->m_pkthdr.rcvif) :
2971 match = (m_tag_find(m,
2972 PACKET_TAG_IPSEC_IN_DONE, NULL) != NULL);
2974 /* otherwise no match */
2980 IN6_ARE_ADDR_EQUAL(&args->f_id.src_ip6,
2981 &((ipfw_insn_ip6 *)cmd)->addr6);
2986 IN6_ARE_ADDR_EQUAL(&args->f_id.dst_ip6,
2987 &((ipfw_insn_ip6 *)cmd)->addr6);
2989 case O_IP6_SRC_MASK:
2990 case O_IP6_DST_MASK:
2994 struct in6_addr *d =
2995 &((ipfw_insn_ip6 *)cmd)->addr6;
2997 for (; !match && i > 0; d += 2,
2998 i -= F_INSN_SIZE(struct in6_addr)
3004 APPLY_MASK(&p, &d[1]);
3006 IN6_ARE_ADDR_EQUAL(&d[0],
3013 match= is_ipv6 && search_ip6_addr_net(&args->f_id.src_ip6);
3017 match= is_ipv6 && search_ip6_addr_net(&args->f_id.dst_ip6);
3022 flow6id_match(args->f_id.flow_id6,
3023 (ipfw_insn_u32 *) cmd);
3028 (ext_hd & ((ipfw_insn *) cmd)->arg1);
3041 uint32_t tag = (cmd->arg1 == IP_FW_TABLEARG) ?
3042 tablearg : cmd->arg1;
3044 /* Packet is already tagged with this tag? */
3045 mtag = m_tag_locate(m, MTAG_IPFW, tag, NULL);
3047 /* We have `untag' action when F_NOT flag is
3048 * present. And we must remove this mtag from
3049 * mbuf and reset `match' to zero (`match' will
3050 * be inversed later).
3051 * Otherwise we should allocate new mtag and
3052 * push it into mbuf.
3054 if (cmd->len & F_NOT) { /* `untag' action */
3056 m_tag_delete(m, mtag);
3057 } else if (mtag == NULL) {
3058 if ((mtag = m_tag_alloc(MTAG_IPFW,
3059 tag, 0, M_NOWAIT)) != NULL)
3060 m_tag_prepend(m, mtag);
3062 match = (cmd->len & F_NOT) ? 0: 1;
3066 case O_FIB: /* try match the specified fib */
3067 if (args->f_id.fib == cmd->arg1)
3072 uint32_t tag = (cmd->arg1 == IP_FW_TABLEARG) ?
3073 tablearg : cmd->arg1;
3076 match = m_tag_locate(m, MTAG_IPFW,
3081 /* we have ranges */
3082 for (mtag = m_tag_first(m);
3083 mtag != NULL && !match;
3084 mtag = m_tag_next(m, mtag)) {
3088 if (mtag->m_tag_cookie != MTAG_IPFW)
3091 p = ((ipfw_insn_u16 *)cmd)->ports;
3093 for(; !match && i > 0; i--, p += 2)
3095 mtag->m_tag_id >= p[0] &&
3096 mtag->m_tag_id <= p[1];
3102 * The second set of opcodes represents 'actions',
3103 * i.e. the terminal part of a rule once the packet
3104 * matches all previous patterns.
3105 * Typically there is only one action for each rule,
3106 * and the opcode is stored at the end of the rule
3107 * (but there are exceptions -- see below).
3109 * In general, here we set retval and terminate the
3110 * outer loop (would be a 'break 3' in some language,
3111 * but we need to do a 'goto done').
3114 * O_COUNT and O_SKIPTO actions:
3115 * instead of terminating, we jump to the next rule
3116 * ('goto next_rule', equivalent to a 'break 2'),
3117 * or to the SKIPTO target ('goto again' after
3118 * having set f, cmd and l), respectively.
3120 * O_TAG, O_LOG and O_ALTQ action parameters:
3121 * perform some action and set match = 1;
3123 * O_LIMIT and O_KEEP_STATE: these opcodes are
3124 * not real 'actions', and are stored right
3125 * before the 'action' part of the rule.
3126 * These opcodes try to install an entry in the
3127 * state tables; if successful, we continue with
3128 * the next opcode (match=1; break;), otherwise
3129 * the packet * must be dropped
3130 * ('goto done' after setting retval);
3132 * O_PROBE_STATE and O_CHECK_STATE: these opcodes
3133 * cause a lookup of the state table, and a jump
3134 * to the 'action' part of the parent rule
3135 * ('goto check_body') if an entry is found, or
3136 * (CHECK_STATE only) a jump to the next rule if
3137 * the entry is not found ('goto next_rule').
3138 * The result of the lookup is cached to make
3139 * further instances of these opcodes are
3144 if (install_state(f,
3145 (ipfw_insn_limit *)cmd, args, tablearg)) {
3146 retval = IP_FW_DENY;
3147 goto done; /* error/limit violation */
3155 * dynamic rules are checked at the first
3156 * keep-state or check-state occurrence,
3157 * with the result being stored in dyn_dir.
3158 * The compiler introduces a PROBE_STATE
3159 * instruction for us when we have a
3160 * KEEP_STATE (because PROBE_STATE needs
3163 if (dyn_dir == MATCH_UNKNOWN &&
3164 (q = lookup_dyn_rule(&args->f_id,
3165 &dyn_dir, proto == IPPROTO_TCP ?
3169 * Found dynamic entry, update stats
3170 * and jump to the 'action' part of
3176 cmd = ACTION_PTR(f);
3177 l = f->cmd_len - f->act_ofs;
3182 * Dynamic entry not found. If CHECK_STATE,
3183 * skip to next rule, if PROBE_STATE just
3184 * ignore and continue with next opcode.
3186 if (cmd->opcode == O_CHECK_STATE)
3192 retval = 0; /* accept */
3197 args->rule = f; /* report matching rule */
3198 if (cmd->arg1 == IP_FW_TABLEARG)
3199 args->cookie = tablearg;
3201 args->cookie = cmd->arg1;
3202 retval = IP_FW_DUMMYNET;
3207 struct divert_tag *dt;
3209 if (args->eh) /* not on layer 2 */
3211 mtag = m_tag_get(PACKET_TAG_DIVERT,
3212 sizeof(struct divert_tag),
3217 IPFW_RUNLOCK(chain);
3218 return (IP_FW_DENY);
3220 dt = (struct divert_tag *)(mtag+1);
3221 dt->cookie = f->rulenum;
3222 if (cmd->arg1 == IP_FW_TABLEARG)
3223 dt->info = tablearg;
3225 dt->info = cmd->arg1;
3226 m_tag_prepend(m, mtag);
3227 retval = (cmd->opcode == O_DIVERT) ?
3228 IP_FW_DIVERT : IP_FW_TEE;
3233 f->pcnt++; /* update stats */
3235 f->timestamp = time_uptime;
3236 if (cmd->opcode == O_COUNT)
3239 if (cmd->arg1 == IP_FW_TABLEARG) {
3240 f = lookup_next_rule(f, tablearg);
3242 if (f->next_rule == NULL)
3243 lookup_next_rule(f, 0);
3250 * Drop the packet and send a reject notice
3251 * if the packet is not ICMP (or is an ICMP
3252 * query), and it is not multicast/broadcast.
3254 if (hlen > 0 && is_ipv4 && offset == 0 &&
3255 (proto != IPPROTO_ICMP ||
3256 is_icmp_query(ICMP(ulp))) &&
3257 !(m->m_flags & (M_BCAST|M_MCAST)) &&
3258 !IN_MULTICAST(ntohl(dst_ip.s_addr))) {
3259 send_reject(args, cmd->arg1, ip_len, ip);
3265 if (hlen > 0 && is_ipv6 &&
3266 ((offset & IP6F_OFF_MASK) == 0) &&
3267 (proto != IPPROTO_ICMPV6 ||
3268 (is_icmp6_query(args->f_id.flags) == 1)) &&
3269 !(m->m_flags & (M_BCAST|M_MCAST)) &&
3270 !IN6_IS_ADDR_MULTICAST(&args->f_id.dst_ip6)) {
3272 args, cmd->arg1, hlen,
3273 (struct ip6_hdr *)ip);
3279 retval = IP_FW_DENY;
3282 case O_FORWARD_IP: {
3283 struct sockaddr_in *sa;
3284 sa = &(((ipfw_insn_sa *)cmd)->sa);
3285 if (args->eh) /* not valid on layer2 pkts */
3287 if (!q || dyn_dir == MATCH_FORWARD) {
3288 if (sa->sin_addr.s_addr == INADDR_ANY) {
3289 bcopy(sa, &args->hopstore,
3291 args->hopstore.sin_addr.s_addr =
3296 args->next_hop = sa;
3299 retval = IP_FW_PASS;
3305 args->rule = f; /* report matching rule */
3306 if (cmd->arg1 == IP_FW_TABLEARG)
3307 args->cookie = tablearg;
3309 args->cookie = cmd->arg1;
3310 retval = (cmd->opcode == O_NETGRAPH) ?
3311 IP_FW_NETGRAPH : IP_FW_NGTEE;
3315 f->pcnt++; /* update stats */
3317 f->timestamp = time_uptime;
3318 M_SETFIB(m, cmd->arg1);
3319 args->f_id.fib = cmd->arg1;
3326 if (IPFW_NAT_LOADED) {
3327 args->rule = f; /* Report matching rule. */
3328 t = ((ipfw_insn_nat *)cmd)->nat;
3330 nat_id = (cmd->arg1 == IP_FW_TABLEARG) ?
3331 tablearg : cmd->arg1;
3332 LOOKUP_NAT(V_layer3_chain, nat_id, t);
3334 retval = IP_FW_DENY;
3337 if (cmd->arg1 != IP_FW_TABLEARG)
3338 ((ipfw_insn_nat *)cmd)->nat = t;
3340 retval = ipfw_nat_ptr(args, t, m);
3342 retval = IP_FW_DENY;
3347 panic("-- unknown opcode %d\n", cmd->opcode);
3348 } /* end of switch() on opcodes */
3350 if (cmd->len & F_NOT)
3354 if (cmd->len & F_OR)
3357 if (!(cmd->len & F_OR)) /* not an OR block, */
3358 break; /* try next rule */
3361 } /* end of inner for, scan opcodes */
3363 next_rule:; /* try next rule */
3365 } /* end of outer for, scan rules */
3366 printf("ipfw: ouch!, skip past end of rules, denying packet\n");
3367 IPFW_RUNLOCK(chain);
3368 return (IP_FW_DENY);
3371 /* Update statistics */
3374 f->timestamp = time_uptime;
3375 IPFW_RUNLOCK(chain);
3380 printf("ipfw: pullup failed\n");
3381 return (IP_FW_DENY);
3385 * When a rule is added/deleted, clear the next_rule pointers in all rules.
3386 * These will be reconstructed on the fly as packets are matched.
3389 flush_rule_ptrs(struct ip_fw_chain *chain)
3393 IPFW_WLOCK_ASSERT(chain);
3395 for (rule = chain->rules; rule; rule = rule->next)
3396 rule->next_rule = NULL;
3400 * Add a new rule to the list. Copy the rule into a malloc'ed area, then
3401 * possibly create a rule number and add the rule to the list.
3402 * Update the rule_number in the input struct so the caller knows it as well.
3405 add_rule(struct ip_fw_chain *chain, struct ip_fw *input_rule)
3407 struct ip_fw *rule, *f, *prev;
3408 int l = RULESIZE(input_rule);
3410 if (chain->rules == NULL && input_rule->rulenum != IPFW_DEFAULT_RULE)
3413 rule = malloc(l, M_IPFW, M_NOWAIT | M_ZERO);
3417 bcopy(input_rule, rule, l);
3420 rule->next_rule = NULL;
3424 rule->timestamp = 0;
3428 if (chain->rules == NULL) { /* default rule */
3429 chain->rules = rule;
3434 * If rulenum is 0, find highest numbered rule before the
3435 * default rule, and add autoinc_step
3437 if (V_autoinc_step < 1)
3439 else if (V_autoinc_step > 1000)
3440 V_autoinc_step = 1000;
3441 if (rule->rulenum == 0) {
3443 * locate the highest numbered rule before default
3445 for (f = chain->rules; f; f = f->next) {
3446 if (f->rulenum == IPFW_DEFAULT_RULE)
3448 rule->rulenum = f->rulenum;
3450 if (rule->rulenum < IPFW_DEFAULT_RULE - V_autoinc_step)
3451 rule->rulenum += V_autoinc_step;
3452 input_rule->rulenum = rule->rulenum;
3456 * Now insert the new rule in the right place in the sorted list.
3458 for (prev = NULL, f = chain->rules; f; prev = f, f = f->next) {
3459 if (f->rulenum > rule->rulenum) { /* found the location */
3463 } else { /* head insert */
3464 rule->next = chain->rules;
3465 chain->rules = rule;
3470 flush_rule_ptrs(chain);
3474 IPFW_WUNLOCK(chain);
3475 DEB(printf("ipfw: installed rule %d, static count now %d\n",
3476 rule->rulenum, V_static_count);)
3481 * Remove a static rule (including derived * dynamic rules)
3482 * and place it on the ``reap list'' for later reclamation.
3483 * The caller is in charge of clearing rule pointers to avoid
3484 * dangling pointers.
3485 * @return a pointer to the next entry.
3486 * Arguments are not checked, so they better be correct.
3488 static struct ip_fw *
3489 remove_rule(struct ip_fw_chain *chain, struct ip_fw *rule,
3493 int l = RULESIZE(rule);
3495 IPFW_WLOCK_ASSERT(chain);
3499 remove_dyn_rule(rule, NULL /* force removal */);
3508 rule->next = chain->reap;
3515 * Reclaim storage associated with a list of rules. This is
3516 * typically the list created using remove_rule.
3519 reap_rules(struct ip_fw *head)
3523 while ((rule = head) != NULL) {
3525 if (DUMMYNET_LOADED)
3526 ip_dn_ruledel_ptr(rule);
3532 * Remove all rules from a chain (except rules in set RESVD_SET
3533 * unless kill_default = 1). The caller is responsible for
3534 * reclaiming storage for the rules left in chain->reap.
3537 free_chain(struct ip_fw_chain *chain, int kill_default)
3539 struct ip_fw *prev, *rule;
3541 IPFW_WLOCK_ASSERT(chain);
3543 flush_rule_ptrs(chain); /* more efficient to do outside the loop */
3544 for (prev = NULL, rule = chain->rules; rule ; )
3545 if (kill_default || rule->set != RESVD_SET)
3546 rule = remove_rule(chain, rule, prev);
3554 * Remove all rules with given number, and also do set manipulation.
3555 * Assumes chain != NULL && *chain != NULL.
3557 * The argument is an u_int32_t. The low 16 bit are the rule or set number,
3558 * the next 8 bits are the new set, the top 8 bits are the command:
3560 * 0 delete rules with given number
3561 * 1 delete rules with given set number
3562 * 2 move rules with given number to new set
3563 * 3 move rules with given set number to new set
3564 * 4 swap sets with given numbers
3565 * 5 delete rules with given number and with given set number
3568 del_entry(struct ip_fw_chain *chain, u_int32_t arg)
3570 struct ip_fw *prev = NULL, *rule;
3571 u_int16_t rulenum; /* rule or old_set */
3572 u_int8_t cmd, new_set;
3574 rulenum = arg & 0xffff;
3575 cmd = (arg >> 24) & 0xff;
3576 new_set = (arg >> 16) & 0xff;
3578 if (cmd > 5 || new_set > RESVD_SET)
3580 if (cmd == 0 || cmd == 2 || cmd == 5) {
3581 if (rulenum >= IPFW_DEFAULT_RULE)
3584 if (rulenum > RESVD_SET) /* old_set */
3589 rule = chain->rules;
3592 case 0: /* delete rules with given number */
3594 * locate first rule to delete
3596 for (; rule->rulenum < rulenum; prev = rule, rule = rule->next)
3598 if (rule->rulenum != rulenum) {
3599 IPFW_WUNLOCK(chain);
3604 * flush pointers outside the loop, then delete all matching
3605 * rules. prev remains the same throughout the cycle.
3607 flush_rule_ptrs(chain);
3608 while (rule->rulenum == rulenum)
3609 rule = remove_rule(chain, rule, prev);
3612 case 1: /* delete all rules with given set number */
3613 flush_rule_ptrs(chain);
3614 rule = chain->rules;
3615 while (rule->rulenum < IPFW_DEFAULT_RULE)
3616 if (rule->set == rulenum)
3617 rule = remove_rule(chain, rule, prev);
3624 case 2: /* move rules with given number to new set */
3625 rule = chain->rules;
3626 for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
3627 if (rule->rulenum == rulenum)
3628 rule->set = new_set;
3631 case 3: /* move rules with given set number to new set */
3632 for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
3633 if (rule->set == rulenum)
3634 rule->set = new_set;
3637 case 4: /* swap two sets */
3638 for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
3639 if (rule->set == rulenum)
3640 rule->set = new_set;
3641 else if (rule->set == new_set)
3642 rule->set = rulenum;
3644 case 5: /* delete rules with given number and with given set number.
3645 * rulenum - given rule number;
3646 * new_set - given set number.
3648 for (; rule->rulenum < rulenum; prev = rule, rule = rule->next)
3650 if (rule->rulenum != rulenum) {
3651 IPFW_WUNLOCK(chain);
3654 flush_rule_ptrs(chain);
3655 while (rule->rulenum == rulenum) {
3656 if (rule->set == new_set)
3657 rule = remove_rule(chain, rule, prev);
3665 * Look for rules to reclaim. We grab the list before
3666 * releasing the lock then reclaim them w/o the lock to
3667 * avoid a LOR with dummynet.
3671 IPFW_WUNLOCK(chain);
3678 * Clear counters for a specific rule.
3679 * The enclosing "table" is assumed locked.
3682 clear_counters(struct ip_fw *rule, int log_only)
3684 ipfw_insn_log *l = (ipfw_insn_log *)ACTION_PTR(rule);
3686 if (log_only == 0) {
3687 rule->bcnt = rule->pcnt = 0;
3688 rule->timestamp = 0;
3690 if (l->o.opcode == O_LOG)
3691 l->log_left = l->max_log;
3695 * Reset some or all counters on firewall rules.
3696 * The argument `arg' is an u_int32_t. The low 16 bit are the rule number,
3697 * the next 8 bits are the set number, the top 8 bits are the command:
3698 * 0 work with rules from all set's;
3699 * 1 work with rules only from specified set.
3700 * Specified rule number is zero if we want to clear all entries.
3701 * log_only is 1 if we only want to reset logs, zero otherwise.
3704 zero_entry(struct ip_fw_chain *chain, u_int32_t arg, int log_only)
3709 uint16_t rulenum = arg & 0xffff;
3710 uint8_t set = (arg >> 16) & 0xff;
3711 uint8_t cmd = (arg >> 24) & 0xff;
3715 if (cmd == 1 && set > RESVD_SET)
3720 V_norule_counter = 0;
3721 for (rule = chain->rules; rule; rule = rule->next) {
3722 /* Skip rules from another set. */
3723 if (cmd == 1 && rule->set != set)
3725 clear_counters(rule, log_only);
3727 msg = log_only ? "ipfw: All logging counts reset.\n" :
3728 "ipfw: Accounting cleared.\n";
3732 * We can have multiple rules with the same number, so we
3733 * need to clear them all.
3735 for (rule = chain->rules; rule; rule = rule->next)
3736 if (rule->rulenum == rulenum) {
3737 while (rule && rule->rulenum == rulenum) {
3738 if (cmd == 0 || rule->set == set)
3739 clear_counters(rule, log_only);
3745 if (!cleared) { /* we did not find any matching rules */
3746 IPFW_WUNLOCK(chain);
3749 msg = log_only ? "ipfw: Entry %d logging count reset.\n" :
3750 "ipfw: Entry %d cleared.\n";
3752 IPFW_WUNLOCK(chain);
3755 log(LOG_SECURITY | LOG_NOTICE, msg, rulenum);
3760 * Check validity of the structure before insert.
3761 * Fortunately rules are simple, so this mostly need to check rule sizes.
3764 check_ipfw_struct(struct ip_fw *rule, int size)
3770 if (size < sizeof(*rule)) {
3771 printf("ipfw: rule too short\n");
3774 /* first, check for valid size */
3777 printf("ipfw: size mismatch (have %d want %d)\n", size, l);
3780 if (rule->act_ofs >= rule->cmd_len) {
3781 printf("ipfw: bogus action offset (%u > %u)\n",
3782 rule->act_ofs, rule->cmd_len - 1);
3786 * Now go for the individual checks. Very simple ones, basically only
3787 * instruction sizes.
3789 for (l = rule->cmd_len, cmd = rule->cmd ;
3790 l > 0 ; l -= cmdlen, cmd += cmdlen) {
3791 cmdlen = F_LEN(cmd);
3793 printf("ipfw: opcode %d size truncated\n",
3797 DEB(printf("ipfw: opcode %d\n", cmd->opcode);)
3798 switch (cmd->opcode) {
3810 case O_IPPRECEDENCE:
3828 if (cmdlen != F_INSN_SIZE(ipfw_insn))
3833 if (cmdlen != F_INSN_SIZE(ipfw_insn))
3835 if (cmd->arg1 >= rt_numfibs) {
3836 printf("ipfw: invalid fib number %d\n",
3843 if (cmdlen != F_INSN_SIZE(ipfw_insn))
3845 if (cmd->arg1 >= rt_numfibs) {
3846 printf("ipfw: invalid fib number %d\n",
3861 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32))
3866 if (cmdlen != F_INSN_SIZE(ipfw_insn_limit))
3871 if (cmdlen != F_INSN_SIZE(ipfw_insn_log))
3874 ((ipfw_insn_log *)cmd)->log_left =
3875 ((ipfw_insn_log *)cmd)->max_log;
3881 /* only odd command lengths */
3882 if ( !(cmdlen & 1) || cmdlen > 31)
3888 if (cmd->arg1 == 0 || cmd->arg1 > 256) {
3889 printf("ipfw: invalid set size %d\n",
3893 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
3898 case O_IP_SRC_LOOKUP:
3899 case O_IP_DST_LOOKUP:
3900 if (cmd->arg1 >= IPFW_TABLES_MAX) {
3901 printf("ipfw: invalid table number %d\n",
3905 if (cmdlen != F_INSN_SIZE(ipfw_insn) &&
3906 cmdlen != F_INSN_SIZE(ipfw_insn_u32))
3911 if (cmdlen != F_INSN_SIZE(ipfw_insn_mac))
3921 if (cmdlen < 1 || cmdlen > 31)
3927 case O_IP_DSTPORT: /* XXX artificial limit, 30 port pairs */
3928 if (cmdlen < 2 || cmdlen > 31)
3935 if (cmdlen != F_INSN_SIZE(ipfw_insn_if))
3940 if (cmdlen != F_INSN_SIZE(ipfw_insn_altq))
3946 if (cmdlen != F_INSN_SIZE(ipfw_insn))
3951 #ifdef IPFIREWALL_FORWARD
3952 if (cmdlen != F_INSN_SIZE(ipfw_insn_sa))
3961 if (ip_divert_ptr == NULL)
3967 if (!NG_IPFW_LOADED)
3972 if (!IPFW_NAT_LOADED)
3974 if (cmdlen != F_INSN_SIZE(ipfw_insn_nat))
3977 case O_FORWARD_MAC: /* XXX not implemented yet */
3988 if (cmdlen != F_INSN_SIZE(ipfw_insn))
3992 printf("ipfw: opcode %d, multiple actions"
3999 printf("ipfw: opcode %d, action must be"
4008 if (cmdlen != F_INSN_SIZE(struct in6_addr) +
4009 F_INSN_SIZE(ipfw_insn))
4014 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
4015 ((ipfw_insn_u32 *)cmd)->o.arg1)
4019 case O_IP6_SRC_MASK:
4020 case O_IP6_DST_MASK:
4021 if ( !(cmdlen & 1) || cmdlen > 127)
4025 if( cmdlen != F_INSN_SIZE( ipfw_insn_icmp6 ) )
4031 switch (cmd->opcode) {
4041 case O_IP6_SRC_MASK:
4042 case O_IP6_DST_MASK:
4044 printf("ipfw: no IPv6 support in kernel\n");
4045 return EPROTONOSUPPORT;
4048 printf("ipfw: opcode %d, unknown opcode\n",
4054 if (have_action == 0) {
4055 printf("ipfw: missing action\n");
4061 printf("ipfw: opcode %d size %d wrong\n",
4062 cmd->opcode, cmdlen);
4067 * Copy the static and dynamic rules to the supplied buffer
4068 * and return the amount of space actually used.
4071 ipfw_getrules(struct ip_fw_chain *chain, void *buf, size_t space)
4074 char *ep = bp + space;
4077 time_t boot_seconds;
4079 boot_seconds = boottime.tv_sec;
4080 /* XXX this can take a long time and locking will block packet flow */
4082 for (rule = chain->rules; rule ; rule = rule->next) {
4084 * Verify the entry fits in the buffer in case the
4085 * rules changed between calculating buffer space and
4086 * now. This would be better done using a generation
4087 * number but should suffice for now.
4093 * XXX HACK. Store the disable mask in the "next"
4094 * pointer in a wild attempt to keep the ABI the same.
4095 * Why do we do this on EVERY rule?
4097 bcopy(&V_set_disable,
4098 &(((struct ip_fw *)bp)->next_rule),
4099 sizeof(V_set_disable));
4100 if (((struct ip_fw *)bp)->timestamp)
4101 ((struct ip_fw *)bp)->timestamp += boot_seconds;
4105 IPFW_RUNLOCK(chain);
4107 ipfw_dyn_rule *p, *last = NULL;
4110 for (i = 0 ; i < V_curr_dyn_buckets; i++)
4111 for (p = V_ipfw_dyn_v[i] ; p != NULL; p = p->next) {
4112 if (bp + sizeof *p <= ep) {
4113 ipfw_dyn_rule *dst =
4114 (ipfw_dyn_rule *)bp;
4115 bcopy(p, dst, sizeof *p);
4116 bcopy(&(p->rule->rulenum), &(dst->rule),
4117 sizeof(p->rule->rulenum));
4119 * store set number into high word of
4120 * dst->rule pointer.
4122 bcopy(&(p->rule->set),
4123 (char *)&dst->rule +
4124 sizeof(p->rule->rulenum),
4125 sizeof(p->rule->set));
4127 * store a non-null value in "next".
4128 * The userland code will interpret a
4129 * NULL here as a marker
4130 * for the last dynamic rule.
4132 bcopy(&dst, &dst->next, sizeof(dst));
4135 TIME_LEQ(dst->expire, time_uptime) ?
4136 0 : dst->expire - time_uptime ;
4137 bp += sizeof(ipfw_dyn_rule);
4141 if (last != NULL) /* mark last dynamic rule */
4142 bzero(&last->next, sizeof(last));
4144 return (bp - (char *)buf);
4149 * {set|get}sockopt parser.
4152 ipfw_ctl(struct sockopt *sopt)
4154 #define RULE_MAXSIZE (256*sizeof(u_int32_t))
4157 struct ip_fw *buf, *rule;
4158 u_int32_t rulenum[2];
4160 error = priv_check(sopt->sopt_td, PRIV_NETINET_IPFW);
4165 * Disallow modifications in really-really secure mode, but still allow
4166 * the logging counters to be reset.
4168 if (sopt->sopt_name == IP_FW_ADD ||
4169 (sopt->sopt_dir == SOPT_SET && sopt->sopt_name != IP_FW_RESETLOG)) {
4170 error = securelevel_ge(sopt->sopt_td->td_ucred, 3);
4177 switch (sopt->sopt_name) {
4180 * pass up a copy of the current rules. Static rules
4181 * come first (the last of which has number IPFW_DEFAULT_RULE),
4182 * followed by a possibly empty list of dynamic rule.
4183 * The last dynamic rule has NULL in the "next" field.
4185 * Note that the calculated size is used to bound the
4186 * amount of data returned to the user. The rule set may
4187 * change between calculating the size and returning the
4188 * data in which case we'll just return what fits.
4190 size = V_static_len; /* size of static rules */
4191 if (V_ipfw_dyn_v) /* add size of dyn.rules */
4192 size += (V_dyn_count * sizeof(ipfw_dyn_rule));
4195 * XXX todo: if the user passes a short length just to know
4196 * how much room is needed, do not bother filling up the
4197 * buffer, just jump to the sooptcopyout.
4199 buf = malloc(size, M_TEMP, M_WAITOK);
4200 error = sooptcopyout(sopt, buf,
4201 ipfw_getrules(&V_layer3_chain, buf, size));
4207 * Normally we cannot release the lock on each iteration.
4208 * We could do it here only because we start from the head all
4209 * the times so there is no risk of missing some entries.
4210 * On the other hand, the risk is that we end up with
4211 * a very inconsistent ruleset, so better keep the lock
4212 * around the whole cycle.
4214 * XXX this code can be improved by resetting the head of
4215 * the list to point to the default rule, and then freeing
4216 * the old list without the need for a lock.
4219 IPFW_WLOCK(&V_layer3_chain);
4220 V_layer3_chain.reap = NULL;
4221 free_chain(&V_layer3_chain, 0 /* keep default rule */);
4222 rule = V_layer3_chain.reap;
4223 V_layer3_chain.reap = NULL;
4224 IPFW_WUNLOCK(&V_layer3_chain);
4230 rule = malloc(RULE_MAXSIZE, M_TEMP, M_WAITOK);
4231 error = sooptcopyin(sopt, rule, RULE_MAXSIZE,
4232 sizeof(struct ip_fw) );
4234 error = check_ipfw_struct(rule, sopt->sopt_valsize);
4236 error = add_rule(&V_layer3_chain, rule);
4237 size = RULESIZE(rule);
4238 if (!error && sopt->sopt_dir == SOPT_GET)
4239 error = sooptcopyout(sopt, rule, size);
4246 * IP_FW_DEL is used for deleting single rules or sets,
4247 * and (ab)used to atomically manipulate sets. Argument size
4248 * is used to distinguish between the two:
4250 * delete single rule or set of rules,
4251 * or reassign rules (or sets) to a different set.
4252 * 2*sizeof(u_int32_t)
4253 * atomic disable/enable sets.
4254 * first u_int32_t contains sets to be disabled,
4255 * second u_int32_t contains sets to be enabled.
4257 error = sooptcopyin(sopt, rulenum,
4258 2*sizeof(u_int32_t), sizeof(u_int32_t));
4261 size = sopt->sopt_valsize;
4262 if (size == sizeof(u_int32_t)) /* delete or reassign */
4263 error = del_entry(&V_layer3_chain, rulenum[0]);
4264 else if (size == 2*sizeof(u_int32_t)) /* set enable/disable */
4266 (V_set_disable | rulenum[0]) & ~rulenum[1] &
4267 ~(1<<RESVD_SET); /* set RESVD_SET always enabled */
4273 case IP_FW_RESETLOG: /* argument is an u_int_32, the rule number */
4275 if (sopt->sopt_val != 0) {
4276 error = sooptcopyin(sopt, rulenum,
4277 sizeof(u_int32_t), sizeof(u_int32_t));
4281 error = zero_entry(&V_layer3_chain, rulenum[0],
4282 sopt->sopt_name == IP_FW_RESETLOG);
4285 case IP_FW_TABLE_ADD:
4287 ipfw_table_entry ent;
4289 error = sooptcopyin(sopt, &ent,
4290 sizeof(ent), sizeof(ent));
4293 error = add_table_entry(&V_layer3_chain, ent.tbl,
4294 ent.addr, ent.masklen, ent.value);
4298 case IP_FW_TABLE_DEL:
4300 ipfw_table_entry ent;
4302 error = sooptcopyin(sopt, &ent,
4303 sizeof(ent), sizeof(ent));
4306 error = del_table_entry(&V_layer3_chain, ent.tbl,
4307 ent.addr, ent.masklen);
4311 case IP_FW_TABLE_FLUSH:
4315 error = sooptcopyin(sopt, &tbl,
4316 sizeof(tbl), sizeof(tbl));
4319 IPFW_WLOCK(&V_layer3_chain);
4320 error = flush_table(&V_layer3_chain, tbl);
4321 IPFW_WUNLOCK(&V_layer3_chain);
4325 case IP_FW_TABLE_GETSIZE:
4329 if ((error = sooptcopyin(sopt, &tbl, sizeof(tbl),
4332 IPFW_RLOCK(&V_layer3_chain);
4333 error = count_table(&V_layer3_chain, tbl, &cnt);
4334 IPFW_RUNLOCK(&V_layer3_chain);
4337 error = sooptcopyout(sopt, &cnt, sizeof(cnt));
4341 case IP_FW_TABLE_LIST:
4345 if (sopt->sopt_valsize < sizeof(*tbl)) {
4349 size = sopt->sopt_valsize;
4350 tbl = malloc(size, M_TEMP, M_WAITOK);
4351 error = sooptcopyin(sopt, tbl, size, sizeof(*tbl));
4356 tbl->size = (size - sizeof(*tbl)) /
4357 sizeof(ipfw_table_entry);
4358 IPFW_RLOCK(&V_layer3_chain);
4359 error = dump_table(&V_layer3_chain, tbl);
4360 IPFW_RUNLOCK(&V_layer3_chain);
4365 error = sooptcopyout(sopt, tbl, size);
4372 if (IPFW_NAT_LOADED)
4373 error = ipfw_nat_cfg_ptr(sopt);
4375 printf("IP_FW_NAT_CFG: ipfw_nat not present, please load it.\n");
4383 if (IPFW_NAT_LOADED)
4384 error = ipfw_nat_del_ptr(sopt);
4386 printf("IP_FW_NAT_DEL: ipfw_nat not present, please load it.\n");
4387 printf("ipfw_nat not loaded: %d\n", sopt->sopt_name);
4393 case IP_FW_NAT_GET_CONFIG:
4395 if (IPFW_NAT_LOADED)
4396 error = ipfw_nat_get_cfg_ptr(sopt);
4398 printf("IP_FW_NAT_GET_CFG: ipfw_nat not present, please load it.\n");
4404 case IP_FW_NAT_GET_LOG:
4406 if (IPFW_NAT_LOADED)
4407 error = ipfw_nat_get_log_ptr(sopt);
4409 printf("IP_FW_NAT_GET_LOG: ipfw_nat not present, please load it.\n");
4416 printf("ipfw: ipfw_ctl invalid option %d\n", sopt->sopt_name);
4425 * dummynet needs a reference to the default rule, because rules can be
4426 * deleted while packets hold a reference to them. When this happens,
4427 * dummynet changes the reference to the default rule (it could well be a
4428 * NULL pointer, but this way we do not need to check for the special
4429 * case, plus here he have info on the default behaviour).
4431 struct ip_fw *ip_fw_default_rule;
4434 * This procedure is only used to handle keepalives. It is invoked
4435 * every dyn_keepalive_period
4438 ipfw_tick(void * __unused unused)
4440 struct mbuf *m0, *m, *mnext, **mtailp;
4444 if (V_dyn_keepalive == 0 || V_ipfw_dyn_v == NULL || V_dyn_count == 0)
4448 * We make a chain of packets to go out here -- not deferring
4449 * until after we drop the IPFW dynamic rule lock would result
4450 * in a lock order reversal with the normal packet input -> ipfw
4456 for (i = 0 ; i < V_curr_dyn_buckets ; i++) {
4457 for (q = V_ipfw_dyn_v[i] ; q ; q = q->next ) {
4458 if (q->dyn_type == O_LIMIT_PARENT)
4460 if (q->id.proto != IPPROTO_TCP)
4462 if ( (q->state & BOTH_SYN) != BOTH_SYN)
4464 if (TIME_LEQ( time_uptime+V_dyn_keepalive_interval,
4466 continue; /* too early */
4467 if (TIME_LEQ(q->expire, time_uptime))
4468 continue; /* too late, rule expired */
4470 *mtailp = send_pkt(NULL, &(q->id), q->ack_rev - 1,
4471 q->ack_fwd, TH_SYN);
4472 if (*mtailp != NULL)
4473 mtailp = &(*mtailp)->m_nextpkt;
4474 *mtailp = send_pkt(NULL, &(q->id), q->ack_fwd - 1,
4476 if (*mtailp != NULL)
4477 mtailp = &(*mtailp)->m_nextpkt;
4481 for (m = mnext = m0; m != NULL; m = mnext) {
4482 mnext = m->m_nextpkt;
4483 m->m_nextpkt = NULL;
4484 ip_output(m, NULL, NULL, 0, NULL, NULL);
4487 callout_reset(&V_ipfw_timeout, V_dyn_keepalive_period * hz,
4494 struct ip_fw default_rule;
4498 /* Setup IPv6 fw sysctl tree. */
4499 sysctl_ctx_init(&ip6_fw_sysctl_ctx);
4500 ip6_fw_sysctl_tree = SYSCTL_ADD_NODE(&ip6_fw_sysctl_ctx,
4501 SYSCTL_STATIC_CHILDREN(_net_inet6_ip6), OID_AUTO, "fw",
4502 CTLFLAG_RW | CTLFLAG_SECURE, 0, "Firewall");
4503 SYSCTL_ADD_PROC(&ip6_fw_sysctl_ctx, SYSCTL_CHILDREN(ip6_fw_sysctl_tree),
4504 OID_AUTO, "enable", CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE3,
4505 &V_fw6_enable, 0, ipfw_chg_hook, "I", "Enable ipfw+6");
4506 SYSCTL_ADD_INT(&ip6_fw_sysctl_ctx, SYSCTL_CHILDREN(ip6_fw_sysctl_tree),
4507 OID_AUTO, "deny_unknown_exthdrs", CTLFLAG_RW | CTLFLAG_SECURE,
4508 &V_fw_deny_unknown_exthdrs, 0,
4509 "Deny packets with unknown IPv6 Extension Headers");
4512 V_layer3_chain.rules = NULL;
4513 IPFW_LOCK_INIT(&V_layer3_chain);
4514 ipfw_dyn_rule_zone = uma_zcreate("IPFW dynamic rule",
4515 sizeof(ipfw_dyn_rule), NULL, NULL, NULL, NULL,
4517 IPFW_DYN_LOCK_INIT();
4518 callout_init(&V_ipfw_timeout, CALLOUT_MPSAFE);
4520 bzero(&default_rule, sizeof default_rule);
4522 default_rule.act_ofs = 0;
4523 default_rule.rulenum = IPFW_DEFAULT_RULE;
4524 default_rule.cmd_len = 1;
4525 default_rule.set = RESVD_SET;
4527 default_rule.cmd[0].len = 1;
4528 default_rule.cmd[0].opcode =
4529 #ifdef IPFIREWALL_DEFAULT_TO_ACCEPT
4534 error = add_rule(&V_layer3_chain, &default_rule);
4536 printf("ipfw2: error %u initializing default rule "
4537 "(support disabled)\n", error);
4538 IPFW_DYN_LOCK_DESTROY();
4539 IPFW_LOCK_DESTROY(&V_layer3_chain);
4540 uma_zdestroy(ipfw_dyn_rule_zone);
4544 ip_fw_default_rule = V_layer3_chain.rules;
4549 "initialized, divert %s, nat %s, "
4550 "rule-based forwarding "
4551 #ifdef IPFIREWALL_FORWARD
4556 "default to %s, logging ",
4562 #ifdef IPFIREWALL_NAT
4568 default_rule.cmd[0].opcode == O_ACCEPT ? "accept" : "deny");
4570 #ifdef IPFIREWALL_VERBOSE
4573 #ifdef IPFIREWALL_VERBOSE_LIMIT
4574 V_verbose_limit = IPFIREWALL_VERBOSE_LIMIT;
4576 if (V_fw_verbose == 0)
4577 printf("disabled\n");
4578 else if (V_verbose_limit == 0)
4579 printf("unlimited\n");
4581 printf("limited to %d packets/entry by default\n",
4584 error = init_tables(&V_layer3_chain);
4586 IPFW_DYN_LOCK_DESTROY();
4587 IPFW_LOCK_DESTROY(&V_layer3_chain);
4588 uma_zdestroy(ipfw_dyn_rule_zone);
4591 ip_fw_ctl_ptr = ipfw_ctl;
4592 ip_fw_chk_ptr = ipfw_chk;
4593 callout_reset(&V_ipfw_timeout, hz, ipfw_tick, NULL);
4594 LIST_INIT(&V_layer3_chain.nat);
4603 ip_fw_chk_ptr = NULL;
4604 ip_fw_ctl_ptr = NULL;
4605 callout_drain(&V_ipfw_timeout);
4606 IPFW_WLOCK(&V_layer3_chain);
4607 flush_tables(&V_layer3_chain);
4608 V_layer3_chain.reap = NULL;
4609 free_chain(&V_layer3_chain, 1 /* kill default rule */);
4610 reap = V_layer3_chain.reap, V_layer3_chain.reap = NULL;
4611 IPFW_WUNLOCK(&V_layer3_chain);
4614 IPFW_DYN_LOCK_DESTROY();
4615 uma_zdestroy(ipfw_dyn_rule_zone);
4616 if (V_ipfw_dyn_v != NULL)
4617 free(V_ipfw_dyn_v, M_IPFW);
4618 IPFW_LOCK_DESTROY(&V_layer3_chain);
4621 /* Free IPv6 fw sysctl tree. */
4622 sysctl_ctx_free(&ip6_fw_sysctl_ctx);
4625 printf("IP firewall unloaded\n");