2 * Copyright (c) 2002 Luigi Rizzo, Universita` di Pisa
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
13 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
14 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
16 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
17 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
19 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
20 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
21 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 #include <sys/cdefs.h>
27 __FBSDID("$FreeBSD$");
33 * Implement IP packet firewall (new version)
36 #if !defined(KLD_MODULE)
38 #include "opt_ipdivert.h"
42 #error IPFIREWALL requires INET.
45 #include "opt_inet6.h"
46 #include "opt_ipsec.h"
48 #include <sys/param.h>
49 #include <sys/systm.h>
50 #include <sys/condvar.h>
51 #include <sys/eventhandler.h>
52 #include <sys/malloc.h>
54 #include <sys/kernel.h>
57 #include <sys/module.h>
60 #include <sys/rwlock.h>
61 #include <sys/socket.h>
62 #include <sys/socketvar.h>
63 #include <sys/sysctl.h>
64 #include <sys/syslog.h>
65 #include <sys/ucred.h>
66 #include <net/ethernet.h> /* for ETHERTYPE_IP */
68 #include <net/radix.h>
69 #include <net/route.h>
70 #include <net/pf_mtag.h>
73 #define IPFW_INTERNAL /* Access to protected data structures in ip_fw.h. */
75 #include <netinet/in.h>
76 #include <netinet/in_var.h>
77 #include <netinet/in_pcb.h>
78 #include <netinet/ip.h>
79 #include <netinet/ip_var.h>
80 #include <netinet/ip_icmp.h>
81 #include <netinet/ip_fw.h>
82 #include <netinet/ip_divert.h>
83 #include <netinet/ip_dummynet.h>
84 #include <netinet/ip_carp.h>
85 #include <netinet/pim.h>
86 #include <netinet/tcp_var.h>
87 #include <netinet/udp.h>
88 #include <netinet/udp_var.h>
89 #include <netinet/sctp.h>
91 #include <netgraph/ng_ipfw.h>
93 #include <netinet/ip6.h>
94 #include <netinet/icmp6.h>
96 #include <netinet6/scope6_var.h>
99 #include <machine/in_cksum.h> /* XXX for in_cksum */
102 #include <security/mac/mac_framework.h>
105 static VNET_DEFINE(int, ipfw_vnet_ready) = 0;
106 #define V_ipfw_vnet_ready VNET(ipfw_vnet_ready)
108 * set_disable contains one bit per set value (0..31).
109 * If the bit is set, all rules with the corresponding set
110 * are disabled. Set RESVD_SET(31) is reserved for the default rule
111 * and rules that are not deleted by the flush command,
112 * and CANNOT be disabled.
113 * Rules in set RESVD_SET can only be deleted explicitly.
115 static VNET_DEFINE(u_int32_t, set_disable);
116 static VNET_DEFINE(int, fw_verbose);
117 static VNET_DEFINE(struct callout, ipfw_timeout);
118 static VNET_DEFINE(int, verbose_limit);
120 #define V_set_disable VNET(set_disable)
121 #define V_fw_verbose VNET(fw_verbose)
122 #define V_ipfw_timeout VNET(ipfw_timeout)
123 #define V_verbose_limit VNET(verbose_limit)
125 #ifdef IPFIREWALL_DEFAULT_TO_ACCEPT
126 static int default_to_accept = 1;
128 static int default_to_accept;
130 static uma_zone_t ipfw_dyn_rule_zone;
132 struct ip_fw *ip_fw_default_rule;
135 * list of rules for layer 3
137 VNET_DEFINE(struct ip_fw_chain, layer3_chain);
139 MALLOC_DEFINE(M_IPFW, "IpFw/IpAcct", "IpFw/IpAcct chain's");
140 MALLOC_DEFINE(M_IPFW_TBL, "ipfw_tbl", "IpFw tables");
141 #define IPFW_NAT_LOADED (ipfw_nat_ptr != NULL)
142 ipfw_nat_t *ipfw_nat_ptr = NULL;
143 ipfw_nat_cfg_t *ipfw_nat_cfg_ptr;
144 ipfw_nat_cfg_t *ipfw_nat_del_ptr;
145 ipfw_nat_cfg_t *ipfw_nat_get_cfg_ptr;
146 ipfw_nat_cfg_t *ipfw_nat_get_log_ptr;
149 struct radix_node rn[2];
150 struct sockaddr_in addr, mask;
154 static VNET_DEFINE(int, autoinc_step);
155 #define V_autoinc_step VNET(autoinc_step)
156 static VNET_DEFINE(int, fw_deny_unknown_exthdrs);
157 #define V_fw_deny_unknown_exthdrs VNET(fw_deny_unknown_exthdrs)
159 extern int ipfw_chg_hook(SYSCTL_HANDLER_ARGS);
162 SYSCTL_NODE(_net_inet_ip, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall");
163 SYSCTL_VNET_PROC(_net_inet_ip_fw, OID_AUTO, enable,
164 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE3, &VNET_NAME(fw_enable), 0,
165 ipfw_chg_hook, "I", "Enable ipfw");
166 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, autoinc_step,
167 CTLFLAG_RW, &VNET_NAME(autoinc_step), 0,
168 "Rule number auto-increment step");
169 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, one_pass,
170 CTLFLAG_RW | CTLFLAG_SECURE3, &VNET_NAME(fw_one_pass), 0,
171 "Only do a single pass through ipfw when using dummynet(4)");
172 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, verbose,
173 CTLFLAG_RW | CTLFLAG_SECURE3, &VNET_NAME(fw_verbose), 0,
174 "Log matches to ipfw rules");
175 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, verbose_limit,
176 CTLFLAG_RW, &VNET_NAME(verbose_limit), 0,
177 "Set upper limit of matches of ipfw rules logged");
178 SYSCTL_UINT(_net_inet_ip_fw, OID_AUTO, default_rule, CTLFLAG_RD,
179 NULL, IPFW_DEFAULT_RULE,
180 "The default/max possible rule number.");
181 SYSCTL_UINT(_net_inet_ip_fw, OID_AUTO, tables_max, CTLFLAG_RD,
182 NULL, IPFW_TABLES_MAX,
183 "The maximum number of tables.");
184 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, default_to_accept, CTLFLAG_RDTUN,
185 &default_to_accept, 0,
186 "Make the default rule accept all packets.");
187 TUNABLE_INT("net.inet.ip.fw.default_to_accept", &default_to_accept);
189 SYSCTL_DECL(_net_inet6_ip6);
190 SYSCTL_NODE(_net_inet6_ip6, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall");
191 SYSCTL_VNET_PROC(_net_inet6_ip6_fw, OID_AUTO, enable,
192 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE3, &VNET_NAME(fw6_enable), 0,
193 ipfw_chg_hook, "I", "Enable ipfw+6");
194 SYSCTL_VNET_INT(_net_inet6_ip6_fw, OID_AUTO, deny_unknown_exthdrs,
195 CTLFLAG_RW | CTLFLAG_SECURE, &VNET_NAME(fw_deny_unknown_exthdrs), 0,
196 "Deny packets with unknown IPv6 Extension Headers");
201 * Description of dynamic rules.
203 * Dynamic rules are stored in lists accessed through a hash table
204 * (ipfw_dyn_v) whose size is curr_dyn_buckets. This value can
205 * be modified through the sysctl variable dyn_buckets which is
206 * updated when the table becomes empty.
208 * XXX currently there is only one list, ipfw_dyn.
210 * When a packet is received, its address fields are first masked
211 * with the mask defined for the rule, then hashed, then matched
212 * against the entries in the corresponding list.
213 * Dynamic rules can be used for different purposes:
215 * + enforcing limits on the number of sessions;
216 * + in-kernel NAT (not implemented yet)
218 * The lifetime of dynamic rules is regulated by dyn_*_lifetime,
219 * measured in seconds and depending on the flags.
221 * The total number of dynamic rules is stored in dyn_count.
222 * The max number of dynamic rules is dyn_max. When we reach
223 * the maximum number of rules we do not create anymore. This is
224 * done to avoid consuming too much memory, but also too much
225 * time when searching on each packet (ideally, we should try instead
226 * to put a limit on the length of the list on each bucket...).
228 * Each dynamic rule holds a pointer to the parent ipfw rule so
229 * we know what action to perform. Dynamic rules are removed when
230 * the parent rule is deleted. XXX we should make them survive.
232 * There are some limitations with dynamic rules -- we do not
233 * obey the 'randomized match', and we do not do multiple
234 * passes through the firewall. XXX check the latter!!!
236 static VNET_DEFINE(ipfw_dyn_rule **, ipfw_dyn_v);
237 static VNET_DEFINE(u_int32_t, dyn_buckets);
238 static VNET_DEFINE(u_int32_t, curr_dyn_buckets);
240 #define V_ipfw_dyn_v VNET(ipfw_dyn_v)
241 #define V_dyn_buckets VNET(dyn_buckets)
242 #define V_curr_dyn_buckets VNET(curr_dyn_buckets)
244 static struct mtx ipfw_dyn_mtx; /* mutex guarding dynamic rules */
245 #define IPFW_DYN_LOCK_INIT() \
246 mtx_init(&ipfw_dyn_mtx, "IPFW dynamic rules", NULL, MTX_DEF)
247 #define IPFW_DYN_LOCK_DESTROY() mtx_destroy(&ipfw_dyn_mtx)
248 #define IPFW_DYN_LOCK() mtx_lock(&ipfw_dyn_mtx)
249 #define IPFW_DYN_UNLOCK() mtx_unlock(&ipfw_dyn_mtx)
250 #define IPFW_DYN_LOCK_ASSERT() mtx_assert(&ipfw_dyn_mtx, MA_OWNED)
253 * Timeouts for various events in handing dynamic rules.
255 static VNET_DEFINE(u_int32_t, dyn_ack_lifetime);
256 static VNET_DEFINE(u_int32_t, dyn_syn_lifetime);
257 static VNET_DEFINE(u_int32_t, dyn_fin_lifetime);
258 static VNET_DEFINE(u_int32_t, dyn_rst_lifetime);
259 static VNET_DEFINE(u_int32_t, dyn_udp_lifetime);
260 static VNET_DEFINE(u_int32_t, dyn_short_lifetime);
262 #define V_dyn_ack_lifetime VNET(dyn_ack_lifetime)
263 #define V_dyn_syn_lifetime VNET(dyn_syn_lifetime)
264 #define V_dyn_fin_lifetime VNET(dyn_fin_lifetime)
265 #define V_dyn_rst_lifetime VNET(dyn_rst_lifetime)
266 #define V_dyn_udp_lifetime VNET(dyn_udp_lifetime)
267 #define V_dyn_short_lifetime VNET(dyn_short_lifetime)
270 * Keepalives are sent if dyn_keepalive is set. They are sent every
271 * dyn_keepalive_period seconds, in the last dyn_keepalive_interval
272 * seconds of lifetime of a rule.
273 * dyn_rst_lifetime and dyn_fin_lifetime should be strictly lower
274 * than dyn_keepalive_period.
277 static VNET_DEFINE(u_int32_t, dyn_keepalive_interval);
278 static VNET_DEFINE(u_int32_t, dyn_keepalive_period);
279 static VNET_DEFINE(u_int32_t, dyn_keepalive);
281 #define V_dyn_keepalive_interval VNET(dyn_keepalive_interval)
282 #define V_dyn_keepalive_period VNET(dyn_keepalive_period)
283 #define V_dyn_keepalive VNET(dyn_keepalive)
285 static VNET_DEFINE(u_int32_t, static_count); /* # of static rules */
286 static VNET_DEFINE(u_int32_t, static_len); /* bytes of static rules */
287 static VNET_DEFINE(u_int32_t, dyn_count); /* # of dynamic rules */
288 static VNET_DEFINE(u_int32_t, dyn_max); /* max # of dynamic rules */
290 #define V_static_count VNET(static_count)
291 #define V_static_len VNET(static_len)
292 #define V_dyn_count VNET(dyn_count)
293 #define V_dyn_max VNET(dyn_max)
296 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_buckets,
297 CTLFLAG_RW, &VNET_NAME(dyn_buckets), 0,
298 "Number of dyn. buckets");
299 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, curr_dyn_buckets,
300 CTLFLAG_RD, &VNET_NAME(curr_dyn_buckets), 0,
301 "Current Number of dyn. buckets");
302 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_count,
303 CTLFLAG_RD, &VNET_NAME(dyn_count), 0,
304 "Number of dyn. rules");
305 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_max,
306 CTLFLAG_RW, &VNET_NAME(dyn_max), 0,
307 "Max number of dyn. rules");
308 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, static_count,
309 CTLFLAG_RD, &VNET_NAME(static_count), 0,
310 "Number of static rules");
311 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_ack_lifetime,
312 CTLFLAG_RW, &VNET_NAME(dyn_ack_lifetime), 0,
313 "Lifetime of dyn. rules for acks");
314 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_syn_lifetime,
315 CTLFLAG_RW, &VNET_NAME(dyn_syn_lifetime), 0,
316 "Lifetime of dyn. rules for syn");
317 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_fin_lifetime,
318 CTLFLAG_RW, &VNET_NAME(dyn_fin_lifetime), 0,
319 "Lifetime of dyn. rules for fin");
320 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_rst_lifetime,
321 CTLFLAG_RW, &VNET_NAME(dyn_rst_lifetime), 0,
322 "Lifetime of dyn. rules for rst");
323 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_udp_lifetime,
324 CTLFLAG_RW, &VNET_NAME(dyn_udp_lifetime), 0,
325 "Lifetime of dyn. rules for UDP");
326 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_short_lifetime,
327 CTLFLAG_RW, &VNET_NAME(dyn_short_lifetime), 0,
328 "Lifetime of dyn. rules for other situations");
329 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_keepalive,
330 CTLFLAG_RW, &VNET_NAME(dyn_keepalive), 0,
331 "Enable keepalives for dyn. rules");
332 #endif /* SYSCTL_NODE */
335 * L3HDR maps an ipv4 pointer into a layer3 header pointer of type T
336 * Other macros just cast void * into the appropriate type
338 #define L3HDR(T, ip) ((T *)((u_int32_t *)(ip) + (ip)->ip_hl))
339 #define TCP(p) ((struct tcphdr *)(p))
340 #define SCTP(p) ((struct sctphdr *)(p))
341 #define UDP(p) ((struct udphdr *)(p))
342 #define ICMP(p) ((struct icmphdr *)(p))
343 #define ICMP6(p) ((struct icmp6_hdr *)(p))
346 icmptype_match(struct icmphdr *icmp, ipfw_insn_u32 *cmd)
348 int type = icmp->icmp_type;
350 return (type <= ICMP_MAXTYPE && (cmd->d[0] & (1<<type)) );
353 #define TT ( (1 << ICMP_ECHO) | (1 << ICMP_ROUTERSOLICIT) | \
354 (1 << ICMP_TSTAMP) | (1 << ICMP_IREQ) | (1 << ICMP_MASKREQ) )
357 is_icmp_query(struct icmphdr *icmp)
359 int type = icmp->icmp_type;
361 return (type <= ICMP_MAXTYPE && (TT & (1<<type)) );
366 * The following checks use two arrays of 8 or 16 bits to store the
367 * bits that we want set or clear, respectively. They are in the
368 * low and high half of cmd->arg1 or cmd->d[0].
370 * We scan options and store the bits we find set. We succeed if
372 * (want_set & ~bits) == 0 && (want_clear & ~bits) == want_clear
374 * The code is sometimes optimized not to store additional variables.
378 flags_match(ipfw_insn *cmd, u_int8_t bits)
383 if ( ((cmd->arg1 & 0xff) & bits) != 0)
384 return 0; /* some bits we want set were clear */
385 want_clear = (cmd->arg1 >> 8) & 0xff;
386 if ( (want_clear & bits) != want_clear)
387 return 0; /* some bits we want clear were set */
392 ipopts_match(struct ip *ip, ipfw_insn *cmd)
394 int optlen, bits = 0;
395 u_char *cp = (u_char *)(ip + 1);
396 int x = (ip->ip_hl << 2) - sizeof (struct ip);
398 for (; x > 0; x -= optlen, cp += optlen) {
399 int opt = cp[IPOPT_OPTVAL];
401 if (opt == IPOPT_EOL)
403 if (opt == IPOPT_NOP)
406 optlen = cp[IPOPT_OLEN];
407 if (optlen <= 0 || optlen > x)
408 return 0; /* invalid or truncated */
416 bits |= IP_FW_IPOPT_LSRR;
420 bits |= IP_FW_IPOPT_SSRR;
424 bits |= IP_FW_IPOPT_RR;
428 bits |= IP_FW_IPOPT_TS;
432 return (flags_match(cmd, bits));
436 tcpopts_match(struct tcphdr *tcp, ipfw_insn *cmd)
438 int optlen, bits = 0;
439 u_char *cp = (u_char *)(tcp + 1);
440 int x = (tcp->th_off << 2) - sizeof(struct tcphdr);
442 for (; x > 0; x -= optlen, cp += optlen) {
444 if (opt == TCPOPT_EOL)
446 if (opt == TCPOPT_NOP)
460 bits |= IP_FW_TCPOPT_MSS;
464 bits |= IP_FW_TCPOPT_WINDOW;
467 case TCPOPT_SACK_PERMITTED:
469 bits |= IP_FW_TCPOPT_SACK;
472 case TCPOPT_TIMESTAMP:
473 bits |= IP_FW_TCPOPT_TS;
478 return (flags_match(cmd, bits));
482 iface_match(struct ifnet *ifp, ipfw_insn_if *cmd)
484 if (ifp == NULL) /* no iface with this packet, match fails */
486 /* Check by name or by IP address */
487 if (cmd->name[0] != '\0') { /* match by name */
490 if (fnmatch(cmd->name, ifp->if_xname, 0) == 0)
493 if (strncmp(ifp->if_xname, cmd->name, IFNAMSIZ) == 0)
500 TAILQ_FOREACH(ia, &ifp->if_addrhead, ifa_link) {
501 if (ia->ifa_addr->sa_family != AF_INET)
503 if (cmd->p.ip.s_addr == ((struct sockaddr_in *)
504 (ia->ifa_addr))->sin_addr.s_addr) {
505 if_addr_runlock(ifp);
506 return(1); /* match */
509 if_addr_runlock(ifp);
511 return(0); /* no match, fail ... */
515 * The verify_path function checks if a route to the src exists and
516 * if it is reachable via ifp (when provided).
518 * The 'verrevpath' option checks that the interface that an IP packet
519 * arrives on is the same interface that traffic destined for the
520 * packet's source address would be routed out of. The 'versrcreach'
521 * option just checks that the source address is reachable via any route
522 * (except default) in the routing table. These two are a measure to block
523 * forged packets. This is also commonly known as "anti-spoofing" or Unicast
524 * Reverse Path Forwarding (Unicast RFP) in Cisco-ese. The name of the knobs
525 * is purposely reminiscent of the Cisco IOS command,
527 * ip verify unicast reverse-path
528 * ip verify unicast source reachable-via any
530 * which implements the same functionality. But note that syntax is
531 * misleading. The check may be performed on all IP packets whether unicast,
532 * multicast, or broadcast.
535 verify_path(struct in_addr src, struct ifnet *ifp, u_int fib)
538 struct sockaddr_in *dst;
540 bzero(&ro, sizeof(ro));
542 dst = (struct sockaddr_in *)&(ro.ro_dst);
543 dst->sin_family = AF_INET;
544 dst->sin_len = sizeof(*dst);
546 in_rtalloc_ign(&ro, 0, fib);
548 if (ro.ro_rt == NULL)
552 * If ifp is provided, check for equality with rtentry.
553 * We should use rt->rt_ifa->ifa_ifp, instead of rt->rt_ifp,
554 * in order to pass packets injected back by if_simloop():
555 * if useloopback == 1 routing entry (via lo0) for our own address
556 * may exist, so we need to handle routing assymetry.
558 if (ifp != NULL && ro.ro_rt->rt_ifa->ifa_ifp != ifp) {
563 /* if no ifp provided, check if rtentry is not default route */
565 satosin(rt_key(ro.ro_rt))->sin_addr.s_addr == INADDR_ANY) {
570 /* or if this is a blackhole/reject route */
571 if (ifp == NULL && ro.ro_rt->rt_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
576 /* found valid route */
583 * ipv6 specific rules here...
586 icmp6type_match (int type, ipfw_insn_u32 *cmd)
588 return (type <= ICMP6_MAXTYPE && (cmd->d[type/32] & (1<<(type%32)) ) );
592 flow6id_match( int curr_flow, ipfw_insn_u32 *cmd )
595 for (i=0; i <= cmd->o.arg1; ++i )
596 if (curr_flow == cmd->d[i] )
601 /* support for IP6_*_ME opcodes */
603 search_ip6_addr_net (struct in6_addr * ip6_addr)
607 struct in6_ifaddr *fdm;
608 struct in6_addr copia;
610 TAILQ_FOREACH(mdc, &V_ifnet, if_link) {
612 TAILQ_FOREACH(mdc2, &mdc->if_addrhead, ifa_link) {
613 if (mdc2->ifa_addr->sa_family == AF_INET6) {
614 fdm = (struct in6_ifaddr *)mdc2;
615 copia = fdm->ia_addr.sin6_addr;
616 /* need for leaving scope_id in the sock_addr */
617 in6_clearscope(&copia);
618 if (IN6_ARE_ADDR_EQUAL(ip6_addr, &copia)) {
619 if_addr_runlock(mdc);
624 if_addr_runlock(mdc);
630 verify_path6(struct in6_addr *src, struct ifnet *ifp)
633 struct sockaddr_in6 *dst;
635 bzero(&ro, sizeof(ro));
637 dst = (struct sockaddr_in6 * )&(ro.ro_dst);
638 dst->sin6_family = AF_INET6;
639 dst->sin6_len = sizeof(*dst);
640 dst->sin6_addr = *src;
641 /* XXX MRT 0 for ipv6 at this time */
642 rtalloc_ign((struct route *)&ro, 0);
644 if (ro.ro_rt == NULL)
648 * if ifp is provided, check for equality with rtentry
649 * We should use rt->rt_ifa->ifa_ifp, instead of rt->rt_ifp,
650 * to support the case of sending packets to an address of our own.
651 * (where the former interface is the first argument of if_simloop()
652 * (=ifp), the latter is lo0)
654 if (ifp != NULL && ro.ro_rt->rt_ifa->ifa_ifp != ifp) {
659 /* if no ifp provided, check if rtentry is not default route */
661 IN6_IS_ADDR_UNSPECIFIED(&satosin6(rt_key(ro.ro_rt))->sin6_addr)) {
666 /* or if this is a blackhole/reject route */
667 if (ifp == NULL && ro.ro_rt->rt_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
672 /* found valid route */
678 hash_packet6(struct ipfw_flow_id *id)
681 i = (id->dst_ip6.__u6_addr.__u6_addr32[2]) ^
682 (id->dst_ip6.__u6_addr.__u6_addr32[3]) ^
683 (id->src_ip6.__u6_addr.__u6_addr32[2]) ^
684 (id->src_ip6.__u6_addr.__u6_addr32[3]) ^
685 (id->dst_port) ^ (id->src_port);
690 is_icmp6_query(int icmp6_type)
692 if ((icmp6_type <= ICMP6_MAXTYPE) &&
693 (icmp6_type == ICMP6_ECHO_REQUEST ||
694 icmp6_type == ICMP6_MEMBERSHIP_QUERY ||
695 icmp6_type == ICMP6_WRUREQUEST ||
696 icmp6_type == ICMP6_FQDN_QUERY ||
697 icmp6_type == ICMP6_NI_QUERY))
704 send_reject6(struct ip_fw_args *args, int code, u_int hlen, struct ip6_hdr *ip6)
709 if (code == ICMP6_UNREACH_RST && args->f_id.proto == IPPROTO_TCP) {
717 tcp = (struct tcphdr *)((char *)ip6 + hlen);
719 if ((tcp->th_flags & TH_RST) != 0) {
727 ti.th.th_seq = ntohl(ti.th.th_seq);
728 ti.th.th_ack = ntohl(ti.th.th_ack);
729 ti.ip6.ip6_nxt = IPPROTO_TCP;
731 if (ti.th.th_flags & TH_ACK) {
737 if ((m->m_flags & M_PKTHDR) != 0) {
739 * total new data to ACK is:
740 * total packet length,
741 * minus the header length,
742 * minus the tcp header length.
744 ack += m->m_pkthdr.len - hlen
745 - (ti.th.th_off << 2);
746 } else if (ip6->ip6_plen) {
747 ack += ntohs(ip6->ip6_plen) + sizeof(*ip6) -
748 hlen - (ti.th.th_off << 2);
753 if (tcp->th_flags & TH_SYN)
756 flags = TH_RST|TH_ACK;
758 bcopy(&ti, ip6, sizeof(ti));
760 * m is only used to recycle the mbuf
761 * The data in it is never read so we don't need
762 * to correct the offsets or anything
764 tcp_respond(NULL, ip6, tcp, m, ack, seq, flags);
765 } else if (code != ICMP6_UNREACH_RST) { /* Send an ICMPv6 unreach. */
768 * Unlike above, the mbufs need to line up with the ip6 hdr,
769 * as the contents are read. We need to m_adj() the
771 * The mbuf will however be thrown away so we can adjust it.
772 * Remember we did an m_pullup on it already so we
773 * can make some assumptions about contiguousness.
776 m_adj(m, args->L3offset);
778 icmp6_error(m, ICMP6_DST_UNREACH, code, 0);
787 /* counter for ipfw_log(NULL...) */
788 static VNET_DEFINE(u_int64_t, norule_counter);
789 #define V_norule_counter VNET(norule_counter)
791 #define SNPARGS(buf, len) buf + len, sizeof(buf) > len ? sizeof(buf) - len : 0
792 #define SNP(buf) buf, sizeof(buf)
795 * We enter here when we have a rule with O_LOG.
796 * XXX this function alone takes about 2Kbytes of code!
799 ipfw_log(struct ip_fw *f, u_int hlen, struct ip_fw_args *args,
800 struct mbuf *m, struct ifnet *oif, u_short offset, uint32_t tablearg,
803 struct ether_header *eh = args->eh;
805 int limit_reached = 0;
806 char action2[40], proto[128], fragment[32];
811 if (f == NULL) { /* bogus pkt */
812 if (V_verbose_limit != 0 && V_norule_counter >= V_verbose_limit)
815 if (V_norule_counter == V_verbose_limit)
816 limit_reached = V_verbose_limit;
818 } else { /* O_LOG is the first action, find the real one */
819 ipfw_insn *cmd = ACTION_PTR(f);
820 ipfw_insn_log *l = (ipfw_insn_log *)cmd;
822 if (l->max_log != 0 && l->log_left == 0)
825 if (l->log_left == 0)
826 limit_reached = l->max_log;
827 cmd += F_LEN(cmd); /* point to first action */
828 if (cmd->opcode == O_ALTQ) {
829 ipfw_insn_altq *altq = (ipfw_insn_altq *)cmd;
831 snprintf(SNPARGS(action2, 0), "Altq %d",
835 if (cmd->opcode == O_PROB)
838 if (cmd->opcode == O_TAG)
842 switch (cmd->opcode) {
848 if (cmd->arg1==ICMP_REJECT_RST)
850 else if (cmd->arg1==ICMP_UNREACH_HOST)
853 snprintf(SNPARGS(action2, 0), "Unreach %d",
858 if (cmd->arg1==ICMP6_UNREACH_RST)
861 snprintf(SNPARGS(action2, 0), "Unreach %d",
872 snprintf(SNPARGS(action2, 0), "Divert %d",
876 snprintf(SNPARGS(action2, 0), "Tee %d",
880 snprintf(SNPARGS(action2, 0), "SetFib %d",
884 snprintf(SNPARGS(action2, 0), "SkipTo %d",
888 snprintf(SNPARGS(action2, 0), "Pipe %d",
892 snprintf(SNPARGS(action2, 0), "Queue %d",
896 ipfw_insn_sa *sa = (ipfw_insn_sa *)cmd;
898 struct in_addr dummyaddr;
899 if (sa->sa.sin_addr.s_addr == INADDR_ANY)
900 dummyaddr.s_addr = htonl(tablearg);
902 dummyaddr.s_addr = sa->sa.sin_addr.s_addr;
904 len = snprintf(SNPARGS(action2, 0), "Forward to %s",
905 inet_ntoa(dummyaddr));
908 snprintf(SNPARGS(action2, len), ":%d",
913 snprintf(SNPARGS(action2, 0), "Netgraph %d",
917 snprintf(SNPARGS(action2, 0), "Ngtee %d",
932 if (hlen == 0) { /* non-ip */
933 snprintf(SNPARGS(proto, 0), "MAC");
937 char src[48], dst[48];
938 struct icmphdr *icmp;
942 struct ip6_hdr *ip6 = NULL;
943 struct icmp6_hdr *icmp6;
948 if (IS_IP6_FLOW_ID(&(args->f_id))) {
949 char ip6buf[INET6_ADDRSTRLEN];
950 snprintf(src, sizeof(src), "[%s]",
951 ip6_sprintf(ip6buf, &args->f_id.src_ip6));
952 snprintf(dst, sizeof(dst), "[%s]",
953 ip6_sprintf(ip6buf, &args->f_id.dst_ip6));
955 ip6 = (struct ip6_hdr *)ip;
956 tcp = (struct tcphdr *)(((char *)ip) + hlen);
957 udp = (struct udphdr *)(((char *)ip) + hlen);
961 tcp = L3HDR(struct tcphdr, ip);
962 udp = L3HDR(struct udphdr, ip);
964 inet_ntoa_r(ip->ip_src, src);
965 inet_ntoa_r(ip->ip_dst, dst);
968 switch (args->f_id.proto) {
970 len = snprintf(SNPARGS(proto, 0), "TCP %s", src);
972 snprintf(SNPARGS(proto, len), ":%d %s:%d",
973 ntohs(tcp->th_sport),
975 ntohs(tcp->th_dport));
977 snprintf(SNPARGS(proto, len), " %s", dst);
981 len = snprintf(SNPARGS(proto, 0), "UDP %s", src);
983 snprintf(SNPARGS(proto, len), ":%d %s:%d",
984 ntohs(udp->uh_sport),
986 ntohs(udp->uh_dport));
988 snprintf(SNPARGS(proto, len), " %s", dst);
992 icmp = L3HDR(struct icmphdr, ip);
994 len = snprintf(SNPARGS(proto, 0),
996 icmp->icmp_type, icmp->icmp_code);
998 len = snprintf(SNPARGS(proto, 0), "ICMP ");
999 len += snprintf(SNPARGS(proto, len), "%s", src);
1000 snprintf(SNPARGS(proto, len), " %s", dst);
1003 case IPPROTO_ICMPV6:
1004 icmp6 = (struct icmp6_hdr *)(((char *)ip) + hlen);
1006 len = snprintf(SNPARGS(proto, 0),
1008 icmp6->icmp6_type, icmp6->icmp6_code);
1010 len = snprintf(SNPARGS(proto, 0), "ICMPv6 ");
1011 len += snprintf(SNPARGS(proto, len), "%s", src);
1012 snprintf(SNPARGS(proto, len), " %s", dst);
1016 len = snprintf(SNPARGS(proto, 0), "P:%d %s",
1017 args->f_id.proto, src);
1018 snprintf(SNPARGS(proto, len), " %s", dst);
1023 if (IS_IP6_FLOW_ID(&(args->f_id))) {
1024 if (offset & (IP6F_OFF_MASK | IP6F_MORE_FRAG))
1025 snprintf(SNPARGS(fragment, 0),
1026 " (frag %08x:%d@%d%s)",
1027 args->f_id.frag_id6,
1028 ntohs(ip6->ip6_plen) - hlen,
1029 ntohs(offset & IP6F_OFF_MASK) << 3,
1030 (offset & IP6F_MORE_FRAG) ? "+" : "");
1035 if (eh != NULL) { /* layer 2 packets are as on the wire */
1036 ip_off = ntohs(ip->ip_off);
1037 ip_len = ntohs(ip->ip_len);
1039 ip_off = ip->ip_off;
1040 ip_len = ip->ip_len;
1042 if (ip_off & (IP_MF | IP_OFFMASK))
1043 snprintf(SNPARGS(fragment, 0),
1044 " (frag %d:%d@%d%s)",
1045 ntohs(ip->ip_id), ip_len - (ip->ip_hl << 2),
1047 (ip_off & IP_MF) ? "+" : "");
1050 if (oif || m->m_pkthdr.rcvif)
1051 log(LOG_SECURITY | LOG_INFO,
1052 "ipfw: %d %s %s %s via %s%s\n",
1053 f ? f->rulenum : -1,
1054 action, proto, oif ? "out" : "in",
1055 oif ? oif->if_xname : m->m_pkthdr.rcvif->if_xname,
1058 log(LOG_SECURITY | LOG_INFO,
1059 "ipfw: %d %s %s [no if info]%s\n",
1060 f ? f->rulenum : -1,
1061 action, proto, fragment);
1063 log(LOG_SECURITY | LOG_NOTICE,
1064 "ipfw: limit %d reached on entry %d\n",
1065 limit_reached, f ? f->rulenum : -1);
1069 * IMPORTANT: the hash function for dynamic rules must be commutative
1070 * in source and destination (ip,port), because rules are bidirectional
1071 * and we want to find both in the same bucket.
1074 hash_packet(struct ipfw_flow_id *id)
1079 if (IS_IP6_FLOW_ID(id))
1080 i = hash_packet6(id);
1083 i = (id->dst_ip) ^ (id->src_ip) ^ (id->dst_port) ^ (id->src_port);
1084 i &= (V_curr_dyn_buckets - 1);
1089 * unlink a dynamic rule from a chain. prev is a pointer to
1090 * the previous one, q is a pointer to the rule to delete,
1091 * head is a pointer to the head of the queue.
1092 * Modifies q and potentially also head.
1094 #define UNLINK_DYN_RULE(prev, head, q) { \
1095 ipfw_dyn_rule *old_q = q; \
1097 /* remove a refcount to the parent */ \
1098 if (q->dyn_type == O_LIMIT) \
1099 q->parent->count--; \
1100 DEB(printf("ipfw: unlink entry 0x%08x %d -> 0x%08x %d, %d left\n",\
1101 (q->id.src_ip), (q->id.src_port), \
1102 (q->id.dst_ip), (q->id.dst_port), V_dyn_count-1 ); ) \
1104 prev->next = q = q->next; \
1106 head = q = q->next; \
1108 uma_zfree(ipfw_dyn_rule_zone, old_q); }
1110 #define TIME_LEQ(a,b) ((int)((a)-(b)) <= 0)
1113 * Remove dynamic rules pointing to "rule", or all of them if rule == NULL.
1115 * If keep_me == NULL, rules are deleted even if not expired,
1116 * otherwise only expired rules are removed.
1118 * The value of the second parameter is also used to point to identify
1119 * a rule we absolutely do not want to remove (e.g. because we are
1120 * holding a reference to it -- this is the case with O_LIMIT_PARENT
1121 * rules). The pointer is only used for comparison, so any non-null
1125 remove_dyn_rule(struct ip_fw *rule, ipfw_dyn_rule *keep_me)
1127 static u_int32_t last_remove = 0;
1129 #define FORCE (keep_me == NULL)
1131 ipfw_dyn_rule *prev, *q;
1132 int i, pass = 0, max_pass = 0;
1134 IPFW_DYN_LOCK_ASSERT();
1136 if (V_ipfw_dyn_v == NULL || V_dyn_count == 0)
1138 /* do not expire more than once per second, it is useless */
1139 if (!FORCE && last_remove == time_uptime)
1141 last_remove = time_uptime;
1144 * because O_LIMIT refer to parent rules, during the first pass only
1145 * remove child and mark any pending LIMIT_PARENT, and remove
1146 * them in a second pass.
1149 for (i = 0 ; i < V_curr_dyn_buckets ; i++) {
1150 for (prev=NULL, q = V_ipfw_dyn_v[i] ; q ; ) {
1152 * Logic can become complex here, so we split tests.
1156 if (rule != NULL && rule != q->rule)
1157 goto next; /* not the one we are looking for */
1158 if (q->dyn_type == O_LIMIT_PARENT) {
1160 * handle parent in the second pass,
1161 * record we need one.
1166 if (FORCE && q->count != 0 ) {
1167 /* XXX should not happen! */
1168 printf("ipfw: OUCH! cannot remove rule,"
1169 " count %d\n", q->count);
1173 !TIME_LEQ( q->expire, time_uptime ))
1176 if (q->dyn_type != O_LIMIT_PARENT || !q->count) {
1177 UNLINK_DYN_RULE(prev, V_ipfw_dyn_v[i], q);
1185 if (pass++ < max_pass)
1191 * lookup a dynamic rule.
1193 static ipfw_dyn_rule *
1194 lookup_dyn_rule_locked(struct ipfw_flow_id *pkt, int *match_direction,
1198 * stateful ipfw extensions.
1199 * Lookup into dynamic session queue
1201 #define MATCH_REVERSE 0
1202 #define MATCH_FORWARD 1
1203 #define MATCH_NONE 2
1204 #define MATCH_UNKNOWN 3
1205 int i, dir = MATCH_NONE;
1206 ipfw_dyn_rule *prev, *q=NULL;
1208 IPFW_DYN_LOCK_ASSERT();
1210 if (V_ipfw_dyn_v == NULL)
1211 goto done; /* not found */
1212 i = hash_packet( pkt );
1213 for (prev=NULL, q = V_ipfw_dyn_v[i] ; q != NULL ; ) {
1214 if (q->dyn_type == O_LIMIT_PARENT && q->count)
1216 if (TIME_LEQ( q->expire, time_uptime)) { /* expire entry */
1217 UNLINK_DYN_RULE(prev, V_ipfw_dyn_v[i], q);
1220 if (pkt->proto == q->id.proto &&
1221 q->dyn_type != O_LIMIT_PARENT) {
1222 if (IS_IP6_FLOW_ID(pkt)) {
1223 if (IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
1224 &(q->id.src_ip6)) &&
1225 IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
1226 &(q->id.dst_ip6)) &&
1227 pkt->src_port == q->id.src_port &&
1228 pkt->dst_port == q->id.dst_port ) {
1229 dir = MATCH_FORWARD;
1232 if (IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
1233 &(q->id.dst_ip6)) &&
1234 IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
1235 &(q->id.src_ip6)) &&
1236 pkt->src_port == q->id.dst_port &&
1237 pkt->dst_port == q->id.src_port ) {
1238 dir = MATCH_REVERSE;
1242 if (pkt->src_ip == q->id.src_ip &&
1243 pkt->dst_ip == q->id.dst_ip &&
1244 pkt->src_port == q->id.src_port &&
1245 pkt->dst_port == q->id.dst_port ) {
1246 dir = MATCH_FORWARD;
1249 if (pkt->src_ip == q->id.dst_ip &&
1250 pkt->dst_ip == q->id.src_ip &&
1251 pkt->src_port == q->id.dst_port &&
1252 pkt->dst_port == q->id.src_port ) {
1253 dir = MATCH_REVERSE;
1263 goto done; /* q = NULL, not found */
1265 if ( prev != NULL) { /* found and not in front */
1266 prev->next = q->next;
1267 q->next = V_ipfw_dyn_v[i];
1268 V_ipfw_dyn_v[i] = q;
1270 if (pkt->proto == IPPROTO_TCP) { /* update state according to flags */
1271 u_char flags = pkt->flags & (TH_FIN|TH_SYN|TH_RST);
1273 #define BOTH_SYN (TH_SYN | (TH_SYN << 8))
1274 #define BOTH_FIN (TH_FIN | (TH_FIN << 8))
1275 q->state |= (dir == MATCH_FORWARD ) ? flags : (flags << 8);
1277 case TH_SYN: /* opening */
1278 q->expire = time_uptime + V_dyn_syn_lifetime;
1281 case BOTH_SYN: /* move to established */
1282 case BOTH_SYN | TH_FIN : /* one side tries to close */
1283 case BOTH_SYN | (TH_FIN << 8) :
1285 #define _SEQ_GE(a,b) ((int)(a) - (int)(b) >= 0)
1286 u_int32_t ack = ntohl(tcp->th_ack);
1287 if (dir == MATCH_FORWARD) {
1288 if (q->ack_fwd == 0 || _SEQ_GE(ack, q->ack_fwd))
1290 else { /* ignore out-of-sequence */
1294 if (q->ack_rev == 0 || _SEQ_GE(ack, q->ack_rev))
1296 else { /* ignore out-of-sequence */
1301 q->expire = time_uptime + V_dyn_ack_lifetime;
1304 case BOTH_SYN | BOTH_FIN: /* both sides closed */
1305 if (V_dyn_fin_lifetime >= V_dyn_keepalive_period)
1306 V_dyn_fin_lifetime = V_dyn_keepalive_period - 1;
1307 q->expire = time_uptime + V_dyn_fin_lifetime;
1313 * reset or some invalid combination, but can also
1314 * occur if we use keep-state the wrong way.
1316 if ( (q->state & ((TH_RST << 8)|TH_RST)) == 0)
1317 printf("invalid state: 0x%x\n", q->state);
1319 if (V_dyn_rst_lifetime >= V_dyn_keepalive_period)
1320 V_dyn_rst_lifetime = V_dyn_keepalive_period - 1;
1321 q->expire = time_uptime + V_dyn_rst_lifetime;
1324 } else if (pkt->proto == IPPROTO_UDP) {
1325 q->expire = time_uptime + V_dyn_udp_lifetime;
1327 /* other protocols */
1328 q->expire = time_uptime + V_dyn_short_lifetime;
1331 if (match_direction)
1332 *match_direction = dir;
1336 static ipfw_dyn_rule *
1337 lookup_dyn_rule(struct ipfw_flow_id *pkt, int *match_direction,
1343 q = lookup_dyn_rule_locked(pkt, match_direction, tcp);
1346 /* NB: return table locked when q is not NULL */
1351 realloc_dynamic_table(void)
1353 IPFW_DYN_LOCK_ASSERT();
1356 * Try reallocation, make sure we have a power of 2 and do
1357 * not allow more than 64k entries. In case of overflow,
1361 if (V_dyn_buckets > 65536)
1362 V_dyn_buckets = 1024;
1363 if ((V_dyn_buckets & (V_dyn_buckets-1)) != 0) { /* not a power of 2 */
1364 V_dyn_buckets = V_curr_dyn_buckets; /* reset */
1367 V_curr_dyn_buckets = V_dyn_buckets;
1368 if (V_ipfw_dyn_v != NULL)
1369 free(V_ipfw_dyn_v, M_IPFW);
1371 V_ipfw_dyn_v = malloc(V_curr_dyn_buckets * sizeof(ipfw_dyn_rule *),
1372 M_IPFW, M_NOWAIT | M_ZERO);
1373 if (V_ipfw_dyn_v != NULL || V_curr_dyn_buckets <= 2)
1375 V_curr_dyn_buckets /= 2;
1380 * Install state of type 'type' for a dynamic session.
1381 * The hash table contains two type of rules:
1382 * - regular rules (O_KEEP_STATE)
1383 * - rules for sessions with limited number of sess per user
1384 * (O_LIMIT). When they are created, the parent is
1385 * increased by 1, and decreased on delete. In this case,
1386 * the third parameter is the parent rule and not the chain.
1387 * - "parent" rules for the above (O_LIMIT_PARENT).
1389 static ipfw_dyn_rule *
1390 add_dyn_rule(struct ipfw_flow_id *id, u_int8_t dyn_type, struct ip_fw *rule)
1395 IPFW_DYN_LOCK_ASSERT();
1397 if (V_ipfw_dyn_v == NULL ||
1398 (V_dyn_count == 0 && V_dyn_buckets != V_curr_dyn_buckets)) {
1399 realloc_dynamic_table();
1400 if (V_ipfw_dyn_v == NULL)
1401 return NULL; /* failed ! */
1403 i = hash_packet(id);
1405 r = uma_zalloc(ipfw_dyn_rule_zone, M_NOWAIT | M_ZERO);
1407 printf ("ipfw: sorry cannot allocate state\n");
1411 /* increase refcount on parent, and set pointer */
1412 if (dyn_type == O_LIMIT) {
1413 ipfw_dyn_rule *parent = (ipfw_dyn_rule *)rule;
1414 if ( parent->dyn_type != O_LIMIT_PARENT)
1415 panic("invalid parent");
1418 rule = parent->rule;
1422 r->expire = time_uptime + V_dyn_syn_lifetime;
1424 r->dyn_type = dyn_type;
1425 r->pcnt = r->bcnt = 0;
1429 r->next = V_ipfw_dyn_v[i];
1430 V_ipfw_dyn_v[i] = r;
1432 DEB(printf("ipfw: add dyn entry ty %d 0x%08x %d -> 0x%08x %d, total %d\n",
1434 (r->id.src_ip), (r->id.src_port),
1435 (r->id.dst_ip), (r->id.dst_port),
1441 * lookup dynamic parent rule using pkt and rule as search keys.
1442 * If the lookup fails, then install one.
1444 static ipfw_dyn_rule *
1445 lookup_dyn_parent(struct ipfw_flow_id *pkt, struct ip_fw *rule)
1450 IPFW_DYN_LOCK_ASSERT();
1453 int is_v6 = IS_IP6_FLOW_ID(pkt);
1454 i = hash_packet( pkt );
1455 for (q = V_ipfw_dyn_v[i] ; q != NULL ; q=q->next)
1456 if (q->dyn_type == O_LIMIT_PARENT &&
1458 pkt->proto == q->id.proto &&
1459 pkt->src_port == q->id.src_port &&
1460 pkt->dst_port == q->id.dst_port &&
1463 IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
1464 &(q->id.src_ip6)) &&
1465 IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
1466 &(q->id.dst_ip6))) ||
1468 pkt->src_ip == q->id.src_ip &&
1469 pkt->dst_ip == q->id.dst_ip)
1472 q->expire = time_uptime + V_dyn_short_lifetime;
1473 DEB(printf("ipfw: lookup_dyn_parent found 0x%p\n",q);)
1477 return add_dyn_rule(pkt, O_LIMIT_PARENT, rule);
1481 * Install dynamic state for rule type cmd->o.opcode
1483 * Returns 1 (failure) if state is not installed because of errors or because
1484 * session limitations are enforced.
1487 install_state(struct ip_fw *rule, ipfw_insn_limit *cmd,
1488 struct ip_fw_args *args, uint32_t tablearg)
1490 static int last_log;
1493 char src[48], dst[48];
1499 printf("ipfw: %s: type %d 0x%08x %u -> 0x%08x %u\n",
1500 __func__, cmd->o.opcode,
1501 (args->f_id.src_ip), (args->f_id.src_port),
1502 (args->f_id.dst_ip), (args->f_id.dst_port));
1507 q = lookup_dyn_rule_locked(&args->f_id, NULL, NULL);
1509 if (q != NULL) { /* should never occur */
1510 if (last_log != time_uptime) {
1511 last_log = time_uptime;
1512 printf("ipfw: %s: entry already present, done\n",
1519 if (V_dyn_count >= V_dyn_max)
1520 /* Run out of slots, try to remove any expired rule. */
1521 remove_dyn_rule(NULL, (ipfw_dyn_rule *)1);
1523 if (V_dyn_count >= V_dyn_max) {
1524 if (last_log != time_uptime) {
1525 last_log = time_uptime;
1526 printf("ipfw: %s: Too many dynamic rules\n", __func__);
1529 return (1); /* cannot install, notify caller */
1532 switch (cmd->o.opcode) {
1533 case O_KEEP_STATE: /* bidir rule */
1534 add_dyn_rule(&args->f_id, O_KEEP_STATE, rule);
1537 case O_LIMIT: { /* limit number of sessions */
1538 struct ipfw_flow_id id;
1539 ipfw_dyn_rule *parent;
1540 uint32_t conn_limit;
1541 uint16_t limit_mask = cmd->limit_mask;
1543 conn_limit = (cmd->conn_limit == IP_FW_TABLEARG) ?
1544 tablearg : cmd->conn_limit;
1547 if (cmd->conn_limit == IP_FW_TABLEARG)
1548 printf("ipfw: %s: O_LIMIT rule, conn_limit: %u "
1549 "(tablearg)\n", __func__, conn_limit);
1551 printf("ipfw: %s: O_LIMIT rule, conn_limit: %u\n",
1552 __func__, conn_limit);
1555 id.dst_ip = id.src_ip = id.dst_port = id.src_port = 0;
1556 id.proto = args->f_id.proto;
1557 id.addr_type = args->f_id.addr_type;
1558 id.fib = M_GETFIB(args->m);
1560 if (IS_IP6_FLOW_ID (&(args->f_id))) {
1561 if (limit_mask & DYN_SRC_ADDR)
1562 id.src_ip6 = args->f_id.src_ip6;
1563 if (limit_mask & DYN_DST_ADDR)
1564 id.dst_ip6 = args->f_id.dst_ip6;
1566 if (limit_mask & DYN_SRC_ADDR)
1567 id.src_ip = args->f_id.src_ip;
1568 if (limit_mask & DYN_DST_ADDR)
1569 id.dst_ip = args->f_id.dst_ip;
1571 if (limit_mask & DYN_SRC_PORT)
1572 id.src_port = args->f_id.src_port;
1573 if (limit_mask & DYN_DST_PORT)
1574 id.dst_port = args->f_id.dst_port;
1575 if ((parent = lookup_dyn_parent(&id, rule)) == NULL) {
1576 printf("ipfw: %s: add parent failed\n", __func__);
1581 if (parent->count >= conn_limit) {
1582 /* See if we can remove some expired rule. */
1583 remove_dyn_rule(rule, parent);
1584 if (parent->count >= conn_limit) {
1585 if (V_fw_verbose && last_log != time_uptime) {
1586 last_log = time_uptime;
1589 * XXX IPv6 flows are not
1592 if (IS_IP6_FLOW_ID(&(args->f_id))) {
1593 char ip6buf[INET6_ADDRSTRLEN];
1594 snprintf(src, sizeof(src),
1595 "[%s]", ip6_sprintf(ip6buf,
1596 &args->f_id.src_ip6));
1597 snprintf(dst, sizeof(dst),
1598 "[%s]", ip6_sprintf(ip6buf,
1599 &args->f_id.dst_ip6));
1604 htonl(args->f_id.src_ip);
1605 inet_ntoa_r(da, src);
1607 htonl(args->f_id.dst_ip);
1608 inet_ntoa_r(da, dst);
1610 log(LOG_SECURITY | LOG_DEBUG,
1611 "ipfw: %d %s %s:%u -> %s:%u, %s\n",
1612 parent->rule->rulenum,
1614 src, (args->f_id.src_port),
1615 dst, (args->f_id.dst_port),
1616 "too many entries");
1622 add_dyn_rule(&args->f_id, O_LIMIT, (struct ip_fw *)parent);
1626 printf("ipfw: %s: unknown dynamic rule type %u\n",
1627 __func__, cmd->o.opcode);
1632 /* XXX just set lifetime */
1633 lookup_dyn_rule_locked(&args->f_id, NULL, NULL);
1640 * Generate a TCP packet, containing either a RST or a keepalive.
1641 * When flags & TH_RST, we are sending a RST packet, because of a
1642 * "reset" action matched the packet.
1643 * Otherwise we are sending a keepalive, and flags & TH_
1644 * The 'replyto' mbuf is the mbuf being replied to, if any, and is required
1645 * so that MAC can label the reply appropriately.
1647 static struct mbuf *
1648 send_pkt(struct mbuf *replyto, struct ipfw_flow_id *id, u_int32_t seq,
1649 u_int32_t ack, int flags)
1655 MGETHDR(m, M_DONTWAIT, MT_DATA);
1658 m->m_pkthdr.rcvif = (struct ifnet *)0;
1660 M_SETFIB(m, id->fib);
1662 if (replyto != NULL)
1663 mac_netinet_firewall_reply(replyto, m);
1665 mac_netinet_firewall_send(m);
1667 (void)replyto; /* don't warn about unused arg */
1670 m->m_pkthdr.len = m->m_len = sizeof(struct ip) + sizeof(struct tcphdr);
1671 m->m_data += max_linkhdr;
1673 ip = mtod(m, struct ip *);
1674 bzero(ip, m->m_len);
1675 tcp = (struct tcphdr *)(ip + 1); /* no IP options */
1676 ip->ip_p = IPPROTO_TCP;
1679 * Assume we are sending a RST (or a keepalive in the reverse
1680 * direction), swap src and destination addresses and ports.
1682 ip->ip_src.s_addr = htonl(id->dst_ip);
1683 ip->ip_dst.s_addr = htonl(id->src_ip);
1684 tcp->th_sport = htons(id->dst_port);
1685 tcp->th_dport = htons(id->src_port);
1686 if (flags & TH_RST) { /* we are sending a RST */
1687 if (flags & TH_ACK) {
1688 tcp->th_seq = htonl(ack);
1689 tcp->th_ack = htonl(0);
1690 tcp->th_flags = TH_RST;
1694 tcp->th_seq = htonl(0);
1695 tcp->th_ack = htonl(seq);
1696 tcp->th_flags = TH_RST | TH_ACK;
1700 * We are sending a keepalive. flags & TH_SYN determines
1701 * the direction, forward if set, reverse if clear.
1702 * NOTE: seq and ack are always assumed to be correct
1703 * as set by the caller. This may be confusing...
1705 if (flags & TH_SYN) {
1707 * we have to rewrite the correct addresses!
1709 ip->ip_dst.s_addr = htonl(id->dst_ip);
1710 ip->ip_src.s_addr = htonl(id->src_ip);
1711 tcp->th_dport = htons(id->dst_port);
1712 tcp->th_sport = htons(id->src_port);
1714 tcp->th_seq = htonl(seq);
1715 tcp->th_ack = htonl(ack);
1716 tcp->th_flags = TH_ACK;
1719 * set ip_len to the payload size so we can compute
1720 * the tcp checksum on the pseudoheader
1721 * XXX check this, could save a couple of words ?
1723 ip->ip_len = htons(sizeof(struct tcphdr));
1724 tcp->th_sum = in_cksum(m, m->m_pkthdr.len);
1726 * now fill fields left out earlier
1728 ip->ip_ttl = V_ip_defttl;
1729 ip->ip_len = m->m_pkthdr.len;
1730 m->m_flags |= M_SKIP_FIREWALL;
1735 * sends a reject message, consuming the mbuf passed as an argument.
1738 send_reject(struct ip_fw_args *args, int code, int ip_len, struct ip *ip)
1742 /* XXX When ip is not guaranteed to be at mtod() we will
1743 * need to account for this */
1744 * The mbuf will however be thrown away so we can adjust it.
1745 * Remember we did an m_pullup on it already so we
1746 * can make some assumptions about contiguousness.
1749 m_adj(m, args->L3offset);
1751 if (code != ICMP_REJECT_RST) { /* Send an ICMP unreach */
1752 /* We need the IP header in host order for icmp_error(). */
1753 if (args->eh != NULL) {
1754 ip->ip_len = ntohs(ip->ip_len);
1755 ip->ip_off = ntohs(ip->ip_off);
1757 icmp_error(args->m, ICMP_UNREACH, code, 0L, 0);
1758 } else if (args->f_id.proto == IPPROTO_TCP) {
1759 struct tcphdr *const tcp =
1760 L3HDR(struct tcphdr, mtod(args->m, struct ip *));
1761 if ( (tcp->th_flags & TH_RST) == 0) {
1763 m = send_pkt(args->m, &(args->f_id),
1764 ntohl(tcp->th_seq), ntohl(tcp->th_ack),
1765 tcp->th_flags | TH_RST);
1767 ip_output(m, NULL, NULL, 0, NULL, NULL);
1777 * Given an ip_fw *, lookup_next_rule will return a pointer
1778 * to the next rule, which can be either the jump
1779 * target (for skipto instructions) or the next one in the list (in
1780 * all other cases including a missing jump target).
1781 * The result is also written in the "next_rule" field of the rule.
1782 * Backward jumps are not allowed, so start looking from the next
1785 * This never returns NULL -- in case we do not have an exact match,
1786 * the next rule is returned. When the ruleset is changed,
1787 * pointers are flushed so we are always correct.
1790 static struct ip_fw *
1791 lookup_next_rule(struct ip_fw *me, u_int32_t tablearg)
1793 struct ip_fw *rule = NULL;
1797 /* look for action, in case it is a skipto */
1798 cmd = ACTION_PTR(me);
1799 if (cmd->opcode == O_LOG)
1801 if (cmd->opcode == O_ALTQ)
1803 if (cmd->opcode == O_TAG)
1805 if (cmd->opcode == O_SKIPTO ) {
1806 if (tablearg != 0) {
1807 rulenum = (u_int16_t)tablearg;
1809 rulenum = cmd->arg1;
1811 for (rule = me->next; rule ; rule = rule->next) {
1812 if (rule->rulenum >= rulenum) {
1817 if (rule == NULL) /* failure or not a skipto */
1819 me->next_rule = rule;
1824 add_table_entry(struct ip_fw_chain *ch, uint16_t tbl, in_addr_t addr,
1825 uint8_t mlen, uint32_t value)
1827 struct radix_node_head *rnh;
1828 struct table_entry *ent;
1829 struct radix_node *rn;
1831 if (tbl >= IPFW_TABLES_MAX)
1833 rnh = ch->tables[tbl];
1834 ent = malloc(sizeof(*ent), M_IPFW_TBL, M_NOWAIT | M_ZERO);
1838 ent->addr.sin_len = ent->mask.sin_len = 8;
1839 ent->mask.sin_addr.s_addr = htonl(mlen ? ~((1 << (32 - mlen)) - 1) : 0);
1840 ent->addr.sin_addr.s_addr = addr & ent->mask.sin_addr.s_addr;
1842 rn = rnh->rnh_addaddr(&ent->addr, &ent->mask, rnh, (void *)ent);
1845 free(ent, M_IPFW_TBL);
1853 del_table_entry(struct ip_fw_chain *ch, uint16_t tbl, in_addr_t addr,
1856 struct radix_node_head *rnh;
1857 struct table_entry *ent;
1858 struct sockaddr_in sa, mask;
1860 if (tbl >= IPFW_TABLES_MAX)
1862 rnh = ch->tables[tbl];
1863 sa.sin_len = mask.sin_len = 8;
1864 mask.sin_addr.s_addr = htonl(mlen ? ~((1 << (32 - mlen)) - 1) : 0);
1865 sa.sin_addr.s_addr = addr & mask.sin_addr.s_addr;
1867 ent = (struct table_entry *)rnh->rnh_deladdr(&sa, &mask, rnh);
1873 free(ent, M_IPFW_TBL);
1878 flush_table_entry(struct radix_node *rn, void *arg)
1880 struct radix_node_head * const rnh = arg;
1881 struct table_entry *ent;
1883 ent = (struct table_entry *)
1884 rnh->rnh_deladdr(rn->rn_key, rn->rn_mask, rnh);
1886 free(ent, M_IPFW_TBL);
1891 flush_table(struct ip_fw_chain *ch, uint16_t tbl)
1893 struct radix_node_head *rnh;
1895 IPFW_WLOCK_ASSERT(ch);
1897 if (tbl >= IPFW_TABLES_MAX)
1899 rnh = ch->tables[tbl];
1900 KASSERT(rnh != NULL, ("NULL IPFW table"));
1901 rnh->rnh_walktree(rnh, flush_table_entry, rnh);
1906 flush_tables(struct ip_fw_chain *ch)
1910 IPFW_WLOCK_ASSERT(ch);
1912 for (tbl = 0; tbl < IPFW_TABLES_MAX; tbl++)
1913 flush_table(ch, tbl);
1917 init_tables(struct ip_fw_chain *ch)
1922 for (i = 0; i < IPFW_TABLES_MAX; i++) {
1923 if (!rn_inithead((void **)&ch->tables[i], 32)) {
1924 for (j = 0; j < i; j++) {
1925 (void) flush_table(ch, j);
1934 lookup_table(struct ip_fw_chain *ch, uint16_t tbl, in_addr_t addr,
1937 struct radix_node_head *rnh;
1938 struct table_entry *ent;
1939 struct sockaddr_in sa;
1941 if (tbl >= IPFW_TABLES_MAX)
1943 rnh = ch->tables[tbl];
1945 sa.sin_addr.s_addr = addr;
1946 ent = (struct table_entry *)(rnh->rnh_lookup(&sa, NULL, rnh));
1955 count_table_entry(struct radix_node *rn, void *arg)
1957 u_int32_t * const cnt = arg;
1964 count_table(struct ip_fw_chain *ch, uint32_t tbl, uint32_t *cnt)
1966 struct radix_node_head *rnh;
1968 if (tbl >= IPFW_TABLES_MAX)
1970 rnh = ch->tables[tbl];
1972 rnh->rnh_walktree(rnh, count_table_entry, cnt);
1977 dump_table_entry(struct radix_node *rn, void *arg)
1979 struct table_entry * const n = (struct table_entry *)rn;
1980 ipfw_table * const tbl = arg;
1981 ipfw_table_entry *ent;
1983 if (tbl->cnt == tbl->size)
1985 ent = &tbl->ent[tbl->cnt];
1986 ent->tbl = tbl->tbl;
1987 if (in_nullhost(n->mask.sin_addr))
1990 ent->masklen = 33 - ffs(ntohl(n->mask.sin_addr.s_addr));
1991 ent->addr = n->addr.sin_addr.s_addr;
1992 ent->value = n->value;
1998 dump_table(struct ip_fw_chain *ch, ipfw_table *tbl)
2000 struct radix_node_head *rnh;
2002 if (tbl->tbl >= IPFW_TABLES_MAX)
2004 rnh = ch->tables[tbl->tbl];
2006 rnh->rnh_walktree(rnh, dump_table_entry, tbl);
2011 check_uidgid(ipfw_insn_u32 *insn, int proto, struct ifnet *oif,
2012 struct in_addr dst_ip, u_int16_t dst_port, struct in_addr src_ip,
2013 u_int16_t src_port, struct ucred **uc, int *ugid_lookupp,
2016 struct inpcbinfo *pi;
2022 * Check to see if the UDP or TCP stack supplied us with
2023 * the PCB. If so, rather then holding a lock and looking
2024 * up the PCB, we can use the one that was supplied.
2026 if (inp && *ugid_lookupp == 0) {
2027 INP_LOCK_ASSERT(inp);
2028 if (inp->inp_socket != NULL) {
2029 *uc = crhold(inp->inp_cred);
2035 * If we have already been here and the packet has no
2036 * PCB entry associated with it, then we can safely
2037 * assume that this is a no match.
2039 if (*ugid_lookupp == -1)
2041 if (proto == IPPROTO_TCP) {
2044 } else if (proto == IPPROTO_UDP) {
2045 wildcard = INPLOOKUP_WILDCARD;
2050 if (*ugid_lookupp == 0) {
2053 in_pcblookup_hash(pi,
2054 dst_ip, htons(dst_port),
2055 src_ip, htons(src_port),
2057 in_pcblookup_hash(pi,
2058 src_ip, htons(src_port),
2059 dst_ip, htons(dst_port),
2062 *uc = crhold(pcb->inp_cred);
2065 INP_INFO_RUNLOCK(pi);
2066 if (*ugid_lookupp == 0) {
2068 * If the lookup did not yield any results, there
2069 * is no sense in coming back and trying again. So
2070 * we can set lookup to -1 and ensure that we wont
2071 * bother the pcb system again.
2077 if (insn->o.opcode == O_UID)
2078 match = ((*uc)->cr_uid == (uid_t)insn->d[0]);
2079 else if (insn->o.opcode == O_GID)
2080 match = groupmember((gid_t)insn->d[0], *uc);
2081 else if (insn->o.opcode == O_JAIL)
2082 match = ((*uc)->cr_prison->pr_id == (int)insn->d[0]);
2087 * The main check routine for the firewall.
2089 * All arguments are in args so we can modify them and return them
2090 * back to the caller.
2094 * args->m (in/out) The packet; we set to NULL when/if we nuke it.
2095 * Starts with the IP header.
2096 * args->eh (in) Mac header if present, or NULL for layer3 packet.
2097 * args->L3offset Number of bytes bypassed if we came from L2.
2098 * e.g. often sizeof(eh) ** NOTYET **
2099 * args->oif Outgoing interface, or NULL if packet is incoming.
2100 * The incoming interface is in the mbuf. (in)
2101 * args->divert_rule (in/out)
2102 * Skip up to the first rule past this rule number;
2103 * upon return, non-zero port number for divert or tee.
2105 * args->rule Pointer to the last matching rule (in/out)
2106 * args->next_hop Socket we are forwarding to (out).
2107 * args->f_id Addresses grabbed from the packet (out)
2108 * args->cookie a cookie depending on rule action
2112 * IP_FW_PASS the packet must be accepted
2113 * IP_FW_DENY the packet must be dropped
2114 * IP_FW_DIVERT divert packet, port in m_tag
2115 * IP_FW_TEE tee packet, port in m_tag
2116 * IP_FW_DUMMYNET to dummynet, pipe in args->cookie
2117 * IP_FW_NETGRAPH into netgraph, cookie args->cookie
2121 ipfw_chk(struct ip_fw_args *args)
2125 * Local variables holding state during the processing of a packet:
2127 * IMPORTANT NOTE: to speed up the processing of rules, there
2128 * are some assumption on the values of the variables, which
2129 * are documented here. Should you change them, please check
2130 * the implementation of the various instructions to make sure
2131 * that they still work.
2133 * args->eh The MAC header. It is non-null for a layer2
2134 * packet, it is NULL for a layer-3 packet.
2136 * args->L3offset Offset in the packet to the L3 (IP or equiv.) header.
2138 * m | args->m Pointer to the mbuf, as received from the caller.
2139 * It may change if ipfw_chk() does an m_pullup, or if it
2140 * consumes the packet because it calls send_reject().
2141 * XXX This has to change, so that ipfw_chk() never modifies
2142 * or consumes the buffer.
2143 * ip is the beginning of the ip(4 or 6) header.
2144 * Calculated by adding the L3offset to the start of data.
2145 * (Until we start using L3offset, the packet is
2146 * supposed to start with the ip header).
2148 struct mbuf *m = args->m;
2149 struct ip *ip = mtod(m, struct ip *);
2152 * For rules which contain uid/gid or jail constraints, cache
2153 * a copy of the users credentials after the pcb lookup has been
2154 * executed. This will speed up the processing of rules with
2155 * these types of constraints, as well as decrease contention
2156 * on pcb related locks.
2158 struct ucred *ucred_cache = NULL;
2159 int ucred_lookup = 0;
2162 * divinput_flags If non-zero, set to the IP_FW_DIVERT_*_FLAG
2163 * associated with a packet input on a divert socket. This
2164 * will allow to distinguish traffic and its direction when
2165 * it originates from a divert socket.
2167 u_int divinput_flags = 0;
2170 * oif | args->oif If NULL, ipfw_chk has been called on the
2171 * inbound path (ether_input, ip_input).
2172 * If non-NULL, ipfw_chk has been called on the outbound path
2173 * (ether_output, ip_output).
2175 struct ifnet *oif = args->oif;
2177 struct ip_fw *f = NULL; /* matching rule */
2181 * hlen The length of the IP header.
2183 u_int hlen = 0; /* hlen >0 means we have an IP pkt */
2186 * offset The offset of a fragment. offset != 0 means that
2187 * we have a fragment at this offset of an IPv4 packet.
2188 * offset == 0 means that (if this is an IPv4 packet)
2189 * this is the first or only fragment.
2190 * For IPv6 offset == 0 means there is no Fragment Header.
2191 * If offset != 0 for IPv6 always use correct mask to
2192 * get the correct offset because we add IP6F_MORE_FRAG
2193 * to be able to dectect the first fragment which would
2194 * otherwise have offset = 0.
2199 * Local copies of addresses. They are only valid if we have
2202 * proto The protocol. Set to 0 for non-ip packets,
2203 * or to the protocol read from the packet otherwise.
2204 * proto != 0 means that we have an IPv4 packet.
2206 * src_port, dst_port port numbers, in HOST format. Only
2207 * valid for TCP and UDP packets.
2209 * src_ip, dst_ip ip addresses, in NETWORK format.
2210 * Only valid for IPv4 packets.
2213 u_int16_t src_port = 0, dst_port = 0; /* NOTE: host format */
2214 struct in_addr src_ip, dst_ip; /* NOTE: network format */
2217 u_int16_t etype = 0; /* Host order stored ether type */
2220 * dyn_dir = MATCH_UNKNOWN when rules unchecked,
2221 * MATCH_NONE when checked and not matched (q = NULL),
2222 * MATCH_FORWARD or MATCH_REVERSE otherwise (q != NULL)
2224 int dyn_dir = MATCH_UNKNOWN;
2225 ipfw_dyn_rule *q = NULL;
2226 struct ip_fw_chain *chain = &V_layer3_chain;
2230 * We store in ulp a pointer to the upper layer protocol header.
2231 * In the ipv4 case this is easy to determine from the header,
2232 * but for ipv6 we might have some additional headers in the middle.
2233 * ulp is NULL if not found.
2235 void *ulp = NULL; /* upper layer protocol pointer. */
2236 /* XXX ipv6 variables */
2238 u_int16_t ext_hd = 0; /* bits vector for extension header filtering */
2239 /* end of ipv6 variables */
2242 if (m->m_flags & M_SKIP_FIREWALL || (! V_ipfw_vnet_ready))
2243 return (IP_FW_PASS); /* accept */
2245 dst_ip.s_addr = 0; /* make sure it is initialized */
2246 pktlen = m->m_pkthdr.len;
2247 args->f_id.fib = M_GETFIB(m); /* note mbuf not altered) */
2248 proto = args->f_id.proto = 0; /* mark f_id invalid */
2249 /* XXX 0 is a valid proto: IP/IPv6 Hop-by-Hop Option */
2252 * PULLUP_TO(len, p, T) makes sure that len + sizeof(T) is contiguous,
2253 * then it sets p to point at the offset "len" in the mbuf. WARNING: the
2254 * pointer might become stale after other pullups (but we never use it
2257 #define PULLUP_TO(len, p, T) \
2259 int x = (len) + sizeof(T); \
2260 if ((m)->m_len < x) { \
2261 args->m = m = m_pullup(m, x); \
2263 goto pullup_failed; \
2265 p = (mtod(m, char *) + (len)); \
2269 * if we have an ether header,
2272 etype = ntohs(args->eh->ether_type);
2274 /* Identify IP packets and fill up variables. */
2275 if (pktlen >= sizeof(struct ip6_hdr) &&
2276 (args->eh == NULL || etype == ETHERTYPE_IPV6) && ip->ip_v == 6) {
2277 struct ip6_hdr *ip6 = (struct ip6_hdr *)ip;
2279 args->f_id.addr_type = 6;
2280 hlen = sizeof(struct ip6_hdr);
2281 proto = ip6->ip6_nxt;
2283 /* Search extension headers to find upper layer protocols */
2284 while (ulp == NULL) {
2286 case IPPROTO_ICMPV6:
2287 PULLUP_TO(hlen, ulp, struct icmp6_hdr);
2288 args->f_id.flags = ICMP6(ulp)->icmp6_type;
2292 PULLUP_TO(hlen, ulp, struct tcphdr);
2293 dst_port = TCP(ulp)->th_dport;
2294 src_port = TCP(ulp)->th_sport;
2295 args->f_id.flags = TCP(ulp)->th_flags;
2299 PULLUP_TO(hlen, ulp, struct sctphdr);
2300 src_port = SCTP(ulp)->src_port;
2301 dst_port = SCTP(ulp)->dest_port;
2305 PULLUP_TO(hlen, ulp, struct udphdr);
2306 dst_port = UDP(ulp)->uh_dport;
2307 src_port = UDP(ulp)->uh_sport;
2310 case IPPROTO_HOPOPTS: /* RFC 2460 */
2311 PULLUP_TO(hlen, ulp, struct ip6_hbh);
2312 ext_hd |= EXT_HOPOPTS;
2313 hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3;
2314 proto = ((struct ip6_hbh *)ulp)->ip6h_nxt;
2318 case IPPROTO_ROUTING: /* RFC 2460 */
2319 PULLUP_TO(hlen, ulp, struct ip6_rthdr);
2320 switch (((struct ip6_rthdr *)ulp)->ip6r_type) {
2322 ext_hd |= EXT_RTHDR0;
2325 ext_hd |= EXT_RTHDR2;
2328 printf("IPFW2: IPV6 - Unknown Routing "
2329 "Header type(%d)\n",
2330 ((struct ip6_rthdr *)ulp)->ip6r_type);
2331 if (V_fw_deny_unknown_exthdrs)
2332 return (IP_FW_DENY);
2335 ext_hd |= EXT_ROUTING;
2336 hlen += (((struct ip6_rthdr *)ulp)->ip6r_len + 1) << 3;
2337 proto = ((struct ip6_rthdr *)ulp)->ip6r_nxt;
2341 case IPPROTO_FRAGMENT: /* RFC 2460 */
2342 PULLUP_TO(hlen, ulp, struct ip6_frag);
2343 ext_hd |= EXT_FRAGMENT;
2344 hlen += sizeof (struct ip6_frag);
2345 proto = ((struct ip6_frag *)ulp)->ip6f_nxt;
2346 offset = ((struct ip6_frag *)ulp)->ip6f_offlg &
2348 /* Add IP6F_MORE_FRAG for offset of first
2349 * fragment to be != 0. */
2350 offset |= ((struct ip6_frag *)ulp)->ip6f_offlg &
2353 printf("IPFW2: IPV6 - Invalid Fragment "
2355 if (V_fw_deny_unknown_exthdrs)
2356 return (IP_FW_DENY);
2359 args->f_id.frag_id6 =
2360 ntohl(((struct ip6_frag *)ulp)->ip6f_ident);
2364 case IPPROTO_DSTOPTS: /* RFC 2460 */
2365 PULLUP_TO(hlen, ulp, struct ip6_hbh);
2366 ext_hd |= EXT_DSTOPTS;
2367 hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3;
2368 proto = ((struct ip6_hbh *)ulp)->ip6h_nxt;
2372 case IPPROTO_AH: /* RFC 2402 */
2373 PULLUP_TO(hlen, ulp, struct ip6_ext);
2375 hlen += (((struct ip6_ext *)ulp)->ip6e_len + 2) << 2;
2376 proto = ((struct ip6_ext *)ulp)->ip6e_nxt;
2380 case IPPROTO_ESP: /* RFC 2406 */
2381 PULLUP_TO(hlen, ulp, uint32_t); /* SPI, Seq# */
2382 /* Anything past Seq# is variable length and
2383 * data past this ext. header is encrypted. */
2387 case IPPROTO_NONE: /* RFC 2460 */
2389 * Packet ends here, and IPv6 header has
2390 * already been pulled up. If ip6e_len!=0
2391 * then octets must be ignored.
2393 ulp = ip; /* non-NULL to get out of loop. */
2396 case IPPROTO_OSPFIGP:
2397 /* XXX OSPF header check? */
2398 PULLUP_TO(hlen, ulp, struct ip6_ext);
2402 /* XXX PIM header check? */
2403 PULLUP_TO(hlen, ulp, struct pim);
2407 PULLUP_TO(hlen, ulp, struct carp_header);
2408 if (((struct carp_header *)ulp)->carp_version !=
2410 return (IP_FW_DENY);
2411 if (((struct carp_header *)ulp)->carp_type !=
2413 return (IP_FW_DENY);
2416 case IPPROTO_IPV6: /* RFC 2893 */
2417 PULLUP_TO(hlen, ulp, struct ip6_hdr);
2420 case IPPROTO_IPV4: /* RFC 2893 */
2421 PULLUP_TO(hlen, ulp, struct ip);
2425 printf("IPFW2: IPV6 - Unknown Extension "
2426 "Header(%d), ext_hd=%x\n", proto, ext_hd);
2427 if (V_fw_deny_unknown_exthdrs)
2428 return (IP_FW_DENY);
2429 PULLUP_TO(hlen, ulp, struct ip6_ext);
2433 ip = mtod(m, struct ip *);
2434 ip6 = (struct ip6_hdr *)ip;
2435 args->f_id.src_ip6 = ip6->ip6_src;
2436 args->f_id.dst_ip6 = ip6->ip6_dst;
2437 args->f_id.src_ip = 0;
2438 args->f_id.dst_ip = 0;
2439 args->f_id.flow_id6 = ntohl(ip6->ip6_flow);
2440 } else if (pktlen >= sizeof(struct ip) &&
2441 (args->eh == NULL || etype == ETHERTYPE_IP) && ip->ip_v == 4) {
2443 hlen = ip->ip_hl << 2;
2444 args->f_id.addr_type = 4;
2447 * Collect parameters into local variables for faster matching.
2450 src_ip = ip->ip_src;
2451 dst_ip = ip->ip_dst;
2452 if (args->eh != NULL) { /* layer 2 packets are as on the wire */
2453 offset = ntohs(ip->ip_off) & IP_OFFMASK;
2454 ip_len = ntohs(ip->ip_len);
2456 offset = ip->ip_off & IP_OFFMASK;
2457 ip_len = ip->ip_len;
2459 pktlen = ip_len < pktlen ? ip_len : pktlen;
2464 PULLUP_TO(hlen, ulp, struct tcphdr);
2465 dst_port = TCP(ulp)->th_dport;
2466 src_port = TCP(ulp)->th_sport;
2467 args->f_id.flags = TCP(ulp)->th_flags;
2471 PULLUP_TO(hlen, ulp, struct udphdr);
2472 dst_port = UDP(ulp)->uh_dport;
2473 src_port = UDP(ulp)->uh_sport;
2477 PULLUP_TO(hlen, ulp, struct icmphdr);
2478 args->f_id.flags = ICMP(ulp)->icmp_type;
2486 ip = mtod(m, struct ip *);
2487 args->f_id.src_ip = ntohl(src_ip.s_addr);
2488 args->f_id.dst_ip = ntohl(dst_ip.s_addr);
2491 if (proto) { /* we may have port numbers, store them */
2492 args->f_id.proto = proto;
2493 args->f_id.src_port = src_port = ntohs(src_port);
2494 args->f_id.dst_port = dst_port = ntohs(dst_port);
2498 mtag = m_tag_find(m, PACKET_TAG_DIVERT, NULL);
2501 * Packet has already been tagged. Look for the next rule
2502 * to restart processing. Make sure that args->rule still
2503 * exists and not changed.
2505 if (chain->id != args->chain_id) {
2506 for (f = chain->rules; f != NULL; f = f->next)
2507 if (f == args->rule && f->id == args->rule_id)
2513 f = ip_fw_default_rule;
2515 f = args->rule->next_rule;
2518 f = lookup_next_rule(args->rule, 0);
2521 * Find the starting rule. It can be either the first
2522 * one, or the one after divert_rule if asked so.
2524 int skipto = mtag ? divert_cookie(mtag) : 0;
2527 if (args->eh == NULL && skipto != 0) {
2528 if (skipto >= IPFW_DEFAULT_RULE) {
2529 IPFW_RUNLOCK(chain);
2530 return (IP_FW_DENY); /* invalid */
2532 while (f && f->rulenum <= skipto)
2534 if (f == NULL) { /* drop packet */
2535 IPFW_RUNLOCK(chain);
2536 return (IP_FW_DENY);
2540 /* reset divert rule to avoid confusion later */
2542 divinput_flags = divert_info(mtag) &
2543 (IP_FW_DIVERT_OUTPUT_FLAG | IP_FW_DIVERT_LOOPBACK_FLAG);
2544 m_tag_delete(m, mtag);
2548 * Now scan the rules, and parse microinstructions for each rule.
2550 for (; f; f = f->next) {
2552 uint32_t tablearg = 0;
2553 int l, cmdlen, skip_or; /* skip rest of OR block */
2556 if (V_set_disable & (1 << f->set) )
2560 for (l = f->cmd_len, cmd = f->cmd ; l > 0 ;
2561 l -= cmdlen, cmd += cmdlen) {
2565 * check_body is a jump target used when we find a
2566 * CHECK_STATE, and need to jump to the body of
2571 cmdlen = F_LEN(cmd);
2573 * An OR block (insn_1 || .. || insn_n) has the
2574 * F_OR bit set in all but the last instruction.
2575 * The first match will set "skip_or", and cause
2576 * the following instructions to be skipped until
2577 * past the one with the F_OR bit clear.
2579 if (skip_or) { /* skip this instruction */
2580 if ((cmd->len & F_OR) == 0)
2581 skip_or = 0; /* next one is good */
2584 match = 0; /* set to 1 if we succeed */
2586 switch (cmd->opcode) {
2588 * The first set of opcodes compares the packet's
2589 * fields with some pattern, setting 'match' if a
2590 * match is found. At the end of the loop there is
2591 * logic to deal with F_NOT and F_OR flags associated
2599 printf("ipfw: opcode %d unimplemented\n",
2607 * We only check offset == 0 && proto != 0,
2608 * as this ensures that we have a
2609 * packet with the ports info.
2613 if (is_ipv6) /* XXX to be fixed later */
2615 if (proto == IPPROTO_TCP ||
2616 proto == IPPROTO_UDP)
2617 match = check_uidgid(
2618 (ipfw_insn_u32 *)cmd,
2621 src_ip, src_port, &ucred_cache,
2622 &ucred_lookup, args->inp);
2626 match = iface_match(m->m_pkthdr.rcvif,
2627 (ipfw_insn_if *)cmd);
2631 match = iface_match(oif, (ipfw_insn_if *)cmd);
2635 match = iface_match(oif ? oif :
2636 m->m_pkthdr.rcvif, (ipfw_insn_if *)cmd);
2640 if (args->eh != NULL) { /* have MAC header */
2641 u_int32_t *want = (u_int32_t *)
2642 ((ipfw_insn_mac *)cmd)->addr;
2643 u_int32_t *mask = (u_int32_t *)
2644 ((ipfw_insn_mac *)cmd)->mask;
2645 u_int32_t *hdr = (u_int32_t *)args->eh;
2648 ( want[0] == (hdr[0] & mask[0]) &&
2649 want[1] == (hdr[1] & mask[1]) &&
2650 want[2] == (hdr[2] & mask[2]) );
2655 if (args->eh != NULL) {
2657 ((ipfw_insn_u16 *)cmd)->ports;
2660 for (i = cmdlen - 1; !match && i>0;
2662 match = (etype >= p[0] &&
2668 match = (offset != 0);
2671 case O_IN: /* "out" is "not in" */
2672 match = (oif == NULL);
2676 match = (args->eh != NULL);
2680 match = (cmd->arg1 & 1 && divinput_flags &
2681 IP_FW_DIVERT_LOOPBACK_FLAG) ||
2682 (cmd->arg1 & 2 && divinput_flags &
2683 IP_FW_DIVERT_OUTPUT_FLAG);
2688 * We do not allow an arg of 0 so the
2689 * check of "proto" only suffices.
2691 match = (proto == cmd->arg1);
2696 (((ipfw_insn_ip *)cmd)->addr.s_addr ==
2700 case O_IP_SRC_LOOKUP:
2701 case O_IP_DST_LOOKUP:
2704 (cmd->opcode == O_IP_DST_LOOKUP) ?
2705 dst_ip.s_addr : src_ip.s_addr;
2708 match = lookup_table(chain, cmd->arg1, a,
2712 if (cmdlen == F_INSN_SIZE(ipfw_insn_u32))
2714 ((ipfw_insn_u32 *)cmd)->d[0] == v;
2724 (cmd->opcode == O_IP_DST_MASK) ?
2725 dst_ip.s_addr : src_ip.s_addr;
2726 uint32_t *p = ((ipfw_insn_u32 *)cmd)->d;
2729 for (; !match && i>0; i-= 2, p+= 2)
2730 match = (p[0] == (a & p[1]));
2738 INADDR_TO_IFP(src_ip, tif);
2739 match = (tif != NULL);
2746 u_int32_t *d = (u_int32_t *)(cmd+1);
2748 cmd->opcode == O_IP_DST_SET ?
2754 addr -= d[0]; /* subtract base */
2755 match = (addr < cmd->arg1) &&
2756 ( d[ 1 + (addr>>5)] &
2757 (1<<(addr & 0x1f)) );
2763 (((ipfw_insn_ip *)cmd)->addr.s_addr ==
2771 INADDR_TO_IFP(dst_ip, tif);
2772 match = (tif != NULL);
2779 * offset == 0 && proto != 0 is enough
2780 * to guarantee that we have a
2781 * packet with port info.
2783 if ((proto==IPPROTO_UDP || proto==IPPROTO_TCP)
2786 (cmd->opcode == O_IP_SRCPORT) ?
2787 src_port : dst_port ;
2789 ((ipfw_insn_u16 *)cmd)->ports;
2792 for (i = cmdlen - 1; !match && i>0;
2794 match = (x>=p[0] && x<=p[1]);
2799 match = (offset == 0 && proto==IPPROTO_ICMP &&
2800 icmptype_match(ICMP(ulp), (ipfw_insn_u32 *)cmd) );
2805 match = is_ipv6 && offset == 0 &&
2806 proto==IPPROTO_ICMPV6 &&
2808 ICMP6(ulp)->icmp6_type,
2809 (ipfw_insn_u32 *)cmd);
2815 ipopts_match(ip, cmd) );
2820 cmd->arg1 == ip->ip_v);
2826 if (is_ipv4) { /* only for IP packets */
2831 if (cmd->opcode == O_IPLEN)
2833 else if (cmd->opcode == O_IPTTL)
2835 else /* must be IPID */
2836 x = ntohs(ip->ip_id);
2838 match = (cmd->arg1 == x);
2841 /* otherwise we have ranges */
2842 p = ((ipfw_insn_u16 *)cmd)->ports;
2844 for (; !match && i>0; i--, p += 2)
2845 match = (x >= p[0] && x <= p[1]);
2849 case O_IPPRECEDENCE:
2851 (cmd->arg1 == (ip->ip_tos & 0xe0)) );
2856 flags_match(cmd, ip->ip_tos));
2860 if (proto == IPPROTO_TCP && offset == 0) {
2868 ((ip->ip_hl + tcp->th_off) << 2);
2870 match = (cmd->arg1 == x);
2873 /* otherwise we have ranges */
2874 p = ((ipfw_insn_u16 *)cmd)->ports;
2876 for (; !match && i>0; i--, p += 2)
2877 match = (x >= p[0] && x <= p[1]);
2882 match = (proto == IPPROTO_TCP && offset == 0 &&
2883 flags_match(cmd, TCP(ulp)->th_flags));
2887 match = (proto == IPPROTO_TCP && offset == 0 &&
2888 tcpopts_match(TCP(ulp), cmd));
2892 match = (proto == IPPROTO_TCP && offset == 0 &&
2893 ((ipfw_insn_u32 *)cmd)->d[0] ==
2898 match = (proto == IPPROTO_TCP && offset == 0 &&
2899 ((ipfw_insn_u32 *)cmd)->d[0] ==
2904 match = (proto == IPPROTO_TCP && offset == 0 &&
2905 cmd->arg1 == TCP(ulp)->th_win);
2909 /* reject packets which have SYN only */
2910 /* XXX should i also check for TH_ACK ? */
2911 match = (proto == IPPROTO_TCP && offset == 0 &&
2912 (TCP(ulp)->th_flags &
2913 (TH_RST | TH_ACK | TH_SYN)) != TH_SYN);
2918 ipfw_insn_altq *altq = (ipfw_insn_altq *)cmd;
2921 at = pf_find_mtag(m);
2922 if (at != NULL && at->qid != 0)
2924 at = pf_get_mtag(m);
2927 * Let the packet fall back to the
2932 at->qid = altq->qid;
2943 ipfw_log(f, hlen, args, m,
2944 oif, offset, tablearg, ip);
2949 match = (random()<((ipfw_insn_u32 *)cmd)->d[0]);
2953 /* Outgoing packets automatically pass/match */
2954 match = ((oif != NULL) ||
2955 (m->m_pkthdr.rcvif == NULL) ||
2959 verify_path6(&(args->f_id.src_ip6),
2960 m->m_pkthdr.rcvif) :
2962 verify_path(src_ip, m->m_pkthdr.rcvif,
2967 /* Outgoing packets automatically pass/match */
2968 match = (hlen > 0 && ((oif != NULL) ||
2971 verify_path6(&(args->f_id.src_ip6),
2974 verify_path(src_ip, NULL, args->f_id.fib)));
2978 /* Outgoing packets automatically pass/match */
2979 if (oif == NULL && hlen > 0 &&
2980 ( (is_ipv4 && in_localaddr(src_ip))
2983 in6_localaddr(&(args->f_id.src_ip6)))
2988 is_ipv6 ? verify_path6(
2989 &(args->f_id.src_ip6),
2990 m->m_pkthdr.rcvif) :
3001 match = (m_tag_find(m,
3002 PACKET_TAG_IPSEC_IN_DONE, NULL) != NULL);
3004 /* otherwise no match */
3010 IN6_ARE_ADDR_EQUAL(&args->f_id.src_ip6,
3011 &((ipfw_insn_ip6 *)cmd)->addr6);
3016 IN6_ARE_ADDR_EQUAL(&args->f_id.dst_ip6,
3017 &((ipfw_insn_ip6 *)cmd)->addr6);
3019 case O_IP6_SRC_MASK:
3020 case O_IP6_DST_MASK:
3024 struct in6_addr *d =
3025 &((ipfw_insn_ip6 *)cmd)->addr6;
3027 for (; !match && i > 0; d += 2,
3028 i -= F_INSN_SIZE(struct in6_addr)
3034 APPLY_MASK(&p, &d[1]);
3036 IN6_ARE_ADDR_EQUAL(&d[0],
3043 match= is_ipv6 && search_ip6_addr_net(&args->f_id.src_ip6);
3047 match= is_ipv6 && search_ip6_addr_net(&args->f_id.dst_ip6);
3052 flow6id_match(args->f_id.flow_id6,
3053 (ipfw_insn_u32 *) cmd);
3058 (ext_hd & ((ipfw_insn *) cmd)->arg1);
3071 uint32_t tag = (cmd->arg1 == IP_FW_TABLEARG) ?
3072 tablearg : cmd->arg1;
3074 /* Packet is already tagged with this tag? */
3075 mtag = m_tag_locate(m, MTAG_IPFW, tag, NULL);
3077 /* We have `untag' action when F_NOT flag is
3078 * present. And we must remove this mtag from
3079 * mbuf and reset `match' to zero (`match' will
3080 * be inversed later).
3081 * Otherwise we should allocate new mtag and
3082 * push it into mbuf.
3084 if (cmd->len & F_NOT) { /* `untag' action */
3086 m_tag_delete(m, mtag);
3087 } else if (mtag == NULL) {
3088 if ((mtag = m_tag_alloc(MTAG_IPFW,
3089 tag, 0, M_NOWAIT)) != NULL)
3090 m_tag_prepend(m, mtag);
3092 match = (cmd->len & F_NOT) ? 0: 1;
3096 case O_FIB: /* try match the specified fib */
3097 if (args->f_id.fib == cmd->arg1)
3102 uint32_t tag = (cmd->arg1 == IP_FW_TABLEARG) ?
3103 tablearg : cmd->arg1;
3106 match = m_tag_locate(m, MTAG_IPFW,
3111 /* we have ranges */
3112 for (mtag = m_tag_first(m);
3113 mtag != NULL && !match;
3114 mtag = m_tag_next(m, mtag)) {
3118 if (mtag->m_tag_cookie != MTAG_IPFW)
3121 p = ((ipfw_insn_u16 *)cmd)->ports;
3123 for(; !match && i > 0; i--, p += 2)
3125 mtag->m_tag_id >= p[0] &&
3126 mtag->m_tag_id <= p[1];
3132 * The second set of opcodes represents 'actions',
3133 * i.e. the terminal part of a rule once the packet
3134 * matches all previous patterns.
3135 * Typically there is only one action for each rule,
3136 * and the opcode is stored at the end of the rule
3137 * (but there are exceptions -- see below).
3139 * In general, here we set retval and terminate the
3140 * outer loop (would be a 'break 3' in some language,
3141 * but we need to do a 'goto done').
3144 * O_COUNT and O_SKIPTO actions:
3145 * instead of terminating, we jump to the next rule
3146 * ('goto next_rule', equivalent to a 'break 2'),
3147 * or to the SKIPTO target ('goto again' after
3148 * having set f, cmd and l), respectively.
3150 * O_TAG, O_LOG and O_ALTQ action parameters:
3151 * perform some action and set match = 1;
3153 * O_LIMIT and O_KEEP_STATE: these opcodes are
3154 * not real 'actions', and are stored right
3155 * before the 'action' part of the rule.
3156 * These opcodes try to install an entry in the
3157 * state tables; if successful, we continue with
3158 * the next opcode (match=1; break;), otherwise
3159 * the packet * must be dropped
3160 * ('goto done' after setting retval);
3162 * O_PROBE_STATE and O_CHECK_STATE: these opcodes
3163 * cause a lookup of the state table, and a jump
3164 * to the 'action' part of the parent rule
3165 * ('goto check_body') if an entry is found, or
3166 * (CHECK_STATE only) a jump to the next rule if
3167 * the entry is not found ('goto next_rule').
3168 * The result of the lookup is cached to make
3169 * further instances of these opcodes are
3174 if (install_state(f,
3175 (ipfw_insn_limit *)cmd, args, tablearg)) {
3176 retval = IP_FW_DENY;
3177 goto done; /* error/limit violation */
3185 * dynamic rules are checked at the first
3186 * keep-state or check-state occurrence,
3187 * with the result being stored in dyn_dir.
3188 * The compiler introduces a PROBE_STATE
3189 * instruction for us when we have a
3190 * KEEP_STATE (because PROBE_STATE needs
3193 if (dyn_dir == MATCH_UNKNOWN &&
3194 (q = lookup_dyn_rule(&args->f_id,
3195 &dyn_dir, proto == IPPROTO_TCP ?
3199 * Found dynamic entry, update stats
3200 * and jump to the 'action' part of
3206 cmd = ACTION_PTR(f);
3207 l = f->cmd_len - f->act_ofs;
3212 * Dynamic entry not found. If CHECK_STATE,
3213 * skip to next rule, if PROBE_STATE just
3214 * ignore and continue with next opcode.
3216 if (cmd->opcode == O_CHECK_STATE)
3222 retval = 0; /* accept */
3227 args->rule = f; /* report matching rule */
3228 args->rule_id = f->id;
3229 args->chain_id = chain->id;
3230 if (cmd->arg1 == IP_FW_TABLEARG)
3231 args->cookie = tablearg;
3233 args->cookie = cmd->arg1;
3234 retval = IP_FW_DUMMYNET;
3239 struct divert_tag *dt;
3241 if (args->eh) /* not on layer 2 */
3243 mtag = m_tag_get(PACKET_TAG_DIVERT,
3244 sizeof(struct divert_tag),
3249 IPFW_RUNLOCK(chain);
3250 if (ucred_cache != NULL)
3251 crfree(ucred_cache);
3252 return (IP_FW_DENY);
3254 dt = (struct divert_tag *)(mtag+1);
3255 dt->cookie = f->rulenum;
3256 if (cmd->arg1 == IP_FW_TABLEARG)
3257 dt->info = tablearg;
3259 dt->info = cmd->arg1;
3260 m_tag_prepend(m, mtag);
3261 retval = (cmd->opcode == O_DIVERT) ?
3262 IP_FW_DIVERT : IP_FW_TEE;
3267 f->pcnt++; /* update stats */
3269 f->timestamp = time_uptime;
3270 if (cmd->opcode == O_COUNT)
3273 if (cmd->arg1 == IP_FW_TABLEARG) {
3274 f = lookup_next_rule(f, tablearg);
3276 if (f->next_rule == NULL)
3277 lookup_next_rule(f, 0);
3284 * Drop the packet and send a reject notice
3285 * if the packet is not ICMP (or is an ICMP
3286 * query), and it is not multicast/broadcast.
3288 if (hlen > 0 && is_ipv4 && offset == 0 &&
3289 (proto != IPPROTO_ICMP ||
3290 is_icmp_query(ICMP(ulp))) &&
3291 !(m->m_flags & (M_BCAST|M_MCAST)) &&
3292 !IN_MULTICAST(ntohl(dst_ip.s_addr))) {
3293 send_reject(args, cmd->arg1, ip_len, ip);
3299 if (hlen > 0 && is_ipv6 &&
3300 ((offset & IP6F_OFF_MASK) == 0) &&
3301 (proto != IPPROTO_ICMPV6 ||
3302 (is_icmp6_query(args->f_id.flags) == 1)) &&
3303 !(m->m_flags & (M_BCAST|M_MCAST)) &&
3304 !IN6_IS_ADDR_MULTICAST(&args->f_id.dst_ip6)) {
3306 args, cmd->arg1, hlen,
3307 (struct ip6_hdr *)ip);
3313 retval = IP_FW_DENY;
3316 case O_FORWARD_IP: {
3317 struct sockaddr_in *sa;
3318 sa = &(((ipfw_insn_sa *)cmd)->sa);
3319 if (args->eh) /* not valid on layer2 pkts */
3321 if (!q || dyn_dir == MATCH_FORWARD) {
3322 if (sa->sin_addr.s_addr == INADDR_ANY) {
3323 bcopy(sa, &args->hopstore,
3325 args->hopstore.sin_addr.s_addr =
3330 args->next_hop = sa;
3333 retval = IP_FW_PASS;
3339 args->rule = f; /* report matching rule */
3340 args->rule_id = f->id;
3341 args->chain_id = chain->id;
3342 if (cmd->arg1 == IP_FW_TABLEARG)
3343 args->cookie = tablearg;
3345 args->cookie = cmd->arg1;
3346 retval = (cmd->opcode == O_NETGRAPH) ?
3347 IP_FW_NETGRAPH : IP_FW_NGTEE;
3351 f->pcnt++; /* update stats */
3353 f->timestamp = time_uptime;
3354 M_SETFIB(m, cmd->arg1);
3355 args->f_id.fib = cmd->arg1;
3362 if (IPFW_NAT_LOADED) {
3363 args->rule = f; /* Report matching rule. */
3364 args->rule_id = f->id;
3365 args->chain_id = chain->id;
3366 t = ((ipfw_insn_nat *)cmd)->nat;
3368 nat_id = (cmd->arg1 == IP_FW_TABLEARG) ?
3369 tablearg : cmd->arg1;
3370 LOOKUP_NAT(V_layer3_chain, nat_id, t);
3372 retval = IP_FW_DENY;
3375 if (cmd->arg1 != IP_FW_TABLEARG)
3376 ((ipfw_insn_nat *)cmd)->nat = t;
3378 retval = ipfw_nat_ptr(args, t, m);
3380 retval = IP_FW_DENY;
3389 ip_off = (args->eh != NULL) ? ntohs(ip->ip_off) : ip->ip_off;
3390 if (ip_off & (IP_MF | IP_OFFMASK)) {
3392 * ip_reass() expects len & off in host
3393 * byte order: fix them in case we come
3396 if (args->eh != NULL) {
3397 ip->ip_len = ntohs(ip->ip_len);
3398 ip->ip_off = ntohs(ip->ip_off);
3405 * IP header checksum fixup after
3406 * reassembly and leave header
3407 * in network byte order.
3412 ip = mtod(m, struct ip *);
3413 hlen = ip->ip_hl << 2;
3414 /* revert len & off for layer2 pkts */
3415 if (args->eh != NULL)
3416 ip->ip_len = htons(ip->ip_len);
3418 if (hlen == sizeof(struct ip))
3419 ip->ip_sum = in_cksum_hdr(ip);
3421 ip->ip_sum = in_cksum(m, hlen);
3422 retval = IP_FW_REASS;
3424 args->rule_id = f->id;
3425 args->chain_id = chain->id;
3428 retval = IP_FW_DENY;
3436 panic("-- unknown opcode %d\n", cmd->opcode);
3437 } /* end of switch() on opcodes */
3439 if (cmd->len & F_NOT)
3443 if (cmd->len & F_OR)
3446 if (!(cmd->len & F_OR)) /* not an OR block, */
3447 break; /* try next rule */
3450 } /* end of inner for, scan opcodes */
3452 next_rule:; /* try next rule */
3454 } /* end of outer for, scan rules */
3455 printf("ipfw: ouch!, skip past end of rules, denying packet\n");
3456 IPFW_RUNLOCK(chain);
3457 if (ucred_cache != NULL)
3458 crfree(ucred_cache);
3459 return (IP_FW_DENY);
3462 /* Update statistics */
3465 f->timestamp = time_uptime;
3466 IPFW_RUNLOCK(chain);
3467 if (ucred_cache != NULL)
3468 crfree(ucred_cache);
3473 printf("ipfw: pullup failed\n");
3474 return (IP_FW_DENY);
3478 * When a rule is added/deleted, clear the next_rule pointers in all rules.
3479 * These will be reconstructed on the fly as packets are matched.
3482 flush_rule_ptrs(struct ip_fw_chain *chain)
3486 IPFW_WLOCK_ASSERT(chain);
3490 for (rule = chain->rules; rule; rule = rule->next)
3491 rule->next_rule = NULL;
3495 * Add a new rule to the list. Copy the rule into a malloc'ed area, then
3496 * possibly create a rule number and add the rule to the list.
3497 * Update the rule_number in the input struct so the caller knows it as well.
3500 add_rule(struct ip_fw_chain *chain, struct ip_fw *input_rule)
3502 struct ip_fw *rule, *f, *prev;
3503 int l = RULESIZE(input_rule);
3505 if (chain->rules == NULL && input_rule->rulenum != IPFW_DEFAULT_RULE)
3508 rule = malloc(l, M_IPFW, M_NOWAIT | M_ZERO);
3512 bcopy(input_rule, rule, l);
3515 rule->next_rule = NULL;
3519 rule->timestamp = 0;
3523 if (chain->rules == NULL) { /* default rule */
3524 chain->rules = rule;
3525 rule->id = ++chain->id;
3530 * If rulenum is 0, find highest numbered rule before the
3531 * default rule, and add autoinc_step
3533 if (V_autoinc_step < 1)
3535 else if (V_autoinc_step > 1000)
3536 V_autoinc_step = 1000;
3537 if (rule->rulenum == 0) {
3539 * locate the highest numbered rule before default
3541 for (f = chain->rules; f; f = f->next) {
3542 if (f->rulenum == IPFW_DEFAULT_RULE)
3544 rule->rulenum = f->rulenum;
3546 if (rule->rulenum < IPFW_DEFAULT_RULE - V_autoinc_step)
3547 rule->rulenum += V_autoinc_step;
3548 input_rule->rulenum = rule->rulenum;
3552 * Now insert the new rule in the right place in the sorted list.
3554 for (prev = NULL, f = chain->rules; f; prev = f, f = f->next) {
3555 if (f->rulenum > rule->rulenum) { /* found the location */
3559 } else { /* head insert */
3560 rule->next = chain->rules;
3561 chain->rules = rule;
3566 flush_rule_ptrs(chain);
3567 /* chain->id incremented inside flush_rule_ptrs() */
3568 rule->id = chain->id;
3572 IPFW_WUNLOCK(chain);
3573 DEB(printf("ipfw: installed rule %d, static count now %d\n",
3574 rule->rulenum, V_static_count);)
3579 * Remove a static rule (including derived * dynamic rules)
3580 * and place it on the ``reap list'' for later reclamation.
3581 * The caller is in charge of clearing rule pointers to avoid
3582 * dangling pointers.
3583 * @return a pointer to the next entry.
3584 * Arguments are not checked, so they better be correct.
3586 static struct ip_fw *
3587 remove_rule(struct ip_fw_chain *chain, struct ip_fw *rule,
3591 int l = RULESIZE(rule);
3593 IPFW_WLOCK_ASSERT(chain);
3597 remove_dyn_rule(rule, NULL /* force removal */);
3606 rule->next = chain->reap;
3613 * Reclaim storage associated with a list of rules. This is
3614 * typically the list created using remove_rule.
3615 * A NULL pointer on input is handled correctly.
3618 reap_rules(struct ip_fw *head)
3622 while ((rule = head) != NULL) {
3629 * Remove all rules from a chain (except rules in set RESVD_SET
3630 * unless kill_default = 1). The caller is responsible for
3631 * reclaiming storage for the rules left in chain->reap.
3634 free_chain(struct ip_fw_chain *chain, int kill_default)
3636 struct ip_fw *prev, *rule;
3638 IPFW_WLOCK_ASSERT(chain);
3641 flush_rule_ptrs(chain); /* more efficient to do outside the loop */
3642 for (prev = NULL, rule = chain->rules; rule ; )
3643 if (kill_default || rule->set != RESVD_SET)
3644 rule = remove_rule(chain, rule, prev);
3652 * Remove all rules with given number, and also do set manipulation.
3653 * Assumes chain != NULL && *chain != NULL.
3655 * The argument is an u_int32_t. The low 16 bit are the rule or set number,
3656 * the next 8 bits are the new set, the top 8 bits are the command:
3658 * 0 delete rules with given number
3659 * 1 delete rules with given set number
3660 * 2 move rules with given number to new set
3661 * 3 move rules with given set number to new set
3662 * 4 swap sets with given numbers
3663 * 5 delete rules with given number and with given set number
3666 del_entry(struct ip_fw_chain *chain, u_int32_t arg)
3668 struct ip_fw *prev = NULL, *rule;
3669 u_int16_t rulenum; /* rule or old_set */
3670 u_int8_t cmd, new_set;
3672 rulenum = arg & 0xffff;
3673 cmd = (arg >> 24) & 0xff;
3674 new_set = (arg >> 16) & 0xff;
3676 if (cmd > 5 || new_set > RESVD_SET)
3678 if (cmd == 0 || cmd == 2 || cmd == 5) {
3679 if (rulenum >= IPFW_DEFAULT_RULE)
3682 if (rulenum > RESVD_SET) /* old_set */
3687 rule = chain->rules; /* common starting point */
3688 chain->reap = NULL; /* prepare for deletions */
3690 case 0: /* delete rules with given number */
3692 * locate first rule to delete
3694 for (; rule->rulenum < rulenum; prev = rule, rule = rule->next)
3696 if (rule->rulenum != rulenum) {
3697 IPFW_WUNLOCK(chain);
3702 * flush pointers outside the loop, then delete all matching
3703 * rules. prev remains the same throughout the cycle.
3705 flush_rule_ptrs(chain);
3706 while (rule->rulenum == rulenum)
3707 rule = remove_rule(chain, rule, prev);
3710 case 1: /* delete all rules with given set number */
3711 flush_rule_ptrs(chain);
3712 while (rule->rulenum < IPFW_DEFAULT_RULE) {
3713 if (rule->set == rulenum)
3714 rule = remove_rule(chain, rule, prev);
3722 case 2: /* move rules with given number to new set */
3723 for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
3724 if (rule->rulenum == rulenum)
3725 rule->set = new_set;
3728 case 3: /* move rules with given set number to new set */
3729 for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
3730 if (rule->set == rulenum)
3731 rule->set = new_set;
3734 case 4: /* swap two sets */
3735 for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
3736 if (rule->set == rulenum)
3737 rule->set = new_set;
3738 else if (rule->set == new_set)
3739 rule->set = rulenum;
3742 case 5: /* delete rules with given number and with given set number.
3743 * rulenum - given rule number;
3744 * new_set - given set number.
3746 for (; rule->rulenum < rulenum; prev = rule, rule = rule->next)
3748 if (rule->rulenum != rulenum) {
3749 IPFW_WUNLOCK(chain);
3752 flush_rule_ptrs(chain);
3753 while (rule->rulenum == rulenum) {
3754 if (rule->set == new_set)
3755 rule = remove_rule(chain, rule, prev);
3763 * Look for rules to reclaim. We grab the list before
3764 * releasing the lock then reclaim them w/o the lock to
3765 * avoid a LOR with dummynet.
3768 IPFW_WUNLOCK(chain);
3774 * Clear counters for a specific rule.
3775 * The enclosing "table" is assumed locked.
3778 clear_counters(struct ip_fw *rule, int log_only)
3780 ipfw_insn_log *l = (ipfw_insn_log *)ACTION_PTR(rule);
3782 if (log_only == 0) {
3783 rule->bcnt = rule->pcnt = 0;
3784 rule->timestamp = 0;
3786 if (l->o.opcode == O_LOG)
3787 l->log_left = l->max_log;
3791 * Reset some or all counters on firewall rules.
3792 * The argument `arg' is an u_int32_t. The low 16 bit are the rule number,
3793 * the next 8 bits are the set number, the top 8 bits are the command:
3794 * 0 work with rules from all set's;
3795 * 1 work with rules only from specified set.
3796 * Specified rule number is zero if we want to clear all entries.
3797 * log_only is 1 if we only want to reset logs, zero otherwise.
3800 zero_entry(struct ip_fw_chain *chain, u_int32_t arg, int log_only)
3805 uint16_t rulenum = arg & 0xffff;
3806 uint8_t set = (arg >> 16) & 0xff;
3807 uint8_t cmd = (arg >> 24) & 0xff;
3811 if (cmd == 1 && set > RESVD_SET)
3816 V_norule_counter = 0;
3817 for (rule = chain->rules; rule; rule = rule->next) {
3818 /* Skip rules from another set. */
3819 if (cmd == 1 && rule->set != set)
3821 clear_counters(rule, log_only);
3823 msg = log_only ? "All logging counts reset" :
3824 "Accounting cleared";
3828 * We can have multiple rules with the same number, so we
3829 * need to clear them all.
3831 for (rule = chain->rules; rule; rule = rule->next)
3832 if (rule->rulenum == rulenum) {
3833 while (rule && rule->rulenum == rulenum) {
3834 if (cmd == 0 || rule->set == set)
3835 clear_counters(rule, log_only);
3841 if (!cleared) { /* we did not find any matching rules */
3842 IPFW_WUNLOCK(chain);
3845 msg = log_only ? "logging count reset" : "cleared";
3847 IPFW_WUNLOCK(chain);
3850 int lev = LOG_SECURITY | LOG_NOTICE;
3853 log(lev, "ipfw: Entry %d %s.\n", rulenum, msg);
3855 log(lev, "ipfw: %s.\n", msg);
3861 * Check validity of the structure before insert.
3862 * Fortunately rules are simple, so this mostly need to check rule sizes.
3865 check_ipfw_struct(struct ip_fw *rule, int size)
3871 if (size < sizeof(*rule)) {
3872 printf("ipfw: rule too short\n");
3875 /* first, check for valid size */
3878 printf("ipfw: size mismatch (have %d want %d)\n", size, l);
3881 if (rule->act_ofs >= rule->cmd_len) {
3882 printf("ipfw: bogus action offset (%u > %u)\n",
3883 rule->act_ofs, rule->cmd_len - 1);
3887 * Now go for the individual checks. Very simple ones, basically only
3888 * instruction sizes.
3890 for (l = rule->cmd_len, cmd = rule->cmd ;
3891 l > 0 ; l -= cmdlen, cmd += cmdlen) {
3892 cmdlen = F_LEN(cmd);
3894 printf("ipfw: opcode %d size truncated\n",
3898 DEB(printf("ipfw: opcode %d\n", cmd->opcode);)
3899 switch (cmd->opcode) {
3911 case O_IPPRECEDENCE:
3929 if (cmdlen != F_INSN_SIZE(ipfw_insn))
3934 if (cmdlen != F_INSN_SIZE(ipfw_insn))
3936 if (cmd->arg1 >= rt_numfibs) {
3937 printf("ipfw: invalid fib number %d\n",
3944 if (cmdlen != F_INSN_SIZE(ipfw_insn))
3946 if (cmd->arg1 >= rt_numfibs) {
3947 printf("ipfw: invalid fib number %d\n",
3962 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32))
3967 if (cmdlen != F_INSN_SIZE(ipfw_insn_limit))
3972 if (cmdlen != F_INSN_SIZE(ipfw_insn_log))
3975 ((ipfw_insn_log *)cmd)->log_left =
3976 ((ipfw_insn_log *)cmd)->max_log;
3982 /* only odd command lengths */
3983 if ( !(cmdlen & 1) || cmdlen > 31)
3989 if (cmd->arg1 == 0 || cmd->arg1 > 256) {
3990 printf("ipfw: invalid set size %d\n",
3994 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
3999 case O_IP_SRC_LOOKUP:
4000 case O_IP_DST_LOOKUP:
4001 if (cmd->arg1 >= IPFW_TABLES_MAX) {
4002 printf("ipfw: invalid table number %d\n",
4006 if (cmdlen != F_INSN_SIZE(ipfw_insn) &&
4007 cmdlen != F_INSN_SIZE(ipfw_insn_u32))
4012 if (cmdlen != F_INSN_SIZE(ipfw_insn_mac))
4022 if (cmdlen < 1 || cmdlen > 31)
4028 case O_IP_DSTPORT: /* XXX artificial limit, 30 port pairs */
4029 if (cmdlen < 2 || cmdlen > 31)
4036 if (cmdlen != F_INSN_SIZE(ipfw_insn_if))
4041 if (cmdlen != F_INSN_SIZE(ipfw_insn_altq))
4047 if (cmdlen != F_INSN_SIZE(ipfw_insn))
4052 #ifdef IPFIREWALL_FORWARD
4053 if (cmdlen != F_INSN_SIZE(ipfw_insn_sa))
4062 if (ip_divert_ptr == NULL)
4068 if (!NG_IPFW_LOADED)
4073 if (!IPFW_NAT_LOADED)
4075 if (cmdlen != F_INSN_SIZE(ipfw_insn_nat))
4078 case O_FORWARD_MAC: /* XXX not implemented yet */
4090 if (cmdlen != F_INSN_SIZE(ipfw_insn))
4094 printf("ipfw: opcode %d, multiple actions"
4101 printf("ipfw: opcode %d, action must be"
4110 if (cmdlen != F_INSN_SIZE(struct in6_addr) +
4111 F_INSN_SIZE(ipfw_insn))
4116 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
4117 ((ipfw_insn_u32 *)cmd)->o.arg1)
4121 case O_IP6_SRC_MASK:
4122 case O_IP6_DST_MASK:
4123 if ( !(cmdlen & 1) || cmdlen > 127)
4127 if( cmdlen != F_INSN_SIZE( ipfw_insn_icmp6 ) )
4133 switch (cmd->opcode) {
4143 case O_IP6_SRC_MASK:
4144 case O_IP6_DST_MASK:
4146 printf("ipfw: no IPv6 support in kernel\n");
4147 return EPROTONOSUPPORT;
4150 printf("ipfw: opcode %d, unknown opcode\n",
4156 if (have_action == 0) {
4157 printf("ipfw: missing action\n");
4163 printf("ipfw: opcode %d size %d wrong\n",
4164 cmd->opcode, cmdlen);
4169 * Copy the static and dynamic rules to the supplied buffer
4170 * and return the amount of space actually used.
4173 ipfw_getrules(struct ip_fw_chain *chain, void *buf, size_t space)
4176 char *ep = bp + space;
4179 time_t boot_seconds;
4181 boot_seconds = boottime.tv_sec;
4182 /* XXX this can take a long time and locking will block packet flow */
4184 for (rule = chain->rules; rule ; rule = rule->next) {
4186 * Verify the entry fits in the buffer in case the
4187 * rules changed between calculating buffer space and
4188 * now. This would be better done using a generation
4189 * number but should suffice for now.
4195 * XXX HACK. Store the disable mask in the "next"
4196 * pointer in a wild attempt to keep the ABI the same.
4197 * Why do we do this on EVERY rule?
4199 bcopy(&V_set_disable,
4200 &(((struct ip_fw *)bp)->next_rule),
4201 sizeof(V_set_disable));
4202 if (((struct ip_fw *)bp)->timestamp)
4203 ((struct ip_fw *)bp)->timestamp += boot_seconds;
4207 IPFW_RUNLOCK(chain);
4209 ipfw_dyn_rule *p, *last = NULL;
4212 for (i = 0 ; i < V_curr_dyn_buckets; i++)
4213 for (p = V_ipfw_dyn_v[i] ; p != NULL; p = p->next) {
4214 if (bp + sizeof *p <= ep) {
4215 ipfw_dyn_rule *dst =
4216 (ipfw_dyn_rule *)bp;
4217 bcopy(p, dst, sizeof *p);
4218 bcopy(&(p->rule->rulenum), &(dst->rule),
4219 sizeof(p->rule->rulenum));
4221 * store set number into high word of
4222 * dst->rule pointer.
4224 bcopy(&(p->rule->set),
4225 (char *)&dst->rule +
4226 sizeof(p->rule->rulenum),
4227 sizeof(p->rule->set));
4229 * store a non-null value in "next".
4230 * The userland code will interpret a
4231 * NULL here as a marker
4232 * for the last dynamic rule.
4234 bcopy(&dst, &dst->next, sizeof(dst));
4237 TIME_LEQ(dst->expire, time_uptime) ?
4238 0 : dst->expire - time_uptime ;
4239 bp += sizeof(ipfw_dyn_rule);
4243 if (last != NULL) /* mark last dynamic rule */
4244 bzero(&last->next, sizeof(last));
4246 return (bp - (char *)buf);
4251 * {set|get}sockopt parser.
4254 ipfw_ctl(struct sockopt *sopt)
4256 #define RULE_MAXSIZE (256*sizeof(u_int32_t))
4259 struct ip_fw *buf, *rule;
4260 u_int32_t rulenum[2];
4262 error = priv_check(sopt->sopt_td, PRIV_NETINET_IPFW);
4267 * Disallow modifications in really-really secure mode, but still allow
4268 * the logging counters to be reset.
4270 if (sopt->sopt_name == IP_FW_ADD ||
4271 (sopt->sopt_dir == SOPT_SET && sopt->sopt_name != IP_FW_RESETLOG)) {
4272 error = securelevel_ge(sopt->sopt_td->td_ucred, 3);
4279 switch (sopt->sopt_name) {
4282 * pass up a copy of the current rules. Static rules
4283 * come first (the last of which has number IPFW_DEFAULT_RULE),
4284 * followed by a possibly empty list of dynamic rule.
4285 * The last dynamic rule has NULL in the "next" field.
4287 * Note that the calculated size is used to bound the
4288 * amount of data returned to the user. The rule set may
4289 * change between calculating the size and returning the
4290 * data in which case we'll just return what fits.
4292 size = V_static_len; /* size of static rules */
4293 if (V_ipfw_dyn_v) /* add size of dyn.rules */
4294 size += (V_dyn_count * sizeof(ipfw_dyn_rule));
4296 if (size >= sopt->sopt_valsize)
4299 * XXX todo: if the user passes a short length just to know
4300 * how much room is needed, do not bother filling up the
4301 * buffer, just jump to the sooptcopyout.
4303 buf = malloc(size, M_TEMP, M_WAITOK);
4304 error = sooptcopyout(sopt, buf,
4305 ipfw_getrules(&V_layer3_chain, buf, size));
4311 * Normally we cannot release the lock on each iteration.
4312 * We could do it here only because we start from the head all
4313 * the times so there is no risk of missing some entries.
4314 * On the other hand, the risk is that we end up with
4315 * a very inconsistent ruleset, so better keep the lock
4316 * around the whole cycle.
4318 * XXX this code can be improved by resetting the head of
4319 * the list to point to the default rule, and then freeing
4320 * the old list without the need for a lock.
4323 IPFW_WLOCK(&V_layer3_chain);
4324 free_chain(&V_layer3_chain, 0 /* keep default rule */);
4325 rule = V_layer3_chain.reap;
4326 IPFW_WUNLOCK(&V_layer3_chain);
4331 rule = malloc(RULE_MAXSIZE, M_TEMP, M_WAITOK);
4332 error = sooptcopyin(sopt, rule, RULE_MAXSIZE,
4333 sizeof(struct ip_fw) );
4335 error = check_ipfw_struct(rule, sopt->sopt_valsize);
4337 error = add_rule(&V_layer3_chain, rule);
4338 size = RULESIZE(rule);
4339 if (!error && sopt->sopt_dir == SOPT_GET)
4340 error = sooptcopyout(sopt, rule, size);
4347 * IP_FW_DEL is used for deleting single rules or sets,
4348 * and (ab)used to atomically manipulate sets. Argument size
4349 * is used to distinguish between the two:
4351 * delete single rule or set of rules,
4352 * or reassign rules (or sets) to a different set.
4353 * 2*sizeof(u_int32_t)
4354 * atomic disable/enable sets.
4355 * first u_int32_t contains sets to be disabled,
4356 * second u_int32_t contains sets to be enabled.
4358 error = sooptcopyin(sopt, rulenum,
4359 2*sizeof(u_int32_t), sizeof(u_int32_t));
4362 size = sopt->sopt_valsize;
4363 if (size == sizeof(u_int32_t)) /* delete or reassign */
4364 error = del_entry(&V_layer3_chain, rulenum[0]);
4365 else if (size == 2*sizeof(u_int32_t)) /* set enable/disable */
4367 (V_set_disable | rulenum[0]) & ~rulenum[1] &
4368 ~(1<<RESVD_SET); /* set RESVD_SET always enabled */
4374 case IP_FW_RESETLOG: /* argument is an u_int_32, the rule number */
4376 if (sopt->sopt_val != 0) {
4377 error = sooptcopyin(sopt, rulenum,
4378 sizeof(u_int32_t), sizeof(u_int32_t));
4382 error = zero_entry(&V_layer3_chain, rulenum[0],
4383 sopt->sopt_name == IP_FW_RESETLOG);
4386 case IP_FW_TABLE_ADD:
4388 ipfw_table_entry ent;
4390 error = sooptcopyin(sopt, &ent,
4391 sizeof(ent), sizeof(ent));
4394 error = add_table_entry(&V_layer3_chain, ent.tbl,
4395 ent.addr, ent.masklen, ent.value);
4399 case IP_FW_TABLE_DEL:
4401 ipfw_table_entry ent;
4403 error = sooptcopyin(sopt, &ent,
4404 sizeof(ent), sizeof(ent));
4407 error = del_table_entry(&V_layer3_chain, ent.tbl,
4408 ent.addr, ent.masklen);
4412 case IP_FW_TABLE_FLUSH:
4416 error = sooptcopyin(sopt, &tbl,
4417 sizeof(tbl), sizeof(tbl));
4420 IPFW_WLOCK(&V_layer3_chain);
4421 error = flush_table(&V_layer3_chain, tbl);
4422 IPFW_WUNLOCK(&V_layer3_chain);
4426 case IP_FW_TABLE_GETSIZE:
4430 if ((error = sooptcopyin(sopt, &tbl, sizeof(tbl),
4433 IPFW_RLOCK(&V_layer3_chain);
4434 error = count_table(&V_layer3_chain, tbl, &cnt);
4435 IPFW_RUNLOCK(&V_layer3_chain);
4438 error = sooptcopyout(sopt, &cnt, sizeof(cnt));
4442 case IP_FW_TABLE_LIST:
4446 if (sopt->sopt_valsize < sizeof(*tbl)) {
4450 size = sopt->sopt_valsize;
4451 tbl = malloc(size, M_TEMP, M_WAITOK);
4452 error = sooptcopyin(sopt, tbl, size, sizeof(*tbl));
4457 tbl->size = (size - sizeof(*tbl)) /
4458 sizeof(ipfw_table_entry);
4459 IPFW_RLOCK(&V_layer3_chain);
4460 error = dump_table(&V_layer3_chain, tbl);
4461 IPFW_RUNLOCK(&V_layer3_chain);
4466 error = sooptcopyout(sopt, tbl, size);
4472 if (IPFW_NAT_LOADED)
4473 error = ipfw_nat_cfg_ptr(sopt);
4475 printf("IP_FW_NAT_CFG: %s\n",
4476 "ipfw_nat not present, please load it");
4482 if (IPFW_NAT_LOADED)
4483 error = ipfw_nat_del_ptr(sopt);
4485 printf("IP_FW_NAT_DEL: %s\n",
4486 "ipfw_nat not present, please load it");
4491 case IP_FW_NAT_GET_CONFIG:
4492 if (IPFW_NAT_LOADED)
4493 error = ipfw_nat_get_cfg_ptr(sopt);
4495 printf("IP_FW_NAT_GET_CFG: %s\n",
4496 "ipfw_nat not present, please load it");
4501 case IP_FW_NAT_GET_LOG:
4502 if (IPFW_NAT_LOADED)
4503 error = ipfw_nat_get_log_ptr(sopt);
4505 printf("IP_FW_NAT_GET_LOG: %s\n",
4506 "ipfw_nat not present, please load it");
4512 printf("ipfw: ipfw_ctl invalid option %d\n", sopt->sopt_name);
4522 * This procedure is only used to handle keepalives. It is invoked
4523 * every dyn_keepalive_period
4526 ipfw_tick(void * vnetx)
4528 struct mbuf *m0, *m, *mnext, **mtailp;
4532 struct vnet *vp = vnetx;
4536 if (V_dyn_keepalive == 0 || V_ipfw_dyn_v == NULL || V_dyn_count == 0)
4540 * We make a chain of packets to go out here -- not deferring
4541 * until after we drop the IPFW dynamic rule lock would result
4542 * in a lock order reversal with the normal packet input -> ipfw
4548 for (i = 0 ; i < V_curr_dyn_buckets ; i++) {
4549 for (q = V_ipfw_dyn_v[i] ; q ; q = q->next ) {
4550 if (q->dyn_type == O_LIMIT_PARENT)
4552 if (q->id.proto != IPPROTO_TCP)
4554 if ( (q->state & BOTH_SYN) != BOTH_SYN)
4556 if (TIME_LEQ(time_uptime + V_dyn_keepalive_interval,
4558 continue; /* too early */
4559 if (TIME_LEQ(q->expire, time_uptime))
4560 continue; /* too late, rule expired */
4562 *mtailp = send_pkt(NULL, &(q->id), q->ack_rev - 1,
4563 q->ack_fwd, TH_SYN);
4564 if (*mtailp != NULL)
4565 mtailp = &(*mtailp)->m_nextpkt;
4566 *mtailp = send_pkt(NULL, &(q->id), q->ack_fwd - 1,
4568 if (*mtailp != NULL)
4569 mtailp = &(*mtailp)->m_nextpkt;
4573 for (m = mnext = m0; m != NULL; m = mnext) {
4574 mnext = m->m_nextpkt;
4575 m->m_nextpkt = NULL;
4576 ip_output(m, NULL, NULL, 0, NULL, NULL);
4579 callout_reset(&V_ipfw_timeout, V_dyn_keepalive_period * hz,
4585 * Stuff that must be initialised only on boot or module load
4592 ipfw_dyn_rule_zone = uma_zcreate("IPFW dynamic rule",
4593 sizeof(ipfw_dyn_rule), NULL, NULL, NULL, NULL,
4596 IPFW_DYN_LOCK_INIT();
4598 * Only print out this stuff the first time around,
4599 * when called from the sysinit code.
4605 "initialized, divert %s, nat %s, "
4606 "rule-based forwarding "
4607 #ifdef IPFIREWALL_FORWARD
4612 "default to %s, logging ",
4618 #ifdef IPFIREWALL_NAT
4623 default_to_accept ? "accept" : "deny");
4626 * Note: V_xxx variables can be accessed here but the vnet specific
4627 * initializer may not have been called yet for the VIMAGE case.
4628 * Tuneables will have been processed. We will print out values for
4630 * XXX This should all be rationalized AFTER 8.0
4632 if (V_fw_verbose == 0)
4633 printf("disabled\n");
4634 else if (V_verbose_limit == 0)
4635 printf("unlimited\n");
4637 printf("limited to %d packets/entry by default\n",
4641 * Hook us up to pfil.
4642 * Eventually pfil will be per vnet.
4644 if ((error = ipfw_hook()) != 0) {
4645 printf("ipfw_hook() error\n");
4649 if ((error = ipfw6_hook()) != 0) {
4650 printf("ipfw6_hook() error\n");
4655 * Other things that are only done the first time.
4656 * (now that we a re cuaranteed of success).
4658 ip_fw_ctl_ptr = ipfw_ctl;
4659 ip_fw_chk_ptr = ipfw_chk;
4664 * Stuff that must be initialized for every instance
4665 * (including the first of course).
4668 vnet_ipfw_init(const void *unused)
4671 struct ip_fw default_rule;
4673 /* First set up some values that are compile time options */
4674 #ifdef IPFIREWALL_VERBOSE
4677 #ifdef IPFIREWALL_VERBOSE_LIMIT
4678 V_verbose_limit = IPFIREWALL_VERBOSE_LIMIT;
4681 error = init_tables(&V_layer3_chain);
4683 panic("init_tables"); /* XXX Marko fix this ! */
4685 #ifdef IPFIREWALL_NAT
4686 LIST_INIT(&V_layer3_chain.nat);
4689 V_autoinc_step = 100; /* bounded to 1..1000 in add_rule() */
4691 V_ipfw_dyn_v = NULL;
4692 V_dyn_buckets = 256; /* must be power of 2 */
4693 V_curr_dyn_buckets = 256; /* must be power of 2 */
4695 V_dyn_ack_lifetime = 300;
4696 V_dyn_syn_lifetime = 20;
4697 V_dyn_fin_lifetime = 1;
4698 V_dyn_rst_lifetime = 1;
4699 V_dyn_udp_lifetime = 10;
4700 V_dyn_short_lifetime = 5;
4702 V_dyn_keepalive_interval = 20;
4703 V_dyn_keepalive_period = 5;
4704 V_dyn_keepalive = 1; /* do send keepalives */
4706 V_dyn_max = 4096; /* max # of dynamic rules */
4708 V_fw_deny_unknown_exthdrs = 1;
4710 V_layer3_chain.rules = NULL;
4711 IPFW_LOCK_INIT(&V_layer3_chain);
4712 callout_init(&V_ipfw_timeout, CALLOUT_MPSAFE);
4714 bzero(&default_rule, sizeof default_rule);
4715 default_rule.act_ofs = 0;
4716 default_rule.rulenum = IPFW_DEFAULT_RULE;
4717 default_rule.cmd_len = 1;
4718 default_rule.set = RESVD_SET;
4719 default_rule.cmd[0].len = 1;
4720 default_rule.cmd[0].opcode = default_to_accept ? O_ACCEPT : O_DENY;
4721 error = add_rule(&V_layer3_chain, &default_rule);
4724 printf("ipfw2: error %u initializing default rule "
4725 "(support disabled)\n", error);
4726 IPFW_LOCK_DESTROY(&V_layer3_chain);
4727 printf("leaving ipfw_iattach (1) with error %d\n", error);
4731 ip_fw_default_rule = V_layer3_chain.rules;
4734 IPFW_LOCK_DESTROY(&V_layer3_chain);
4735 printf("leaving ipfw_iattach (2) with error %d\n", error);
4738 #ifdef VIMAGE /* want a better way to do this */
4739 callout_reset(&V_ipfw_timeout, hz, ipfw_tick, curvnet);
4741 callout_reset(&V_ipfw_timeout, hz, ipfw_tick, NULL);
4744 /* First set up some values that are compile time options */
4745 V_ipfw_vnet_ready = 1; /* Open for business */
4749 /**********************
4750 * Called for the removal of the last instance only on module unload.
4756 uma_zdestroy(ipfw_dyn_rule_zone);
4757 IPFW_DYN_LOCK_DESTROY();
4758 printf("IP firewall unloaded\n");
4761 /***********************
4762 * Called for the removal of each instance.
4765 vnet_ipfw_uninit(const void *unused)
4769 V_ipfw_vnet_ready = 0; /* tell new callers to go away */
4770 callout_drain(&V_ipfw_timeout);
4771 /* We wait on the wlock here until the last user leaves */
4772 IPFW_WLOCK(&V_layer3_chain);
4773 flush_tables(&V_layer3_chain);
4774 V_layer3_chain.reap = NULL;
4775 free_chain(&V_layer3_chain, 1 /* kill default rule */);
4776 reap = V_layer3_chain.reap;
4777 V_layer3_chain.reap = NULL;
4778 IPFW_WUNLOCK(&V_layer3_chain);
4781 IPFW_LOCK_DESTROY(&V_layer3_chain);
4782 if (V_ipfw_dyn_v != NULL)
4783 free(V_ipfw_dyn_v, M_IPFW);
4788 * Module event handler.
4789 * In general we have the choice of handling most of these events by the
4790 * event handler or by the (VNET_)SYS(UN)INIT handlers. I have chosen to
4791 * use the SYSINIT handlers as they are more capable of expressing the
4792 * flow of control during module and vnet operations, so this is just
4793 * a skeleton. Note there is no SYSINIT equivalent of the module
4794 * SHUTDOWN handler, but we don't have anything to do in that case anyhow.
4797 ipfw_modevent(module_t mod, int type, void *unused)
4803 /* Called once at module load or
4804 * system boot if compiled in. */
4809 /* Yes, the unhooks can return errors, we can safely ignore
4810 * them. Eventually these will be done per jail as they
4811 * shut down. We will wait on each vnet's l3 lock as existing
4818 /* layer2 and other entrypoints still come in this way. */
4819 ip_fw_chk_ptr = NULL;
4820 ip_fw_ctl_ptr = NULL;
4821 /* Called during unload. */
4824 /* Called during system shutdown. */
4833 static moduledata_t ipfwmod = {
4839 /* Define startup order. */
4840 #define IPFW_SI_SUB_FIREWALL SI_SUB_PROTO_IFATTACHDOMAIN
4841 #define IPFW_MODEVENT_ORDER (SI_ORDER_ANY - 255) /* On boot slot in here. */
4842 #define IPFW_MODULE_ORDER (IPFW_MODEVENT_ORDER + 1) /* A little later. */
4843 #define IPFW_VNET_ORDER (IPFW_MODEVENT_ORDER + 2) /* Later still. */
4845 DECLARE_MODULE(ipfw, ipfwmod, IPFW_SI_SUB_FIREWALL, IPFW_MODEVENT_ORDER);
4846 MODULE_VERSION(ipfw, 2);
4847 /* should declare some dependencies here */
4850 * Starting up. Done in order after ipfwmod() has been called.
4851 * VNET_SYSINIT is also called for each existing vnet and each new vnet.
4853 SYSINIT(ipfw_init, IPFW_SI_SUB_FIREWALL, IPFW_MODULE_ORDER,
4855 VNET_SYSINIT(vnet_ipfw_init, IPFW_SI_SUB_FIREWALL, IPFW_VNET_ORDER,
4856 vnet_ipfw_init, NULL);
4859 * Closing up shop. These are done in REVERSE ORDER, but still
4860 * after ipfwmod() has been called. Not called on reboot.
4861 * VNET_SYSUNINIT is also called for each exiting vnet as it exits.
4862 * or when the module is unloaded.
4864 SYSUNINIT(ipfw_destroy, IPFW_SI_SUB_FIREWALL, IPFW_MODULE_ORDER,
4865 ipfw_destroy, NULL);
4866 VNET_SYSUNINIT(vnet_ipfw_uninit, IPFW_SI_SUB_FIREWALL, IPFW_VNET_ORDER,
4867 vnet_ipfw_uninit, NULL);