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: src/sys/netinet/ip_fw2.c,v 1.175.2.13 2008/10/30 16:29:04 bz Exp $");
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/malloc.h>
53 #include <sys/kernel.h>
56 #include <sys/module.h>
59 #include <sys/socket.h>
60 #include <sys/socketvar.h>
61 #include <sys/sysctl.h>
62 #include <sys/syslog.h>
63 #include <sys/ucred.h>
64 #include <net/ethernet.h> /* for ETHERTYPE_IP */
66 #include <net/radix.h>
67 #include <net/route.h>
68 #include <net/pf_mtag.h>
70 #define IPFW_INTERNAL /* Access to protected data structures in ip_fw.h. */
72 #include <netinet/in.h>
73 #include <netinet/in_var.h>
74 #include <netinet/in_pcb.h>
75 #include <netinet/ip.h>
76 #include <netinet/ip_var.h>
77 #include <netinet/ip_icmp.h>
78 #include <netinet/ip_fw.h>
79 #include <netinet/ip_divert.h>
80 #include <netinet/ip_dummynet.h>
81 #include <netinet/ip_carp.h>
82 #include <netinet/pim.h>
83 #include <netinet/tcp_var.h>
84 #include <netinet/udp.h>
85 #include <netinet/udp_var.h>
86 #include <netinet/sctp.h>
87 #include <netgraph/ng_ipfw.h>
89 #include <netinet/ip6.h>
90 #include <netinet/icmp6.h>
92 #include <netinet6/scope6_var.h>
95 #include <machine/in_cksum.h> /* XXX for in_cksum */
98 #include <security/mac/mac_framework.h>
104 * set_disable contains one bit per set value (0..31).
105 * If the bit is set, all rules with the corresponding set
106 * are disabled. Set RESVD_SET(31) is reserved for the default rule
107 * and rules that are not deleted by the flush command,
108 * and CANNOT be disabled.
109 * Rules in set RESVD_SET can only be deleted explicitly.
111 static u_int32_t set_disable;
112 static int fw_verbose;
113 static struct callout ipfw_timeout;
114 static int verbose_limit;
116 static uma_zone_t ipfw_dyn_rule_zone;
119 * Data structure to cache our ucred related
120 * information. This structure only gets used if
121 * the user specified UID/GID based constraints in
125 gid_t fw_groups[NGROUPS];
132 * list of rules for layer 3
134 struct ip_fw_chain layer3_chain;
136 MALLOC_DEFINE(M_IPFW, "IpFw/IpAcct", "IpFw/IpAcct chain's");
137 MALLOC_DEFINE(M_IPFW_TBL, "ipfw_tbl", "IpFw tables");
138 #define IPFW_NAT_LOADED (ipfw_nat_ptr != NULL)
139 ipfw_nat_t *ipfw_nat_ptr = NULL;
140 ipfw_nat_cfg_t *ipfw_nat_cfg_ptr;
141 ipfw_nat_cfg_t *ipfw_nat_del_ptr;
142 ipfw_nat_cfg_t *ipfw_nat_get_cfg_ptr;
143 ipfw_nat_cfg_t *ipfw_nat_get_log_ptr;
146 struct radix_node rn[2];
147 struct sockaddr_in addr, mask;
151 static int autoinc_step = 100; /* bounded to 1..1000 in add_rule() */
153 extern int ipfw_chg_hook(SYSCTL_HANDLER_ARGS);
156 SYSCTL_NODE(_net_inet_ip, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall");
157 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, enable,
158 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE3, &fw_enable, 0,
159 ipfw_chg_hook, "I", "Enable ipfw");
160 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, autoinc_step, CTLFLAG_RW,
161 &autoinc_step, 0, "Rule number autincrement step");
162 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, one_pass,
163 CTLFLAG_RW | CTLFLAG_SECURE3,
165 "Only do a single pass through ipfw when using dummynet(4)");
166 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose,
167 CTLFLAG_RW | CTLFLAG_SECURE3,
168 &fw_verbose, 0, "Log matches to ipfw rules");
169 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose_limit, CTLFLAG_RW,
170 &verbose_limit, 0, "Set upper limit of matches of ipfw rules logged");
171 SYSCTL_UINT(_net_inet_ip_fw, OID_AUTO, default_rule, CTLFLAG_RD,
172 NULL, IPFW_DEFAULT_RULE, "The default/max possible rule number.");
173 SYSCTL_UINT(_net_inet_ip_fw, OID_AUTO, tables_max, CTLFLAG_RD,
174 NULL, IPFW_TABLES_MAX, "The maximum number of tables.");
175 #endif /* SYSCTL_NODE */
178 * Description of dynamic rules.
180 * Dynamic rules are stored in lists accessed through a hash table
181 * (ipfw_dyn_v) whose size is curr_dyn_buckets. This value can
182 * be modified through the sysctl variable dyn_buckets which is
183 * updated when the table becomes empty.
185 * XXX currently there is only one list, ipfw_dyn.
187 * When a packet is received, its address fields are first masked
188 * with the mask defined for the rule, then hashed, then matched
189 * against the entries in the corresponding list.
190 * Dynamic rules can be used for different purposes:
192 * + enforcing limits on the number of sessions;
193 * + in-kernel NAT (not implemented yet)
195 * The lifetime of dynamic rules is regulated by dyn_*_lifetime,
196 * measured in seconds and depending on the flags.
198 * The total number of dynamic rules is stored in dyn_count.
199 * The max number of dynamic rules is dyn_max. When we reach
200 * the maximum number of rules we do not create anymore. This is
201 * done to avoid consuming too much memory, but also too much
202 * time when searching on each packet (ideally, we should try instead
203 * to put a limit on the length of the list on each bucket...).
205 * Each dynamic rule holds a pointer to the parent ipfw rule so
206 * we know what action to perform. Dynamic rules are removed when
207 * the parent rule is deleted. XXX we should make them survive.
209 * There are some limitations with dynamic rules -- we do not
210 * obey the 'randomized match', and we do not do multiple
211 * passes through the firewall. XXX check the latter!!!
213 static ipfw_dyn_rule **ipfw_dyn_v = NULL;
214 static u_int32_t dyn_buckets = 256; /* must be power of 2 */
215 static u_int32_t curr_dyn_buckets = 256; /* must be power of 2 */
217 #if defined( __linux__ ) || defined( _WIN32 )
218 DEFINE_SPINLOCK(ipfw_dyn_mtx);
220 static struct mtx ipfw_dyn_mtx; /* mutex guarding dynamic rules */
221 #endif /* !__linux__ */
222 #define IPFW_DYN_LOCK_INIT() \
223 mtx_init(&ipfw_dyn_mtx, "IPFW dynamic rules", NULL, MTX_DEF)
224 #define IPFW_DYN_LOCK_DESTROY() mtx_destroy(&ipfw_dyn_mtx)
225 #define IPFW_DYN_LOCK() mtx_lock(&ipfw_dyn_mtx)
226 #define IPFW_DYN_UNLOCK() mtx_unlock(&ipfw_dyn_mtx)
227 #define IPFW_DYN_LOCK_ASSERT() mtx_assert(&ipfw_dyn_mtx, MA_OWNED)
230 * Timeouts for various events in handing dynamic rules.
232 static u_int32_t dyn_ack_lifetime = 300;
233 static u_int32_t dyn_syn_lifetime = 20;
234 static u_int32_t dyn_fin_lifetime = 1;
235 static u_int32_t dyn_rst_lifetime = 1;
236 static u_int32_t dyn_udp_lifetime = 10;
237 static u_int32_t dyn_short_lifetime = 5;
240 * Keepalives are sent if dyn_keepalive is set. They are sent every
241 * dyn_keepalive_period seconds, in the last dyn_keepalive_interval
242 * seconds of lifetime of a rule.
243 * dyn_rst_lifetime and dyn_fin_lifetime should be strictly lower
244 * than dyn_keepalive_period.
247 static u_int32_t dyn_keepalive_interval = 20;
248 static u_int32_t dyn_keepalive_period = 5;
249 static u_int32_t dyn_keepalive = 1; /* do send keepalives */
251 static u_int32_t static_count; /* # of static rules */
252 static u_int32_t static_len; /* size in bytes of static rules */
253 static u_int32_t dyn_count; /* # of dynamic rules */
254 static u_int32_t dyn_max = 4096; /* max # of dynamic rules */
257 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_buckets, CTLFLAG_RW,
258 &dyn_buckets, 0, "Number of dyn. buckets");
259 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, curr_dyn_buckets, CTLFLAG_RD,
260 &curr_dyn_buckets, 0, "Current Number of dyn. buckets");
261 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_count, CTLFLAG_RD,
262 &dyn_count, 0, "Number of dyn. rules");
263 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_max, CTLFLAG_RW,
264 &dyn_max, 0, "Max number of dyn. rules");
265 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, static_count, CTLFLAG_RD,
266 &static_count, 0, "Number of static rules");
267 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_ack_lifetime, CTLFLAG_RW,
268 &dyn_ack_lifetime, 0, "Lifetime of dyn. rules for acks");
269 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_syn_lifetime, CTLFLAG_RW,
270 &dyn_syn_lifetime, 0, "Lifetime of dyn. rules for syn");
271 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_fin_lifetime, CTLFLAG_RW,
272 &dyn_fin_lifetime, 0, "Lifetime of dyn. rules for fin");
273 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_rst_lifetime, CTLFLAG_RW,
274 &dyn_rst_lifetime, 0, "Lifetime of dyn. rules for rst");
275 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_udp_lifetime, CTLFLAG_RW,
276 &dyn_udp_lifetime, 0, "Lifetime of dyn. rules for UDP");
277 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_short_lifetime, CTLFLAG_RW,
278 &dyn_short_lifetime, 0, "Lifetime of dyn. rules for other situations");
279 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_keepalive, CTLFLAG_RW,
280 &dyn_keepalive, 0, "Enable keepalives for dyn. rules");
281 #endif /* SYSCTL_NODE */
285 * IPv6 specific variables
288 SYSCTL_DECL(_net_inet6_ip6);
289 #endif /* SYSCTL_NODE */
291 static struct sysctl_ctx_list ip6_fw_sysctl_ctx;
292 static struct sysctl_oid *ip6_fw_sysctl_tree;
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)
461 #if !defined( __linux__ ) && !defined( _WIN32 )
465 TAILQ_FOREACH(ia, &ifp->if_addrhead, ifa_link) {
466 if (ia->ifa_addr->sa_family != AF_INET)
468 if (cmd->p.ip.s_addr == ((struct sockaddr_in *)
469 (ia->ifa_addr))->sin_addr.s_addr)
470 return(1); /* match */
474 return(0); /* no match, fail ... */
477 #if !defined( __linux__ ) && !defined( _WIN32 )
479 * The verify_path function checks if a route to the src exists and
480 * if it is reachable via ifp (when provided).
482 * The 'verrevpath' option checks that the interface that an IP packet
483 * arrives on is the same interface that traffic destined for the
484 * packet's source address would be routed out of. The 'versrcreach'
485 * option just checks that the source address is reachable via any route
486 * (except default) in the routing table. These two are a measure to block
487 * forged packets. This is also commonly known as "anti-spoofing" or Unicast
488 * Reverse Path Forwarding (Unicast RFP) in Cisco-ese. The name of the knobs
489 * is purposely reminiscent of the Cisco IOS command,
491 * ip verify unicast reverse-path
492 * ip verify unicast source reachable-via any
494 * which implements the same functionality. But note that syntax is
495 * misleading. The check may be performed on all IP packets whether unicast,
496 * multicast, or broadcast.
499 verify_path(struct in_addr src, struct ifnet *ifp, u_int fib)
502 struct sockaddr_in *dst;
504 bzero(&ro, sizeof(ro));
506 dst = (struct sockaddr_in *)&(ro.ro_dst);
507 dst->sin_family = AF_INET;
508 dst->sin_len = sizeof(*dst);
510 in_rtalloc_ign(&ro, RTF_CLONING, fib);
512 if (ro.ro_rt == NULL)
516 * If ifp is provided, check for equality with rtentry.
517 * We should use rt->rt_ifa->ifa_ifp, instead of rt->rt_ifp,
518 * in order to pass packets injected back by if_simloop():
519 * if useloopback == 1 routing entry (via lo0) for our own address
520 * may exist, so we need to handle routing assymetry.
522 if (ifp != NULL && ro.ro_rt->rt_ifa->ifa_ifp != ifp) {
527 /* if no ifp provided, check if rtentry is not default route */
529 satosin(rt_key(ro.ro_rt))->sin_addr.s_addr == INADDR_ANY) {
534 /* or if this is a blackhole/reject route */
535 if (ifp == NULL && ro.ro_rt->rt_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
540 /* found valid route */
548 * ipv6 specific rules here...
551 icmp6type_match (int type, ipfw_insn_u32 *cmd)
553 return (type <= ICMP6_MAXTYPE && (cmd->d[type/32] & (1<<(type%32)) ) );
557 flow6id_match( int curr_flow, ipfw_insn_u32 *cmd )
560 for (i=0; i <= cmd->o.arg1; ++i )
561 if (curr_flow == cmd->d[i] )
566 /* support for IP6_*_ME opcodes */
568 search_ip6_addr_net (struct in6_addr * ip6_addr)
572 struct in6_ifaddr *fdm;
573 struct in6_addr copia;
575 TAILQ_FOREACH(mdc, &ifnet, if_link)
576 TAILQ_FOREACH(mdc2, &mdc->if_addrlist, ifa_list) {
577 if (mdc2->ifa_addr->sa_family == AF_INET6) {
578 fdm = (struct in6_ifaddr *)mdc2;
579 copia = fdm->ia_addr.sin6_addr;
580 /* need for leaving scope_id in the sock_addr */
581 in6_clearscope(&copia);
582 if (IN6_ARE_ADDR_EQUAL(ip6_addr, &copia))
590 verify_path6(struct in6_addr *src, struct ifnet *ifp)
593 struct sockaddr_in6 *dst;
595 bzero(&ro, sizeof(ro));
597 dst = (struct sockaddr_in6 * )&(ro.ro_dst);
598 dst->sin6_family = AF_INET6;
599 dst->sin6_len = sizeof(*dst);
600 dst->sin6_addr = *src;
601 /* XXX MRT 0 for ipv6 at this time */
602 rtalloc_ign((struct route *)&ro, RTF_CLONING);
604 if (ro.ro_rt == NULL)
608 * if ifp is provided, check for equality with rtentry
609 * We should use rt->rt_ifa->ifa_ifp, instead of rt->rt_ifp,
610 * to support the case of sending packets to an address of our own.
611 * (where the former interface is the first argument of if_simloop()
612 * (=ifp), the latter is lo0)
614 if (ifp != NULL && ro.ro_rt->rt_ifa->ifa_ifp != ifp) {
619 /* if no ifp provided, check if rtentry is not default route */
621 IN6_IS_ADDR_UNSPECIFIED(&satosin6(rt_key(ro.ro_rt))->sin6_addr)) {
626 /* or if this is a blackhole/reject route */
627 if (ifp == NULL && ro.ro_rt->rt_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
632 /* found valid route */
638 hash_packet6(struct ipfw_flow_id *id)
641 i = (id->dst_ip6.__u6_addr.__u6_addr32[2]) ^
642 (id->dst_ip6.__u6_addr.__u6_addr32[3]) ^
643 (id->src_ip6.__u6_addr.__u6_addr32[2]) ^
644 (id->src_ip6.__u6_addr.__u6_addr32[3]) ^
645 (id->dst_port) ^ (id->src_port);
650 is_icmp6_query(int icmp6_type)
652 if ((icmp6_type <= ICMP6_MAXTYPE) &&
653 (icmp6_type == ICMP6_ECHO_REQUEST ||
654 icmp6_type == ICMP6_MEMBERSHIP_QUERY ||
655 icmp6_type == ICMP6_WRUREQUEST ||
656 icmp6_type == ICMP6_FQDN_QUERY ||
657 icmp6_type == ICMP6_NI_QUERY))
664 send_reject6(struct ip_fw_args *args, int code, u_int hlen, struct ip6_hdr *ip6)
669 if (code == ICMP6_UNREACH_RST && args->f_id.proto == IPPROTO_TCP) {
677 tcp = (struct tcphdr *)((char *)ip6 + hlen);
679 if ((tcp->th_flags & TH_RST) != 0) {
687 ti.th.th_seq = ntohl(ti.th.th_seq);
688 ti.th.th_ack = ntohl(ti.th.th_ack);
689 ti.ip6.ip6_nxt = IPPROTO_TCP;
691 if (ti.th.th_flags & TH_ACK) {
697 if ((m->m_flags & M_PKTHDR) != 0) {
699 * total new data to ACK is:
700 * total packet length,
701 * minus the header length,
702 * minus the tcp header length.
704 ack += m->m_pkthdr.len - hlen
705 - (ti.th.th_off << 2);
706 } else if (ip6->ip6_plen) {
707 ack += ntohs(ip6->ip6_plen) + sizeof(*ip6) -
708 hlen - (ti.th.th_off << 2);
713 if (tcp->th_flags & TH_SYN)
716 flags = TH_RST|TH_ACK;
718 bcopy(&ti, ip6, sizeof(ti));
720 * m is only used to recycle the mbuf
721 * The data in it is never read so we don't need
722 * to correct the offsets or anything
724 tcp_respond(NULL, ip6, tcp, m, ack, seq, flags);
725 } else if (code != ICMP6_UNREACH_RST) { /* Send an ICMPv6 unreach. */
728 * Unlike above, the mbufs need to line up with the ip6 hdr,
729 * as the contents are read. We need to m_adj() the
731 * The mbuf will however be thrown away so we can adjust it.
732 * Remember we did an m_pullup on it already so we
733 * can make some assumptions about contiguousness.
736 m_adj(m, args->L3offset);
738 icmp6_error(m, ICMP6_DST_UNREACH, code, 0);
747 static u_int64_t norule_counter; /* counter for ipfw_log(NULL...) */
749 #define SNPARGS(buf, len) buf + len, sizeof(buf) > len ? sizeof(buf) - len : 0
750 #define SNP(buf) buf, sizeof(buf)
753 * We enter here when we have a rule with O_LOG.
754 * XXX this function alone takes about 2Kbytes of code!
757 ipfw_log(struct ip_fw *f, u_int hlen, struct ip_fw_args *args,
758 struct mbuf *m, struct ifnet *oif, u_short offset, uint32_t tablearg,
761 struct ether_header *eh = args->eh;
763 int limit_reached = 0;
764 char action2[40], proto[128], fragment[32];
769 if (f == NULL) { /* bogus pkt */
770 if (verbose_limit != 0 && norule_counter >= verbose_limit)
773 if (norule_counter == verbose_limit)
774 limit_reached = verbose_limit;
776 } else { /* O_LOG is the first action, find the real one */
777 ipfw_insn *cmd = ACTION_PTR(f);
778 ipfw_insn_log *l = (ipfw_insn_log *)cmd;
780 if (l->max_log != 0 && l->log_left == 0)
783 if (l->log_left == 0)
784 limit_reached = l->max_log;
785 cmd += F_LEN(cmd); /* point to first action */
786 if (cmd->opcode == O_ALTQ) {
787 ipfw_insn_altq *altq = (ipfw_insn_altq *)cmd;
789 snprintf(SNPARGS(action2, 0), "Altq %d",
793 if (cmd->opcode == O_PROB)
796 if (cmd->opcode == O_TAG)
800 switch (cmd->opcode) {
806 if (cmd->arg1==ICMP_REJECT_RST)
808 else if (cmd->arg1==ICMP_UNREACH_HOST)
811 snprintf(SNPARGS(action2, 0), "Unreach %d",
816 if (cmd->arg1==ICMP6_UNREACH_RST)
819 snprintf(SNPARGS(action2, 0), "Unreach %d",
830 snprintf(SNPARGS(action2, 0), "Divert %d",
834 snprintf(SNPARGS(action2, 0), "Tee %d",
838 snprintf(SNPARGS(action2, 0), "SetFib %d",
842 snprintf(SNPARGS(action2, 0), "SkipTo %d",
846 snprintf(SNPARGS(action2, 0), "Pipe %d",
850 snprintf(SNPARGS(action2, 0), "Queue %d",
854 ipfw_insn_sa *sa = (ipfw_insn_sa *)cmd;
856 struct in_addr dummyaddr;
857 if (sa->sa.sin_addr.s_addr == INADDR_ANY)
858 dummyaddr.s_addr = htonl(tablearg);
860 dummyaddr.s_addr = sa->sa.sin_addr.s_addr;
862 len = snprintf(SNPARGS(action2, 0), "Forward to %s",
863 inet_ntoa(dummyaddr));
866 snprintf(SNPARGS(action2, len), ":%d",
871 snprintf(SNPARGS(action2, 0), "Netgraph %d",
875 snprintf(SNPARGS(action2, 0), "Ngtee %d",
887 if (hlen == 0) { /* non-ip */
888 snprintf(SNPARGS(proto, 0), "MAC");
892 char src[48], dst[48];
893 struct icmphdr *icmp;
897 struct ip6_hdr *ip6 = NULL;
898 struct icmp6_hdr *icmp6;
903 if (IS_IP6_FLOW_ID(&(args->f_id))) {
904 char ip6buf[INET6_ADDRSTRLEN];
905 snprintf(src, sizeof(src), "[%s]",
906 ip6_sprintf(ip6buf, &args->f_id.src_ip6));
907 snprintf(dst, sizeof(dst), "[%s]",
908 ip6_sprintf(ip6buf, &args->f_id.dst_ip6));
910 ip6 = (struct ip6_hdr *)ip;
911 tcp = (struct tcphdr *)(((char *)ip) + hlen);
912 udp = (struct udphdr *)(((char *)ip) + hlen);
916 tcp = L3HDR(struct tcphdr, ip);
917 udp = L3HDR(struct udphdr, ip);
919 inet_ntoa_r(ip->ip_src, src);
920 inet_ntoa_r(ip->ip_dst, dst);
923 switch (args->f_id.proto) {
925 len = snprintf(SNPARGS(proto, 0), "TCP %s", src);
927 snprintf(SNPARGS(proto, len), ":%d %s:%d",
928 ntohs(tcp->th_sport),
930 ntohs(tcp->th_dport));
932 snprintf(SNPARGS(proto, len), " %s", dst);
936 len = snprintf(SNPARGS(proto, 0), "UDP %s", src);
938 snprintf(SNPARGS(proto, len), ":%d %s:%d",
939 ntohs(udp->uh_sport),
941 ntohs(udp->uh_dport));
943 snprintf(SNPARGS(proto, len), " %s", dst);
947 icmp = L3HDR(struct icmphdr, ip);
949 len = snprintf(SNPARGS(proto, 0),
951 icmp->icmp_type, icmp->icmp_code);
953 len = snprintf(SNPARGS(proto, 0), "ICMP ");
954 len += snprintf(SNPARGS(proto, len), "%s", src);
955 snprintf(SNPARGS(proto, len), " %s", dst);
959 icmp6 = (struct icmp6_hdr *)(((char *)ip) + hlen);
961 len = snprintf(SNPARGS(proto, 0),
963 icmp6->icmp6_type, icmp6->icmp6_code);
965 len = snprintf(SNPARGS(proto, 0), "ICMPv6 ");
966 len += snprintf(SNPARGS(proto, len), "%s", src);
967 snprintf(SNPARGS(proto, len), " %s", dst);
971 len = snprintf(SNPARGS(proto, 0), "P:%d %s",
972 args->f_id.proto, src);
973 snprintf(SNPARGS(proto, len), " %s", dst);
978 if (IS_IP6_FLOW_ID(&(args->f_id))) {
979 if (offset & (IP6F_OFF_MASK | IP6F_MORE_FRAG))
980 snprintf(SNPARGS(fragment, 0),
981 " (frag %08x:%d@%d%s)",
983 ntohs(ip6->ip6_plen) - hlen,
984 ntohs(offset & IP6F_OFF_MASK) << 3,
985 (offset & IP6F_MORE_FRAG) ? "+" : "");
990 if (1 || eh != NULL) { /* layer 2 packets are as on the wire */
991 ip_off = ntohs(ip->ip_off);
992 ip_len = ntohs(ip->ip_len);
997 if (ip_off & (IP_MF | IP_OFFMASK))
998 snprintf(SNPARGS(fragment, 0),
999 " (frag %d:%d@%d%s)",
1000 ntohs(ip->ip_id), ip_len - (ip->ip_hl << 2),
1002 (ip_off & IP_MF) ? "+" : "");
1005 if (oif || m->m_pkthdr.rcvif)
1006 log(LOG_SECURITY | LOG_INFO,
1007 "ipfw: %d %s %s %s via %s%s\n",
1008 f ? f->rulenum : -1,
1009 action, proto, oif ? "out" : "in",
1010 oif ? oif->if_xname : m->m_pkthdr.rcvif->if_xname,
1013 log(LOG_SECURITY | LOG_INFO,
1014 "ipfw: %d %s %s [no if info]%s\n",
1015 f ? f->rulenum : -1,
1016 action, proto, fragment);
1018 log(LOG_SECURITY | LOG_NOTICE,
1019 "ipfw: limit %d reached on entry %d\n",
1020 limit_reached, f ? f->rulenum : -1);
1024 * IMPORTANT: the hash function for dynamic rules must be commutative
1025 * in source and destination (ip,port), because rules are bidirectional
1026 * and we want to find both in the same bucket.
1029 hash_packet(struct ipfw_flow_id *id)
1034 if (IS_IP6_FLOW_ID(id))
1035 i = hash_packet6(id);
1038 i = (id->dst_ip) ^ (id->src_ip) ^ (id->dst_port) ^ (id->src_port);
1039 i &= (curr_dyn_buckets - 1);
1044 * unlink a dynamic rule from a chain. prev is a pointer to
1045 * the previous one, q is a pointer to the rule to delete,
1046 * head is a pointer to the head of the queue.
1047 * Modifies q and potentially also head.
1049 #define UNLINK_DYN_RULE(prev, head, q) { \
1050 ipfw_dyn_rule *old_q = q; \
1052 /* remove a refcount to the parent */ \
1053 if (q->dyn_type == O_LIMIT) \
1054 q->parent->count--; \
1055 DEB(printf("ipfw: unlink entry 0x%08x %d -> 0x%08x %d, %d left\n",\
1056 (q->id.src_ip), (q->id.src_port), \
1057 (q->id.dst_ip), (q->id.dst_port), dyn_count-1 ); ) \
1059 prev->next = q = q->next; \
1061 head = q = q->next; \
1063 uma_zfree(ipfw_dyn_rule_zone, old_q); }
1065 #define TIME_LEQ(a,b) ((int)((a)-(b)) <= 0)
1068 * Remove dynamic rules pointing to "rule", or all of them if rule == NULL.
1070 * If keep_me == NULL, rules are deleted even if not expired,
1071 * otherwise only expired rules are removed.
1073 * The value of the second parameter is also used to point to identify
1074 * a rule we absolutely do not want to remove (e.g. because we are
1075 * holding a reference to it -- this is the case with O_LIMIT_PARENT
1076 * rules). The pointer is only used for comparison, so any non-null
1080 remove_dyn_rule(struct ip_fw *rule, ipfw_dyn_rule *keep_me)
1082 static u_int32_t last_remove = 0;
1084 #define FORCE (keep_me == NULL)
1086 ipfw_dyn_rule *prev, *q;
1087 int i, pass = 0, max_pass = 0;
1089 IPFW_DYN_LOCK_ASSERT();
1091 if (ipfw_dyn_v == NULL || dyn_count == 0)
1093 /* do not expire more than once per second, it is useless */
1094 if (!FORCE && last_remove == time_uptime)
1096 last_remove = time_uptime;
1099 * because O_LIMIT refer to parent rules, during the first pass only
1100 * remove child and mark any pending LIMIT_PARENT, and remove
1101 * them in a second pass.
1104 for (i = 0 ; i < curr_dyn_buckets ; i++) {
1105 for (prev=NULL, q = ipfw_dyn_v[i] ; q ; ) {
1107 * Logic can become complex here, so we split tests.
1111 if (rule != NULL && rule != q->rule)
1112 goto next; /* not the one we are looking for */
1113 if (q->dyn_type == O_LIMIT_PARENT) {
1115 * handle parent in the second pass,
1116 * record we need one.
1121 if (FORCE && q->count != 0 ) {
1122 /* XXX should not happen! */
1123 printf("ipfw: OUCH! cannot remove rule,"
1124 " count %d\n", q->count);
1128 !TIME_LEQ( q->expire, time_uptime ))
1131 if (q->dyn_type != O_LIMIT_PARENT || !q->count) {
1132 UNLINK_DYN_RULE(prev, ipfw_dyn_v[i], q);
1140 if (pass++ < max_pass)
1146 * lookup a dynamic rule.
1148 static ipfw_dyn_rule *
1149 lookup_dyn_rule_locked(struct ipfw_flow_id *pkt, int *match_direction,
1153 * stateful ipfw extensions.
1154 * Lookup into dynamic session queue
1156 #define MATCH_REVERSE 0
1157 #define MATCH_FORWARD 1
1158 #define MATCH_NONE 2
1159 #define MATCH_UNKNOWN 3
1160 int i, dir = MATCH_NONE;
1161 ipfw_dyn_rule *prev, *q=NULL;
1163 IPFW_DYN_LOCK_ASSERT();
1165 if (ipfw_dyn_v == NULL)
1166 goto done; /* not found */
1167 i = hash_packet( pkt );
1168 for (prev=NULL, q = ipfw_dyn_v[i] ; q != NULL ; ) {
1169 if (q->dyn_type == O_LIMIT_PARENT && q->count)
1171 if (TIME_LEQ( q->expire, time_uptime)) { /* expire entry */
1172 UNLINK_DYN_RULE(prev, ipfw_dyn_v[i], q);
1175 if (pkt->proto == q->id.proto &&
1176 q->dyn_type != O_LIMIT_PARENT) {
1177 if (IS_IP6_FLOW_ID(pkt)) {
1178 if (IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
1179 &(q->id.src_ip6)) &&
1180 IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
1181 &(q->id.dst_ip6)) &&
1182 pkt->src_port == q->id.src_port &&
1183 pkt->dst_port == q->id.dst_port ) {
1184 dir = MATCH_FORWARD;
1187 if (IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
1188 &(q->id.dst_ip6)) &&
1189 IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
1190 &(q->id.src_ip6)) &&
1191 pkt->src_port == q->id.dst_port &&
1192 pkt->dst_port == q->id.src_port ) {
1193 dir = MATCH_REVERSE;
1197 if (pkt->src_ip == q->id.src_ip &&
1198 pkt->dst_ip == q->id.dst_ip &&
1199 pkt->src_port == q->id.src_port &&
1200 pkt->dst_port == q->id.dst_port ) {
1201 dir = MATCH_FORWARD;
1204 if (pkt->src_ip == q->id.dst_ip &&
1205 pkt->dst_ip == q->id.src_ip &&
1206 pkt->src_port == q->id.dst_port &&
1207 pkt->dst_port == q->id.src_port ) {
1208 dir = MATCH_REVERSE;
1218 goto done; /* q = NULL, not found */
1220 if ( prev != NULL) { /* found and not in front */
1221 prev->next = q->next;
1222 q->next = ipfw_dyn_v[i];
1225 if (pkt->proto == IPPROTO_TCP) { /* update state according to flags */
1226 u_char flags = pkt->flags & (TH_FIN|TH_SYN|TH_RST);
1228 #define BOTH_SYN (TH_SYN | (TH_SYN << 8))
1229 #define BOTH_FIN (TH_FIN | (TH_FIN << 8))
1230 q->state |= (dir == MATCH_FORWARD ) ? flags : (flags << 8);
1232 case TH_SYN: /* opening */
1233 q->expire = time_uptime + dyn_syn_lifetime;
1236 case BOTH_SYN: /* move to established */
1237 case BOTH_SYN | TH_FIN : /* one side tries to close */
1238 case BOTH_SYN | (TH_FIN << 8) :
1240 #define _SEQ_GE(a,b) ((int)(a) - (int)(b) >= 0)
1241 u_int32_t ack = ntohl(tcp->th_ack);
1242 if (dir == MATCH_FORWARD) {
1243 if (q->ack_fwd == 0 || _SEQ_GE(ack, q->ack_fwd))
1245 else { /* ignore out-of-sequence */
1249 if (q->ack_rev == 0 || _SEQ_GE(ack, q->ack_rev))
1251 else { /* ignore out-of-sequence */
1256 q->expire = time_uptime + dyn_ack_lifetime;
1259 case BOTH_SYN | BOTH_FIN: /* both sides closed */
1260 if (dyn_fin_lifetime >= dyn_keepalive_period)
1261 dyn_fin_lifetime = dyn_keepalive_period - 1;
1262 q->expire = time_uptime + dyn_fin_lifetime;
1268 * reset or some invalid combination, but can also
1269 * occur if we use keep-state the wrong way.
1271 if ( (q->state & ((TH_RST << 8)|TH_RST)) == 0)
1272 printf("invalid state: 0x%x\n", q->state);
1274 if (dyn_rst_lifetime >= dyn_keepalive_period)
1275 dyn_rst_lifetime = dyn_keepalive_period - 1;
1276 q->expire = time_uptime + dyn_rst_lifetime;
1279 } else if (pkt->proto == IPPROTO_UDP) {
1280 q->expire = time_uptime + dyn_udp_lifetime;
1282 /* other protocols */
1283 q->expire = time_uptime + dyn_short_lifetime;
1286 if (match_direction)
1287 *match_direction = dir;
1291 static ipfw_dyn_rule *
1292 lookup_dyn_rule(struct ipfw_flow_id *pkt, int *match_direction,
1298 q = lookup_dyn_rule_locked(pkt, match_direction, tcp);
1301 /* NB: return table locked when q is not NULL */
1306 realloc_dynamic_table(void)
1308 IPFW_DYN_LOCK_ASSERT();
1311 * Try reallocation, make sure we have a power of 2 and do
1312 * not allow more than 64k entries. In case of overflow,
1316 if (dyn_buckets > 65536)
1318 if ((dyn_buckets & (dyn_buckets-1)) != 0) { /* not a power of 2 */
1319 dyn_buckets = curr_dyn_buckets; /* reset */
1322 curr_dyn_buckets = dyn_buckets;
1323 if (ipfw_dyn_v != NULL)
1324 free(ipfw_dyn_v, M_IPFW);
1326 ipfw_dyn_v = malloc(curr_dyn_buckets * sizeof(ipfw_dyn_rule *),
1327 M_IPFW, M_NOWAIT | M_ZERO);
1328 if (ipfw_dyn_v != NULL || curr_dyn_buckets <= 2)
1330 curr_dyn_buckets /= 2;
1335 * Install state of type 'type' for a dynamic session.
1336 * The hash table contains two type of rules:
1337 * - regular rules (O_KEEP_STATE)
1338 * - rules for sessions with limited number of sess per user
1339 * (O_LIMIT). When they are created, the parent is
1340 * increased by 1, and decreased on delete. In this case,
1341 * the third parameter is the parent rule and not the chain.
1342 * - "parent" rules for the above (O_LIMIT_PARENT).
1344 static ipfw_dyn_rule *
1345 add_dyn_rule(struct ipfw_flow_id *id, u_int8_t dyn_type, struct ip_fw *rule)
1350 IPFW_DYN_LOCK_ASSERT();
1352 if (ipfw_dyn_v == NULL ||
1353 (dyn_count == 0 && dyn_buckets != curr_dyn_buckets)) {
1354 realloc_dynamic_table();
1355 if (ipfw_dyn_v == NULL)
1356 return NULL; /* failed ! */
1358 i = hash_packet(id);
1360 r = uma_zalloc(ipfw_dyn_rule_zone, M_NOWAIT | M_ZERO);
1362 printf ("ipfw: sorry cannot allocate state\n");
1366 /* increase refcount on parent, and set pointer */
1367 if (dyn_type == O_LIMIT) {
1368 ipfw_dyn_rule *parent = (ipfw_dyn_rule *)rule;
1369 if ( parent->dyn_type != O_LIMIT_PARENT)
1370 panic("invalid parent");
1373 rule = parent->rule;
1377 r->expire = time_uptime + dyn_syn_lifetime;
1379 r->dyn_type = dyn_type;
1380 r->pcnt = r->bcnt = 0;
1384 r->next = ipfw_dyn_v[i];
1387 DEB(printf("ipfw: add dyn entry ty %d 0x%08x %d -> 0x%08x %d, total %d\n",
1389 (r->id.src_ip), (r->id.src_port),
1390 (r->id.dst_ip), (r->id.dst_port),
1396 * lookup dynamic parent rule using pkt and rule as search keys.
1397 * If the lookup fails, then install one.
1399 static ipfw_dyn_rule *
1400 lookup_dyn_parent(struct ipfw_flow_id *pkt, struct ip_fw *rule)
1405 IPFW_DYN_LOCK_ASSERT();
1408 int is_v6 = IS_IP6_FLOW_ID(pkt);
1409 i = hash_packet( pkt );
1410 for (q = ipfw_dyn_v[i] ; q != NULL ; q=q->next)
1411 if (q->dyn_type == O_LIMIT_PARENT &&
1413 pkt->proto == q->id.proto &&
1414 pkt->src_port == q->id.src_port &&
1415 pkt->dst_port == q->id.dst_port &&
1418 IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
1419 &(q->id.src_ip6)) &&
1420 IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
1421 &(q->id.dst_ip6))) ||
1423 pkt->src_ip == q->id.src_ip &&
1424 pkt->dst_ip == q->id.dst_ip)
1427 q->expire = time_uptime + dyn_short_lifetime;
1428 DEB(printf("ipfw: lookup_dyn_parent found 0x%p\n",q);)
1432 return add_dyn_rule(pkt, O_LIMIT_PARENT, rule);
1436 * Install dynamic state for rule type cmd->o.opcode
1438 * Returns 1 (failure) if state is not installed because of errors or because
1439 * session limitations are enforced.
1442 install_state(struct ip_fw *rule, ipfw_insn_limit *cmd,
1443 struct ip_fw_args *args, uint32_t tablearg)
1445 static int last_log;
1448 char src[48], dst[48];
1454 printf("ipfw: %s: type %d 0x%08x %u -> 0x%08x %u\n",
1455 __func__, cmd->o.opcode,
1456 (args->f_id.src_ip), (args->f_id.src_port),
1457 (args->f_id.dst_ip), (args->f_id.dst_port));
1462 q = lookup_dyn_rule_locked(&args->f_id, NULL, NULL);
1464 if (q != NULL) { /* should never occur */
1465 if (last_log != time_uptime) {
1466 last_log = time_uptime;
1467 printf("ipfw: %s: entry already present, done\n",
1474 if (dyn_count >= dyn_max)
1475 /* Run out of slots, try to remove any expired rule. */
1476 remove_dyn_rule(NULL, (ipfw_dyn_rule *)1);
1478 if (dyn_count >= dyn_max) {
1479 if (last_log != time_uptime) {
1480 last_log = time_uptime;
1481 printf("ipfw: %s: Too many dynamic rules\n", __func__);
1484 return (1); /* cannot install, notify caller */
1487 switch (cmd->o.opcode) {
1488 case O_KEEP_STATE: /* bidir rule */
1489 add_dyn_rule(&args->f_id, O_KEEP_STATE, rule);
1492 case O_LIMIT: { /* limit number of sessions */
1493 struct ipfw_flow_id id;
1494 ipfw_dyn_rule *parent;
1495 uint32_t conn_limit;
1496 uint16_t limit_mask = cmd->limit_mask;
1498 conn_limit = (cmd->conn_limit == IP_FW_TABLEARG) ?
1499 tablearg : cmd->conn_limit;
1502 if (cmd->conn_limit == IP_FW_TABLEARG)
1503 printf("ipfw: %s: O_LIMIT rule, conn_limit: %u "
1504 "(tablearg)\n", __func__, conn_limit);
1506 printf("ipfw: %s: O_LIMIT rule, conn_limit: %u\n",
1507 __func__, conn_limit);
1510 id.dst_ip = id.src_ip = id.dst_port = id.src_port = 0;
1511 id.proto = args->f_id.proto;
1512 id.addr_type = args->f_id.addr_type;
1513 id.fib = M_GETFIB(args->m);
1515 if (IS_IP6_FLOW_ID (&(args->f_id))) {
1516 if (limit_mask & DYN_SRC_ADDR)
1517 id.src_ip6 = args->f_id.src_ip6;
1518 if (limit_mask & DYN_DST_ADDR)
1519 id.dst_ip6 = args->f_id.dst_ip6;
1521 if (limit_mask & DYN_SRC_ADDR)
1522 id.src_ip = args->f_id.src_ip;
1523 if (limit_mask & DYN_DST_ADDR)
1524 id.dst_ip = args->f_id.dst_ip;
1526 if (limit_mask & DYN_SRC_PORT)
1527 id.src_port = args->f_id.src_port;
1528 if (limit_mask & DYN_DST_PORT)
1529 id.dst_port = args->f_id.dst_port;
1530 if ((parent = lookup_dyn_parent(&id, rule)) == NULL) {
1531 printf("ipfw: %s: add parent failed\n", __func__);
1536 if (parent->count >= conn_limit) {
1537 /* See if we can remove some expired rule. */
1538 remove_dyn_rule(rule, parent);
1539 if (parent->count >= conn_limit) {
1540 if (fw_verbose && last_log != time_uptime) {
1541 last_log = time_uptime;
1544 * XXX IPv6 flows are not
1547 if (IS_IP6_FLOW_ID(&(args->f_id))) {
1548 char ip6buf[INET6_ADDRSTRLEN];
1549 snprintf(src, sizeof(src),
1550 "[%s]", ip6_sprintf(ip6buf,
1551 &args->f_id.src_ip6));
1552 snprintf(dst, sizeof(dst),
1553 "[%s]", ip6_sprintf(ip6buf,
1554 &args->f_id.dst_ip6));
1559 htonl(args->f_id.src_ip);
1560 inet_ntoa_r(da, src);
1562 htonl(args->f_id.dst_ip);
1563 inet_ntoa_r(da, dst);
1565 log(LOG_SECURITY | LOG_DEBUG,
1566 "ipfw: %d %s %s:%u -> %s:%u, %s\n",
1567 parent->rule->rulenum,
1569 src, (args->f_id.src_port),
1570 dst, (args->f_id.dst_port),
1571 "too many entries");
1577 add_dyn_rule(&args->f_id, O_LIMIT, (struct ip_fw *)parent);
1581 printf("ipfw: %s: unknown dynamic rule type %u\n",
1582 __func__, cmd->o.opcode);
1587 /* XXX just set lifetime */
1588 lookup_dyn_rule_locked(&args->f_id, NULL, NULL);
1595 * Generate a TCP packet, containing either a RST or a keepalive.
1596 * When flags & TH_RST, we are sending a RST packet, because of a
1597 * "reset" action matched the packet.
1598 * Otherwise we are sending a keepalive, and flags & TH_
1599 * The 'replyto' mbuf is the mbuf being replied to, if any, and is required
1600 * so that MAC can label the reply appropriately.
1602 static struct mbuf *
1603 send_pkt(struct mbuf *replyto, struct ipfw_flow_id *id, u_int32_t seq,
1604 u_int32_t ack, int flags)
1606 #if defined( __linux__ ) || defined( _WIN32 )
1613 MGETHDR(m, M_DONTWAIT, MT_DATA);
1616 m->m_pkthdr.rcvif = (struct ifnet *)0;
1618 M_SETFIB(m, id->fib);
1620 if (replyto != NULL)
1621 mac_create_mbuf_netlayer(replyto, m);
1623 mac_create_mbuf_from_firewall(m);
1625 (void)replyto; /* don't warn about unused arg */
1628 m->m_pkthdr.len = m->m_len = sizeof(struct ip) + sizeof(struct tcphdr);
1629 m->m_data += max_linkhdr;
1631 ip = mtod(m, struct ip *);
1632 bzero(ip, m->m_len);
1633 tcp = (struct tcphdr *)(ip + 1); /* no IP options */
1634 ip->ip_p = IPPROTO_TCP;
1637 * Assume we are sending a RST (or a keepalive in the reverse
1638 * direction), swap src and destination addresses and ports.
1640 ip->ip_src.s_addr = htonl(id->dst_ip);
1641 ip->ip_dst.s_addr = htonl(id->src_ip);
1642 tcp->th_sport = htons(id->dst_port);
1643 tcp->th_dport = htons(id->src_port);
1644 if (flags & TH_RST) { /* we are sending a RST */
1645 if (flags & TH_ACK) {
1646 tcp->th_seq = htonl(ack);
1647 tcp->th_ack = htonl(0);
1648 tcp->th_flags = TH_RST;
1652 tcp->th_seq = htonl(0);
1653 tcp->th_ack = htonl(seq);
1654 tcp->th_flags = TH_RST | TH_ACK;
1658 * We are sending a keepalive. flags & TH_SYN determines
1659 * the direction, forward if set, reverse if clear.
1660 * NOTE: seq and ack are always assumed to be correct
1661 * as set by the caller. This may be confusing...
1663 if (flags & TH_SYN) {
1665 * we have to rewrite the correct addresses!
1667 ip->ip_dst.s_addr = htonl(id->dst_ip);
1668 ip->ip_src.s_addr = htonl(id->src_ip);
1669 tcp->th_dport = htons(id->dst_port);
1670 tcp->th_sport = htons(id->src_port);
1672 tcp->th_seq = htonl(seq);
1673 tcp->th_ack = htonl(ack);
1674 tcp->th_flags = TH_ACK;
1677 * set ip_len to the payload size so we can compute
1678 * the tcp checksum on the pseudoheader
1679 * XXX check this, could save a couple of words ?
1681 ip->ip_len = htons(sizeof(struct tcphdr));
1682 tcp->th_sum = in_cksum(m, m->m_pkthdr.len);
1684 * now fill fields left out earlier
1686 ip->ip_ttl = ip_defttl;
1687 ip->ip_len = m->m_pkthdr.len;
1688 m->m_flags |= M_SKIP_FIREWALL;
1690 #endif /* !__linux__ */
1694 * sends a reject message, consuming the mbuf passed as an argument.
1697 send_reject(struct ip_fw_args *args, int code, int ip_len, struct ip *ip)
1701 /* XXX When ip is not guaranteed to be at mtod() we will
1702 * need to account for this */
1703 * The mbuf will however be thrown away so we can adjust it.
1704 * Remember we did an m_pullup on it already so we
1705 * can make some assumptions about contiguousness.
1708 m_adj(m, args->L3offset);
1710 if (code != ICMP_REJECT_RST) { /* Send an ICMP unreach */
1711 /* We need the IP header in host order for icmp_error(). */
1712 #if !defined( __linux__ ) && !defined( _WIN32 )
1713 if (args->eh != NULL) {
1714 ip->ip_len = ntohs(ip->ip_len);
1715 ip->ip_off = ntohs(ip->ip_off);
1718 icmp_error(args->m, ICMP_UNREACH, code, 0L, 0);
1719 } else if (args->f_id.proto == IPPROTO_TCP) {
1720 struct tcphdr *const tcp =
1721 L3HDR(struct tcphdr, mtod(args->m, struct ip *));
1722 if ( (tcp->th_flags & TH_RST) == 0) {
1724 m = send_pkt(args->m, &(args->f_id),
1725 ntohl(tcp->th_seq), ntohl(tcp->th_ack),
1726 tcp->th_flags | TH_RST);
1728 ip_output(m, NULL, NULL, 0, NULL, NULL);
1738 * Given an ip_fw *, lookup_next_rule will return a pointer
1739 * to the next rule, which can be either the jump
1740 * target (for skipto instructions) or the next one in the list (in
1741 * all other cases including a missing jump target).
1742 * The result is also written in the "next_rule" field of the rule.
1743 * Backward jumps are not allowed, so start looking from the next
1746 * This never returns NULL -- in case we do not have an exact match,
1747 * the next rule is returned. When the ruleset is changed,
1748 * pointers are flushed so we are always correct.
1751 static struct ip_fw *
1752 lookup_next_rule(struct ip_fw *me, u_int32_t tablearg)
1754 struct ip_fw *rule = NULL;
1758 /* look for action, in case it is a skipto */
1759 cmd = ACTION_PTR(me);
1760 if (cmd->opcode == O_LOG)
1762 if (cmd->opcode == O_ALTQ)
1764 if (cmd->opcode == O_TAG)
1766 if (cmd->opcode == O_SKIPTO ) {
1767 if (tablearg != 0) {
1768 rulenum = (u_int16_t)tablearg;
1770 rulenum = cmd->arg1;
1772 for (rule = me->next; rule ; rule = rule->next) {
1773 if (rule->rulenum >= rulenum) {
1778 if (rule == NULL) /* failure or not a skipto */
1780 me->next_rule = rule;
1786 add_table_entry(struct ip_fw_chain *ch, uint16_t tbl, in_addr_t addr,
1787 uint8_t mlen, uint32_t value)
1789 struct radix_node_head *rnh;
1790 struct table_entry *ent;
1791 struct radix_node *rn;
1793 if (tbl >= IPFW_TABLES_MAX)
1795 rnh = ch->tables[tbl];
1796 ent = malloc(sizeof(*ent), M_IPFW_TBL, M_NOWAIT | M_ZERO);
1800 ent->addr.sin_len = ent->mask.sin_len = 8;
1801 ent->mask.sin_addr.s_addr = htonl(mlen ? ~((1 << (32 - mlen)) - 1) : 0);
1802 ent->addr.sin_addr.s_addr = addr & ent->mask.sin_addr.s_addr;
1804 rn = rnh->rnh_addaddr(&ent->addr, &ent->mask, rnh, (void *)ent);
1807 free(ent, M_IPFW_TBL);
1815 del_table_entry(struct ip_fw_chain *ch, uint16_t tbl, in_addr_t addr,
1818 struct radix_node_head *rnh;
1819 struct table_entry *ent;
1820 struct sockaddr_in sa, mask;
1822 if (tbl >= IPFW_TABLES_MAX)
1824 rnh = ch->tables[tbl];
1825 sa.sin_len = mask.sin_len = 8;
1826 mask.sin_addr.s_addr = htonl(mlen ? ~((1 << (32 - mlen)) - 1) : 0);
1827 sa.sin_addr.s_addr = addr & mask.sin_addr.s_addr;
1829 ent = (struct table_entry *)rnh->rnh_deladdr(&sa, &mask, rnh);
1835 free(ent, M_IPFW_TBL);
1840 flush_table_entry(struct radix_node *rn, void *arg)
1842 struct radix_node_head * const rnh = arg;
1843 struct table_entry *ent;
1845 ent = (struct table_entry *)
1846 rnh->rnh_deladdr(rn->rn_key, rn->rn_mask, rnh);
1848 free(ent, M_IPFW_TBL);
1853 flush_table(struct ip_fw_chain *ch, uint16_t tbl)
1855 struct radix_node_head *rnh;
1857 IPFW_WLOCK_ASSERT(ch);
1859 if (tbl >= IPFW_TABLES_MAX)
1861 rnh = ch->tables[tbl];
1862 KASSERT(rnh != NULL, ("NULL IPFW table"));
1863 rnh->rnh_walktree(rnh, flush_table_entry, rnh);
1869 flush_tables(struct ip_fw_chain *ch)
1874 IPFW_WLOCK_ASSERT(ch);
1876 for (tbl = 0; tbl < IPFW_TABLES_MAX; tbl++)
1877 flush_table(ch, tbl);
1882 init_tables(struct ip_fw_chain *ch)
1888 for (i = 0; i < IPFW_TABLES_MAX; i++) {
1889 if (!rn_inithead((void **)&ch->tables[i], 32)) {
1890 for (j = 0; j < i; j++) {
1891 (void) flush_table(ch, j);
1901 lookup_table(struct ip_fw_chain *ch, uint16_t tbl, in_addr_t addr,
1905 struct radix_node_head *rnh;
1906 struct table_entry *ent;
1907 struct sockaddr_in sa;
1909 if (tbl >= IPFW_TABLES_MAX)
1911 rnh = ch->tables[tbl];
1913 sa.sin_addr.s_addr = addr;
1914 ent = (struct table_entry *)(rnh->rnh_lookup(&sa, NULL, rnh));
1925 count_table_entry(struct radix_node *rn, void *arg)
1927 u_int32_t * const cnt = arg;
1934 count_table(struct ip_fw_chain *ch, uint32_t tbl, uint32_t *cnt)
1936 struct radix_node_head *rnh;
1938 if (tbl >= IPFW_TABLES_MAX)
1940 rnh = ch->tables[tbl];
1942 rnh->rnh_walktree(rnh, count_table_entry, cnt);
1947 dump_table_entry(struct radix_node *rn, void *arg)
1949 struct table_entry * const n = (struct table_entry *)rn;
1950 ipfw_table * const tbl = arg;
1951 ipfw_table_entry *ent;
1953 if (tbl->cnt == tbl->size)
1955 ent = &tbl->ent[tbl->cnt];
1956 ent->tbl = tbl->tbl;
1957 if (in_nullhost(n->mask.sin_addr))
1960 ent->masklen = 33 - ffs(ntohl(n->mask.sin_addr.s_addr));
1961 ent->addr = n->addr.sin_addr.s_addr;
1962 ent->value = n->value;
1968 dump_table(struct ip_fw_chain *ch, ipfw_table *tbl)
1970 struct radix_node_head *rnh;
1972 if (tbl->tbl >= IPFW_TABLES_MAX)
1974 rnh = ch->tables[tbl->tbl];
1976 rnh->rnh_walktree(rnh, dump_table_entry, tbl);
1981 #ifndef linux /* FreeBSD */
1983 fill_ugid_cache(struct inpcb *inp, struct ip_fw_ugid *ugp)
1988 ugp->fw_prid = jailed(cr) ? cr->cr_prison->pr_id : -1;
1989 ugp->fw_uid = cr->cr_uid;
1990 ugp->fw_ngroups = cr->cr_ngroups;
1991 bcopy(cr->cr_groups, ugp->fw_groups, sizeof(ugp->fw_groups));
1996 check_uidgid(ipfw_insn_u32 *insn, int proto, struct ifnet *oif,
1997 struct in_addr dst_ip, u_int16_t dst_port, struct in_addr src_ip,
1998 u_int16_t src_port, struct ip_fw_ugid *ugp, int *ugid_lookupp,
2003 struct sk_buff *skb = ((struct mbuf *)inp)->m_skb;
2006 printf("%s opcode %d arg %d oif %p src 0x%x:%d dst 0x%x:%d\n", __FUNCTION__,
2007 insn->o.opcode, insn->d[0], oif,
2008 ntohl(src_ip.s_addr), ntohs(src_port),
2009 ntohl(dst_ip.s_addr), ntohs(dst_port)
2012 if (insn->o.opcode == O_JAIL) {
2013 #ifdef IPFW_PLANETLAB
2014 match = (skb->skb_tag == insn->d[0]);
2016 printf("JAIL compiled for planetlab xid %d want %d result %d\n",
2017 skb->skb_tag, insn->d[0], match);
2024 if (*ugid_lookupp == 0) { /* actively lookup and copy in cache */
2026 /* returns null if any element of the chain up to file is null.
2027 * if sk != NULL then we also have a reference
2029 *ugid_lookupp = linux_lookup(proto,
2030 src_ip.s_addr, htons(src_port),
2031 dst_ip.s_addr, htons(dst_port),
2032 skb, oif ? 1 : 0, ugp);
2035 if (*ugid_lookupp < 0)
2038 if (insn->o.opcode == O_UID)
2039 match = (ugp->fw_uid == (uid_t)insn->d[0]);
2044 struct inpcbinfo *pi;
2051 * Check to see if the UDP or TCP stack supplied us with
2052 * the PCB. If so, rather then holding a lock and looking
2053 * up the PCB, we can use the one that was supplied.
2055 if (inp && *ugid_lookupp == 0) {
2056 INP_LOCK_ASSERT(inp);
2057 if (inp->inp_socket != NULL) {
2058 fill_ugid_cache(inp, ugp);
2064 * If we have already been here and the packet has no
2065 * PCB entry associated with it, then we can safely
2066 * assume that this is a no match.
2068 if (*ugid_lookupp == -1)
2070 if (proto == IPPROTO_TCP) {
2073 } else if (proto == IPPROTO_UDP) {
2074 wildcard = INPLOOKUP_WILDCARD;
2079 if (*ugid_lookupp == 0) {
2082 in_pcblookup_hash(pi,
2083 dst_ip, htons(dst_port),
2084 src_ip, htons(src_port),
2086 in_pcblookup_hash(pi,
2087 src_ip, htons(src_port),
2088 dst_ip, htons(dst_port),
2091 fill_ugid_cache(pcb, ugp);
2094 INP_INFO_RUNLOCK(pi);
2095 if (*ugid_lookupp == 0) {
2097 * If the lookup did not yield any results, there
2098 * is no sense in coming back and trying again. So
2099 * we can set lookup to -1 and ensure that we wont
2100 * bother the pcb system again.
2106 if (insn->o.opcode == O_UID)
2107 match = (ugp->fw_uid == (uid_t)insn->d[0]);
2108 else if (insn->o.opcode == O_GID) {
2109 for (gp = ugp->fw_groups;
2110 gp < &ugp->fw_groups[ugp->fw_ngroups]; gp++)
2111 if (*gp == (gid_t)insn->d[0]) {
2115 } else if (insn->o.opcode == O_JAIL)
2116 match = (ugp->fw_prid == (int)insn->d[0]);
2122 * The main check routine for the firewall.
2124 * All arguments are in args so we can modify them and return them
2125 * back to the caller.
2129 * args->m (in/out) The packet; we set to NULL when/if we nuke it.
2130 * Starts with the IP header.
2131 * args->eh (in) Mac header if present, or NULL for layer3 packet.
2132 * args->L3offset Number of bytes bypassed if we came from L2.
2133 * e.g. often sizeof(eh) ** NOTYET **
2134 * args->oif Outgoing interface, or NULL if packet is incoming.
2135 * The incoming interface is in the mbuf. (in)
2136 * args->divert_rule (in/out)
2137 * Skip up to the first rule past this rule number;
2138 * upon return, non-zero port number for divert or tee.
2140 * args->rule Pointer to the last matching rule (in/out)
2141 * args->next_hop Socket we are forwarding to (out).
2142 * args->f_id Addresses grabbed from the packet (out)
2143 * args->cookie a cookie depending on rule action
2147 * IP_FW_PASS the packet must be accepted
2148 * IP_FW_DENY the packet must be dropped
2149 * IP_FW_DIVERT divert packet, port in m_tag
2150 * IP_FW_TEE tee packet, port in m_tag
2151 * IP_FW_DUMMYNET to dummynet, pipe in args->cookie
2152 * IP_FW_NETGRAPH into netgraph, cookie args->cookie
2156 ipfw_chk(struct ip_fw_args *args)
2159 * Local variables holding state during the processing of a packet:
2161 * IMPORTANT NOTE: to speed up the processing of rules, there
2162 * are some assumption on the values of the variables, which
2163 * are documented here. Should you change them, please check
2164 * the implementation of the various instructions to make sure
2165 * that they still work.
2167 * args->eh The MAC header. It is non-null for a layer2
2168 * packet, it is NULL for a layer-3 packet.
2170 * args->L3offset Offset in the packet to the L3 (IP or equiv.) header.
2172 * m | args->m Pointer to the mbuf, as received from the caller.
2173 * It may change if ipfw_chk() does an m_pullup, or if it
2174 * consumes the packet because it calls send_reject().
2175 * XXX This has to change, so that ipfw_chk() never modifies
2176 * or consumes the buffer.
2177 * ip is the beginning of the ip(4 or 6) header.
2178 * Calculated by adding the L3offset to the start of data.
2179 * (Until we start using L3offset, the packet is
2180 * supposed to start with the ip header).
2182 struct mbuf *m = args->m;
2183 struct ip *ip = mtod(m, struct ip *);
2186 * For rules which contain uid/gid or jail constraints, cache
2187 * a copy of the users credentials after the pcb lookup has been
2188 * executed. This will speed up the processing of rules with
2189 * these types of constraints, as well as decrease contention
2190 * on pcb related locks.
2192 struct ip_fw_ugid fw_ugid_cache;
2193 int ugid_lookup = 0;
2196 * divinput_flags If non-zero, set to the IP_FW_DIVERT_*_FLAG
2197 * associated with a packet input on a divert socket. This
2198 * will allow to distinguish traffic and its direction when
2199 * it originates from a divert socket.
2201 u_int divinput_flags = 0;
2204 * oif | args->oif If NULL, ipfw_chk has been called on the
2205 * inbound path (ether_input, ip_input).
2206 * If non-NULL, ipfw_chk has been called on the outbound path
2207 * (ether_output, ip_output).
2209 struct ifnet *oif = args->oif;
2211 struct ip_fw *f = NULL; /* matching rule */
2215 * hlen The length of the IP header.
2217 u_int hlen = 0; /* hlen >0 means we have an IP pkt */
2220 * offset The offset of a fragment. offset != 0 means that
2221 * we have a fragment at this offset of an IPv4 packet.
2222 * offset == 0 means that (if this is an IPv4 packet)
2223 * this is the first or only fragment.
2224 * For IPv6 offset == 0 means there is no Fragment Header.
2225 * If offset != 0 for IPv6 always use correct mask to
2226 * get the correct offset because we add IP6F_MORE_FRAG
2227 * to be able to dectect the first fragment which would
2228 * otherwise have offset = 0.
2233 * Local copies of addresses. They are only valid if we have
2236 * proto The protocol. Set to 0 for non-ip packets,
2237 * or to the protocol read from the packet otherwise.
2238 * proto != 0 means that we have an IPv4 packet.
2240 * src_port, dst_port port numbers, in HOST format. Only
2241 * valid for TCP and UDP packets.
2243 * src_ip, dst_ip ip addresses, in NETWORK format.
2244 * Only valid for IPv4 packets.
2247 u_int16_t src_port = 0, dst_port = 0; /* NOTE: host format */
2248 struct in_addr src_ip, dst_ip; /* NOTE: network format */
2251 u_int16_t etype = 0; /* Host order stored ether type */
2254 * dyn_dir = MATCH_UNKNOWN when rules unchecked,
2255 * MATCH_NONE when checked and not matched (q = NULL),
2256 * MATCH_FORWARD or MATCH_REVERSE otherwise (q != NULL)
2258 int dyn_dir = MATCH_UNKNOWN;
2259 ipfw_dyn_rule *q = NULL;
2260 struct ip_fw_chain *chain = &layer3_chain;
2264 * We store in ulp a pointer to the upper layer protocol header.
2265 * In the ipv4 case this is easy to determine from the header,
2266 * but for ipv6 we might have some additional headers in the middle.
2267 * ulp is NULL if not found.
2269 void *ulp = NULL; /* upper layer protocol pointer. */
2270 /* XXX ipv6 variables */
2272 u_int16_t ext_hd = 0; /* bits vector for extension header filtering */
2273 /* end of ipv6 variables */
2276 if (m->m_flags & M_SKIP_FIREWALL)
2277 return (IP_FW_PASS); /* accept */
2279 dst_ip.s_addr = 0; /* make sure it is initialized */
2280 src_ip.s_addr = 0; /* make sure it is initialized */
2281 pktlen = m->m_pkthdr.len;
2282 args->f_id.fib = M_GETFIB(m); /* note mbuf not altered) */
2283 proto = args->f_id.proto = 0; /* mark f_id invalid */
2284 /* XXX 0 is a valid proto: IP/IPv6 Hop-by-Hop Option */
2287 * PULLUP_TO(len, p, T) makes sure that len + sizeof(T) is contiguous,
2288 * then it sets p to point at the offset "len" in the mbuf. WARNING: the
2289 * pointer might become stale after other pullups (but we never use it
2292 #define PULLUP_TO(_len, p, T) \
2294 int x = (_len) + sizeof(T); \
2295 if ((m)->m_len < x) { \
2296 goto pullup_failed; \
2298 p = (mtod(m, char *) + (_len)); \
2302 * if we have an ether header,
2305 etype = ntohs(args->eh->ether_type);
2307 /* Identify IP packets and fill up variables. */
2308 if (pktlen >= sizeof(struct ip6_hdr) &&
2309 (args->eh == NULL || etype == ETHERTYPE_IPV6) && ip->ip_v == 6) {
2310 struct ip6_hdr *ip6 = (struct ip6_hdr *)ip;
2312 args->f_id.addr_type = 6;
2313 hlen = sizeof(struct ip6_hdr);
2314 proto = ip6->ip6_nxt;
2316 /* Search extension headers to find upper layer protocols */
2317 while (ulp == NULL) {
2319 case IPPROTO_ICMPV6:
2320 PULLUP_TO(hlen, ulp, struct icmp6_hdr);
2321 args->f_id.flags = ICMP6(ulp)->icmp6_type;
2325 PULLUP_TO(hlen, ulp, struct tcphdr);
2326 dst_port = TCP(ulp)->th_dport;
2327 src_port = TCP(ulp)->th_sport;
2328 args->f_id.flags = TCP(ulp)->th_flags;
2332 PULLUP_TO(hlen, ulp, struct sctphdr);
2333 src_port = SCTP(ulp)->src_port;
2334 dst_port = SCTP(ulp)->dest_port;
2338 PULLUP_TO(hlen, ulp, struct udphdr);
2339 dst_port = UDP(ulp)->uh_dport;
2340 src_port = UDP(ulp)->uh_sport;
2343 case IPPROTO_HOPOPTS: /* RFC 2460 */
2344 PULLUP_TO(hlen, ulp, struct ip6_hbh);
2345 ext_hd |= EXT_HOPOPTS;
2346 hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3;
2347 proto = ((struct ip6_hbh *)ulp)->ip6h_nxt;
2351 case IPPROTO_ROUTING: /* RFC 2460 */
2352 PULLUP_TO(hlen, ulp, struct ip6_rthdr);
2353 switch (((struct ip6_rthdr *)ulp)->ip6r_type) {
2355 ext_hd |= EXT_RTHDR0;
2358 ext_hd |= EXT_RTHDR2;
2361 printf("IPFW2: IPV6 - Unknown Routing "
2362 "Header type(%d)\n",
2363 ((struct ip6_rthdr *)ulp)->ip6r_type);
2364 if (fw_deny_unknown_exthdrs)
2365 return (IP_FW_DENY);
2368 ext_hd |= EXT_ROUTING;
2369 hlen += (((struct ip6_rthdr *)ulp)->ip6r_len + 1) << 3;
2370 proto = ((struct ip6_rthdr *)ulp)->ip6r_nxt;
2374 case IPPROTO_FRAGMENT: /* RFC 2460 */
2375 PULLUP_TO(hlen, ulp, struct ip6_frag);
2376 ext_hd |= EXT_FRAGMENT;
2377 hlen += sizeof (struct ip6_frag);
2378 proto = ((struct ip6_frag *)ulp)->ip6f_nxt;
2379 offset = ((struct ip6_frag *)ulp)->ip6f_offlg &
2381 /* Add IP6F_MORE_FRAG for offset of first
2382 * fragment to be != 0. */
2383 offset |= ((struct ip6_frag *)ulp)->ip6f_offlg &
2386 printf("IPFW2: IPV6 - Invalid Fragment "
2388 if (fw_deny_unknown_exthdrs)
2389 return (IP_FW_DENY);
2392 args->f_id.frag_id6 =
2393 ntohl(((struct ip6_frag *)ulp)->ip6f_ident);
2397 case IPPROTO_DSTOPTS: /* RFC 2460 */
2398 PULLUP_TO(hlen, ulp, struct ip6_hbh);
2399 ext_hd |= EXT_DSTOPTS;
2400 hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3;
2401 proto = ((struct ip6_hbh *)ulp)->ip6h_nxt;
2405 case IPPROTO_AH: /* RFC 2402 */
2406 PULLUP_TO(hlen, ulp, struct ip6_ext);
2408 hlen += (((struct ip6_ext *)ulp)->ip6e_len + 2) << 2;
2409 proto = ((struct ip6_ext *)ulp)->ip6e_nxt;
2413 case IPPROTO_ESP: /* RFC 2406 */
2414 PULLUP_TO(hlen, ulp, uint32_t); /* SPI, Seq# */
2415 /* Anything past Seq# is variable length and
2416 * data past this ext. header is encrypted. */
2420 case IPPROTO_NONE: /* RFC 2460 */
2422 * Packet ends here, and IPv6 header has
2423 * already been pulled up. If ip6e_len!=0
2424 * then octets must be ignored.
2426 ulp = ip; /* non-NULL to get out of loop. */
2429 case IPPROTO_OSPFIGP:
2430 /* XXX OSPF header check? */
2431 PULLUP_TO(hlen, ulp, struct ip6_ext);
2435 /* XXX PIM header check? */
2436 PULLUP_TO(hlen, ulp, struct pim);
2440 PULLUP_TO(hlen, ulp, struct carp_header);
2441 if (((struct carp_header *)ulp)->carp_version !=
2443 return (IP_FW_DENY);
2444 if (((struct carp_header *)ulp)->carp_type !=
2446 return (IP_FW_DENY);
2449 case IPPROTO_IPV6: /* RFC 2893 */
2450 PULLUP_TO(hlen, ulp, struct ip6_hdr);
2453 case IPPROTO_IPV4: /* RFC 2893 */
2454 PULLUP_TO(hlen, ulp, struct ip);
2458 printf("IPFW2: IPV6 - Unknown Extension "
2459 "Header(%d), ext_hd=%x\n", proto, ext_hd);
2460 if (fw_deny_unknown_exthdrs)
2461 return (IP_FW_DENY);
2462 PULLUP_TO(hlen, ulp, struct ip6_ext);
2466 ip = mtod(m, struct ip *);
2467 ip6 = (struct ip6_hdr *)ip;
2468 args->f_id.src_ip6 = ip6->ip6_src;
2469 args->f_id.dst_ip6 = ip6->ip6_dst;
2470 args->f_id.src_ip = 0;
2471 args->f_id.dst_ip = 0;
2472 args->f_id.flow_id6 = ntohl(ip6->ip6_flow);
2473 } else if (pktlen >= sizeof(struct ip) &&
2474 (args->eh == NULL || etype == ETHERTYPE_IP) && ip->ip_v == 4) {
2476 hlen = ip->ip_hl << 2;
2477 args->f_id.addr_type = 4;
2480 * Collect parameters into local variables for faster matching.
2483 src_ip = ip->ip_src;
2484 dst_ip = ip->ip_dst;
2486 if (1 || args->eh != NULL) { /* layer 2 packets are as on the wire */
2487 offset = ntohs(ip->ip_off) & IP_OFFMASK;
2488 ip_len = ntohs(ip->ip_len);
2490 offset = ip->ip_off & IP_OFFMASK;
2491 ip_len = ip->ip_len;
2493 pktlen = ip_len < pktlen ? ip_len : pktlen;
2498 PULLUP_TO(hlen, ulp, struct tcphdr);
2499 dst_port = TCP(ulp)->th_dport;
2500 src_port = TCP(ulp)->th_sport;
2501 args->f_id.flags = TCP(ulp)->th_flags;
2505 PULLUP_TO(hlen, ulp, struct udphdr);
2506 dst_port = UDP(ulp)->uh_dport;
2507 src_port = UDP(ulp)->uh_sport;
2511 PULLUP_TO(hlen, ulp, struct icmphdr);
2512 args->f_id.flags = ICMP(ulp)->icmp_type;
2520 ip = mtod(m, struct ip *);
2521 args->f_id.src_ip = ntohl(src_ip.s_addr);
2522 args->f_id.dst_ip = ntohl(dst_ip.s_addr);
2525 if (proto) { /* we may have port numbers, store them */
2526 args->f_id.proto = proto;
2527 args->f_id.src_port = src_port = ntohs(src_port);
2528 args->f_id.dst_port = dst_port = ntohs(dst_port);
2532 mtag = m_tag_find(m, PACKET_TAG_DIVERT, NULL);
2535 * Packet has already been tagged. Look for the next rule
2536 * to restart processing.
2538 * If fw_one_pass != 0 then just accept it.
2539 * XXX should not happen here, but optimized out in
2543 IPFW_RUNLOCK(chain);
2544 return (IP_FW_PASS);
2547 f = args->rule->next_rule;
2549 f = lookup_next_rule(args->rule, 0);
2552 * Find the starting rule. It can be either the first
2553 * one, or the one after divert_rule if asked so.
2555 int skipto = mtag ? divert_cookie(mtag) : 0;
2558 if (args->eh == NULL && skipto != 0) {
2559 if (skipto >= IPFW_DEFAULT_RULE) {
2560 IPFW_RUNLOCK(chain);
2561 return (IP_FW_DENY); /* invalid */
2563 while (f && f->rulenum <= skipto)
2565 if (f == NULL) { /* drop packet */
2566 IPFW_RUNLOCK(chain);
2567 return (IP_FW_DENY);
2571 /* reset divert rule to avoid confusion later */
2573 divinput_flags = divert_info(mtag) &
2574 (IP_FW_DIVERT_OUTPUT_FLAG | IP_FW_DIVERT_LOOPBACK_FLAG);
2575 m_tag_delete(m, mtag);
2579 * Now scan the rules, and parse microinstructions for each rule.
2581 for (; f; f = f->next) {
2583 uint32_t tablearg = 0;
2584 int l, cmdlen, skip_or; /* skip rest of OR block */
2587 if (set_disable & (1 << f->set) )
2591 for (l = f->cmd_len, cmd = f->cmd ; l > 0 ;
2592 l -= cmdlen, cmd += cmdlen) {
2596 * check_body is a jump target used when we find a
2597 * CHECK_STATE, and need to jump to the body of
2602 cmdlen = F_LEN(cmd);
2604 * An OR block (insn_1 || .. || insn_n) has the
2605 * F_OR bit set in all but the last instruction.
2606 * The first match will set "skip_or", and cause
2607 * the following instructions to be skipped until
2608 * past the one with the F_OR bit clear.
2610 if (skip_or) { /* skip this instruction */
2611 if ((cmd->len & F_OR) == 0)
2612 skip_or = 0; /* next one is good */
2615 match = 0; /* set to 1 if we succeed */
2617 switch (cmd->opcode) {
2619 * The first set of opcodes compares the packet's
2620 * fields with some pattern, setting 'match' if a
2621 * match is found. At the end of the loop there is
2622 * logic to deal with F_NOT and F_OR flags associated
2630 printf("ipfw: opcode %d unimplemented\n",
2638 * We only check offset == 0 && proto != 0,
2639 * as this ensures that we have a
2640 * packet with the ports info.
2644 if (is_ipv6) /* XXX to be fixed later */
2646 if (proto == IPPROTO_TCP ||
2647 proto == IPPROTO_UDP)
2648 match = check_uidgid(
2649 (ipfw_insn_u32 *)cmd,
2652 src_ip, src_port, &fw_ugid_cache,
2653 &ugid_lookup, (struct inpcb *)args->m);
2657 match = iface_match(m->m_pkthdr.rcvif,
2658 (ipfw_insn_if *)cmd);
2662 match = iface_match(oif, (ipfw_insn_if *)cmd);
2666 match = iface_match(oif ? oif :
2667 m->m_pkthdr.rcvif, (ipfw_insn_if *)cmd);
2671 if (args->eh != NULL) { /* have MAC header */
2672 u_int32_t *want = (u_int32_t *)
2673 ((ipfw_insn_mac *)cmd)->addr;
2674 u_int32_t *mask = (u_int32_t *)
2675 ((ipfw_insn_mac *)cmd)->mask;
2676 u_int32_t *hdr = (u_int32_t *)args->eh;
2679 ( want[0] == (hdr[0] & mask[0]) &&
2680 want[1] == (hdr[1] & mask[1]) &&
2681 want[2] == (hdr[2] & mask[2]) );
2686 if (args->eh != NULL) {
2688 ((ipfw_insn_u16 *)cmd)->ports;
2691 for (i = cmdlen - 1; !match && i>0;
2693 match = (etype >= p[0] &&
2699 match = (offset != 0);
2702 case O_IN: /* "out" is "not in" */
2703 match = (oif == NULL);
2707 match = (args->eh != NULL);
2711 match = (cmd->arg1 & 1 && divinput_flags &
2712 IP_FW_DIVERT_LOOPBACK_FLAG) ||
2713 (cmd->arg1 & 2 && divinput_flags &
2714 IP_FW_DIVERT_OUTPUT_FLAG);
2719 * We do not allow an arg of 0 so the
2720 * check of "proto" only suffices.
2722 match = (proto == cmd->arg1);
2727 (((ipfw_insn_ip *)cmd)->addr.s_addr ==
2731 case O_IP_SRC_LOOKUP:
2732 case O_IP_DST_LOOKUP:
2735 (cmd->opcode == O_IP_DST_LOOKUP) ?
2736 dst_ip.s_addr : src_ip.s_addr;
2739 match = lookup_table(chain, cmd->arg1, a,
2743 if (cmdlen == F_INSN_SIZE(ipfw_insn_u32))
2745 ((ipfw_insn_u32 *)cmd)->d[0] == v;
2755 (cmd->opcode == O_IP_DST_MASK) ?
2756 dst_ip.s_addr : src_ip.s_addr;
2757 uint32_t *p = ((ipfw_insn_u32 *)cmd)->d;
2760 for (; !match && i>0; i-= 2, p+= 2)
2761 match = (p[0] == (a & p[1]));
2769 INADDR_TO_IFP(src_ip, tif);
2770 match = (tif != NULL);
2777 u_int32_t *d = (u_int32_t *)(cmd+1);
2779 cmd->opcode == O_IP_DST_SET ?
2785 addr -= d[0]; /* subtract base */
2786 match = (addr < cmd->arg1) &&
2787 ( d[ 1 + (addr>>5)] &
2788 (1<<(addr & 0x1f)) );
2794 (((ipfw_insn_ip *)cmd)->addr.s_addr ==
2802 INADDR_TO_IFP(dst_ip, tif);
2803 match = (tif != NULL);
2810 * offset == 0 && proto != 0 is enough
2811 * to guarantee that we have a
2812 * packet with port info.
2814 if ((proto==IPPROTO_UDP || proto==IPPROTO_TCP)
2817 (cmd->opcode == O_IP_SRCPORT) ?
2818 src_port : dst_port ;
2820 ((ipfw_insn_u16 *)cmd)->ports;
2823 for (i = cmdlen - 1; !match && i>0;
2825 match = (x>=p[0] && x<=p[1]);
2830 match = (offset == 0 && proto==IPPROTO_ICMP &&
2831 icmptype_match(ICMP(ulp), (ipfw_insn_u32 *)cmd) );
2836 match = is_ipv6 && offset == 0 &&
2837 proto==IPPROTO_ICMPV6 &&
2839 ICMP6(ulp)->icmp6_type,
2840 (ipfw_insn_u32 *)cmd);
2846 ipopts_match(ip, cmd) );
2851 cmd->arg1 == ip->ip_v);
2857 if (is_ipv4) { /* only for IP packets */
2862 if (cmd->opcode == O_IPLEN)
2864 else if (cmd->opcode == O_IPTTL)
2866 else /* must be IPID */
2867 x = ntohs(ip->ip_id);
2869 match = (cmd->arg1 == x);
2872 /* otherwise we have ranges */
2873 p = ((ipfw_insn_u16 *)cmd)->ports;
2875 for (; !match && i>0; i--, p += 2)
2876 match = (x >= p[0] && x <= p[1]);
2880 case O_IPPRECEDENCE:
2882 (cmd->arg1 == (ip->ip_tos & 0xe0)) );
2887 flags_match(cmd, ip->ip_tos));
2891 if (proto == IPPROTO_TCP && offset == 0) {
2899 ((ip->ip_hl + tcp->th_off) << 2);
2901 match = (cmd->arg1 == x);
2904 /* otherwise we have ranges */
2905 p = ((ipfw_insn_u16 *)cmd)->ports;
2907 for (; !match && i>0; i--, p += 2)
2908 match = (x >= p[0] && x <= p[1]);
2913 match = (proto == IPPROTO_TCP && offset == 0 &&
2914 flags_match(cmd, TCP(ulp)->th_flags));
2918 match = (proto == IPPROTO_TCP && offset == 0 &&
2919 tcpopts_match(TCP(ulp), cmd));
2923 match = (proto == IPPROTO_TCP && offset == 0 &&
2924 ((ipfw_insn_u32 *)cmd)->d[0] ==
2929 match = (proto == IPPROTO_TCP && offset == 0 &&
2930 ((ipfw_insn_u32 *)cmd)->d[0] ==
2935 match = (proto == IPPROTO_TCP && offset == 0 &&
2936 cmd->arg1 == TCP(ulp)->th_win);
2940 /* reject packets which have SYN only */
2941 /* XXX should i also check for TH_ACK ? */
2942 match = (proto == IPPROTO_TCP && offset == 0 &&
2943 (TCP(ulp)->th_flags &
2944 (TH_RST | TH_ACK | TH_SYN)) != TH_SYN);
2949 ipfw_insn_altq *altq = (ipfw_insn_altq *)cmd;
2952 at = pf_find_mtag(m);
2953 if (at != NULL && at->qid != 0)
2955 at = pf_get_mtag(m);
2958 * Let the packet fall back to the
2963 at->qid = altq->qid;
2974 ipfw_log(f, hlen, args, m,
2975 oif, offset, tablearg, ip);
2980 match = (random()<((ipfw_insn_u32 *)cmd)->d[0]);
2985 /* Outgoing packets automatically pass/match */
2986 match = ((oif != NULL) ||
2987 (m->m_pkthdr.rcvif == NULL) ||
2991 verify_path6(&(args->f_id.src_ip6),
2992 m->m_pkthdr.rcvif) :
2994 verify_path(src_ip, m->m_pkthdr.rcvif,
2999 /* Outgoing packets automatically pass/match */
3000 match = (hlen > 0 && ((oif != NULL) ||
3003 verify_path6(&(args->f_id.src_ip6),
3006 verify_path(src_ip, NULL, args->f_id.fib)));
3010 /* Outgoing packets automatically pass/match */
3011 if (oif == NULL && hlen > 0 &&
3012 ( (is_ipv4 && in_localaddr(src_ip))
3015 in6_localaddr(&(args->f_id.src_ip6)))
3020 is_ipv6 ? verify_path6(
3021 &(args->f_id.src_ip6),
3022 m->m_pkthdr.rcvif) :
3034 match = (m_tag_find(m,
3035 PACKET_TAG_IPSEC_IN_DONE, NULL) != NULL);
3037 /* otherwise no match */
3043 IN6_ARE_ADDR_EQUAL(&args->f_id.src_ip6,
3044 &((ipfw_insn_ip6 *)cmd)->addr6);
3049 IN6_ARE_ADDR_EQUAL(&args->f_id.dst_ip6,
3050 &((ipfw_insn_ip6 *)cmd)->addr6);
3052 case O_IP6_SRC_MASK:
3053 case O_IP6_DST_MASK:
3057 struct in6_addr *d =
3058 &((ipfw_insn_ip6 *)cmd)->addr6;
3060 for (; !match && i > 0; d += 2,
3061 i -= F_INSN_SIZE(struct in6_addr)
3067 APPLY_MASK(&p, &d[1]);
3069 IN6_ARE_ADDR_EQUAL(&d[0],
3076 match= is_ipv6 && search_ip6_addr_net(&args->f_id.src_ip6);
3080 match= is_ipv6 && search_ip6_addr_net(&args->f_id.dst_ip6);
3085 flow6id_match(args->f_id.flow_id6,
3086 (ipfw_insn_u32 *) cmd);
3091 (ext_hd & ((ipfw_insn *) cmd)->arg1);
3105 uint32_t tag = (cmd->arg1 == IP_FW_TABLEARG) ?
3106 tablearg : cmd->arg1;
3108 /* Packet is already tagged with this tag? */
3109 mtag = m_tag_locate(m, MTAG_IPFW, tag, NULL);
3111 /* We have `untag' action when F_NOT flag is
3112 * present. And we must remove this mtag from
3113 * mbuf and reset `match' to zero (`match' will
3114 * be inversed later).
3115 * Otherwise we should allocate new mtag and
3116 * push it into mbuf.
3118 if (cmd->len & F_NOT) { /* `untag' action */
3120 m_tag_delete(m, mtag);
3121 } else if (mtag == NULL) {
3122 if ((mtag = m_tag_alloc(MTAG_IPFW,
3123 tag, 0, M_NOWAIT)) != NULL)
3124 m_tag_prepend(m, mtag);
3126 match = (cmd->len & F_NOT) ? 0: 1;
3130 case O_FIB: /* try match the specified fib */
3131 if (args->f_id.fib == cmd->arg1)
3136 uint32_t tag = (cmd->arg1 == IP_FW_TABLEARG) ?
3137 tablearg : cmd->arg1;
3140 match = m_tag_locate(m, MTAG_IPFW,
3145 /* we have ranges */
3146 for (mtag = m_tag_first(m);
3147 mtag != NULL && !match;
3148 mtag = m_tag_next(m, mtag)) {
3152 if (mtag->m_tag_cookie != MTAG_IPFW)
3155 p = ((ipfw_insn_u16 *)cmd)->ports;
3157 for(; !match && i > 0; i--, p += 2)
3159 mtag->m_tag_id >= p[0] &&
3160 mtag->m_tag_id <= p[1];
3167 * The second set of opcodes represents 'actions',
3168 * i.e. the terminal part of a rule once the packet
3169 * matches all previous patterns.
3170 * Typically there is only one action for each rule,
3171 * and the opcode is stored at the end of the rule
3172 * (but there are exceptions -- see below).
3174 * In general, here we set retval and terminate the
3175 * outer loop (would be a 'break 3' in some language,
3176 * but we need to do a 'goto done').
3179 * O_COUNT and O_SKIPTO actions:
3180 * instead of terminating, we jump to the next rule
3181 * ('goto next_rule', equivalent to a 'break 2'),
3182 * or to the SKIPTO target ('goto again' after
3183 * having set f, cmd and l), respectively.
3185 * O_TAG, O_LOG and O_ALTQ action parameters:
3186 * perform some action and set match = 1;
3188 * O_LIMIT and O_KEEP_STATE: these opcodes are
3189 * not real 'actions', and are stored right
3190 * before the 'action' part of the rule.
3191 * These opcodes try to install an entry in the
3192 * state tables; if successful, we continue with
3193 * the next opcode (match=1; break;), otherwise
3194 * the packet * must be dropped
3195 * ('goto done' after setting retval);
3197 * O_PROBE_STATE and O_CHECK_STATE: these opcodes
3198 * cause a lookup of the state table, and a jump
3199 * to the 'action' part of the parent rule
3200 * ('goto check_body') if an entry is found, or
3201 * (CHECK_STATE only) a jump to the next rule if
3202 * the entry is not found ('goto next_rule').
3203 * The result of the lookup is cached to make
3204 * further instances of these opcodes are
3209 if (install_state(f,
3210 (ipfw_insn_limit *)cmd, args, tablearg)) {
3211 retval = IP_FW_DENY;
3212 goto done; /* error/limit violation */
3220 * dynamic rules are checked at the first
3221 * keep-state or check-state occurrence,
3222 * with the result being stored in dyn_dir.
3223 * The compiler introduces a PROBE_STATE
3224 * instruction for us when we have a
3225 * KEEP_STATE (because PROBE_STATE needs
3228 if (dyn_dir == MATCH_UNKNOWN &&
3229 (q = lookup_dyn_rule(&args->f_id,
3230 &dyn_dir, proto == IPPROTO_TCP ?
3234 * Found dynamic entry, update stats
3235 * and jump to the 'action' part of
3241 cmd = ACTION_PTR(f);
3242 l = f->cmd_len - f->act_ofs;
3247 * Dynamic entry not found. If CHECK_STATE,
3248 * skip to next rule, if PROBE_STATE just
3249 * ignore and continue with next opcode.
3251 if (cmd->opcode == O_CHECK_STATE)
3257 retval = 0; /* accept */
3262 args->rule = f; /* report matching rule */
3263 if (cmd->arg1 == IP_FW_TABLEARG)
3264 args->cookie = tablearg;
3266 args->cookie = cmd->arg1;
3267 retval = IP_FW_DUMMYNET;
3273 struct divert_tag *dt;
3275 if (args->eh) /* not on layer 2 */
3277 mtag = m_tag_get(PACKET_TAG_DIVERT,
3278 sizeof(struct divert_tag),
3283 IPFW_RUNLOCK(chain);
3284 return (IP_FW_DENY);
3286 dt = (struct divert_tag *)(mtag+1);
3287 dt->cookie = f->rulenum;
3288 if (cmd->arg1 == IP_FW_TABLEARG)
3289 dt->info = tablearg;
3291 dt->info = cmd->arg1;
3292 m_tag_prepend(m, mtag);
3293 retval = (cmd->opcode == O_DIVERT) ?
3294 IP_FW_DIVERT : IP_FW_TEE;
3301 f->pcnt++; /* update stats */
3303 f->timestamp = time_uptime;
3304 if (cmd->opcode == O_COUNT)
3307 if (cmd->arg1 == IP_FW_TABLEARG) {
3308 f = lookup_next_rule(f, tablearg);
3310 if (f->next_rule == NULL)
3311 lookup_next_rule(f, 0);
3318 * Drop the packet and send a reject notice
3319 * if the packet is not ICMP (or is an ICMP
3320 * query), and it is not multicast/broadcast.
3322 if (hlen > 0 && is_ipv4 && offset == 0 &&
3323 (proto != IPPROTO_ICMP ||
3324 is_icmp_query(ICMP(ulp))) &&
3325 !(m->m_flags & (M_BCAST|M_MCAST)) &&
3326 !IN_MULTICAST(ntohl(dst_ip.s_addr))) {
3327 send_reject(args, cmd->arg1, ip_len, ip);
3333 if (hlen > 0 && is_ipv6 &&
3334 ((offset & IP6F_OFF_MASK) == 0) &&
3335 (proto != IPPROTO_ICMPV6 ||
3336 (is_icmp6_query(args->f_id.flags) == 1)) &&
3337 !(m->m_flags & (M_BCAST|M_MCAST)) &&
3338 !IN6_IS_ADDR_MULTICAST(&args->f_id.dst_ip6)) {
3340 args, cmd->arg1, hlen,
3341 (struct ip6_hdr *)ip);
3347 retval = IP_FW_DENY;
3350 case O_FORWARD_IP: {
3351 struct sockaddr_in *sa;
3352 sa = &(((ipfw_insn_sa *)cmd)->sa);
3353 if (args->eh) /* not valid on layer2 pkts */
3355 if (!q || dyn_dir == MATCH_FORWARD) {
3356 if (sa->sin_addr.s_addr == INADDR_ANY) {
3357 bcopy(sa, &args->hopstore,
3359 args->hopstore.sin_addr.s_addr =
3364 args->next_hop = sa;
3367 retval = IP_FW_PASS;
3373 args->rule = f; /* report matching rule */
3374 if (cmd->arg1 == IP_FW_TABLEARG)
3375 args->cookie = tablearg;
3377 args->cookie = cmd->arg1;
3378 retval = (cmd->opcode == O_NETGRAPH) ?
3379 IP_FW_NETGRAPH : IP_FW_NGTEE;
3384 f->pcnt++; /* update stats */
3386 f->timestamp = time_uptime;
3387 M_SETFIB(m, cmd->arg1);
3388 args->f_id.fib = cmd->arg1;
3395 if (IPFW_NAT_LOADED) {
3396 args->rule = f; /* Report matching rule. */
3397 t = ((ipfw_insn_nat *)cmd)->nat;
3399 nat_id = (cmd->arg1 == IP_FW_TABLEARG) ?
3400 tablearg : cmd->arg1;
3401 LOOKUP_NAT(layer3_chain, nat_id, t);
3403 retval = IP_FW_DENY;
3406 if (cmd->arg1 != IP_FW_TABLEARG)
3407 ((ipfw_insn_nat *)cmd)->nat = t;
3409 retval = ipfw_nat_ptr(args, t, m);
3411 retval = IP_FW_DENY;
3417 break; // XXX we disabled some
3418 panic("-- unknown opcode %d\n", cmd->opcode);
3419 } /* end of switch() on opcodes */
3421 if (cmd->len & F_NOT)
3425 if (cmd->len & F_OR)
3428 if (!(cmd->len & F_OR)) /* not an OR block, */
3429 break; /* try next rule */
3432 } /* end of inner for, scan opcodes */
3434 next_rule:; /* try next rule */
3436 } /* end of outer for, scan rules */
3437 printf("ipfw: ouch!, skip past end of rules, denying packet\n");
3438 IPFW_RUNLOCK(chain);
3439 return (IP_FW_DENY);
3442 /* Update statistics */
3445 f->timestamp = time_uptime;
3446 IPFW_RUNLOCK(chain);
3451 printf("ipfw: pullup failed\n");
3452 return (IP_FW_DENY);
3456 * When a rule is added/deleted, clear the next_rule pointers in all rules.
3457 * These will be reconstructed on the fly as packets are matched.
3460 flush_rule_ptrs(struct ip_fw_chain *chain)
3464 IPFW_WLOCK_ASSERT(chain);
3466 for (rule = chain->rules; rule; rule = rule->next)
3467 rule->next_rule = NULL;
3471 * Add a new rule to the list. Copy the rule into a malloc'ed area, then
3472 * possibly create a rule number and add the rule to the list.
3473 * Update the rule_number in the input struct so the caller knows it as well.
3476 add_rule(struct ip_fw_chain *chain, struct ip_fw *input_rule)
3478 struct ip_fw *rule, *f, *prev;
3479 int l = RULESIZE(input_rule);
3481 if (chain->rules == NULL && input_rule->rulenum != IPFW_DEFAULT_RULE)
3484 rule = malloc(l, M_IPFW, M_NOWAIT | M_ZERO);
3488 bcopy(input_rule, rule, l);
3491 rule->next_rule = NULL;
3495 rule->timestamp = 0;
3499 if (chain->rules == NULL) { /* default rule */
3500 chain->rules = rule;
3505 * If rulenum is 0, find highest numbered rule before the
3506 * default rule, and add autoinc_step
3508 if (autoinc_step < 1)
3510 else if (autoinc_step > 1000)
3511 autoinc_step = 1000;
3512 if (rule->rulenum == 0) {
3514 * locate the highest numbered rule before default
3516 for (f = chain->rules; f; f = f->next) {
3517 if (f->rulenum == IPFW_DEFAULT_RULE)
3519 rule->rulenum = f->rulenum;
3521 if (rule->rulenum < IPFW_DEFAULT_RULE - autoinc_step)
3522 rule->rulenum += autoinc_step;
3523 input_rule->rulenum = rule->rulenum;
3527 * Now insert the new rule in the right place in the sorted list.
3529 for (prev = NULL, f = chain->rules; f; prev = f, f = f->next) {
3530 if (f->rulenum > rule->rulenum) { /* found the location */
3534 } else { /* head insert */
3535 rule->next = chain->rules;
3536 chain->rules = rule;
3541 flush_rule_ptrs(chain);
3545 IPFW_WUNLOCK(chain);
3546 DEB(printf("ipfw: installed rule %d, static count now %d\n",
3547 rule->rulenum, static_count);)
3552 * Remove a static rule (including derived * dynamic rules)
3553 * and place it on the ``reap list'' for later reclamation.
3554 * The caller is in charge of clearing rule pointers to avoid
3555 * dangling pointers.
3556 * @return a pointer to the next entry.
3557 * Arguments are not checked, so they better be correct.
3559 static struct ip_fw *
3560 remove_rule(struct ip_fw_chain *chain, struct ip_fw *rule,
3564 int l = RULESIZE(rule);
3566 IPFW_WLOCK_ASSERT(chain);
3570 remove_dyn_rule(rule, NULL /* force removal */);
3579 rule->next = chain->reap;
3586 * Hook for cleaning up dummynet when an ipfw rule is deleted.
3587 * Set/cleared when dummynet module is loaded/unloaded.
3589 void (*ip_dn_ruledel_ptr)(void *) = NULL;
3592 * Reclaim storage associated with a list of rules. This is
3593 * typically the list created using remove_rule.
3594 * A NULL pointer on input is handled correctly.
3597 reap_rules(struct ip_fw *head)
3601 while ((rule = head) != NULL) {
3603 if (ip_dn_ruledel_ptr)
3604 ip_dn_ruledel_ptr(rule);
3610 * Remove all rules from a chain (except rules in set RESVD_SET
3611 * unless kill_default = 1). The caller is responsible for
3612 * reclaiming storage for the rules left in chain->reap.
3615 free_chain(struct ip_fw_chain *chain, int kill_default)
3617 struct ip_fw *prev, *rule;
3619 IPFW_WLOCK_ASSERT(chain);
3621 flush_rule_ptrs(chain); /* more efficient to do outside the loop */
3622 for (prev = NULL, rule = chain->rules; rule ; )
3623 if (kill_default || rule->set != RESVD_SET)
3624 rule = remove_rule(chain, rule, prev);
3632 * Remove all rules with given number, and also do set manipulation.
3633 * Assumes chain != NULL && *chain != NULL.
3635 * The argument is an u_int32_t. The low 16 bit are the rule or set number,
3636 * the next 8 bits are the new set, the top 8 bits are the command:
3638 * 0 delete rules with given number
3639 * 1 delete rules with given set number
3640 * 2 move rules with given number to new set
3641 * 3 move rules with given set number to new set
3642 * 4 swap sets with given numbers
3643 * 5 delete rules with given number and with given set number
3646 del_entry(struct ip_fw_chain *chain, u_int32_t arg)
3648 struct ip_fw *prev = NULL, *rule;
3649 u_int16_t rulenum; /* rule or old_set */
3650 u_int8_t cmd, new_set;
3652 rulenum = arg & 0xffff;
3653 cmd = (arg >> 24) & 0xff;
3654 new_set = (arg >> 16) & 0xff;
3656 if (cmd > 5 || new_set > RESVD_SET)
3658 if (cmd == 0 || cmd == 2 || cmd == 5) {
3659 if (rulenum >= IPFW_DEFAULT_RULE)
3662 if (rulenum > RESVD_SET) /* old_set */
3667 rule = chain->rules;
3670 case 0: /* delete rules with given number */
3672 * locate first rule to delete
3674 for (; rule->rulenum < rulenum; prev = rule, rule = rule->next)
3676 if (rule->rulenum != rulenum) {
3677 IPFW_WUNLOCK(chain);
3682 * flush pointers outside the loop, then delete all matching
3683 * rules. prev remains the same throughout the cycle.
3685 flush_rule_ptrs(chain);
3686 while (rule->rulenum == rulenum)
3687 rule = remove_rule(chain, rule, prev);
3690 case 1: /* delete all rules with given set number */
3691 flush_rule_ptrs(chain);
3692 rule = chain->rules;
3693 while (rule->rulenum < IPFW_DEFAULT_RULE)
3694 if (rule->set == rulenum)
3695 rule = remove_rule(chain, rule, prev);
3702 case 2: /* move rules with given number to new set */
3703 rule = chain->rules;
3704 for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
3705 if (rule->rulenum == rulenum)
3706 rule->set = new_set;
3709 case 3: /* move rules with given set number to new set */
3710 for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
3711 if (rule->set == rulenum)
3712 rule->set = new_set;
3715 case 4: /* swap two sets */
3716 for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
3717 if (rule->set == rulenum)
3718 rule->set = new_set;
3719 else if (rule->set == new_set)
3720 rule->set = rulenum;
3722 case 5: /* delete rules with given number and with given set number.
3723 * rulenum - given rule number;
3724 * new_set - given set number.
3726 for (; rule->rulenum < rulenum; prev = rule, rule = rule->next)
3728 if (rule->rulenum != rulenum) {
3729 IPFW_WUNLOCK(chain);
3732 flush_rule_ptrs(chain);
3733 while (rule->rulenum == rulenum) {
3734 if (rule->set == new_set)
3735 rule = remove_rule(chain, rule, prev);
3743 * Look for rules to reclaim. We grab the list before
3744 * releasing the lock then reclaim them w/o the lock to
3745 * avoid a LOR with dummynet.
3749 IPFW_WUNLOCK(chain);
3756 * Clear counters for a specific rule.
3757 * The enclosing "table" is assumed locked.
3760 clear_counters(struct ip_fw *rule, int log_only)
3762 ipfw_insn_log *l = (ipfw_insn_log *)ACTION_PTR(rule);
3764 if (log_only == 0) {
3765 rule->bcnt = rule->pcnt = 0;
3766 rule->timestamp = 0;
3768 if (l->o.opcode == O_LOG)
3769 l->log_left = l->max_log;
3773 * Reset some or all counters on firewall rules.
3774 * The argument `arg' is an u_int32_t. The low 16 bit are the rule number,
3775 * the next 8 bits are the set number, the top 8 bits are the command:
3776 * 0 work with rules from all set's;
3777 * 1 work with rules only from specified set.
3778 * Specified rule number is zero if we want to clear all entries.
3779 * log_only is 1 if we only want to reset logs, zero otherwise.
3782 zero_entry(struct ip_fw_chain *chain, u_int32_t arg, int log_only)
3787 uint16_t rulenum = arg & 0xffff;
3788 uint8_t set = (arg >> 16) & 0xff;
3789 uint8_t cmd = (arg >> 24) & 0xff;
3793 if (cmd == 1 && set > RESVD_SET)
3799 for (rule = chain->rules; rule; rule = rule->next) {
3800 /* Skip rules from another set. */
3801 if (cmd == 1 && rule->set != set)
3803 clear_counters(rule, log_only);
3805 msg = log_only ? "All logging counts reset" :
3806 "Accounting cleared";
3810 * We can have multiple rules with the same number, so we
3811 * need to clear them all.
3813 for (rule = chain->rules; rule; rule = rule->next)
3814 if (rule->rulenum == rulenum) {
3815 while (rule && rule->rulenum == rulenum) {
3816 if (cmd == 0 || rule->set == set)
3817 clear_counters(rule, log_only);
3823 if (!cleared) { /* we did not find any matching rules */
3824 IPFW_WUNLOCK(chain);
3827 msg = log_only ? "logging count reset" : "cleared";
3829 IPFW_WUNLOCK(chain);
3832 #define lev LOG_SECURITY | LOG_NOTICE
3835 log(lev, "ipfw: Entry %d %s.\n", rulenum, msg);
3837 log(lev, "ipfw: %s.\n", msg);
3843 * Check validity of the structure before insert.
3844 * Fortunately rules are simple, so this mostly need to check rule sizes.
3847 check_ipfw_struct(struct ip_fw *rule, int size)
3853 if (size < sizeof(*rule)) {
3854 printf("ipfw: rule too short\n");
3857 /* first, check for valid size */
3860 printf("ipfw: size mismatch (have %d want %d)\n", size, l);
3863 if (rule->act_ofs >= rule->cmd_len) {
3864 printf("ipfw: bogus action offset (%u > %u)\n",
3865 rule->act_ofs, rule->cmd_len - 1);
3869 * Now go for the individual checks. Very simple ones, basically only
3870 * instruction sizes.
3872 for (l = rule->cmd_len, cmd = rule->cmd ;
3873 l > 0 ; l -= cmdlen, cmd += cmdlen) {
3874 cmdlen = F_LEN(cmd);
3876 printf("ipfw: opcode %d size truncated\n",
3880 DEB(printf("ipfw: opcode %d\n", cmd->opcode);)
3881 switch (cmd->opcode) {
3893 case O_IPPRECEDENCE:
3911 if (cmdlen != F_INSN_SIZE(ipfw_insn))
3916 if (cmdlen != F_INSN_SIZE(ipfw_insn))
3918 if (cmd->arg1 >= rt_numfibs) {
3919 printf("ipfw: invalid fib number %d\n",
3926 if (cmdlen != F_INSN_SIZE(ipfw_insn))
3928 if (cmd->arg1 >= rt_numfibs) {
3929 printf("ipfw: invalid fib number %d\n",
3944 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32))
3949 if (cmdlen != F_INSN_SIZE(ipfw_insn_limit))
3954 if (cmdlen != F_INSN_SIZE(ipfw_insn_log))
3957 ((ipfw_insn_log *)cmd)->log_left =
3958 ((ipfw_insn_log *)cmd)->max_log;
3964 /* only odd command lengths */
3965 if ( !(cmdlen & 1) || cmdlen > 31)
3971 if (cmd->arg1 == 0 || cmd->arg1 > 256) {
3972 printf("ipfw: invalid set size %d\n",
3976 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
3981 case O_IP_SRC_LOOKUP:
3982 case O_IP_DST_LOOKUP:
3983 if (cmd->arg1 >= IPFW_TABLES_MAX) {
3984 printf("ipfw: invalid table number %d\n",
3988 if (cmdlen != F_INSN_SIZE(ipfw_insn) &&
3989 cmdlen != F_INSN_SIZE(ipfw_insn_u32))
3994 if (cmdlen != F_INSN_SIZE(ipfw_insn_mac))
4004 if (cmdlen < 1 || cmdlen > 31)
4010 case O_IP_DSTPORT: /* XXX artificial limit, 30 port pairs */
4011 if (cmdlen < 2 || cmdlen > 31)
4018 if (cmdlen != F_INSN_SIZE(ipfw_insn_if))
4023 if (cmdlen != F_INSN_SIZE(ipfw_insn_altq))
4029 if (cmdlen != F_INSN_SIZE(ipfw_insn))
4034 #ifdef IPFIREWALL_FORWARD
4035 if (cmdlen != F_INSN_SIZE(ipfw_insn_sa))
4044 if (ip_divert_ptr == NULL)
4050 if (!NG_IPFW_LOADED)
4055 if (!IPFW_NAT_LOADED)
4057 if (cmdlen != F_INSN_SIZE(ipfw_insn_nat))
4060 case O_FORWARD_MAC: /* XXX not implemented yet */
4071 if (cmdlen != F_INSN_SIZE(ipfw_insn))
4075 printf("ipfw: opcode %d, multiple actions"
4082 printf("ipfw: opcode %d, action must be"
4091 if (cmdlen != F_INSN_SIZE(struct in6_addr) +
4092 F_INSN_SIZE(ipfw_insn))
4097 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
4098 ((ipfw_insn_u32 *)cmd)->o.arg1)
4102 case O_IP6_SRC_MASK:
4103 case O_IP6_DST_MASK:
4104 if ( !(cmdlen & 1) || cmdlen > 127)
4108 if( cmdlen != F_INSN_SIZE( ipfw_insn_icmp6 ) )
4114 switch (cmd->opcode) {
4124 case O_IP6_SRC_MASK:
4125 case O_IP6_DST_MASK:
4127 printf("ipfw: no IPv6 support in kernel\n");
4128 return EPROTONOSUPPORT;
4131 printf("ipfw: opcode %d, unknown opcode\n",
4137 if (have_action == 0) {
4138 printf("ipfw: missing action\n");
4144 printf("ipfw: opcode %d size %d wrong\n",
4145 cmd->opcode, cmdlen);
4150 * Copy the static and dynamic rules to the supplied buffer
4151 * and return the amount of space actually used.
4154 ipfw_getrules(struct ip_fw_chain *chain, void *buf, size_t space)
4157 char *ep = bp + space;
4160 time_t boot_seconds;
4162 boot_seconds = boottime.tv_sec;
4163 /* XXX this can take a long time and locking will block packet flow */
4165 for (rule = chain->rules; rule ; rule = rule->next) {
4167 * Verify the entry fits in the buffer in case the
4168 * rules changed between calculating buffer space and
4169 * now. This would be better done using a generation
4170 * number but should suffice for now.
4176 * XXX HACK. Store the disable mask in the "next" pointer
4177 * in a wild attempt to keep the ABI the same.
4178 * Why do we do this on EVERY rule?
4180 bcopy(&set_disable, &(((struct ip_fw *)bp)->next_rule),
4181 sizeof(set_disable));
4182 if (((struct ip_fw *)bp)->timestamp)
4183 ((struct ip_fw *)bp)->timestamp += boot_seconds;
4187 IPFW_RUNLOCK(chain);
4189 ipfw_dyn_rule *p, *last = NULL;
4192 for (i = 0 ; i < curr_dyn_buckets; i++)
4193 for (p = ipfw_dyn_v[i] ; p != NULL; p = p->next) {
4194 if (bp + sizeof *p <= ep) {
4195 ipfw_dyn_rule *dst =
4196 (ipfw_dyn_rule *)bp;
4197 bcopy(p, dst, sizeof *p);
4198 bcopy(&(p->rule->rulenum), &(dst->rule),
4199 sizeof(p->rule->rulenum));
4201 * store set number into high word of
4202 * dst->rule pointer.
4204 bcopy(&(p->rule->set),
4205 (char *)&dst->rule +
4206 sizeof(p->rule->rulenum),
4207 sizeof(p->rule->set));
4209 * store a non-null value in "next".
4210 * The userland code will interpret a
4211 * NULL here as a marker
4212 * for the last dynamic rule.
4214 bcopy(&dst, &dst->next, sizeof(dst));
4217 TIME_LEQ(dst->expire, time_uptime) ?
4218 0 : dst->expire - time_uptime ;
4219 bp += sizeof(ipfw_dyn_rule);
4223 if (last != NULL) /* mark last dynamic rule */
4224 bzero(&last->next, sizeof(last));
4226 return (bp - (char *)buf);
4231 * {set|get}sockopt parser.
4234 ipfw_ctl(struct sockopt *sopt)
4236 #define RULE_MAXSIZE (256*sizeof(u_int32_t))
4239 struct ip_fw *buf, *rule;
4240 u_int32_t rulenum[2];
4242 error = priv_check(sopt->sopt_td, PRIV_NETINET_IPFW);
4247 * Disallow modifications in really-really secure mode, but still allow
4248 * the logging counters to be reset.
4250 if (sopt->sopt_name == IP_FW_ADD ||
4251 (sopt->sopt_dir == SOPT_SET && sopt->sopt_name != IP_FW_RESETLOG)) {
4252 error = securelevel_ge(sopt->sopt_td->td_ucred, 3);
4259 switch (sopt->sopt_name) {
4262 * pass up a copy of the current rules. Static rules
4263 * come first (the last of which has number IPFW_DEFAULT_RULE),
4264 * followed by a possibly empty list of dynamic rule.
4265 * The last dynamic rule has NULL in the "next" field.
4267 * Note that the calculated size is used to bound the
4268 * amount of data returned to the user. The rule set may
4269 * change between calculating the size and returning the
4270 * data in which case we'll just return what fits.
4272 size = static_len; /* size of static rules */
4273 if (ipfw_dyn_v) /* add size of dyn.rules */
4274 size += (dyn_count * sizeof(ipfw_dyn_rule));
4277 * XXX todo: if the user passes a short length just to know
4278 * how much room is needed, do not bother filling up the
4279 * buffer, just jump to the sooptcopyout.
4281 buf = malloc(size, M_TEMP, M_WAITOK);
4282 error = sooptcopyout(sopt, buf,
4283 ipfw_getrules(&layer3_chain, buf, size));
4289 * Normally we cannot release the lock on each iteration.
4290 * We could do it here only because we start from the head all
4291 * the times so there is no risk of missing some entries.
4292 * On the other hand, the risk is that we end up with
4293 * a very inconsistent ruleset, so better keep the lock
4294 * around the whole cycle.
4296 * XXX this code can be improved by resetting the head of
4297 * the list to point to the default rule, and then freeing
4298 * the old list without the need for a lock.
4301 IPFW_WLOCK(&layer3_chain);
4302 layer3_chain.reap = NULL;
4303 free_chain(&layer3_chain, 0 /* keep default rule */);
4304 rule = layer3_chain.reap;
4305 layer3_chain.reap = NULL;
4306 IPFW_WUNLOCK(&layer3_chain);
4312 rule = malloc(RULE_MAXSIZE, M_TEMP, M_WAITOK);
4313 error = sooptcopyin(sopt, rule, RULE_MAXSIZE,
4314 sizeof(struct ip_fw) );
4316 error = check_ipfw_struct(rule, sopt->sopt_valsize);
4318 error = add_rule(&layer3_chain, rule);
4319 size = RULESIZE(rule);
4320 if (!error && sopt->sopt_dir == SOPT_GET)
4321 error = sooptcopyout(sopt, rule, size);
4328 * IP_FW_DEL is used for deleting single rules or sets,
4329 * and (ab)used to atomically manipulate sets. Argument size
4330 * is used to distinguish between the two:
4332 * delete single rule or set of rules,
4333 * or reassign rules (or sets) to a different set.
4334 * 2*sizeof(u_int32_t)
4335 * atomic disable/enable sets.
4336 * first u_int32_t contains sets to be disabled,
4337 * second u_int32_t contains sets to be enabled.
4339 error = sooptcopyin(sopt, rulenum,
4340 2*sizeof(u_int32_t), sizeof(u_int32_t));
4343 size = sopt->sopt_valsize;
4344 if (size == sizeof(u_int32_t)) /* delete or reassign */
4345 error = del_entry(&layer3_chain, rulenum[0]);
4346 else if (size == 2*sizeof(u_int32_t)) /* set enable/disable */
4348 (set_disable | rulenum[0]) & ~rulenum[1] &
4349 ~(1<<RESVD_SET); /* set RESVD_SET always enabled */
4355 case IP_FW_RESETLOG: /* argument is an u_int_32, the rule number */
4357 if (sopt->sopt_val != 0) {
4358 error = sooptcopyin(sopt, rulenum,
4359 sizeof(u_int32_t), sizeof(u_int32_t));
4363 error = zero_entry(&layer3_chain, rulenum[0],
4364 sopt->sopt_name == IP_FW_RESETLOG);
4368 case IP_FW_TABLE_ADD:
4370 ipfw_table_entry ent;
4372 error = sooptcopyin(sopt, &ent,
4373 sizeof(ent), sizeof(ent));
4376 error = add_table_entry(&layer3_chain, ent.tbl,
4377 ent.addr, ent.masklen, ent.value);
4381 case IP_FW_TABLE_DEL:
4383 ipfw_table_entry ent;
4385 error = sooptcopyin(sopt, &ent,
4386 sizeof(ent), sizeof(ent));
4389 error = del_table_entry(&layer3_chain, ent.tbl,
4390 ent.addr, ent.masklen);
4394 case IP_FW_TABLE_FLUSH:
4398 error = sooptcopyin(sopt, &tbl,
4399 sizeof(tbl), sizeof(tbl));
4402 IPFW_WLOCK(&layer3_chain);
4403 error = flush_table(&layer3_chain, tbl);
4404 IPFW_WUNLOCK(&layer3_chain);
4408 case IP_FW_TABLE_GETSIZE:
4412 if ((error = sooptcopyin(sopt, &tbl, sizeof(tbl),
4415 IPFW_RLOCK(&layer3_chain);
4416 error = count_table(&layer3_chain, tbl, &cnt);
4417 IPFW_RUNLOCK(&layer3_chain);
4420 error = sooptcopyout(sopt, &cnt, sizeof(cnt));
4424 case IP_FW_TABLE_LIST:
4428 if (sopt->sopt_valsize < sizeof(*tbl)) {
4432 size = sopt->sopt_valsize;
4433 tbl = malloc(size, M_TEMP, M_WAITOK);
4434 error = sooptcopyin(sopt, tbl, size, sizeof(*tbl));
4439 tbl->size = (size - sizeof(*tbl)) /
4440 sizeof(ipfw_table_entry);
4441 IPFW_RLOCK(&layer3_chain);
4442 error = dump_table(&layer3_chain, tbl);
4443 IPFW_RUNLOCK(&layer3_chain);
4448 error = sooptcopyout(sopt, tbl, size);
4456 if (IPFW_NAT_LOADED)
4457 error = ipfw_nat_cfg_ptr(sopt);
4459 printf("IP_FW_NAT_CFG: %s\n",
4460 "ipfw_nat not present, please load it");
4466 if (IPFW_NAT_LOADED)
4467 error = ipfw_nat_del_ptr(sopt);
4469 printf("IP_FW_NAT_DEL: %s\n",
4470 "ipfw_nat not present, please load it");
4475 case IP_FW_NAT_GET_CONFIG:
4476 if (IPFW_NAT_LOADED)
4477 error = ipfw_nat_get_cfg_ptr(sopt);
4479 printf("IP_FW_NAT_GET_CFG: %s\n",
4480 "ipfw_nat not present, please load it");
4485 case IP_FW_NAT_GET_LOG:
4486 if (IPFW_NAT_LOADED)
4487 error = ipfw_nat_get_log_ptr(sopt);
4489 printf("IP_FW_NAT_GET_LOG: %s\n",
4490 "ipfw_nat not present, please load it");
4496 printf("ipfw: ipfw_ctl invalid option %d\n", sopt->sopt_name);
4505 * dummynet needs a reference to the default rule, because rules can be
4506 * deleted while packets hold a reference to them. When this happens,
4507 * dummynet changes the reference to the default rule (it could well be a
4508 * NULL pointer, but this way we do not need to check for the special
4509 * case, plus here he have info on the default behaviour).
4511 struct ip_fw *ip_fw_default_rule;
4514 * This procedure is only used to handle keepalives. It is invoked
4515 * every dyn_keepalive_period
4518 ipfw_tick(void * __unused unused)
4520 struct mbuf *m0, *m, *mnext, **mtailp;
4524 if (dyn_keepalive == 0 || ipfw_dyn_v == NULL || dyn_count == 0)
4528 * We make a chain of packets to go out here -- not deferring
4529 * until after we drop the IPFW dynamic rule lock would result
4530 * in a lock order reversal with the normal packet input -> ipfw
4536 for (i = 0 ; i < curr_dyn_buckets ; i++) {
4537 for (q = ipfw_dyn_v[i] ; q ; q = q->next ) {
4538 if (q->dyn_type == O_LIMIT_PARENT)
4540 if (q->id.proto != IPPROTO_TCP)
4542 if ( (q->state & BOTH_SYN) != BOTH_SYN)
4544 if (TIME_LEQ( time_uptime+dyn_keepalive_interval,
4546 continue; /* too early */
4547 if (TIME_LEQ(q->expire, time_uptime))
4548 continue; /* too late, rule expired */
4550 *mtailp = send_pkt(NULL, &(q->id), q->ack_rev - 1,
4551 q->ack_fwd, TH_SYN);
4552 if (*mtailp != NULL)
4553 mtailp = &(*mtailp)->m_nextpkt;
4554 *mtailp = send_pkt(NULL, &(q->id), q->ack_fwd - 1,
4556 if (*mtailp != NULL)
4557 mtailp = &(*mtailp)->m_nextpkt;
4561 for (m = mnext = m0; m != NULL; m = mnext) {
4562 mnext = m->m_nextpkt;
4563 m->m_nextpkt = NULL;
4564 ip_output(m, NULL, NULL, 0, NULL, NULL);
4567 callout_reset(&ipfw_timeout, dyn_keepalive_period*hz, ipfw_tick, NULL);
4573 struct ip_fw default_rule;
4577 /* Setup IPv6 fw sysctl tree. */
4578 sysctl_ctx_init(&ip6_fw_sysctl_ctx);
4579 ip6_fw_sysctl_tree = SYSCTL_ADD_NODE(&ip6_fw_sysctl_ctx,
4580 SYSCTL_STATIC_CHILDREN(_net_inet6_ip6), OID_AUTO, "fw",
4581 CTLFLAG_RW | CTLFLAG_SECURE, 0, "Firewall");
4582 SYSCTL_ADD_PROC(&ip6_fw_sysctl_ctx, SYSCTL_CHILDREN(ip6_fw_sysctl_tree),
4583 OID_AUTO, "enable", CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE3,
4584 &fw6_enable, 0, ipfw_chg_hook, "I", "Enable ipfw+6");
4585 SYSCTL_ADD_INT(&ip6_fw_sysctl_ctx, SYSCTL_CHILDREN(ip6_fw_sysctl_tree),
4586 OID_AUTO, "deny_unknown_exthdrs", CTLFLAG_RW | CTLFLAG_SECURE,
4587 &fw_deny_unknown_exthdrs, 0,
4588 "Deny packets with unknown IPv6 Extension Headers");
4591 layer3_chain.rules = NULL;
4592 IPFW_LOCK_INIT(&layer3_chain);
4593 ipfw_dyn_rule_zone = uma_zcreate("IPFW dynamic rule",
4594 sizeof(ipfw_dyn_rule), NULL, NULL, NULL, NULL,
4596 IPFW_DYN_LOCK_INIT();
4597 callout_init(&ipfw_timeout, CALLOUT_MPSAFE);
4599 bzero(&default_rule, sizeof default_rule);
4601 default_rule.act_ofs = 0;
4602 default_rule.rulenum = IPFW_DEFAULT_RULE;
4603 default_rule.cmd_len = 1;
4604 default_rule.set = RESVD_SET;
4606 default_rule.cmd[0].len = 1;
4607 default_rule.cmd[0].opcode =
4608 #ifdef IPFIREWALL_DEFAULT_TO_ACCEPT
4613 error = add_rule(&layer3_chain, &default_rule);
4615 printf("ipfw2: error %u initializing default rule "
4616 "(support disabled)\n", error);
4617 IPFW_DYN_LOCK_DESTROY();
4618 IPFW_LOCK_DESTROY(&layer3_chain);
4619 uma_zdestroy(ipfw_dyn_rule_zone);
4623 ip_fw_default_rule = layer3_chain.rules;
4628 "initialized, divert %s, nat %s, "
4629 "rule-based forwarding "
4630 #ifdef IPFIREWALL_FORWARD
4635 "default to %s, logging ",
4641 #ifdef IPFIREWALL_NAT
4647 default_rule.cmd[0].opcode == O_ACCEPT ? "accept" : "deny");
4649 #ifdef IPFIREWALL_VERBOSE
4652 #ifdef IPFIREWALL_VERBOSE_LIMIT
4653 verbose_limit = IPFIREWALL_VERBOSE_LIMIT;
4655 if (fw_verbose == 0)
4656 printf("disabled\n");
4657 else if (verbose_limit == 0)
4658 printf("unlimited\n");
4660 printf("limited to %d packets/entry by default\n",
4663 error = init_tables(&layer3_chain);
4665 IPFW_DYN_LOCK_DESTROY();
4666 IPFW_LOCK_DESTROY(&layer3_chain);
4667 uma_zdestroy(ipfw_dyn_rule_zone);
4670 ip_fw_ctl_ptr = ipfw_ctl;
4671 ip_fw_chk_ptr = ipfw_chk;
4672 callout_reset(&ipfw_timeout, hz, ipfw_tick, NULL);
4673 LIST_INIT(&layer3_chain.nat);
4682 ip_fw_chk_ptr = NULL;
4683 ip_fw_ctl_ptr = NULL;
4684 callout_drain(&ipfw_timeout);
4685 IPFW_WLOCK(&layer3_chain);
4686 flush_tables(&layer3_chain);
4687 layer3_chain.reap = NULL;
4688 free_chain(&layer3_chain, 1 /* kill default rule */);
4689 reap = layer3_chain.reap, layer3_chain.reap = NULL;
4690 IPFW_WUNLOCK(&layer3_chain);
4693 IPFW_DYN_LOCK_DESTROY();
4694 uma_zdestroy(ipfw_dyn_rule_zone);
4695 if (ipfw_dyn_v != NULL)
4696 free(ipfw_dyn_v, M_IPFW);
4697 IPFW_LOCK_DESTROY(&layer3_chain);
4700 /* Free IPv6 fw sysctl tree. */
4701 sysctl_ctx_free(&ip6_fw_sysctl_ctx);
4704 printf("IP firewall unloaded\n");