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>
74 #define INP_LOCK_ASSERT /* define before missing.h otherwise ? */
78 #define IPFW_INTERNAL /* Access to protected data structures in ip_fw.h. */
80 #include <netinet/in.h>
81 #include <netinet/in_var.h>
82 #include <netinet/in_pcb.h>
83 #include <netinet/ip.h>
84 #include <netinet/ip_var.h>
85 #include <netinet/ip_icmp.h>
86 #include <netinet/ip_fw.h>
87 #include <netinet/ip_divert.h>
88 #include <netinet/ip_dummynet.h>
89 #include <netinet/ip_carp.h>
90 #include <netinet/pim.h>
91 #include <netinet/tcp_var.h>
92 #include <netinet/udp.h>
93 #include <netinet/udp_var.h>
94 #include <netinet/sctp.h>
96 #include <netgraph/ng_ipfw.h>
98 #include <netinet/ip6.h>
99 #include <netinet/icmp6.h>
101 #include <netinet6/scope6_var.h>
102 #include <netinet6/ip6_var.h>
105 #include <machine/in_cksum.h> /* XXX for in_cksum */
107 #ifdef IPFW_HASHTABLES
108 #include "hashtable.h"
112 #include <security/mac/mac_framework.h>
115 static VNET_DEFINE(int, ipfw_vnet_ready) = 0;
116 #define V_ipfw_vnet_ready VNET(ipfw_vnet_ready)
118 * set_disable contains one bit per set value (0..31).
119 * If the bit is set, all rules with the corresponding set
120 * are disabled. Set RESVD_SET(31) is reserved for the default rule
121 * and rules that are not deleted by the flush command,
122 * and CANNOT be disabled.
123 * Rules in set RESVD_SET can only be deleted explicitly.
125 static VNET_DEFINE(u_int32_t, set_disable);
126 static VNET_DEFINE(int, fw_verbose);
127 static VNET_DEFINE(struct callout, ipfw_timeout);
128 static VNET_DEFINE(int, verbose_limit);
130 #define V_set_disable VNET(set_disable)
131 #define V_fw_verbose VNET(fw_verbose)
132 #define V_ipfw_timeout VNET(ipfw_timeout)
133 #define V_verbose_limit VNET(verbose_limit)
135 #ifdef IPFIREWALL_DEFAULT_TO_ACCEPT
136 static int default_to_accept = 1;
138 static int default_to_accept;
140 static uma_zone_t ipfw_dyn_rule_zone;
143 * list of rules for layer 3
145 VNET_DEFINE(struct ip_fw_chain, layer3_chain);
147 MALLOC_DEFINE(M_IPFW, "IpFw/IpAcct", "IpFw/IpAcct chain's");
148 MALLOC_DEFINE(M_IPFW_TBL, "ipfw_tbl", "IpFw tables");
149 #define IPFW_NAT_LOADED (ipfw_nat_ptr != NULL)
150 ipfw_nat_t *ipfw_nat_ptr = NULL;
151 ipfw_nat_cfg_t *ipfw_nat_cfg_ptr;
152 ipfw_nat_cfg_t *ipfw_nat_del_ptr;
153 ipfw_nat_cfg_t *ipfw_nat_get_cfg_ptr;
154 ipfw_nat_cfg_t *ipfw_nat_get_log_ptr;
157 struct radix_node rn[2];
158 struct sockaddr_in addr, mask;
162 static VNET_DEFINE(int, autoinc_step);
163 #define V_autoinc_step VNET(autoinc_step)
164 static VNET_DEFINE(int, fw_deny_unknown_exthdrs);
165 #define V_fw_deny_unknown_exthdrs VNET(fw_deny_unknown_exthdrs)
167 extern int ipfw_chg_hook(SYSCTL_HANDLER_ARGS);
170 SYSCTL_NODE(_net_inet_ip, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall");
171 SYSCTL_VNET_PROC(_net_inet_ip_fw, OID_AUTO, enable,
172 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE3, &VNET_NAME(fw_enable), 0,
173 ipfw_chg_hook, "I", "Enable ipfw");
174 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, autoinc_step,
175 CTLFLAG_RW, &VNET_NAME(autoinc_step), 0,
176 "Rule number auto-increment step");
177 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, one_pass,
178 CTLFLAG_RW | CTLFLAG_SECURE3, &VNET_NAME(fw_one_pass), 0,
179 "Only do a single pass through ipfw when using dummynet(4)");
180 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, verbose,
181 CTLFLAG_RW | CTLFLAG_SECURE3, &VNET_NAME(fw_verbose), 0,
182 "Log matches to ipfw rules");
183 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, verbose_limit,
184 CTLFLAG_RW, &VNET_NAME(verbose_limit), 0,
185 "Set upper limit of matches of ipfw rules logged");
186 static unsigned int dummy_default_rule = IPFW_DEFAULT_RULE;
187 SYSCTL_UINT(_net_inet_ip_fw, OID_AUTO, default_rule, CTLFLAG_RD,
188 &dummy_default_rule, IPFW_DEFAULT_RULE,
189 "The default/max possible rule number.");
190 static unsigned int dummy_tables_max = IPFW_TABLES_MAX;
191 SYSCTL_UINT(_net_inet_ip_fw, OID_AUTO, tables_max, CTLFLAG_RD,
192 &dummy_tables_max, IPFW_TABLES_MAX,
193 "The maximum number of tables.");
194 static unsigned int skipto_entries = 256;
195 SYSCTL_UINT(_net_inet_ip_fw, OID_AUTO, skipto_entries,
196 CTLFLAG_RW, &skipto_entries, 0,
197 "Number of entries in the skipto cache");
198 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, default_to_accept, CTLFLAG_RDTUN,
199 &default_to_accept, 0,
200 "Make the default rule accept all packets.");
201 TUNABLE_INT("net.inet.ip.fw.default_to_accept", &default_to_accept);
204 SYSCTL_DECL(_net_inet6_ip6);
205 SYSCTL_NODE(_net_inet6_ip6, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall");
206 SYSCTL_VNET_PROC(_net_inet6_ip6_fw, OID_AUTO, enable,
207 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE3, &VNET_NAME(fw6_enable), 0,
208 ipfw_chg_hook, "I", "Enable ipfw+6");
209 SYSCTL_VNET_INT(_net_inet6_ip6_fw, OID_AUTO, deny_unknown_exthdrs,
210 CTLFLAG_RW | CTLFLAG_SECURE, &VNET_NAME(fw_deny_unknown_exthdrs), 0,
211 "Deny packets with unknown IPv6 Extension Headers");
214 #endif /* SYSCTL_NODE */
217 * Description of dynamic rules.
219 * Dynamic rules are stored in lists accessed through a hash table
220 * (ipfw_dyn_v) whose size is curr_dyn_buckets. This value can
221 * be modified through the sysctl variable dyn_buckets which is
222 * updated when the table becomes empty.
224 * XXX currently there is only one list, ipfw_dyn.
226 * When a packet is received, its address fields are first masked
227 * with the mask defined for the rule, then hashed, then matched
228 * against the entries in the corresponding list.
229 * Dynamic rules can be used for different purposes:
231 * + enforcing limits on the number of sessions;
232 * + in-kernel NAT (not implemented yet)
234 * The lifetime of dynamic rules is regulated by dyn_*_lifetime,
235 * measured in seconds and depending on the flags.
237 * The total number of dynamic rules is stored in dyn_count.
238 * The max number of dynamic rules is dyn_max. When we reach
239 * the maximum number of rules we do not create anymore. This is
240 * done to avoid consuming too much memory, but also too much
241 * time when searching on each packet (ideally, we should try instead
242 * to put a limit on the length of the list on each bucket...).
244 * Each dynamic rule holds a pointer to the parent ipfw rule so
245 * we know what action to perform. Dynamic rules are removed when
246 * the parent rule is deleted. XXX we should make them survive.
248 * There are some limitations with dynamic rules -- we do not
249 * obey the 'randomized match', and we do not do multiple
250 * passes through the firewall. XXX check the latter!!!
252 static VNET_DEFINE(ipfw_dyn_rule **, ipfw_dyn_v);
253 static VNET_DEFINE(u_int32_t, dyn_buckets);
254 static VNET_DEFINE(u_int32_t, curr_dyn_buckets);
256 #define V_ipfw_dyn_v VNET(ipfw_dyn_v)
257 #define V_dyn_buckets VNET(dyn_buckets)
258 #define V_curr_dyn_buckets VNET(curr_dyn_buckets)
260 #if defined( __linux__ ) || defined( _WIN32 )
261 DEFINE_SPINLOCK(ipfw_dyn_mtx);
263 static struct mtx ipfw_dyn_mtx; /* mutex guarding dynamic rules */
264 #endif /* !__linux__ */
265 #define IPFW_DYN_LOCK_INIT() \
266 mtx_init(&ipfw_dyn_mtx, "IPFW dynamic rules", NULL, MTX_DEF)
267 #define IPFW_DYN_LOCK_DESTROY() mtx_destroy(&ipfw_dyn_mtx)
268 #define IPFW_DYN_LOCK() mtx_lock(&ipfw_dyn_mtx)
269 #define IPFW_DYN_UNLOCK() mtx_unlock(&ipfw_dyn_mtx)
270 #define IPFW_DYN_LOCK_ASSERT() mtx_assert(&ipfw_dyn_mtx, MA_OWNED)
272 static struct mbuf *send_pkt(struct mbuf *, struct ipfw_flow_id *,
273 u_int32_t, u_int32_t, int);
277 * Timeouts for various events in handing dynamic rules.
279 static VNET_DEFINE(u_int32_t, dyn_ack_lifetime);
280 static VNET_DEFINE(u_int32_t, dyn_syn_lifetime);
281 static VNET_DEFINE(u_int32_t, dyn_fin_lifetime);
282 static VNET_DEFINE(u_int32_t, dyn_rst_lifetime);
283 static VNET_DEFINE(u_int32_t, dyn_udp_lifetime);
284 static VNET_DEFINE(u_int32_t, dyn_short_lifetime);
286 #define V_dyn_ack_lifetime VNET(dyn_ack_lifetime)
287 #define V_dyn_syn_lifetime VNET(dyn_syn_lifetime)
288 #define V_dyn_fin_lifetime VNET(dyn_fin_lifetime)
289 #define V_dyn_rst_lifetime VNET(dyn_rst_lifetime)
290 #define V_dyn_udp_lifetime VNET(dyn_udp_lifetime)
291 #define V_dyn_short_lifetime VNET(dyn_short_lifetime)
294 * Keepalives are sent if dyn_keepalive is set. They are sent every
295 * dyn_keepalive_period seconds, in the last dyn_keepalive_interval
296 * seconds of lifetime of a rule.
297 * dyn_rst_lifetime and dyn_fin_lifetime should be strictly lower
298 * than dyn_keepalive_period.
301 static VNET_DEFINE(u_int32_t, dyn_keepalive_interval);
302 static VNET_DEFINE(u_int32_t, dyn_keepalive_period);
303 static VNET_DEFINE(u_int32_t, dyn_keepalive);
305 #define V_dyn_keepalive_interval VNET(dyn_keepalive_interval)
306 #define V_dyn_keepalive_period VNET(dyn_keepalive_period)
307 #define V_dyn_keepalive VNET(dyn_keepalive)
309 static VNET_DEFINE(u_int32_t, static_count); /* # of static rules */
310 static VNET_DEFINE(u_int32_t, static_len); /* bytes of static rules */
311 static VNET_DEFINE(u_int32_t, dyn_count); /* # of dynamic rules */
312 static VNET_DEFINE(u_int32_t, dyn_max); /* max # of dynamic rules */
314 #define V_static_count VNET(static_count)
315 #define V_static_len VNET(static_len)
316 #define V_dyn_count VNET(dyn_count)
317 #define V_dyn_max VNET(dyn_max)
320 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_buckets,
321 CTLFLAG_RW, &VNET_NAME(dyn_buckets), 0,
322 "Number of dyn. buckets");
323 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, curr_dyn_buckets,
324 CTLFLAG_RD, &VNET_NAME(curr_dyn_buckets), 0,
325 "Current Number of dyn. buckets");
326 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_count,
327 CTLFLAG_RD, &VNET_NAME(dyn_count), 0,
328 "Number of dyn. rules");
329 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_max,
330 CTLFLAG_RW, &VNET_NAME(dyn_max), 0,
331 "Max number of dyn. rules");
332 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, static_count,
333 CTLFLAG_RD, &VNET_NAME(static_count), 0,
334 "Number of static rules");
335 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_ack_lifetime,
336 CTLFLAG_RW, &VNET_NAME(dyn_ack_lifetime), 0,
337 "Lifetime of dyn. rules for acks");
338 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_syn_lifetime,
339 CTLFLAG_RW, &VNET_NAME(dyn_syn_lifetime), 0,
340 "Lifetime of dyn. rules for syn");
341 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_fin_lifetime,
342 CTLFLAG_RW, &VNET_NAME(dyn_fin_lifetime), 0,
343 "Lifetime of dyn. rules for fin");
344 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_rst_lifetime,
345 CTLFLAG_RW, &VNET_NAME(dyn_rst_lifetime), 0,
346 "Lifetime of dyn. rules for rst");
347 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_udp_lifetime,
348 CTLFLAG_RW, &VNET_NAME(dyn_udp_lifetime), 0,
349 "Lifetime of dyn. rules for UDP");
350 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_short_lifetime,
351 CTLFLAG_RW, &VNET_NAME(dyn_short_lifetime), 0,
352 "Lifetime of dyn. rules for other situations");
353 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_keepalive,
354 CTLFLAG_RW, &VNET_NAME(dyn_keepalive), 0,
355 "Enable keepalives for dyn. rules");
356 #endif /* SYSCTL_NODE */
359 * L3HDR maps an ipv4 pointer into a layer3 header pointer of type T
360 * Other macros just cast void * into the appropriate type
362 #define L3HDR(T, ip) ((T *)((u_int32_t *)(ip) + (ip)->ip_hl))
363 #define TCP(p) ((struct tcphdr *)(p))
364 #define SCTP(p) ((struct sctphdr *)(p))
365 #define UDP(p) ((struct udphdr *)(p))
366 #define ICMP(p) ((struct icmphdr *)(p))
367 #define ICMP6(p) ((struct icmp6_hdr *)(p))
370 icmptype_match(struct icmphdr *icmp, ipfw_insn_u32 *cmd)
372 int type = icmp->icmp_type;
374 return (type <= ICMP_MAXTYPE && (cmd->d[0] & (1<<type)) );
377 #define TT ( (1 << ICMP_ECHO) | (1 << ICMP_ROUTERSOLICIT) | \
378 (1 << ICMP_TSTAMP) | (1 << ICMP_IREQ) | (1 << ICMP_MASKREQ) )
381 is_icmp_query(struct icmphdr *icmp)
383 int type = icmp->icmp_type;
385 return (type <= ICMP_MAXTYPE && (TT & (1<<type)) );
390 * The following checks use two arrays of 8 or 16 bits to store the
391 * bits that we want set or clear, respectively. They are in the
392 * low and high half of cmd->arg1 or cmd->d[0].
394 * We scan options and store the bits we find set. We succeed if
396 * (want_set & ~bits) == 0 && (want_clear & ~bits) == want_clear
398 * The code is sometimes optimized not to store additional variables.
402 flags_match(ipfw_insn *cmd, u_int8_t bits)
407 if ( ((cmd->arg1 & 0xff) & bits) != 0)
408 return 0; /* some bits we want set were clear */
409 want_clear = (cmd->arg1 >> 8) & 0xff;
410 if ( (want_clear & bits) != want_clear)
411 return 0; /* some bits we want clear were set */
416 ipopts_match(struct ip *ip, ipfw_insn *cmd)
418 int optlen, bits = 0;
419 u_char *cp = (u_char *)(ip + 1);
420 int x = (ip->ip_hl << 2) - sizeof (struct ip);
422 for (; x > 0; x -= optlen, cp += optlen) {
423 int opt = cp[IPOPT_OPTVAL];
425 if (opt == IPOPT_EOL)
427 if (opt == IPOPT_NOP)
430 optlen = cp[IPOPT_OLEN];
431 if (optlen <= 0 || optlen > x)
432 return 0; /* invalid or truncated */
440 bits |= IP_FW_IPOPT_LSRR;
444 bits |= IP_FW_IPOPT_SSRR;
448 bits |= IP_FW_IPOPT_RR;
452 bits |= IP_FW_IPOPT_TS;
456 return (flags_match(cmd, bits));
460 tcpopts_match(struct tcphdr *tcp, ipfw_insn *cmd)
462 int optlen, bits = 0;
463 u_char *cp = (u_char *)(tcp + 1);
464 int x = (tcp->th_off << 2) - sizeof(struct tcphdr);
466 for (; x > 0; x -= optlen, cp += optlen) {
468 if (opt == TCPOPT_EOL)
470 if (opt == TCPOPT_NOP)
484 bits |= IP_FW_TCPOPT_MSS;
488 bits |= IP_FW_TCPOPT_WINDOW;
491 case TCPOPT_SACK_PERMITTED:
493 bits |= IP_FW_TCPOPT_SACK;
496 case TCPOPT_TIMESTAMP:
497 bits |= IP_FW_TCPOPT_TS;
502 return (flags_match(cmd, bits));
506 iface_match(struct ifnet *ifp, ipfw_insn_if *cmd)
508 if (ifp == NULL) /* no iface with this packet, match fails */
510 /* Check by name or by IP address */
511 if (cmd->name[0] != '\0') { /* match by name */
514 if (fnmatch(cmd->name, ifp->if_xname, 0) == 0)
517 if (strncmp(ifp->if_xname, cmd->name, IFNAMSIZ) == 0)
521 #if !defined( __linux__ ) && !defined( _WIN32 )
525 TAILQ_FOREACH(ia, &ifp->if_addrhead, ifa_link) {
526 if (ia->ifa_addr->sa_family != AF_INET)
528 if (cmd->p.ip.s_addr == ((struct sockaddr_in *)
529 (ia->ifa_addr))->sin_addr.s_addr) {
530 if_addr_runlock(ifp);
531 return(1); /* match */
534 if_addr_runlock(ifp);
537 return(0); /* no match, fail ... */
540 #if !defined( __linux__ ) && !defined( _WIN32 )
542 * The verify_path function checks if a route to the src exists and
543 * if it is reachable via ifp (when provided).
545 * The 'verrevpath' option checks that the interface that an IP packet
546 * arrives on is the same interface that traffic destined for the
547 * packet's source address would be routed out of. The 'versrcreach'
548 * option just checks that the source address is reachable via any route
549 * (except default) in the routing table. These two are a measure to block
550 * forged packets. This is also commonly known as "anti-spoofing" or Unicast
551 * Reverse Path Forwarding (Unicast RFP) in Cisco-ese. The name of the knobs
552 * is purposely reminiscent of the Cisco IOS command,
554 * ip verify unicast reverse-path
555 * ip verify unicast source reachable-via any
557 * which implements the same functionality. But note that syntax is
558 * misleading. The check may be performed on all IP packets whether unicast,
559 * multicast, or broadcast.
562 verify_path(struct in_addr src, struct ifnet *ifp, u_int fib)
565 struct sockaddr_in *dst;
567 bzero(&ro, sizeof(ro));
569 dst = (struct sockaddr_in *)&(ro.ro_dst);
570 dst->sin_family = AF_INET;
571 dst->sin_len = sizeof(*dst);
573 in_rtalloc_ign(&ro, 0, fib);
575 if (ro.ro_rt == NULL)
579 * If ifp is provided, check for equality with rtentry.
580 * We should use rt->rt_ifa->ifa_ifp, instead of rt->rt_ifp,
581 * in order to pass packets injected back by if_simloop():
582 * if useloopback == 1 routing entry (via lo0) for our own address
583 * may exist, so we need to handle routing assymetry.
585 if (ifp != NULL && ro.ro_rt->rt_ifa->ifa_ifp != ifp) {
590 /* if no ifp provided, check if rtentry is not default route */
592 satosin(rt_key(ro.ro_rt))->sin_addr.s_addr == INADDR_ANY) {
597 /* or if this is a blackhole/reject route */
598 if (ifp == NULL && ro.ro_rt->rt_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
603 /* found valid route */
611 * ipv6 specific rules here...
614 icmp6type_match (int type, ipfw_insn_u32 *cmd)
616 return (type <= ICMP6_MAXTYPE && (cmd->d[type/32] & (1<<(type%32)) ) );
620 flow6id_match( int curr_flow, ipfw_insn_u32 *cmd )
623 for (i=0; i <= cmd->o.arg1; ++i )
624 if (curr_flow == cmd->d[i] )
629 /* support for IP6_*_ME opcodes */
631 search_ip6_addr_net (struct in6_addr * ip6_addr)
635 struct in6_ifaddr *fdm;
636 struct in6_addr copia;
638 TAILQ_FOREACH(mdc, &V_ifnet, if_link) {
640 TAILQ_FOREACH(mdc2, &mdc->if_addrhead, ifa_link) {
641 if (mdc2->ifa_addr->sa_family == AF_INET6) {
642 fdm = (struct in6_ifaddr *)mdc2;
643 copia = fdm->ia_addr.sin6_addr;
644 /* need for leaving scope_id in the sock_addr */
645 in6_clearscope(&copia);
646 if (IN6_ARE_ADDR_EQUAL(ip6_addr, &copia)) {
647 if_addr_runlock(mdc);
652 if_addr_runlock(mdc);
658 verify_path6(struct in6_addr *src, struct ifnet *ifp)
661 struct sockaddr_in6 *dst;
663 bzero(&ro, sizeof(ro));
665 dst = (struct sockaddr_in6 * )&(ro.ro_dst);
666 dst->sin6_family = AF_INET6;
667 dst->sin6_len = sizeof(*dst);
668 dst->sin6_addr = *src;
669 /* XXX MRT 0 for ipv6 at this time */
670 rtalloc_ign((struct route *)&ro, 0);
672 if (ro.ro_rt == NULL)
676 * if ifp is provided, check for equality with rtentry
677 * We should use rt->rt_ifa->ifa_ifp, instead of rt->rt_ifp,
678 * to support the case of sending packets to an address of our own.
679 * (where the former interface is the first argument of if_simloop()
680 * (=ifp), the latter is lo0)
682 if (ifp != NULL && ro.ro_rt->rt_ifa->ifa_ifp != ifp) {
687 /* if no ifp provided, check if rtentry is not default route */
689 IN6_IS_ADDR_UNSPECIFIED(&satosin6(rt_key(ro.ro_rt))->sin6_addr)) {
694 /* or if this is a blackhole/reject route */
695 if (ifp == NULL && ro.ro_rt->rt_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
700 /* found valid route */
706 hash_packet6(struct ipfw_flow_id *id)
709 i = (id->dst_ip6.__u6_addr.__u6_addr32[2]) ^
710 (id->dst_ip6.__u6_addr.__u6_addr32[3]) ^
711 (id->src_ip6.__u6_addr.__u6_addr32[2]) ^
712 (id->src_ip6.__u6_addr.__u6_addr32[3]) ^
713 (id->dst_port) ^ (id->src_port);
718 is_icmp6_query(int icmp6_type)
720 if ((icmp6_type <= ICMP6_MAXTYPE) &&
721 (icmp6_type == ICMP6_ECHO_REQUEST ||
722 icmp6_type == ICMP6_MEMBERSHIP_QUERY ||
723 icmp6_type == ICMP6_WRUREQUEST ||
724 icmp6_type == ICMP6_FQDN_QUERY ||
725 icmp6_type == ICMP6_NI_QUERY))
732 send_reject6(struct ip_fw_args *args, int code, u_int hlen, struct ip6_hdr *ip6)
737 if (code == ICMP6_UNREACH_RST && args->f_id.proto == IPPROTO_TCP) {
739 tcp = (struct tcphdr *)((char *)ip6 + hlen);
741 if ((tcp->th_flags & TH_RST) == 0) {
743 m0 = send_pkt(args->m, &(args->f_id),
744 ntohl(tcp->th_seq), ntohl(tcp->th_ack),
745 tcp->th_flags | TH_RST);
747 ip6_output(m0, NULL, NULL, 0, NULL, NULL,
751 } else if (code != ICMP6_UNREACH_RST) { /* Send an ICMPv6 unreach. */
754 * Unlike above, the mbufs need to line up with the ip6 hdr,
755 * as the contents are read. We need to m_adj() the
757 * The mbuf will however be thrown away so we can adjust it.
758 * Remember we did an m_pullup on it already so we
759 * can make some assumptions about contiguousness.
762 m_adj(m, args->L3offset);
764 icmp6_error(m, ICMP6_DST_UNREACH, code, 0);
773 /* counter for ipfw_log(NULL...) */
774 static VNET_DEFINE(u_int64_t, norule_counter);
775 #define V_norule_counter VNET(norule_counter)
777 #define SNPARGS(buf, len) buf + len, sizeof(buf) > len ? sizeof(buf) - len : 0
778 #define SNP(buf) buf, sizeof(buf)
781 * We enter here when we have a rule with O_LOG.
782 * XXX this function alone takes about 2Kbytes of code!
785 ipfw_log(struct ip_fw *f, u_int hlen, struct ip_fw_args *args,
786 struct mbuf *m, struct ifnet *oif, u_short offset, uint32_t tablearg,
789 struct ether_header *eh = args->eh;
791 int limit_reached = 0;
792 char action2[40], proto[128], fragment[32];
797 if (f == NULL) { /* bogus pkt */
798 if (V_verbose_limit != 0 && V_norule_counter >= V_verbose_limit)
801 if (V_norule_counter == V_verbose_limit)
802 limit_reached = V_verbose_limit;
804 } else { /* O_LOG is the first action, find the real one */
805 ipfw_insn *cmd = ACTION_PTR(f);
806 ipfw_insn_log *l = (ipfw_insn_log *)cmd;
808 if (l->max_log != 0 && l->log_left == 0)
811 if (l->log_left == 0)
812 limit_reached = l->max_log;
813 cmd += F_LEN(cmd); /* point to first action */
814 if (cmd->opcode == O_ALTQ) {
815 ipfw_insn_altq *altq = (ipfw_insn_altq *)cmd;
817 snprintf(SNPARGS(action2, 0), "Altq %d",
821 if (cmd->opcode == O_PROB)
824 if (cmd->opcode == O_TAG)
828 switch (cmd->opcode) {
834 if (cmd->arg1==ICMP_REJECT_RST)
836 else if (cmd->arg1==ICMP_UNREACH_HOST)
839 snprintf(SNPARGS(action2, 0), "Unreach %d",
844 if (cmd->arg1==ICMP6_UNREACH_RST)
847 snprintf(SNPARGS(action2, 0), "Unreach %d",
858 snprintf(SNPARGS(action2, 0), "Divert %d",
862 snprintf(SNPARGS(action2, 0), "Tee %d",
866 snprintf(SNPARGS(action2, 0), "SetFib %d",
870 snprintf(SNPARGS(action2, 0), "SkipTo %d",
874 snprintf(SNPARGS(action2, 0), "Pipe %d",
878 snprintf(SNPARGS(action2, 0), "Queue %d",
882 ipfw_insn_sa *sa = (ipfw_insn_sa *)cmd;
884 struct in_addr dummyaddr;
885 if (sa->sa.sin_addr.s_addr == INADDR_ANY)
886 dummyaddr.s_addr = htonl(tablearg);
888 dummyaddr.s_addr = sa->sa.sin_addr.s_addr;
890 len = snprintf(SNPARGS(action2, 0), "Forward to %s",
891 inet_ntoa(dummyaddr));
894 snprintf(SNPARGS(action2, len), ":%d",
899 snprintf(SNPARGS(action2, 0), "Netgraph %d",
903 snprintf(SNPARGS(action2, 0), "Ngtee %d",
918 if (hlen == 0) { /* non-ip */
919 snprintf(SNPARGS(proto, 0), "MAC");
924 char src[INET6_ADDRSTRLEN + 2], dst[INET6_ADDRSTRLEN + 2];
926 char src[INET_ADDRSTRLEN], dst[INET_ADDRSTRLEN];
928 struct icmphdr *icmp;
932 struct ip6_hdr *ip6 = NULL;
933 struct icmp6_hdr *icmp6;
938 if (IS_IP6_FLOW_ID(&(args->f_id))) {
939 char ip6buf[INET6_ADDRSTRLEN];
940 snprintf(src, sizeof(src), "[%s]",
941 ip6_sprintf(ip6buf, &args->f_id.src_ip6));
942 snprintf(dst, sizeof(dst), "[%s]",
943 ip6_sprintf(ip6buf, &args->f_id.dst_ip6));
945 ip6 = (struct ip6_hdr *)ip;
946 tcp = (struct tcphdr *)(((char *)ip) + hlen);
947 udp = (struct udphdr *)(((char *)ip) + hlen);
951 tcp = L3HDR(struct tcphdr, ip);
952 udp = L3HDR(struct udphdr, ip);
954 inet_ntoa_r(ip->ip_src, src);
955 inet_ntoa_r(ip->ip_dst, dst);
958 switch (args->f_id.proto) {
960 len = snprintf(SNPARGS(proto, 0), "TCP %s", src);
962 snprintf(SNPARGS(proto, len), ":%d %s:%d",
963 ntohs(tcp->th_sport),
965 ntohs(tcp->th_dport));
967 snprintf(SNPARGS(proto, len), " %s", dst);
971 len = snprintf(SNPARGS(proto, 0), "UDP %s", src);
973 snprintf(SNPARGS(proto, len), ":%d %s:%d",
974 ntohs(udp->uh_sport),
976 ntohs(udp->uh_dport));
978 snprintf(SNPARGS(proto, len), " %s", dst);
982 icmp = L3HDR(struct icmphdr, ip);
984 len = snprintf(SNPARGS(proto, 0),
986 icmp->icmp_type, icmp->icmp_code);
988 len = snprintf(SNPARGS(proto, 0), "ICMP ");
989 len += snprintf(SNPARGS(proto, len), "%s", src);
990 snprintf(SNPARGS(proto, len), " %s", dst);
994 icmp6 = (struct icmp6_hdr *)(((char *)ip) + hlen);
996 len = snprintf(SNPARGS(proto, 0),
998 icmp6->icmp6_type, icmp6->icmp6_code);
1000 len = snprintf(SNPARGS(proto, 0), "ICMPv6 ");
1001 len += snprintf(SNPARGS(proto, len), "%s", src);
1002 snprintf(SNPARGS(proto, len), " %s", dst);
1006 len = snprintf(SNPARGS(proto, 0), "P:%d %s",
1007 args->f_id.proto, src);
1008 snprintf(SNPARGS(proto, len), " %s", dst);
1013 if (IS_IP6_FLOW_ID(&(args->f_id))) {
1014 if (offset & (IP6F_OFF_MASK | IP6F_MORE_FRAG))
1015 snprintf(SNPARGS(fragment, 0),
1016 " (frag %08x:%d@%d%s)",
1017 args->f_id.frag_id6,
1018 ntohs(ip6->ip6_plen) - hlen,
1019 ntohs(offset & IP6F_OFF_MASK) << 3,
1020 (offset & IP6F_MORE_FRAG) ? "+" : "");
1025 if (1 || eh != NULL) { /* layer 2 packets are as on the wire */
1026 ip_off = ntohs(ip->ip_off);
1027 ip_len = ntohs(ip->ip_len);
1029 ip_off = ip->ip_off;
1030 ip_len = ip->ip_len;
1032 if (ip_off & (IP_MF | IP_OFFMASK))
1033 snprintf(SNPARGS(fragment, 0),
1034 " (frag %d:%d@%d%s)",
1035 ntohs(ip->ip_id), ip_len - (ip->ip_hl << 2),
1037 (ip_off & IP_MF) ? "+" : "");
1040 if (oif || m->m_pkthdr.rcvif)
1041 log(LOG_SECURITY | LOG_INFO,
1042 "ipfw: %d %s %s %s via %s%s\n",
1043 f ? f->rulenum : -1,
1044 action, proto, oif ? "out" : "in",
1045 oif ? oif->if_xname : m->m_pkthdr.rcvif->if_xname,
1048 log(LOG_SECURITY | LOG_INFO,
1049 "ipfw: %d %s %s [no if info]%s\n",
1050 f ? f->rulenum : -1,
1051 action, proto, fragment);
1053 log(LOG_SECURITY | LOG_NOTICE,
1054 "ipfw: limit %d reached on entry %d\n",
1055 limit_reached, f ? f->rulenum : -1);
1059 * IMPORTANT: the hash function for dynamic rules must be commutative
1060 * in source and destination (ip,port), because rules are bidirectional
1061 * and we want to find both in the same bucket.
1064 hash_packet(struct ipfw_flow_id *id)
1069 if (IS_IP6_FLOW_ID(id))
1070 i = hash_packet6(id);
1073 i = (id->dst_ip) ^ (id->src_ip) ^ (id->dst_port) ^ (id->src_port);
1074 i &= (V_curr_dyn_buckets - 1);
1078 static __inline void
1079 unlink_dyn_rule_print(struct ipfw_flow_id *id)
1083 char src[INET6_ADDRSTRLEN], dst[INET6_ADDRSTRLEN];
1085 char src[INET_ADDRSTRLEN], dst[INET_ADDRSTRLEN];
1089 if (IS_IP6_FLOW_ID(id)) {
1090 ip6_sprintf(src, &id->src_ip6);
1091 ip6_sprintf(dst, &id->dst_ip6);
1095 da.s_addr = htonl(id->src_ip);
1096 inet_ntoa_r(da, src);
1097 da.s_addr = htonl(id->dst_ip);
1098 inet_ntoa_r(da, dst);
1100 printf("ipfw: unlink entry %s %d -> %s %d, %d left\n",
1101 src, id->src_port, dst, id->dst_port, V_dyn_count - 1);
1105 * unlink a dynamic rule from a chain. prev is a pointer to
1106 * the previous one, q is a pointer to the rule to delete,
1107 * head is a pointer to the head of the queue.
1108 * Modifies q and potentially also head.
1110 #define UNLINK_DYN_RULE(prev, head, q) { \
1111 ipfw_dyn_rule *old_q = q; \
1113 /* remove a refcount to the parent */ \
1114 if (q->dyn_type == O_LIMIT) \
1115 q->parent->count--; \
1116 DEB(unlink_dyn_rule_print(&q->id);) \
1118 prev->next = q = q->next; \
1120 head = q = q->next; \
1122 uma_zfree(ipfw_dyn_rule_zone, old_q); }
1124 #define TIME_LEQ(a,b) ((int)((a)-(b)) <= 0)
1127 * Remove dynamic rules pointing to "rule", or all of them if rule == NULL.
1129 * If keep_me == NULL, rules are deleted even if not expired,
1130 * otherwise only expired rules are removed.
1132 * The value of the second parameter is also used to point to identify
1133 * a rule we absolutely do not want to remove (e.g. because we are
1134 * holding a reference to it -- this is the case with O_LIMIT_PARENT
1135 * rules). The pointer is only used for comparison, so any non-null
1139 remove_dyn_rule(struct ip_fw *rule, ipfw_dyn_rule *keep_me)
1141 static u_int32_t last_remove = 0;
1143 #define FORCE (keep_me == NULL)
1145 ipfw_dyn_rule *prev, *q;
1146 int i, pass = 0, max_pass = 0;
1148 IPFW_DYN_LOCK_ASSERT();
1150 if (V_ipfw_dyn_v == NULL || V_dyn_count == 0)
1152 /* do not expire more than once per second, it is useless */
1153 if (!FORCE && last_remove == time_uptime)
1155 last_remove = time_uptime;
1158 * because O_LIMIT refer to parent rules, during the first pass only
1159 * remove child and mark any pending LIMIT_PARENT, and remove
1160 * them in a second pass.
1163 for (i = 0 ; i < V_curr_dyn_buckets ; i++) {
1164 for (prev=NULL, q = V_ipfw_dyn_v[i] ; q ; ) {
1166 * Logic can become complex here, so we split tests.
1170 if (rule != NULL && rule != q->rule)
1171 goto next; /* not the one we are looking for */
1172 if (q->dyn_type == O_LIMIT_PARENT) {
1174 * handle parent in the second pass,
1175 * record we need one.
1180 if (FORCE && q->count != 0 ) {
1181 /* XXX should not happen! */
1182 printf("ipfw: OUCH! cannot remove rule,"
1183 " count %d\n", q->count);
1187 !TIME_LEQ( q->expire, time_uptime ))
1190 if (q->dyn_type != O_LIMIT_PARENT || !q->count) {
1191 UNLINK_DYN_RULE(prev, V_ipfw_dyn_v[i], q);
1199 if (pass++ < max_pass)
1205 * lookup a dynamic rule.
1207 static ipfw_dyn_rule *
1208 lookup_dyn_rule_locked(struct ipfw_flow_id *pkt, int *match_direction,
1212 * stateful ipfw extensions.
1213 * Lookup into dynamic session queue
1215 #define MATCH_REVERSE 0
1216 #define MATCH_FORWARD 1
1217 #define MATCH_NONE 2
1218 #define MATCH_UNKNOWN 3
1219 int i, dir = MATCH_NONE;
1220 ipfw_dyn_rule *prev, *q=NULL;
1222 IPFW_DYN_LOCK_ASSERT();
1224 if (V_ipfw_dyn_v == NULL)
1225 goto done; /* not found */
1226 i = hash_packet( pkt );
1227 for (prev=NULL, q = V_ipfw_dyn_v[i] ; q != NULL ; ) {
1228 if (q->dyn_type == O_LIMIT_PARENT && q->count)
1230 if (TIME_LEQ( q->expire, time_uptime)) { /* expire entry */
1231 UNLINK_DYN_RULE(prev, V_ipfw_dyn_v[i], q);
1234 if (pkt->proto == q->id.proto &&
1235 q->dyn_type != O_LIMIT_PARENT) {
1236 if (IS_IP6_FLOW_ID(pkt)) {
1237 if (IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
1238 &(q->id.src_ip6)) &&
1239 IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
1240 &(q->id.dst_ip6)) &&
1241 pkt->src_port == q->id.src_port &&
1242 pkt->dst_port == q->id.dst_port ) {
1243 dir = MATCH_FORWARD;
1246 if (IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
1247 &(q->id.dst_ip6)) &&
1248 IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
1249 &(q->id.src_ip6)) &&
1250 pkt->src_port == q->id.dst_port &&
1251 pkt->dst_port == q->id.src_port ) {
1252 dir = MATCH_REVERSE;
1256 if (pkt->src_ip == q->id.src_ip &&
1257 pkt->dst_ip == q->id.dst_ip &&
1258 pkt->src_port == q->id.src_port &&
1259 pkt->dst_port == q->id.dst_port ) {
1260 dir = MATCH_FORWARD;
1263 if (pkt->src_ip == q->id.dst_ip &&
1264 pkt->dst_ip == q->id.src_ip &&
1265 pkt->src_port == q->id.dst_port &&
1266 pkt->dst_port == q->id.src_port ) {
1267 dir = MATCH_REVERSE;
1277 goto done; /* q = NULL, not found */
1279 if ( prev != NULL) { /* found and not in front */
1280 prev->next = q->next;
1281 q->next = V_ipfw_dyn_v[i];
1282 V_ipfw_dyn_v[i] = q;
1284 if (pkt->proto == IPPROTO_TCP) { /* update state according to flags */
1285 u_char flags = pkt->flags & (TH_FIN|TH_SYN|TH_RST);
1287 #define BOTH_SYN (TH_SYN | (TH_SYN << 8))
1288 #define BOTH_FIN (TH_FIN | (TH_FIN << 8))
1289 q->state |= (dir == MATCH_FORWARD ) ? flags : (flags << 8);
1291 case TH_SYN: /* opening */
1292 q->expire = time_uptime + V_dyn_syn_lifetime;
1295 case BOTH_SYN: /* move to established */
1296 case BOTH_SYN | TH_FIN : /* one side tries to close */
1297 case BOTH_SYN | (TH_FIN << 8) :
1299 #define _SEQ_GE(a,b) ((int)(a) - (int)(b) >= 0)
1300 u_int32_t ack = ntohl(tcp->th_ack);
1301 if (dir == MATCH_FORWARD) {
1302 if (q->ack_fwd == 0 || _SEQ_GE(ack, q->ack_fwd))
1304 else { /* ignore out-of-sequence */
1308 if (q->ack_rev == 0 || _SEQ_GE(ack, q->ack_rev))
1310 else { /* ignore out-of-sequence */
1315 q->expire = time_uptime + V_dyn_ack_lifetime;
1318 case BOTH_SYN | BOTH_FIN: /* both sides closed */
1319 if (V_dyn_fin_lifetime >= V_dyn_keepalive_period)
1320 V_dyn_fin_lifetime = V_dyn_keepalive_period - 1;
1321 q->expire = time_uptime + V_dyn_fin_lifetime;
1327 * reset or some invalid combination, but can also
1328 * occur if we use keep-state the wrong way.
1330 if ( (q->state & ((TH_RST << 8)|TH_RST)) == 0)
1331 printf("invalid state: 0x%x\n", q->state);
1333 if (V_dyn_rst_lifetime >= V_dyn_keepalive_period)
1334 V_dyn_rst_lifetime = V_dyn_keepalive_period - 1;
1335 q->expire = time_uptime + V_dyn_rst_lifetime;
1338 } else if (pkt->proto == IPPROTO_UDP) {
1339 q->expire = time_uptime + V_dyn_udp_lifetime;
1341 /* other protocols */
1342 q->expire = time_uptime + V_dyn_short_lifetime;
1345 if (match_direction)
1346 *match_direction = dir;
1350 static ipfw_dyn_rule *
1351 lookup_dyn_rule(struct ipfw_flow_id *pkt, int *match_direction,
1357 q = lookup_dyn_rule_locked(pkt, match_direction, tcp);
1360 /* NB: return table locked when q is not NULL */
1365 realloc_dynamic_table(void)
1367 IPFW_DYN_LOCK_ASSERT();
1370 * Try reallocation, make sure we have a power of 2 and do
1371 * not allow more than 64k entries. In case of overflow,
1375 if (V_dyn_buckets > 65536)
1376 V_dyn_buckets = 1024;
1377 if ((V_dyn_buckets & (V_dyn_buckets-1)) != 0) { /* not a power of 2 */
1378 V_dyn_buckets = V_curr_dyn_buckets; /* reset */
1381 V_curr_dyn_buckets = V_dyn_buckets;
1382 if (V_ipfw_dyn_v != NULL)
1383 free(V_ipfw_dyn_v, M_IPFW);
1385 V_ipfw_dyn_v = malloc(V_curr_dyn_buckets * sizeof(ipfw_dyn_rule *),
1386 M_IPFW, M_NOWAIT | M_ZERO);
1387 if (V_ipfw_dyn_v != NULL || V_curr_dyn_buckets <= 2)
1389 V_curr_dyn_buckets /= 2;
1394 * Install state of type 'type' for a dynamic session.
1395 * The hash table contains two type of rules:
1396 * - regular rules (O_KEEP_STATE)
1397 * - rules for sessions with limited number of sess per user
1398 * (O_LIMIT). When they are created, the parent is
1399 * increased by 1, and decreased on delete. In this case,
1400 * the third parameter is the parent rule and not the chain.
1401 * - "parent" rules for the above (O_LIMIT_PARENT).
1403 static ipfw_dyn_rule *
1404 add_dyn_rule(struct ipfw_flow_id *id, u_int8_t dyn_type, struct ip_fw *rule)
1409 IPFW_DYN_LOCK_ASSERT();
1411 if (V_ipfw_dyn_v == NULL ||
1412 (V_dyn_count == 0 && V_dyn_buckets != V_curr_dyn_buckets)) {
1413 realloc_dynamic_table();
1414 if (V_ipfw_dyn_v == NULL)
1415 return NULL; /* failed ! */
1417 i = hash_packet(id);
1419 r = uma_zalloc(ipfw_dyn_rule_zone, M_NOWAIT | M_ZERO);
1421 printf ("ipfw: sorry cannot allocate state\n");
1425 /* increase refcount on parent, and set pointer */
1426 if (dyn_type == O_LIMIT) {
1427 ipfw_dyn_rule *parent = (ipfw_dyn_rule *)rule;
1428 if ( parent->dyn_type != O_LIMIT_PARENT)
1429 panic("invalid parent");
1432 rule = parent->rule;
1436 r->expire = time_uptime + V_dyn_syn_lifetime;
1438 r->dyn_type = dyn_type;
1439 r->pcnt = r->bcnt = 0;
1443 r->next = V_ipfw_dyn_v[i];
1444 V_ipfw_dyn_v[i] = r;
1449 char src[INET6_ADDRSTRLEN];
1450 char dst[INET6_ADDRSTRLEN];
1452 char src[INET_ADDRSTRLEN];
1453 char dst[INET_ADDRSTRLEN];
1457 if (IS_IP6_FLOW_ID(&(r->id))) {
1458 ip6_sprintf(src, &r->id.src_ip6);
1459 ip6_sprintf(dst, &r->id.dst_ip6);
1463 da.s_addr = htonl(r->id.src_ip);
1464 inet_ntoa_r(da, src);
1465 da.s_addr = htonl(r->id.dst_ip);
1466 inet_ntoa_r(da, dst);
1468 printf("ipfw: add dyn entry ty %d %s %d -> %s %d, total %d\n",
1469 dyn_type, src, r->id.src_port, dst, r->id.dst_port,
1476 * lookup dynamic parent rule using pkt and rule as search keys.
1477 * If the lookup fails, then install one.
1479 static ipfw_dyn_rule *
1480 lookup_dyn_parent(struct ipfw_flow_id *pkt, struct ip_fw *rule)
1485 IPFW_DYN_LOCK_ASSERT();
1488 int is_v6 = IS_IP6_FLOW_ID(pkt);
1489 i = hash_packet( pkt );
1490 for (q = V_ipfw_dyn_v[i] ; q != NULL ; q=q->next)
1491 if (q->dyn_type == O_LIMIT_PARENT &&
1493 pkt->proto == q->id.proto &&
1494 pkt->src_port == q->id.src_port &&
1495 pkt->dst_port == q->id.dst_port &&
1498 IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
1499 &(q->id.src_ip6)) &&
1500 IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
1501 &(q->id.dst_ip6))) ||
1503 pkt->src_ip == q->id.src_ip &&
1504 pkt->dst_ip == q->id.dst_ip)
1507 q->expire = time_uptime + V_dyn_short_lifetime;
1508 DEB(printf("ipfw: lookup_dyn_parent found 0x%p\n",q);)
1512 return add_dyn_rule(pkt, O_LIMIT_PARENT, rule);
1516 * Install dynamic state for rule type cmd->o.opcode
1518 * Returns 1 (failure) if state is not installed because of errors or because
1519 * session limitations are enforced.
1522 install_state(struct ip_fw *rule, ipfw_insn_limit *cmd,
1523 struct ip_fw_args *args, uint32_t tablearg)
1525 static int last_log;
1529 char src[INET6_ADDRSTRLEN + 2], dst[INET6_ADDRSTRLEN + 2];
1531 char src[INET_ADDRSTRLEN], dst[INET_ADDRSTRLEN];
1541 if (IS_IP6_FLOW_ID(&(args->f_id))) {
1542 ip6_sprintf(src, &args->f_id.src_ip6);
1543 ip6_sprintf(dst, &args->f_id.dst_ip6);
1547 da.s_addr = htonl(args->f_id.src_ip);
1548 inet_ntoa_r(da, src);
1549 da.s_addr = htonl(args->f_id.dst_ip);
1550 inet_ntoa_r(da, dst);
1552 printf("ipfw: %s: type %d %s %u -> %s %u\n",
1553 __func__, cmd->o.opcode, src, args->f_id.src_port,
1554 dst, args->f_id.dst_port);
1559 q = lookup_dyn_rule_locked(&args->f_id, NULL, NULL);
1561 if (q != NULL) { /* should never occur */
1562 if (last_log != time_uptime) {
1563 last_log = time_uptime;
1564 printf("ipfw: %s: entry already present, done\n",
1571 if (V_dyn_count >= V_dyn_max)
1572 /* Run out of slots, try to remove any expired rule. */
1573 remove_dyn_rule(NULL, (ipfw_dyn_rule *)1);
1575 if (V_dyn_count >= V_dyn_max) {
1576 if (last_log != time_uptime) {
1577 last_log = time_uptime;
1578 printf("ipfw: %s: Too many dynamic rules\n", __func__);
1581 return (1); /* cannot install, notify caller */
1584 switch (cmd->o.opcode) {
1585 case O_KEEP_STATE: /* bidir rule */
1586 add_dyn_rule(&args->f_id, O_KEEP_STATE, rule);
1589 case O_LIMIT: { /* limit number of sessions */
1590 struct ipfw_flow_id id;
1591 ipfw_dyn_rule *parent;
1592 uint32_t conn_limit;
1593 uint16_t limit_mask = cmd->limit_mask;
1595 conn_limit = (cmd->conn_limit == IP_FW_TABLEARG) ?
1596 tablearg : cmd->conn_limit;
1599 if (cmd->conn_limit == IP_FW_TABLEARG)
1600 printf("ipfw: %s: O_LIMIT rule, conn_limit: %u "
1601 "(tablearg)\n", __func__, conn_limit);
1603 printf("ipfw: %s: O_LIMIT rule, conn_limit: %u\n",
1604 __func__, conn_limit);
1607 id.dst_ip = id.src_ip = id.dst_port = id.src_port = 0;
1608 id.proto = args->f_id.proto;
1609 id.addr_type = args->f_id.addr_type;
1610 id.fib = M_GETFIB(args->m);
1612 if (IS_IP6_FLOW_ID (&(args->f_id))) {
1613 if (limit_mask & DYN_SRC_ADDR)
1614 id.src_ip6 = args->f_id.src_ip6;
1615 if (limit_mask & DYN_DST_ADDR)
1616 id.dst_ip6 = args->f_id.dst_ip6;
1618 if (limit_mask & DYN_SRC_ADDR)
1619 id.src_ip = args->f_id.src_ip;
1620 if (limit_mask & DYN_DST_ADDR)
1621 id.dst_ip = args->f_id.dst_ip;
1623 if (limit_mask & DYN_SRC_PORT)
1624 id.src_port = args->f_id.src_port;
1625 if (limit_mask & DYN_DST_PORT)
1626 id.dst_port = args->f_id.dst_port;
1627 if ((parent = lookup_dyn_parent(&id, rule)) == NULL) {
1628 printf("ipfw: %s: add parent failed\n", __func__);
1633 if (parent->count >= conn_limit) {
1634 /* See if we can remove some expired rule. */
1635 remove_dyn_rule(rule, parent);
1636 if (parent->count >= conn_limit) {
1637 if (V_fw_verbose && last_log != time_uptime) {
1638 last_log = time_uptime;
1641 * XXX IPv6 flows are not
1644 if (IS_IP6_FLOW_ID(&(args->f_id))) {
1645 char ip6buf[INET6_ADDRSTRLEN];
1646 snprintf(src, sizeof(src),
1647 "[%s]", ip6_sprintf(ip6buf,
1648 &args->f_id.src_ip6));
1649 snprintf(dst, sizeof(dst),
1650 "[%s]", ip6_sprintf(ip6buf,
1651 &args->f_id.dst_ip6));
1656 htonl(args->f_id.src_ip);
1657 inet_ntoa_r(da, src);
1659 htonl(args->f_id.dst_ip);
1660 inet_ntoa_r(da, dst);
1662 log(LOG_SECURITY | LOG_DEBUG,
1663 "ipfw: %d %s %s:%u -> %s:%u, %s\n",
1664 parent->rule->rulenum,
1666 src, (args->f_id.src_port),
1667 dst, (args->f_id.dst_port),
1668 "too many entries");
1674 add_dyn_rule(&args->f_id, O_LIMIT, (struct ip_fw *)parent);
1678 printf("ipfw: %s: unknown dynamic rule type %u\n",
1679 __func__, cmd->o.opcode);
1684 /* XXX just set lifetime */
1685 lookup_dyn_rule_locked(&args->f_id, NULL, NULL);
1692 * Generate a TCP packet, containing either a RST or a keepalive.
1693 * When flags & TH_RST, we are sending a RST packet, because of a
1694 * "reset" action matched the packet.
1695 * Otherwise we are sending a keepalive, and flags & TH_
1696 * The 'replyto' mbuf is the mbuf being replied to, if any, and is required
1697 * so that MAC can label the reply appropriately.
1699 static struct mbuf *
1700 send_pkt(struct mbuf *replyto, struct ipfw_flow_id *id, u_int32_t seq,
1701 u_int32_t ack, int flags)
1703 #if defined( __linux__ ) || defined( _WIN32 )
1708 struct ip *h = NULL; /* stupid compiler */
1710 struct ip6_hdr *h6 = NULL;
1712 struct tcphdr *th = NULL;
1714 MGETHDR(m, M_DONTWAIT, MT_DATA);
1718 M_SETFIB(m, id->fib);
1720 if (replyto != NULL)
1721 mac_netinet_firewall_reply(replyto, m);
1723 mac_netinet_firewall_send(m);
1725 (void)replyto; /* don't warn about unused arg */
1728 switch (id->addr_type) {
1730 len = sizeof(struct ip) + sizeof(struct tcphdr);
1734 len = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
1738 /* XXX: log me?!? */
1742 dir = ((flags & (TH_SYN | TH_RST)) == TH_SYN);
1744 m->m_data += max_linkhdr;
1745 m->m_flags |= M_SKIP_FIREWALL;
1746 m->m_pkthdr.len = m->m_len = len;
1747 m->m_pkthdr.rcvif = NULL;
1748 bzero(m->m_data, len);
1750 switch (id->addr_type) {
1752 h = mtod(m, struct ip *);
1754 /* prepare for checksum */
1755 h->ip_p = IPPROTO_TCP;
1756 h->ip_len = htons(sizeof(struct tcphdr));
1758 h->ip_src.s_addr = htonl(id->src_ip);
1759 h->ip_dst.s_addr = htonl(id->dst_ip);
1761 h->ip_src.s_addr = htonl(id->dst_ip);
1762 h->ip_dst.s_addr = htonl(id->src_ip);
1765 th = (struct tcphdr *)(h + 1);
1769 h6 = mtod(m, struct ip6_hdr *);
1771 /* prepare for checksum */
1772 h6->ip6_nxt = IPPROTO_TCP;
1773 h6->ip6_plen = htons(sizeof(struct tcphdr));
1775 h6->ip6_src = id->src_ip6;
1776 h6->ip6_dst = id->dst_ip6;
1778 h6->ip6_src = id->dst_ip6;
1779 h6->ip6_dst = id->src_ip6;
1782 th = (struct tcphdr *)(h6 + 1);
1788 th->th_sport = htons(id->src_port);
1789 th->th_dport = htons(id->dst_port);
1791 th->th_sport = htons(id->dst_port);
1792 th->th_dport = htons(id->src_port);
1794 th->th_off = sizeof(struct tcphdr) >> 2;
1796 if (flags & TH_RST) {
1797 if (flags & TH_ACK) {
1798 th->th_seq = htonl(ack);
1799 // XXX th->th_ack = htonl(0);
1800 th->th_flags = TH_RST;
1804 // XXX th->th_seq = htonl(0);
1805 th->th_ack = htonl(seq);
1806 th->th_flags = TH_RST | TH_ACK;
1810 * Keepalive - use caller provided sequence numbers
1812 th->th_seq = htonl(seq);
1813 th->th_ack = htonl(ack);
1814 th->th_flags = TH_ACK;
1817 switch (id->addr_type) {
1819 th->th_sum = in_cksum(m, len);
1821 /* finish the ip header */
1823 h->ip_hl = sizeof(*h) >> 2;
1824 h->ip_tos = IPTOS_LOWDELAY;
1827 h->ip_ttl = V_ip_defttl;
1832 th->th_sum = in6_cksum(m, IPPROTO_TCP, sizeof(*h6),
1833 sizeof(struct tcphdr));
1835 /* finish the ip6 header */
1836 h6->ip6_vfc |= IPV6_VERSION;
1837 h6->ip6_hlim = IPV6_DEFHLIM;
1843 #endif /* !__linux__ */
1847 * sends a reject message, consuming the mbuf passed as an argument.
1850 send_reject(struct ip_fw_args *args, int code, int ip_len, struct ip *ip)
1854 /* XXX When ip is not guaranteed to be at mtod() we will
1855 * need to account for this */
1856 * The mbuf will however be thrown away so we can adjust it.
1857 * Remember we did an m_pullup on it already so we
1858 * can make some assumptions about contiguousness.
1861 m_adj(m, args->L3offset);
1863 if (code != ICMP_REJECT_RST) { /* Send an ICMP unreach */
1864 /* We need the IP header in host order for icmp_error(). */
1865 #if !defined( __linux__ ) && !defined( _WIN32 )
1866 if (args->eh != NULL) {
1867 ip->ip_len = ntohs(ip->ip_len);
1868 ip->ip_off = ntohs(ip->ip_off);
1871 icmp_error(args->m, ICMP_UNREACH, code, 0L, 0);
1872 } else if (args->f_id.proto == IPPROTO_TCP) {
1873 struct tcphdr *const tcp =
1874 L3HDR(struct tcphdr, mtod(args->m, struct ip *));
1875 if ( (tcp->th_flags & TH_RST) == 0) {
1877 m = send_pkt(args->m, &(args->f_id),
1878 ntohl(tcp->th_seq), ntohl(tcp->th_ack),
1879 tcp->th_flags | TH_RST);
1881 ip_output(m, NULL, NULL, 0, NULL, NULL);
1890 set_skipto_table(struct ip_fw_chain *ch)
1893 struct ip_fw *f, **t, **oldt;
1895 for (sh = 15; sh > 0; sh--)
1896 if (skipto_entries > 1<<sh)
1899 skipto_entries = 1<< (16 - sh) ;
1900 /* XXX unsafe and too long */
1901 t = malloc(skipto_entries * sizeof(*t), M_IPFW_TBL, M_WAITOK | M_ZERO);
1905 /* Store pointers in the table. In the loop i is the next
1906 * free slot, n is the slot where the current rule goes.
1908 for (i = 0, f = ch->rules; f; f = f->next) {
1909 n = f->rulenum >> sh ;
1913 V_layer3_chain.skipto_shift = sh;
1914 V_layer3_chain.skipto_size = skipto_entries;
1915 oldt = V_layer3_chain.skipto_ptrs;
1916 V_layer3_chain.skipto_ptrs = t;
1921 /* now can free oldt */
1922 free(oldt, M_IPFW_TBL);
1927 * Map a rule number to a rule pointer, using the skipto table.
1928 * First lookup the slot, then follow the chain until we find a
1929 * non-null entry with rulenum >= num. Return default_rule on error.
1931 static struct ip_fw *
1932 rule2ptr(struct ip_fw_chain *ch, int num)
1934 struct ip_fw *r = NULL;
1935 int ix = (num & 0xffff) >> ch->skipto_shift;
1937 while (ix < ch->skipto_size && (r = ch->skipto_ptrs[ix]) == NULL)
1939 while (r && num < r->rulenum)
1941 return (r ? r : ch->default_rule);
1946 * Given an ip_fw *, lookup_next_rule will return a pointer
1947 * to the next rule, which can be either the jump
1948 * target (for skipto instructions) or the next one in the list (in
1949 * all other cases including a missing jump target).
1950 * The result is also written in the "next_rule" field of the rule.
1951 * Backward jumps are not allowed, so start looking from the next
1954 * This never returns NULL -- in case we do not have an exact match,
1955 * the next rule is returned. When the ruleset is changed,
1956 * pointers are flushed so we are always correct.
1959 static struct ip_fw *
1960 lookup_next_rule(struct ip_fw_chain *ch, struct ip_fw *me, uint32_t tablearg)
1962 struct ip_fw *rule = NULL;
1965 /* look for action, in case it is a skipto */
1966 cmd = ACTION_PTR(me);
1967 if (cmd->opcode == O_LOG)
1969 if (cmd->opcode == O_ALTQ)
1971 if (cmd->opcode == O_TAG)
1973 if (cmd->opcode != O_SKIPTO ) {
1976 tablearg = tablearg ? tablearg : cmd->arg1;
1977 for (rule = me->next; rule ; rule = rule->next) {
1978 if (rule->rulenum >= tablearg) {
1983 // rule = rule2ptr(ch, tablearg ? tablearg : cmd->arg1);
1985 me->next_rule = rule; /* XXX perhaps unnecessary ? */
1990 add_table_entry(struct ip_fw_chain *ch, uint16_t tbl, in_addr_t addr,
1991 uint8_t mlen, uint32_t value)
1993 struct radix_node_head *rnh;
1994 struct table_entry *ent;
1995 struct radix_node *rn;
1997 #ifdef IPFW_HASHTABLES
1998 if (tbl >= 2*IPFW_TABLES_MAX)
2000 return EINVAL; // XXX to be completed
2002 if (tbl >= IPFW_TABLES_MAX)
2004 rnh = ch->tables[tbl];
2005 ent = malloc(sizeof(*ent), M_IPFW_TBL, M_NOWAIT | M_ZERO);
2010 /* there is no sin_len on linux, and the code assumes the first
2011 * byte in the sockaddr to contain the length in bits.
2012 * So we just dump the number right there
2014 *((uint8_t *)&(ent->addr)) = 8;
2015 *((uint8_t *)&(ent->mask)) = 8;
2017 ent->addr.sin_len = ent->mask.sin_len = 8;
2019 ent->mask.sin_addr.s_addr = htonl(mlen ? ~((1 << (32 - mlen)) - 1) : 0);
2020 ent->addr.sin_addr.s_addr = addr & ent->mask.sin_addr.s_addr;
2022 rn = rnh->rnh_addaddr(&ent->addr, &ent->mask, rnh, (void *)ent);
2025 free(ent, M_IPFW_TBL);
2033 del_table_entry(struct ip_fw_chain *ch, uint16_t tbl, in_addr_t addr,
2036 struct radix_node_head *rnh;
2037 struct table_entry *ent;
2038 struct sockaddr_in sa, mask;
2040 #ifdef IPFW_HASHTABLES
2041 if (tbl >= 2*IPFW_TABLES_MAX)
2043 return EINVAL; // XXX to be completed
2045 if (tbl >= IPFW_TABLES_MAX)
2047 rnh = ch->tables[tbl];
2049 /* there is no sin_len on linux, see above */
2050 *((uint8_t *)&sa) = 8;
2051 *((uint8_t *)&mask) = 8;
2053 sa.sin_len = mask.sin_len = 8;
2055 mask.sin_addr.s_addr = htonl(mlen ? ~((1 << (32 - mlen)) - 1) : 0);
2056 sa.sin_addr.s_addr = addr & mask.sin_addr.s_addr;
2058 ent = (struct table_entry *)rnh->rnh_deladdr(&sa, &mask, rnh);
2064 free(ent, M_IPFW_TBL);
2069 flush_table_entry(struct radix_node *rn, void *arg)
2071 struct radix_node_head * const rnh = arg;
2072 struct table_entry *ent;
2074 ent = (struct table_entry *)
2075 rnh->rnh_deladdr(rn->rn_key, rn->rn_mask, rnh);
2077 free(ent, M_IPFW_TBL);
2082 flush_table(struct ip_fw_chain *ch, uint16_t tbl)
2084 struct radix_node_head *rnh;
2086 IPFW_WLOCK_ASSERT(ch);
2088 #ifdef IPFW_HASHTABLES
2089 if (tbl >= 2*IPFW_TABLES_MAX)
2091 return EINVAL; // XXX to be completed
2093 if (tbl >= IPFW_TABLES_MAX)
2095 rnh = ch->tables[tbl];
2096 KASSERT(rnh != NULL, ("NULL IPFW table"));
2097 rnh->rnh_walktree(rnh, flush_table_entry, rnh);
2102 flush_tables(struct ip_fw_chain *ch)
2106 IPFW_WLOCK_ASSERT(ch);
2108 for (tbl = 0; tbl < IPFW_TABLES_MAX; tbl++)
2109 flush_table(ch, tbl);
2110 #ifdef IPFW_HASHTABLES
2111 for (tbl = 0; tbl < IPFW_TABLES_MAX; tbl++)
2112 ch->hashtab[tbl] = ipfw_ht_destroy(ch->hashtab[tbl]);
2117 init_tables(struct ip_fw_chain *ch)
2122 for (i = 0; i < IPFW_TABLES_MAX; i++) {
2123 if (!rn_inithead((void **)&ch->tables[i], 32)) {
2124 for (j = 0; j < i; j++) {
2125 (void) flush_table(ch, j);
2130 #ifdef IPFW_HASHTABLES
2131 for (i = 0; i < IPFW_TABLES_MAX; i++)
2132 ch->hashtab[i] = ipfw_ht_destroy(ch->hashtab[i]);
2138 lookup_table(struct ip_fw_chain *ch, uint16_t tbl, in_addr_t addr,
2141 struct radix_node_head *rnh;
2142 struct table_entry *ent;
2143 struct sockaddr_in sa;
2145 if (tbl >= IPFW_TABLES_MAX)
2147 rnh = ch->tables[tbl];
2149 /* there is no sin_len on linux, see above */
2150 *((uint8_t *)&sa) = 8;
2154 sa.sin_addr.s_addr = addr;
2155 ent = (struct table_entry *)(rnh->rnh_lookup(&sa, NULL, rnh));
2164 count_table_entry(struct radix_node *rn, void *arg)
2166 u_int32_t * const cnt = arg;
2173 count_table(struct ip_fw_chain *ch, uint32_t tbl, uint32_t *cnt)
2175 struct radix_node_head *rnh;
2177 if (tbl >= IPFW_TABLES_MAX)
2179 rnh = ch->tables[tbl];
2181 rnh->rnh_walktree(rnh, count_table_entry, cnt);
2186 dump_table_entry(struct radix_node *rn, void *arg)
2188 struct table_entry * const n = (struct table_entry *)rn;
2189 ipfw_table * const tbl = arg;
2190 ipfw_table_entry *ent;
2192 if (tbl->cnt == tbl->size)
2194 ent = &tbl->ent[tbl->cnt];
2195 ent->tbl = tbl->tbl;
2196 if (in_nullhost(n->mask.sin_addr))
2199 ent->masklen = 33 - ffs(ntohl(n->mask.sin_addr.s_addr));
2200 ent->addr = n->addr.sin_addr.s_addr;
2201 ent->value = n->value;
2207 dump_table(struct ip_fw_chain *ch, ipfw_table *tbl)
2209 struct radix_node_head *rnh;
2211 if (tbl->tbl >= IPFW_TABLES_MAX)
2213 rnh = ch->tables[tbl->tbl];
2215 rnh->rnh_walktree(rnh, dump_table_entry, tbl);
2220 check_uidgid(ipfw_insn_u32 *insn, int proto, struct ifnet *oif,
2221 struct in_addr dst_ip, u_int16_t dst_port, struct in_addr src_ip,
2222 u_int16_t src_port, struct ucred **uc, int *ugid_lookup,
2227 struct sk_buff *skb = ((struct mbuf *)inp)->m_skb;
2228 struct bsd_ucred *u = (struct bsd_ucred *)uc;
2230 if (*ugid_lookup == 0) { /* actively lookup and copy in cache */
2231 /* returns null if any element of the chain up to file is null.
2232 * if sk != NULL then we also have a reference
2234 *ugid_lookup = linux_lookup(proto,
2235 src_ip.s_addr, htons(src_port),
2236 dst_ip.s_addr, htons(dst_port),
2237 skb, oif ? 1 : 0, u);
2240 if (*ugid_lookup < 0)
2243 if (insn->o.opcode == O_UID)
2244 match = (u->uid == (uid_t)insn->d[0]);
2245 else if (insn->o.opcode == O_JAIL)
2246 match = (u->xid == (uid_t)insn->d[0]);
2247 else if (insn->o.opcode == O_GID)
2248 match = (u->gid == (uid_t)insn->d[0]);
2254 struct inpcbinfo *pi;
2260 * Check to see if the UDP or TCP stack supplied us with
2261 * the PCB. If so, rather then holding a lock and looking
2262 * up the PCB, we can use the one that was supplied.
2264 if (inp && *ugid_lookupp == 0) {
2265 INP_LOCK_ASSERT(inp);
2266 if (inp->inp_socket != NULL) {
2267 *uc = crhold(inp->inp_cred);
2273 * If we have already been here and the packet has no
2274 * PCB entry associated with it, then we can safely
2275 * assume that this is a no match.
2277 if (*ugid_lookupp == -1)
2279 if (proto == IPPROTO_TCP) {
2282 } else if (proto == IPPROTO_UDP) {
2283 wildcard = INPLOOKUP_WILDCARD;
2288 if (*ugid_lookupp == 0) {
2291 in_pcblookup_hash(pi,
2292 dst_ip, htons(dst_port),
2293 src_ip, htons(src_port),
2295 in_pcblookup_hash(pi,
2296 src_ip, htons(src_port),
2297 dst_ip, htons(dst_port),
2300 *uc = crhold(pcb->inp_cred);
2303 INP_INFO_RUNLOCK(pi);
2304 if (*ugid_lookupp == 0) {
2306 * If the lookup did not yield any results, there
2307 * is no sense in coming back and trying again. So
2308 * we can set lookup to -1 and ensure that we wont
2309 * bother the pcb system again.
2315 if (insn->o.opcode == O_UID)
2316 match = ((*uc)->cr_uid == (uid_t)insn->d[0]);
2317 else if (insn->o.opcode == O_GID)
2318 match = groupmember((gid_t)insn->d[0], *uc);
2319 else if (insn->o.opcode == O_JAIL)
2320 match = ((*uc)->cr_prison->pr_id == (int)insn->d[0]);
2326 * The main check routine for the firewall.
2328 * All arguments are in args so we can modify them and return them
2329 * back to the caller.
2333 * args->m (in/out) The packet; we set to NULL when/if we nuke it.
2334 * Starts with the IP header.
2335 * args->eh (in) Mac header if present, or NULL for layer3 packet.
2336 * args->L3offset Number of bytes bypassed if we came from L2.
2337 * e.g. often sizeof(eh) ** NOTYET **
2338 * args->oif Outgoing interface, or NULL if packet is incoming.
2339 * The incoming interface is in the mbuf. (in)
2340 * args->divert_rule (in/out)
2341 * Skip up to the first rule past this rule number;
2342 * upon return, non-zero port number for divert or tee.
2344 * args->rule Pointer to the last matching rule (in/out)
2345 * args->next_hop Socket we are forwarding to (out).
2346 * args->f_id Addresses grabbed from the packet (out)
2347 * args->cookie a cookie depending on rule action
2351 * IP_FW_PASS the packet must be accepted
2352 * IP_FW_DENY the packet must be dropped
2353 * IP_FW_DIVERT divert packet, port in m_tag
2354 * IP_FW_TEE tee packet, port in m_tag
2355 * IP_FW_DUMMYNET to dummynet, pipe in args->cookie
2356 * IP_FW_NETGRAPH into netgraph, cookie args->cookie
2360 ipfw_chk(struct ip_fw_args *args)
2364 * Local variables holding state during the processing of a packet:
2366 * IMPORTANT NOTE: to speed up the processing of rules, there
2367 * are some assumption on the values of the variables, which
2368 * are documented here. Should you change them, please check
2369 * the implementation of the various instructions to make sure
2370 * that they still work.
2372 * args->eh The MAC header. It is non-null for a layer2
2373 * packet, it is NULL for a layer-3 packet.
2375 * args->L3offset Offset in the packet to the L3 (IP or equiv.) header.
2377 * m | args->m Pointer to the mbuf, as received from the caller.
2378 * It may change if ipfw_chk() does an m_pullup, or if it
2379 * consumes the packet because it calls send_reject().
2380 * XXX This has to change, so that ipfw_chk() never modifies
2381 * or consumes the buffer.
2382 * ip is the beginning of the ip(4 or 6) header.
2383 * Calculated by adding the L3offset to the start of data.
2384 * (Until we start using L3offset, the packet is
2385 * supposed to start with the ip header).
2387 struct mbuf *m = args->m;
2388 struct ip *ip = mtod(m, struct ip *);
2391 * For rules which contain uid/gid or jail constraints, cache
2392 * a copy of the users credentials after the pcb lookup has been
2393 * executed. This will speed up the processing of rules with
2394 * these types of constraints, as well as decrease contention
2395 * on pcb related locks.
2397 struct bsd_ucred ucred_cache;
2398 int ucred_lookup = 0;
2401 * divinput_flags If non-zero, set to the IP_FW_DIVERT_*_FLAG
2402 * associated with a packet input on a divert socket. This
2403 * will allow to distinguish traffic and its direction when
2404 * it originates from a divert socket.
2406 u_int divinput_flags = 0;
2409 * oif | args->oif If NULL, ipfw_chk has been called on the
2410 * inbound path (ether_input, ip_input).
2411 * If non-NULL, ipfw_chk has been called on the outbound path
2412 * (ether_output, ip_output).
2414 struct ifnet *oif = args->oif;
2416 struct ip_fw *f = NULL; /* matching rule */
2420 * hlen The length of the IP header.
2422 u_int hlen = 0; /* hlen >0 means we have an IP pkt */
2425 * offset The offset of a fragment. offset != 0 means that
2426 * we have a fragment at this offset of an IPv4 packet.
2427 * offset == 0 means that (if this is an IPv4 packet)
2428 * this is the first or only fragment.
2429 * For IPv6 offset == 0 means there is no Fragment Header.
2430 * If offset != 0 for IPv6 always use correct mask to
2431 * get the correct offset because we add IP6F_MORE_FRAG
2432 * to be able to dectect the first fragment which would
2433 * otherwise have offset = 0.
2438 * Local copies of addresses. They are only valid if we have
2441 * proto The protocol. Set to 0 for non-ip packets,
2442 * or to the protocol read from the packet otherwise.
2443 * proto != 0 means that we have an IPv4 packet.
2445 * src_port, dst_port port numbers, in HOST format. Only
2446 * valid for TCP and UDP packets.
2448 * src_ip, dst_ip ip addresses, in NETWORK format.
2449 * Only valid for IPv4 packets.
2452 u_int16_t src_port = 0, dst_port = 0; /* NOTE: host format */
2453 struct in_addr src_ip, dst_ip; /* NOTE: network format */
2456 u_int16_t etype = 0; /* Host order stored ether type */
2459 * dyn_dir = MATCH_UNKNOWN when rules unchecked,
2460 * MATCH_NONE when checked and not matched (q = NULL),
2461 * MATCH_FORWARD or MATCH_REVERSE otherwise (q != NULL)
2463 int dyn_dir = MATCH_UNKNOWN;
2464 ipfw_dyn_rule *q = NULL;
2465 struct ip_fw_chain *chain = &V_layer3_chain;
2469 * We store in ulp a pointer to the upper layer protocol header.
2470 * In the ipv4 case this is easy to determine from the header,
2471 * but for ipv6 we might have some additional headers in the middle.
2472 * ulp is NULL if not found.
2474 void *ulp = NULL; /* upper layer protocol pointer. */
2475 /* XXX ipv6 variables */
2477 u_int16_t ext_hd = 0; /* bits vector for extension header filtering */
2478 /* end of ipv6 variables */
2481 int done = 0; /* flag to exit the outer loop */
2483 if (m->m_flags & M_SKIP_FIREWALL || (! V_ipfw_vnet_ready))
2484 return (IP_FW_PASS); /* accept */
2486 dst_ip.s_addr = 0; /* make sure it is initialized */
2487 src_ip.s_addr = 0; /* make sure it is initialized */
2488 pktlen = m->m_pkthdr.len;
2489 args->f_id.fib = M_GETFIB(m); /* note mbuf not altered) */
2490 proto = args->f_id.proto = 0; /* mark f_id invalid */
2491 /* XXX 0 is a valid proto: IP/IPv6 Hop-by-Hop Option */
2494 * PULLUP_TO(len, p, T) makes sure that len + sizeof(T) is contiguous,
2495 * then it sets p to point at the offset "len" in the mbuf. WARNING: the
2496 * pointer might become stale after other pullups (but we never use it
2499 #define PULLUP_TO(_len, p, T) \
2501 int x = (_len) + sizeof(T); \
2502 if ((m)->m_len < x) { \
2503 goto pullup_failed; \
2505 p = (mtod(m, char *) + (_len)); \
2509 * if we have an ether header,
2512 etype = ntohs(args->eh->ether_type);
2514 /* Identify IP packets and fill up variables. */
2515 if (pktlen >= sizeof(struct ip6_hdr) &&
2516 (args->eh == NULL || etype == ETHERTYPE_IPV6) && ip->ip_v == 6) {
2517 struct ip6_hdr *ip6 = (struct ip6_hdr *)ip;
2519 args->f_id.addr_type = 6;
2520 hlen = sizeof(struct ip6_hdr);
2521 proto = ip6->ip6_nxt;
2523 /* Search extension headers to find upper layer protocols */
2524 while (ulp == NULL) {
2526 case IPPROTO_ICMPV6:
2527 PULLUP_TO(hlen, ulp, struct icmp6_hdr);
2528 args->f_id.flags = ICMP6(ulp)->icmp6_type;
2532 PULLUP_TO(hlen, ulp, struct tcphdr);
2533 dst_port = TCP(ulp)->th_dport;
2534 src_port = TCP(ulp)->th_sport;
2535 args->f_id.flags = TCP(ulp)->th_flags;
2539 PULLUP_TO(hlen, ulp, struct sctphdr);
2540 src_port = SCTP(ulp)->src_port;
2541 dst_port = SCTP(ulp)->dest_port;
2545 PULLUP_TO(hlen, ulp, struct udphdr);
2546 dst_port = UDP(ulp)->uh_dport;
2547 src_port = UDP(ulp)->uh_sport;
2550 case IPPROTO_HOPOPTS: /* RFC 2460 */
2551 PULLUP_TO(hlen, ulp, struct ip6_hbh);
2552 ext_hd |= EXT_HOPOPTS;
2553 hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3;
2554 proto = ((struct ip6_hbh *)ulp)->ip6h_nxt;
2558 case IPPROTO_ROUTING: /* RFC 2460 */
2559 PULLUP_TO(hlen, ulp, struct ip6_rthdr);
2560 switch (((struct ip6_rthdr *)ulp)->ip6r_type) {
2562 ext_hd |= EXT_RTHDR0;
2565 ext_hd |= EXT_RTHDR2;
2568 printf("IPFW2: IPV6 - Unknown Routing "
2569 "Header type(%d)\n",
2570 ((struct ip6_rthdr *)ulp)->ip6r_type);
2571 if (V_fw_deny_unknown_exthdrs)
2572 return (IP_FW_DENY);
2575 ext_hd |= EXT_ROUTING;
2576 hlen += (((struct ip6_rthdr *)ulp)->ip6r_len + 1) << 3;
2577 proto = ((struct ip6_rthdr *)ulp)->ip6r_nxt;
2581 case IPPROTO_FRAGMENT: /* RFC 2460 */
2582 PULLUP_TO(hlen, ulp, struct ip6_frag);
2583 ext_hd |= EXT_FRAGMENT;
2584 hlen += sizeof (struct ip6_frag);
2585 proto = ((struct ip6_frag *)ulp)->ip6f_nxt;
2586 offset = ((struct ip6_frag *)ulp)->ip6f_offlg &
2588 /* Add IP6F_MORE_FRAG for offset of first
2589 * fragment to be != 0. */
2590 offset |= ((struct ip6_frag *)ulp)->ip6f_offlg &
2593 printf("IPFW2: IPV6 - Invalid Fragment "
2595 if (V_fw_deny_unknown_exthdrs)
2596 return (IP_FW_DENY);
2599 args->f_id.frag_id6 =
2600 ntohl(((struct ip6_frag *)ulp)->ip6f_ident);
2604 case IPPROTO_DSTOPTS: /* RFC 2460 */
2605 PULLUP_TO(hlen, ulp, struct ip6_hbh);
2606 ext_hd |= EXT_DSTOPTS;
2607 hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3;
2608 proto = ((struct ip6_hbh *)ulp)->ip6h_nxt;
2612 case IPPROTO_AH: /* RFC 2402 */
2613 PULLUP_TO(hlen, ulp, struct ip6_ext);
2615 hlen += (((struct ip6_ext *)ulp)->ip6e_len + 2) << 2;
2616 proto = ((struct ip6_ext *)ulp)->ip6e_nxt;
2620 case IPPROTO_ESP: /* RFC 2406 */
2621 PULLUP_TO(hlen, ulp, uint32_t); /* SPI, Seq# */
2622 /* Anything past Seq# is variable length and
2623 * data past this ext. header is encrypted. */
2627 case IPPROTO_NONE: /* RFC 2460 */
2629 * Packet ends here, and IPv6 header has
2630 * already been pulled up. If ip6e_len!=0
2631 * then octets must be ignored.
2633 ulp = ip; /* non-NULL to get out of loop. */
2636 case IPPROTO_OSPFIGP:
2637 /* XXX OSPF header check? */
2638 PULLUP_TO(hlen, ulp, struct ip6_ext);
2642 /* XXX PIM header check? */
2643 PULLUP_TO(hlen, ulp, struct pim);
2647 PULLUP_TO(hlen, ulp, struct carp_header);
2648 if (((struct carp_header *)ulp)->carp_version !=
2650 return (IP_FW_DENY);
2651 if (((struct carp_header *)ulp)->carp_type !=
2653 return (IP_FW_DENY);
2656 case IPPROTO_IPV6: /* RFC 2893 */
2657 PULLUP_TO(hlen, ulp, struct ip6_hdr);
2660 case IPPROTO_IPV4: /* RFC 2893 */
2661 PULLUP_TO(hlen, ulp, struct ip);
2665 printf("IPFW2: IPV6 - Unknown Extension "
2666 "Header(%d), ext_hd=%x\n", proto, ext_hd);
2667 if (V_fw_deny_unknown_exthdrs)
2668 return (IP_FW_DENY);
2669 PULLUP_TO(hlen, ulp, struct ip6_ext);
2673 ip = mtod(m, struct ip *);
2674 ip6 = (struct ip6_hdr *)ip;
2675 args->f_id.src_ip6 = ip6->ip6_src;
2676 args->f_id.dst_ip6 = ip6->ip6_dst;
2677 args->f_id.src_ip = 0;
2678 args->f_id.dst_ip = 0;
2679 args->f_id.flow_id6 = ntohl(ip6->ip6_flow);
2680 } else if (pktlen >= sizeof(struct ip) &&
2681 (args->eh == NULL || etype == ETHERTYPE_IP) && ip->ip_v == 4) {
2683 hlen = ip->ip_hl << 2;
2684 args->f_id.addr_type = 4;
2687 * Collect parameters into local variables for faster matching.
2690 src_ip = ip->ip_src;
2691 dst_ip = ip->ip_dst;
2693 if (1 || args->eh != NULL) { /* layer 2 packets are as on the wire */
2694 offset = ntohs(ip->ip_off) & IP_OFFMASK;
2695 ip_len = ntohs(ip->ip_len);
2697 offset = ip->ip_off & IP_OFFMASK;
2698 ip_len = ip->ip_len;
2700 pktlen = ip_len < pktlen ? ip_len : pktlen;
2705 PULLUP_TO(hlen, ulp, struct tcphdr);
2706 dst_port = TCP(ulp)->th_dport;
2707 src_port = TCP(ulp)->th_sport;
2708 args->f_id.flags = TCP(ulp)->th_flags;
2712 PULLUP_TO(hlen, ulp, struct udphdr);
2713 dst_port = UDP(ulp)->uh_dport;
2714 src_port = UDP(ulp)->uh_sport;
2718 PULLUP_TO(hlen, ulp, struct icmphdr);
2719 args->f_id.flags = ICMP(ulp)->icmp_type;
2727 ip = mtod(m, struct ip *);
2728 args->f_id.src_ip = ntohl(src_ip.s_addr);
2729 args->f_id.dst_ip = ntohl(dst_ip.s_addr);
2732 if (proto) { /* we may have port numbers, store them */
2733 args->f_id.proto = proto;
2734 args->f_id.src_port = src_port = ntohs(src_port);
2735 args->f_id.dst_port = dst_port = ntohs(dst_port);
2739 if (! V_ipfw_vnet_ready) { /* shutting down, leave NOW. */
2740 IPFW_RUNLOCK(chain);
2741 return (IP_FW_PASS); /* accept */
2743 mtag = m_tag_find(m, PACKET_TAG_DIVERT, NULL);
2746 * Packet has already been tagged. Look for the next rule
2747 * to restart processing. Make sure that args->rule still
2748 * exists and not changed.
2749 * If fw_one_pass != 0 then just accept it.
2750 * XXX should not happen here, but optimized out in
2753 if (V_fw_one_pass) {
2754 IPFW_RUNLOCK(chain);
2755 return (IP_FW_PASS);
2757 if (chain->id != args->chain_id) {
2758 for (f = chain->rules; f != NULL; f = f->next)
2759 if (f == args->rule && f->id == args->rule_id)
2765 f = chain->default_rule;
2767 f = args->rule->next_rule;
2770 f = lookup_next_rule(chain, args->rule, 0);
2773 * Find the starting rule. It can be either the first
2774 * one, or the one after divert_rule if asked so.
2776 int skipto = mtag ? divert_cookie(mtag) : 0;
2779 if (args->eh == NULL && skipto != 0) {
2780 if (skipto >= IPFW_DEFAULT_RULE) {
2781 IPFW_RUNLOCK(chain);
2782 return (IP_FW_DENY); /* invalid */
2784 // f = rule2ptr(chain, skipto+1);
2785 while (f && f->rulenum <= skipto)
2789 /* reset divert rule to avoid confusion later */
2791 divinput_flags = divert_info(mtag) &
2792 (IP_FW_DIVERT_OUTPUT_FLAG | IP_FW_DIVERT_LOOPBACK_FLAG);
2793 m_tag_delete(m, mtag);
2797 * Now scan the rules, and parse microinstructions for each rule.
2798 * We have two nested loops and an inner switch. Sometimes we
2799 * need to break out of one or both loops, or re-enter one of
2800 * the loops with updated variables. Loop variables are:
2802 * f (outer loop) points to the current rule.
2803 * On output it points to the matching rule.
2804 * done (outer loop) is used as a flag to break the loop.
2805 * l (inner loop) residual length of current rule.
2806 * cmd points to the current microinstruction.
2808 * We break the inner loop by setting l=0 and possibly
2809 * cmdlen=0 if we don't want to advance cmd.
2810 * We break the outer loop by setting done=1
2811 * We can restart the inner loop by setting l>0 and f, cmd
2814 for (; f; f = f->next) {
2816 uint32_t tablearg = 0;
2817 int l, cmdlen, skip_or; /* skip rest of OR block */
2820 if (V_set_disable & (1 << f->set) )
2824 for (l = f->cmd_len, cmd = f->cmd ; l > 0 ;
2825 l -= cmdlen, cmd += cmdlen) {
2829 * check_body is a jump target used when we find a
2830 * CHECK_STATE, and need to jump to the body of
2835 cmdlen = F_LEN(cmd);
2837 * An OR block (insn_1 || .. || insn_n) has the
2838 * F_OR bit set in all but the last instruction.
2839 * The first match will set "skip_or", and cause
2840 * the following instructions to be skipped until
2841 * past the one with the F_OR bit clear.
2843 if (skip_or) { /* skip this instruction */
2844 if ((cmd->len & F_OR) == 0)
2845 skip_or = 0; /* next one is good */
2848 match = 0; /* set to 1 if we succeed */
2850 switch (cmd->opcode) {
2852 * The first set of opcodes compares the packet's
2853 * fields with some pattern, setting 'match' if a
2854 * match is found. At the end of the loop there is
2855 * logic to deal with F_NOT and F_OR flags associated
2863 printf("ipfw: opcode %d unimplemented\n",
2871 * We only check offset == 0 && proto != 0,
2872 * as this ensures that we have a
2873 * packet with the ports info.
2877 if (is_ipv6) /* XXX to be fixed later */
2879 if (proto == IPPROTO_TCP ||
2880 proto == IPPROTO_UDP)
2881 match = check_uidgid(
2882 (ipfw_insn_u32 *)cmd,
2885 src_ip, src_port, (struct ucred **)&ucred_cache,
2886 &ucred_lookup, (struct inpcb *)args->m);
2890 match = iface_match(m->m_pkthdr.rcvif,
2891 (ipfw_insn_if *)cmd);
2895 match = iface_match(oif, (ipfw_insn_if *)cmd);
2899 match = iface_match(oif ? oif :
2900 m->m_pkthdr.rcvif, (ipfw_insn_if *)cmd);
2904 if (args->eh != NULL) { /* have MAC header */
2905 u_int32_t *want = (u_int32_t *)
2906 ((ipfw_insn_mac *)cmd)->addr;
2907 u_int32_t *mask = (u_int32_t *)
2908 ((ipfw_insn_mac *)cmd)->mask;
2909 u_int32_t *hdr = (u_int32_t *)args->eh;
2912 ( want[0] == (hdr[0] & mask[0]) &&
2913 want[1] == (hdr[1] & mask[1]) &&
2914 want[2] == (hdr[2] & mask[2]) );
2919 if (args->eh != NULL) {
2921 ((ipfw_insn_u16 *)cmd)->ports;
2924 for (i = cmdlen - 1; !match && i>0;
2926 match = (etype >= p[0] &&
2932 match = (offset != 0);
2935 case O_IN: /* "out" is "not in" */
2936 match = (oif == NULL);
2940 match = (args->eh != NULL);
2944 match = (cmd->arg1 & 1 && divinput_flags &
2945 IP_FW_DIVERT_LOOPBACK_FLAG) ||
2946 (cmd->arg1 & 2 && divinput_flags &
2947 IP_FW_DIVERT_OUTPUT_FLAG);
2952 * We do not allow an arg of 0 so the
2953 * check of "proto" only suffices.
2955 match = (proto == cmd->arg1);
2960 (((ipfw_insn_ip *)cmd)->addr.s_addr ==
2964 case O_IP_SRC_LOOKUP:
2965 case O_IP_DST_LOOKUP:
2968 (cmd->opcode == O_IP_DST_LOOKUP) ?
2969 dst_ip.s_addr : src_ip.s_addr;
2972 if (cmdlen > F_INSN_SIZE(ipfw_insn_u32)) {
2973 v = ((ipfw_insn_u32 *)cmd)->d[1];
2978 else if (offset != 0)
2980 else if (proto != IPPROTO_TCP &&
2981 proto != IPPROTO_UDP)
2987 else if (v >= 4 && v <= 6) {
2989 (ipfw_insn_u32 *)cmd,
2992 src_ip, src_port, (struct ucred **)&ucred_cache,
2993 &ucred_lookup, (struct inpcb *)args->m);
2995 if (v ==4 /* O_UID */)
2996 a = ucred_cache.uid;
2997 else if (v == 5 /* O_GID */)
2998 a = ucred_cache.gid;
2999 else if (v == 6 /* O_JAIL */)
3000 a = ucred_cache.xid;
3002 if (v ==4 /* O_UID */)
3004 else if (v == 5 /* O_GID */)
3005 ; // a = groupmember((gid_t)insn->d[0], *uc);
3006 else if (v == 6 /* O_JAIL */)
3007 a = (*uc)->cr_prison->pr_id;
3012 match = lookup_table(chain, cmd->arg1, a,
3016 if (cmdlen == F_INSN_SIZE(ipfw_insn_u32))
3018 ((ipfw_insn_u32 *)cmd)->d[0] == v;
3028 (cmd->opcode == O_IP_DST_MASK) ?
3029 dst_ip.s_addr : src_ip.s_addr;
3030 uint32_t *p = ((ipfw_insn_u32 *)cmd)->d;
3033 for (; !match && i>0; i-= 2, p+= 2)
3034 match = (p[0] == (a & p[1]));
3042 INADDR_TO_IFP(src_ip, tif);
3043 match = (tif != NULL);
3050 u_int32_t *d = (u_int32_t *)(cmd+1);
3052 cmd->opcode == O_IP_DST_SET ?
3058 addr -= d[0]; /* subtract base */
3059 match = (addr < cmd->arg1) &&
3060 ( d[ 1 + (addr>>5)] &
3061 (1<<(addr & 0x1f)) );
3067 (((ipfw_insn_ip *)cmd)->addr.s_addr ==
3075 INADDR_TO_IFP(dst_ip, tif);
3076 match = (tif != NULL);
3083 * offset == 0 && proto != 0 is enough
3084 * to guarantee that we have a
3085 * packet with port info.
3087 if ((proto==IPPROTO_UDP || proto==IPPROTO_TCP)
3090 (cmd->opcode == O_IP_SRCPORT) ?
3091 src_port : dst_port ;
3093 ((ipfw_insn_u16 *)cmd)->ports;
3096 for (i = cmdlen - 1; !match && i>0;
3098 match = (x>=p[0] && x<=p[1]);
3103 match = (offset == 0 && proto==IPPROTO_ICMP &&
3104 icmptype_match(ICMP(ulp), (ipfw_insn_u32 *)cmd) );
3109 match = is_ipv6 && offset == 0 &&
3110 proto==IPPROTO_ICMPV6 &&
3112 ICMP6(ulp)->icmp6_type,
3113 (ipfw_insn_u32 *)cmd);
3119 ipopts_match(ip, cmd) );
3124 cmd->arg1 == ip->ip_v);
3130 if (is_ipv4) { /* only for IP packets */
3135 if (cmd->opcode == O_IPLEN)
3137 else if (cmd->opcode == O_IPTTL)
3139 else /* must be IPID */
3140 x = ntohs(ip->ip_id);
3142 match = (cmd->arg1 == x);
3145 /* otherwise we have ranges */
3146 p = ((ipfw_insn_u16 *)cmd)->ports;
3148 for (; !match && i>0; i--, p += 2)
3149 match = (x >= p[0] && x <= p[1]);
3153 case O_IPPRECEDENCE:
3155 (cmd->arg1 == (ip->ip_tos & 0xe0)) );
3160 flags_match(cmd, ip->ip_tos));
3164 if (proto == IPPROTO_TCP && offset == 0) {
3172 ((ip->ip_hl + tcp->th_off) << 2);
3174 match = (cmd->arg1 == x);
3177 /* otherwise we have ranges */
3178 p = ((ipfw_insn_u16 *)cmd)->ports;
3180 for (; !match && i>0; i--, p += 2)
3181 match = (x >= p[0] && x <= p[1]);
3186 match = (proto == IPPROTO_TCP && offset == 0 &&
3187 flags_match(cmd, TCP(ulp)->th_flags));
3191 match = (proto == IPPROTO_TCP && offset == 0 &&
3192 tcpopts_match(TCP(ulp), cmd));
3196 match = (proto == IPPROTO_TCP && offset == 0 &&
3197 ((ipfw_insn_u32 *)cmd)->d[0] ==
3202 match = (proto == IPPROTO_TCP && offset == 0 &&
3203 ((ipfw_insn_u32 *)cmd)->d[0] ==
3208 match = (proto == IPPROTO_TCP && offset == 0 &&
3209 cmd->arg1 == TCP(ulp)->th_win);
3213 /* reject packets which have SYN only */
3214 /* XXX should i also check for TH_ACK ? */
3215 match = (proto == IPPROTO_TCP && offset == 0 &&
3216 (TCP(ulp)->th_flags &
3217 (TH_RST | TH_ACK | TH_SYN)) != TH_SYN);
3222 ipfw_insn_altq *altq = (ipfw_insn_altq *)cmd;
3225 at = pf_find_mtag(m);
3226 if (at != NULL && at->qid != 0)
3228 at = pf_get_mtag(m);
3231 * Let the packet fall back to the
3236 at->qid = altq->qid;
3247 ipfw_log(f, hlen, args, m,
3248 oif, offset, tablearg, ip);
3253 match = (random()<((ipfw_insn_u32 *)cmd)->d[0]);
3258 /* Outgoing packets automatically pass/match */
3259 match = ((oif != NULL) ||
3260 (m->m_pkthdr.rcvif == NULL) ||
3264 verify_path6(&(args->f_id.src_ip6),
3265 m->m_pkthdr.rcvif) :
3267 verify_path(src_ip, m->m_pkthdr.rcvif,
3272 /* Outgoing packets automatically pass/match */
3273 match = (hlen > 0 && ((oif != NULL) ||
3276 verify_path6(&(args->f_id.src_ip6),
3279 verify_path(src_ip, NULL, args->f_id.fib)));
3283 /* Outgoing packets automatically pass/match */
3284 if (oif == NULL && hlen > 0 &&
3285 ( (is_ipv4 && in_localaddr(src_ip))
3288 in6_localaddr(&(args->f_id.src_ip6)))
3293 is_ipv6 ? verify_path6(
3294 &(args->f_id.src_ip6),
3295 m->m_pkthdr.rcvif) :
3307 match = (m_tag_find(m,
3308 PACKET_TAG_IPSEC_IN_DONE, NULL) != NULL);
3310 /* otherwise no match */
3316 IN6_ARE_ADDR_EQUAL(&args->f_id.src_ip6,
3317 &((ipfw_insn_ip6 *)cmd)->addr6);
3322 IN6_ARE_ADDR_EQUAL(&args->f_id.dst_ip6,
3323 &((ipfw_insn_ip6 *)cmd)->addr6);
3325 case O_IP6_SRC_MASK:
3326 case O_IP6_DST_MASK:
3330 struct in6_addr *d =
3331 &((ipfw_insn_ip6 *)cmd)->addr6;
3333 for (; !match && i > 0; d += 2,
3334 i -= F_INSN_SIZE(struct in6_addr)
3340 APPLY_MASK(&p, &d[1]);
3342 IN6_ARE_ADDR_EQUAL(&d[0],
3349 match= is_ipv6 && search_ip6_addr_net(&args->f_id.src_ip6);
3353 match= is_ipv6 && search_ip6_addr_net(&args->f_id.dst_ip6);
3358 flow6id_match(args->f_id.flow_id6,
3359 (ipfw_insn_u32 *) cmd);
3364 (ext_hd & ((ipfw_insn *) cmd)->arg1);
3378 uint32_t tag = (cmd->arg1 == IP_FW_TABLEARG) ?
3379 tablearg : cmd->arg1;
3381 /* Packet is already tagged with this tag? */
3382 mtag = m_tag_locate(m, MTAG_IPFW, tag, NULL);
3384 /* We have `untag' action when F_NOT flag is
3385 * present. And we must remove this mtag from
3386 * mbuf and reset `match' to zero (`match' will
3387 * be inversed later).
3388 * Otherwise we should allocate new mtag and
3389 * push it into mbuf.
3391 if (cmd->len & F_NOT) { /* `untag' action */
3393 m_tag_delete(m, mtag);
3394 } else if (mtag == NULL) {
3395 if ((mtag = m_tag_alloc(MTAG_IPFW,
3396 tag, 0, M_NOWAIT)) != NULL)
3397 m_tag_prepend(m, mtag);
3399 match = (cmd->len & F_NOT) ? 0: 1;
3403 case O_FIB: /* try match the specified fib */
3404 if (args->f_id.fib == cmd->arg1)
3409 uint32_t tag = (cmd->arg1 == IP_FW_TABLEARG) ?
3410 tablearg : cmd->arg1;
3413 match = m_tag_locate(m, MTAG_IPFW,
3418 /* we have ranges */
3419 for (mtag = m_tag_first(m);
3420 mtag != NULL && !match;
3421 mtag = m_tag_next(m, mtag)) {
3425 if (mtag->m_tag_cookie != MTAG_IPFW)
3428 p = ((ipfw_insn_u16 *)cmd)->ports;
3430 for(; !match && i > 0; i--, p += 2)
3432 mtag->m_tag_id >= p[0] &&
3433 mtag->m_tag_id <= p[1];
3440 * The second set of opcodes represents 'actions',
3441 * i.e. the terminal part of a rule once the packet
3442 * matches all previous patterns.
3443 * Typically there is only one action for each rule,
3444 * and the opcode is stored at the end of the rule
3445 * (but there are exceptions -- see below).
3447 * In general, here we set retval and terminate the
3448 * outer loop (would be a 'break 3' in some language,
3449 * but we need to set l=0, done=1)
3452 * O_COUNT and O_SKIPTO actions:
3453 * instead of terminating, we jump to the next rule
3454 * (setting l=0), or to the SKIPTO target (by
3455 * setting f, cmd and l as needed), respectively.
3457 * O_TAG, O_LOG and O_ALTQ action parameters:
3458 * perform some action and set match = 1;
3460 * O_LIMIT and O_KEEP_STATE: these opcodes are
3461 * not real 'actions', and are stored right
3462 * before the 'action' part of the rule.
3463 * These opcodes try to install an entry in the
3464 * state tables; if successful, we continue with
3465 * the next opcode (match=1; break;), otherwise
3466 * the packet must be dropped (set retval,
3467 * break loops with l=0, done=1)
3469 * O_PROBE_STATE and O_CHECK_STATE: these opcodes
3470 * cause a lookup of the state table, and a jump
3471 * to the 'action' part of the parent rule
3472 * if an entry is found, or
3473 * (CHECK_STATE only) a jump to the next rule if
3474 * the entry is not found.
3475 * The result of the lookup is cached so that
3476 * further instances of these opcodes become NOPs.
3477 * The jump to the next rule is done by setting
3482 if (install_state(f,
3483 (ipfw_insn_limit *)cmd, args, tablearg)) {
3484 /* error or limit violation */
3485 retval = IP_FW_DENY;
3486 l = 0; /* exit inner loop */
3487 done = 1; /* exit outer loop */
3495 * dynamic rules are checked at the first
3496 * keep-state or check-state occurrence,
3497 * with the result being stored in dyn_dir.
3498 * The compiler introduces a PROBE_STATE
3499 * instruction for us when we have a
3500 * KEEP_STATE (because PROBE_STATE needs
3503 if (dyn_dir == MATCH_UNKNOWN &&
3504 (q = lookup_dyn_rule(&args->f_id,
3505 &dyn_dir, proto == IPPROTO_TCP ?
3509 * Found dynamic entry, update stats
3510 * and jump to the 'action' part of
3511 * the parent rule by setting
3512 * f, cmd, l and clearing cmdlen.
3517 cmd = ACTION_PTR(f);
3518 l = f->cmd_len - f->act_ofs;
3525 * Dynamic entry not found. If CHECK_STATE,
3526 * skip to next rule, if PROBE_STATE just
3527 * ignore and continue with next opcode.
3529 if (cmd->opcode == O_CHECK_STATE)
3530 l = 0; /* exit inner loop */
3535 retval = 0; /* accept */
3536 l = 0; /* exit inner loop */
3537 done = 1; /* exit outer loop */
3542 args->rule = f; /* report matching rule */
3543 args->rule_id = f->id;
3544 args->chain_id = chain->id;
3545 if (cmd->arg1 == IP_FW_TABLEARG)
3546 args->cookie = tablearg;
3548 args->cookie = cmd->arg1;
3549 retval = IP_FW_DUMMYNET;
3550 l = 0; /* exit inner loop */
3551 done = 1; /* exit outer loop */
3557 if (args->eh) /* not on layer 2 */
3559 /* otherwise this is terminal */
3560 l = 0; /* exit inner loop */
3561 done = 1; /* exit outer loop */
3562 mtag = m_tag_get(PACKET_TAG_DIVERT,
3563 sizeof(struct divert_tag),
3566 retval = IP_FW_DENY;
3568 struct divert_tag *dt;
3569 dt = (struct divert_tag *)(mtag+1);
3570 dt->cookie = f->rulenum;
3571 if (cmd->arg1 == IP_FW_TABLEARG)
3572 dt->info = tablearg;
3574 dt->info = cmd->arg1;
3575 m_tag_prepend(m, mtag);
3576 retval = (cmd->opcode == O_DIVERT) ?
3577 IP_FW_DIVERT : IP_FW_TEE;
3584 f->pcnt++; /* update stats */
3586 f->timestamp = time_uptime;
3587 if (cmd->opcode == O_COUNT) {
3588 l = 0; /* exit inner loop */
3592 if (cmd->arg1 == IP_FW_TABLEARG) {
3593 f = lookup_next_rule(chain, f, tablearg);
3595 if (f->next_rule == NULL)
3596 lookup_next_rule(chain, f, 0);
3600 * Skip disabled rules, and
3601 * re-enter the inner loop
3602 * with the correct f, l and cmd.
3603 * Also clear cmdlen and skip_or
3605 while (f && (V_set_disable & (1 << f->set)))
3607 if (f) { /* found a valid rule */
3611 l = 0; /* exit inner loop */
3620 * Drop the packet and send a reject notice
3621 * if the packet is not ICMP (or is an ICMP
3622 * query), and it is not multicast/broadcast.
3624 if (hlen > 0 && is_ipv4 && offset == 0 &&
3625 (proto != IPPROTO_ICMP ||
3626 is_icmp_query(ICMP(ulp))) &&
3627 !(m->m_flags & (M_BCAST|M_MCAST)) &&
3628 !IN_MULTICAST(ntohl(dst_ip.s_addr))) {
3629 send_reject(args, cmd->arg1, ip_len, ip);
3635 if (hlen > 0 && is_ipv6 &&
3636 ((offset & IP6F_OFF_MASK) == 0) &&
3637 (proto != IPPROTO_ICMPV6 ||
3638 (is_icmp6_query(args->f_id.flags) == 1)) &&
3639 !(m->m_flags & (M_BCAST|M_MCAST)) &&
3640 !IN6_IS_ADDR_MULTICAST(&args->f_id.dst_ip6)) {
3642 args, cmd->arg1, hlen,
3643 (struct ip6_hdr *)ip);
3649 retval = IP_FW_DENY;
3650 l = 0; /* exit inner loop */
3651 done = 1; /* exit outer loop */
3655 if (args->eh) /* not valid on layer2 pkts */
3657 if (!q || dyn_dir == MATCH_FORWARD) {
3658 struct sockaddr_in *sa;
3659 sa = &(((ipfw_insn_sa *)cmd)->sa);
3660 if (sa->sin_addr.s_addr == INADDR_ANY) {
3661 bcopy(sa, &args->hopstore,
3663 args->hopstore.sin_addr.s_addr =
3665 args->next_hop = &args->hopstore;
3667 args->next_hop = sa;
3670 retval = IP_FW_PASS;
3671 l = 0; /* exit inner loop */
3672 done = 1; /* exit outer loop */
3677 args->rule = f; /* report matching rule */
3678 args->rule_id = f->id;
3679 args->chain_id = chain->id;
3680 if (cmd->arg1 == IP_FW_TABLEARG)
3681 args->cookie = tablearg;
3683 args->cookie = cmd->arg1;
3684 retval = (cmd->opcode == O_NETGRAPH) ?
3685 IP_FW_NETGRAPH : IP_FW_NGTEE;
3686 l = 0; /* exit inner loop */
3687 done = 1; /* exit outer loop */
3692 f->pcnt++; /* update stats */
3694 f->timestamp = time_uptime;
3695 M_SETFIB(m, cmd->arg1);
3696 args->f_id.fib = cmd->arg1;
3697 l = 0; /* exit inner loop */
3701 if (!IPFW_NAT_LOADED) {
3702 retval = IP_FW_DENY;
3707 args->rule = f; /* Report matching rule. */
3708 args->rule_id = f->id;
3709 args->chain_id = chain->id;
3710 t = ((ipfw_insn_nat *)cmd)->nat;
3712 nat_id = (cmd->arg1 == IP_FW_TABLEARG) ?
3713 tablearg : cmd->arg1;
3714 LOOKUP_NAT(V_layer3_chain, nat_id, t);
3716 retval = IP_FW_DENY;
3717 l = 0; /* exit inner loop */
3718 done = 1; /* exit outer loop */
3721 if (cmd->arg1 != IP_FW_TABLEARG)
3722 ((ipfw_insn_nat *)cmd)->nat = t;
3724 retval = ipfw_nat_ptr(args, t, m);
3726 l = 0; /* exit inner loop */
3727 done = 1; /* exit outer loop */
3735 l = 0; /* in any case exit inner loop */
3737 ip_off = (args->eh != NULL) ?
3738 ntohs(ip->ip_off) : ip->ip_off;
3739 /* if not fragmented, go to next rule */
3740 if ((ip_off & (IP_MF | IP_OFFMASK)) == 0)
3743 * ip_reass() expects len & off in host
3744 * byte order: fix them in case we come
3747 if (args->eh != NULL) {
3748 ip->ip_len = ntohs(ip->ip_len);
3749 ip->ip_off = ntohs(ip->ip_off);
3752 args->m = m = ip_reass(m);
3755 * IP header checksum fixup after
3756 * reassembly and leave header
3757 * in network byte order.
3759 if (m == NULL) { /* fragment got swallowed */
3760 retval = IP_FW_DENY;
3761 } else { /* good, packet complete */
3764 ip = mtod(m, struct ip *);
3765 hlen = ip->ip_hl << 2;
3766 /* revert len & off for layer2 pkts */
3767 if (args->eh != NULL)
3768 ip->ip_len = htons(ip->ip_len);
3770 if (hlen == sizeof(struct ip))
3771 ip->ip_sum = in_cksum_hdr(ip);
3773 ip->ip_sum = in_cksum(m, hlen);
3774 retval = IP_FW_REASS;
3776 args->rule_id = f->id;
3777 args->chain_id = chain->id;
3779 done = 1; /* exit outer loop */
3785 break; // XXX we disabled some
3786 panic("-- unknown opcode %d\n", cmd->opcode);
3787 } /* end of switch() on opcodes */
3789 * if we get here with l=0, then match is irrelevant.
3792 if (cmd->len & F_NOT)
3796 if (cmd->len & F_OR)
3799 if (!(cmd->len & F_OR)) /* not an OR block, */
3800 break; /* try next rule */
3803 } /* end of inner loop, scan opcodes */
3808 /* next_rule:;*/ /* try next rule */
3810 } /* end of outer for, scan rules */
3813 /* Update statistics */
3816 f->timestamp = time_uptime;
3818 retval = IP_FW_DENY;
3819 printf("ipfw: ouch!, skip past end of rules, denying packet\n");
3821 IPFW_RUNLOCK(chain);
3823 if (ucred_cache != NULL)
3824 crfree(ucred_cache);
3830 printf("ipfw: pullup failed\n");
3831 return (IP_FW_DENY);
3835 * When a rule is added/deleted, clear the next_rule pointers in all rules.
3836 * These will be reconstructed on the fly as packets are matched.
3839 flush_rule_ptrs(struct ip_fw_chain *chain)
3843 IPFW_WLOCK_ASSERT(chain);
3847 for (rule = chain->rules; rule; rule = rule->next)
3848 rule->next_rule = NULL;
3852 * Add a new rule to the list. Copy the rule into a malloc'ed area, then
3853 * possibly create a rule number and add the rule to the list.
3854 * Update the rule_number in the input struct so the caller knows it as well.
3857 add_rule(struct ip_fw_chain *chain, struct ip_fw *input_rule)
3859 struct ip_fw *rule, *f, *prev;
3860 int l = RULESIZE(input_rule);
3862 if (chain->rules == NULL && input_rule->rulenum != IPFW_DEFAULT_RULE)
3865 rule = malloc(l, M_IPFW, M_NOWAIT | M_ZERO);
3869 bcopy(input_rule, rule, l);
3872 rule->next_rule = NULL;
3876 rule->timestamp = 0;
3880 if (chain->rules == NULL) { /* default rule */
3881 chain->rules = rule;
3882 rule->id = ++chain->id;
3886 if (V_autoinc_step < 1)
3888 else if (V_autoinc_step > 1000)
3889 V_autoinc_step = 1000;
3890 if (rule->rulenum == 0) {
3892 * If rulenum is 0, use highest numbered rule before
3893 * the default, adding autoinc_step if room.
3894 * Also set the number in the caller.
3896 for (f = chain->rules; f; f = f->next) {
3897 if (f->rulenum == IPFW_DEFAULT_RULE)
3899 rule->rulenum = f->rulenum;
3901 if (rule->rulenum < IPFW_DEFAULT_RULE - V_autoinc_step)
3902 rule->rulenum += V_autoinc_step;
3903 input_rule->rulenum = rule->rulenum;
3907 * Now insert the new rule in the right place in the sorted list.
3908 * XXX TODO also put in the skipto table.
3910 for (prev = NULL, f = chain->rules; f; prev = f, f = f->next) {
3911 if (f->rulenum > rule->rulenum) { /* found the location */
3915 } else { /* head insert */
3916 rule->next = chain->rules;
3917 chain->rules = rule;
3922 flush_rule_ptrs(chain);
3923 /* chain->id incremented inside flush_rule_ptrs() */
3924 rule->id = chain->id;
3928 IPFW_WUNLOCK(chain);
3929 DEB(printf("ipfw: installed rule %d, static count now %d\n",
3930 rule->rulenum, V_static_count);)
3935 * Remove a static rule (including derived * dynamic rules)
3936 * and place it on the ``reap list'' for later reclamation.
3937 * The caller is in charge of clearing rule pointers to avoid
3938 * dangling pointers.
3939 * @return a pointer to the next entry.
3940 * Arguments are not checked, so they better be correct.
3942 static struct ip_fw *
3943 remove_rule(struct ip_fw_chain *chain, struct ip_fw *rule,
3947 int l = RULESIZE(rule);
3949 IPFW_WLOCK_ASSERT(chain);
3953 remove_dyn_rule(rule, NULL /* force removal */);
3961 // XXX remove from the skipto table
3963 rule->next = chain->reap;
3970 * Reclaim storage associated with a list of rules. This is
3971 * typically the list created using remove_rule.
3972 * A NULL pointer on input is handled correctly.
3975 reap_rules(struct ip_fw *head)
3979 while ((rule = head) != NULL) {
3986 * Remove all rules from a chain (except rules in set RESVD_SET
3987 * unless kill_default = 1). The caller is responsible for
3988 * reclaiming storage for the rules left in chain->reap.
3991 free_chain(struct ip_fw_chain *chain, int kill_default)
3993 struct ip_fw *prev, *rule;
3995 IPFW_WLOCK_ASSERT(chain);
3998 flush_rule_ptrs(chain); /* more efficient to do outside the loop */
3999 for (prev = NULL, rule = chain->rules; rule ; )
4000 if (kill_default || rule->set != RESVD_SET)
4001 rule = remove_rule(chain, rule, prev);
4009 * Remove all rules with given number, and also do set manipulation.
4010 * Assumes chain != NULL && *chain != NULL.
4012 * The argument is an u_int32_t. The low 16 bit are the rule or set number,
4013 * the next 8 bits are the new set, the top 8 bits are the command:
4015 * 0 delete rules with given number
4016 * 1 delete rules with given set number
4017 * 2 move rules with given number to new set
4018 * 3 move rules with given set number to new set
4019 * 4 swap sets with given numbers
4020 * 5 delete rules with given number and with given set number
4023 del_entry(struct ip_fw_chain *chain, u_int32_t arg)
4025 struct ip_fw *prev = NULL, *rule;
4026 u_int16_t rulenum; /* rule or old_set */
4027 u_int8_t cmd, new_set;
4029 rulenum = arg & 0xffff;
4030 cmd = (arg >> 24) & 0xff;
4031 new_set = (arg >> 16) & 0xff;
4033 if (cmd > 5 || new_set > RESVD_SET)
4035 if (cmd == 0 || cmd == 2 || cmd == 5) {
4036 if (rulenum >= IPFW_DEFAULT_RULE)
4039 if (rulenum > RESVD_SET) /* old_set */
4044 rule = chain->rules; /* common starting point */
4045 chain->reap = NULL; /* prepare for deletions */
4047 case 0: /* delete rules with given number */
4049 * locate first rule to delete
4051 for (; rule->rulenum < rulenum; prev = rule, rule = rule->next)
4053 if (rule->rulenum != rulenum) {
4054 IPFW_WUNLOCK(chain);
4059 * flush pointers outside the loop, then delete all matching
4060 * rules. prev remains the same throughout the cycle.
4062 flush_rule_ptrs(chain);
4063 while (rule->rulenum == rulenum)
4064 rule = remove_rule(chain, rule, prev);
4067 case 1: /* delete all rules with given set number */
4068 flush_rule_ptrs(chain);
4069 while (rule->rulenum < IPFW_DEFAULT_RULE) {
4070 if (rule->set == rulenum)
4071 rule = remove_rule(chain, rule, prev);
4079 case 2: /* move rules with given number to new set */
4080 for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
4081 if (rule->rulenum == rulenum)
4082 rule->set = new_set;
4085 case 3: /* move rules with given set number to new set */
4086 for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
4087 if (rule->set == rulenum)
4088 rule->set = new_set;
4091 case 4: /* swap two sets */
4092 for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
4093 if (rule->set == rulenum)
4094 rule->set = new_set;
4095 else if (rule->set == new_set)
4096 rule->set = rulenum;
4099 case 5: /* delete rules with given number and with given set number.
4100 * rulenum - given rule number;
4101 * new_set - given set number.
4103 for (; rule->rulenum < rulenum; prev = rule, rule = rule->next)
4105 if (rule->rulenum != rulenum) {
4106 IPFW_WUNLOCK(chain);
4109 flush_rule_ptrs(chain);
4110 while (rule->rulenum == rulenum) {
4111 if (rule->set == new_set)
4112 rule = remove_rule(chain, rule, prev);
4120 * Look for rules to reclaim. We grab the list before
4121 * releasing the lock then reclaim them w/o the lock to
4122 * avoid a LOR with dummynet.
4125 IPFW_WUNLOCK(chain);
4131 * Clear counters for a specific rule.
4132 * The enclosing "table" is assumed locked.
4135 clear_counters(struct ip_fw *rule, int log_only)
4137 ipfw_insn_log *l = (ipfw_insn_log *)ACTION_PTR(rule);
4139 if (log_only == 0) {
4140 rule->bcnt = rule->pcnt = 0;
4141 rule->timestamp = 0;
4143 if (l->o.opcode == O_LOG)
4144 l->log_left = l->max_log;
4148 * Reset some or all counters on firewall rules.
4149 * The argument `arg' is an u_int32_t. The low 16 bit are the rule number,
4150 * the next 8 bits are the set number, the top 8 bits are the command:
4151 * 0 work with rules from all set's;
4152 * 1 work with rules only from specified set.
4153 * Specified rule number is zero if we want to clear all entries.
4154 * log_only is 1 if we only want to reset logs, zero otherwise.
4157 zero_entry(struct ip_fw_chain *chain, u_int32_t arg, int log_only)
4162 uint16_t rulenum = arg & 0xffff;
4163 uint8_t set = (arg >> 16) & 0xff;
4164 uint8_t cmd = (arg >> 24) & 0xff;
4168 if (cmd == 1 && set > RESVD_SET)
4173 V_norule_counter = 0;
4174 for (rule = chain->rules; rule; rule = rule->next) {
4175 /* Skip rules from another set. */
4176 if (cmd == 1 && rule->set != set)
4178 clear_counters(rule, log_only);
4180 msg = log_only ? "All logging counts reset" :
4181 "Accounting cleared";
4185 * We can have multiple rules with the same number, so we
4186 * need to clear them all.
4188 for (rule = chain->rules; rule; rule = rule->next)
4189 if (rule->rulenum == rulenum) {
4190 while (rule && rule->rulenum == rulenum) {
4191 if (cmd == 0 || rule->set == set)
4192 clear_counters(rule, log_only);
4198 if (!cleared) { /* we did not find any matching rules */
4199 IPFW_WUNLOCK(chain);
4202 msg = log_only ? "logging count reset" : "cleared";
4204 IPFW_WUNLOCK(chain);
4207 #define lev LOG_SECURITY | LOG_NOTICE
4210 log(lev, "ipfw: Entry %d %s.\n", rulenum, msg);
4212 log(lev, "ipfw: %s.\n", msg);
4218 * Check validity of the structure before insert.
4219 * Fortunately rules are simple, so this mostly need to check rule sizes.
4222 check_ipfw_struct(struct ip_fw *rule, int size)
4228 if (size < sizeof(*rule)) {
4229 printf("ipfw: rule too short\n");
4232 /* first, check for valid size */
4235 printf("ipfw: size mismatch (have %d want %d)\n", size, l);
4238 if (rule->act_ofs >= rule->cmd_len) {
4239 printf("ipfw: bogus action offset (%u > %u)\n",
4240 rule->act_ofs, rule->cmd_len - 1);
4244 * Now go for the individual checks. Very simple ones, basically only
4245 * instruction sizes.
4247 for (l = rule->cmd_len, cmd = rule->cmd ;
4248 l > 0 ; l -= cmdlen, cmd += cmdlen) {
4249 cmdlen = F_LEN(cmd);
4251 printf("ipfw: opcode %d size truncated\n",
4255 DEB(printf("ipfw: opcode %d\n", cmd->opcode);)
4256 switch (cmd->opcode) {
4268 case O_IPPRECEDENCE:
4286 if (cmdlen != F_INSN_SIZE(ipfw_insn))
4291 if (cmdlen != F_INSN_SIZE(ipfw_insn))
4293 if (cmd->arg1 >= rt_numfibs) {
4294 printf("ipfw: invalid fib number %d\n",
4301 if (cmdlen != F_INSN_SIZE(ipfw_insn))
4303 if (cmd->arg1 >= rt_numfibs) {
4304 printf("ipfw: invalid fib number %d\n",
4319 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32))
4324 if (cmdlen != F_INSN_SIZE(ipfw_insn_limit))
4329 if (cmdlen != F_INSN_SIZE(ipfw_insn_log))
4332 ((ipfw_insn_log *)cmd)->log_left =
4333 ((ipfw_insn_log *)cmd)->max_log;
4339 /* only odd command lengths */
4340 if ( !(cmdlen & 1) || cmdlen > 31)
4346 if (cmd->arg1 == 0 || cmd->arg1 > 256) {
4347 printf("ipfw: invalid set size %d\n",
4351 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
4356 case O_IP_SRC_LOOKUP:
4357 case O_IP_DST_LOOKUP:
4358 if (cmd->arg1 >= IPFW_TABLES_MAX) {
4359 printf("ipfw: invalid table number %d\n",
4363 if (cmdlen != F_INSN_SIZE(ipfw_insn) &&
4364 cmdlen != F_INSN_SIZE(ipfw_insn_u32) + 1 &&
4365 cmdlen != F_INSN_SIZE(ipfw_insn_u32))
4370 if (cmdlen != F_INSN_SIZE(ipfw_insn_mac))
4380 if (cmdlen < 1 || cmdlen > 31)
4386 case O_IP_DSTPORT: /* XXX artificial limit, 30 port pairs */
4387 if (cmdlen < 2 || cmdlen > 31)
4394 if (cmdlen != F_INSN_SIZE(ipfw_insn_if))
4399 if (cmdlen != F_INSN_SIZE(ipfw_insn_altq))
4405 if (cmdlen != F_INSN_SIZE(ipfw_insn))
4410 #ifdef IPFIREWALL_FORWARD
4411 if (cmdlen != F_INSN_SIZE(ipfw_insn_sa))
4420 if (ip_divert_ptr == NULL)
4426 if (!NG_IPFW_LOADED)
4431 if (!IPFW_NAT_LOADED)
4433 if (cmdlen != F_INSN_SIZE(ipfw_insn_nat))
4436 case O_FORWARD_MAC: /* XXX not implemented yet */
4448 if (cmdlen != F_INSN_SIZE(ipfw_insn))
4452 printf("ipfw: opcode %d, multiple actions"
4459 printf("ipfw: opcode %d, action must be"
4468 if (cmdlen != F_INSN_SIZE(struct in6_addr) +
4469 F_INSN_SIZE(ipfw_insn))
4474 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
4475 ((ipfw_insn_u32 *)cmd)->o.arg1)
4479 case O_IP6_SRC_MASK:
4480 case O_IP6_DST_MASK:
4481 if ( !(cmdlen & 1) || cmdlen > 127)
4485 if( cmdlen != F_INSN_SIZE( ipfw_insn_icmp6 ) )
4491 switch (cmd->opcode) {
4501 case O_IP6_SRC_MASK:
4502 case O_IP6_DST_MASK:
4504 printf("ipfw: no IPv6 support in kernel\n");
4505 return EPROTONOSUPPORT;
4508 printf("ipfw: opcode %d, unknown opcode\n",
4514 if (have_action == 0) {
4515 printf("ipfw: missing action\n");
4521 printf("ipfw: opcode %d size %d wrong\n",
4522 cmd->opcode, cmdlen);
4527 * Copy the static rules to the supplied buffer
4528 * and return the amount of space actually used.
4531 ipfw_getrules(struct ip_fw_chain *chain, void *buf, size_t space)
4534 char *ep = bp + space;
4537 time_t boot_seconds;
4539 boot_seconds = boottime.tv_sec;
4540 /* XXX this can take a long time and locking will block packet flow */
4542 for (rule = chain->rules; rule ; rule = rule->next) {
4544 * Verify the entry fits in the buffer in case the
4545 * rules changed between calculating buffer space and
4546 * now. This would be better done using a generation
4547 * number but should suffice for now.
4553 * XXX HACK. Store the disable mask in the "next"
4554 * pointer in a wild attempt to keep the ABI the same.
4555 * Why do we do this on EVERY rule?
4557 bcopy(&V_set_disable,
4558 &(((struct ip_fw *)bp)->next_rule),
4559 sizeof(V_set_disable));
4560 if (((struct ip_fw *)bp)->timestamp)
4561 ((struct ip_fw *)bp)->timestamp += boot_seconds;
4565 IPFW_RUNLOCK(chain);
4566 return (bp - (char *)buf);
4570 * Copy the dynamic rules to the supplied buffer
4571 * and return the amount of space actually used.
4572 * XXX marta if we allocate X and rules grows
4573 * we check for size limit while copying rules into the buffer
4576 ipfw_getdynrules(struct ip_fw_chain *chain, void *buf, size_t space)
4579 char *ep = bp + space;
4581 time_t boot_seconds;
4583 printf("dynrules requested\n");
4584 boot_seconds = boottime.tv_sec;
4587 ipfw_dyn_rule *p, *last = NULL;
4590 for (i = 0 ; i < V_curr_dyn_buckets; i++)
4591 for (p = V_ipfw_dyn_v[i] ; p != NULL; p = p->next) {
4592 if (bp + sizeof *p <= ep) {
4593 ipfw_dyn_rule *dst =
4594 (ipfw_dyn_rule *)bp;
4595 bcopy(p, dst, sizeof *p);
4596 bcopy(&(p->rule->rulenum), &(dst->rule),
4597 sizeof(p->rule->rulenum));
4599 * store set number into high word of
4600 * dst->rule pointer.
4602 bcopy(&(p->rule->set),
4603 (char *)&dst->rule +
4604 sizeof(p->rule->rulenum),
4605 sizeof(p->rule->set));
4607 * store a non-null value in "next".
4608 * The userland code will interpret a
4609 * NULL here as a marker
4610 * for the last dynamic rule.
4612 bcopy(&dst, &dst->next, sizeof(dst));
4615 TIME_LEQ(dst->expire, time_uptime) ?
4616 0 : dst->expire - time_uptime ;
4617 bp += sizeof(ipfw_dyn_rule);
4619 p = NULL; /* break the loop */
4620 i = V_curr_dyn_buckets;
4624 if (last != NULL) /* mark last dynamic rule */
4625 bzero(&last->next, sizeof(last));
4627 return (bp - (char *)buf);
4632 * {set|get}sockopt parser.
4635 ipfw_ctl(struct sockopt *sopt)
4637 #define RULE_MAXSIZE (256*sizeof(u_int32_t))
4640 struct ip_fw *buf, *rule;
4641 u_int32_t rulenum[2];
4643 error = priv_check(sopt->sopt_td, PRIV_NETINET_IPFW);
4648 * Disallow modifications in really-really secure mode, but still allow
4649 * the logging counters to be reset.
4651 if (sopt->sopt_name == IP_FW_ADD ||
4652 (sopt->sopt_dir == SOPT_SET && sopt->sopt_name != IP_FW_RESETLOG)) {
4653 error = securelevel_ge(sopt->sopt_td->td_ucred, 3);
4660 switch (sopt->sopt_name) {
4663 * pass up a copy of the current static rules.
4664 * The last static rule has number IPFW_DEFAULT_RULE.
4666 * Note that the calculated size is used to bound the
4667 * amount of data returned to the user. The rule set may
4668 * change between calculating the size and returning the
4669 * data in which case we'll just return what fits.
4671 size = V_static_len; /* size of static rules */
4674 * XXX todo: if the user passes a short length just to know
4675 * how much room is needed, do not bother filling up the
4676 * buffer, just jump to the sooptcopyout.
4678 buf = malloc(size, M_TEMP, M_WAITOK);
4679 error = sooptcopyout(sopt, buf,
4680 ipfw_getrules(&V_layer3_chain, buf, size));
4686 * pass up a copy of the current dynamic rules.
4687 * The last dynamic rule has NULL in the "next" field.
4689 /* if (!V_ipfw_dyn_v) XXX check for empty set ? */
4690 size = (V_dyn_count * sizeof(ipfw_dyn_rule)); /* size of dyn. rules */
4692 buf = malloc(size, M_TEMP, M_WAITOK);
4693 error = sooptcopyout(sopt, buf,
4694 ipfw_getdynrules(&V_layer3_chain, buf, size));
4700 * Normally we cannot release the lock on each iteration.
4701 * We could do it here only because we start from the head all
4702 * the times so there is no risk of missing some entries.
4703 * On the other hand, the risk is that we end up with
4704 * a very inconsistent ruleset, so better keep the lock
4705 * around the whole cycle.
4707 * XXX this code can be improved by resetting the head of
4708 * the list to point to the default rule, and then freeing
4709 * the old list without the need for a lock.
4712 IPFW_WLOCK(&V_layer3_chain);
4713 free_chain(&V_layer3_chain, 0 /* keep default rule */);
4714 rule = V_layer3_chain.reap;
4715 IPFW_WUNLOCK(&V_layer3_chain);
4720 rule = malloc(RULE_MAXSIZE, M_TEMP, M_WAITOK);
4721 error = sooptcopyin(sopt, rule, RULE_MAXSIZE,
4722 sizeof(struct ip_fw) );
4724 error = check_ipfw_struct(rule, sopt->sopt_valsize);
4726 error = add_rule(&V_layer3_chain, rule);
4727 size = RULESIZE(rule);
4728 if (!error && sopt->sopt_dir == SOPT_GET)
4729 error = sooptcopyout(sopt, rule, size);
4736 * IP_FW_DEL is used for deleting single rules or sets,
4737 * and (ab)used to atomically manipulate sets. Argument size
4738 * is used to distinguish between the two:
4740 * delete single rule or set of rules,
4741 * or reassign rules (or sets) to a different set.
4742 * 2*sizeof(u_int32_t)
4743 * atomic disable/enable sets.
4744 * first u_int32_t contains sets to be disabled,
4745 * second u_int32_t contains sets to be enabled.
4747 error = sooptcopyin(sopt, rulenum,
4748 2*sizeof(u_int32_t), sizeof(u_int32_t));
4751 size = sopt->sopt_valsize;
4752 if (size == sizeof(u_int32_t)) /* delete or reassign */
4753 error = del_entry(&V_layer3_chain, rulenum[0]);
4754 else if (size == 2*sizeof(u_int32_t)) /* set enable/disable */
4756 (V_set_disable | rulenum[0]) & ~rulenum[1] &
4757 ~(1<<RESVD_SET); /* set RESVD_SET always enabled */
4763 case IP_FW_RESETLOG: /* argument is an u_int_32, the rule number */
4765 if (sopt->sopt_val != 0) {
4766 error = sooptcopyin(sopt, rulenum,
4767 sizeof(u_int32_t), sizeof(u_int32_t));
4771 error = zero_entry(&V_layer3_chain, rulenum[0],
4772 sopt->sopt_name == IP_FW_RESETLOG);
4775 case IP_FW_TABLE_ADD:
4777 ipfw_table_entry ent;
4779 error = sooptcopyin(sopt, &ent,
4780 sizeof(ent), sizeof(ent));
4783 error = add_table_entry(&V_layer3_chain, ent.tbl,
4784 ent.addr, ent.masklen, ent.value);
4788 case IP_FW_TABLE_DEL:
4790 ipfw_table_entry ent;
4792 error = sooptcopyin(sopt, &ent,
4793 sizeof(ent), sizeof(ent));
4796 error = del_table_entry(&V_layer3_chain, ent.tbl,
4797 ent.addr, ent.masklen);
4801 case IP_FW_TABLE_FLUSH:
4805 error = sooptcopyin(sopt, &tbl,
4806 sizeof(tbl), sizeof(tbl));
4809 IPFW_WLOCK(&V_layer3_chain);
4810 error = flush_table(&V_layer3_chain, tbl);
4811 IPFW_WUNLOCK(&V_layer3_chain);
4815 case IP_FW_TABLE_GETSIZE:
4819 if ((error = sooptcopyin(sopt, &tbl, sizeof(tbl),
4822 IPFW_RLOCK(&V_layer3_chain);
4823 error = count_table(&V_layer3_chain, tbl, &cnt);
4824 IPFW_RUNLOCK(&V_layer3_chain);
4827 error = sooptcopyout(sopt, &cnt, sizeof(cnt));
4831 case IP_FW_TABLE_LIST:
4835 if (sopt->sopt_valsize < sizeof(*tbl)) {
4839 size = sopt->sopt_valsize;
4840 tbl = malloc(size, M_TEMP, M_WAITOK);
4841 error = sooptcopyin(sopt, tbl, size, sizeof(*tbl));
4846 tbl->size = (size - sizeof(*tbl)) /
4847 sizeof(ipfw_table_entry);
4848 IPFW_RLOCK(&V_layer3_chain);
4849 error = dump_table(&V_layer3_chain, tbl);
4850 IPFW_RUNLOCK(&V_layer3_chain);
4855 error = sooptcopyout(sopt, tbl, size);
4861 if (IPFW_NAT_LOADED)
4862 error = ipfw_nat_cfg_ptr(sopt);
4864 printf("IP_FW_NAT_CFG: %s\n",
4865 "ipfw_nat not present, please load it");
4871 if (IPFW_NAT_LOADED)
4872 error = ipfw_nat_del_ptr(sopt);
4874 printf("IP_FW_NAT_DEL: %s\n",
4875 "ipfw_nat not present, please load it");
4880 case IP_FW_NAT_GET_CONFIG:
4881 if (IPFW_NAT_LOADED)
4882 error = ipfw_nat_get_cfg_ptr(sopt);
4884 printf("IP_FW_NAT_GET_CFG: %s\n",
4885 "ipfw_nat not present, please load it");
4890 case IP_FW_NAT_GET_LOG:
4891 if (IPFW_NAT_LOADED)
4892 error = ipfw_nat_get_log_ptr(sopt);
4894 printf("IP_FW_NAT_GET_LOG: %s\n",
4895 "ipfw_nat not present, please load it");
4901 printf("ipfw: ipfw_ctl invalid option %d\n", sopt->sopt_name);
4911 * This procedure is only used to handle keepalives. It is invoked
4912 * every dyn_keepalive_period
4915 ipfw_tick(void * vnetx)
4917 struct mbuf *m0, *m, *mnext, **mtailp;
4919 struct mbuf *m6, **m6_tailp;
4924 struct vnet *vp = vnetx;
4928 if (V_dyn_keepalive == 0 || V_ipfw_dyn_v == NULL || V_dyn_count == 0)
4932 * We make a chain of packets to go out here -- not deferring
4933 * until after we drop the IPFW dynamic rule lock would result
4934 * in a lock order reversal with the normal packet input -> ipfw
4944 for (i = 0 ; i < V_curr_dyn_buckets ; i++) {
4945 for (q = V_ipfw_dyn_v[i] ; q ; q = q->next ) {
4946 if (q->dyn_type == O_LIMIT_PARENT)
4948 if (q->id.proto != IPPROTO_TCP)
4950 if ( (q->state & BOTH_SYN) != BOTH_SYN)
4952 if (TIME_LEQ( time_uptime+V_dyn_keepalive_interval,
4954 continue; /* too early */
4955 if (TIME_LEQ(q->expire, time_uptime))
4956 continue; /* too late, rule expired */
4958 m = send_pkt(NULL, &(q->id), q->ack_rev - 1,
4959 q->ack_fwd, TH_SYN);
4960 mnext = send_pkt(NULL, &(q->id), q->ack_fwd - 1,
4963 switch (q->id.addr_type) {
4967 mtailp = &(*mtailp)->m_nextpkt;
4969 if (mnext != NULL) {
4971 mtailp = &(*mtailp)->m_nextpkt;
4978 m6_tailp = &(*m6_tailp)->m_nextpkt;
4980 if (mnext != NULL) {
4982 m6_tailp = &(*m6_tailp)->m_nextpkt;
4992 for (m = mnext = m0; m != NULL; m = mnext) {
4993 mnext = m->m_nextpkt;
4994 m->m_nextpkt = NULL;
4995 ip_output(m, NULL, NULL, 0, NULL, NULL);
4998 for (m = mnext = m6; m != NULL; m = mnext) {
4999 mnext = m->m_nextpkt;
5000 m->m_nextpkt = NULL;
5001 ip6_output(m, NULL, NULL, 0, NULL, NULL, NULL);
5005 callout_reset(&V_ipfw_timeout, V_dyn_keepalive_period*hz,
5010 static int vnet_ipfw_init(const void *);
5017 ipfw_dyn_rule_zone = uma_zcreate("IPFW dynamic rule",
5018 sizeof(ipfw_dyn_rule), NULL, NULL, NULL, NULL,
5021 IPFW_DYN_LOCK_INIT();
5022 error = vnet_ipfw_init(NULL);
5024 IPFW_DYN_LOCK_DESTROY();
5025 IPFW_LOCK_DESTROY(&V_layer3_chain);
5026 uma_zdestroy(ipfw_dyn_rule_zone);
5031 * Only print out this stuff the first time around,
5032 * when called from the sysinit code.
5038 "initialized, divert %s, nat %s, "
5039 "rule-based forwarding "
5040 #ifdef IPFIREWALL_FORWARD
5045 "default to %s, logging ",
5051 #ifdef IPFIREWALL_NAT
5056 default_to_accept ? "accept" : "deny");
5059 * Note: V_xxx variables can be accessed here but the vnet specific
5060 * initializer may not have been called yet for the VIMAGE case.
5061 * Tuneables will have been processed. We will print out values for
5063 * XXX This should all be rationalized AFTER 8.0
5065 if (V_fw_verbose == 0)
5066 printf("disabled\n");
5067 else if (V_verbose_limit == 0)
5068 printf("unlimited\n");
5070 printf("limited to %d packets/entry by default\n",
5081 ip_fw_chk_ptr = NULL;
5082 ip_fw_ctl_ptr = NULL;
5083 callout_drain(&ipfw_timeout);
5084 IPFW_WLOCK(&V_layer3_chain);
5085 flush_tables(&V_layer3_chain);
5086 V_layer3_chain.reap = NULL;
5087 free_chain(&V_layer3_chain, 1 /* kill default rule */);
5088 reap = V_layer3_chain.reap, V_layer3_chain.reap = NULL;
5089 IPFW_WUNLOCK(&V_layer3_chain);
5092 IPFW_DYN_LOCK_DESTROY();
5093 uma_zdestroy(ipfw_dyn_rule_zone);
5094 if (V_ipfw_dyn_v != NULL)
5095 free(V_ipfw_dyn_v, M_IPFW);
5096 IPFW_LOCK_DESTROY(&V_layer3_chain);
5099 /* Free IPv6 fw sysctl tree. */
5100 sysctl_ctx_free(&ip6_fw_sysctl_ctx);
5103 printf("IP firewall unloaded\n");
5107 * Stuff that must be initialized for every instance
5108 * (including the first of course).
5111 vnet_ipfw_init(const void *unused)
5114 struct ip_fw default_rule;
5116 /* First set up some values that are compile time options */
5117 #ifdef IPFIREWALL_VERBOSE
5120 #ifdef IPFIREWALL_VERBOSE_LIMIT
5121 V_verbose_limit = IPFIREWALL_VERBOSE_LIMIT;
5124 error = init_tables(&V_layer3_chain);
5126 panic("init_tables"); /* XXX Marko fix this ! */
5128 #ifdef IPFIREWALL_NAT
5129 LIST_INIT(&V_layer3_chain.nat);
5132 V_autoinc_step = 100; /* bounded to 1..1000 in add_rule() */
5134 V_ipfw_dyn_v = NULL;
5135 V_dyn_buckets = 256; /* must be power of 2 */
5136 V_curr_dyn_buckets = 256; /* must be power of 2 */
5138 V_dyn_ack_lifetime = 300;
5139 V_dyn_syn_lifetime = 20;
5140 V_dyn_fin_lifetime = 1;
5141 V_dyn_rst_lifetime = 1;
5142 V_dyn_udp_lifetime = 10;
5143 V_dyn_short_lifetime = 5;
5145 V_dyn_keepalive_interval = 20;
5146 V_dyn_keepalive_period = 5;
5147 V_dyn_keepalive = 1; /* do send keepalives */
5149 V_dyn_max = 4096; /* max # of dynamic rules */
5151 V_fw_deny_unknown_exthdrs = 1;
5153 V_layer3_chain.rules = NULL;
5154 IPFW_LOCK_INIT(&V_layer3_chain);
5155 callout_init(&V_ipfw_timeout, CALLOUT_MPSAFE);
5157 set_skipto_table(&V_layer3_chain);
5159 bzero(&default_rule, sizeof default_rule);
5160 default_rule.act_ofs = 0;
5161 default_rule.rulenum = IPFW_DEFAULT_RULE;
5162 default_rule.cmd_len = 1;
5163 default_rule.set = RESVD_SET;
5164 default_rule.cmd[0].len = 1;
5165 default_rule.cmd[0].opcode = default_to_accept ? O_ACCEPT : O_DENY;
5166 error = add_rule(&V_layer3_chain, &default_rule);
5169 printf("ipfw2: error %u initializing default rule "
5170 "(support disabled)\n", error);
5171 IPFW_LOCK_DESTROY(&V_layer3_chain);
5172 printf("leaving ipfw_iattach (1) with error %d\n", error);
5176 V_layer3_chain.default_rule = V_layer3_chain.rules;
5178 /* curvnet is NULL in the !VIMAGE case */
5179 callout_reset(&V_ipfw_timeout, hz, ipfw_tick, curvnet);
5181 /* First set up some values that are compile time options */
5182 V_ipfw_vnet_ready = 1; /* Open for business */
5185 * Hook the sockopt handler, and the layer2 (V_ip_fw_chk_ptr)
5186 * and pfil hooks for ipv4 and ipv6. Even if the latter two fail
5187 * we still keep the module alive because the sockopt and
5188 * layer2 paths are still useful.
5189 * ipfw[6]_hook return 0 on success, ENOENT on failure,
5190 * so we can ignore the exact return value and just set a flag.
5192 * Note that V_fw[6]_enable are manipulated by a SYSCTL_PROC so
5193 * changes in the underlying (per-vnet) variables trigger
5194 * immediate hook()/unhook() calls.
5195 * In layer2 we have the same behaviour, except that V_ether_ipfw
5196 * is checked on each packet because there are no pfil hooks.
5198 V_ip_fw_ctl_ptr = ipfw_ctl;
5199 V_ip_fw_chk_ptr = ipfw_chk;
5201 if (V_fw_enable && ipfw_hook() != 0) {
5202 error = ENOENT; /* see ip_fw_pfil.c::ipfw_hook() */
5203 printf("ipfw_hook() error\n");
5206 if (V_fw6_enable && ipfw6_hook() != 0) {
5208 printf("ipfw6_hook() error\n");