2 * Copyright (c) 2002 Luigi Rizzo, Universita` di Pisa
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
13 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
14 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
16 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
17 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
19 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
20 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
21 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 #include <sys/cdefs.h>
27 __FBSDID("$FreeBSD$");
33 * Implement IP packet firewall (new version)
36 #if !defined(KLD_MODULE)
38 #include "opt_ipdivert.h"
42 #error IPFIREWALL requires INET.
45 #include "opt_inet6.h"
46 #include "opt_ipsec.h"
49 #include <sys/param.h>
50 #include <sys/systm.h>
51 #include <sys/condvar.h>
52 #include <sys/eventhandler.h>
53 #include <sys/malloc.h>
55 #include <sys/kernel.h>
58 #include <sys/module.h>
61 #include <sys/rwlock.h>
62 #include <sys/socket.h>
63 #include <sys/socketvar.h>
64 #include <sys/sysctl.h>
65 #include <sys/syslog.h>
66 #include <sys/ucred.h>
67 #include <sys/vimage.h>
69 #include <net/radix.h>
70 #include <net/route.h>
71 #include <net/pf_mtag.h>
73 #define IPFW_INTERNAL /* Access to protected data structures in ip_fw.h. */
75 #include <netinet/in.h>
76 #include <netinet/in_systm.h>
77 #include <netinet/in_var.h>
78 #include <netinet/in_pcb.h>
79 #include <netinet/ip.h>
80 #include <netinet/ip_var.h>
81 #include <netinet/ip_icmp.h>
82 #include <netinet/ip_fw.h>
83 #include <netinet/ip_divert.h>
84 #include <netinet/ip_dummynet.h>
85 #include <netinet/ip_carp.h>
86 #include <netinet/pim.h>
87 #include <netinet/tcp.h>
88 #include <netinet/tcp_timer.h>
89 #include <netinet/tcp_var.h>
90 #include <netinet/tcpip.h>
91 #include <netinet/udp.h>
92 #include <netinet/udp_var.h>
93 #include <netinet/sctp.h>
94 #include <netgraph/ng_ipfw.h>
96 #include <altq/if_altq.h>
98 #include <netinet/ip6.h>
99 #include <netinet/icmp6.h>
101 #include <netinet6/scope6_var.h>
104 #include <netinet/if_ether.h> /* XXX for ETHERTYPE_IP */
106 #include <machine/in_cksum.h> /* XXX for in_cksum */
108 #include <security/mac/mac_framework.h>
111 * set_disable contains one bit per set value (0..31).
112 * If the bit is set, all rules with the corresponding set
113 * are disabled. Set RESVD_SET(31) is reserved for the default rule
114 * and rules that are not deleted by the flush command,
115 * and CANNOT be disabled.
116 * Rules in set RESVD_SET can only be deleted explicitly.
118 static u_int32_t set_disable;
120 static int fw_verbose;
121 static int verbose_limit;
123 static struct callout ipfw_timeout;
124 static uma_zone_t ipfw_dyn_rule_zone;
127 * Data structure to cache our ucred related
128 * information. This structure only gets used if
129 * the user specified UID/GID based constraints in
133 gid_t fw_groups[NGROUPS];
140 * list of rules for layer 3
142 struct ip_fw_chain layer3_chain;
144 MALLOC_DEFINE(M_IPFW, "IpFw/IpAcct", "IpFw/IpAcct chain's");
145 MALLOC_DEFINE(M_IPFW_TBL, "ipfw_tbl", "IpFw tables");
146 #define IPFW_NAT_LOADED (ipfw_nat_ptr != NULL)
147 ipfw_nat_t *ipfw_nat_ptr = NULL;
148 ipfw_nat_cfg_t *ipfw_nat_cfg_ptr;
149 ipfw_nat_cfg_t *ipfw_nat_del_ptr;
150 ipfw_nat_cfg_t *ipfw_nat_get_cfg_ptr;
151 ipfw_nat_cfg_t *ipfw_nat_get_log_ptr;
154 struct radix_node rn[2];
155 struct sockaddr_in addr, mask;
159 static int fw_debug = 1;
160 static int autoinc_step = 100; /* bounded to 1..1000 in add_rule() */
162 extern int ipfw_chg_hook(SYSCTL_HANDLER_ARGS);
165 SYSCTL_NODE(_net_inet_ip, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall");
166 SYSCTL_V_PROC(V_NET, vnet_ipfw, _net_inet_ip_fw, OID_AUTO, enable,
167 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE3, fw_enable, 0,
168 ipfw_chg_hook, "I", "Enable ipfw");
169 SYSCTL_V_INT(V_NET, vnet_ipfw, _net_inet_ip_fw, OID_AUTO, autoinc_step,
170 CTLFLAG_RW, autoinc_step, 0, "Rule number autincrement step");
171 SYSCTL_V_INT(V_NET, vnet_ipfw, _net_inet_ip_fw, OID_AUTO, one_pass,
172 CTLFLAG_RW | CTLFLAG_SECURE3, fw_one_pass, 0,
173 "Only do a single pass through ipfw when using dummynet(4)");
174 SYSCTL_V_INT(V_NET, vnet_ipfw, _net_inet_ip_fw, OID_AUTO, debug, CTLFLAG_RW,
175 fw_debug, 0, "Enable printing of debug ip_fw statements");
176 SYSCTL_V_INT(V_NET, vnet_ipfw, _net_inet_ip_fw, OID_AUTO, verbose,
177 CTLFLAG_RW | CTLFLAG_SECURE3,
178 fw_verbose, 0, "Log matches to ipfw rules");
179 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose_limit, CTLFLAG_RW,
180 &verbose_limit, 0, "Set upper limit of matches of ipfw rules logged");
181 SYSCTL_UINT(_net_inet_ip_fw, OID_AUTO, default_rule, CTLFLAG_RD,
182 NULL, IPFW_DEFAULT_RULE, "The default/max possible rule number.");
183 SYSCTL_UINT(_net_inet_ip_fw, OID_AUTO, tables_max, CTLFLAG_RD,
184 NULL, IPFW_TABLES_MAX, "The maximum number of tables.");
187 * Description of dynamic rules.
189 * Dynamic rules are stored in lists accessed through a hash table
190 * (ipfw_dyn_v) whose size is curr_dyn_buckets. This value can
191 * be modified through the sysctl variable dyn_buckets which is
192 * updated when the table becomes empty.
194 * XXX currently there is only one list, ipfw_dyn.
196 * When a packet is received, its address fields are first masked
197 * with the mask defined for the rule, then hashed, then matched
198 * against the entries in the corresponding list.
199 * Dynamic rules can be used for different purposes:
201 * + enforcing limits on the number of sessions;
202 * + in-kernel NAT (not implemented yet)
204 * The lifetime of dynamic rules is regulated by dyn_*_lifetime,
205 * measured in seconds and depending on the flags.
207 * The total number of dynamic rules is stored in dyn_count.
208 * The max number of dynamic rules is dyn_max. When we reach
209 * the maximum number of rules we do not create anymore. This is
210 * done to avoid consuming too much memory, but also too much
211 * time when searching on each packet (ideally, we should try instead
212 * to put a limit on the length of the list on each bucket...).
214 * Each dynamic rule holds a pointer to the parent ipfw rule so
215 * we know what action to perform. Dynamic rules are removed when
216 * the parent rule is deleted. XXX we should make them survive.
218 * There are some limitations with dynamic rules -- we do not
219 * obey the 'randomized match', and we do not do multiple
220 * passes through the firewall. XXX check the latter!!!
222 static ipfw_dyn_rule **ipfw_dyn_v = NULL;
223 static u_int32_t dyn_buckets = 256; /* must be power of 2 */
224 static u_int32_t curr_dyn_buckets = 256; /* must be power of 2 */
226 static struct mtx ipfw_dyn_mtx; /* mutex guarding dynamic rules */
227 #define IPFW_DYN_LOCK_INIT() \
228 mtx_init(&ipfw_dyn_mtx, "IPFW dynamic rules", NULL, MTX_DEF)
229 #define IPFW_DYN_LOCK_DESTROY() mtx_destroy(&ipfw_dyn_mtx)
230 #define IPFW_DYN_LOCK() mtx_lock(&ipfw_dyn_mtx)
231 #define IPFW_DYN_UNLOCK() mtx_unlock(&ipfw_dyn_mtx)
232 #define IPFW_DYN_LOCK_ASSERT() mtx_assert(&ipfw_dyn_mtx, MA_OWNED)
235 * Timeouts for various events in handing dynamic rules.
237 static u_int32_t dyn_ack_lifetime = 300;
238 static u_int32_t dyn_syn_lifetime = 20;
239 static u_int32_t dyn_fin_lifetime = 1;
240 static u_int32_t dyn_rst_lifetime = 1;
241 static u_int32_t dyn_udp_lifetime = 10;
242 static u_int32_t dyn_short_lifetime = 5;
245 * Keepalives are sent if dyn_keepalive is set. They are sent every
246 * dyn_keepalive_period seconds, in the last dyn_keepalive_interval
247 * seconds of lifetime of a rule.
248 * dyn_rst_lifetime and dyn_fin_lifetime should be strictly lower
249 * than dyn_keepalive_period.
252 static u_int32_t dyn_keepalive_interval = 20;
253 static u_int32_t dyn_keepalive_period = 5;
254 static u_int32_t dyn_keepalive = 1; /* do send keepalives */
256 static u_int32_t static_count; /* # of static rules */
257 static u_int32_t static_len; /* size in bytes of static rules */
258 static u_int32_t dyn_count; /* # of dynamic rules */
259 static u_int32_t dyn_max = 4096; /* max # of dynamic rules */
261 SYSCTL_V_INT(V_NET, vnet_ipfw, _net_inet_ip_fw, OID_AUTO, dyn_buckets,
262 CTLFLAG_RW, dyn_buckets, 0, "Number of dyn. buckets");
263 SYSCTL_V_INT(V_NET, vnet_ipfw, _net_inet_ip_fw, OID_AUTO, curr_dyn_buckets,
264 CTLFLAG_RD, curr_dyn_buckets, 0, "Current Number of dyn. buckets");
265 SYSCTL_V_INT(V_NET, vnet_ipfw, _net_inet_ip_fw, OID_AUTO, dyn_count,
266 CTLFLAG_RD, dyn_count, 0, "Number of dyn. rules");
267 SYSCTL_V_INT(V_NET, vnet_ipfw, _net_inet_ip_fw, OID_AUTO, dyn_max,
268 CTLFLAG_RW, dyn_max, 0, "Max number of dyn. rules");
269 SYSCTL_V_INT(V_NET, vnet_ipfw, _net_inet_ip_fw, OID_AUTO, static_count,
270 CTLFLAG_RD, static_count, 0, "Number of static rules");
271 SYSCTL_V_INT(V_NET, vnet_ipfw, _net_inet_ip_fw, OID_AUTO, dyn_ack_lifetime,
272 CTLFLAG_RW, dyn_ack_lifetime, 0, "Lifetime of dyn. rules for acks");
273 SYSCTL_V_INT(V_NET, vnet_ipfw, _net_inet_ip_fw, OID_AUTO, dyn_syn_lifetime,
274 CTLFLAG_RW, dyn_syn_lifetime, 0, "Lifetime of dyn. rules for syn");
275 SYSCTL_V_INT(V_NET, vnet_ipfw, _net_inet_ip_fw, OID_AUTO, dyn_fin_lifetime,
276 CTLFLAG_RW, dyn_fin_lifetime, 0, "Lifetime of dyn. rules for fin");
277 SYSCTL_V_INT(V_NET, vnet_ipfw, _net_inet_ip_fw, OID_AUTO, dyn_rst_lifetime,
278 CTLFLAG_RW, dyn_rst_lifetime, 0, "Lifetime of dyn. rules for rst");
279 SYSCTL_V_INT(V_NET, vnet_ipfw, _net_inet_ip_fw, OID_AUTO, dyn_udp_lifetime,
280 CTLFLAG_RW, dyn_udp_lifetime, 0, "Lifetime of dyn. rules for UDP");
281 SYSCTL_V_INT(V_NET, vnet_ipfw, _net_inet_ip_fw, OID_AUTO, dyn_short_lifetime,
282 CTLFLAG_RW, dyn_short_lifetime, 0,
283 "Lifetime of dyn. rules for other situations");
284 SYSCTL_V_INT(V_NET, vnet_ipfw, _net_inet_ip_fw, OID_AUTO, dyn_keepalive,
285 CTLFLAG_RW, dyn_keepalive, 0, "Enable keepalives for dyn. rules");
290 * IPv6 specific variables
292 SYSCTL_DECL(_net_inet6_ip6);
294 static struct sysctl_ctx_list ip6_fw_sysctl_ctx;
295 static struct sysctl_oid *ip6_fw_sysctl_tree;
297 #endif /* SYSCTL_NODE */
299 static int fw_deny_unknown_exthdrs = 1;
303 * L3HDR maps an ipv4 pointer into a layer3 header pointer of type T
304 * Other macros just cast void * into the appropriate type
306 #define L3HDR(T, ip) ((T *)((u_int32_t *)(ip) + (ip)->ip_hl))
307 #define TCP(p) ((struct tcphdr *)(p))
308 #define SCTP(p) ((struct sctphdr *)(p))
309 #define UDP(p) ((struct udphdr *)(p))
310 #define ICMP(p) ((struct icmphdr *)(p))
311 #define ICMP6(p) ((struct icmp6_hdr *)(p))
314 icmptype_match(struct icmphdr *icmp, ipfw_insn_u32 *cmd)
316 int type = icmp->icmp_type;
318 return (type <= ICMP_MAXTYPE && (cmd->d[0] & (1<<type)) );
321 #define TT ( (1 << ICMP_ECHO) | (1 << ICMP_ROUTERSOLICIT) | \
322 (1 << ICMP_TSTAMP) | (1 << ICMP_IREQ) | (1 << ICMP_MASKREQ) )
325 is_icmp_query(struct icmphdr *icmp)
327 int type = icmp->icmp_type;
329 return (type <= ICMP_MAXTYPE && (TT & (1<<type)) );
334 * The following checks use two arrays of 8 or 16 bits to store the
335 * bits that we want set or clear, respectively. They are in the
336 * low and high half of cmd->arg1 or cmd->d[0].
338 * We scan options and store the bits we find set. We succeed if
340 * (want_set & ~bits) == 0 && (want_clear & ~bits) == want_clear
342 * The code is sometimes optimized not to store additional variables.
346 flags_match(ipfw_insn *cmd, u_int8_t bits)
351 if ( ((cmd->arg1 & 0xff) & bits) != 0)
352 return 0; /* some bits we want set were clear */
353 want_clear = (cmd->arg1 >> 8) & 0xff;
354 if ( (want_clear & bits) != want_clear)
355 return 0; /* some bits we want clear were set */
360 ipopts_match(struct ip *ip, ipfw_insn *cmd)
362 int optlen, bits = 0;
363 u_char *cp = (u_char *)(ip + 1);
364 int x = (ip->ip_hl << 2) - sizeof (struct ip);
366 for (; x > 0; x -= optlen, cp += optlen) {
367 int opt = cp[IPOPT_OPTVAL];
369 if (opt == IPOPT_EOL)
371 if (opt == IPOPT_NOP)
374 optlen = cp[IPOPT_OLEN];
375 if (optlen <= 0 || optlen > x)
376 return 0; /* invalid or truncated */
384 bits |= IP_FW_IPOPT_LSRR;
388 bits |= IP_FW_IPOPT_SSRR;
392 bits |= IP_FW_IPOPT_RR;
396 bits |= IP_FW_IPOPT_TS;
400 return (flags_match(cmd, bits));
404 tcpopts_match(struct tcphdr *tcp, ipfw_insn *cmd)
406 int optlen, bits = 0;
407 u_char *cp = (u_char *)(tcp + 1);
408 int x = (tcp->th_off << 2) - sizeof(struct tcphdr);
410 for (; x > 0; x -= optlen, cp += optlen) {
412 if (opt == TCPOPT_EOL)
414 if (opt == TCPOPT_NOP)
428 bits |= IP_FW_TCPOPT_MSS;
432 bits |= IP_FW_TCPOPT_WINDOW;
435 case TCPOPT_SACK_PERMITTED:
437 bits |= IP_FW_TCPOPT_SACK;
440 case TCPOPT_TIMESTAMP:
441 bits |= IP_FW_TCPOPT_TS;
446 return (flags_match(cmd, bits));
450 iface_match(struct ifnet *ifp, ipfw_insn_if *cmd)
452 if (ifp == NULL) /* no iface with this packet, match fails */
454 /* Check by name or by IP address */
455 if (cmd->name[0] != '\0') { /* match by name */
458 if (fnmatch(cmd->name, ifp->if_xname, 0) == 0)
461 if (strncmp(ifp->if_xname, cmd->name, IFNAMSIZ) == 0)
468 TAILQ_FOREACH(ia, &ifp->if_addrhead, ifa_link) {
469 if (ia->ifa_addr->sa_family != AF_INET)
471 if (cmd->p.ip.s_addr == ((struct sockaddr_in *)
472 (ia->ifa_addr))->sin_addr.s_addr)
473 return(1); /* match */
476 return(0); /* no match, fail ... */
480 * The verify_path function checks if a route to the src exists and
481 * if it is reachable via ifp (when provided).
483 * The 'verrevpath' option checks that the interface that an IP packet
484 * arrives on is the same interface that traffic destined for the
485 * packet's source address would be routed out of. The 'versrcreach'
486 * option just checks that the source address is reachable via any route
487 * (except default) in the routing table. These two are a measure to block
488 * forged packets. This is also commonly known as "anti-spoofing" or Unicast
489 * Reverse Path Forwarding (Unicast RFP) in Cisco-ese. The name of the knobs
490 * is purposely reminiscent of the Cisco IOS command,
492 * ip verify unicast reverse-path
493 * ip verify unicast source reachable-via any
495 * which implements the same functionality. But note that syntax is
496 * misleading. The check may be performed on all IP packets whether unicast,
497 * multicast, or broadcast.
500 verify_path(struct in_addr src, struct ifnet *ifp, u_int fib)
503 struct sockaddr_in *dst;
505 bzero(&ro, sizeof(ro));
507 dst = (struct sockaddr_in *)&(ro.ro_dst);
508 dst->sin_family = AF_INET;
509 dst->sin_len = sizeof(*dst);
511 in_rtalloc_ign(&ro, RTF_CLONING, fib);
513 if (ro.ro_rt == NULL)
517 * If ifp is provided, check for equality with rtentry.
518 * We should use rt->rt_ifa->ifa_ifp, instead of rt->rt_ifp,
519 * in order to pass packets injected back by if_simloop():
520 * if useloopback == 1 routing entry (via lo0) for our own address
521 * may exist, so we need to handle routing assymetry.
523 if (ifp != NULL && ro.ro_rt->rt_ifa->ifa_ifp != ifp) {
528 /* if no ifp provided, check if rtentry is not default route */
530 satosin(rt_key(ro.ro_rt))->sin_addr.s_addr == INADDR_ANY) {
535 /* or if this is a blackhole/reject route */
536 if (ifp == NULL && ro.ro_rt->rt_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
541 /* 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)
570 INIT_VNET_NET(curvnet);
573 struct in6_ifaddr *fdm;
574 struct in6_addr copia;
576 TAILQ_FOREACH(mdc, &V_ifnet, if_link)
577 TAILQ_FOREACH(mdc2, &mdc->if_addrlist, ifa_list) {
578 if (mdc2->ifa_addr->sa_family == AF_INET6) {
579 fdm = (struct in6_ifaddr *)mdc2;
580 copia = fdm->ia_addr.sin6_addr;
581 /* need for leaving scope_id in the sock_addr */
582 in6_clearscope(&copia);
583 if (IN6_ARE_ADDR_EQUAL(ip6_addr, &copia))
591 verify_path6(struct in6_addr *src, struct ifnet *ifp)
594 struct sockaddr_in6 *dst;
596 bzero(&ro, sizeof(ro));
598 dst = (struct sockaddr_in6 * )&(ro.ro_dst);
599 dst->sin6_family = AF_INET6;
600 dst->sin6_len = sizeof(*dst);
601 dst->sin6_addr = *src;
602 /* XXX MRT 0 for ipv6 at this time */
603 rtalloc_ign((struct route *)&ro, RTF_CLONING);
605 if (ro.ro_rt == NULL)
609 * if ifp is provided, check for equality with rtentry
610 * We should use rt->rt_ifa->ifa_ifp, instead of rt->rt_ifp,
611 * to support the case of sending packets to an address of our own.
612 * (where the former interface is the first argument of if_simloop()
613 * (=ifp), the latter is lo0)
615 if (ifp != NULL && ro.ro_rt->rt_ifa->ifa_ifp != ifp) {
620 /* if no ifp provided, check if rtentry is not default route */
622 IN6_IS_ADDR_UNSPECIFIED(&satosin6(rt_key(ro.ro_rt))->sin6_addr)) {
627 /* or if this is a blackhole/reject route */
628 if (ifp == NULL && ro.ro_rt->rt_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
633 /* found valid route */
639 hash_packet6(struct ipfw_flow_id *id)
642 i = (id->dst_ip6.__u6_addr.__u6_addr32[2]) ^
643 (id->dst_ip6.__u6_addr.__u6_addr32[3]) ^
644 (id->src_ip6.__u6_addr.__u6_addr32[2]) ^
645 (id->src_ip6.__u6_addr.__u6_addr32[3]) ^
646 (id->dst_port) ^ (id->src_port);
651 is_icmp6_query(int icmp6_type)
653 if ((icmp6_type <= ICMP6_MAXTYPE) &&
654 (icmp6_type == ICMP6_ECHO_REQUEST ||
655 icmp6_type == ICMP6_MEMBERSHIP_QUERY ||
656 icmp6_type == ICMP6_WRUREQUEST ||
657 icmp6_type == ICMP6_FQDN_QUERY ||
658 icmp6_type == ICMP6_NI_QUERY))
665 send_reject6(struct ip_fw_args *args, int code, u_int hlen, struct ip6_hdr *ip6)
670 if (code == ICMP6_UNREACH_RST && args->f_id.proto == IPPROTO_TCP) {
678 tcp = (struct tcphdr *)((char *)ip6 + hlen);
680 if ((tcp->th_flags & TH_RST) != 0) {
688 ti.th.th_seq = ntohl(ti.th.th_seq);
689 ti.th.th_ack = ntohl(ti.th.th_ack);
690 ti.ip6.ip6_nxt = IPPROTO_TCP;
692 if (ti.th.th_flags & TH_ACK) {
698 if ((m->m_flags & M_PKTHDR) != 0) {
700 * total new data to ACK is:
701 * total packet length,
702 * minus the header length,
703 * minus the tcp header length.
705 ack += m->m_pkthdr.len - hlen
706 - (ti.th.th_off << 2);
707 } else if (ip6->ip6_plen) {
708 ack += ntohs(ip6->ip6_plen) + sizeof(*ip6) -
709 hlen - (ti.th.th_off << 2);
714 if (tcp->th_flags & TH_SYN)
717 flags = TH_RST|TH_ACK;
719 bcopy(&ti, ip6, sizeof(ti));
721 * m is only used to recycle the mbuf
722 * The data in it is never read so we don't need
723 * to correct the offsets or anything
725 tcp_respond(NULL, ip6, tcp, m, ack, seq, flags);
726 } else if (code != ICMP6_UNREACH_RST) { /* Send an ICMPv6 unreach. */
729 * Unlike above, the mbufs need to line up with the ip6 hdr,
730 * as the contents are read. We need to m_adj() the
732 * The mbuf will however be thrown away so we can adjust it.
733 * Remember we did an m_pullup on it already so we
734 * can make some assumptions about contiguousness.
737 m_adj(m, args->L3offset);
739 icmp6_error(m, ICMP6_DST_UNREACH, code, 0);
748 static u_int64_t norule_counter; /* counter for ipfw_log(NULL...) */
750 #define SNPARGS(buf, len) buf + len, sizeof(buf) > len ? sizeof(buf) - len : 0
751 #define SNP(buf) buf, sizeof(buf)
754 * We enter here when we have a rule with O_LOG.
755 * XXX this function alone takes about 2Kbytes of code!
758 ipfw_log(struct ip_fw *f, u_int hlen, struct ip_fw_args *args,
759 struct mbuf *m, struct ifnet *oif, u_short offset, uint32_t tablearg,
762 INIT_VNET_IPFW(curvnet);
763 struct ether_header *eh = args->eh;
765 int limit_reached = 0;
766 char action2[40], proto[128], fragment[32];
771 if (f == NULL) { /* bogus pkt */
772 if (V_verbose_limit != 0 && V_norule_counter >= V_verbose_limit)
775 if (V_norule_counter == V_verbose_limit)
776 limit_reached = V_verbose_limit;
778 } else { /* O_LOG is the first action, find the real one */
779 ipfw_insn *cmd = ACTION_PTR(f);
780 ipfw_insn_log *l = (ipfw_insn_log *)cmd;
782 if (l->max_log != 0 && l->log_left == 0)
785 if (l->log_left == 0)
786 limit_reached = l->max_log;
787 cmd += F_LEN(cmd); /* point to first action */
788 if (cmd->opcode == O_ALTQ) {
789 ipfw_insn_altq *altq = (ipfw_insn_altq *)cmd;
791 snprintf(SNPARGS(action2, 0), "Altq %d",
795 if (cmd->opcode == O_PROB)
798 if (cmd->opcode == O_TAG)
802 switch (cmd->opcode) {
808 if (cmd->arg1==ICMP_REJECT_RST)
810 else if (cmd->arg1==ICMP_UNREACH_HOST)
813 snprintf(SNPARGS(action2, 0), "Unreach %d",
818 if (cmd->arg1==ICMP6_UNREACH_RST)
821 snprintf(SNPARGS(action2, 0), "Unreach %d",
832 snprintf(SNPARGS(action2, 0), "Divert %d",
836 snprintf(SNPARGS(action2, 0), "Tee %d",
840 snprintf(SNPARGS(action2, 0), "SetFib %d",
844 snprintf(SNPARGS(action2, 0), "SkipTo %d",
848 snprintf(SNPARGS(action2, 0), "Pipe %d",
852 snprintf(SNPARGS(action2, 0), "Queue %d",
856 ipfw_insn_sa *sa = (ipfw_insn_sa *)cmd;
858 struct in_addr dummyaddr;
859 if (sa->sa.sin_addr.s_addr == INADDR_ANY)
860 dummyaddr.s_addr = htonl(tablearg);
862 dummyaddr.s_addr = sa->sa.sin_addr.s_addr;
864 len = snprintf(SNPARGS(action2, 0), "Forward to %s",
865 inet_ntoa(dummyaddr));
868 snprintf(SNPARGS(action2, len), ":%d",
873 snprintf(SNPARGS(action2, 0), "Netgraph %d",
877 snprintf(SNPARGS(action2, 0), "Ngtee %d",
889 if (hlen == 0) { /* non-ip */
890 snprintf(SNPARGS(proto, 0), "MAC");
894 char src[48], dst[48];
895 struct icmphdr *icmp;
899 struct ip6_hdr *ip6 = NULL;
900 struct icmp6_hdr *icmp6;
905 if (IS_IP6_FLOW_ID(&(args->f_id))) {
906 char ip6buf[INET6_ADDRSTRLEN];
907 snprintf(src, sizeof(src), "[%s]",
908 ip6_sprintf(ip6buf, &args->f_id.src_ip6));
909 snprintf(dst, sizeof(dst), "[%s]",
910 ip6_sprintf(ip6buf, &args->f_id.dst_ip6));
912 ip6 = (struct ip6_hdr *)ip;
913 tcp = (struct tcphdr *)(((char *)ip) + hlen);
914 udp = (struct udphdr *)(((char *)ip) + hlen);
918 tcp = L3HDR(struct tcphdr, ip);
919 udp = L3HDR(struct udphdr, ip);
921 inet_ntoa_r(ip->ip_src, src);
922 inet_ntoa_r(ip->ip_dst, dst);
925 switch (args->f_id.proto) {
927 len = snprintf(SNPARGS(proto, 0), "TCP %s", src);
929 snprintf(SNPARGS(proto, len), ":%d %s:%d",
930 ntohs(tcp->th_sport),
932 ntohs(tcp->th_dport));
934 snprintf(SNPARGS(proto, len), " %s", dst);
938 len = snprintf(SNPARGS(proto, 0), "UDP %s", src);
940 snprintf(SNPARGS(proto, len), ":%d %s:%d",
941 ntohs(udp->uh_sport),
943 ntohs(udp->uh_dport));
945 snprintf(SNPARGS(proto, len), " %s", dst);
949 icmp = L3HDR(struct icmphdr, ip);
951 len = snprintf(SNPARGS(proto, 0),
953 icmp->icmp_type, icmp->icmp_code);
955 len = snprintf(SNPARGS(proto, 0), "ICMP ");
956 len += snprintf(SNPARGS(proto, len), "%s", src);
957 snprintf(SNPARGS(proto, len), " %s", dst);
961 icmp6 = (struct icmp6_hdr *)(((char *)ip) + hlen);
963 len = snprintf(SNPARGS(proto, 0),
965 icmp6->icmp6_type, icmp6->icmp6_code);
967 len = snprintf(SNPARGS(proto, 0), "ICMPv6 ");
968 len += snprintf(SNPARGS(proto, len), "%s", src);
969 snprintf(SNPARGS(proto, len), " %s", dst);
973 len = snprintf(SNPARGS(proto, 0), "P:%d %s",
974 args->f_id.proto, src);
975 snprintf(SNPARGS(proto, len), " %s", dst);
980 if (IS_IP6_FLOW_ID(&(args->f_id))) {
981 if (offset & (IP6F_OFF_MASK | IP6F_MORE_FRAG))
982 snprintf(SNPARGS(fragment, 0),
983 " (frag %08x:%d@%d%s)",
985 ntohs(ip6->ip6_plen) - hlen,
986 ntohs(offset & IP6F_OFF_MASK) << 3,
987 (offset & IP6F_MORE_FRAG) ? "+" : "");
992 if (eh != NULL) { /* layer 2 packets are as on the wire */
993 ip_off = ntohs(ip->ip_off);
994 ip_len = ntohs(ip->ip_len);
999 if (ip_off & (IP_MF | IP_OFFMASK))
1000 snprintf(SNPARGS(fragment, 0),
1001 " (frag %d:%d@%d%s)",
1002 ntohs(ip->ip_id), ip_len - (ip->ip_hl << 2),
1004 (ip_off & IP_MF) ? "+" : "");
1007 if (oif || m->m_pkthdr.rcvif)
1008 log(LOG_SECURITY | LOG_INFO,
1009 "ipfw: %d %s %s %s via %s%s\n",
1010 f ? f->rulenum : -1,
1011 action, proto, oif ? "out" : "in",
1012 oif ? oif->if_xname : m->m_pkthdr.rcvif->if_xname,
1015 log(LOG_SECURITY | LOG_INFO,
1016 "ipfw: %d %s %s [no if info]%s\n",
1017 f ? f->rulenum : -1,
1018 action, proto, fragment);
1020 log(LOG_SECURITY | LOG_NOTICE,
1021 "ipfw: limit %d reached on entry %d\n",
1022 limit_reached, f ? f->rulenum : -1);
1026 * IMPORTANT: the hash function for dynamic rules must be commutative
1027 * in source and destination (ip,port), because rules are bidirectional
1028 * and we want to find both in the same bucket.
1031 hash_packet(struct ipfw_flow_id *id)
1033 INIT_VNET_IPFW(curvnet);
1037 if (IS_IP6_FLOW_ID(id))
1038 i = hash_packet6(id);
1041 i = (id->dst_ip) ^ (id->src_ip) ^ (id->dst_port) ^ (id->src_port);
1042 i &= (V_curr_dyn_buckets - 1);
1047 * unlink a dynamic rule from a chain. prev is a pointer to
1048 * the previous one, q is a pointer to the rule to delete,
1049 * head is a pointer to the head of the queue.
1050 * Modifies q and potentially also head.
1052 #define UNLINK_DYN_RULE(prev, head, q) { \
1053 ipfw_dyn_rule *old_q = q; \
1055 /* remove a refcount to the parent */ \
1056 if (q->dyn_type == O_LIMIT) \
1057 q->parent->count--; \
1058 DEB(printf("ipfw: unlink entry 0x%08x %d -> 0x%08x %d, %d left\n",\
1059 (q->id.src_ip), (q->id.src_port), \
1060 (q->id.dst_ip), (q->id.dst_port), V_dyn_count-1 ); ) \
1062 prev->next = q = q->next; \
1064 head = q = q->next; \
1066 uma_zfree(ipfw_dyn_rule_zone, old_q); }
1068 #define TIME_LEQ(a,b) ((int)((a)-(b)) <= 0)
1071 * Remove dynamic rules pointing to "rule", or all of them if rule == NULL.
1073 * If keep_me == NULL, rules are deleted even if not expired,
1074 * otherwise only expired rules are removed.
1076 * The value of the second parameter is also used to point to identify
1077 * a rule we absolutely do not want to remove (e.g. because we are
1078 * holding a reference to it -- this is the case with O_LIMIT_PARENT
1079 * rules). The pointer is only used for comparison, so any non-null
1083 remove_dyn_rule(struct ip_fw *rule, ipfw_dyn_rule *keep_me)
1085 INIT_VNET_IPFW(curvnet);
1086 static u_int32_t last_remove = 0;
1088 #define FORCE (keep_me == NULL)
1090 ipfw_dyn_rule *prev, *q;
1091 int i, pass = 0, max_pass = 0;
1093 IPFW_DYN_LOCK_ASSERT();
1095 if (V_ipfw_dyn_v == NULL || V_dyn_count == 0)
1097 /* do not expire more than once per second, it is useless */
1098 if (!FORCE && last_remove == time_uptime)
1100 last_remove = time_uptime;
1103 * because O_LIMIT refer to parent rules, during the first pass only
1104 * remove child and mark any pending LIMIT_PARENT, and remove
1105 * them in a second pass.
1108 for (i = 0 ; i < V_curr_dyn_buckets ; i++) {
1109 for (prev=NULL, q = V_ipfw_dyn_v[i] ; q ; ) {
1111 * Logic can become complex here, so we split tests.
1115 if (rule != NULL && rule != q->rule)
1116 goto next; /* not the one we are looking for */
1117 if (q->dyn_type == O_LIMIT_PARENT) {
1119 * handle parent in the second pass,
1120 * record we need one.
1125 if (FORCE && q->count != 0 ) {
1126 /* XXX should not happen! */
1127 printf("ipfw: OUCH! cannot remove rule,"
1128 " count %d\n", q->count);
1132 !TIME_LEQ( q->expire, time_uptime ))
1135 if (q->dyn_type != O_LIMIT_PARENT || !q->count) {
1136 UNLINK_DYN_RULE(prev, V_ipfw_dyn_v[i], q);
1144 if (pass++ < max_pass)
1150 * lookup a dynamic rule.
1152 static ipfw_dyn_rule *
1153 lookup_dyn_rule_locked(struct ipfw_flow_id *pkt, int *match_direction,
1156 INIT_VNET_IPFW(curvnet);
1158 * stateful ipfw extensions.
1159 * Lookup into dynamic session queue
1161 #define MATCH_REVERSE 0
1162 #define MATCH_FORWARD 1
1163 #define MATCH_NONE 2
1164 #define MATCH_UNKNOWN 3
1165 int i, dir = MATCH_NONE;
1166 ipfw_dyn_rule *prev, *q=NULL;
1168 IPFW_DYN_LOCK_ASSERT();
1170 if (V_ipfw_dyn_v == NULL)
1171 goto done; /* not found */
1172 i = hash_packet( pkt );
1173 for (prev=NULL, q = V_ipfw_dyn_v[i] ; q != NULL ; ) {
1174 if (q->dyn_type == O_LIMIT_PARENT && q->count)
1176 if (TIME_LEQ( q->expire, time_uptime)) { /* expire entry */
1177 UNLINK_DYN_RULE(prev, V_ipfw_dyn_v[i], q);
1180 if (pkt->proto == q->id.proto &&
1181 q->dyn_type != O_LIMIT_PARENT) {
1182 if (IS_IP6_FLOW_ID(pkt)) {
1183 if (IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
1184 &(q->id.src_ip6)) &&
1185 IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
1186 &(q->id.dst_ip6)) &&
1187 pkt->src_port == q->id.src_port &&
1188 pkt->dst_port == q->id.dst_port ) {
1189 dir = MATCH_FORWARD;
1192 if (IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
1193 &(q->id.dst_ip6)) &&
1194 IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
1195 &(q->id.src_ip6)) &&
1196 pkt->src_port == q->id.dst_port &&
1197 pkt->dst_port == q->id.src_port ) {
1198 dir = MATCH_REVERSE;
1202 if (pkt->src_ip == q->id.src_ip &&
1203 pkt->dst_ip == q->id.dst_ip &&
1204 pkt->src_port == q->id.src_port &&
1205 pkt->dst_port == q->id.dst_port ) {
1206 dir = MATCH_FORWARD;
1209 if (pkt->src_ip == q->id.dst_ip &&
1210 pkt->dst_ip == q->id.src_ip &&
1211 pkt->src_port == q->id.dst_port &&
1212 pkt->dst_port == q->id.src_port ) {
1213 dir = MATCH_REVERSE;
1223 goto done; /* q = NULL, not found */
1225 if ( prev != NULL) { /* found and not in front */
1226 prev->next = q->next;
1227 q->next = V_ipfw_dyn_v[i];
1228 V_ipfw_dyn_v[i] = q;
1230 if (pkt->proto == IPPROTO_TCP) { /* update state according to flags */
1231 u_char flags = pkt->flags & (TH_FIN|TH_SYN|TH_RST);
1233 #define BOTH_SYN (TH_SYN | (TH_SYN << 8))
1234 #define BOTH_FIN (TH_FIN | (TH_FIN << 8))
1235 q->state |= (dir == MATCH_FORWARD ) ? flags : (flags << 8);
1237 case TH_SYN: /* opening */
1238 q->expire = time_uptime + V_dyn_syn_lifetime;
1241 case BOTH_SYN: /* move to established */
1242 case BOTH_SYN | TH_FIN : /* one side tries to close */
1243 case BOTH_SYN | (TH_FIN << 8) :
1245 #define _SEQ_GE(a,b) ((int)(a) - (int)(b) >= 0)
1246 u_int32_t ack = ntohl(tcp->th_ack);
1247 if (dir == MATCH_FORWARD) {
1248 if (q->ack_fwd == 0 || _SEQ_GE(ack, q->ack_fwd))
1250 else { /* ignore out-of-sequence */
1254 if (q->ack_rev == 0 || _SEQ_GE(ack, q->ack_rev))
1256 else { /* ignore out-of-sequence */
1261 q->expire = time_uptime + V_dyn_ack_lifetime;
1264 case BOTH_SYN | BOTH_FIN: /* both sides closed */
1265 if (V_dyn_fin_lifetime >= V_dyn_keepalive_period)
1266 V_dyn_fin_lifetime = V_dyn_keepalive_period - 1;
1267 q->expire = time_uptime + V_dyn_fin_lifetime;
1273 * reset or some invalid combination, but can also
1274 * occur if we use keep-state the wrong way.
1276 if ( (q->state & ((TH_RST << 8)|TH_RST)) == 0)
1277 printf("invalid state: 0x%x\n", q->state);
1279 if (V_dyn_rst_lifetime >= V_dyn_keepalive_period)
1280 V_dyn_rst_lifetime = V_dyn_keepalive_period - 1;
1281 q->expire = time_uptime + V_dyn_rst_lifetime;
1284 } else if (pkt->proto == IPPROTO_UDP) {
1285 q->expire = time_uptime + V_dyn_udp_lifetime;
1287 /* other protocols */
1288 q->expire = time_uptime + V_dyn_short_lifetime;
1291 if (match_direction)
1292 *match_direction = dir;
1296 static ipfw_dyn_rule *
1297 lookup_dyn_rule(struct ipfw_flow_id *pkt, int *match_direction,
1303 q = lookup_dyn_rule_locked(pkt, match_direction, tcp);
1306 /* NB: return table locked when q is not NULL */
1311 realloc_dynamic_table(void)
1313 INIT_VNET_IPFW(curvnet);
1314 IPFW_DYN_LOCK_ASSERT();
1317 * Try reallocation, make sure we have a power of 2 and do
1318 * not allow more than 64k entries. In case of overflow,
1322 if (V_dyn_buckets > 65536)
1323 V_dyn_buckets = 1024;
1324 if ((V_dyn_buckets & (V_dyn_buckets-1)) != 0) { /* not a power of 2 */
1325 V_dyn_buckets = V_curr_dyn_buckets; /* reset */
1328 V_curr_dyn_buckets = V_dyn_buckets;
1329 if (V_ipfw_dyn_v != NULL)
1330 free(V_ipfw_dyn_v, M_IPFW);
1332 V_ipfw_dyn_v = malloc(V_curr_dyn_buckets * sizeof(ipfw_dyn_rule *),
1333 M_IPFW, M_NOWAIT | M_ZERO);
1334 if (V_ipfw_dyn_v != NULL || V_curr_dyn_buckets <= 2)
1336 V_curr_dyn_buckets /= 2;
1341 * Install state of type 'type' for a dynamic session.
1342 * The hash table contains two type of rules:
1343 * - regular rules (O_KEEP_STATE)
1344 * - rules for sessions with limited number of sess per user
1345 * (O_LIMIT). When they are created, the parent is
1346 * increased by 1, and decreased on delete. In this case,
1347 * the third parameter is the parent rule and not the chain.
1348 * - "parent" rules for the above (O_LIMIT_PARENT).
1350 static ipfw_dyn_rule *
1351 add_dyn_rule(struct ipfw_flow_id *id, u_int8_t dyn_type, struct ip_fw *rule)
1353 INIT_VNET_IPFW(curvnet);
1357 IPFW_DYN_LOCK_ASSERT();
1359 if (V_ipfw_dyn_v == NULL ||
1360 (V_dyn_count == 0 && V_dyn_buckets != V_curr_dyn_buckets)) {
1361 realloc_dynamic_table();
1362 if (V_ipfw_dyn_v == NULL)
1363 return NULL; /* failed ! */
1365 i = hash_packet(id);
1367 r = uma_zalloc(ipfw_dyn_rule_zone, M_NOWAIT | M_ZERO);
1369 printf ("ipfw: sorry cannot allocate state\n");
1373 /* increase refcount on parent, and set pointer */
1374 if (dyn_type == O_LIMIT) {
1375 ipfw_dyn_rule *parent = (ipfw_dyn_rule *)rule;
1376 if ( parent->dyn_type != O_LIMIT_PARENT)
1377 panic("invalid parent");
1380 rule = parent->rule;
1384 r->expire = time_uptime + V_dyn_syn_lifetime;
1386 r->dyn_type = dyn_type;
1387 r->pcnt = r->bcnt = 0;
1391 r->next = V_ipfw_dyn_v[i];
1392 V_ipfw_dyn_v[i] = r;
1394 DEB(printf("ipfw: add dyn entry ty %d 0x%08x %d -> 0x%08x %d, total %d\n",
1396 (r->id.src_ip), (r->id.src_port),
1397 (r->id.dst_ip), (r->id.dst_port),
1403 * lookup dynamic parent rule using pkt and rule as search keys.
1404 * If the lookup fails, then install one.
1406 static ipfw_dyn_rule *
1407 lookup_dyn_parent(struct ipfw_flow_id *pkt, struct ip_fw *rule)
1409 INIT_VNET_IPFW(curvnet);
1413 IPFW_DYN_LOCK_ASSERT();
1416 int is_v6 = IS_IP6_FLOW_ID(pkt);
1417 i = hash_packet( pkt );
1418 for (q = V_ipfw_dyn_v[i] ; q != NULL ; q=q->next)
1419 if (q->dyn_type == O_LIMIT_PARENT &&
1421 pkt->proto == q->id.proto &&
1422 pkt->src_port == q->id.src_port &&
1423 pkt->dst_port == q->id.dst_port &&
1426 IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
1427 &(q->id.src_ip6)) &&
1428 IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
1429 &(q->id.dst_ip6))) ||
1431 pkt->src_ip == q->id.src_ip &&
1432 pkt->dst_ip == q->id.dst_ip)
1435 q->expire = time_uptime + V_dyn_short_lifetime;
1436 DEB(printf("ipfw: lookup_dyn_parent found 0x%p\n",q);)
1440 return add_dyn_rule(pkt, O_LIMIT_PARENT, rule);
1444 * Install dynamic state for rule type cmd->o.opcode
1446 * Returns 1 (failure) if state is not installed because of errors or because
1447 * session limitations are enforced.
1450 install_state(struct ip_fw *rule, ipfw_insn_limit *cmd,
1451 struct ip_fw_args *args, uint32_t tablearg)
1453 INIT_VNET_IPFW(curvnet);
1454 static int last_log;
1457 char src[48], dst[48];
1463 printf("ipfw: %s: type %d 0x%08x %u -> 0x%08x %u\n",
1464 __func__, cmd->o.opcode,
1465 (args->f_id.src_ip), (args->f_id.src_port),
1466 (args->f_id.dst_ip), (args->f_id.dst_port));
1471 q = lookup_dyn_rule_locked(&args->f_id, NULL, NULL);
1473 if (q != NULL) { /* should never occur */
1474 if (last_log != time_uptime) {
1475 last_log = time_uptime;
1476 printf("ipfw: %s: entry already present, done\n",
1483 if (V_dyn_count >= V_dyn_max)
1484 /* Run out of slots, try to remove any expired rule. */
1485 remove_dyn_rule(NULL, (ipfw_dyn_rule *)1);
1487 if (V_dyn_count >= V_dyn_max) {
1488 if (last_log != time_uptime) {
1489 last_log = time_uptime;
1490 printf("ipfw: %s: Too many dynamic rules\n", __func__);
1493 return (1); /* cannot install, notify caller */
1496 switch (cmd->o.opcode) {
1497 case O_KEEP_STATE: /* bidir rule */
1498 add_dyn_rule(&args->f_id, O_KEEP_STATE, rule);
1501 case O_LIMIT: { /* limit number of sessions */
1502 struct ipfw_flow_id id;
1503 ipfw_dyn_rule *parent;
1504 uint32_t conn_limit;
1505 uint16_t limit_mask = cmd->limit_mask;
1507 conn_limit = (cmd->conn_limit == IP_FW_TABLEARG) ?
1508 tablearg : cmd->conn_limit;
1511 if (cmd->conn_limit == IP_FW_TABLEARG)
1512 printf("ipfw: %s: O_LIMIT rule, conn_limit: %u "
1513 "(tablearg)\n", __func__, conn_limit);
1515 printf("ipfw: %s: O_LIMIT rule, conn_limit: %u\n",
1516 __func__, conn_limit);
1519 id.dst_ip = id.src_ip = id.dst_port = id.src_port = 0;
1520 id.proto = args->f_id.proto;
1521 id.addr_type = args->f_id.addr_type;
1522 id.fib = M_GETFIB(args->m);
1524 if (IS_IP6_FLOW_ID (&(args->f_id))) {
1525 if (limit_mask & DYN_SRC_ADDR)
1526 id.src_ip6 = args->f_id.src_ip6;
1527 if (limit_mask & DYN_DST_ADDR)
1528 id.dst_ip6 = args->f_id.dst_ip6;
1530 if (limit_mask & DYN_SRC_ADDR)
1531 id.src_ip = args->f_id.src_ip;
1532 if (limit_mask & DYN_DST_ADDR)
1533 id.dst_ip = args->f_id.dst_ip;
1535 if (limit_mask & DYN_SRC_PORT)
1536 id.src_port = args->f_id.src_port;
1537 if (limit_mask & DYN_DST_PORT)
1538 id.dst_port = args->f_id.dst_port;
1539 if ((parent = lookup_dyn_parent(&id, rule)) == NULL) {
1540 printf("ipfw: %s: add parent failed\n", __func__);
1545 if (parent->count >= conn_limit) {
1546 /* See if we can remove some expired rule. */
1547 remove_dyn_rule(rule, parent);
1548 if (parent->count >= conn_limit) {
1549 if (V_fw_verbose && last_log != time_uptime) {
1550 last_log = time_uptime;
1553 * XXX IPv6 flows are not
1556 if (IS_IP6_FLOW_ID(&(args->f_id))) {
1557 char ip6buf[INET6_ADDRSTRLEN];
1558 snprintf(src, sizeof(src),
1559 "[%s]", ip6_sprintf(ip6buf,
1560 &args->f_id.src_ip6));
1561 snprintf(dst, sizeof(dst),
1562 "[%s]", ip6_sprintf(ip6buf,
1563 &args->f_id.dst_ip6));
1568 htonl(args->f_id.src_ip);
1569 inet_ntoa_r(da, src);
1571 htonl(args->f_id.dst_ip);
1572 inet_ntoa_r(da, dst);
1574 log(LOG_SECURITY | LOG_DEBUG,
1575 "ipfw: %d %s %s:%u -> %s:%u, %s\n",
1576 parent->rule->rulenum,
1578 src, (args->f_id.src_port),
1579 dst, (args->f_id.dst_port),
1580 "too many entries");
1586 add_dyn_rule(&args->f_id, O_LIMIT, (struct ip_fw *)parent);
1590 printf("ipfw: %s: unknown dynamic rule type %u\n",
1591 __func__, cmd->o.opcode);
1596 /* XXX just set lifetime */
1597 lookup_dyn_rule_locked(&args->f_id, NULL, NULL);
1604 * Generate a TCP packet, containing either a RST or a keepalive.
1605 * When flags & TH_RST, we are sending a RST packet, because of a
1606 * "reset" action matched the packet.
1607 * Otherwise we are sending a keepalive, and flags & TH_
1608 * The 'replyto' mbuf is the mbuf being replied to, if any, and is required
1609 * so that MAC can label the reply appropriately.
1611 static struct mbuf *
1612 send_pkt(struct mbuf *replyto, struct ipfw_flow_id *id, u_int32_t seq,
1613 u_int32_t ack, int flags)
1615 INIT_VNET_INET(curvnet);
1620 MGETHDR(m, M_DONTWAIT, MT_DATA);
1623 m->m_pkthdr.rcvif = (struct ifnet *)0;
1625 M_SETFIB(m, id->fib);
1627 if (replyto != NULL)
1628 mac_netinet_firewall_reply(replyto, m);
1630 mac_netinet_firewall_send(m);
1632 (void)replyto; /* don't warn about unused arg */
1635 m->m_pkthdr.len = m->m_len = sizeof(struct ip) + sizeof(struct tcphdr);
1636 m->m_data += max_linkhdr;
1638 ip = mtod(m, struct ip *);
1639 bzero(ip, m->m_len);
1640 tcp = (struct tcphdr *)(ip + 1); /* no IP options */
1641 ip->ip_p = IPPROTO_TCP;
1644 * Assume we are sending a RST (or a keepalive in the reverse
1645 * direction), swap src and destination addresses and ports.
1647 ip->ip_src.s_addr = htonl(id->dst_ip);
1648 ip->ip_dst.s_addr = htonl(id->src_ip);
1649 tcp->th_sport = htons(id->dst_port);
1650 tcp->th_dport = htons(id->src_port);
1651 if (flags & TH_RST) { /* we are sending a RST */
1652 if (flags & TH_ACK) {
1653 tcp->th_seq = htonl(ack);
1654 tcp->th_ack = htonl(0);
1655 tcp->th_flags = TH_RST;
1659 tcp->th_seq = htonl(0);
1660 tcp->th_ack = htonl(seq);
1661 tcp->th_flags = TH_RST | TH_ACK;
1665 * We are sending a keepalive. flags & TH_SYN determines
1666 * the direction, forward if set, reverse if clear.
1667 * NOTE: seq and ack are always assumed to be correct
1668 * as set by the caller. This may be confusing...
1670 if (flags & TH_SYN) {
1672 * we have to rewrite the correct addresses!
1674 ip->ip_dst.s_addr = htonl(id->dst_ip);
1675 ip->ip_src.s_addr = htonl(id->src_ip);
1676 tcp->th_dport = htons(id->dst_port);
1677 tcp->th_sport = htons(id->src_port);
1679 tcp->th_seq = htonl(seq);
1680 tcp->th_ack = htonl(ack);
1681 tcp->th_flags = TH_ACK;
1684 * set ip_len to the payload size so we can compute
1685 * the tcp checksum on the pseudoheader
1686 * XXX check this, could save a couple of words ?
1688 ip->ip_len = htons(sizeof(struct tcphdr));
1689 tcp->th_sum = in_cksum(m, m->m_pkthdr.len);
1691 * now fill fields left out earlier
1693 ip->ip_ttl = V_ip_defttl;
1694 ip->ip_len = m->m_pkthdr.len;
1695 m->m_flags |= M_SKIP_FIREWALL;
1700 * sends a reject message, consuming the mbuf passed as an argument.
1703 send_reject(struct ip_fw_args *args, int code, int ip_len, struct ip *ip)
1707 /* XXX When ip is not guaranteed to be at mtod() we will
1708 * need to account for this */
1709 * The mbuf will however be thrown away so we can adjust it.
1710 * Remember we did an m_pullup on it already so we
1711 * can make some assumptions about contiguousness.
1714 m_adj(m, args->L3offset);
1716 if (code != ICMP_REJECT_RST) { /* Send an ICMP unreach */
1717 /* We need the IP header in host order for icmp_error(). */
1718 if (args->eh != NULL) {
1719 ip->ip_len = ntohs(ip->ip_len);
1720 ip->ip_off = ntohs(ip->ip_off);
1722 icmp_error(args->m, ICMP_UNREACH, code, 0L, 0);
1723 } else if (args->f_id.proto == IPPROTO_TCP) {
1724 struct tcphdr *const tcp =
1725 L3HDR(struct tcphdr, mtod(args->m, struct ip *));
1726 if ( (tcp->th_flags & TH_RST) == 0) {
1728 m = send_pkt(args->m, &(args->f_id),
1729 ntohl(tcp->th_seq), ntohl(tcp->th_ack),
1730 tcp->th_flags | TH_RST);
1732 ip_output(m, NULL, NULL, 0, NULL, NULL);
1742 * Given an ip_fw *, lookup_next_rule will return a pointer
1743 * to the next rule, which can be either the jump
1744 * target (for skipto instructions) or the next one in the list (in
1745 * all other cases including a missing jump target).
1746 * The result is also written in the "next_rule" field of the rule.
1747 * Backward jumps are not allowed, so start looking from the next
1750 * This never returns NULL -- in case we do not have an exact match,
1751 * the next rule is returned. When the ruleset is changed,
1752 * pointers are flushed so we are always correct.
1755 static struct ip_fw *
1756 lookup_next_rule(struct ip_fw *me, u_int32_t tablearg)
1758 struct ip_fw *rule = NULL;
1762 /* look for action, in case it is a skipto */
1763 cmd = ACTION_PTR(me);
1764 if (cmd->opcode == O_LOG)
1766 if (cmd->opcode == O_ALTQ)
1768 if (cmd->opcode == O_TAG)
1770 if (cmd->opcode == O_SKIPTO ) {
1771 if (tablearg != 0) {
1772 rulenum = (u_int16_t)tablearg;
1774 rulenum = cmd->arg1;
1776 for (rule = me->next; rule ; rule = rule->next) {
1777 if (rule->rulenum >= rulenum) {
1782 if (rule == NULL) /* failure or not a skipto */
1784 me->next_rule = rule;
1789 add_table_entry(struct ip_fw_chain *ch, uint16_t tbl, in_addr_t addr,
1790 uint8_t mlen, uint32_t value)
1792 INIT_VNET_IPFW(curvnet);
1793 struct radix_node_head *rnh;
1794 struct table_entry *ent;
1796 if (tbl >= IPFW_TABLES_MAX)
1798 rnh = ch->tables[tbl];
1799 ent = malloc(sizeof(*ent), M_IPFW_TBL, M_NOWAIT | M_ZERO);
1803 ent->addr.sin_len = ent->mask.sin_len = 8;
1804 ent->mask.sin_addr.s_addr = htonl(mlen ? ~((1 << (32 - mlen)) - 1) : 0);
1805 ent->addr.sin_addr.s_addr = addr & ent->mask.sin_addr.s_addr;
1806 IPFW_WLOCK(&V_layer3_chain);
1807 if (rnh->rnh_addaddr(&ent->addr, &ent->mask, rnh, (void *)ent) ==
1809 IPFW_WUNLOCK(&V_layer3_chain);
1810 free(ent, M_IPFW_TBL);
1813 IPFW_WUNLOCK(&V_layer3_chain);
1818 del_table_entry(struct ip_fw_chain *ch, uint16_t tbl, in_addr_t addr,
1821 struct radix_node_head *rnh;
1822 struct table_entry *ent;
1823 struct sockaddr_in sa, mask;
1825 if (tbl >= IPFW_TABLES_MAX)
1827 rnh = ch->tables[tbl];
1828 sa.sin_len = mask.sin_len = 8;
1829 mask.sin_addr.s_addr = htonl(mlen ? ~((1 << (32 - mlen)) - 1) : 0);
1830 sa.sin_addr.s_addr = addr & mask.sin_addr.s_addr;
1832 ent = (struct table_entry *)rnh->rnh_deladdr(&sa, &mask, rnh);
1838 free(ent, M_IPFW_TBL);
1843 flush_table_entry(struct radix_node *rn, void *arg)
1845 struct radix_node_head * const rnh = arg;
1846 struct table_entry *ent;
1848 ent = (struct table_entry *)
1849 rnh->rnh_deladdr(rn->rn_key, rn->rn_mask, rnh);
1851 free(ent, M_IPFW_TBL);
1856 flush_table(struct ip_fw_chain *ch, uint16_t tbl)
1858 struct radix_node_head *rnh;
1860 IPFW_WLOCK_ASSERT(ch);
1862 if (tbl >= IPFW_TABLES_MAX)
1864 rnh = ch->tables[tbl];
1865 KASSERT(rnh != NULL, ("NULL IPFW table"));
1866 rnh->rnh_walktree(rnh, flush_table_entry, rnh);
1871 flush_tables(struct ip_fw_chain *ch)
1875 IPFW_WLOCK_ASSERT(ch);
1877 for (tbl = 0; tbl < IPFW_TABLES_MAX; tbl++)
1878 flush_table(ch, tbl);
1882 init_tables(struct ip_fw_chain *ch)
1887 for (i = 0; i < IPFW_TABLES_MAX; i++) {
1888 if (!rn_inithead((void **)&ch->tables[i], 32)) {
1889 for (j = 0; j < i; j++) {
1890 (void) flush_table(ch, j);
1899 lookup_table(struct ip_fw_chain *ch, uint16_t tbl, in_addr_t addr,
1902 struct radix_node_head *rnh;
1903 struct table_entry *ent;
1904 struct sockaddr_in sa;
1906 if (tbl >= IPFW_TABLES_MAX)
1908 rnh = ch->tables[tbl];
1910 sa.sin_addr.s_addr = addr;
1911 ent = (struct table_entry *)(rnh->rnh_lookup(&sa, NULL, rnh));
1920 count_table_entry(struct radix_node *rn, void *arg)
1922 u_int32_t * const cnt = arg;
1929 count_table(struct ip_fw_chain *ch, uint32_t tbl, uint32_t *cnt)
1931 struct radix_node_head *rnh;
1933 if (tbl >= IPFW_TABLES_MAX)
1935 rnh = ch->tables[tbl];
1937 rnh->rnh_walktree(rnh, count_table_entry, cnt);
1942 dump_table_entry(struct radix_node *rn, void *arg)
1944 struct table_entry * const n = (struct table_entry *)rn;
1945 ipfw_table * const tbl = arg;
1946 ipfw_table_entry *ent;
1948 if (tbl->cnt == tbl->size)
1950 ent = &tbl->ent[tbl->cnt];
1951 ent->tbl = tbl->tbl;
1952 if (in_nullhost(n->mask.sin_addr))
1955 ent->masklen = 33 - ffs(ntohl(n->mask.sin_addr.s_addr));
1956 ent->addr = n->addr.sin_addr.s_addr;
1957 ent->value = n->value;
1963 dump_table(struct ip_fw_chain *ch, ipfw_table *tbl)
1965 struct radix_node_head *rnh;
1967 if (tbl->tbl >= IPFW_TABLES_MAX)
1969 rnh = ch->tables[tbl->tbl];
1971 rnh->rnh_walktree(rnh, dump_table_entry, tbl);
1976 fill_ugid_cache(struct inpcb *inp, struct ip_fw_ugid *ugp)
1981 ugp->fw_prid = jailed(cr) ? cr->cr_prison->pr_id : -1;
1982 ugp->fw_uid = cr->cr_uid;
1983 ugp->fw_ngroups = cr->cr_ngroups;
1984 bcopy(cr->cr_groups, ugp->fw_groups, sizeof(ugp->fw_groups));
1988 check_uidgid(ipfw_insn_u32 *insn, int proto, struct ifnet *oif,
1989 struct in_addr dst_ip, u_int16_t dst_port, struct in_addr src_ip,
1990 u_int16_t src_port, struct ip_fw_ugid *ugp, int *ugid_lookupp,
1993 INIT_VNET_INET(curvnet);
1994 struct inpcbinfo *pi;
2001 * Check to see if the UDP or TCP stack supplied us with
2002 * the PCB. If so, rather then holding a lock and looking
2003 * up the PCB, we can use the one that was supplied.
2005 if (inp && *ugid_lookupp == 0) {
2006 INP_LOCK_ASSERT(inp);
2007 if (inp->inp_socket != NULL) {
2008 fill_ugid_cache(inp, ugp);
2014 * If we have already been here and the packet has no
2015 * PCB entry associated with it, then we can safely
2016 * assume that this is a no match.
2018 if (*ugid_lookupp == -1)
2020 if (proto == IPPROTO_TCP) {
2023 } else if (proto == IPPROTO_UDP) {
2024 wildcard = INPLOOKUP_WILDCARD;
2029 if (*ugid_lookupp == 0) {
2032 in_pcblookup_hash(pi,
2033 dst_ip, htons(dst_port),
2034 src_ip, htons(src_port),
2036 in_pcblookup_hash(pi,
2037 src_ip, htons(src_port),
2038 dst_ip, htons(dst_port),
2041 fill_ugid_cache(pcb, ugp);
2044 INP_INFO_RUNLOCK(pi);
2045 if (*ugid_lookupp == 0) {
2047 * If the lookup did not yield any results, there
2048 * is no sense in coming back and trying again. So
2049 * we can set lookup to -1 and ensure that we wont
2050 * bother the pcb system again.
2056 if (insn->o.opcode == O_UID)
2057 match = (ugp->fw_uid == (uid_t)insn->d[0]);
2058 else if (insn->o.opcode == O_GID) {
2059 for (gp = ugp->fw_groups;
2060 gp < &ugp->fw_groups[ugp->fw_ngroups]; gp++)
2061 if (*gp == (gid_t)insn->d[0]) {
2065 } else if (insn->o.opcode == O_JAIL)
2066 match = (ugp->fw_prid == (int)insn->d[0]);
2071 * The main check routine for the firewall.
2073 * All arguments are in args so we can modify them and return them
2074 * back to the caller.
2078 * args->m (in/out) The packet; we set to NULL when/if we nuke it.
2079 * Starts with the IP header.
2080 * args->eh (in) Mac header if present, or NULL for layer3 packet.
2081 * args->L3offset Number of bytes bypassed if we came from L2.
2082 * e.g. often sizeof(eh) ** NOTYET **
2083 * args->oif Outgoing interface, or NULL if packet is incoming.
2084 * The incoming interface is in the mbuf. (in)
2085 * args->divert_rule (in/out)
2086 * Skip up to the first rule past this rule number;
2087 * upon return, non-zero port number for divert or tee.
2089 * args->rule Pointer to the last matching rule (in/out)
2090 * args->next_hop Socket we are forwarding to (out).
2091 * args->f_id Addresses grabbed from the packet (out)
2092 * args->cookie a cookie depending on rule action
2096 * IP_FW_PASS the packet must be accepted
2097 * IP_FW_DENY the packet must be dropped
2098 * IP_FW_DIVERT divert packet, port in m_tag
2099 * IP_FW_TEE tee packet, port in m_tag
2100 * IP_FW_DUMMYNET to dummynet, pipe in args->cookie
2101 * IP_FW_NETGRAPH into netgraph, cookie args->cookie
2105 ipfw_chk(struct ip_fw_args *args)
2107 INIT_VNET_INET(curvnet);
2108 INIT_VNET_IPFW(curvnet);
2111 * Local variables holding state during the processing of a packet:
2113 * IMPORTANT NOTE: to speed up the processing of rules, there
2114 * are some assumption on the values of the variables, which
2115 * are documented here. Should you change them, please check
2116 * the implementation of the various instructions to make sure
2117 * that they still work.
2119 * args->eh The MAC header. It is non-null for a layer2
2120 * packet, it is NULL for a layer-3 packet.
2122 * args->L3offset Offset in the packet to the L3 (IP or equiv.) header.
2124 * m | args->m Pointer to the mbuf, as received from the caller.
2125 * It may change if ipfw_chk() does an m_pullup, or if it
2126 * consumes the packet because it calls send_reject().
2127 * XXX This has to change, so that ipfw_chk() never modifies
2128 * or consumes the buffer.
2129 * ip is the beginning of the ip(4 or 6) header.
2130 * Calculated by adding the L3offset to the start of data.
2131 * (Until we start using L3offset, the packet is
2132 * supposed to start with the ip header).
2134 struct mbuf *m = args->m;
2135 struct ip *ip = mtod(m, struct ip *);
2138 * For rules which contain uid/gid or jail constraints, cache
2139 * a copy of the users credentials after the pcb lookup has been
2140 * executed. This will speed up the processing of rules with
2141 * these types of constraints, as well as decrease contention
2142 * on pcb related locks.
2144 struct ip_fw_ugid fw_ugid_cache;
2145 int ugid_lookup = 0;
2148 * divinput_flags If non-zero, set to the IP_FW_DIVERT_*_FLAG
2149 * associated with a packet input on a divert socket. This
2150 * will allow to distinguish traffic and its direction when
2151 * it originates from a divert socket.
2153 u_int divinput_flags = 0;
2156 * oif | args->oif If NULL, ipfw_chk has been called on the
2157 * inbound path (ether_input, ip_input).
2158 * If non-NULL, ipfw_chk has been called on the outbound path
2159 * (ether_output, ip_output).
2161 struct ifnet *oif = args->oif;
2163 struct ip_fw *f = NULL; /* matching rule */
2167 * hlen The length of the IP header.
2169 u_int hlen = 0; /* hlen >0 means we have an IP pkt */
2172 * offset The offset of a fragment. offset != 0 means that
2173 * we have a fragment at this offset of an IPv4 packet.
2174 * offset == 0 means that (if this is an IPv4 packet)
2175 * this is the first or only fragment.
2176 * For IPv6 offset == 0 means there is no Fragment Header.
2177 * If offset != 0 for IPv6 always use correct mask to
2178 * get the correct offset because we add IP6F_MORE_FRAG
2179 * to be able to dectect the first fragment which would
2180 * otherwise have offset = 0.
2185 * Local copies of addresses. They are only valid if we have
2188 * proto The protocol. Set to 0 for non-ip packets,
2189 * or to the protocol read from the packet otherwise.
2190 * proto != 0 means that we have an IPv4 packet.
2192 * src_port, dst_port port numbers, in HOST format. Only
2193 * valid for TCP and UDP packets.
2195 * src_ip, dst_ip ip addresses, in NETWORK format.
2196 * Only valid for IPv4 packets.
2199 u_int16_t src_port = 0, dst_port = 0; /* NOTE: host format */
2200 struct in_addr src_ip, dst_ip; /* NOTE: network format */
2203 u_int16_t etype = 0; /* Host order stored ether type */
2206 * dyn_dir = MATCH_UNKNOWN when rules unchecked,
2207 * MATCH_NONE when checked and not matched (q = NULL),
2208 * MATCH_FORWARD or MATCH_REVERSE otherwise (q != NULL)
2210 int dyn_dir = MATCH_UNKNOWN;
2211 ipfw_dyn_rule *q = NULL;
2212 struct ip_fw_chain *chain = &V_layer3_chain;
2216 * We store in ulp a pointer to the upper layer protocol header.
2217 * In the ipv4 case this is easy to determine from the header,
2218 * but for ipv6 we might have some additional headers in the middle.
2219 * ulp is NULL if not found.
2221 void *ulp = NULL; /* upper layer protocol pointer. */
2222 /* XXX ipv6 variables */
2224 u_int16_t ext_hd = 0; /* bits vector for extension header filtering */
2225 /* end of ipv6 variables */
2228 if (m->m_flags & M_SKIP_FIREWALL)
2229 return (IP_FW_PASS); /* accept */
2231 pktlen = m->m_pkthdr.len;
2232 args->f_id.fib = M_GETFIB(m); /* note mbuf not altered) */
2233 proto = args->f_id.proto = 0; /* mark f_id invalid */
2234 /* XXX 0 is a valid proto: IP/IPv6 Hop-by-Hop Option */
2237 * PULLUP_TO(len, p, T) makes sure that len + sizeof(T) is contiguous,
2238 * then it sets p to point at the offset "len" in the mbuf. WARNING: the
2239 * pointer might become stale after other pullups (but we never use it
2242 #define PULLUP_TO(len, p, T) \
2244 int x = (len) + sizeof(T); \
2245 if ((m)->m_len < x) { \
2246 args->m = m = m_pullup(m, x); \
2248 goto pullup_failed; \
2250 p = (mtod(m, char *) + (len)); \
2254 * if we have an ether header,
2257 etype = ntohs(args->eh->ether_type);
2259 /* Identify IP packets and fill up variables. */
2260 if (pktlen >= sizeof(struct ip6_hdr) &&
2261 (args->eh == NULL || etype == ETHERTYPE_IPV6) && ip->ip_v == 6) {
2262 struct ip6_hdr *ip6 = (struct ip6_hdr *)ip;
2264 args->f_id.addr_type = 6;
2265 hlen = sizeof(struct ip6_hdr);
2266 proto = ip6->ip6_nxt;
2268 /* Search extension headers to find upper layer protocols */
2269 while (ulp == NULL) {
2271 case IPPROTO_ICMPV6:
2272 PULLUP_TO(hlen, ulp, struct icmp6_hdr);
2273 args->f_id.flags = ICMP6(ulp)->icmp6_type;
2277 PULLUP_TO(hlen, ulp, struct tcphdr);
2278 dst_port = TCP(ulp)->th_dport;
2279 src_port = TCP(ulp)->th_sport;
2280 args->f_id.flags = TCP(ulp)->th_flags;
2284 PULLUP_TO(hlen, ulp, struct sctphdr);
2285 src_port = SCTP(ulp)->src_port;
2286 dst_port = SCTP(ulp)->dest_port;
2290 PULLUP_TO(hlen, ulp, struct udphdr);
2291 dst_port = UDP(ulp)->uh_dport;
2292 src_port = UDP(ulp)->uh_sport;
2295 case IPPROTO_HOPOPTS: /* RFC 2460 */
2296 PULLUP_TO(hlen, ulp, struct ip6_hbh);
2297 ext_hd |= EXT_HOPOPTS;
2298 hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3;
2299 proto = ((struct ip6_hbh *)ulp)->ip6h_nxt;
2303 case IPPROTO_ROUTING: /* RFC 2460 */
2304 PULLUP_TO(hlen, ulp, struct ip6_rthdr);
2305 switch (((struct ip6_rthdr *)ulp)->ip6r_type) {
2307 ext_hd |= EXT_RTHDR0;
2310 ext_hd |= EXT_RTHDR2;
2313 printf("IPFW2: IPV6 - Unknown Routing "
2314 "Header type(%d)\n",
2315 ((struct ip6_rthdr *)ulp)->ip6r_type);
2316 if (V_fw_deny_unknown_exthdrs)
2317 return (IP_FW_DENY);
2320 ext_hd |= EXT_ROUTING;
2321 hlen += (((struct ip6_rthdr *)ulp)->ip6r_len + 1) << 3;
2322 proto = ((struct ip6_rthdr *)ulp)->ip6r_nxt;
2326 case IPPROTO_FRAGMENT: /* RFC 2460 */
2327 PULLUP_TO(hlen, ulp, struct ip6_frag);
2328 ext_hd |= EXT_FRAGMENT;
2329 hlen += sizeof (struct ip6_frag);
2330 proto = ((struct ip6_frag *)ulp)->ip6f_nxt;
2331 offset = ((struct ip6_frag *)ulp)->ip6f_offlg &
2333 /* Add IP6F_MORE_FRAG for offset of first
2334 * fragment to be != 0. */
2335 offset |= ((struct ip6_frag *)ulp)->ip6f_offlg &
2338 printf("IPFW2: IPV6 - Invalid Fragment "
2340 if (V_fw_deny_unknown_exthdrs)
2341 return (IP_FW_DENY);
2344 args->f_id.frag_id6 =
2345 ntohl(((struct ip6_frag *)ulp)->ip6f_ident);
2349 case IPPROTO_DSTOPTS: /* RFC 2460 */
2350 PULLUP_TO(hlen, ulp, struct ip6_hbh);
2351 ext_hd |= EXT_DSTOPTS;
2352 hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3;
2353 proto = ((struct ip6_hbh *)ulp)->ip6h_nxt;
2357 case IPPROTO_AH: /* RFC 2402 */
2358 PULLUP_TO(hlen, ulp, struct ip6_ext);
2360 hlen += (((struct ip6_ext *)ulp)->ip6e_len + 2) << 2;
2361 proto = ((struct ip6_ext *)ulp)->ip6e_nxt;
2365 case IPPROTO_ESP: /* RFC 2406 */
2366 PULLUP_TO(hlen, ulp, uint32_t); /* SPI, Seq# */
2367 /* Anything past Seq# is variable length and
2368 * data past this ext. header is encrypted. */
2372 case IPPROTO_NONE: /* RFC 2460 */
2374 * Packet ends here, and IPv6 header has
2375 * already been pulled up. If ip6e_len!=0
2376 * then octets must be ignored.
2378 ulp = ip; /* non-NULL to get out of loop. */
2381 case IPPROTO_OSPFIGP:
2382 /* XXX OSPF header check? */
2383 PULLUP_TO(hlen, ulp, struct ip6_ext);
2387 /* XXX PIM header check? */
2388 PULLUP_TO(hlen, ulp, struct pim);
2392 PULLUP_TO(hlen, ulp, struct carp_header);
2393 if (((struct carp_header *)ulp)->carp_version !=
2395 return (IP_FW_DENY);
2396 if (((struct carp_header *)ulp)->carp_type !=
2398 return (IP_FW_DENY);
2401 case IPPROTO_IPV6: /* RFC 2893 */
2402 PULLUP_TO(hlen, ulp, struct ip6_hdr);
2405 case IPPROTO_IPV4: /* RFC 2893 */
2406 PULLUP_TO(hlen, ulp, struct ip);
2410 printf("IPFW2: IPV6 - Unknown Extension "
2411 "Header(%d), ext_hd=%x\n", proto, ext_hd);
2412 if (V_fw_deny_unknown_exthdrs)
2413 return (IP_FW_DENY);
2414 PULLUP_TO(hlen, ulp, struct ip6_ext);
2418 ip = mtod(m, struct ip *);
2419 ip6 = (struct ip6_hdr *)ip;
2420 args->f_id.src_ip6 = ip6->ip6_src;
2421 args->f_id.dst_ip6 = ip6->ip6_dst;
2422 args->f_id.src_ip = 0;
2423 args->f_id.dst_ip = 0;
2424 args->f_id.flow_id6 = ntohl(ip6->ip6_flow);
2425 } else if (pktlen >= sizeof(struct ip) &&
2426 (args->eh == NULL || etype == ETHERTYPE_IP) && ip->ip_v == 4) {
2428 hlen = ip->ip_hl << 2;
2429 args->f_id.addr_type = 4;
2432 * Collect parameters into local variables for faster matching.
2435 src_ip = ip->ip_src;
2436 dst_ip = ip->ip_dst;
2437 if (args->eh != NULL) { /* layer 2 packets are as on the wire */
2438 offset = ntohs(ip->ip_off) & IP_OFFMASK;
2439 ip_len = ntohs(ip->ip_len);
2441 offset = ip->ip_off & IP_OFFMASK;
2442 ip_len = ip->ip_len;
2444 pktlen = ip_len < pktlen ? ip_len : pktlen;
2449 PULLUP_TO(hlen, ulp, struct tcphdr);
2450 dst_port = TCP(ulp)->th_dport;
2451 src_port = TCP(ulp)->th_sport;
2452 args->f_id.flags = TCP(ulp)->th_flags;
2456 PULLUP_TO(hlen, ulp, struct udphdr);
2457 dst_port = UDP(ulp)->uh_dport;
2458 src_port = UDP(ulp)->uh_sport;
2462 PULLUP_TO(hlen, ulp, struct icmphdr);
2463 args->f_id.flags = ICMP(ulp)->icmp_type;
2471 ip = mtod(m, struct ip *);
2472 args->f_id.src_ip = ntohl(src_ip.s_addr);
2473 args->f_id.dst_ip = ntohl(dst_ip.s_addr);
2476 if (proto) { /* we may have port numbers, store them */
2477 args->f_id.proto = proto;
2478 args->f_id.src_port = src_port = ntohs(src_port);
2479 args->f_id.dst_port = dst_port = ntohs(dst_port);
2483 mtag = m_tag_find(m, PACKET_TAG_DIVERT, NULL);
2486 * Packet has already been tagged. Look for the next rule
2487 * to restart processing.
2489 * If fw_one_pass != 0 then just accept it.
2490 * XXX should not happen here, but optimized out in
2493 if (V_fw_one_pass) {
2494 IPFW_RUNLOCK(chain);
2495 return (IP_FW_PASS);
2498 f = args->rule->next_rule;
2500 f = lookup_next_rule(args->rule, 0);
2503 * Find the starting rule. It can be either the first
2504 * one, or the one after divert_rule if asked so.
2506 int skipto = mtag ? divert_cookie(mtag) : 0;
2509 if (args->eh == NULL && skipto != 0) {
2510 if (skipto >= IPFW_DEFAULT_RULE) {
2511 IPFW_RUNLOCK(chain);
2512 return (IP_FW_DENY); /* invalid */
2514 while (f && f->rulenum <= skipto)
2516 if (f == NULL) { /* drop packet */
2517 IPFW_RUNLOCK(chain);
2518 return (IP_FW_DENY);
2522 /* reset divert rule to avoid confusion later */
2524 divinput_flags = divert_info(mtag) &
2525 (IP_FW_DIVERT_OUTPUT_FLAG | IP_FW_DIVERT_LOOPBACK_FLAG);
2526 m_tag_delete(m, mtag);
2530 * Now scan the rules, and parse microinstructions for each rule.
2532 for (; f; f = f->next) {
2534 uint32_t tablearg = 0;
2535 int l, cmdlen, skip_or; /* skip rest of OR block */
2538 if (V_set_disable & (1 << f->set) )
2542 for (l = f->cmd_len, cmd = f->cmd ; l > 0 ;
2543 l -= cmdlen, cmd += cmdlen) {
2547 * check_body is a jump target used when we find a
2548 * CHECK_STATE, and need to jump to the body of
2553 cmdlen = F_LEN(cmd);
2555 * An OR block (insn_1 || .. || insn_n) has the
2556 * F_OR bit set in all but the last instruction.
2557 * The first match will set "skip_or", and cause
2558 * the following instructions to be skipped until
2559 * past the one with the F_OR bit clear.
2561 if (skip_or) { /* skip this instruction */
2562 if ((cmd->len & F_OR) == 0)
2563 skip_or = 0; /* next one is good */
2566 match = 0; /* set to 1 if we succeed */
2568 switch (cmd->opcode) {
2570 * The first set of opcodes compares the packet's
2571 * fields with some pattern, setting 'match' if a
2572 * match is found. At the end of the loop there is
2573 * logic to deal with F_NOT and F_OR flags associated
2581 printf("ipfw: opcode %d unimplemented\n",
2589 * We only check offset == 0 && proto != 0,
2590 * as this ensures that we have a
2591 * packet with the ports info.
2595 if (is_ipv6) /* XXX to be fixed later */
2597 if (proto == IPPROTO_TCP ||
2598 proto == IPPROTO_UDP)
2599 match = check_uidgid(
2600 (ipfw_insn_u32 *)cmd,
2603 src_ip, src_port, &fw_ugid_cache,
2604 &ugid_lookup, args->inp);
2608 match = iface_match(m->m_pkthdr.rcvif,
2609 (ipfw_insn_if *)cmd);
2613 match = iface_match(oif, (ipfw_insn_if *)cmd);
2617 match = iface_match(oif ? oif :
2618 m->m_pkthdr.rcvif, (ipfw_insn_if *)cmd);
2622 if (args->eh != NULL) { /* have MAC header */
2623 u_int32_t *want = (u_int32_t *)
2624 ((ipfw_insn_mac *)cmd)->addr;
2625 u_int32_t *mask = (u_int32_t *)
2626 ((ipfw_insn_mac *)cmd)->mask;
2627 u_int32_t *hdr = (u_int32_t *)args->eh;
2630 ( want[0] == (hdr[0] & mask[0]) &&
2631 want[1] == (hdr[1] & mask[1]) &&
2632 want[2] == (hdr[2] & mask[2]) );
2637 if (args->eh != NULL) {
2639 ((ipfw_insn_u16 *)cmd)->ports;
2642 for (i = cmdlen - 1; !match && i>0;
2644 match = (etype >= p[0] &&
2650 match = (offset != 0);
2653 case O_IN: /* "out" is "not in" */
2654 match = (oif == NULL);
2658 match = (args->eh != NULL);
2662 match = (cmd->arg1 & 1 && divinput_flags &
2663 IP_FW_DIVERT_LOOPBACK_FLAG) ||
2664 (cmd->arg1 & 2 && divinput_flags &
2665 IP_FW_DIVERT_OUTPUT_FLAG);
2670 * We do not allow an arg of 0 so the
2671 * check of "proto" only suffices.
2673 match = (proto == cmd->arg1);
2678 (((ipfw_insn_ip *)cmd)->addr.s_addr ==
2682 case O_IP_SRC_LOOKUP:
2683 case O_IP_DST_LOOKUP:
2686 (cmd->opcode == O_IP_DST_LOOKUP) ?
2687 dst_ip.s_addr : src_ip.s_addr;
2690 match = lookup_table(chain, cmd->arg1, a,
2694 if (cmdlen == F_INSN_SIZE(ipfw_insn_u32))
2696 ((ipfw_insn_u32 *)cmd)->d[0] == v;
2706 (cmd->opcode == O_IP_DST_MASK) ?
2707 dst_ip.s_addr : src_ip.s_addr;
2708 uint32_t *p = ((ipfw_insn_u32 *)cmd)->d;
2711 for (; !match && i>0; i-= 2, p+= 2)
2712 match = (p[0] == (a & p[1]));
2720 INADDR_TO_IFP(src_ip, tif);
2721 match = (tif != NULL);
2728 u_int32_t *d = (u_int32_t *)(cmd+1);
2730 cmd->opcode == O_IP_DST_SET ?
2736 addr -= d[0]; /* subtract base */
2737 match = (addr < cmd->arg1) &&
2738 ( d[ 1 + (addr>>5)] &
2739 (1<<(addr & 0x1f)) );
2745 (((ipfw_insn_ip *)cmd)->addr.s_addr ==
2753 INADDR_TO_IFP(dst_ip, tif);
2754 match = (tif != NULL);
2761 * offset == 0 && proto != 0 is enough
2762 * to guarantee that we have a
2763 * packet with port info.
2765 if ((proto==IPPROTO_UDP || proto==IPPROTO_TCP)
2768 (cmd->opcode == O_IP_SRCPORT) ?
2769 src_port : dst_port ;
2771 ((ipfw_insn_u16 *)cmd)->ports;
2774 for (i = cmdlen - 1; !match && i>0;
2776 match = (x>=p[0] && x<=p[1]);
2781 match = (offset == 0 && proto==IPPROTO_ICMP &&
2782 icmptype_match(ICMP(ulp), (ipfw_insn_u32 *)cmd) );
2787 match = is_ipv6 && offset == 0 &&
2788 proto==IPPROTO_ICMPV6 &&
2790 ICMP6(ulp)->icmp6_type,
2791 (ipfw_insn_u32 *)cmd);
2797 ipopts_match(ip, cmd) );
2802 cmd->arg1 == ip->ip_v);
2808 if (is_ipv4) { /* only for IP packets */
2813 if (cmd->opcode == O_IPLEN)
2815 else if (cmd->opcode == O_IPTTL)
2817 else /* must be IPID */
2818 x = ntohs(ip->ip_id);
2820 match = (cmd->arg1 == x);
2823 /* otherwise we have ranges */
2824 p = ((ipfw_insn_u16 *)cmd)->ports;
2826 for (; !match && i>0; i--, p += 2)
2827 match = (x >= p[0] && x <= p[1]);
2831 case O_IPPRECEDENCE:
2833 (cmd->arg1 == (ip->ip_tos & 0xe0)) );
2838 flags_match(cmd, ip->ip_tos));
2842 if (proto == IPPROTO_TCP && offset == 0) {
2850 ((ip->ip_hl + tcp->th_off) << 2);
2852 match = (cmd->arg1 == x);
2855 /* otherwise we have ranges */
2856 p = ((ipfw_insn_u16 *)cmd)->ports;
2858 for (; !match && i>0; i--, p += 2)
2859 match = (x >= p[0] && x <= p[1]);
2864 match = (proto == IPPROTO_TCP && offset == 0 &&
2865 flags_match(cmd, TCP(ulp)->th_flags));
2869 match = (proto == IPPROTO_TCP && offset == 0 &&
2870 tcpopts_match(TCP(ulp), cmd));
2874 match = (proto == IPPROTO_TCP && offset == 0 &&
2875 ((ipfw_insn_u32 *)cmd)->d[0] ==
2880 match = (proto == IPPROTO_TCP && offset == 0 &&
2881 ((ipfw_insn_u32 *)cmd)->d[0] ==
2886 match = (proto == IPPROTO_TCP && offset == 0 &&
2887 cmd->arg1 == TCP(ulp)->th_win);
2891 /* reject packets which have SYN only */
2892 /* XXX should i also check for TH_ACK ? */
2893 match = (proto == IPPROTO_TCP && offset == 0 &&
2894 (TCP(ulp)->th_flags &
2895 (TH_RST | TH_ACK | TH_SYN)) != TH_SYN);
2900 ipfw_insn_altq *altq = (ipfw_insn_altq *)cmd;
2903 at = pf_find_mtag(m);
2904 if (at != NULL && at->qid != 0)
2906 at = pf_get_mtag(m);
2909 * Let the packet fall back to the
2914 at->qid = altq->qid;
2925 ipfw_log(f, hlen, args, m,
2926 oif, offset, tablearg, ip);
2931 match = (random()<((ipfw_insn_u32 *)cmd)->d[0]);
2935 /* Outgoing packets automatically pass/match */
2936 match = ((oif != NULL) ||
2937 (m->m_pkthdr.rcvif == NULL) ||
2941 verify_path6(&(args->f_id.src_ip6),
2942 m->m_pkthdr.rcvif) :
2944 verify_path(src_ip, m->m_pkthdr.rcvif,
2949 /* Outgoing packets automatically pass/match */
2950 match = (hlen > 0 && ((oif != NULL) ||
2953 verify_path6(&(args->f_id.src_ip6),
2956 verify_path(src_ip, NULL, args->f_id.fib)));
2960 /* Outgoing packets automatically pass/match */
2961 if (oif == NULL && hlen > 0 &&
2962 ( (is_ipv4 && in_localaddr(src_ip))
2965 in6_localaddr(&(args->f_id.src_ip6)))
2970 is_ipv6 ? verify_path6(
2971 &(args->f_id.src_ip6),
2972 m->m_pkthdr.rcvif) :
2983 match = (m_tag_find(m,
2984 PACKET_TAG_IPSEC_IN_DONE, NULL) != NULL);
2986 /* otherwise no match */
2992 IN6_ARE_ADDR_EQUAL(&args->f_id.src_ip6,
2993 &((ipfw_insn_ip6 *)cmd)->addr6);
2998 IN6_ARE_ADDR_EQUAL(&args->f_id.dst_ip6,
2999 &((ipfw_insn_ip6 *)cmd)->addr6);
3001 case O_IP6_SRC_MASK:
3002 case O_IP6_DST_MASK:
3006 struct in6_addr *d =
3007 &((ipfw_insn_ip6 *)cmd)->addr6;
3009 for (; !match && i > 0; d += 2,
3010 i -= F_INSN_SIZE(struct in6_addr)
3016 APPLY_MASK(&p, &d[1]);
3018 IN6_ARE_ADDR_EQUAL(&d[0],
3025 match= is_ipv6 && search_ip6_addr_net(&args->f_id.src_ip6);
3029 match= is_ipv6 && search_ip6_addr_net(&args->f_id.dst_ip6);
3034 flow6id_match(args->f_id.flow_id6,
3035 (ipfw_insn_u32 *) cmd);
3040 (ext_hd & ((ipfw_insn *) cmd)->arg1);
3053 uint32_t tag = (cmd->arg1 == IP_FW_TABLEARG) ?
3054 tablearg : cmd->arg1;
3056 /* Packet is already tagged with this tag? */
3057 mtag = m_tag_locate(m, MTAG_IPFW, tag, NULL);
3059 /* We have `untag' action when F_NOT flag is
3060 * present. And we must remove this mtag from
3061 * mbuf and reset `match' to zero (`match' will
3062 * be inversed later).
3063 * Otherwise we should allocate new mtag and
3064 * push it into mbuf.
3066 if (cmd->len & F_NOT) { /* `untag' action */
3068 m_tag_delete(m, mtag);
3069 } else if (mtag == NULL) {
3070 if ((mtag = m_tag_alloc(MTAG_IPFW,
3071 tag, 0, M_NOWAIT)) != NULL)
3072 m_tag_prepend(m, mtag);
3074 match = (cmd->len & F_NOT) ? 0: 1;
3078 case O_FIB: /* try match the specified fib */
3079 if (args->f_id.fib == cmd->arg1)
3084 uint32_t tag = (cmd->arg1 == IP_FW_TABLEARG) ?
3085 tablearg : cmd->arg1;
3088 match = m_tag_locate(m, MTAG_IPFW,
3093 /* we have ranges */
3094 for (mtag = m_tag_first(m);
3095 mtag != NULL && !match;
3096 mtag = m_tag_next(m, mtag)) {
3100 if (mtag->m_tag_cookie != MTAG_IPFW)
3103 p = ((ipfw_insn_u16 *)cmd)->ports;
3105 for(; !match && i > 0; i--, p += 2)
3107 mtag->m_tag_id >= p[0] &&
3108 mtag->m_tag_id <= p[1];
3114 * The second set of opcodes represents 'actions',
3115 * i.e. the terminal part of a rule once the packet
3116 * matches all previous patterns.
3117 * Typically there is only one action for each rule,
3118 * and the opcode is stored at the end of the rule
3119 * (but there are exceptions -- see below).
3121 * In general, here we set retval and terminate the
3122 * outer loop (would be a 'break 3' in some language,
3123 * but we need to do a 'goto done').
3126 * O_COUNT and O_SKIPTO actions:
3127 * instead of terminating, we jump to the next rule
3128 * ('goto next_rule', equivalent to a 'break 2'),
3129 * or to the SKIPTO target ('goto again' after
3130 * having set f, cmd and l), respectively.
3132 * O_TAG, O_LOG and O_ALTQ action parameters:
3133 * perform some action and set match = 1;
3135 * O_LIMIT and O_KEEP_STATE: these opcodes are
3136 * not real 'actions', and are stored right
3137 * before the 'action' part of the rule.
3138 * These opcodes try to install an entry in the
3139 * state tables; if successful, we continue with
3140 * the next opcode (match=1; break;), otherwise
3141 * the packet * must be dropped
3142 * ('goto done' after setting retval);
3144 * O_PROBE_STATE and O_CHECK_STATE: these opcodes
3145 * cause a lookup of the state table, and a jump
3146 * to the 'action' part of the parent rule
3147 * ('goto check_body') if an entry is found, or
3148 * (CHECK_STATE only) a jump to the next rule if
3149 * the entry is not found ('goto next_rule').
3150 * The result of the lookup is cached to make
3151 * further instances of these opcodes are
3156 if (install_state(f,
3157 (ipfw_insn_limit *)cmd, args, tablearg)) {
3158 retval = IP_FW_DENY;
3159 goto done; /* error/limit violation */
3167 * dynamic rules are checked at the first
3168 * keep-state or check-state occurrence,
3169 * with the result being stored in dyn_dir.
3170 * The compiler introduces a PROBE_STATE
3171 * instruction for us when we have a
3172 * KEEP_STATE (because PROBE_STATE needs
3175 if (dyn_dir == MATCH_UNKNOWN &&
3176 (q = lookup_dyn_rule(&args->f_id,
3177 &dyn_dir, proto == IPPROTO_TCP ?
3181 * Found dynamic entry, update stats
3182 * and jump to the 'action' part of
3188 cmd = ACTION_PTR(f);
3189 l = f->cmd_len - f->act_ofs;
3194 * Dynamic entry not found. If CHECK_STATE,
3195 * skip to next rule, if PROBE_STATE just
3196 * ignore and continue with next opcode.
3198 if (cmd->opcode == O_CHECK_STATE)
3204 retval = 0; /* accept */
3209 args->rule = f; /* report matching rule */
3210 if (cmd->arg1 == IP_FW_TABLEARG)
3211 args->cookie = tablearg;
3213 args->cookie = cmd->arg1;
3214 retval = IP_FW_DUMMYNET;
3219 struct divert_tag *dt;
3221 if (args->eh) /* not on layer 2 */
3223 mtag = m_tag_get(PACKET_TAG_DIVERT,
3224 sizeof(struct divert_tag),
3229 IPFW_RUNLOCK(chain);
3230 return (IP_FW_DENY);
3232 dt = (struct divert_tag *)(mtag+1);
3233 dt->cookie = f->rulenum;
3234 if (cmd->arg1 == IP_FW_TABLEARG)
3235 dt->info = tablearg;
3237 dt->info = cmd->arg1;
3238 m_tag_prepend(m, mtag);
3239 retval = (cmd->opcode == O_DIVERT) ?
3240 IP_FW_DIVERT : IP_FW_TEE;
3245 f->pcnt++; /* update stats */
3247 f->timestamp = time_uptime;
3248 if (cmd->opcode == O_COUNT)
3251 if (cmd->arg1 == IP_FW_TABLEARG) {
3252 f = lookup_next_rule(f, tablearg);
3254 if (f->next_rule == NULL)
3255 lookup_next_rule(f, 0);
3262 * Drop the packet and send a reject notice
3263 * if the packet is not ICMP (or is an ICMP
3264 * query), and it is not multicast/broadcast.
3266 if (hlen > 0 && is_ipv4 && offset == 0 &&
3267 (proto != IPPROTO_ICMP ||
3268 is_icmp_query(ICMP(ulp))) &&
3269 !(m->m_flags & (M_BCAST|M_MCAST)) &&
3270 !IN_MULTICAST(ntohl(dst_ip.s_addr))) {
3271 send_reject(args, cmd->arg1, ip_len, ip);
3277 if (hlen > 0 && is_ipv6 &&
3278 ((offset & IP6F_OFF_MASK) == 0) &&
3279 (proto != IPPROTO_ICMPV6 ||
3280 (is_icmp6_query(args->f_id.flags) == 1)) &&
3281 !(m->m_flags & (M_BCAST|M_MCAST)) &&
3282 !IN6_IS_ADDR_MULTICAST(&args->f_id.dst_ip6)) {
3284 args, cmd->arg1, hlen,
3285 (struct ip6_hdr *)ip);
3291 retval = IP_FW_DENY;
3294 case O_FORWARD_IP: {
3295 struct sockaddr_in *sa;
3296 sa = &(((ipfw_insn_sa *)cmd)->sa);
3297 if (args->eh) /* not valid on layer2 pkts */
3299 if (!q || dyn_dir == MATCH_FORWARD) {
3300 if (sa->sin_addr.s_addr == INADDR_ANY) {
3301 bcopy(sa, &args->hopstore,
3303 args->hopstore.sin_addr.s_addr =
3308 args->next_hop = sa;
3311 retval = IP_FW_PASS;
3317 args->rule = f; /* report matching rule */
3318 if (cmd->arg1 == IP_FW_TABLEARG)
3319 args->cookie = tablearg;
3321 args->cookie = cmd->arg1;
3322 retval = (cmd->opcode == O_NETGRAPH) ?
3323 IP_FW_NETGRAPH : IP_FW_NGTEE;
3327 f->pcnt++; /* update stats */
3329 f->timestamp = time_uptime;
3330 M_SETFIB(m, cmd->arg1);
3331 args->f_id.fib = cmd->arg1;
3338 if (IPFW_NAT_LOADED) {
3339 args->rule = f; /* Report matching rule. */
3340 t = ((ipfw_insn_nat *)cmd)->nat;
3342 nat_id = (cmd->arg1 == IP_FW_TABLEARG) ?
3343 tablearg : cmd->arg1;
3344 LOOKUP_NAT(V_layer3_chain, nat_id, t);
3346 retval = IP_FW_DENY;
3349 if (cmd->arg1 != IP_FW_TABLEARG)
3350 ((ipfw_insn_nat *)cmd)->nat = t;
3352 retval = ipfw_nat_ptr(args, t, m);
3354 retval = IP_FW_DENY;
3359 panic("-- unknown opcode %d\n", cmd->opcode);
3360 } /* end of switch() on opcodes */
3362 if (cmd->len & F_NOT)
3366 if (cmd->len & F_OR)
3369 if (!(cmd->len & F_OR)) /* not an OR block, */
3370 break; /* try next rule */
3373 } /* end of inner for, scan opcodes */
3375 next_rule:; /* try next rule */
3377 } /* end of outer for, scan rules */
3378 printf("ipfw: ouch!, skip past end of rules, denying packet\n");
3379 IPFW_RUNLOCK(chain);
3380 return (IP_FW_DENY);
3383 /* Update statistics */
3386 f->timestamp = time_uptime;
3387 IPFW_RUNLOCK(chain);
3392 printf("ipfw: pullup failed\n");
3393 return (IP_FW_DENY);
3397 * When a rule is added/deleted, clear the next_rule pointers in all rules.
3398 * These will be reconstructed on the fly as packets are matched.
3401 flush_rule_ptrs(struct ip_fw_chain *chain)
3405 IPFW_WLOCK_ASSERT(chain);
3407 for (rule = chain->rules; rule; rule = rule->next)
3408 rule->next_rule = NULL;
3412 * Add a new rule to the list. Copy the rule into a malloc'ed area, then
3413 * possibly create a rule number and add the rule to the list.
3414 * Update the rule_number in the input struct so the caller knows it as well.
3417 add_rule(struct ip_fw_chain *chain, struct ip_fw *input_rule)
3419 INIT_VNET_IPFW(curvnet);
3420 struct ip_fw *rule, *f, *prev;
3421 int l = RULESIZE(input_rule);
3423 if (chain->rules == NULL && input_rule->rulenum != IPFW_DEFAULT_RULE)
3426 rule = malloc(l, M_IPFW, M_NOWAIT | M_ZERO);
3430 bcopy(input_rule, rule, l);
3433 rule->next_rule = NULL;
3437 rule->timestamp = 0;
3441 if (chain->rules == NULL) { /* default rule */
3442 chain->rules = rule;
3447 * If rulenum is 0, find highest numbered rule before the
3448 * default rule, and add autoinc_step
3450 if (V_autoinc_step < 1)
3452 else if (V_autoinc_step > 1000)
3453 V_autoinc_step = 1000;
3454 if (rule->rulenum == 0) {
3456 * locate the highest numbered rule before default
3458 for (f = chain->rules; f; f = f->next) {
3459 if (f->rulenum == IPFW_DEFAULT_RULE)
3461 rule->rulenum = f->rulenum;
3463 if (rule->rulenum < IPFW_DEFAULT_RULE - V_autoinc_step)
3464 rule->rulenum += V_autoinc_step;
3465 input_rule->rulenum = rule->rulenum;
3469 * Now insert the new rule in the right place in the sorted list.
3471 for (prev = NULL, f = chain->rules; f; prev = f, f = f->next) {
3472 if (f->rulenum > rule->rulenum) { /* found the location */
3476 } else { /* head insert */
3477 rule->next = chain->rules;
3478 chain->rules = rule;
3483 flush_rule_ptrs(chain);
3487 IPFW_WUNLOCK(chain);
3488 DEB(printf("ipfw: installed rule %d, static count now %d\n",
3489 rule->rulenum, V_static_count);)
3494 * Remove a static rule (including derived * dynamic rules)
3495 * and place it on the ``reap list'' for later reclamation.
3496 * The caller is in charge of clearing rule pointers to avoid
3497 * dangling pointers.
3498 * @return a pointer to the next entry.
3499 * Arguments are not checked, so they better be correct.
3501 static struct ip_fw *
3502 remove_rule(struct ip_fw_chain *chain, struct ip_fw *rule,
3505 INIT_VNET_IPFW(curvnet);
3507 int l = RULESIZE(rule);
3509 IPFW_WLOCK_ASSERT(chain);
3513 remove_dyn_rule(rule, NULL /* force removal */);
3522 rule->next = chain->reap;
3529 * Reclaim storage associated with a list of rules. This is
3530 * typically the list created using remove_rule.
3533 reap_rules(struct ip_fw *head)
3537 while ((rule = head) != NULL) {
3539 if (DUMMYNET_LOADED)
3540 ip_dn_ruledel_ptr(rule);
3546 * Remove all rules from a chain (except rules in set RESVD_SET
3547 * unless kill_default = 1). The caller is responsible for
3548 * reclaiming storage for the rules left in chain->reap.
3551 free_chain(struct ip_fw_chain *chain, int kill_default)
3553 struct ip_fw *prev, *rule;
3555 IPFW_WLOCK_ASSERT(chain);
3557 flush_rule_ptrs(chain); /* more efficient to do outside the loop */
3558 for (prev = NULL, rule = chain->rules; rule ; )
3559 if (kill_default || rule->set != RESVD_SET)
3560 rule = remove_rule(chain, rule, prev);
3568 * Remove all rules with given number, and also do set manipulation.
3569 * Assumes chain != NULL && *chain != NULL.
3571 * The argument is an u_int32_t. The low 16 bit are the rule or set number,
3572 * the next 8 bits are the new set, the top 8 bits are the command:
3574 * 0 delete rules with given number
3575 * 1 delete rules with given set number
3576 * 2 move rules with given number to new set
3577 * 3 move rules with given set number to new set
3578 * 4 swap sets with given numbers
3579 * 5 delete rules with given number and with given set number
3582 del_entry(struct ip_fw_chain *chain, u_int32_t arg)
3584 struct ip_fw *prev = NULL, *rule;
3585 u_int16_t rulenum; /* rule or old_set */
3586 u_int8_t cmd, new_set;
3588 rulenum = arg & 0xffff;
3589 cmd = (arg >> 24) & 0xff;
3590 new_set = (arg >> 16) & 0xff;
3592 if (cmd > 5 || new_set > RESVD_SET)
3594 if (cmd == 0 || cmd == 2 || cmd == 5) {
3595 if (rulenum >= IPFW_DEFAULT_RULE)
3598 if (rulenum > RESVD_SET) /* old_set */
3603 rule = chain->rules;
3606 case 0: /* delete rules with given number */
3608 * locate first rule to delete
3610 for (; rule->rulenum < rulenum; prev = rule, rule = rule->next)
3612 if (rule->rulenum != rulenum) {
3613 IPFW_WUNLOCK(chain);
3618 * flush pointers outside the loop, then delete all matching
3619 * rules. prev remains the same throughout the cycle.
3621 flush_rule_ptrs(chain);
3622 while (rule->rulenum == rulenum)
3623 rule = remove_rule(chain, rule, prev);
3626 case 1: /* delete all rules with given set number */
3627 flush_rule_ptrs(chain);
3628 rule = chain->rules;
3629 while (rule->rulenum < IPFW_DEFAULT_RULE)
3630 if (rule->set == rulenum)
3631 rule = remove_rule(chain, rule, prev);
3638 case 2: /* move rules with given number to new set */
3639 rule = chain->rules;
3640 for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
3641 if (rule->rulenum == rulenum)
3642 rule->set = new_set;
3645 case 3: /* move rules with given set number to new set */
3646 for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
3647 if (rule->set == rulenum)
3648 rule->set = new_set;
3651 case 4: /* swap two sets */
3652 for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
3653 if (rule->set == rulenum)
3654 rule->set = new_set;
3655 else if (rule->set == new_set)
3656 rule->set = rulenum;
3658 case 5: /* delete rules with given number and with given set number.
3659 * rulenum - given rule number;
3660 * new_set - given set number.
3662 for (; rule->rulenum < rulenum; prev = rule, rule = rule->next)
3664 if (rule->rulenum != rulenum) {
3665 IPFW_WUNLOCK(chain);
3668 flush_rule_ptrs(chain);
3669 while (rule->rulenum == rulenum) {
3670 if (rule->set == new_set)
3671 rule = remove_rule(chain, rule, prev);
3679 * Look for rules to reclaim. We grab the list before
3680 * releasing the lock then reclaim them w/o the lock to
3681 * avoid a LOR with dummynet.
3685 IPFW_WUNLOCK(chain);
3692 * Clear counters for a specific rule.
3693 * The enclosing "table" is assumed locked.
3696 clear_counters(struct ip_fw *rule, int log_only)
3698 ipfw_insn_log *l = (ipfw_insn_log *)ACTION_PTR(rule);
3700 if (log_only == 0) {
3701 rule->bcnt = rule->pcnt = 0;
3702 rule->timestamp = 0;
3704 if (l->o.opcode == O_LOG)
3705 l->log_left = l->max_log;
3709 * Reset some or all counters on firewall rules.
3710 * The argument `arg' is an u_int32_t. The low 16 bit are the rule number,
3711 * the next 8 bits are the set number, the top 8 bits are the command:
3712 * 0 work with rules from all set's;
3713 * 1 work with rules only from specified set.
3714 * Specified rule number is zero if we want to clear all entries.
3715 * log_only is 1 if we only want to reset logs, zero otherwise.
3718 zero_entry(struct ip_fw_chain *chain, u_int32_t arg, int log_only)
3720 INIT_VNET_IPFW(curvnet);
3724 uint16_t rulenum = arg & 0xffff;
3725 uint8_t set = (arg >> 16) & 0xff;
3726 uint8_t cmd = (arg >> 24) & 0xff;
3730 if (cmd == 1 && set > RESVD_SET)
3735 V_norule_counter = 0;
3736 for (rule = chain->rules; rule; rule = rule->next) {
3737 /* Skip rules from another set. */
3738 if (cmd == 1 && rule->set != set)
3740 clear_counters(rule, log_only);
3742 msg = log_only ? "ipfw: All logging counts reset.\n" :
3743 "ipfw: Accounting cleared.\n";
3747 * We can have multiple rules with the same number, so we
3748 * need to clear them all.
3750 for (rule = chain->rules; rule; rule = rule->next)
3751 if (rule->rulenum == rulenum) {
3752 while (rule && rule->rulenum == rulenum) {
3753 if (cmd == 0 || rule->set == set)
3754 clear_counters(rule, log_only);
3760 if (!cleared) { /* we did not find any matching rules */
3761 IPFW_WUNLOCK(chain);
3764 msg = log_only ? "ipfw: Entry %d logging count reset.\n" :
3765 "ipfw: Entry %d cleared.\n";
3767 IPFW_WUNLOCK(chain);
3770 log(LOG_SECURITY | LOG_NOTICE, msg, rulenum);
3775 * Check validity of the structure before insert.
3776 * Fortunately rules are simple, so this mostly need to check rule sizes.
3779 check_ipfw_struct(struct ip_fw *rule, int size)
3785 if (size < sizeof(*rule)) {
3786 printf("ipfw: rule too short\n");
3789 /* first, check for valid size */
3792 printf("ipfw: size mismatch (have %d want %d)\n", size, l);
3795 if (rule->act_ofs >= rule->cmd_len) {
3796 printf("ipfw: bogus action offset (%u > %u)\n",
3797 rule->act_ofs, rule->cmd_len - 1);
3801 * Now go for the individual checks. Very simple ones, basically only
3802 * instruction sizes.
3804 for (l = rule->cmd_len, cmd = rule->cmd ;
3805 l > 0 ; l -= cmdlen, cmd += cmdlen) {
3806 cmdlen = F_LEN(cmd);
3808 printf("ipfw: opcode %d size truncated\n",
3812 DEB(printf("ipfw: opcode %d\n", cmd->opcode);)
3813 switch (cmd->opcode) {
3825 case O_IPPRECEDENCE:
3843 if (cmdlen != F_INSN_SIZE(ipfw_insn))
3848 if (cmdlen != F_INSN_SIZE(ipfw_insn))
3850 if (cmd->arg1 >= rt_numfibs) {
3851 printf("ipfw: invalid fib number %d\n",
3858 if (cmdlen != F_INSN_SIZE(ipfw_insn))
3860 if (cmd->arg1 >= rt_numfibs) {
3861 printf("ipfw: invalid fib number %d\n",
3876 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32))
3881 if (cmdlen != F_INSN_SIZE(ipfw_insn_limit))
3886 if (cmdlen != F_INSN_SIZE(ipfw_insn_log))
3889 ((ipfw_insn_log *)cmd)->log_left =
3890 ((ipfw_insn_log *)cmd)->max_log;
3896 /* only odd command lengths */
3897 if ( !(cmdlen & 1) || cmdlen > 31)
3903 if (cmd->arg1 == 0 || cmd->arg1 > 256) {
3904 printf("ipfw: invalid set size %d\n",
3908 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
3913 case O_IP_SRC_LOOKUP:
3914 case O_IP_DST_LOOKUP:
3915 if (cmd->arg1 >= IPFW_TABLES_MAX) {
3916 printf("ipfw: invalid table number %d\n",
3920 if (cmdlen != F_INSN_SIZE(ipfw_insn) &&
3921 cmdlen != F_INSN_SIZE(ipfw_insn_u32))
3926 if (cmdlen != F_INSN_SIZE(ipfw_insn_mac))
3936 if (cmdlen < 1 || cmdlen > 31)
3942 case O_IP_DSTPORT: /* XXX artificial limit, 30 port pairs */
3943 if (cmdlen < 2 || cmdlen > 31)
3950 if (cmdlen != F_INSN_SIZE(ipfw_insn_if))
3955 if (cmdlen != F_INSN_SIZE(ipfw_insn_altq))
3961 if (cmdlen != F_INSN_SIZE(ipfw_insn))
3966 #ifdef IPFIREWALL_FORWARD
3967 if (cmdlen != F_INSN_SIZE(ipfw_insn_sa))
3976 if (ip_divert_ptr == NULL)
3982 if (!NG_IPFW_LOADED)
3987 if (!IPFW_NAT_LOADED)
3989 if (cmdlen != F_INSN_SIZE(ipfw_insn_nat))
3992 case O_FORWARD_MAC: /* XXX not implemented yet */
4003 if (cmdlen != F_INSN_SIZE(ipfw_insn))
4007 printf("ipfw: opcode %d, multiple actions"
4014 printf("ipfw: opcode %d, action must be"
4023 if (cmdlen != F_INSN_SIZE(struct in6_addr) +
4024 F_INSN_SIZE(ipfw_insn))
4029 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
4030 ((ipfw_insn_u32 *)cmd)->o.arg1)
4034 case O_IP6_SRC_MASK:
4035 case O_IP6_DST_MASK:
4036 if ( !(cmdlen & 1) || cmdlen > 127)
4040 if( cmdlen != F_INSN_SIZE( ipfw_insn_icmp6 ) )
4046 switch (cmd->opcode) {
4056 case O_IP6_SRC_MASK:
4057 case O_IP6_DST_MASK:
4059 printf("ipfw: no IPv6 support in kernel\n");
4060 return EPROTONOSUPPORT;
4063 printf("ipfw: opcode %d, unknown opcode\n",
4069 if (have_action == 0) {
4070 printf("ipfw: missing action\n");
4076 printf("ipfw: opcode %d size %d wrong\n",
4077 cmd->opcode, cmdlen);
4082 * Copy the static and dynamic rules to the supplied buffer
4083 * and return the amount of space actually used.
4086 ipfw_getrules(struct ip_fw_chain *chain, void *buf, size_t space)
4088 INIT_VNET_IPFW(curvnet);
4090 char *ep = bp + space;
4093 time_t boot_seconds;
4095 boot_seconds = boottime.tv_sec;
4096 /* XXX this can take a long time and locking will block packet flow */
4098 for (rule = chain->rules; rule ; rule = rule->next) {
4100 * Verify the entry fits in the buffer in case the
4101 * rules changed between calculating buffer space and
4102 * now. This would be better done using a generation
4103 * number but should suffice for now.
4109 * XXX HACK. Store the disable mask in the "next"
4110 * pointer in a wild attempt to keep the ABI the same.
4111 * Why do we do this on EVERY rule?
4113 bcopy(&V_set_disable,
4114 &(((struct ip_fw *)bp)->next_rule),
4115 sizeof(V_set_disable));
4116 if (((struct ip_fw *)bp)->timestamp)
4117 ((struct ip_fw *)bp)->timestamp += boot_seconds;
4121 IPFW_RUNLOCK(chain);
4123 ipfw_dyn_rule *p, *last = NULL;
4126 for (i = 0 ; i < V_curr_dyn_buckets; i++)
4127 for (p = V_ipfw_dyn_v[i] ; p != NULL; p = p->next) {
4128 if (bp + sizeof *p <= ep) {
4129 ipfw_dyn_rule *dst =
4130 (ipfw_dyn_rule *)bp;
4131 bcopy(p, dst, sizeof *p);
4132 bcopy(&(p->rule->rulenum), &(dst->rule),
4133 sizeof(p->rule->rulenum));
4135 * store set number into high word of
4136 * dst->rule pointer.
4138 bcopy(&(p->rule->set),
4139 (char *)&dst->rule +
4140 sizeof(p->rule->rulenum),
4141 sizeof(p->rule->set));
4143 * store a non-null value in "next".
4144 * The userland code will interpret a
4145 * NULL here as a marker
4146 * for the last dynamic rule.
4148 bcopy(&dst, &dst->next, sizeof(dst));
4151 TIME_LEQ(dst->expire, time_uptime) ?
4152 0 : dst->expire - time_uptime ;
4153 bp += sizeof(ipfw_dyn_rule);
4157 if (last != NULL) /* mark last dynamic rule */
4158 bzero(&last->next, sizeof(last));
4160 return (bp - (char *)buf);
4165 * {set|get}sockopt parser.
4168 ipfw_ctl(struct sockopt *sopt)
4170 #define RULE_MAXSIZE (256*sizeof(u_int32_t))
4171 INIT_VNET_IPFW(curvnet);
4174 struct ip_fw *buf, *rule;
4175 u_int32_t rulenum[2];
4177 error = priv_check(sopt->sopt_td, PRIV_NETINET_IPFW);
4182 * Disallow modifications in really-really secure mode, but still allow
4183 * the logging counters to be reset.
4185 if (sopt->sopt_name == IP_FW_ADD ||
4186 (sopt->sopt_dir == SOPT_SET && sopt->sopt_name != IP_FW_RESETLOG)) {
4187 error = securelevel_ge(sopt->sopt_td->td_ucred, 3);
4194 switch (sopt->sopt_name) {
4197 * pass up a copy of the current rules. Static rules
4198 * come first (the last of which has number IPFW_DEFAULT_RULE),
4199 * followed by a possibly empty list of dynamic rule.
4200 * The last dynamic rule has NULL in the "next" field.
4202 * Note that the calculated size is used to bound the
4203 * amount of data returned to the user. The rule set may
4204 * change between calculating the size and returning the
4205 * data in which case we'll just return what fits.
4207 size = V_static_len; /* size of static rules */
4208 if (V_ipfw_dyn_v) /* add size of dyn.rules */
4209 size += (V_dyn_count * sizeof(ipfw_dyn_rule));
4212 * XXX todo: if the user passes a short length just to know
4213 * how much room is needed, do not bother filling up the
4214 * buffer, just jump to the sooptcopyout.
4216 buf = malloc(size, M_TEMP, M_WAITOK);
4217 error = sooptcopyout(sopt, buf,
4218 ipfw_getrules(&V_layer3_chain, buf, size));
4224 * Normally we cannot release the lock on each iteration.
4225 * We could do it here only because we start from the head all
4226 * the times so there is no risk of missing some entries.
4227 * On the other hand, the risk is that we end up with
4228 * a very inconsistent ruleset, so better keep the lock
4229 * around the whole cycle.
4231 * XXX this code can be improved by resetting the head of
4232 * the list to point to the default rule, and then freeing
4233 * the old list without the need for a lock.
4236 IPFW_WLOCK(&V_layer3_chain);
4237 V_layer3_chain.reap = NULL;
4238 free_chain(&V_layer3_chain, 0 /* keep default rule */);
4239 rule = V_layer3_chain.reap;
4240 V_layer3_chain.reap = NULL;
4241 IPFW_WUNLOCK(&V_layer3_chain);
4247 rule = malloc(RULE_MAXSIZE, M_TEMP, M_WAITOK);
4248 error = sooptcopyin(sopt, rule, RULE_MAXSIZE,
4249 sizeof(struct ip_fw) );
4251 error = check_ipfw_struct(rule, sopt->sopt_valsize);
4253 error = add_rule(&V_layer3_chain, rule);
4254 size = RULESIZE(rule);
4255 if (!error && sopt->sopt_dir == SOPT_GET)
4256 error = sooptcopyout(sopt, rule, size);
4263 * IP_FW_DEL is used for deleting single rules or sets,
4264 * and (ab)used to atomically manipulate sets. Argument size
4265 * is used to distinguish between the two:
4267 * delete single rule or set of rules,
4268 * or reassign rules (or sets) to a different set.
4269 * 2*sizeof(u_int32_t)
4270 * atomic disable/enable sets.
4271 * first u_int32_t contains sets to be disabled,
4272 * second u_int32_t contains sets to be enabled.
4274 error = sooptcopyin(sopt, rulenum,
4275 2*sizeof(u_int32_t), sizeof(u_int32_t));
4278 size = sopt->sopt_valsize;
4279 if (size == sizeof(u_int32_t)) /* delete or reassign */
4280 error = del_entry(&V_layer3_chain, rulenum[0]);
4281 else if (size == 2*sizeof(u_int32_t)) /* set enable/disable */
4283 (V_set_disable | rulenum[0]) & ~rulenum[1] &
4284 ~(1<<RESVD_SET); /* set RESVD_SET always enabled */
4290 case IP_FW_RESETLOG: /* argument is an u_int_32, the rule number */
4292 if (sopt->sopt_val != 0) {
4293 error = sooptcopyin(sopt, rulenum,
4294 sizeof(u_int32_t), sizeof(u_int32_t));
4298 error = zero_entry(&V_layer3_chain, rulenum[0],
4299 sopt->sopt_name == IP_FW_RESETLOG);
4302 case IP_FW_TABLE_ADD:
4304 ipfw_table_entry ent;
4306 error = sooptcopyin(sopt, &ent,
4307 sizeof(ent), sizeof(ent));
4310 error = add_table_entry(&V_layer3_chain, ent.tbl,
4311 ent.addr, ent.masklen, ent.value);
4315 case IP_FW_TABLE_DEL:
4317 ipfw_table_entry ent;
4319 error = sooptcopyin(sopt, &ent,
4320 sizeof(ent), sizeof(ent));
4323 error = del_table_entry(&V_layer3_chain, ent.tbl,
4324 ent.addr, ent.masklen);
4328 case IP_FW_TABLE_FLUSH:
4332 error = sooptcopyin(sopt, &tbl,
4333 sizeof(tbl), sizeof(tbl));
4336 IPFW_WLOCK(&V_layer3_chain);
4337 error = flush_table(&V_layer3_chain, tbl);
4338 IPFW_WUNLOCK(&V_layer3_chain);
4342 case IP_FW_TABLE_GETSIZE:
4346 if ((error = sooptcopyin(sopt, &tbl, sizeof(tbl),
4349 IPFW_RLOCK(&V_layer3_chain);
4350 error = count_table(&V_layer3_chain, tbl, &cnt);
4351 IPFW_RUNLOCK(&V_layer3_chain);
4354 error = sooptcopyout(sopt, &cnt, sizeof(cnt));
4358 case IP_FW_TABLE_LIST:
4362 if (sopt->sopt_valsize < sizeof(*tbl)) {
4366 size = sopt->sopt_valsize;
4367 tbl = malloc(size, M_TEMP, M_WAITOK);
4368 error = sooptcopyin(sopt, tbl, size, sizeof(*tbl));
4373 tbl->size = (size - sizeof(*tbl)) /
4374 sizeof(ipfw_table_entry);
4375 IPFW_RLOCK(&V_layer3_chain);
4376 error = dump_table(&V_layer3_chain, tbl);
4377 IPFW_RUNLOCK(&V_layer3_chain);
4382 error = sooptcopyout(sopt, tbl, size);
4388 if (IPFW_NAT_LOADED)
4389 error = ipfw_nat_cfg_ptr(sopt);
4391 printf("IP_FW_NAT_CFG: %s\n",
4392 "ipfw_nat not present, please load it");
4398 if (IPFW_NAT_LOADED)
4399 error = ipfw_nat_del_ptr(sopt);
4401 printf("IP_FW_NAT_DEL: %s\n",
4402 "ipfw_nat not present, please load it");
4407 case IP_FW_NAT_GET_CONFIG:
4408 if (IPFW_NAT_LOADED)
4409 error = ipfw_nat_get_cfg_ptr(sopt);
4411 printf("IP_FW_NAT_GET_CFG: %s\n",
4412 "ipfw_nat not present, please load it");
4417 case IP_FW_NAT_GET_LOG:
4418 if (IPFW_NAT_LOADED)
4419 error = ipfw_nat_get_log_ptr(sopt);
4421 printf("IP_FW_NAT_GET_LOG: %s\n",
4422 "ipfw_nat not present, please load it");
4428 printf("ipfw: ipfw_ctl invalid option %d\n", sopt->sopt_name);
4437 * dummynet needs a reference to the default rule, because rules can be
4438 * deleted while packets hold a reference to them. When this happens,
4439 * dummynet changes the reference to the default rule (it could well be a
4440 * NULL pointer, but this way we do not need to check for the special
4441 * case, plus here he have info on the default behaviour).
4443 struct ip_fw *ip_fw_default_rule;
4446 * This procedure is only used to handle keepalives. It is invoked
4447 * every dyn_keepalive_period
4450 ipfw_tick(void * __unused unused)
4452 struct mbuf *m0, *m, *mnext, **mtailp;
4456 if (V_dyn_keepalive == 0 || V_ipfw_dyn_v == NULL || V_dyn_count == 0)
4460 * We make a chain of packets to go out here -- not deferring
4461 * until after we drop the IPFW dynamic rule lock would result
4462 * in a lock order reversal with the normal packet input -> ipfw
4468 for (i = 0 ; i < V_curr_dyn_buckets ; i++) {
4469 for (q = V_ipfw_dyn_v[i] ; q ; q = q->next ) {
4470 if (q->dyn_type == O_LIMIT_PARENT)
4472 if (q->id.proto != IPPROTO_TCP)
4474 if ( (q->state & BOTH_SYN) != BOTH_SYN)
4476 if (TIME_LEQ(time_uptime + V_dyn_keepalive_interval,
4478 continue; /* too early */
4479 if (TIME_LEQ(q->expire, time_uptime))
4480 continue; /* too late, rule expired */
4482 *mtailp = send_pkt(NULL, &(q->id), q->ack_rev - 1,
4483 q->ack_fwd, TH_SYN);
4484 if (*mtailp != NULL)
4485 mtailp = &(*mtailp)->m_nextpkt;
4486 *mtailp = send_pkt(NULL, &(q->id), q->ack_fwd - 1,
4488 if (*mtailp != NULL)
4489 mtailp = &(*mtailp)->m_nextpkt;
4493 for (m = mnext = m0; m != NULL; m = mnext) {
4494 mnext = m->m_nextpkt;
4495 m->m_nextpkt = NULL;
4496 ip_output(m, NULL, NULL, 0, NULL, NULL);
4499 callout_reset(&V_ipfw_timeout, V_dyn_keepalive_period * hz,
4506 INIT_VNET_IPFW(curvnet);
4507 struct ip_fw default_rule;
4511 /* Setup IPv6 fw sysctl tree. */
4512 sysctl_ctx_init(&ip6_fw_sysctl_ctx);
4513 ip6_fw_sysctl_tree = SYSCTL_ADD_NODE(&ip6_fw_sysctl_ctx,
4514 SYSCTL_STATIC_CHILDREN(_net_inet6_ip6), OID_AUTO, "fw",
4515 CTLFLAG_RW | CTLFLAG_SECURE, 0, "Firewall");
4516 SYSCTL_ADD_PROC(&ip6_fw_sysctl_ctx, SYSCTL_CHILDREN(ip6_fw_sysctl_tree),
4517 OID_AUTO, "enable", CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE3,
4518 &V_fw6_enable, 0, ipfw_chg_hook, "I", "Enable ipfw+6");
4519 SYSCTL_ADD_INT(&ip6_fw_sysctl_ctx, SYSCTL_CHILDREN(ip6_fw_sysctl_tree),
4520 OID_AUTO, "deny_unknown_exthdrs", CTLFLAG_RW | CTLFLAG_SECURE,
4521 &V_fw_deny_unknown_exthdrs, 0,
4522 "Deny packets with unknown IPv6 Extension Headers");
4525 V_layer3_chain.rules = NULL;
4526 IPFW_LOCK_INIT(&V_layer3_chain);
4527 ipfw_dyn_rule_zone = uma_zcreate("IPFW dynamic rule",
4528 sizeof(ipfw_dyn_rule), NULL, NULL, NULL, NULL,
4530 IPFW_DYN_LOCK_INIT();
4531 callout_init(&V_ipfw_timeout, CALLOUT_MPSAFE);
4533 bzero(&default_rule, sizeof default_rule);
4535 default_rule.act_ofs = 0;
4536 default_rule.rulenum = IPFW_DEFAULT_RULE;
4537 default_rule.cmd_len = 1;
4538 default_rule.set = RESVD_SET;
4540 default_rule.cmd[0].len = 1;
4541 default_rule.cmd[0].opcode =
4542 #ifdef IPFIREWALL_DEFAULT_TO_ACCEPT
4547 error = add_rule(&V_layer3_chain, &default_rule);
4549 printf("ipfw2: error %u initializing default rule "
4550 "(support disabled)\n", error);
4551 IPFW_DYN_LOCK_DESTROY();
4552 IPFW_LOCK_DESTROY(&V_layer3_chain);
4553 uma_zdestroy(ipfw_dyn_rule_zone);
4557 ip_fw_default_rule = V_layer3_chain.rules;
4562 "initialized, divert %s, nat %s, "
4563 "rule-based forwarding "
4564 #ifdef IPFIREWALL_FORWARD
4569 "default to %s, logging ",
4575 #ifdef IPFIREWALL_NAT
4581 default_rule.cmd[0].opcode == O_ACCEPT ? "accept" : "deny");
4583 #ifdef IPFIREWALL_VERBOSE
4586 #ifdef IPFIREWALL_VERBOSE_LIMIT
4587 V_verbose_limit = IPFIREWALL_VERBOSE_LIMIT;
4589 if (V_fw_verbose == 0)
4590 printf("disabled\n");
4591 else if (V_verbose_limit == 0)
4592 printf("unlimited\n");
4594 printf("limited to %d packets/entry by default\n",
4597 error = init_tables(&V_layer3_chain);
4599 IPFW_DYN_LOCK_DESTROY();
4600 IPFW_LOCK_DESTROY(&V_layer3_chain);
4601 uma_zdestroy(ipfw_dyn_rule_zone);
4604 ip_fw_ctl_ptr = ipfw_ctl;
4605 ip_fw_chk_ptr = ipfw_chk;
4606 callout_reset(&V_ipfw_timeout, hz, ipfw_tick, NULL);
4607 LIST_INIT(&V_layer3_chain.nat);
4616 ip_fw_chk_ptr = NULL;
4617 ip_fw_ctl_ptr = NULL;
4618 callout_drain(&V_ipfw_timeout);
4619 IPFW_WLOCK(&V_layer3_chain);
4620 flush_tables(&V_layer3_chain);
4621 V_layer3_chain.reap = NULL;
4622 free_chain(&V_layer3_chain, 1 /* kill default rule */);
4623 reap = V_layer3_chain.reap, V_layer3_chain.reap = NULL;
4624 IPFW_WUNLOCK(&V_layer3_chain);
4627 IPFW_DYN_LOCK_DESTROY();
4628 uma_zdestroy(ipfw_dyn_rule_zone);
4629 if (V_ipfw_dyn_v != NULL)
4630 free(V_ipfw_dyn_v, M_IPFW);
4631 IPFW_LOCK_DESTROY(&V_layer3_chain);
4634 /* Free IPv6 fw sysctl tree. */
4635 sysctl_ctx_free(&ip6_fw_sysctl_ctx);
4638 printf("IP firewall unloaded\n");