2 * Copyright (c) 2002 Luigi Rizzo, Universita` di Pisa
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
13 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
14 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
16 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
17 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
19 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
20 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
21 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 #include <sys/cdefs.h>
27 __FBSDID("$FreeBSD: src/sys/netinet/ip_fw2.c,v 1.175.2.13 2008/10/30 16:29:04 bz Exp $");
33 * Implement IP packet firewall (new version)
36 #if !defined(KLD_MODULE)
38 #include "opt_ipdivert.h"
42 #error IPFIREWALL requires INET.
45 #include "opt_inet6.h"
46 #include "opt_ipsec.h"
48 #include <sys/param.h>
49 #include <sys/systm.h>
50 #include <sys/condvar.h>
51 #include <sys/eventhandler.h>
52 #include <sys/malloc.h>
54 #include <sys/kernel.h>
57 #include <sys/module.h>
60 #include <sys/rwlock.h>
61 #include <sys/socket.h>
62 #include <sys/socketvar.h>
63 #include <sys/sysctl.h>
64 #include <sys/syslog.h>
65 #include <sys/ucred.h>
66 #include <net/ethernet.h> /* for ETHERTYPE_IP */
68 #include <net/radix.h>
69 #include <net/route.h>
70 #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_var.h>
77 #include <netinet/in_pcb.h>
78 #include <netinet/ip.h>
79 #include <netinet/ip_var.h>
80 #include <netinet/ip_icmp.h>
81 #include <netinet/ip_fw.h>
82 #include <netinet/ip_divert.h>
83 #include <netinet/ip_dummynet.h>
84 #include <netinet/ip_carp.h>
85 #include <netinet/pim.h>
86 #include <netinet/tcp_var.h>
87 #include <netinet/udp.h>
88 #include <netinet/udp_var.h>
89 #include <netinet/sctp.h>
91 #include <netgraph/ng_ipfw.h>
93 #include <netinet/ip6.h>
94 #include <netinet/icmp6.h>
96 #include <netinet6/scope6_var.h>
97 #include <netinet6/ip6_var.h>
100 #include <machine/in_cksum.h> /* XXX for in_cksum */
103 #include <security/mac/mac_framework.h>
106 static VNET_DEFINE(int, ipfw_vnet_ready) = 0;
107 #define V_ipfw_vnet_ready VNET(ipfw_vnet_ready)
109 * set_disable contains one bit per set value (0..31).
110 * If the bit is set, all rules with the corresponding set
111 * are disabled. Set RESVD_SET(31) is reserved for the default rule
112 * and rules that are not deleted by the flush command,
113 * and CANNOT be disabled.
114 * Rules in set RESVD_SET can only be deleted explicitly.
116 static VNET_DEFINE(u_int32_t, set_disable);
117 static VNET_DEFINE(int, fw_verbose);
118 static VNET_DEFINE(struct callout, ipfw_timeout);
119 static VNET_DEFINE(int, verbose_limit);
121 #define V_set_disable VNET(set_disable)
122 #define V_fw_verbose VNET(fw_verbose)
123 #define V_ipfw_timeout VNET(ipfw_timeout)
124 #define V_verbose_limit VNET(verbose_limit)
126 #ifdef IPFIREWALL_DEFAULT_TO_ACCEPT
127 static int default_to_accept = 1;
129 static int default_to_accept;
131 static uma_zone_t ipfw_dyn_rule_zone;
134 * list of rules for layer 3
136 VNET_DEFINE(struct ip_fw_chain, layer3_chain);
138 MALLOC_DEFINE(M_IPFW, "IpFw/IpAcct", "IpFw/IpAcct chain's");
139 MALLOC_DEFINE(M_IPFW_TBL, "ipfw_tbl", "IpFw tables");
140 #define IPFW_NAT_LOADED (ipfw_nat_ptr != NULL)
141 ipfw_nat_t *ipfw_nat_ptr = NULL;
142 ipfw_nat_cfg_t *ipfw_nat_cfg_ptr;
143 ipfw_nat_cfg_t *ipfw_nat_del_ptr;
144 ipfw_nat_cfg_t *ipfw_nat_get_cfg_ptr;
145 ipfw_nat_cfg_t *ipfw_nat_get_log_ptr;
148 struct radix_node rn[2];
149 struct sockaddr_in addr, mask;
153 static VNET_DEFINE(int, autoinc_step);
154 #define V_autoinc_step VNET(autoinc_step)
155 static VNET_DEFINE(int, fw_deny_unknown_exthdrs);
156 #define V_fw_deny_unknown_exthdrs VNET(fw_deny_unknown_exthdrs)
158 extern int ipfw_chg_hook(SYSCTL_HANDLER_ARGS);
161 SYSCTL_NODE(_net_inet_ip, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall");
162 SYSCTL_VNET_PROC(_net_inet_ip_fw, OID_AUTO, enable,
163 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE3, &VNET_NAME(fw_enable), 0,
164 ipfw_chg_hook, "I", "Enable ipfw");
165 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, autoinc_step,
166 CTLFLAG_RW, &VNET_NAME(autoinc_step), 0,
167 "Rule number auto-increment step");
168 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, one_pass,
169 CTLFLAG_RW | CTLFLAG_SECURE3, &VNET_NAME(fw_one_pass), 0,
170 "Only do a single pass through ipfw when using dummynet(4)");
171 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, verbose,
172 CTLFLAG_RW | CTLFLAG_SECURE3, &VNET_NAME(fw_verbose), 0,
173 "Log matches to ipfw rules");
174 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, verbose_limit,
175 CTLFLAG_RW, &VNET_NAME(verbose_limit), 0,
176 "Set upper limit of matches of ipfw rules logged");
177 unsigned int dummy_default_rule = IPFW_DEFAULT_RULE;
178 SYSCTL_UINT(_net_inet_ip_fw, OID_AUTO, default_rule, CTLFLAG_RD,
179 &dummy_default_rule, IPFW_DEFAULT_RULE,
180 "The default/max possible rule number.");
181 unsigned int dummy_tables_max = IPFW_TABLES_MAX;
182 SYSCTL_UINT(_net_inet_ip_fw, OID_AUTO, tables_max, CTLFLAG_RD,
183 &dummy_tables_max, IPFW_TABLES_MAX,
184 "The maximum number of tables.");
185 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, default_to_accept, CTLFLAG_RDTUN,
186 &default_to_accept, 0,
187 "Make the default rule accept all packets.");
188 TUNABLE_INT("net.inet.ip.fw.default_to_accept", &default_to_accept);
191 SYSCTL_DECL(_net_inet6_ip6);
192 SYSCTL_NODE(_net_inet6_ip6, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall");
193 SYSCTL_VNET_PROC(_net_inet6_ip6_fw, OID_AUTO, enable,
194 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE3, &VNET_NAME(fw6_enable), 0,
195 ipfw_chg_hook, "I", "Enable ipfw+6");
196 SYSCTL_VNET_INT(_net_inet6_ip6_fw, OID_AUTO, deny_unknown_exthdrs,
197 CTLFLAG_RW | CTLFLAG_SECURE, &VNET_NAME(fw_deny_unknown_exthdrs), 0,
198 "Deny packets with unknown IPv6 Extension Headers");
201 #endif /* SYSCTL_NODE */
204 * Description of dynamic rules.
206 * Dynamic rules are stored in lists accessed through a hash table
207 * (ipfw_dyn_v) whose size is curr_dyn_buckets. This value can
208 * be modified through the sysctl variable dyn_buckets which is
209 * updated when the table becomes empty.
211 * XXX currently there is only one list, ipfw_dyn.
213 * When a packet is received, its address fields are first masked
214 * with the mask defined for the rule, then hashed, then matched
215 * against the entries in the corresponding list.
216 * Dynamic rules can be used for different purposes:
218 * + enforcing limits on the number of sessions;
219 * + in-kernel NAT (not implemented yet)
221 * The lifetime of dynamic rules is regulated by dyn_*_lifetime,
222 * measured in seconds and depending on the flags.
224 * The total number of dynamic rules is stored in dyn_count.
225 * The max number of dynamic rules is dyn_max. When we reach
226 * the maximum number of rules we do not create anymore. This is
227 * done to avoid consuming too much memory, but also too much
228 * time when searching on each packet (ideally, we should try instead
229 * to put a limit on the length of the list on each bucket...).
231 * Each dynamic rule holds a pointer to the parent ipfw rule so
232 * we know what action to perform. Dynamic rules are removed when
233 * the parent rule is deleted. XXX we should make them survive.
235 * There are some limitations with dynamic rules -- we do not
236 * obey the 'randomized match', and we do not do multiple
237 * passes through the firewall. XXX check the latter!!!
239 static VNET_DEFINE(ipfw_dyn_rule **, ipfw_dyn_v);
240 static VNET_DEFINE(u_int32_t, dyn_buckets);
241 static VNET_DEFINE(u_int32_t, curr_dyn_buckets);
243 #define V_ipfw_dyn_v VNET(ipfw_dyn_v)
244 #define V_dyn_buckets VNET(dyn_buckets)
245 #define V_curr_dyn_buckets VNET(curr_dyn_buckets)
247 #if defined( __linux__ ) || defined( _WIN32 )
248 DEFINE_SPINLOCK(ipfw_dyn_mtx);
250 static struct mtx ipfw_dyn_mtx; /* mutex guarding dynamic rules */
251 #endif /* !__linux__ */
252 #define IPFW_DYN_LOCK_INIT() \
253 mtx_init(&ipfw_dyn_mtx, "IPFW dynamic rules", NULL, MTX_DEF)
254 #define IPFW_DYN_LOCK_DESTROY() mtx_destroy(&ipfw_dyn_mtx)
255 #define IPFW_DYN_LOCK() mtx_lock(&ipfw_dyn_mtx)
256 #define IPFW_DYN_UNLOCK() mtx_unlock(&ipfw_dyn_mtx)
257 #define IPFW_DYN_LOCK_ASSERT() mtx_assert(&ipfw_dyn_mtx, MA_OWNED)
259 static struct mbuf *send_pkt(struct mbuf *, struct ipfw_flow_id *,
260 u_int32_t, u_int32_t, int);
264 * Timeouts for various events in handing dynamic rules.
266 static VNET_DEFINE(u_int32_t, dyn_ack_lifetime);
267 static VNET_DEFINE(u_int32_t, dyn_syn_lifetime);
268 static VNET_DEFINE(u_int32_t, dyn_fin_lifetime);
269 static VNET_DEFINE(u_int32_t, dyn_rst_lifetime);
270 static VNET_DEFINE(u_int32_t, dyn_udp_lifetime);
271 static VNET_DEFINE(u_int32_t, dyn_short_lifetime);
273 #define V_dyn_ack_lifetime VNET(dyn_ack_lifetime)
274 #define V_dyn_syn_lifetime VNET(dyn_syn_lifetime)
275 #define V_dyn_fin_lifetime VNET(dyn_fin_lifetime)
276 #define V_dyn_rst_lifetime VNET(dyn_rst_lifetime)
277 #define V_dyn_udp_lifetime VNET(dyn_udp_lifetime)
278 #define V_dyn_short_lifetime VNET(dyn_short_lifetime)
281 * Keepalives are sent if dyn_keepalive is set. They are sent every
282 * dyn_keepalive_period seconds, in the last dyn_keepalive_interval
283 * seconds of lifetime of a rule.
284 * dyn_rst_lifetime and dyn_fin_lifetime should be strictly lower
285 * than dyn_keepalive_period.
288 static VNET_DEFINE(u_int32_t, dyn_keepalive_interval);
289 static VNET_DEFINE(u_int32_t, dyn_keepalive_period);
290 static VNET_DEFINE(u_int32_t, dyn_keepalive);
292 #define V_dyn_keepalive_interval VNET(dyn_keepalive_interval)
293 #define V_dyn_keepalive_period VNET(dyn_keepalive_period)
294 #define V_dyn_keepalive VNET(dyn_keepalive)
296 static VNET_DEFINE(u_int32_t, static_count); /* # of static rules */
297 static VNET_DEFINE(u_int32_t, static_len); /* bytes of static rules */
298 static VNET_DEFINE(u_int32_t, dyn_count); /* # of dynamic rules */
299 static VNET_DEFINE(u_int32_t, dyn_max); /* max # of dynamic rules */
301 #define V_static_count VNET(static_count)
302 #define V_static_len VNET(static_len)
303 #define V_dyn_count VNET(dyn_count)
304 #define V_dyn_max VNET(dyn_max)
307 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_buckets,
308 CTLFLAG_RW, &VNET_NAME(dyn_buckets), 0,
309 "Number of dyn. buckets");
310 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, curr_dyn_buckets,
311 CTLFLAG_RD, &VNET_NAME(curr_dyn_buckets), 0,
312 "Current Number of dyn. buckets");
313 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_count,
314 CTLFLAG_RD, &VNET_NAME(dyn_count), 0,
315 "Number of dyn. rules");
316 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_max,
317 CTLFLAG_RW, &VNET_NAME(dyn_max), 0,
318 "Max number of dyn. rules");
319 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, static_count,
320 CTLFLAG_RD, &VNET_NAME(static_count), 0,
321 "Number of static rules");
322 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_ack_lifetime,
323 CTLFLAG_RW, &VNET_NAME(dyn_ack_lifetime), 0,
324 "Lifetime of dyn. rules for acks");
325 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_syn_lifetime,
326 CTLFLAG_RW, &VNET_NAME(dyn_syn_lifetime), 0,
327 "Lifetime of dyn. rules for syn");
328 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_fin_lifetime,
329 CTLFLAG_RW, &VNET_NAME(dyn_fin_lifetime), 0,
330 "Lifetime of dyn. rules for fin");
331 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_rst_lifetime,
332 CTLFLAG_RW, &VNET_NAME(dyn_rst_lifetime), 0,
333 "Lifetime of dyn. rules for rst");
334 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_udp_lifetime,
335 CTLFLAG_RW, &VNET_NAME(dyn_udp_lifetime), 0,
336 "Lifetime of dyn. rules for UDP");
337 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_short_lifetime,
338 CTLFLAG_RW, &VNET_NAME(dyn_short_lifetime), 0,
339 "Lifetime of dyn. rules for other situations");
340 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_keepalive,
341 CTLFLAG_RW, &VNET_NAME(dyn_keepalive), 0,
342 "Enable keepalives for dyn. rules");
343 #endif /* SYSCTL_NODE */
346 * L3HDR maps an ipv4 pointer into a layer3 header pointer of type T
347 * Other macros just cast void * into the appropriate type
349 #define L3HDR(T, ip) ((T *)((u_int32_t *)(ip) + (ip)->ip_hl))
350 #define TCP(p) ((struct tcphdr *)(p))
351 #define SCTP(p) ((struct sctphdr *)(p))
352 #define UDP(p) ((struct udphdr *)(p))
353 #define ICMP(p) ((struct icmphdr *)(p))
354 #define ICMP6(p) ((struct icmp6_hdr *)(p))
357 icmptype_match(struct icmphdr *icmp, ipfw_insn_u32 *cmd)
359 int type = icmp->icmp_type;
361 return (type <= ICMP_MAXTYPE && (cmd->d[0] & (1<<type)) );
364 #define TT ( (1 << ICMP_ECHO) | (1 << ICMP_ROUTERSOLICIT) | \
365 (1 << ICMP_TSTAMP) | (1 << ICMP_IREQ) | (1 << ICMP_MASKREQ) )
368 is_icmp_query(struct icmphdr *icmp)
370 int type = icmp->icmp_type;
372 return (type <= ICMP_MAXTYPE && (TT & (1<<type)) );
377 * The following checks use two arrays of 8 or 16 bits to store the
378 * bits that we want set or clear, respectively. They are in the
379 * low and high half of cmd->arg1 or cmd->d[0].
381 * We scan options and store the bits we find set. We succeed if
383 * (want_set & ~bits) == 0 && (want_clear & ~bits) == want_clear
385 * The code is sometimes optimized not to store additional variables.
389 flags_match(ipfw_insn *cmd, u_int8_t bits)
394 if ( ((cmd->arg1 & 0xff) & bits) != 0)
395 return 0; /* some bits we want set were clear */
396 want_clear = (cmd->arg1 >> 8) & 0xff;
397 if ( (want_clear & bits) != want_clear)
398 return 0; /* some bits we want clear were set */
403 ipopts_match(struct ip *ip, ipfw_insn *cmd)
405 int optlen, bits = 0;
406 u_char *cp = (u_char *)(ip + 1);
407 int x = (ip->ip_hl << 2) - sizeof (struct ip);
409 for (; x > 0; x -= optlen, cp += optlen) {
410 int opt = cp[IPOPT_OPTVAL];
412 if (opt == IPOPT_EOL)
414 if (opt == IPOPT_NOP)
417 optlen = cp[IPOPT_OLEN];
418 if (optlen <= 0 || optlen > x)
419 return 0; /* invalid or truncated */
427 bits |= IP_FW_IPOPT_LSRR;
431 bits |= IP_FW_IPOPT_SSRR;
435 bits |= IP_FW_IPOPT_RR;
439 bits |= IP_FW_IPOPT_TS;
443 return (flags_match(cmd, bits));
447 tcpopts_match(struct tcphdr *tcp, ipfw_insn *cmd)
449 int optlen, bits = 0;
450 u_char *cp = (u_char *)(tcp + 1);
451 int x = (tcp->th_off << 2) - sizeof(struct tcphdr);
453 for (; x > 0; x -= optlen, cp += optlen) {
455 if (opt == TCPOPT_EOL)
457 if (opt == TCPOPT_NOP)
471 bits |= IP_FW_TCPOPT_MSS;
475 bits |= IP_FW_TCPOPT_WINDOW;
478 case TCPOPT_SACK_PERMITTED:
480 bits |= IP_FW_TCPOPT_SACK;
483 case TCPOPT_TIMESTAMP:
484 bits |= IP_FW_TCPOPT_TS;
489 return (flags_match(cmd, bits));
493 iface_match(struct ifnet *ifp, ipfw_insn_if *cmd)
495 if (ifp == NULL) /* no iface with this packet, match fails */
497 /* Check by name or by IP address */
498 if (cmd->name[0] != '\0') { /* match by name */
501 if (fnmatch(cmd->name, ifp->if_xname, 0) == 0)
504 if (strncmp(ifp->if_xname, cmd->name, IFNAMSIZ) == 0)
508 #if !defined( __linux__ ) && !defined( _WIN32 )
512 TAILQ_FOREACH(ia, &ifp->if_addrhead, ifa_link) {
513 if (ia->ifa_addr->sa_family != AF_INET)
515 if (cmd->p.ip.s_addr == ((struct sockaddr_in *)
516 (ia->ifa_addr))->sin_addr.s_addr) {
517 if_addr_runlock(ifp);
518 return(1); /* match */
521 if_addr_runlock(ifp);
524 return(0); /* no match, fail ... */
527 #if !defined( __linux__ ) && !defined( _WIN32 )
529 * The verify_path function checks if a route to the src exists and
530 * if it is reachable via ifp (when provided).
532 * The 'verrevpath' option checks that the interface that an IP packet
533 * arrives on is the same interface that traffic destined for the
534 * packet's source address would be routed out of. The 'versrcreach'
535 * option just checks that the source address is reachable via any route
536 * (except default) in the routing table. These two are a measure to block
537 * forged packets. This is also commonly known as "anti-spoofing" or Unicast
538 * Reverse Path Forwarding (Unicast RFP) in Cisco-ese. The name of the knobs
539 * is purposely reminiscent of the Cisco IOS command,
541 * ip verify unicast reverse-path
542 * ip verify unicast source reachable-via any
544 * which implements the same functionality. But note that syntax is
545 * misleading. The check may be performed on all IP packets whether unicast,
546 * multicast, or broadcast.
549 verify_path(struct in_addr src, struct ifnet *ifp, u_int fib)
552 struct sockaddr_in *dst;
554 bzero(&ro, sizeof(ro));
556 dst = (struct sockaddr_in *)&(ro.ro_dst);
557 dst->sin_family = AF_INET;
558 dst->sin_len = sizeof(*dst);
560 in_rtalloc_ign(&ro, 0, fib);
562 if (ro.ro_rt == NULL)
566 * If ifp is provided, check for equality with rtentry.
567 * We should use rt->rt_ifa->ifa_ifp, instead of rt->rt_ifp,
568 * in order to pass packets injected back by if_simloop():
569 * if useloopback == 1 routing entry (via lo0) for our own address
570 * may exist, so we need to handle routing assymetry.
572 if (ifp != NULL && ro.ro_rt->rt_ifa->ifa_ifp != ifp) {
577 /* if no ifp provided, check if rtentry is not default route */
579 satosin(rt_key(ro.ro_rt))->sin_addr.s_addr == INADDR_ANY) {
584 /* or if this is a blackhole/reject route */
585 if (ifp == NULL && ro.ro_rt->rt_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
590 /* found valid route */
598 * ipv6 specific rules here...
601 icmp6type_match (int type, ipfw_insn_u32 *cmd)
603 return (type <= ICMP6_MAXTYPE && (cmd->d[type/32] & (1<<(type%32)) ) );
607 flow6id_match( int curr_flow, ipfw_insn_u32 *cmd )
610 for (i=0; i <= cmd->o.arg1; ++i )
611 if (curr_flow == cmd->d[i] )
616 /* support for IP6_*_ME opcodes */
618 search_ip6_addr_net (struct in6_addr * ip6_addr)
622 struct in6_ifaddr *fdm;
623 struct in6_addr copia;
625 TAILQ_FOREACH(mdc, &V_ifnet, if_link) {
627 TAILQ_FOREACH(mdc2, &mdc->if_addrhead, ifa_link) {
628 if (mdc2->ifa_addr->sa_family == AF_INET6) {
629 fdm = (struct in6_ifaddr *)mdc2;
630 copia = fdm->ia_addr.sin6_addr;
631 /* need for leaving scope_id in the sock_addr */
632 in6_clearscope(&copia);
633 if (IN6_ARE_ADDR_EQUAL(ip6_addr, &copia)) {
634 if_addr_runlock(mdc);
639 if_addr_runlock(mdc);
645 verify_path6(struct in6_addr *src, struct ifnet *ifp)
648 struct sockaddr_in6 *dst;
650 bzero(&ro, sizeof(ro));
652 dst = (struct sockaddr_in6 * )&(ro.ro_dst);
653 dst->sin6_family = AF_INET6;
654 dst->sin6_len = sizeof(*dst);
655 dst->sin6_addr = *src;
656 /* XXX MRT 0 for ipv6 at this time */
657 rtalloc_ign((struct route *)&ro, 0);
659 if (ro.ro_rt == NULL)
663 * if ifp is provided, check for equality with rtentry
664 * We should use rt->rt_ifa->ifa_ifp, instead of rt->rt_ifp,
665 * to support the case of sending packets to an address of our own.
666 * (where the former interface is the first argument of if_simloop()
667 * (=ifp), the latter is lo0)
669 if (ifp != NULL && ro.ro_rt->rt_ifa->ifa_ifp != ifp) {
674 /* if no ifp provided, check if rtentry is not default route */
676 IN6_IS_ADDR_UNSPECIFIED(&satosin6(rt_key(ro.ro_rt))->sin6_addr)) {
681 /* or if this is a blackhole/reject route */
682 if (ifp == NULL && ro.ro_rt->rt_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
687 /* found valid route */
693 hash_packet6(struct ipfw_flow_id *id)
696 i = (id->dst_ip6.__u6_addr.__u6_addr32[2]) ^
697 (id->dst_ip6.__u6_addr.__u6_addr32[3]) ^
698 (id->src_ip6.__u6_addr.__u6_addr32[2]) ^
699 (id->src_ip6.__u6_addr.__u6_addr32[3]) ^
700 (id->dst_port) ^ (id->src_port);
705 is_icmp6_query(int icmp6_type)
707 if ((icmp6_type <= ICMP6_MAXTYPE) &&
708 (icmp6_type == ICMP6_ECHO_REQUEST ||
709 icmp6_type == ICMP6_MEMBERSHIP_QUERY ||
710 icmp6_type == ICMP6_WRUREQUEST ||
711 icmp6_type == ICMP6_FQDN_QUERY ||
712 icmp6_type == ICMP6_NI_QUERY))
719 send_reject6(struct ip_fw_args *args, int code, u_int hlen, struct ip6_hdr *ip6)
724 if (code == ICMP6_UNREACH_RST && args->f_id.proto == IPPROTO_TCP) {
726 tcp = (struct tcphdr *)((char *)ip6 + hlen);
728 if ((tcp->th_flags & TH_RST) == 0) {
730 m0 = send_pkt(args->m, &(args->f_id),
731 ntohl(tcp->th_seq), ntohl(tcp->th_ack),
732 tcp->th_flags | TH_RST);
734 ip6_output(m0, NULL, NULL, 0, NULL, NULL,
738 } else if (code != ICMP6_UNREACH_RST) { /* Send an ICMPv6 unreach. */
741 * Unlike above, the mbufs need to line up with the ip6 hdr,
742 * as the contents are read. We need to m_adj() the
744 * The mbuf will however be thrown away so we can adjust it.
745 * Remember we did an m_pullup on it already so we
746 * can make some assumptions about contiguousness.
749 m_adj(m, args->L3offset);
751 icmp6_error(m, ICMP6_DST_UNREACH, code, 0);
760 /* counter for ipfw_log(NULL...) */
761 static VNET_DEFINE(u_int64_t, norule_counter);
762 #define V_norule_counter VNET(norule_counter)
764 #define SNPARGS(buf, len) buf + len, sizeof(buf) > len ? sizeof(buf) - len : 0
765 #define SNP(buf) buf, sizeof(buf)
768 * We enter here when we have a rule with O_LOG.
769 * XXX this function alone takes about 2Kbytes of code!
772 ipfw_log(struct ip_fw *f, u_int hlen, struct ip_fw_args *args,
773 struct mbuf *m, struct ifnet *oif, u_short offset, uint32_t tablearg,
776 struct ether_header *eh = args->eh;
778 int limit_reached = 0;
779 char action2[40], proto[128], fragment[32];
784 if (f == NULL) { /* bogus pkt */
785 if (V_verbose_limit != 0 && V_norule_counter >= V_verbose_limit)
788 if (V_norule_counter == V_verbose_limit)
789 limit_reached = V_verbose_limit;
791 } else { /* O_LOG is the first action, find the real one */
792 ipfw_insn *cmd = ACTION_PTR(f);
793 ipfw_insn_log *l = (ipfw_insn_log *)cmd;
795 if (l->max_log != 0 && l->log_left == 0)
798 if (l->log_left == 0)
799 limit_reached = l->max_log;
800 cmd += F_LEN(cmd); /* point to first action */
801 if (cmd->opcode == O_ALTQ) {
802 ipfw_insn_altq *altq = (ipfw_insn_altq *)cmd;
804 snprintf(SNPARGS(action2, 0), "Altq %d",
808 if (cmd->opcode == O_PROB)
811 if (cmd->opcode == O_TAG)
815 switch (cmd->opcode) {
821 if (cmd->arg1==ICMP_REJECT_RST)
823 else if (cmd->arg1==ICMP_UNREACH_HOST)
826 snprintf(SNPARGS(action2, 0), "Unreach %d",
831 if (cmd->arg1==ICMP6_UNREACH_RST)
834 snprintf(SNPARGS(action2, 0), "Unreach %d",
845 snprintf(SNPARGS(action2, 0), "Divert %d",
849 snprintf(SNPARGS(action2, 0), "Tee %d",
853 snprintf(SNPARGS(action2, 0), "SetFib %d",
857 snprintf(SNPARGS(action2, 0), "SkipTo %d",
861 snprintf(SNPARGS(action2, 0), "Pipe %d",
865 snprintf(SNPARGS(action2, 0), "Queue %d",
869 ipfw_insn_sa *sa = (ipfw_insn_sa *)cmd;
871 struct in_addr dummyaddr;
872 if (sa->sa.sin_addr.s_addr == INADDR_ANY)
873 dummyaddr.s_addr = htonl(tablearg);
875 dummyaddr.s_addr = sa->sa.sin_addr.s_addr;
877 len = snprintf(SNPARGS(action2, 0), "Forward to %s",
878 inet_ntoa(dummyaddr));
881 snprintf(SNPARGS(action2, len), ":%d",
886 snprintf(SNPARGS(action2, 0), "Netgraph %d",
890 snprintf(SNPARGS(action2, 0), "Ngtee %d",
905 if (hlen == 0) { /* non-ip */
906 snprintf(SNPARGS(proto, 0), "MAC");
911 char src[INET6_ADDRSTRLEN + 2], dst[INET6_ADDRSTRLEN + 2];
913 char src[INET_ADDRSTRLEN], dst[INET_ADDRSTRLEN];
915 struct icmphdr *icmp;
919 struct ip6_hdr *ip6 = NULL;
920 struct icmp6_hdr *icmp6;
925 if (IS_IP6_FLOW_ID(&(args->f_id))) {
926 char ip6buf[INET6_ADDRSTRLEN];
927 snprintf(src, sizeof(src), "[%s]",
928 ip6_sprintf(ip6buf, &args->f_id.src_ip6));
929 snprintf(dst, sizeof(dst), "[%s]",
930 ip6_sprintf(ip6buf, &args->f_id.dst_ip6));
932 ip6 = (struct ip6_hdr *)ip;
933 tcp = (struct tcphdr *)(((char *)ip) + hlen);
934 udp = (struct udphdr *)(((char *)ip) + hlen);
938 tcp = L3HDR(struct tcphdr, ip);
939 udp = L3HDR(struct udphdr, ip);
941 inet_ntoa_r(ip->ip_src, src);
942 inet_ntoa_r(ip->ip_dst, dst);
945 switch (args->f_id.proto) {
947 len = snprintf(SNPARGS(proto, 0), "TCP %s", src);
949 snprintf(SNPARGS(proto, len), ":%d %s:%d",
950 ntohs(tcp->th_sport),
952 ntohs(tcp->th_dport));
954 snprintf(SNPARGS(proto, len), " %s", dst);
958 len = snprintf(SNPARGS(proto, 0), "UDP %s", src);
960 snprintf(SNPARGS(proto, len), ":%d %s:%d",
961 ntohs(udp->uh_sport),
963 ntohs(udp->uh_dport));
965 snprintf(SNPARGS(proto, len), " %s", dst);
969 icmp = L3HDR(struct icmphdr, ip);
971 len = snprintf(SNPARGS(proto, 0),
973 icmp->icmp_type, icmp->icmp_code);
975 len = snprintf(SNPARGS(proto, 0), "ICMP ");
976 len += snprintf(SNPARGS(proto, len), "%s", src);
977 snprintf(SNPARGS(proto, len), " %s", dst);
981 icmp6 = (struct icmp6_hdr *)(((char *)ip) + hlen);
983 len = snprintf(SNPARGS(proto, 0),
985 icmp6->icmp6_type, icmp6->icmp6_code);
987 len = snprintf(SNPARGS(proto, 0), "ICMPv6 ");
988 len += snprintf(SNPARGS(proto, len), "%s", src);
989 snprintf(SNPARGS(proto, len), " %s", dst);
993 len = snprintf(SNPARGS(proto, 0), "P:%d %s",
994 args->f_id.proto, src);
995 snprintf(SNPARGS(proto, len), " %s", dst);
1000 if (IS_IP6_FLOW_ID(&(args->f_id))) {
1001 if (offset & (IP6F_OFF_MASK | IP6F_MORE_FRAG))
1002 snprintf(SNPARGS(fragment, 0),
1003 " (frag %08x:%d@%d%s)",
1004 args->f_id.frag_id6,
1005 ntohs(ip6->ip6_plen) - hlen,
1006 ntohs(offset & IP6F_OFF_MASK) << 3,
1007 (offset & IP6F_MORE_FRAG) ? "+" : "");
1012 if (1 || eh != NULL) { /* layer 2 packets are as on the wire */
1013 ip_off = ntohs(ip->ip_off);
1014 ip_len = ntohs(ip->ip_len);
1016 ip_off = ip->ip_off;
1017 ip_len = ip->ip_len;
1019 if (ip_off & (IP_MF | IP_OFFMASK))
1020 snprintf(SNPARGS(fragment, 0),
1021 " (frag %d:%d@%d%s)",
1022 ntohs(ip->ip_id), ip_len - (ip->ip_hl << 2),
1024 (ip_off & IP_MF) ? "+" : "");
1027 if (oif || m->m_pkthdr.rcvif)
1028 log(LOG_SECURITY | LOG_INFO,
1029 "ipfw: %d %s %s %s via %s%s\n",
1030 f ? f->rulenum : -1,
1031 action, proto, oif ? "out" : "in",
1032 oif ? oif->if_xname : m->m_pkthdr.rcvif->if_xname,
1035 log(LOG_SECURITY | LOG_INFO,
1036 "ipfw: %d %s %s [no if info]%s\n",
1037 f ? f->rulenum : -1,
1038 action, proto, fragment);
1040 log(LOG_SECURITY | LOG_NOTICE,
1041 "ipfw: limit %d reached on entry %d\n",
1042 limit_reached, f ? f->rulenum : -1);
1046 * IMPORTANT: the hash function for dynamic rules must be commutative
1047 * in source and destination (ip,port), because rules are bidirectional
1048 * and we want to find both in the same bucket.
1051 hash_packet(struct ipfw_flow_id *id)
1056 if (IS_IP6_FLOW_ID(id))
1057 i = hash_packet6(id);
1060 i = (id->dst_ip) ^ (id->src_ip) ^ (id->dst_port) ^ (id->src_port);
1061 i &= (V_curr_dyn_buckets - 1);
1065 static __inline void
1066 unlink_dyn_rule_print(struct ipfw_flow_id *id)
1070 char src[INET6_ADDRSTRLEN], dst[INET6_ADDRSTRLEN];
1072 char src[INET_ADDRSTRLEN], dst[INET_ADDRSTRLEN];
1076 if (IS_IP6_FLOW_ID(id)) {
1077 ip6_sprintf(src, &id->src_ip6);
1078 ip6_sprintf(dst, &id->dst_ip6);
1082 da.s_addr = htonl(id->src_ip);
1083 inet_ntoa_r(da, src);
1084 da.s_addr = htonl(id->dst_ip);
1085 inet_ntoa_r(da, dst);
1087 printf("ipfw: unlink entry %s %d -> %s %d, %d left\n",
1088 src, id->src_port, dst, id->dst_port, V_dyn_count - 1);
1092 * unlink a dynamic rule from a chain. prev is a pointer to
1093 * the previous one, q is a pointer to the rule to delete,
1094 * head is a pointer to the head of the queue.
1095 * Modifies q and potentially also head.
1097 #define UNLINK_DYN_RULE(prev, head, q) { \
1098 ipfw_dyn_rule *old_q = q; \
1100 /* remove a refcount to the parent */ \
1101 if (q->dyn_type == O_LIMIT) \
1102 q->parent->count--; \
1103 DEB(unlink_dyn_rule_print(&q->id);) \
1105 prev->next = q = q->next; \
1107 head = q = q->next; \
1109 uma_zfree(ipfw_dyn_rule_zone, old_q); }
1111 #define TIME_LEQ(a,b) ((int)((a)-(b)) <= 0)
1114 * Remove dynamic rules pointing to "rule", or all of them if rule == NULL.
1116 * If keep_me == NULL, rules are deleted even if not expired,
1117 * otherwise only expired rules are removed.
1119 * The value of the second parameter is also used to point to identify
1120 * a rule we absolutely do not want to remove (e.g. because we are
1121 * holding a reference to it -- this is the case with O_LIMIT_PARENT
1122 * rules). The pointer is only used for comparison, so any non-null
1126 remove_dyn_rule(struct ip_fw *rule, ipfw_dyn_rule *keep_me)
1128 static u_int32_t last_remove = 0;
1130 #define FORCE (keep_me == NULL)
1132 ipfw_dyn_rule *prev, *q;
1133 int i, pass = 0, max_pass = 0;
1135 IPFW_DYN_LOCK_ASSERT();
1137 if (V_ipfw_dyn_v == NULL || V_dyn_count == 0)
1139 /* do not expire more than once per second, it is useless */
1140 if (!FORCE && last_remove == time_uptime)
1142 last_remove = time_uptime;
1145 * because O_LIMIT refer to parent rules, during the first pass only
1146 * remove child and mark any pending LIMIT_PARENT, and remove
1147 * them in a second pass.
1150 for (i = 0 ; i < V_curr_dyn_buckets ; i++) {
1151 for (prev=NULL, q = V_ipfw_dyn_v[i] ; q ; ) {
1153 * Logic can become complex here, so we split tests.
1157 if (rule != NULL && rule != q->rule)
1158 goto next; /* not the one we are looking for */
1159 if (q->dyn_type == O_LIMIT_PARENT) {
1161 * handle parent in the second pass,
1162 * record we need one.
1167 if (FORCE && q->count != 0 ) {
1168 /* XXX should not happen! */
1169 printf("ipfw: OUCH! cannot remove rule,"
1170 " count %d\n", q->count);
1174 !TIME_LEQ( q->expire, time_uptime ))
1177 if (q->dyn_type != O_LIMIT_PARENT || !q->count) {
1178 UNLINK_DYN_RULE(prev, V_ipfw_dyn_v[i], q);
1186 if (pass++ < max_pass)
1192 * lookup a dynamic rule.
1194 static ipfw_dyn_rule *
1195 lookup_dyn_rule_locked(struct ipfw_flow_id *pkt, int *match_direction,
1199 * stateful ipfw extensions.
1200 * Lookup into dynamic session queue
1202 #define MATCH_REVERSE 0
1203 #define MATCH_FORWARD 1
1204 #define MATCH_NONE 2
1205 #define MATCH_UNKNOWN 3
1206 int i, dir = MATCH_NONE;
1207 ipfw_dyn_rule *prev, *q=NULL;
1209 IPFW_DYN_LOCK_ASSERT();
1211 if (V_ipfw_dyn_v == NULL)
1212 goto done; /* not found */
1213 i = hash_packet( pkt );
1214 for (prev=NULL, q = V_ipfw_dyn_v[i] ; q != NULL ; ) {
1215 if (q->dyn_type == O_LIMIT_PARENT && q->count)
1217 if (TIME_LEQ( q->expire, time_uptime)) { /* expire entry */
1218 UNLINK_DYN_RULE(prev, V_ipfw_dyn_v[i], q);
1221 if (pkt->proto == q->id.proto &&
1222 q->dyn_type != O_LIMIT_PARENT) {
1223 if (IS_IP6_FLOW_ID(pkt)) {
1224 if (IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
1225 &(q->id.src_ip6)) &&
1226 IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
1227 &(q->id.dst_ip6)) &&
1228 pkt->src_port == q->id.src_port &&
1229 pkt->dst_port == q->id.dst_port ) {
1230 dir = MATCH_FORWARD;
1233 if (IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
1234 &(q->id.dst_ip6)) &&
1235 IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
1236 &(q->id.src_ip6)) &&
1237 pkt->src_port == q->id.dst_port &&
1238 pkt->dst_port == q->id.src_port ) {
1239 dir = MATCH_REVERSE;
1243 if (pkt->src_ip == q->id.src_ip &&
1244 pkt->dst_ip == q->id.dst_ip &&
1245 pkt->src_port == q->id.src_port &&
1246 pkt->dst_port == q->id.dst_port ) {
1247 dir = MATCH_FORWARD;
1250 if (pkt->src_ip == q->id.dst_ip &&
1251 pkt->dst_ip == q->id.src_ip &&
1252 pkt->src_port == q->id.dst_port &&
1253 pkt->dst_port == q->id.src_port ) {
1254 dir = MATCH_REVERSE;
1264 goto done; /* q = NULL, not found */
1266 if ( prev != NULL) { /* found and not in front */
1267 prev->next = q->next;
1268 q->next = V_ipfw_dyn_v[i];
1269 V_ipfw_dyn_v[i] = q;
1271 if (pkt->proto == IPPROTO_TCP) { /* update state according to flags */
1272 u_char flags = pkt->flags & (TH_FIN|TH_SYN|TH_RST);
1274 #define BOTH_SYN (TH_SYN | (TH_SYN << 8))
1275 #define BOTH_FIN (TH_FIN | (TH_FIN << 8))
1276 q->state |= (dir == MATCH_FORWARD ) ? flags : (flags << 8);
1278 case TH_SYN: /* opening */
1279 q->expire = time_uptime + V_dyn_syn_lifetime;
1282 case BOTH_SYN: /* move to established */
1283 case BOTH_SYN | TH_FIN : /* one side tries to close */
1284 case BOTH_SYN | (TH_FIN << 8) :
1286 #define _SEQ_GE(a,b) ((int)(a) - (int)(b) >= 0)
1287 u_int32_t ack = ntohl(tcp->th_ack);
1288 if (dir == MATCH_FORWARD) {
1289 if (q->ack_fwd == 0 || _SEQ_GE(ack, q->ack_fwd))
1291 else { /* ignore out-of-sequence */
1295 if (q->ack_rev == 0 || _SEQ_GE(ack, q->ack_rev))
1297 else { /* ignore out-of-sequence */
1302 q->expire = time_uptime + V_dyn_ack_lifetime;
1305 case BOTH_SYN | BOTH_FIN: /* both sides closed */
1306 if (V_dyn_fin_lifetime >= V_dyn_keepalive_period)
1307 V_dyn_fin_lifetime = V_dyn_keepalive_period - 1;
1308 q->expire = time_uptime + V_dyn_fin_lifetime;
1314 * reset or some invalid combination, but can also
1315 * occur if we use keep-state the wrong way.
1317 if ( (q->state & ((TH_RST << 8)|TH_RST)) == 0)
1318 printf("invalid state: 0x%x\n", q->state);
1320 if (V_dyn_rst_lifetime >= V_dyn_keepalive_period)
1321 V_dyn_rst_lifetime = V_dyn_keepalive_period - 1;
1322 q->expire = time_uptime + V_dyn_rst_lifetime;
1325 } else if (pkt->proto == IPPROTO_UDP) {
1326 q->expire = time_uptime + V_dyn_udp_lifetime;
1328 /* other protocols */
1329 q->expire = time_uptime + V_dyn_short_lifetime;
1332 if (match_direction)
1333 *match_direction = dir;
1337 static ipfw_dyn_rule *
1338 lookup_dyn_rule(struct ipfw_flow_id *pkt, int *match_direction,
1344 q = lookup_dyn_rule_locked(pkt, match_direction, tcp);
1347 /* NB: return table locked when q is not NULL */
1352 realloc_dynamic_table(void)
1354 IPFW_DYN_LOCK_ASSERT();
1357 * Try reallocation, make sure we have a power of 2 and do
1358 * not allow more than 64k entries. In case of overflow,
1362 if (V_dyn_buckets > 65536)
1363 V_dyn_buckets = 1024;
1364 if ((V_dyn_buckets & (V_dyn_buckets-1)) != 0) { /* not a power of 2 */
1365 V_dyn_buckets = V_curr_dyn_buckets; /* reset */
1368 V_curr_dyn_buckets = V_dyn_buckets;
1369 if (V_ipfw_dyn_v != NULL)
1370 free(V_ipfw_dyn_v, M_IPFW);
1372 V_ipfw_dyn_v = malloc(V_curr_dyn_buckets * sizeof(ipfw_dyn_rule *),
1373 M_IPFW, M_NOWAIT | M_ZERO);
1374 if (V_ipfw_dyn_v != NULL || V_curr_dyn_buckets <= 2)
1376 V_curr_dyn_buckets /= 2;
1381 * Install state of type 'type' for a dynamic session.
1382 * The hash table contains two type of rules:
1383 * - regular rules (O_KEEP_STATE)
1384 * - rules for sessions with limited number of sess per user
1385 * (O_LIMIT). When they are created, the parent is
1386 * increased by 1, and decreased on delete. In this case,
1387 * the third parameter is the parent rule and not the chain.
1388 * - "parent" rules for the above (O_LIMIT_PARENT).
1390 static ipfw_dyn_rule *
1391 add_dyn_rule(struct ipfw_flow_id *id, u_int8_t dyn_type, struct ip_fw *rule)
1396 IPFW_DYN_LOCK_ASSERT();
1398 if (V_ipfw_dyn_v == NULL ||
1399 (V_dyn_count == 0 && V_dyn_buckets != V_curr_dyn_buckets)) {
1400 realloc_dynamic_table();
1401 if (V_ipfw_dyn_v == NULL)
1402 return NULL; /* failed ! */
1404 i = hash_packet(id);
1406 r = uma_zalloc(ipfw_dyn_rule_zone, M_NOWAIT | M_ZERO);
1408 printf ("ipfw: sorry cannot allocate state\n");
1412 /* increase refcount on parent, and set pointer */
1413 if (dyn_type == O_LIMIT) {
1414 ipfw_dyn_rule *parent = (ipfw_dyn_rule *)rule;
1415 if ( parent->dyn_type != O_LIMIT_PARENT)
1416 panic("invalid parent");
1419 rule = parent->rule;
1423 r->expire = time_uptime + V_dyn_syn_lifetime;
1425 r->dyn_type = dyn_type;
1426 r->pcnt = r->bcnt = 0;
1430 r->next = V_ipfw_dyn_v[i];
1431 V_ipfw_dyn_v[i] = r;
1436 char src[INET6_ADDRSTRLEN];
1437 char dst[INET6_ADDRSTRLEN];
1439 char src[INET_ADDRSTRLEN];
1440 char dst[INET_ADDRSTRLEN];
1444 if (IS_IP6_FLOW_ID(&(r->id))) {
1445 ip6_sprintf(src, &r->id.src_ip6);
1446 ip6_sprintf(dst, &r->id.dst_ip6);
1450 da.s_addr = htonl(r->id.src_ip);
1451 inet_ntoa_r(da, src);
1452 da.s_addr = htonl(r->id.dst_ip);
1453 inet_ntoa_r(da, dst);
1455 printf("ipfw: add dyn entry ty %d %s %d -> %s %d, total %d\n",
1456 dyn_type, src, r->id.src_port, dst, r->id.dst_port,
1463 * lookup dynamic parent rule using pkt and rule as search keys.
1464 * If the lookup fails, then install one.
1466 static ipfw_dyn_rule *
1467 lookup_dyn_parent(struct ipfw_flow_id *pkt, struct ip_fw *rule)
1472 IPFW_DYN_LOCK_ASSERT();
1475 int is_v6 = IS_IP6_FLOW_ID(pkt);
1476 i = hash_packet( pkt );
1477 for (q = V_ipfw_dyn_v[i] ; q != NULL ; q=q->next)
1478 if (q->dyn_type == O_LIMIT_PARENT &&
1480 pkt->proto == q->id.proto &&
1481 pkt->src_port == q->id.src_port &&
1482 pkt->dst_port == q->id.dst_port &&
1485 IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
1486 &(q->id.src_ip6)) &&
1487 IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
1488 &(q->id.dst_ip6))) ||
1490 pkt->src_ip == q->id.src_ip &&
1491 pkt->dst_ip == q->id.dst_ip)
1494 q->expire = time_uptime + V_dyn_short_lifetime;
1495 DEB(printf("ipfw: lookup_dyn_parent found 0x%p\n",q);)
1499 return add_dyn_rule(pkt, O_LIMIT_PARENT, rule);
1503 * Install dynamic state for rule type cmd->o.opcode
1505 * Returns 1 (failure) if state is not installed because of errors or because
1506 * session limitations are enforced.
1509 install_state(struct ip_fw *rule, ipfw_insn_limit *cmd,
1510 struct ip_fw_args *args, uint32_t tablearg)
1512 static int last_log;
1516 char src[INET6_ADDRSTRLEN + 2], dst[INET6_ADDRSTRLEN + 2];
1518 char src[INET_ADDRSTRLEN], dst[INET_ADDRSTRLEN];
1528 if (IS_IP6_FLOW_ID(&(args->f_id))) {
1529 ip6_sprintf(src, &args->f_id.src_ip6);
1530 ip6_sprintf(dst, &args->f_id.dst_ip6);
1534 da.s_addr = htonl(args->f_id.src_ip);
1535 inet_ntoa_r(da, src);
1536 da.s_addr = htonl(args->f_id.dst_ip);
1537 inet_ntoa_r(da, dst);
1539 printf("ipfw: %s: type %d %s %u -> %s %u\n",
1540 __func__, cmd->o.opcode, src, args->f_id.src_port,
1541 dst, args->f_id.dst_port);
1546 q = lookup_dyn_rule_locked(&args->f_id, NULL, NULL);
1548 if (q != NULL) { /* should never occur */
1549 if (last_log != time_uptime) {
1550 last_log = time_uptime;
1551 printf("ipfw: %s: entry already present, done\n",
1558 if (V_dyn_count >= V_dyn_max)
1559 /* Run out of slots, try to remove any expired rule. */
1560 remove_dyn_rule(NULL, (ipfw_dyn_rule *)1);
1562 if (V_dyn_count >= V_dyn_max) {
1563 if (last_log != time_uptime) {
1564 last_log = time_uptime;
1565 printf("ipfw: %s: Too many dynamic rules\n", __func__);
1568 return (1); /* cannot install, notify caller */
1571 switch (cmd->o.opcode) {
1572 case O_KEEP_STATE: /* bidir rule */
1573 add_dyn_rule(&args->f_id, O_KEEP_STATE, rule);
1576 case O_LIMIT: { /* limit number of sessions */
1577 struct ipfw_flow_id id;
1578 ipfw_dyn_rule *parent;
1579 uint32_t conn_limit;
1580 uint16_t limit_mask = cmd->limit_mask;
1582 conn_limit = (cmd->conn_limit == IP_FW_TABLEARG) ?
1583 tablearg : cmd->conn_limit;
1586 if (cmd->conn_limit == IP_FW_TABLEARG)
1587 printf("ipfw: %s: O_LIMIT rule, conn_limit: %u "
1588 "(tablearg)\n", __func__, conn_limit);
1590 printf("ipfw: %s: O_LIMIT rule, conn_limit: %u\n",
1591 __func__, conn_limit);
1594 id.dst_ip = id.src_ip = id.dst_port = id.src_port = 0;
1595 id.proto = args->f_id.proto;
1596 id.addr_type = args->f_id.addr_type;
1597 id.fib = M_GETFIB(args->m);
1599 if (IS_IP6_FLOW_ID (&(args->f_id))) {
1600 if (limit_mask & DYN_SRC_ADDR)
1601 id.src_ip6 = args->f_id.src_ip6;
1602 if (limit_mask & DYN_DST_ADDR)
1603 id.dst_ip6 = args->f_id.dst_ip6;
1605 if (limit_mask & DYN_SRC_ADDR)
1606 id.src_ip = args->f_id.src_ip;
1607 if (limit_mask & DYN_DST_ADDR)
1608 id.dst_ip = args->f_id.dst_ip;
1610 if (limit_mask & DYN_SRC_PORT)
1611 id.src_port = args->f_id.src_port;
1612 if (limit_mask & DYN_DST_PORT)
1613 id.dst_port = args->f_id.dst_port;
1614 if ((parent = lookup_dyn_parent(&id, rule)) == NULL) {
1615 printf("ipfw: %s: add parent failed\n", __func__);
1620 if (parent->count >= conn_limit) {
1621 /* See if we can remove some expired rule. */
1622 remove_dyn_rule(rule, parent);
1623 if (parent->count >= conn_limit) {
1624 if (V_fw_verbose && last_log != time_uptime) {
1625 last_log = time_uptime;
1628 * XXX IPv6 flows are not
1631 if (IS_IP6_FLOW_ID(&(args->f_id))) {
1632 char ip6buf[INET6_ADDRSTRLEN];
1633 snprintf(src, sizeof(src),
1634 "[%s]", ip6_sprintf(ip6buf,
1635 &args->f_id.src_ip6));
1636 snprintf(dst, sizeof(dst),
1637 "[%s]", ip6_sprintf(ip6buf,
1638 &args->f_id.dst_ip6));
1643 htonl(args->f_id.src_ip);
1644 inet_ntoa_r(da, src);
1646 htonl(args->f_id.dst_ip);
1647 inet_ntoa_r(da, dst);
1649 log(LOG_SECURITY | LOG_DEBUG,
1650 "ipfw: %d %s %s:%u -> %s:%u, %s\n",
1651 parent->rule->rulenum,
1653 src, (args->f_id.src_port),
1654 dst, (args->f_id.dst_port),
1655 "too many entries");
1661 add_dyn_rule(&args->f_id, O_LIMIT, (struct ip_fw *)parent);
1665 printf("ipfw: %s: unknown dynamic rule type %u\n",
1666 __func__, cmd->o.opcode);
1671 /* XXX just set lifetime */
1672 lookup_dyn_rule_locked(&args->f_id, NULL, NULL);
1679 * Generate a TCP packet, containing either a RST or a keepalive.
1680 * When flags & TH_RST, we are sending a RST packet, because of a
1681 * "reset" action matched the packet.
1682 * Otherwise we are sending a keepalive, and flags & TH_
1683 * The 'replyto' mbuf is the mbuf being replied to, if any, and is required
1684 * so that MAC can label the reply appropriately.
1686 static struct mbuf *
1687 send_pkt(struct mbuf *replyto, struct ipfw_flow_id *id, u_int32_t seq,
1688 u_int32_t ack, int flags)
1690 #if defined( __linux__ ) || defined( _WIN32 )
1695 struct ip *h = NULL; /* stupid compiler */
1697 struct ip6_hdr *h6 = NULL;
1699 struct tcphdr *th = NULL;
1701 MGETHDR(m, M_DONTWAIT, MT_DATA);
1705 M_SETFIB(m, id->fib);
1707 if (replyto != NULL)
1708 mac_netinet_firewall_reply(replyto, m);
1710 mac_netinet_firewall_send(m);
1712 (void)replyto; /* don't warn about unused arg */
1715 switch (id->addr_type) {
1717 len = sizeof(struct ip) + sizeof(struct tcphdr);
1721 len = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
1725 /* XXX: log me?!? */
1729 dir = ((flags & (TH_SYN | TH_RST)) == TH_SYN);
1731 m->m_data += max_linkhdr;
1732 m->m_flags |= M_SKIP_FIREWALL;
1733 m->m_pkthdr.len = m->m_len = len;
1734 m->m_pkthdr.rcvif = NULL;
1735 bzero(m->m_data, len);
1737 switch (id->addr_type) {
1739 h = mtod(m, struct ip *);
1741 /* prepare for checksum */
1742 h->ip_p = IPPROTO_TCP;
1743 h->ip_len = htons(sizeof(struct tcphdr));
1745 h->ip_src.s_addr = htonl(id->src_ip);
1746 h->ip_dst.s_addr = htonl(id->dst_ip);
1748 h->ip_src.s_addr = htonl(id->dst_ip);
1749 h->ip_dst.s_addr = htonl(id->src_ip);
1752 th = (struct tcphdr *)(h + 1);
1756 h6 = mtod(m, struct ip6_hdr *);
1758 /* prepare for checksum */
1759 h6->ip6_nxt = IPPROTO_TCP;
1760 h6->ip6_plen = htons(sizeof(struct tcphdr));
1762 h6->ip6_src = id->src_ip6;
1763 h6->ip6_dst = id->dst_ip6;
1765 h6->ip6_src = id->dst_ip6;
1766 h6->ip6_dst = id->src_ip6;
1769 th = (struct tcphdr *)(h6 + 1);
1775 th->th_sport = htons(id->src_port);
1776 th->th_dport = htons(id->dst_port);
1778 th->th_sport = htons(id->dst_port);
1779 th->th_dport = htons(id->src_port);
1781 th->th_off = sizeof(struct tcphdr) >> 2;
1783 if (flags & TH_RST) {
1784 if (flags & TH_ACK) {
1785 th->th_seq = htonl(ack);
1786 // XXX th->th_ack = htonl(0);
1787 th->th_flags = TH_RST;
1791 // XXX th->th_seq = htonl(0);
1792 th->th_ack = htonl(seq);
1793 th->th_flags = TH_RST | TH_ACK;
1797 * Keepalive - use caller provided sequence numbers
1799 th->th_seq = htonl(seq);
1800 th->th_ack = htonl(ack);
1801 th->th_flags = TH_ACK;
1804 switch (id->addr_type) {
1806 th->th_sum = in_cksum(m, len);
1808 /* finish the ip header */
1810 h->ip_hl = sizeof(*h) >> 2;
1811 h->ip_tos = IPTOS_LOWDELAY;
1814 h->ip_ttl = V_ip_defttl;
1819 th->th_sum = in6_cksum(m, IPPROTO_TCP, sizeof(*h6),
1820 sizeof(struct tcphdr));
1822 /* finish the ip6 header */
1823 h6->ip6_vfc |= IPV6_VERSION;
1824 h6->ip6_hlim = IPV6_DEFHLIM;
1830 #endif /* !__linux__ */
1834 * sends a reject message, consuming the mbuf passed as an argument.
1837 send_reject(struct ip_fw_args *args, int code, int ip_len, struct ip *ip)
1841 /* XXX When ip is not guaranteed to be at mtod() we will
1842 * need to account for this */
1843 * The mbuf will however be thrown away so we can adjust it.
1844 * Remember we did an m_pullup on it already so we
1845 * can make some assumptions about contiguousness.
1848 m_adj(m, args->L3offset);
1850 if (code != ICMP_REJECT_RST) { /* Send an ICMP unreach */
1851 /* We need the IP header in host order for icmp_error(). */
1852 #if !defined( __linux__ ) && !defined( _WIN32 )
1853 if (args->eh != NULL) {
1854 ip->ip_len = ntohs(ip->ip_len);
1855 ip->ip_off = ntohs(ip->ip_off);
1858 icmp_error(args->m, ICMP_UNREACH, code, 0L, 0);
1859 } else if (args->f_id.proto == IPPROTO_TCP) {
1860 struct tcphdr *const tcp =
1861 L3HDR(struct tcphdr, mtod(args->m, struct ip *));
1862 if ( (tcp->th_flags & TH_RST) == 0) {
1864 m = send_pkt(args->m, &(args->f_id),
1865 ntohl(tcp->th_seq), ntohl(tcp->th_ack),
1866 tcp->th_flags | TH_RST);
1868 ip_output(m, NULL, NULL, 0, NULL, NULL);
1878 * Given an ip_fw *, lookup_next_rule will return a pointer
1879 * to the next rule, which can be either the jump
1880 * target (for skipto instructions) or the next one in the list (in
1881 * all other cases including a missing jump target).
1882 * The result is also written in the "next_rule" field of the rule.
1883 * Backward jumps are not allowed, so start looking from the next
1886 * This never returns NULL -- in case we do not have an exact match,
1887 * the next rule is returned. When the ruleset is changed,
1888 * pointers are flushed so we are always correct.
1891 static struct ip_fw *
1892 lookup_next_rule(struct ip_fw *me, u_int32_t tablearg)
1894 struct ip_fw *rule = NULL;
1898 /* look for action, in case it is a skipto */
1899 cmd = ACTION_PTR(me);
1900 if (cmd->opcode == O_LOG)
1902 if (cmd->opcode == O_ALTQ)
1904 if (cmd->opcode == O_TAG)
1906 if (cmd->opcode == O_SKIPTO ) {
1907 if (tablearg != 0) {
1908 rulenum = (u_int16_t)tablearg;
1910 rulenum = cmd->arg1;
1912 for (rule = me->next; rule ; rule = rule->next) {
1913 if (rule->rulenum >= rulenum) {
1918 if (rule == NULL) /* failure or not a skipto */
1920 me->next_rule = rule;
1925 add_table_entry(struct ip_fw_chain *ch, uint16_t tbl, in_addr_t addr,
1926 uint8_t mlen, uint32_t value)
1928 struct radix_node_head *rnh;
1929 struct table_entry *ent;
1930 struct radix_node *rn;
1932 if (tbl >= IPFW_TABLES_MAX)
1934 rnh = ch->tables[tbl];
1935 ent = malloc(sizeof(*ent), M_IPFW_TBL, M_NOWAIT | M_ZERO);
1940 /* there is no sin_len on linux, and the code assumes the first
1941 * byte in the sockaddr to contain the length in bits.
1942 * So we just dump the number right there
1944 *((uint8_t *)&(ent->addr)) = 8;
1945 *((uint8_t *)&(ent->mask)) = 8;
1947 ent->addr.sin_len = ent->mask.sin_len = 8;
1949 ent->mask.sin_addr.s_addr = htonl(mlen ? ~((1 << (32 - mlen)) - 1) : 0);
1950 ent->addr.sin_addr.s_addr = addr & ent->mask.sin_addr.s_addr;
1952 rn = rnh->rnh_addaddr(&ent->addr, &ent->mask, rnh, (void *)ent);
1955 free(ent, M_IPFW_TBL);
1963 del_table_entry(struct ip_fw_chain *ch, uint16_t tbl, in_addr_t addr,
1966 struct radix_node_head *rnh;
1967 struct table_entry *ent;
1968 struct sockaddr_in sa, mask;
1970 if (tbl >= IPFW_TABLES_MAX)
1972 rnh = ch->tables[tbl];
1974 /* there is no sin_len on linux, see above */
1975 *((uint8_t *)&sa) = 8;
1976 *((uint8_t *)&mask) = 8;
1978 sa.sin_len = mask.sin_len = 8;
1980 mask.sin_addr.s_addr = htonl(mlen ? ~((1 << (32 - mlen)) - 1) : 0);
1981 sa.sin_addr.s_addr = addr & mask.sin_addr.s_addr;
1983 ent = (struct table_entry *)rnh->rnh_deladdr(&sa, &mask, rnh);
1989 free(ent, M_IPFW_TBL);
1994 flush_table_entry(struct radix_node *rn, void *arg)
1996 struct radix_node_head * const rnh = arg;
1997 struct table_entry *ent;
1999 ent = (struct table_entry *)
2000 rnh->rnh_deladdr(rn->rn_key, rn->rn_mask, rnh);
2002 free(ent, M_IPFW_TBL);
2007 flush_table(struct ip_fw_chain *ch, uint16_t tbl)
2009 struct radix_node_head *rnh;
2011 IPFW_WLOCK_ASSERT(ch);
2013 if (tbl >= IPFW_TABLES_MAX)
2015 rnh = ch->tables[tbl];
2016 KASSERT(rnh != NULL, ("NULL IPFW table"));
2017 rnh->rnh_walktree(rnh, flush_table_entry, rnh);
2022 flush_tables(struct ip_fw_chain *ch)
2026 IPFW_WLOCK_ASSERT(ch);
2028 for (tbl = 0; tbl < IPFW_TABLES_MAX; tbl++)
2029 flush_table(ch, tbl);
2033 init_tables(struct ip_fw_chain *ch)
2038 for (i = 0; i < IPFW_TABLES_MAX; i++) {
2039 if (!rn_inithead((void **)&ch->tables[i], 32)) {
2040 for (j = 0; j < i; j++) {
2041 (void) flush_table(ch, j);
2050 lookup_table(struct ip_fw_chain *ch, uint16_t tbl, in_addr_t addr,
2053 struct radix_node_head *rnh;
2054 struct table_entry *ent;
2055 struct sockaddr_in sa;
2057 if (tbl >= IPFW_TABLES_MAX)
2059 rnh = ch->tables[tbl];
2061 /* there is no sin_len on linux, see above */
2062 *((uint8_t *)&sa) = 8;
2066 sa.sin_addr.s_addr = addr;
2067 ent = (struct table_entry *)(rnh->rnh_lookup(&sa, NULL, rnh));
2076 count_table_entry(struct radix_node *rn, void *arg)
2078 u_int32_t * const cnt = arg;
2085 count_table(struct ip_fw_chain *ch, uint32_t tbl, uint32_t *cnt)
2087 struct radix_node_head *rnh;
2089 if (tbl >= IPFW_TABLES_MAX)
2091 rnh = ch->tables[tbl];
2093 rnh->rnh_walktree(rnh, count_table_entry, cnt);
2098 dump_table_entry(struct radix_node *rn, void *arg)
2100 struct table_entry * const n = (struct table_entry *)rn;
2101 ipfw_table * const tbl = arg;
2102 ipfw_table_entry *ent;
2104 if (tbl->cnt == tbl->size)
2106 ent = &tbl->ent[tbl->cnt];
2107 ent->tbl = tbl->tbl;
2108 if (in_nullhost(n->mask.sin_addr))
2111 ent->masklen = 33 - ffs(ntohl(n->mask.sin_addr.s_addr));
2112 ent->addr = n->addr.sin_addr.s_addr;
2113 ent->value = n->value;
2119 dump_table(struct ip_fw_chain *ch, ipfw_table *tbl)
2121 struct radix_node_head *rnh;
2123 if (tbl->tbl >= IPFW_TABLES_MAX)
2125 rnh = ch->tables[tbl->tbl];
2127 rnh->rnh_walktree(rnh, dump_table_entry, tbl);
2132 check_uidgid(ipfw_insn_u32 *insn, int proto, struct ifnet *oif,
2133 struct in_addr dst_ip, u_int16_t dst_port, struct in_addr src_ip,
2134 u_int16_t src_port, struct ucred **uc, int *ugid_lookup,
2139 struct sk_buff *skb = ((struct mbuf *)inp)->m_skb;
2140 struct bsd_ucred *u = (struct bsd_ucred *)uc;
2142 if (*ugid_lookup == 0) { /* actively lookup and copy in cache */
2143 /* returns null if any element of the chain up to file is null.
2144 * if sk != NULL then we also have a reference
2146 *ugid_lookup = linux_lookup(proto,
2147 src_ip.s_addr, htons(src_port),
2148 dst_ip.s_addr, htons(dst_port),
2149 skb, oif ? 1 : 0, u);
2152 if (*ugid_lookup < 0)
2155 if (insn->o.opcode == O_UID)
2156 match = (u->uid == (uid_t)insn->d[0]);
2157 else if (insn->o.opcode == O_JAIL)
2158 match = (u->xid == (uid_t)insn->d[0]);
2159 else if (insn->o.opcode == O_GID)
2160 match = (u->gid == (uid_t)insn->d[0]);
2166 struct inpcbinfo *pi;
2172 * Check to see if the UDP or TCP stack supplied us with
2173 * the PCB. If so, rather then holding a lock and looking
2174 * up the PCB, we can use the one that was supplied.
2176 if (inp && *ugid_lookupp == 0) {
2177 INP_LOCK_ASSERT(inp);
2178 if (inp->inp_socket != NULL) {
2179 *uc = crhold(inp->inp_cred);
2185 * If we have already been here and the packet has no
2186 * PCB entry associated with it, then we can safely
2187 * assume that this is a no match.
2189 if (*ugid_lookupp == -1)
2191 if (proto == IPPROTO_TCP) {
2194 } else if (proto == IPPROTO_UDP) {
2195 wildcard = INPLOOKUP_WILDCARD;
2200 if (*ugid_lookupp == 0) {
2203 in_pcblookup_hash(pi,
2204 dst_ip, htons(dst_port),
2205 src_ip, htons(src_port),
2207 in_pcblookup_hash(pi,
2208 src_ip, htons(src_port),
2209 dst_ip, htons(dst_port),
2212 *uc = crhold(pcb->inp_cred);
2215 INP_INFO_RUNLOCK(pi);
2216 if (*ugid_lookupp == 0) {
2218 * If the lookup did not yield any results, there
2219 * is no sense in coming back and trying again. So
2220 * we can set lookup to -1 and ensure that we wont
2221 * bother the pcb system again.
2227 if (insn->o.opcode == O_UID)
2228 match = ((*uc)->cr_uid == (uid_t)insn->d[0]);
2229 else if (insn->o.opcode == O_GID)
2230 match = groupmember((gid_t)insn->d[0], *uc);
2231 else if (insn->o.opcode == O_JAIL)
2232 match = ((*uc)->cr_prison->pr_id == (int)insn->d[0]);
2238 * The main check routine for the firewall.
2240 * All arguments are in args so we can modify them and return them
2241 * back to the caller.
2245 * args->m (in/out) The packet; we set to NULL when/if we nuke it.
2246 * Starts with the IP header.
2247 * args->eh (in) Mac header if present, or NULL for layer3 packet.
2248 * args->L3offset Number of bytes bypassed if we came from L2.
2249 * e.g. often sizeof(eh) ** NOTYET **
2250 * args->oif Outgoing interface, or NULL if packet is incoming.
2251 * The incoming interface is in the mbuf. (in)
2252 * args->divert_rule (in/out)
2253 * Skip up to the first rule past this rule number;
2254 * upon return, non-zero port number for divert or tee.
2256 * args->rule Pointer to the last matching rule (in/out)
2257 * args->next_hop Socket we are forwarding to (out).
2258 * args->f_id Addresses grabbed from the packet (out)
2259 * args->cookie a cookie depending on rule action
2263 * IP_FW_PASS the packet must be accepted
2264 * IP_FW_DENY the packet must be dropped
2265 * IP_FW_DIVERT divert packet, port in m_tag
2266 * IP_FW_TEE tee packet, port in m_tag
2267 * IP_FW_DUMMYNET to dummynet, pipe in args->cookie
2268 * IP_FW_NETGRAPH into netgraph, cookie args->cookie
2272 ipfw_chk(struct ip_fw_args *args)
2276 * Local variables holding state during the processing of a packet:
2278 * IMPORTANT NOTE: to speed up the processing of rules, there
2279 * are some assumption on the values of the variables, which
2280 * are documented here. Should you change them, please check
2281 * the implementation of the various instructions to make sure
2282 * that they still work.
2284 * args->eh The MAC header. It is non-null for a layer2
2285 * packet, it is NULL for a layer-3 packet.
2287 * args->L3offset Offset in the packet to the L3 (IP or equiv.) header.
2289 * m | args->m Pointer to the mbuf, as received from the caller.
2290 * It may change if ipfw_chk() does an m_pullup, or if it
2291 * consumes the packet because it calls send_reject().
2292 * XXX This has to change, so that ipfw_chk() never modifies
2293 * or consumes the buffer.
2294 * ip is the beginning of the ip(4 or 6) header.
2295 * Calculated by adding the L3offset to the start of data.
2296 * (Until we start using L3offset, the packet is
2297 * supposed to start with the ip header).
2299 struct mbuf *m = args->m;
2300 struct ip *ip = mtod(m, struct ip *);
2303 * For rules which contain uid/gid or jail constraints, cache
2304 * a copy of the users credentials after the pcb lookup has been
2305 * executed. This will speed up the processing of rules with
2306 * these types of constraints, as well as decrease contention
2307 * on pcb related locks.
2309 struct bsd_ucred ucred_cache;
2310 int ucred_lookup = 0;
2313 * divinput_flags If non-zero, set to the IP_FW_DIVERT_*_FLAG
2314 * associated with a packet input on a divert socket. This
2315 * will allow to distinguish traffic and its direction when
2316 * it originates from a divert socket.
2318 u_int divinput_flags = 0;
2321 * oif | args->oif If NULL, ipfw_chk has been called on the
2322 * inbound path (ether_input, ip_input).
2323 * If non-NULL, ipfw_chk has been called on the outbound path
2324 * (ether_output, ip_output).
2326 struct ifnet *oif = args->oif;
2328 struct ip_fw *f = NULL; /* matching rule */
2332 * hlen The length of the IP header.
2334 u_int hlen = 0; /* hlen >0 means we have an IP pkt */
2337 * offset The offset of a fragment. offset != 0 means that
2338 * we have a fragment at this offset of an IPv4 packet.
2339 * offset == 0 means that (if this is an IPv4 packet)
2340 * this is the first or only fragment.
2341 * For IPv6 offset == 0 means there is no Fragment Header.
2342 * If offset != 0 for IPv6 always use correct mask to
2343 * get the correct offset because we add IP6F_MORE_FRAG
2344 * to be able to dectect the first fragment which would
2345 * otherwise have offset = 0.
2350 * Local copies of addresses. They are only valid if we have
2353 * proto The protocol. Set to 0 for non-ip packets,
2354 * or to the protocol read from the packet otherwise.
2355 * proto != 0 means that we have an IPv4 packet.
2357 * src_port, dst_port port numbers, in HOST format. Only
2358 * valid for TCP and UDP packets.
2360 * src_ip, dst_ip ip addresses, in NETWORK format.
2361 * Only valid for IPv4 packets.
2364 u_int16_t src_port = 0, dst_port = 0; /* NOTE: host format */
2365 struct in_addr src_ip, dst_ip; /* NOTE: network format */
2368 u_int16_t etype = 0; /* Host order stored ether type */
2371 * dyn_dir = MATCH_UNKNOWN when rules unchecked,
2372 * MATCH_NONE when checked and not matched (q = NULL),
2373 * MATCH_FORWARD or MATCH_REVERSE otherwise (q != NULL)
2375 int dyn_dir = MATCH_UNKNOWN;
2376 ipfw_dyn_rule *q = NULL;
2377 struct ip_fw_chain *chain = &V_layer3_chain;
2381 * We store in ulp a pointer to the upper layer protocol header.
2382 * In the ipv4 case this is easy to determine from the header,
2383 * but for ipv6 we might have some additional headers in the middle.
2384 * ulp is NULL if not found.
2386 void *ulp = NULL; /* upper layer protocol pointer. */
2387 /* XXX ipv6 variables */
2389 u_int16_t ext_hd = 0; /* bits vector for extension header filtering */
2390 /* end of ipv6 variables */
2393 int done = 0; /* flag to exit the outer loop */
2395 if (m->m_flags & M_SKIP_FIREWALL || (! V_ipfw_vnet_ready))
2396 return (IP_FW_PASS); /* accept */
2398 dst_ip.s_addr = 0; /* make sure it is initialized */
2399 src_ip.s_addr = 0; /* make sure it is initialized */
2400 pktlen = m->m_pkthdr.len;
2401 args->f_id.fib = M_GETFIB(m); /* note mbuf not altered) */
2402 proto = args->f_id.proto = 0; /* mark f_id invalid */
2403 /* XXX 0 is a valid proto: IP/IPv6 Hop-by-Hop Option */
2406 * PULLUP_TO(len, p, T) makes sure that len + sizeof(T) is contiguous,
2407 * then it sets p to point at the offset "len" in the mbuf. WARNING: the
2408 * pointer might become stale after other pullups (but we never use it
2411 #define PULLUP_TO(_len, p, T) \
2413 int x = (_len) + sizeof(T); \
2414 if ((m)->m_len < x) { \
2415 goto pullup_failed; \
2417 p = (mtod(m, char *) + (_len)); \
2421 * if we have an ether header,
2424 etype = ntohs(args->eh->ether_type);
2426 /* Identify IP packets and fill up variables. */
2427 if (pktlen >= sizeof(struct ip6_hdr) &&
2428 (args->eh == NULL || etype == ETHERTYPE_IPV6) && ip->ip_v == 6) {
2429 struct ip6_hdr *ip6 = (struct ip6_hdr *)ip;
2431 args->f_id.addr_type = 6;
2432 hlen = sizeof(struct ip6_hdr);
2433 proto = ip6->ip6_nxt;
2435 /* Search extension headers to find upper layer protocols */
2436 while (ulp == NULL) {
2438 case IPPROTO_ICMPV6:
2439 PULLUP_TO(hlen, ulp, struct icmp6_hdr);
2440 args->f_id.flags = ICMP6(ulp)->icmp6_type;
2444 PULLUP_TO(hlen, ulp, struct tcphdr);
2445 dst_port = TCP(ulp)->th_dport;
2446 src_port = TCP(ulp)->th_sport;
2447 args->f_id.flags = TCP(ulp)->th_flags;
2451 PULLUP_TO(hlen, ulp, struct sctphdr);
2452 src_port = SCTP(ulp)->src_port;
2453 dst_port = SCTP(ulp)->dest_port;
2457 PULLUP_TO(hlen, ulp, struct udphdr);
2458 dst_port = UDP(ulp)->uh_dport;
2459 src_port = UDP(ulp)->uh_sport;
2462 case IPPROTO_HOPOPTS: /* RFC 2460 */
2463 PULLUP_TO(hlen, ulp, struct ip6_hbh);
2464 ext_hd |= EXT_HOPOPTS;
2465 hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3;
2466 proto = ((struct ip6_hbh *)ulp)->ip6h_nxt;
2470 case IPPROTO_ROUTING: /* RFC 2460 */
2471 PULLUP_TO(hlen, ulp, struct ip6_rthdr);
2472 switch (((struct ip6_rthdr *)ulp)->ip6r_type) {
2474 ext_hd |= EXT_RTHDR0;
2477 ext_hd |= EXT_RTHDR2;
2480 printf("IPFW2: IPV6 - Unknown Routing "
2481 "Header type(%d)\n",
2482 ((struct ip6_rthdr *)ulp)->ip6r_type);
2483 if (V_fw_deny_unknown_exthdrs)
2484 return (IP_FW_DENY);
2487 ext_hd |= EXT_ROUTING;
2488 hlen += (((struct ip6_rthdr *)ulp)->ip6r_len + 1) << 3;
2489 proto = ((struct ip6_rthdr *)ulp)->ip6r_nxt;
2493 case IPPROTO_FRAGMENT: /* RFC 2460 */
2494 PULLUP_TO(hlen, ulp, struct ip6_frag);
2495 ext_hd |= EXT_FRAGMENT;
2496 hlen += sizeof (struct ip6_frag);
2497 proto = ((struct ip6_frag *)ulp)->ip6f_nxt;
2498 offset = ((struct ip6_frag *)ulp)->ip6f_offlg &
2500 /* Add IP6F_MORE_FRAG for offset of first
2501 * fragment to be != 0. */
2502 offset |= ((struct ip6_frag *)ulp)->ip6f_offlg &
2505 printf("IPFW2: IPV6 - Invalid Fragment "
2507 if (V_fw_deny_unknown_exthdrs)
2508 return (IP_FW_DENY);
2511 args->f_id.frag_id6 =
2512 ntohl(((struct ip6_frag *)ulp)->ip6f_ident);
2516 case IPPROTO_DSTOPTS: /* RFC 2460 */
2517 PULLUP_TO(hlen, ulp, struct ip6_hbh);
2518 ext_hd |= EXT_DSTOPTS;
2519 hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3;
2520 proto = ((struct ip6_hbh *)ulp)->ip6h_nxt;
2524 case IPPROTO_AH: /* RFC 2402 */
2525 PULLUP_TO(hlen, ulp, struct ip6_ext);
2527 hlen += (((struct ip6_ext *)ulp)->ip6e_len + 2) << 2;
2528 proto = ((struct ip6_ext *)ulp)->ip6e_nxt;
2532 case IPPROTO_ESP: /* RFC 2406 */
2533 PULLUP_TO(hlen, ulp, uint32_t); /* SPI, Seq# */
2534 /* Anything past Seq# is variable length and
2535 * data past this ext. header is encrypted. */
2539 case IPPROTO_NONE: /* RFC 2460 */
2541 * Packet ends here, and IPv6 header has
2542 * already been pulled up. If ip6e_len!=0
2543 * then octets must be ignored.
2545 ulp = ip; /* non-NULL to get out of loop. */
2548 case IPPROTO_OSPFIGP:
2549 /* XXX OSPF header check? */
2550 PULLUP_TO(hlen, ulp, struct ip6_ext);
2554 /* XXX PIM header check? */
2555 PULLUP_TO(hlen, ulp, struct pim);
2559 PULLUP_TO(hlen, ulp, struct carp_header);
2560 if (((struct carp_header *)ulp)->carp_version !=
2562 return (IP_FW_DENY);
2563 if (((struct carp_header *)ulp)->carp_type !=
2565 return (IP_FW_DENY);
2568 case IPPROTO_IPV6: /* RFC 2893 */
2569 PULLUP_TO(hlen, ulp, struct ip6_hdr);
2572 case IPPROTO_IPV4: /* RFC 2893 */
2573 PULLUP_TO(hlen, ulp, struct ip);
2577 printf("IPFW2: IPV6 - Unknown Extension "
2578 "Header(%d), ext_hd=%x\n", proto, ext_hd);
2579 if (V_fw_deny_unknown_exthdrs)
2580 return (IP_FW_DENY);
2581 PULLUP_TO(hlen, ulp, struct ip6_ext);
2585 ip = mtod(m, struct ip *);
2586 ip6 = (struct ip6_hdr *)ip;
2587 args->f_id.src_ip6 = ip6->ip6_src;
2588 args->f_id.dst_ip6 = ip6->ip6_dst;
2589 args->f_id.src_ip = 0;
2590 args->f_id.dst_ip = 0;
2591 args->f_id.flow_id6 = ntohl(ip6->ip6_flow);
2592 } else if (pktlen >= sizeof(struct ip) &&
2593 (args->eh == NULL || etype == ETHERTYPE_IP) && ip->ip_v == 4) {
2595 hlen = ip->ip_hl << 2;
2596 args->f_id.addr_type = 4;
2599 * Collect parameters into local variables for faster matching.
2602 src_ip = ip->ip_src;
2603 dst_ip = ip->ip_dst;
2605 if (1 || args->eh != NULL) { /* layer 2 packets are as on the wire */
2606 offset = ntohs(ip->ip_off) & IP_OFFMASK;
2607 ip_len = ntohs(ip->ip_len);
2609 offset = ip->ip_off & IP_OFFMASK;
2610 ip_len = ip->ip_len;
2612 pktlen = ip_len < pktlen ? ip_len : pktlen;
2617 PULLUP_TO(hlen, ulp, struct tcphdr);
2618 dst_port = TCP(ulp)->th_dport;
2619 src_port = TCP(ulp)->th_sport;
2620 args->f_id.flags = TCP(ulp)->th_flags;
2624 PULLUP_TO(hlen, ulp, struct udphdr);
2625 dst_port = UDP(ulp)->uh_dport;
2626 src_port = UDP(ulp)->uh_sport;
2630 PULLUP_TO(hlen, ulp, struct icmphdr);
2631 args->f_id.flags = ICMP(ulp)->icmp_type;
2639 ip = mtod(m, struct ip *);
2640 args->f_id.src_ip = ntohl(src_ip.s_addr);
2641 args->f_id.dst_ip = ntohl(dst_ip.s_addr);
2644 if (proto) { /* we may have port numbers, store them */
2645 args->f_id.proto = proto;
2646 args->f_id.src_port = src_port = ntohs(src_port);
2647 args->f_id.dst_port = dst_port = ntohs(dst_port);
2651 if (! V_ipfw_vnet_ready) { /* shutting down, leave NOW. */
2652 IPFW_RUNLOCK(chain);
2653 return (IP_FW_PASS); /* accept */
2655 mtag = m_tag_find(m, PACKET_TAG_DIVERT, NULL);
2658 * Packet has already been tagged. Look for the next rule
2659 * to restart processing. Make sure that args->rule still
2660 * exists and not changed.
2661 * If fw_one_pass != 0 then just accept it.
2662 * XXX should not happen here, but optimized out in
2665 if (V_fw_one_pass) {
2666 IPFW_RUNLOCK(chain);
2667 return (IP_FW_PASS);
2669 if (chain->id != args->chain_id) {
2670 for (f = chain->rules; f != NULL; f = f->next)
2671 if (f == args->rule && f->id == args->rule_id)
2677 f = chain->default_rule;
2679 f = args->rule->next_rule;
2682 f = lookup_next_rule(args->rule, 0);
2685 * Find the starting rule. It can be either the first
2686 * one, or the one after divert_rule if asked so.
2688 int skipto = mtag ? divert_cookie(mtag) : 0;
2691 if (args->eh == NULL && skipto != 0) {
2692 if (skipto >= IPFW_DEFAULT_RULE) {
2693 IPFW_RUNLOCK(chain);
2694 return (IP_FW_DENY); /* invalid */
2696 // f = rule2ptr(chain, skipto+1);
2697 while (f && f->rulenum <= skipto)
2701 /* reset divert rule to avoid confusion later */
2703 divinput_flags = divert_info(mtag) &
2704 (IP_FW_DIVERT_OUTPUT_FLAG | IP_FW_DIVERT_LOOPBACK_FLAG);
2705 m_tag_delete(m, mtag);
2709 * Now scan the rules, and parse microinstructions for each rule.
2710 * We have two nested loops and an inner switch. Sometimes we
2711 * need to break out of one or both loops, or re-enter one of
2712 * the loops with updated variables. Loop variables are:
2714 * f (outer loop) points to the current rule.
2715 * On output it points to the matching rule.
2716 * done (outer loop) is used as a flag to break the loop.
2717 * l (inner loop) residual length of current rule.
2718 * cmd points to the current microinstruction.
2720 * We break the inner loop by setting l=0 and possibly
2721 * cmdlen=0 if we don't want to advance cmd.
2722 * We break the outer loop by setting done=1
2723 * We can restart the inner loop by setting l>0 and f, cmd
2726 for (; f; f = f->next) {
2728 uint32_t tablearg = 0;
2729 int l, cmdlen, skip_or; /* skip rest of OR block */
2732 if (V_set_disable & (1 << f->set) )
2736 for (l = f->cmd_len, cmd = f->cmd ; l > 0 ;
2737 l -= cmdlen, cmd += cmdlen) {
2741 * check_body is a jump target used when we find a
2742 * CHECK_STATE, and need to jump to the body of
2747 cmdlen = F_LEN(cmd);
2749 * An OR block (insn_1 || .. || insn_n) has the
2750 * F_OR bit set in all but the last instruction.
2751 * The first match will set "skip_or", and cause
2752 * the following instructions to be skipped until
2753 * past the one with the F_OR bit clear.
2755 if (skip_or) { /* skip this instruction */
2756 if ((cmd->len & F_OR) == 0)
2757 skip_or = 0; /* next one is good */
2760 match = 0; /* set to 1 if we succeed */
2762 switch (cmd->opcode) {
2764 * The first set of opcodes compares the packet's
2765 * fields with some pattern, setting 'match' if a
2766 * match is found. At the end of the loop there is
2767 * logic to deal with F_NOT and F_OR flags associated
2775 printf("ipfw: opcode %d unimplemented\n",
2783 * We only check offset == 0 && proto != 0,
2784 * as this ensures that we have a
2785 * packet with the ports info.
2789 if (is_ipv6) /* XXX to be fixed later */
2791 if (proto == IPPROTO_TCP ||
2792 proto == IPPROTO_UDP)
2793 match = check_uidgid(
2794 (ipfw_insn_u32 *)cmd,
2797 src_ip, src_port, (struct ucred **)&ucred_cache,
2798 &ucred_lookup, (struct inpcb *)args->m);
2802 match = iface_match(m->m_pkthdr.rcvif,
2803 (ipfw_insn_if *)cmd);
2807 match = iface_match(oif, (ipfw_insn_if *)cmd);
2811 match = iface_match(oif ? oif :
2812 m->m_pkthdr.rcvif, (ipfw_insn_if *)cmd);
2816 if (args->eh != NULL) { /* have MAC header */
2817 u_int32_t *want = (u_int32_t *)
2818 ((ipfw_insn_mac *)cmd)->addr;
2819 u_int32_t *mask = (u_int32_t *)
2820 ((ipfw_insn_mac *)cmd)->mask;
2821 u_int32_t *hdr = (u_int32_t *)args->eh;
2824 ( want[0] == (hdr[0] & mask[0]) &&
2825 want[1] == (hdr[1] & mask[1]) &&
2826 want[2] == (hdr[2] & mask[2]) );
2831 if (args->eh != NULL) {
2833 ((ipfw_insn_u16 *)cmd)->ports;
2836 for (i = cmdlen - 1; !match && i>0;
2838 match = (etype >= p[0] &&
2844 match = (offset != 0);
2847 case O_IN: /* "out" is "not in" */
2848 match = (oif == NULL);
2852 match = (args->eh != NULL);
2856 match = (cmd->arg1 & 1 && divinput_flags &
2857 IP_FW_DIVERT_LOOPBACK_FLAG) ||
2858 (cmd->arg1 & 2 && divinput_flags &
2859 IP_FW_DIVERT_OUTPUT_FLAG);
2864 * We do not allow an arg of 0 so the
2865 * check of "proto" only suffices.
2867 match = (proto == cmd->arg1);
2872 (((ipfw_insn_ip *)cmd)->addr.s_addr ==
2876 case O_IP_SRC_LOOKUP:
2877 case O_IP_DST_LOOKUP:
2880 (cmd->opcode == O_IP_DST_LOOKUP) ?
2881 dst_ip.s_addr : src_ip.s_addr;
2884 if (cmdlen > F_INSN_SIZE(ipfw_insn_u32)) {
2885 v = ((ipfw_insn_u32 *)cmd)->d[1];
2890 else if (offset != 0)
2892 else if (proto != IPPROTO_TCP &&
2893 proto != IPPROTO_UDP)
2899 else if (v == 4 || v == 5) {
2901 (ipfw_insn_u32 *)cmd,
2904 src_ip, src_port, (struct ucred **)&ucred_cache,
2905 &ucred_lookup, (struct inpcb *)args->m);
2907 if (v ==4 /* O_UID */)
2908 a = ucred_cache.uid;
2909 else if (v == 5 /* O_JAIL */)
2910 a = ucred_cache.xid;
2912 if (v ==4 /* O_UID */)
2914 else if (v == 5 /* O_JAIL */)
2915 a = (*uc)->cr_prison->pr_id;
2920 match = lookup_table(chain, cmd->arg1, a,
2924 if (cmdlen == F_INSN_SIZE(ipfw_insn_u32))
2926 ((ipfw_insn_u32 *)cmd)->d[0] == v;
2936 (cmd->opcode == O_IP_DST_MASK) ?
2937 dst_ip.s_addr : src_ip.s_addr;
2938 uint32_t *p = ((ipfw_insn_u32 *)cmd)->d;
2941 for (; !match && i>0; i-= 2, p+= 2)
2942 match = (p[0] == (a & p[1]));
2950 INADDR_TO_IFP(src_ip, tif);
2951 match = (tif != NULL);
2958 u_int32_t *d = (u_int32_t *)(cmd+1);
2960 cmd->opcode == O_IP_DST_SET ?
2966 addr -= d[0]; /* subtract base */
2967 match = (addr < cmd->arg1) &&
2968 ( d[ 1 + (addr>>5)] &
2969 (1<<(addr & 0x1f)) );
2975 (((ipfw_insn_ip *)cmd)->addr.s_addr ==
2983 INADDR_TO_IFP(dst_ip, tif);
2984 match = (tif != NULL);
2991 * offset == 0 && proto != 0 is enough
2992 * to guarantee that we have a
2993 * packet with port info.
2995 if ((proto==IPPROTO_UDP || proto==IPPROTO_TCP)
2998 (cmd->opcode == O_IP_SRCPORT) ?
2999 src_port : dst_port ;
3001 ((ipfw_insn_u16 *)cmd)->ports;
3004 for (i = cmdlen - 1; !match && i>0;
3006 match = (x>=p[0] && x<=p[1]);
3011 match = (offset == 0 && proto==IPPROTO_ICMP &&
3012 icmptype_match(ICMP(ulp), (ipfw_insn_u32 *)cmd) );
3017 match = is_ipv6 && offset == 0 &&
3018 proto==IPPROTO_ICMPV6 &&
3020 ICMP6(ulp)->icmp6_type,
3021 (ipfw_insn_u32 *)cmd);
3027 ipopts_match(ip, cmd) );
3032 cmd->arg1 == ip->ip_v);
3038 if (is_ipv4) { /* only for IP packets */
3043 if (cmd->opcode == O_IPLEN)
3045 else if (cmd->opcode == O_IPTTL)
3047 else /* must be IPID */
3048 x = ntohs(ip->ip_id);
3050 match = (cmd->arg1 == x);
3053 /* otherwise we have ranges */
3054 p = ((ipfw_insn_u16 *)cmd)->ports;
3056 for (; !match && i>0; i--, p += 2)
3057 match = (x >= p[0] && x <= p[1]);
3061 case O_IPPRECEDENCE:
3063 (cmd->arg1 == (ip->ip_tos & 0xe0)) );
3068 flags_match(cmd, ip->ip_tos));
3072 if (proto == IPPROTO_TCP && offset == 0) {
3080 ((ip->ip_hl + tcp->th_off) << 2);
3082 match = (cmd->arg1 == x);
3085 /* otherwise we have ranges */
3086 p = ((ipfw_insn_u16 *)cmd)->ports;
3088 for (; !match && i>0; i--, p += 2)
3089 match = (x >= p[0] && x <= p[1]);
3094 match = (proto == IPPROTO_TCP && offset == 0 &&
3095 flags_match(cmd, TCP(ulp)->th_flags));
3099 match = (proto == IPPROTO_TCP && offset == 0 &&
3100 tcpopts_match(TCP(ulp), cmd));
3104 match = (proto == IPPROTO_TCP && offset == 0 &&
3105 ((ipfw_insn_u32 *)cmd)->d[0] ==
3110 match = (proto == IPPROTO_TCP && offset == 0 &&
3111 ((ipfw_insn_u32 *)cmd)->d[0] ==
3116 match = (proto == IPPROTO_TCP && offset == 0 &&
3117 cmd->arg1 == TCP(ulp)->th_win);
3121 /* reject packets which have SYN only */
3122 /* XXX should i also check for TH_ACK ? */
3123 match = (proto == IPPROTO_TCP && offset == 0 &&
3124 (TCP(ulp)->th_flags &
3125 (TH_RST | TH_ACK | TH_SYN)) != TH_SYN);
3130 ipfw_insn_altq *altq = (ipfw_insn_altq *)cmd;
3133 at = pf_find_mtag(m);
3134 if (at != NULL && at->qid != 0)
3136 at = pf_get_mtag(m);
3139 * Let the packet fall back to the
3144 at->qid = altq->qid;
3155 ipfw_log(f, hlen, args, m,
3156 oif, offset, tablearg, ip);
3161 match = (random()<((ipfw_insn_u32 *)cmd)->d[0]);
3166 /* Outgoing packets automatically pass/match */
3167 match = ((oif != NULL) ||
3168 (m->m_pkthdr.rcvif == NULL) ||
3172 verify_path6(&(args->f_id.src_ip6),
3173 m->m_pkthdr.rcvif) :
3175 verify_path(src_ip, m->m_pkthdr.rcvif,
3180 /* Outgoing packets automatically pass/match */
3181 match = (hlen > 0 && ((oif != NULL) ||
3184 verify_path6(&(args->f_id.src_ip6),
3187 verify_path(src_ip, NULL, args->f_id.fib)));
3191 /* Outgoing packets automatically pass/match */
3192 if (oif == NULL && hlen > 0 &&
3193 ( (is_ipv4 && in_localaddr(src_ip))
3196 in6_localaddr(&(args->f_id.src_ip6)))
3201 is_ipv6 ? verify_path6(
3202 &(args->f_id.src_ip6),
3203 m->m_pkthdr.rcvif) :
3215 match = (m_tag_find(m,
3216 PACKET_TAG_IPSEC_IN_DONE, NULL) != NULL);
3218 /* otherwise no match */
3224 IN6_ARE_ADDR_EQUAL(&args->f_id.src_ip6,
3225 &((ipfw_insn_ip6 *)cmd)->addr6);
3230 IN6_ARE_ADDR_EQUAL(&args->f_id.dst_ip6,
3231 &((ipfw_insn_ip6 *)cmd)->addr6);
3233 case O_IP6_SRC_MASK:
3234 case O_IP6_DST_MASK:
3238 struct in6_addr *d =
3239 &((ipfw_insn_ip6 *)cmd)->addr6;
3241 for (; !match && i > 0; d += 2,
3242 i -= F_INSN_SIZE(struct in6_addr)
3248 APPLY_MASK(&p, &d[1]);
3250 IN6_ARE_ADDR_EQUAL(&d[0],
3257 match= is_ipv6 && search_ip6_addr_net(&args->f_id.src_ip6);
3261 match= is_ipv6 && search_ip6_addr_net(&args->f_id.dst_ip6);
3266 flow6id_match(args->f_id.flow_id6,
3267 (ipfw_insn_u32 *) cmd);
3272 (ext_hd & ((ipfw_insn *) cmd)->arg1);
3286 uint32_t tag = (cmd->arg1 == IP_FW_TABLEARG) ?
3287 tablearg : cmd->arg1;
3289 /* Packet is already tagged with this tag? */
3290 mtag = m_tag_locate(m, MTAG_IPFW, tag, NULL);
3292 /* We have `untag' action when F_NOT flag is
3293 * present. And we must remove this mtag from
3294 * mbuf and reset `match' to zero (`match' will
3295 * be inversed later).
3296 * Otherwise we should allocate new mtag and
3297 * push it into mbuf.
3299 if (cmd->len & F_NOT) { /* `untag' action */
3301 m_tag_delete(m, mtag);
3302 } else if (mtag == NULL) {
3303 if ((mtag = m_tag_alloc(MTAG_IPFW,
3304 tag, 0, M_NOWAIT)) != NULL)
3305 m_tag_prepend(m, mtag);
3307 match = (cmd->len & F_NOT) ? 0: 1;
3311 case O_FIB: /* try match the specified fib */
3312 if (args->f_id.fib == cmd->arg1)
3317 uint32_t tag = (cmd->arg1 == IP_FW_TABLEARG) ?
3318 tablearg : cmd->arg1;
3321 match = m_tag_locate(m, MTAG_IPFW,
3326 /* we have ranges */
3327 for (mtag = m_tag_first(m);
3328 mtag != NULL && !match;
3329 mtag = m_tag_next(m, mtag)) {
3333 if (mtag->m_tag_cookie != MTAG_IPFW)
3336 p = ((ipfw_insn_u16 *)cmd)->ports;
3338 for(; !match && i > 0; i--, p += 2)
3340 mtag->m_tag_id >= p[0] &&
3341 mtag->m_tag_id <= p[1];
3348 * The second set of opcodes represents 'actions',
3349 * i.e. the terminal part of a rule once the packet
3350 * matches all previous patterns.
3351 * Typically there is only one action for each rule,
3352 * and the opcode is stored at the end of the rule
3353 * (but there are exceptions -- see below).
3355 * In general, here we set retval and terminate the
3356 * outer loop (would be a 'break 3' in some language,
3357 * but we need to set l=0, done=1)
3360 * O_COUNT and O_SKIPTO actions:
3361 * instead of terminating, we jump to the next rule
3362 * (setting l=0), or to the SKIPTO target (by
3363 * setting f, cmd and l as needed), respectively.
3365 * O_TAG, O_LOG and O_ALTQ action parameters:
3366 * perform some action and set match = 1;
3368 * O_LIMIT and O_KEEP_STATE: these opcodes are
3369 * not real 'actions', and are stored right
3370 * before the 'action' part of the rule.
3371 * These opcodes try to install an entry in the
3372 * state tables; if successful, we continue with
3373 * the next opcode (match=1; break;), otherwise
3374 * the packet must be dropped (set retval,
3375 * break loops with l=0, done=1)
3377 * O_PROBE_STATE and O_CHECK_STATE: these opcodes
3378 * cause a lookup of the state table, and a jump
3379 * to the 'action' part of the parent rule
3380 * if an entry is found, or
3381 * (CHECK_STATE only) a jump to the next rule if
3382 * the entry is not found.
3383 * The result of the lookup is cached so that
3384 * further instances of these opcodes become NOPs.
3385 * The jump to the next rule is done by setting
3390 if (install_state(f,
3391 (ipfw_insn_limit *)cmd, args, tablearg)) {
3392 /* error or limit violation */
3393 retval = IP_FW_DENY;
3394 l = 0; /* exit inner loop */
3395 done = 1; /* exit outer loop */
3403 * dynamic rules are checked at the first
3404 * keep-state or check-state occurrence,
3405 * with the result being stored in dyn_dir.
3406 * The compiler introduces a PROBE_STATE
3407 * instruction for us when we have a
3408 * KEEP_STATE (because PROBE_STATE needs
3411 if (dyn_dir == MATCH_UNKNOWN &&
3412 (q = lookup_dyn_rule(&args->f_id,
3413 &dyn_dir, proto == IPPROTO_TCP ?
3417 * Found dynamic entry, update stats
3418 * and jump to the 'action' part of
3419 * the parent rule by setting
3420 * f, cmd, l and clearing cmdlen.
3425 cmd = ACTION_PTR(f);
3426 l = f->cmd_len - f->act_ofs;
3433 * Dynamic entry not found. If CHECK_STATE,
3434 * skip to next rule, if PROBE_STATE just
3435 * ignore and continue with next opcode.
3437 if (cmd->opcode == O_CHECK_STATE)
3438 l = 0; /* exit inner loop */
3443 retval = 0; /* accept */
3444 l = 0; /* exit inner loop */
3445 done = 1; /* exit outer loop */
3450 args->rule = f; /* report matching rule */
3451 args->rule_id = f->id;
3452 args->chain_id = chain->id;
3453 if (cmd->arg1 == IP_FW_TABLEARG)
3454 args->cookie = tablearg;
3456 args->cookie = cmd->arg1;
3457 retval = IP_FW_DUMMYNET;
3458 l = 0; /* exit inner loop */
3459 done = 1; /* exit outer loop */
3465 if (args->eh) /* not on layer 2 */
3467 /* otherwise this is terminal */
3468 l = 0; /* exit inner loop */
3469 done = 1; /* exit outer loop */
3470 mtag = m_tag_get(PACKET_TAG_DIVERT,
3471 sizeof(struct divert_tag),
3474 retval = IP_FW_DENY;
3476 struct divert_tag *dt;
3477 dt = (struct divert_tag *)(mtag+1);
3478 dt->cookie = f->rulenum;
3479 if (cmd->arg1 == IP_FW_TABLEARG)
3480 dt->info = tablearg;
3482 dt->info = cmd->arg1;
3483 m_tag_prepend(m, mtag);
3484 retval = (cmd->opcode == O_DIVERT) ?
3485 IP_FW_DIVERT : IP_FW_TEE;
3492 f->pcnt++; /* update stats */
3494 f->timestamp = time_uptime;
3495 if (cmd->opcode == O_COUNT) {
3496 l = 0; /* exit inner loop */
3500 if (cmd->arg1 == IP_FW_TABLEARG) {
3501 f = lookup_next_rule(f, tablearg);
3503 if (f->next_rule == NULL)
3504 lookup_next_rule(f, 0);
3508 * Skip disabled rules, and
3509 * re-enter the inner loop
3510 * with the correct f, l and cmd.
3511 * Also clear cmdlen and skip_or
3513 while (f && (V_set_disable & (1 << f->set)))
3515 if (f) { /* found a valid rule */
3519 l = 0; /* exit inner loop */
3528 * Drop the packet and send a reject notice
3529 * if the packet is not ICMP (or is an ICMP
3530 * query), and it is not multicast/broadcast.
3532 if (hlen > 0 && is_ipv4 && offset == 0 &&
3533 (proto != IPPROTO_ICMP ||
3534 is_icmp_query(ICMP(ulp))) &&
3535 !(m->m_flags & (M_BCAST|M_MCAST)) &&
3536 !IN_MULTICAST(ntohl(dst_ip.s_addr))) {
3537 send_reject(args, cmd->arg1, ip_len, ip);
3543 if (hlen > 0 && is_ipv6 &&
3544 ((offset & IP6F_OFF_MASK) == 0) &&
3545 (proto != IPPROTO_ICMPV6 ||
3546 (is_icmp6_query(args->f_id.flags) == 1)) &&
3547 !(m->m_flags & (M_BCAST|M_MCAST)) &&
3548 !IN6_IS_ADDR_MULTICAST(&args->f_id.dst_ip6)) {
3550 args, cmd->arg1, hlen,
3551 (struct ip6_hdr *)ip);
3557 retval = IP_FW_DENY;
3558 l = 0; /* exit inner loop */
3559 done = 1; /* exit outer loop */
3563 if (args->eh) /* not valid on layer2 pkts */
3565 if (!q || dyn_dir == MATCH_FORWARD) {
3566 struct sockaddr_in *sa;
3567 sa = &(((ipfw_insn_sa *)cmd)->sa);
3568 if (sa->sin_addr.s_addr == INADDR_ANY) {
3569 bcopy(sa, &args->hopstore,
3571 args->hopstore.sin_addr.s_addr =
3573 args->next_hop = &args->hopstore;
3575 args->next_hop = sa;
3578 retval = IP_FW_PASS;
3579 l = 0; /* exit inner loop */
3580 done = 1; /* exit outer loop */
3585 args->rule = f; /* report matching rule */
3586 args->rule_id = f->id;
3587 args->chain_id = chain->id;
3588 if (cmd->arg1 == IP_FW_TABLEARG)
3589 args->cookie = tablearg;
3591 args->cookie = cmd->arg1;
3592 retval = (cmd->opcode == O_NETGRAPH) ?
3593 IP_FW_NETGRAPH : IP_FW_NGTEE;
3594 l = 0; /* exit inner loop */
3595 done = 1; /* exit outer loop */
3600 f->pcnt++; /* update stats */
3602 f->timestamp = time_uptime;
3603 M_SETFIB(m, cmd->arg1);
3604 args->f_id.fib = cmd->arg1;
3605 l = 0; /* exit inner loop */
3609 if (!IPFW_NAT_LOADED) {
3610 retval = IP_FW_DENY;
3615 args->rule = f; /* Report matching rule. */
3616 args->rule_id = f->id;
3617 args->chain_id = chain->id;
3618 t = ((ipfw_insn_nat *)cmd)->nat;
3620 nat_id = (cmd->arg1 == IP_FW_TABLEARG) ?
3621 tablearg : cmd->arg1;
3622 LOOKUP_NAT(V_layer3_chain, nat_id, t);
3624 retval = IP_FW_DENY;
3625 l = 0; /* exit inner loop */
3626 done = 1; /* exit outer loop */
3629 if (cmd->arg1 != IP_FW_TABLEARG)
3630 ((ipfw_insn_nat *)cmd)->nat = t;
3632 retval = ipfw_nat_ptr(args, t, m);
3634 l = 0; /* exit inner loop */
3635 done = 1; /* exit outer loop */
3643 l = 0; /* in any case exit inner loop */
3645 ip_off = (args->eh != NULL) ?
3646 ntohs(ip->ip_off) : ip->ip_off;
3647 /* if not fragmented, go to next rule */
3648 if ((ip_off & (IP_MF | IP_OFFMASK)) == 0)
3651 * ip_reass() expects len & off in host
3652 * byte order: fix them in case we come
3655 if (args->eh != NULL) {
3656 ip->ip_len = ntohs(ip->ip_len);
3657 ip->ip_off = ntohs(ip->ip_off);
3660 args->m = m = ip_reass(m);
3663 * IP header checksum fixup after
3664 * reassembly and leave header
3665 * in network byte order.
3667 if (m == NULL) { /* fragment got swallowed */
3668 retval = IP_FW_DENY;
3669 } else { /* good, packet complete */
3672 ip = mtod(m, struct ip *);
3673 hlen = ip->ip_hl << 2;
3674 /* revert len & off for layer2 pkts */
3675 if (args->eh != NULL)
3676 ip->ip_len = htons(ip->ip_len);
3678 if (hlen == sizeof(struct ip))
3679 ip->ip_sum = in_cksum_hdr(ip);
3681 ip->ip_sum = in_cksum(m, hlen);
3682 retval = IP_FW_REASS;
3684 args->rule_id = f->id;
3685 args->chain_id = chain->id;
3687 done = 1; /* exit outer loop */
3693 break; // XXX we disabled some
3694 panic("-- unknown opcode %d\n", cmd->opcode);
3695 } /* end of switch() on opcodes */
3697 * if we get here with l=0, then match is irrelevant.
3700 if (cmd->len & F_NOT)
3704 if (cmd->len & F_OR)
3707 if (!(cmd->len & F_OR)) /* not an OR block, */
3708 break; /* try next rule */
3711 } /* end of inner loop, scan opcodes */
3716 /* next_rule:;*/ /* try next rule */
3718 } /* end of outer for, scan rules */
3721 /* Update statistics */
3724 f->timestamp = time_uptime;
3726 retval = IP_FW_DENY;
3727 printf("ipfw: ouch!, skip past end of rules, denying packet\n");
3729 IPFW_RUNLOCK(chain);
3731 if (ucred_cache != NULL)
3732 crfree(ucred_cache);
3738 printf("ipfw: pullup failed\n");
3739 return (IP_FW_DENY);
3743 * When a rule is added/deleted, clear the next_rule pointers in all rules.
3744 * These will be reconstructed on the fly as packets are matched.
3747 flush_rule_ptrs(struct ip_fw_chain *chain)
3751 IPFW_WLOCK_ASSERT(chain);
3755 for (rule = chain->rules; rule; rule = rule->next)
3756 rule->next_rule = NULL;
3760 * Add a new rule to the list. Copy the rule into a malloc'ed area, then
3761 * possibly create a rule number and add the rule to the list.
3762 * Update the rule_number in the input struct so the caller knows it as well.
3765 add_rule(struct ip_fw_chain *chain, struct ip_fw *input_rule)
3767 struct ip_fw *rule, *f, *prev;
3768 int l = RULESIZE(input_rule);
3770 if (chain->rules == NULL && input_rule->rulenum != IPFW_DEFAULT_RULE)
3773 rule = malloc(l, M_IPFW, M_NOWAIT | M_ZERO);
3777 bcopy(input_rule, rule, l);
3780 rule->next_rule = NULL;
3784 rule->timestamp = 0;
3788 if (chain->rules == NULL) { /* default rule */
3789 chain->rules = rule;
3790 rule->id = ++chain->id;
3795 * If rulenum is 0, find highest numbered rule before the
3796 * default rule, and add autoinc_step
3798 if (V_autoinc_step < 1)
3800 else if (V_autoinc_step > 1000)
3801 V_autoinc_step = 1000;
3802 if (rule->rulenum == 0) {
3804 * locate the highest numbered rule before default
3806 for (f = chain->rules; f; f = f->next) {
3807 if (f->rulenum == IPFW_DEFAULT_RULE)
3809 rule->rulenum = f->rulenum;
3811 if (rule->rulenum < IPFW_DEFAULT_RULE - V_autoinc_step)
3812 rule->rulenum += V_autoinc_step;
3813 input_rule->rulenum = rule->rulenum;
3817 * Now insert the new rule in the right place in the sorted list.
3819 for (prev = NULL, f = chain->rules; f; prev = f, f = f->next) {
3820 if (f->rulenum > rule->rulenum) { /* found the location */
3824 } else { /* head insert */
3825 rule->next = chain->rules;
3826 chain->rules = rule;
3831 flush_rule_ptrs(chain);
3832 /* chain->id incremented inside flush_rule_ptrs() */
3833 rule->id = chain->id;
3837 IPFW_WUNLOCK(chain);
3838 DEB(printf("ipfw: installed rule %d, static count now %d\n",
3839 rule->rulenum, V_static_count);)
3844 * Remove a static rule (including derived * dynamic rules)
3845 * and place it on the ``reap list'' for later reclamation.
3846 * The caller is in charge of clearing rule pointers to avoid
3847 * dangling pointers.
3848 * @return a pointer to the next entry.
3849 * Arguments are not checked, so they better be correct.
3851 static struct ip_fw *
3852 remove_rule(struct ip_fw_chain *chain, struct ip_fw *rule,
3856 int l = RULESIZE(rule);
3858 IPFW_WLOCK_ASSERT(chain);
3862 remove_dyn_rule(rule, NULL /* force removal */);
3871 rule->next = chain->reap;
3878 * Reclaim storage associated with a list of rules. This is
3879 * typically the list created using remove_rule.
3880 * A NULL pointer on input is handled correctly.
3883 reap_rules(struct ip_fw *head)
3887 while ((rule = head) != NULL) {
3894 * Remove all rules from a chain (except rules in set RESVD_SET
3895 * unless kill_default = 1). The caller is responsible for
3896 * reclaiming storage for the rules left in chain->reap.
3899 free_chain(struct ip_fw_chain *chain, int kill_default)
3901 struct ip_fw *prev, *rule;
3903 IPFW_WLOCK_ASSERT(chain);
3906 flush_rule_ptrs(chain); /* more efficient to do outside the loop */
3907 for (prev = NULL, rule = chain->rules; rule ; )
3908 if (kill_default || rule->set != RESVD_SET)
3909 rule = remove_rule(chain, rule, prev);
3917 * Remove all rules with given number, and also do set manipulation.
3918 * Assumes chain != NULL && *chain != NULL.
3920 * The argument is an u_int32_t. The low 16 bit are the rule or set number,
3921 * the next 8 bits are the new set, the top 8 bits are the command:
3923 * 0 delete rules with given number
3924 * 1 delete rules with given set number
3925 * 2 move rules with given number to new set
3926 * 3 move rules with given set number to new set
3927 * 4 swap sets with given numbers
3928 * 5 delete rules with given number and with given set number
3931 del_entry(struct ip_fw_chain *chain, u_int32_t arg)
3933 struct ip_fw *prev = NULL, *rule;
3934 u_int16_t rulenum; /* rule or old_set */
3935 u_int8_t cmd, new_set;
3937 rulenum = arg & 0xffff;
3938 cmd = (arg >> 24) & 0xff;
3939 new_set = (arg >> 16) & 0xff;
3941 if (cmd > 5 || new_set > RESVD_SET)
3943 if (cmd == 0 || cmd == 2 || cmd == 5) {
3944 if (rulenum >= IPFW_DEFAULT_RULE)
3947 if (rulenum > RESVD_SET) /* old_set */
3952 rule = chain->rules; /* common starting point */
3953 chain->reap = NULL; /* prepare for deletions */
3955 case 0: /* delete rules with given number */
3957 * locate first rule to delete
3959 for (; rule->rulenum < rulenum; prev = rule, rule = rule->next)
3961 if (rule->rulenum != rulenum) {
3962 IPFW_WUNLOCK(chain);
3967 * flush pointers outside the loop, then delete all matching
3968 * rules. prev remains the same throughout the cycle.
3970 flush_rule_ptrs(chain);
3971 while (rule->rulenum == rulenum)
3972 rule = remove_rule(chain, rule, prev);
3975 case 1: /* delete all rules with given set number */
3976 flush_rule_ptrs(chain);
3977 while (rule->rulenum < IPFW_DEFAULT_RULE) {
3978 if (rule->set == rulenum)
3979 rule = remove_rule(chain, rule, prev);
3987 case 2: /* move rules with given number to new set */
3988 for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
3989 if (rule->rulenum == rulenum)
3990 rule->set = new_set;
3993 case 3: /* move rules with given set number to new set */
3994 for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
3995 if (rule->set == rulenum)
3996 rule->set = new_set;
3999 case 4: /* swap two sets */
4000 for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
4001 if (rule->set == rulenum)
4002 rule->set = new_set;
4003 else if (rule->set == new_set)
4004 rule->set = rulenum;
4007 case 5: /* delete rules with given number and with given set number.
4008 * rulenum - given rule number;
4009 * new_set - given set number.
4011 for (; rule->rulenum < rulenum; prev = rule, rule = rule->next)
4013 if (rule->rulenum != rulenum) {
4014 IPFW_WUNLOCK(chain);
4017 flush_rule_ptrs(chain);
4018 while (rule->rulenum == rulenum) {
4019 if (rule->set == new_set)
4020 rule = remove_rule(chain, rule, prev);
4028 * Look for rules to reclaim. We grab the list before
4029 * releasing the lock then reclaim them w/o the lock to
4030 * avoid a LOR with dummynet.
4033 IPFW_WUNLOCK(chain);
4039 * Clear counters for a specific rule.
4040 * The enclosing "table" is assumed locked.
4043 clear_counters(struct ip_fw *rule, int log_only)
4045 ipfw_insn_log *l = (ipfw_insn_log *)ACTION_PTR(rule);
4047 if (log_only == 0) {
4048 rule->bcnt = rule->pcnt = 0;
4049 rule->timestamp = 0;
4051 if (l->o.opcode == O_LOG)
4052 l->log_left = l->max_log;
4056 * Reset some or all counters on firewall rules.
4057 * The argument `arg' is an u_int32_t. The low 16 bit are the rule number,
4058 * the next 8 bits are the set number, the top 8 bits are the command:
4059 * 0 work with rules from all set's;
4060 * 1 work with rules only from specified set.
4061 * Specified rule number is zero if we want to clear all entries.
4062 * log_only is 1 if we only want to reset logs, zero otherwise.
4065 zero_entry(struct ip_fw_chain *chain, u_int32_t arg, int log_only)
4070 uint16_t rulenum = arg & 0xffff;
4071 uint8_t set = (arg >> 16) & 0xff;
4072 uint8_t cmd = (arg >> 24) & 0xff;
4076 if (cmd == 1 && set > RESVD_SET)
4081 V_norule_counter = 0;
4082 for (rule = chain->rules; rule; rule = rule->next) {
4083 /* Skip rules from another set. */
4084 if (cmd == 1 && rule->set != set)
4086 clear_counters(rule, log_only);
4088 msg = log_only ? "All logging counts reset" :
4089 "Accounting cleared";
4093 * We can have multiple rules with the same number, so we
4094 * need to clear them all.
4096 for (rule = chain->rules; rule; rule = rule->next)
4097 if (rule->rulenum == rulenum) {
4098 while (rule && rule->rulenum == rulenum) {
4099 if (cmd == 0 || rule->set == set)
4100 clear_counters(rule, log_only);
4106 if (!cleared) { /* we did not find any matching rules */
4107 IPFW_WUNLOCK(chain);
4110 msg = log_only ? "logging count reset" : "cleared";
4112 IPFW_WUNLOCK(chain);
4115 #define lev LOG_SECURITY | LOG_NOTICE
4118 log(lev, "ipfw: Entry %d %s.\n", rulenum, msg);
4120 log(lev, "ipfw: %s.\n", msg);
4126 * Check validity of the structure before insert.
4127 * Fortunately rules are simple, so this mostly need to check rule sizes.
4130 check_ipfw_struct(struct ip_fw *rule, int size)
4136 if (size < sizeof(*rule)) {
4137 printf("ipfw: rule too short\n");
4140 /* first, check for valid size */
4143 printf("ipfw: size mismatch (have %d want %d)\n", size, l);
4146 if (rule->act_ofs >= rule->cmd_len) {
4147 printf("ipfw: bogus action offset (%u > %u)\n",
4148 rule->act_ofs, rule->cmd_len - 1);
4152 * Now go for the individual checks. Very simple ones, basically only
4153 * instruction sizes.
4155 for (l = rule->cmd_len, cmd = rule->cmd ;
4156 l > 0 ; l -= cmdlen, cmd += cmdlen) {
4157 cmdlen = F_LEN(cmd);
4159 printf("ipfw: opcode %d size truncated\n",
4163 DEB(printf("ipfw: opcode %d\n", cmd->opcode);)
4164 switch (cmd->opcode) {
4176 case O_IPPRECEDENCE:
4194 if (cmdlen != F_INSN_SIZE(ipfw_insn))
4199 if (cmdlen != F_INSN_SIZE(ipfw_insn))
4201 if (cmd->arg1 >= rt_numfibs) {
4202 printf("ipfw: invalid fib number %d\n",
4209 if (cmdlen != F_INSN_SIZE(ipfw_insn))
4211 if (cmd->arg1 >= rt_numfibs) {
4212 printf("ipfw: invalid fib number %d\n",
4227 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32))
4232 if (cmdlen != F_INSN_SIZE(ipfw_insn_limit))
4237 if (cmdlen != F_INSN_SIZE(ipfw_insn_log))
4240 ((ipfw_insn_log *)cmd)->log_left =
4241 ((ipfw_insn_log *)cmd)->max_log;
4247 /* only odd command lengths */
4248 if ( !(cmdlen & 1) || cmdlen > 31)
4254 if (cmd->arg1 == 0 || cmd->arg1 > 256) {
4255 printf("ipfw: invalid set size %d\n",
4259 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
4264 case O_IP_SRC_LOOKUP:
4265 case O_IP_DST_LOOKUP:
4266 if (cmd->arg1 >= IPFW_TABLES_MAX) {
4267 printf("ipfw: invalid table number %d\n",
4271 if (cmdlen != F_INSN_SIZE(ipfw_insn) &&
4272 cmdlen != F_INSN_SIZE(ipfw_insn_u32) + 1 &&
4273 cmdlen != F_INSN_SIZE(ipfw_insn_u32))
4278 if (cmdlen != F_INSN_SIZE(ipfw_insn_mac))
4288 if (cmdlen < 1 || cmdlen > 31)
4294 case O_IP_DSTPORT: /* XXX artificial limit, 30 port pairs */
4295 if (cmdlen < 2 || cmdlen > 31)
4302 if (cmdlen != F_INSN_SIZE(ipfw_insn_if))
4307 if (cmdlen != F_INSN_SIZE(ipfw_insn_altq))
4313 if (cmdlen != F_INSN_SIZE(ipfw_insn))
4318 #ifdef IPFIREWALL_FORWARD
4319 if (cmdlen != F_INSN_SIZE(ipfw_insn_sa))
4328 if (ip_divert_ptr == NULL)
4334 if (!NG_IPFW_LOADED)
4339 if (!IPFW_NAT_LOADED)
4341 if (cmdlen != F_INSN_SIZE(ipfw_insn_nat))
4344 case O_FORWARD_MAC: /* XXX not implemented yet */
4356 if (cmdlen != F_INSN_SIZE(ipfw_insn))
4360 printf("ipfw: opcode %d, multiple actions"
4367 printf("ipfw: opcode %d, action must be"
4376 if (cmdlen != F_INSN_SIZE(struct in6_addr) +
4377 F_INSN_SIZE(ipfw_insn))
4382 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
4383 ((ipfw_insn_u32 *)cmd)->o.arg1)
4387 case O_IP6_SRC_MASK:
4388 case O_IP6_DST_MASK:
4389 if ( !(cmdlen & 1) || cmdlen > 127)
4393 if( cmdlen != F_INSN_SIZE( ipfw_insn_icmp6 ) )
4399 switch (cmd->opcode) {
4409 case O_IP6_SRC_MASK:
4410 case O_IP6_DST_MASK:
4412 printf("ipfw: no IPv6 support in kernel\n");
4413 return EPROTONOSUPPORT;
4416 printf("ipfw: opcode %d, unknown opcode\n",
4422 if (have_action == 0) {
4423 printf("ipfw: missing action\n");
4429 printf("ipfw: opcode %d size %d wrong\n",
4430 cmd->opcode, cmdlen);
4435 * Copy the static rules to the supplied buffer
4436 * and return the amount of space actually used.
4439 ipfw_getrules(struct ip_fw_chain *chain, void *buf, size_t space)
4442 char *ep = bp + space;
4445 time_t boot_seconds;
4447 boot_seconds = boottime.tv_sec;
4448 /* XXX this can take a long time and locking will block packet flow */
4450 for (rule = chain->rules; rule ; rule = rule->next) {
4452 * Verify the entry fits in the buffer in case the
4453 * rules changed between calculating buffer space and
4454 * now. This would be better done using a generation
4455 * number but should suffice for now.
4461 * XXX HACK. Store the disable mask in the "next"
4462 * pointer in a wild attempt to keep the ABI the same.
4463 * Why do we do this on EVERY rule?
4465 bcopy(&V_set_disable,
4466 &(((struct ip_fw *)bp)->next_rule),
4467 sizeof(V_set_disable));
4468 if (((struct ip_fw *)bp)->timestamp)
4469 ((struct ip_fw *)bp)->timestamp += boot_seconds;
4473 IPFW_RUNLOCK(chain);
4474 return (bp - (char *)buf);
4478 * Copy the dynamic rules to the supplied buffer
4479 * and return the amount of space actually used.
4480 * XXX marta if we allocate X and rules grows
4481 * we check for size limit while copying rules into the buffer
4484 ipfw_getdynrules(struct ip_fw_chain *chain, void *buf, size_t space)
4487 char *ep = bp + space;
4489 time_t boot_seconds;
4491 printf("dynrules requested\n");
4492 boot_seconds = boottime.tv_sec;
4495 ipfw_dyn_rule *p, *last = NULL;
4498 for (i = 0 ; i < V_curr_dyn_buckets; i++)
4499 for (p = V_ipfw_dyn_v[i] ; p != NULL; p = p->next) {
4500 if (bp + sizeof *p <= ep) {
4501 ipfw_dyn_rule *dst =
4502 (ipfw_dyn_rule *)bp;
4503 bcopy(p, dst, sizeof *p);
4504 bcopy(&(p->rule->rulenum), &(dst->rule),
4505 sizeof(p->rule->rulenum));
4507 * store set number into high word of
4508 * dst->rule pointer.
4510 bcopy(&(p->rule->set),
4511 (char *)&dst->rule +
4512 sizeof(p->rule->rulenum),
4513 sizeof(p->rule->set));
4515 * store a non-null value in "next".
4516 * The userland code will interpret a
4517 * NULL here as a marker
4518 * for the last dynamic rule.
4520 bcopy(&dst, &dst->next, sizeof(dst));
4523 TIME_LEQ(dst->expire, time_uptime) ?
4524 0 : dst->expire - time_uptime ;
4525 bp += sizeof(ipfw_dyn_rule);
4527 p = NULL; /* break the loop */
4528 i = V_curr_dyn_buckets;
4532 if (last != NULL) /* mark last dynamic rule */
4533 bzero(&last->next, sizeof(last));
4535 return (bp - (char *)buf);
4540 * {set|get}sockopt parser.
4543 ipfw_ctl(struct sockopt *sopt)
4545 #define RULE_MAXSIZE (256*sizeof(u_int32_t))
4548 struct ip_fw *buf, *rule;
4549 u_int32_t rulenum[2];
4551 error = priv_check(sopt->sopt_td, PRIV_NETINET_IPFW);
4556 * Disallow modifications in really-really secure mode, but still allow
4557 * the logging counters to be reset.
4559 if (sopt->sopt_name == IP_FW_ADD ||
4560 (sopt->sopt_dir == SOPT_SET && sopt->sopt_name != IP_FW_RESETLOG)) {
4561 error = securelevel_ge(sopt->sopt_td->td_ucred, 3);
4568 switch (sopt->sopt_name) {
4571 * pass up a copy of the current static rules.
4572 * The last static rule has number IPFW_DEFAULT_RULE.
4574 * Note that the calculated size is used to bound the
4575 * amount of data returned to the user. The rule set may
4576 * change between calculating the size and returning the
4577 * data in which case we'll just return what fits.
4579 size = V_static_len; /* size of static rules */
4582 * XXX todo: if the user passes a short length just to know
4583 * how much room is needed, do not bother filling up the
4584 * buffer, just jump to the sooptcopyout.
4586 buf = malloc(size, M_TEMP, M_WAITOK);
4587 error = sooptcopyout(sopt, buf,
4588 ipfw_getrules(&V_layer3_chain, buf, size));
4594 * pass up a copy of the current dynamic rules.
4595 * The last dynamic rule has NULL in the "next" field.
4597 /* if (!V_ipfw_dyn_v) XXX check for empty set ? */
4598 size = (V_dyn_count * sizeof(ipfw_dyn_rule)); /* size of dyn. rules */
4600 buf = malloc(size, M_TEMP, M_WAITOK);
4601 error = sooptcopyout(sopt, buf,
4602 ipfw_getdynrules(&V_layer3_chain, buf, size));
4608 * Normally we cannot release the lock on each iteration.
4609 * We could do it here only because we start from the head all
4610 * the times so there is no risk of missing some entries.
4611 * On the other hand, the risk is that we end up with
4612 * a very inconsistent ruleset, so better keep the lock
4613 * around the whole cycle.
4615 * XXX this code can be improved by resetting the head of
4616 * the list to point to the default rule, and then freeing
4617 * the old list without the need for a lock.
4620 IPFW_WLOCK(&V_layer3_chain);
4621 free_chain(&V_layer3_chain, 0 /* keep default rule */);
4622 rule = V_layer3_chain.reap;
4623 IPFW_WUNLOCK(&V_layer3_chain);
4628 rule = malloc(RULE_MAXSIZE, M_TEMP, M_WAITOK);
4629 error = sooptcopyin(sopt, rule, RULE_MAXSIZE,
4630 sizeof(struct ip_fw) );
4632 error = check_ipfw_struct(rule, sopt->sopt_valsize);
4634 error = add_rule(&V_layer3_chain, rule);
4635 size = RULESIZE(rule);
4636 if (!error && sopt->sopt_dir == SOPT_GET)
4637 error = sooptcopyout(sopt, rule, size);
4644 * IP_FW_DEL is used for deleting single rules or sets,
4645 * and (ab)used to atomically manipulate sets. Argument size
4646 * is used to distinguish between the two:
4648 * delete single rule or set of rules,
4649 * or reassign rules (or sets) to a different set.
4650 * 2*sizeof(u_int32_t)
4651 * atomic disable/enable sets.
4652 * first u_int32_t contains sets to be disabled,
4653 * second u_int32_t contains sets to be enabled.
4655 error = sooptcopyin(sopt, rulenum,
4656 2*sizeof(u_int32_t), sizeof(u_int32_t));
4659 size = sopt->sopt_valsize;
4660 if (size == sizeof(u_int32_t)) /* delete or reassign */
4661 error = del_entry(&V_layer3_chain, rulenum[0]);
4662 else if (size == 2*sizeof(u_int32_t)) /* set enable/disable */
4664 (V_set_disable | rulenum[0]) & ~rulenum[1] &
4665 ~(1<<RESVD_SET); /* set RESVD_SET always enabled */
4671 case IP_FW_RESETLOG: /* argument is an u_int_32, the rule number */
4673 if (sopt->sopt_val != 0) {
4674 error = sooptcopyin(sopt, rulenum,
4675 sizeof(u_int32_t), sizeof(u_int32_t));
4679 error = zero_entry(&V_layer3_chain, rulenum[0],
4680 sopt->sopt_name == IP_FW_RESETLOG);
4683 case IP_FW_TABLE_ADD:
4685 ipfw_table_entry ent;
4687 error = sooptcopyin(sopt, &ent,
4688 sizeof(ent), sizeof(ent));
4691 error = add_table_entry(&V_layer3_chain, ent.tbl,
4692 ent.addr, ent.masklen, ent.value);
4696 case IP_FW_TABLE_DEL:
4698 ipfw_table_entry ent;
4700 error = sooptcopyin(sopt, &ent,
4701 sizeof(ent), sizeof(ent));
4704 error = del_table_entry(&V_layer3_chain, ent.tbl,
4705 ent.addr, ent.masklen);
4709 case IP_FW_TABLE_FLUSH:
4713 error = sooptcopyin(sopt, &tbl,
4714 sizeof(tbl), sizeof(tbl));
4717 IPFW_WLOCK(&V_layer3_chain);
4718 error = flush_table(&V_layer3_chain, tbl);
4719 IPFW_WUNLOCK(&V_layer3_chain);
4723 case IP_FW_TABLE_GETSIZE:
4727 if ((error = sooptcopyin(sopt, &tbl, sizeof(tbl),
4730 IPFW_RLOCK(&V_layer3_chain);
4731 error = count_table(&V_layer3_chain, tbl, &cnt);
4732 IPFW_RUNLOCK(&V_layer3_chain);
4735 error = sooptcopyout(sopt, &cnt, sizeof(cnt));
4739 case IP_FW_TABLE_LIST:
4743 if (sopt->sopt_valsize < sizeof(*tbl)) {
4747 size = sopt->sopt_valsize;
4748 tbl = malloc(size, M_TEMP, M_WAITOK);
4749 error = sooptcopyin(sopt, tbl, size, sizeof(*tbl));
4754 tbl->size = (size - sizeof(*tbl)) /
4755 sizeof(ipfw_table_entry);
4756 IPFW_RLOCK(&V_layer3_chain);
4757 error = dump_table(&V_layer3_chain, tbl);
4758 IPFW_RUNLOCK(&V_layer3_chain);
4763 error = sooptcopyout(sopt, tbl, size);
4769 if (IPFW_NAT_LOADED)
4770 error = ipfw_nat_cfg_ptr(sopt);
4772 printf("IP_FW_NAT_CFG: %s\n",
4773 "ipfw_nat not present, please load it");
4779 if (IPFW_NAT_LOADED)
4780 error = ipfw_nat_del_ptr(sopt);
4782 printf("IP_FW_NAT_DEL: %s\n",
4783 "ipfw_nat not present, please load it");
4788 case IP_FW_NAT_GET_CONFIG:
4789 if (IPFW_NAT_LOADED)
4790 error = ipfw_nat_get_cfg_ptr(sopt);
4792 printf("IP_FW_NAT_GET_CFG: %s\n",
4793 "ipfw_nat not present, please load it");
4798 case IP_FW_NAT_GET_LOG:
4799 if (IPFW_NAT_LOADED)
4800 error = ipfw_nat_get_log_ptr(sopt);
4802 printf("IP_FW_NAT_GET_LOG: %s\n",
4803 "ipfw_nat not present, please load it");
4809 printf("ipfw: ipfw_ctl invalid option %d\n", sopt->sopt_name);
4819 * This procedure is only used to handle keepalives. It is invoked
4820 * every dyn_keepalive_period
4823 ipfw_tick(void * vnetx)
4825 struct mbuf *m0, *m, *mnext, **mtailp;
4827 struct mbuf *m6, **m6_tailp;
4832 struct vnet *vp = vnetx;
4836 if (V_dyn_keepalive == 0 || V_ipfw_dyn_v == NULL || V_dyn_count == 0)
4840 * We make a chain of packets to go out here -- not deferring
4841 * until after we drop the IPFW dynamic rule lock would result
4842 * in a lock order reversal with the normal packet input -> ipfw
4852 for (i = 0 ; i < V_curr_dyn_buckets ; i++) {
4853 for (q = V_ipfw_dyn_v[i] ; q ; q = q->next ) {
4854 if (q->dyn_type == O_LIMIT_PARENT)
4856 if (q->id.proto != IPPROTO_TCP)
4858 if ( (q->state & BOTH_SYN) != BOTH_SYN)
4860 if (TIME_LEQ( time_uptime+V_dyn_keepalive_interval,
4862 continue; /* too early */
4863 if (TIME_LEQ(q->expire, time_uptime))
4864 continue; /* too late, rule expired */
4866 m = send_pkt(NULL, &(q->id), q->ack_rev - 1,
4867 q->ack_fwd, TH_SYN);
4868 mnext = send_pkt(NULL, &(q->id), q->ack_fwd - 1,
4871 switch (q->id.addr_type) {
4875 mtailp = &(*mtailp)->m_nextpkt;
4877 if (mnext != NULL) {
4879 mtailp = &(*mtailp)->m_nextpkt;
4886 m6_tailp = &(*m6_tailp)->m_nextpkt;
4888 if (mnext != NULL) {
4890 m6_tailp = &(*m6_tailp)->m_nextpkt;
4900 for (m = mnext = m0; m != NULL; m = mnext) {
4901 mnext = m->m_nextpkt;
4902 m->m_nextpkt = NULL;
4903 ip_output(m, NULL, NULL, 0, NULL, NULL);
4906 for (m = mnext = m6; m != NULL; m = mnext) {
4907 mnext = m->m_nextpkt;
4908 m->m_nextpkt = NULL;
4909 ip6_output(m, NULL, NULL, 0, NULL, NULL, NULL);
4913 callout_reset(&V_ipfw_timeout, V_dyn_keepalive_period*hz,
4918 static int vnet_ipfw_init(const void *);
4925 ipfw_dyn_rule_zone = uma_zcreate("IPFW dynamic rule",
4926 sizeof(ipfw_dyn_rule), NULL, NULL, NULL, NULL,
4929 IPFW_DYN_LOCK_INIT();
4930 error = vnet_ipfw_init(NULL);
4932 IPFW_DYN_LOCK_DESTROY();
4933 IPFW_LOCK_DESTROY(&V_layer3_chain);
4934 uma_zdestroy(ipfw_dyn_rule_zone);
4939 * Only print out this stuff the first time around,
4940 * when called from the sysinit code.
4946 "initialized, divert %s, nat %s, "
4947 "rule-based forwarding "
4948 #ifdef IPFIREWALL_FORWARD
4953 "default to %s, logging ",
4959 #ifdef IPFIREWALL_NAT
4964 default_to_accept ? "accept" : "deny");
4967 * Note: V_xxx variables can be accessed here but the vnet specific
4968 * initializer may not have been called yet for the VIMAGE case.
4969 * Tuneables will have been processed. We will print out values for
4971 * XXX This should all be rationalized AFTER 8.0
4973 if (V_fw_verbose == 0)
4974 printf("disabled\n");
4975 else if (V_verbose_limit == 0)
4976 printf("unlimited\n");
4978 printf("limited to %d packets/entry by default\n",
4989 ip_fw_chk_ptr = NULL;
4990 ip_fw_ctl_ptr = NULL;
4991 callout_drain(&ipfw_timeout);
4992 IPFW_WLOCK(&V_layer3_chain);
4993 flush_tables(&V_layer3_chain);
4994 V_layer3_chain.reap = NULL;
4995 free_chain(&V_layer3_chain, 1 /* kill default rule */);
4996 reap = V_layer3_chain.reap, V_layer3_chain.reap = NULL;
4997 IPFW_WUNLOCK(&V_layer3_chain);
5000 uma_zdestroy(ipfw_dyn_rule_zone);
5001 IPFW_DYN_LOCK_DESTROY();
5002 if (V_ipfw_dyn_v != NULL)
5003 free(V_ipfw_dyn_v, M_IPFW);
5004 IPFW_LOCK_DESTROY(&V_layer3_chain);
5006 printf("IP firewall unloaded\n");
5010 * Stuff that must be initialized for every instance
5011 * (including the first of course).
5014 vnet_ipfw_init(const void *unused)
5017 struct ip_fw default_rule;
5019 /* First set up some values that are compile time options */
5020 #ifdef IPFIREWALL_VERBOSE
5023 #ifdef IPFIREWALL_VERBOSE_LIMIT
5024 V_verbose_limit = IPFIREWALL_VERBOSE_LIMIT;
5027 error = init_tables(&V_layer3_chain);
5029 panic("init_tables"); /* XXX Marko fix this ! */
5031 #ifdef IPFIREWALL_NAT
5032 LIST_INIT(&V_layer3_chain.nat);
5035 V_autoinc_step = 100; /* bounded to 1..1000 in add_rule() */
5037 V_ipfw_dyn_v = NULL;
5038 V_dyn_buckets = 256; /* must be power of 2 */
5039 V_curr_dyn_buckets = 256; /* must be power of 2 */
5041 V_dyn_ack_lifetime = 300;
5042 V_dyn_syn_lifetime = 20;
5043 V_dyn_fin_lifetime = 1;
5044 V_dyn_rst_lifetime = 1;
5045 V_dyn_udp_lifetime = 10;
5046 V_dyn_short_lifetime = 5;
5048 V_dyn_keepalive_interval = 20;
5049 V_dyn_keepalive_period = 5;
5050 V_dyn_keepalive = 1; /* do send keepalives */
5052 V_dyn_max = 4096; /* max # of dynamic rules */
5054 V_fw_deny_unknown_exthdrs = 1;
5056 V_layer3_chain.rules = NULL;
5057 IPFW_LOCK_INIT(&V_layer3_chain);
5058 callout_init(&V_ipfw_timeout, CALLOUT_MPSAFE);
5060 bzero(&default_rule, sizeof default_rule);
5061 default_rule.act_ofs = 0;
5062 default_rule.rulenum = IPFW_DEFAULT_RULE;
5063 default_rule.cmd_len = 1;
5064 default_rule.set = RESVD_SET;
5065 default_rule.cmd[0].len = 1;
5066 default_rule.cmd[0].opcode = default_to_accept ? O_ACCEPT : O_DENY;
5067 error = add_rule(&V_layer3_chain, &default_rule);
5070 printf("ipfw2: error %u initializing default rule "
5071 "(support disabled)\n", error);
5072 IPFW_LOCK_DESTROY(&V_layer3_chain);
5073 printf("leaving ipfw_iattach (1) with error %d\n", error);
5077 V_layer3_chain.default_rule = V_layer3_chain.rules;
5079 /* curvnet is NULL in the !VIMAGE case */
5080 callout_reset(&V_ipfw_timeout, hz, ipfw_tick, curvnet);
5082 /* First set up some values that are compile time options */
5083 V_ipfw_vnet_ready = 1; /* Open for business */
5086 * Hook the sockopt handler, and the layer2 (V_ip_fw_chk_ptr)
5087 * and pfil hooks for ipv4 and ipv6. Even if the latter two fail
5088 * we still keep the module alive because the sockopt and
5089 * layer2 paths are still useful.
5090 * ipfw[6]_hook return 0 on success, ENOENT on failure,
5091 * so we can ignore the exact return value and just set a flag.
5093 * Note that V_fw[6]_enable are manipulated by a SYSCTL_PROC so
5094 * changes in the underlying (per-vnet) variables trigger
5095 * immediate hook()/unhook() calls.
5096 * In layer2 we have the same behaviour, except that V_ether_ipfw
5097 * is checked on each packet because there are no pfil hooks.
5099 V_ip_fw_ctl_ptr = ipfw_ctl;
5100 V_ip_fw_chk_ptr = ipfw_chk;
5102 if (V_fw_enable && ipfw_hook() != 0) {
5103 error = ENOENT; /* see ip_fw_pfil.c::ipfw_hook() */
5104 printf("ipfw_hook() error\n");
5107 if (V_fw6_enable && ipfw6_hook() != 0) {
5109 printf("ipfw6_hook() error\n");