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>
106 * set_disable contains one bit per set value (0..31).
107 * If the bit is set, all rules with the corresponding set
108 * are disabled. Set RESVD_SET(31) is reserved for the default rule
109 * and rules that are not deleted by the flush command,
110 * and CANNOT be disabled.
111 * Rules in set RESVD_SET can only be deleted explicitly.
113 static VNET_DEFINE(u_int32_t, set_disable);
114 static VNET_DEFINE(int, fw_verbose);
115 static VNET_DEFINE(struct callout, ipfw_timeout);
116 static VNET_DEFINE(int, verbose_limit);
118 #define V_set_disable VNET(set_disable)
119 #define V_fw_verbose VNET(fw_verbose)
120 #define V_ipfw_timeout VNET(ipfw_timeout)
121 #define V_verbose_limit VNET(verbose_limit)
123 #ifdef IPFIREWALL_DEFAULT_TO_ACCEPT
124 static int default_to_accept = 1;
126 static int default_to_accept;
128 static uma_zone_t ipfw_dyn_rule_zone;
130 struct ip_fw *ip_fw_default_rule;
133 * list of rules for layer 3
135 VNET_DEFINE(struct ip_fw_chain, layer3_chain);
137 MALLOC_DEFINE(M_IPFW, "IpFw/IpAcct", "IpFw/IpAcct chain's");
138 MALLOC_DEFINE(M_IPFW_TBL, "ipfw_tbl", "IpFw tables");
139 #define IPFW_NAT_LOADED (ipfw_nat_ptr != NULL)
140 ipfw_nat_t *ipfw_nat_ptr = NULL;
141 ipfw_nat_cfg_t *ipfw_nat_cfg_ptr;
142 ipfw_nat_cfg_t *ipfw_nat_del_ptr;
143 ipfw_nat_cfg_t *ipfw_nat_get_cfg_ptr;
144 ipfw_nat_cfg_t *ipfw_nat_get_log_ptr;
147 struct radix_node rn[2];
148 struct sockaddr_in addr, mask;
152 static VNET_DEFINE(int, autoinc_step);
153 #define V_autoinc_step VNET(autoinc_step)
154 static VNET_DEFINE(int, fw_deny_unknown_exthdrs);
155 #define V_fw_deny_unknown_exthdrs VNET(fw_deny_unknown_exthdrs)
157 extern int ipfw_chg_hook(SYSCTL_HANDLER_ARGS);
160 SYSCTL_NODE(_net_inet_ip, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall");
161 SYSCTL_VNET_PROC(_net_inet_ip_fw, OID_AUTO, enable,
162 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE3, &VNET_NAME(fw_enable), 0,
163 ipfw_chg_hook, "I", "Enable ipfw");
164 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, autoinc_step,
165 CTLFLAG_RW, &VNET_NAME(autoinc_step), 0,
166 "Rule number auto-increment step");
167 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, one_pass,
168 CTLFLAG_RW | CTLFLAG_SECURE3, &VNET_NAME(fw_one_pass), 0,
169 "Only do a single pass through ipfw when using dummynet(4)");
170 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, verbose,
171 CTLFLAG_RW | CTLFLAG_SECURE3, &VNET_NAME(fw_verbose), 0,
172 "Log matches to ipfw rules");
173 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, verbose_limit,
174 CTLFLAG_RW, &VNET_NAME(verbose_limit), 0,
175 "Set upper limit of matches of ipfw rules logged");
176 SYSCTL_UINT(_net_inet_ip_fw, OID_AUTO, default_rule, CTLFLAG_RD,
177 NULL, IPFW_DEFAULT_RULE,
178 "The default/max possible rule number.");
179 SYSCTL_UINT(_net_inet_ip_fw, OID_AUTO, tables_max, CTLFLAG_RD,
180 NULL, IPFW_TABLES_MAX,
181 "The maximum number of tables.");
182 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, default_to_accept, CTLFLAG_RDTUN,
183 &default_to_accept, 0,
184 "Make the default rule accept all packets.");
185 TUNABLE_INT("net.inet.ip.fw.default_to_accept", &default_to_accept);
187 SYSCTL_DECL(_net_inet6_ip6);
188 SYSCTL_NODE(_net_inet6_ip6, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall");
189 SYSCTL_VNET_PROC(_net_inet6_ip6_fw, OID_AUTO, enable,
190 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE3, &VNET_NAME(fw6_enable), 0,
191 ipfw_chg_hook, "I", "Enable ipfw+6");
192 SYSCTL_VNET_INT(_net_inet6_ip6_fw, OID_AUTO, deny_unknown_exthdrs,
193 CTLFLAG_RW | CTLFLAG_SECURE, &VNET_NAME(fw_deny_unknown_exthdrs), 0,
194 "Deny packets with unknown IPv6 Extension Headers");
199 * Description of dynamic rules.
201 * Dynamic rules are stored in lists accessed through a hash table
202 * (ipfw_dyn_v) whose size is curr_dyn_buckets. This value can
203 * be modified through the sysctl variable dyn_buckets which is
204 * updated when the table becomes empty.
206 * XXX currently there is only one list, ipfw_dyn.
208 * When a packet is received, its address fields are first masked
209 * with the mask defined for the rule, then hashed, then matched
210 * against the entries in the corresponding list.
211 * Dynamic rules can be used for different purposes:
213 * + enforcing limits on the number of sessions;
214 * + in-kernel NAT (not implemented yet)
216 * The lifetime of dynamic rules is regulated by dyn_*_lifetime,
217 * measured in seconds and depending on the flags.
219 * The total number of dynamic rules is stored in dyn_count.
220 * The max number of dynamic rules is dyn_max. When we reach
221 * the maximum number of rules we do not create anymore. This is
222 * done to avoid consuming too much memory, but also too much
223 * time when searching on each packet (ideally, we should try instead
224 * to put a limit on the length of the list on each bucket...).
226 * Each dynamic rule holds a pointer to the parent ipfw rule so
227 * we know what action to perform. Dynamic rules are removed when
228 * the parent rule is deleted. XXX we should make them survive.
230 * There are some limitations with dynamic rules -- we do not
231 * obey the 'randomized match', and we do not do multiple
232 * passes through the firewall. XXX check the latter!!!
234 static VNET_DEFINE(ipfw_dyn_rule **, ipfw_dyn_v);
235 static VNET_DEFINE(u_int32_t, dyn_buckets);
236 static VNET_DEFINE(u_int32_t, curr_dyn_buckets);
238 #define V_ipfw_dyn_v VNET(ipfw_dyn_v)
239 #define V_dyn_buckets VNET(dyn_buckets)
240 #define V_curr_dyn_buckets VNET(curr_dyn_buckets)
242 static struct mtx ipfw_dyn_mtx; /* mutex guarding dynamic rules */
243 #define IPFW_DYN_LOCK_INIT() \
244 mtx_init(&ipfw_dyn_mtx, "IPFW dynamic rules", NULL, MTX_DEF)
245 #define IPFW_DYN_LOCK_DESTROY() mtx_destroy(&ipfw_dyn_mtx)
246 #define IPFW_DYN_LOCK() mtx_lock(&ipfw_dyn_mtx)
247 #define IPFW_DYN_UNLOCK() mtx_unlock(&ipfw_dyn_mtx)
248 #define IPFW_DYN_LOCK_ASSERT() mtx_assert(&ipfw_dyn_mtx, MA_OWNED)
251 * Timeouts for various events in handing dynamic rules.
253 static VNET_DEFINE(u_int32_t, dyn_ack_lifetime);
254 static VNET_DEFINE(u_int32_t, dyn_syn_lifetime);
255 static VNET_DEFINE(u_int32_t, dyn_fin_lifetime);
256 static VNET_DEFINE(u_int32_t, dyn_rst_lifetime);
257 static VNET_DEFINE(u_int32_t, dyn_udp_lifetime);
258 static VNET_DEFINE(u_int32_t, dyn_short_lifetime);
260 #define V_dyn_ack_lifetime VNET(dyn_ack_lifetime)
261 #define V_dyn_syn_lifetime VNET(dyn_syn_lifetime)
262 #define V_dyn_fin_lifetime VNET(dyn_fin_lifetime)
263 #define V_dyn_rst_lifetime VNET(dyn_rst_lifetime)
264 #define V_dyn_udp_lifetime VNET(dyn_udp_lifetime)
265 #define V_dyn_short_lifetime VNET(dyn_short_lifetime)
268 * Keepalives are sent if dyn_keepalive is set. They are sent every
269 * dyn_keepalive_period seconds, in the last dyn_keepalive_interval
270 * seconds of lifetime of a rule.
271 * dyn_rst_lifetime and dyn_fin_lifetime should be strictly lower
272 * than dyn_keepalive_period.
275 static VNET_DEFINE(u_int32_t, dyn_keepalive_interval);
276 static VNET_DEFINE(u_int32_t, dyn_keepalive_period);
277 static VNET_DEFINE(u_int32_t, dyn_keepalive);
279 #define V_dyn_keepalive_interval VNET(dyn_keepalive_interval)
280 #define V_dyn_keepalive_period VNET(dyn_keepalive_period)
281 #define V_dyn_keepalive VNET(dyn_keepalive)
283 static VNET_DEFINE(u_int32_t, static_count); /* # of static rules */
284 static VNET_DEFINE(u_int32_t, static_len); /* bytes of static rules */
285 static VNET_DEFINE(u_int32_t, dyn_count); /* # of dynamic rules */
286 static VNET_DEFINE(u_int32_t, dyn_max); /* max # of dynamic rules */
288 #define V_static_count VNET(static_count)
289 #define V_static_len VNET(static_len)
290 #define V_dyn_count VNET(dyn_count)
291 #define V_dyn_max VNET(dyn_max)
294 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_buckets,
295 CTLFLAG_RW, &VNET_NAME(dyn_buckets), 0,
296 "Number of dyn. buckets");
297 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, curr_dyn_buckets,
298 CTLFLAG_RD, &VNET_NAME(curr_dyn_buckets), 0,
299 "Current Number of dyn. buckets");
300 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_count,
301 CTLFLAG_RD, &VNET_NAME(dyn_count), 0,
302 "Number of dyn. rules");
303 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_max,
304 CTLFLAG_RW, &VNET_NAME(dyn_max), 0,
305 "Max number of dyn. rules");
306 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, static_count,
307 CTLFLAG_RD, &VNET_NAME(static_count), 0,
308 "Number of static rules");
309 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_ack_lifetime,
310 CTLFLAG_RW, &VNET_NAME(dyn_ack_lifetime), 0,
311 "Lifetime of dyn. rules for acks");
312 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_syn_lifetime,
313 CTLFLAG_RW, &VNET_NAME(dyn_syn_lifetime), 0,
314 "Lifetime of dyn. rules for syn");
315 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_fin_lifetime,
316 CTLFLAG_RW, &VNET_NAME(dyn_fin_lifetime), 0,
317 "Lifetime of dyn. rules for fin");
318 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_rst_lifetime,
319 CTLFLAG_RW, &VNET_NAME(dyn_rst_lifetime), 0,
320 "Lifetime of dyn. rules for rst");
321 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_udp_lifetime,
322 CTLFLAG_RW, &VNET_NAME(dyn_udp_lifetime), 0,
323 "Lifetime of dyn. rules for UDP");
324 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_short_lifetime,
325 CTLFLAG_RW, &VNET_NAME(dyn_short_lifetime), 0,
326 "Lifetime of dyn. rules for other situations");
327 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_keepalive,
328 CTLFLAG_RW, &VNET_NAME(dyn_keepalive), 0,
329 "Enable keepalives for dyn. rules");
330 #endif /* SYSCTL_NODE */
333 * L3HDR maps an ipv4 pointer into a layer3 header pointer of type T
334 * Other macros just cast void * into the appropriate type
336 #define L3HDR(T, ip) ((T *)((u_int32_t *)(ip) + (ip)->ip_hl))
337 #define TCP(p) ((struct tcphdr *)(p))
338 #define SCTP(p) ((struct sctphdr *)(p))
339 #define UDP(p) ((struct udphdr *)(p))
340 #define ICMP(p) ((struct icmphdr *)(p))
341 #define ICMP6(p) ((struct icmp6_hdr *)(p))
344 icmptype_match(struct icmphdr *icmp, ipfw_insn_u32 *cmd)
346 int type = icmp->icmp_type;
348 return (type <= ICMP_MAXTYPE && (cmd->d[0] & (1<<type)) );
351 #define TT ( (1 << ICMP_ECHO) | (1 << ICMP_ROUTERSOLICIT) | \
352 (1 << ICMP_TSTAMP) | (1 << ICMP_IREQ) | (1 << ICMP_MASKREQ) )
355 is_icmp_query(struct icmphdr *icmp)
357 int type = icmp->icmp_type;
359 return (type <= ICMP_MAXTYPE && (TT & (1<<type)) );
364 * The following checks use two arrays of 8 or 16 bits to store the
365 * bits that we want set or clear, respectively. They are in the
366 * low and high half of cmd->arg1 or cmd->d[0].
368 * We scan options and store the bits we find set. We succeed if
370 * (want_set & ~bits) == 0 && (want_clear & ~bits) == want_clear
372 * The code is sometimes optimized not to store additional variables.
376 flags_match(ipfw_insn *cmd, u_int8_t bits)
381 if ( ((cmd->arg1 & 0xff) & bits) != 0)
382 return 0; /* some bits we want set were clear */
383 want_clear = (cmd->arg1 >> 8) & 0xff;
384 if ( (want_clear & bits) != want_clear)
385 return 0; /* some bits we want clear were set */
390 ipopts_match(struct ip *ip, ipfw_insn *cmd)
392 int optlen, bits = 0;
393 u_char *cp = (u_char *)(ip + 1);
394 int x = (ip->ip_hl << 2) - sizeof (struct ip);
396 for (; x > 0; x -= optlen, cp += optlen) {
397 int opt = cp[IPOPT_OPTVAL];
399 if (opt == IPOPT_EOL)
401 if (opt == IPOPT_NOP)
404 optlen = cp[IPOPT_OLEN];
405 if (optlen <= 0 || optlen > x)
406 return 0; /* invalid or truncated */
414 bits |= IP_FW_IPOPT_LSRR;
418 bits |= IP_FW_IPOPT_SSRR;
422 bits |= IP_FW_IPOPT_RR;
426 bits |= IP_FW_IPOPT_TS;
430 return (flags_match(cmd, bits));
434 tcpopts_match(struct tcphdr *tcp, ipfw_insn *cmd)
436 int optlen, bits = 0;
437 u_char *cp = (u_char *)(tcp + 1);
438 int x = (tcp->th_off << 2) - sizeof(struct tcphdr);
440 for (; x > 0; x -= optlen, cp += optlen) {
442 if (opt == TCPOPT_EOL)
444 if (opt == TCPOPT_NOP)
458 bits |= IP_FW_TCPOPT_MSS;
462 bits |= IP_FW_TCPOPT_WINDOW;
465 case TCPOPT_SACK_PERMITTED:
467 bits |= IP_FW_TCPOPT_SACK;
470 case TCPOPT_TIMESTAMP:
471 bits |= IP_FW_TCPOPT_TS;
476 return (flags_match(cmd, bits));
480 iface_match(struct ifnet *ifp, ipfw_insn_if *cmd)
482 if (ifp == NULL) /* no iface with this packet, match fails */
484 /* Check by name or by IP address */
485 if (cmd->name[0] != '\0') { /* match by name */
488 if (fnmatch(cmd->name, ifp->if_xname, 0) == 0)
491 if (strncmp(ifp->if_xname, cmd->name, IFNAMSIZ) == 0)
498 TAILQ_FOREACH(ia, &ifp->if_addrhead, ifa_link) {
499 if (ia->ifa_addr->sa_family != AF_INET)
501 if (cmd->p.ip.s_addr == ((struct sockaddr_in *)
502 (ia->ifa_addr))->sin_addr.s_addr) {
503 if_addr_runlock(ifp);
504 return(1); /* match */
507 if_addr_runlock(ifp);
509 return(0); /* no match, fail ... */
513 * The verify_path function checks if a route to the src exists and
514 * if it is reachable via ifp (when provided).
516 * The 'verrevpath' option checks that the interface that an IP packet
517 * arrives on is the same interface that traffic destined for the
518 * packet's source address would be routed out of. The 'versrcreach'
519 * option just checks that the source address is reachable via any route
520 * (except default) in the routing table. These two are a measure to block
521 * forged packets. This is also commonly known as "anti-spoofing" or Unicast
522 * Reverse Path Forwarding (Unicast RFP) in Cisco-ese. The name of the knobs
523 * is purposely reminiscent of the Cisco IOS command,
525 * ip verify unicast reverse-path
526 * ip verify unicast source reachable-via any
528 * which implements the same functionality. But note that syntax is
529 * misleading. The check may be performed on all IP packets whether unicast,
530 * multicast, or broadcast.
533 verify_path(struct in_addr src, struct ifnet *ifp, u_int fib)
536 struct sockaddr_in *dst;
538 bzero(&ro, sizeof(ro));
540 dst = (struct sockaddr_in *)&(ro.ro_dst);
541 dst->sin_family = AF_INET;
542 dst->sin_len = sizeof(*dst);
544 in_rtalloc_ign(&ro, 0, fib);
546 if (ro.ro_rt == NULL)
550 * If ifp is provided, check for equality with rtentry.
551 * We should use rt->rt_ifa->ifa_ifp, instead of rt->rt_ifp,
552 * in order to pass packets injected back by if_simloop():
553 * if useloopback == 1 routing entry (via lo0) for our own address
554 * may exist, so we need to handle routing assymetry.
556 if (ifp != NULL && ro.ro_rt->rt_ifa->ifa_ifp != ifp) {
561 /* if no ifp provided, check if rtentry is not default route */
563 satosin(rt_key(ro.ro_rt))->sin_addr.s_addr == INADDR_ANY) {
568 /* or if this is a blackhole/reject route */
569 if (ifp == NULL && ro.ro_rt->rt_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
574 /* found valid route */
581 * ipv6 specific rules here...
584 icmp6type_match (int type, ipfw_insn_u32 *cmd)
586 return (type <= ICMP6_MAXTYPE && (cmd->d[type/32] & (1<<(type%32)) ) );
590 flow6id_match( int curr_flow, ipfw_insn_u32 *cmd )
593 for (i=0; i <= cmd->o.arg1; ++i )
594 if (curr_flow == cmd->d[i] )
599 /* support for IP6_*_ME opcodes */
601 search_ip6_addr_net (struct in6_addr * ip6_addr)
605 struct in6_ifaddr *fdm;
606 struct in6_addr copia;
608 TAILQ_FOREACH(mdc, &V_ifnet, if_link) {
610 TAILQ_FOREACH(mdc2, &mdc->if_addrhead, ifa_link) {
611 if (mdc2->ifa_addr->sa_family == AF_INET6) {
612 fdm = (struct in6_ifaddr *)mdc2;
613 copia = fdm->ia_addr.sin6_addr;
614 /* need for leaving scope_id in the sock_addr */
615 in6_clearscope(&copia);
616 if (IN6_ARE_ADDR_EQUAL(ip6_addr, &copia)) {
617 if_addr_runlock(mdc);
622 if_addr_runlock(mdc);
628 verify_path6(struct in6_addr *src, struct ifnet *ifp)
631 struct sockaddr_in6 *dst;
633 bzero(&ro, sizeof(ro));
635 dst = (struct sockaddr_in6 * )&(ro.ro_dst);
636 dst->sin6_family = AF_INET6;
637 dst->sin6_len = sizeof(*dst);
638 dst->sin6_addr = *src;
639 /* XXX MRT 0 for ipv6 at this time */
640 rtalloc_ign((struct route *)&ro, 0);
642 if (ro.ro_rt == NULL)
646 * if ifp is provided, check for equality with rtentry
647 * We should use rt->rt_ifa->ifa_ifp, instead of rt->rt_ifp,
648 * to support the case of sending packets to an address of our own.
649 * (where the former interface is the first argument of if_simloop()
650 * (=ifp), the latter is lo0)
652 if (ifp != NULL && ro.ro_rt->rt_ifa->ifa_ifp != ifp) {
657 /* if no ifp provided, check if rtentry is not default route */
659 IN6_IS_ADDR_UNSPECIFIED(&satosin6(rt_key(ro.ro_rt))->sin6_addr)) {
664 /* or if this is a blackhole/reject route */
665 if (ifp == NULL && ro.ro_rt->rt_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
670 /* found valid route */
676 hash_packet6(struct ipfw_flow_id *id)
679 i = (id->dst_ip6.__u6_addr.__u6_addr32[2]) ^
680 (id->dst_ip6.__u6_addr.__u6_addr32[3]) ^
681 (id->src_ip6.__u6_addr.__u6_addr32[2]) ^
682 (id->src_ip6.__u6_addr.__u6_addr32[3]) ^
683 (id->dst_port) ^ (id->src_port);
688 is_icmp6_query(int icmp6_type)
690 if ((icmp6_type <= ICMP6_MAXTYPE) &&
691 (icmp6_type == ICMP6_ECHO_REQUEST ||
692 icmp6_type == ICMP6_MEMBERSHIP_QUERY ||
693 icmp6_type == ICMP6_WRUREQUEST ||
694 icmp6_type == ICMP6_FQDN_QUERY ||
695 icmp6_type == ICMP6_NI_QUERY))
702 send_reject6(struct ip_fw_args *args, int code, u_int hlen, struct ip6_hdr *ip6)
707 if (code == ICMP6_UNREACH_RST && args->f_id.proto == IPPROTO_TCP) {
715 tcp = (struct tcphdr *)((char *)ip6 + hlen);
717 if ((tcp->th_flags & TH_RST) != 0) {
725 ti.th.th_seq = ntohl(ti.th.th_seq);
726 ti.th.th_ack = ntohl(ti.th.th_ack);
727 ti.ip6.ip6_nxt = IPPROTO_TCP;
729 if (ti.th.th_flags & TH_ACK) {
735 if ((m->m_flags & M_PKTHDR) != 0) {
737 * total new data to ACK is:
738 * total packet length,
739 * minus the header length,
740 * minus the tcp header length.
742 ack += m->m_pkthdr.len - hlen
743 - (ti.th.th_off << 2);
744 } else if (ip6->ip6_plen) {
745 ack += ntohs(ip6->ip6_plen) + sizeof(*ip6) -
746 hlen - (ti.th.th_off << 2);
751 if (tcp->th_flags & TH_SYN)
754 flags = TH_RST|TH_ACK;
756 bcopy(&ti, ip6, sizeof(ti));
758 * m is only used to recycle the mbuf
759 * The data in it is never read so we don't need
760 * to correct the offsets or anything
762 tcp_respond(NULL, ip6, tcp, m, ack, seq, flags);
763 } else if (code != ICMP6_UNREACH_RST) { /* Send an ICMPv6 unreach. */
766 * Unlike above, the mbufs need to line up with the ip6 hdr,
767 * as the contents are read. We need to m_adj() the
769 * The mbuf will however be thrown away so we can adjust it.
770 * Remember we did an m_pullup on it already so we
771 * can make some assumptions about contiguousness.
774 m_adj(m, args->L3offset);
776 icmp6_error(m, ICMP6_DST_UNREACH, code, 0);
785 /* counter for ipfw_log(NULL...) */
786 static VNET_DEFINE(u_int64_t, norule_counter);
787 #define V_norule_counter VNET(norule_counter)
789 #define SNPARGS(buf, len) buf + len, sizeof(buf) > len ? sizeof(buf) - len : 0
790 #define SNP(buf) buf, sizeof(buf)
793 * We enter here when we have a rule with O_LOG.
794 * XXX this function alone takes about 2Kbytes of code!
797 ipfw_log(struct ip_fw *f, u_int hlen, struct ip_fw_args *args,
798 struct mbuf *m, struct ifnet *oif, u_short offset, uint32_t tablearg,
801 struct ether_header *eh = args->eh;
803 int limit_reached = 0;
804 char action2[40], proto[128], fragment[32];
809 if (f == NULL) { /* bogus pkt */
810 if (V_verbose_limit != 0 && V_norule_counter >= V_verbose_limit)
813 if (V_norule_counter == V_verbose_limit)
814 limit_reached = V_verbose_limit;
816 } else { /* O_LOG is the first action, find the real one */
817 ipfw_insn *cmd = ACTION_PTR(f);
818 ipfw_insn_log *l = (ipfw_insn_log *)cmd;
820 if (l->max_log != 0 && l->log_left == 0)
823 if (l->log_left == 0)
824 limit_reached = l->max_log;
825 cmd += F_LEN(cmd); /* point to first action */
826 if (cmd->opcode == O_ALTQ) {
827 ipfw_insn_altq *altq = (ipfw_insn_altq *)cmd;
829 snprintf(SNPARGS(action2, 0), "Altq %d",
833 if (cmd->opcode == O_PROB)
836 if (cmd->opcode == O_TAG)
840 switch (cmd->opcode) {
846 if (cmd->arg1==ICMP_REJECT_RST)
848 else if (cmd->arg1==ICMP_UNREACH_HOST)
851 snprintf(SNPARGS(action2, 0), "Unreach %d",
856 if (cmd->arg1==ICMP6_UNREACH_RST)
859 snprintf(SNPARGS(action2, 0), "Unreach %d",
870 snprintf(SNPARGS(action2, 0), "Divert %d",
874 snprintf(SNPARGS(action2, 0), "Tee %d",
878 snprintf(SNPARGS(action2, 0), "SetFib %d",
882 snprintf(SNPARGS(action2, 0), "SkipTo %d",
886 snprintf(SNPARGS(action2, 0), "Pipe %d",
890 snprintf(SNPARGS(action2, 0), "Queue %d",
894 ipfw_insn_sa *sa = (ipfw_insn_sa *)cmd;
896 struct in_addr dummyaddr;
897 if (sa->sa.sin_addr.s_addr == INADDR_ANY)
898 dummyaddr.s_addr = htonl(tablearg);
900 dummyaddr.s_addr = sa->sa.sin_addr.s_addr;
902 len = snprintf(SNPARGS(action2, 0), "Forward to %s",
903 inet_ntoa(dummyaddr));
906 snprintf(SNPARGS(action2, len), ":%d",
911 snprintf(SNPARGS(action2, 0), "Netgraph %d",
915 snprintf(SNPARGS(action2, 0), "Ngtee %d",
930 if (hlen == 0) { /* non-ip */
931 snprintf(SNPARGS(proto, 0), "MAC");
935 char src[48], dst[48];
936 struct icmphdr *icmp;
940 struct ip6_hdr *ip6 = NULL;
941 struct icmp6_hdr *icmp6;
946 if (IS_IP6_FLOW_ID(&(args->f_id))) {
947 char ip6buf[INET6_ADDRSTRLEN];
948 snprintf(src, sizeof(src), "[%s]",
949 ip6_sprintf(ip6buf, &args->f_id.src_ip6));
950 snprintf(dst, sizeof(dst), "[%s]",
951 ip6_sprintf(ip6buf, &args->f_id.dst_ip6));
953 ip6 = (struct ip6_hdr *)ip;
954 tcp = (struct tcphdr *)(((char *)ip) + hlen);
955 udp = (struct udphdr *)(((char *)ip) + hlen);
959 tcp = L3HDR(struct tcphdr, ip);
960 udp = L3HDR(struct udphdr, ip);
962 inet_ntoa_r(ip->ip_src, src);
963 inet_ntoa_r(ip->ip_dst, dst);
966 switch (args->f_id.proto) {
968 len = snprintf(SNPARGS(proto, 0), "TCP %s", src);
970 snprintf(SNPARGS(proto, len), ":%d %s:%d",
971 ntohs(tcp->th_sport),
973 ntohs(tcp->th_dport));
975 snprintf(SNPARGS(proto, len), " %s", dst);
979 len = snprintf(SNPARGS(proto, 0), "UDP %s", src);
981 snprintf(SNPARGS(proto, len), ":%d %s:%d",
982 ntohs(udp->uh_sport),
984 ntohs(udp->uh_dport));
986 snprintf(SNPARGS(proto, len), " %s", dst);
990 icmp = L3HDR(struct icmphdr, ip);
992 len = snprintf(SNPARGS(proto, 0),
994 icmp->icmp_type, icmp->icmp_code);
996 len = snprintf(SNPARGS(proto, 0), "ICMP ");
997 len += snprintf(SNPARGS(proto, len), "%s", src);
998 snprintf(SNPARGS(proto, len), " %s", dst);
1001 case IPPROTO_ICMPV6:
1002 icmp6 = (struct icmp6_hdr *)(((char *)ip) + hlen);
1004 len = snprintf(SNPARGS(proto, 0),
1006 icmp6->icmp6_type, icmp6->icmp6_code);
1008 len = snprintf(SNPARGS(proto, 0), "ICMPv6 ");
1009 len += snprintf(SNPARGS(proto, len), "%s", src);
1010 snprintf(SNPARGS(proto, len), " %s", dst);
1014 len = snprintf(SNPARGS(proto, 0), "P:%d %s",
1015 args->f_id.proto, src);
1016 snprintf(SNPARGS(proto, len), " %s", dst);
1021 if (IS_IP6_FLOW_ID(&(args->f_id))) {
1022 if (offset & (IP6F_OFF_MASK | IP6F_MORE_FRAG))
1023 snprintf(SNPARGS(fragment, 0),
1024 " (frag %08x:%d@%d%s)",
1025 args->f_id.frag_id6,
1026 ntohs(ip6->ip6_plen) - hlen,
1027 ntohs(offset & IP6F_OFF_MASK) << 3,
1028 (offset & IP6F_MORE_FRAG) ? "+" : "");
1033 if (eh != NULL) { /* layer 2 packets are as on the wire */
1034 ip_off = ntohs(ip->ip_off);
1035 ip_len = ntohs(ip->ip_len);
1037 ip_off = ip->ip_off;
1038 ip_len = ip->ip_len;
1040 if (ip_off & (IP_MF | IP_OFFMASK))
1041 snprintf(SNPARGS(fragment, 0),
1042 " (frag %d:%d@%d%s)",
1043 ntohs(ip->ip_id), ip_len - (ip->ip_hl << 2),
1045 (ip_off & IP_MF) ? "+" : "");
1048 if (oif || m->m_pkthdr.rcvif)
1049 log(LOG_SECURITY | LOG_INFO,
1050 "ipfw: %d %s %s %s via %s%s\n",
1051 f ? f->rulenum : -1,
1052 action, proto, oif ? "out" : "in",
1053 oif ? oif->if_xname : m->m_pkthdr.rcvif->if_xname,
1056 log(LOG_SECURITY | LOG_INFO,
1057 "ipfw: %d %s %s [no if info]%s\n",
1058 f ? f->rulenum : -1,
1059 action, proto, fragment);
1061 log(LOG_SECURITY | LOG_NOTICE,
1062 "ipfw: limit %d reached on entry %d\n",
1063 limit_reached, f ? f->rulenum : -1);
1067 * IMPORTANT: the hash function for dynamic rules must be commutative
1068 * in source and destination (ip,port), because rules are bidirectional
1069 * and we want to find both in the same bucket.
1072 hash_packet(struct ipfw_flow_id *id)
1077 if (IS_IP6_FLOW_ID(id))
1078 i = hash_packet6(id);
1081 i = (id->dst_ip) ^ (id->src_ip) ^ (id->dst_port) ^ (id->src_port);
1082 i &= (V_curr_dyn_buckets - 1);
1087 * unlink a dynamic rule from a chain. prev is a pointer to
1088 * the previous one, q is a pointer to the rule to delete,
1089 * head is a pointer to the head of the queue.
1090 * Modifies q and potentially also head.
1092 #define UNLINK_DYN_RULE(prev, head, q) { \
1093 ipfw_dyn_rule *old_q = q; \
1095 /* remove a refcount to the parent */ \
1096 if (q->dyn_type == O_LIMIT) \
1097 q->parent->count--; \
1098 DEB(printf("ipfw: unlink entry 0x%08x %d -> 0x%08x %d, %d left\n",\
1099 (q->id.src_ip), (q->id.src_port), \
1100 (q->id.dst_ip), (q->id.dst_port), V_dyn_count-1 ); ) \
1102 prev->next = q = q->next; \
1104 head = q = q->next; \
1106 uma_zfree(ipfw_dyn_rule_zone, old_q); }
1108 #define TIME_LEQ(a,b) ((int)((a)-(b)) <= 0)
1111 * Remove dynamic rules pointing to "rule", or all of them if rule == NULL.
1113 * If keep_me == NULL, rules are deleted even if not expired,
1114 * otherwise only expired rules are removed.
1116 * The value of the second parameter is also used to point to identify
1117 * a rule we absolutely do not want to remove (e.g. because we are
1118 * holding a reference to it -- this is the case with O_LIMIT_PARENT
1119 * rules). The pointer is only used for comparison, so any non-null
1123 remove_dyn_rule(struct ip_fw *rule, ipfw_dyn_rule *keep_me)
1125 static u_int32_t last_remove = 0;
1127 #define FORCE (keep_me == NULL)
1129 ipfw_dyn_rule *prev, *q;
1130 int i, pass = 0, max_pass = 0;
1132 IPFW_DYN_LOCK_ASSERT();
1134 if (V_ipfw_dyn_v == NULL || V_dyn_count == 0)
1136 /* do not expire more than once per second, it is useless */
1137 if (!FORCE && last_remove == time_uptime)
1139 last_remove = time_uptime;
1142 * because O_LIMIT refer to parent rules, during the first pass only
1143 * remove child and mark any pending LIMIT_PARENT, and remove
1144 * them in a second pass.
1147 for (i = 0 ; i < V_curr_dyn_buckets ; i++) {
1148 for (prev=NULL, q = V_ipfw_dyn_v[i] ; q ; ) {
1150 * Logic can become complex here, so we split tests.
1154 if (rule != NULL && rule != q->rule)
1155 goto next; /* not the one we are looking for */
1156 if (q->dyn_type == O_LIMIT_PARENT) {
1158 * handle parent in the second pass,
1159 * record we need one.
1164 if (FORCE && q->count != 0 ) {
1165 /* XXX should not happen! */
1166 printf("ipfw: OUCH! cannot remove rule,"
1167 " count %d\n", q->count);
1171 !TIME_LEQ( q->expire, time_uptime ))
1174 if (q->dyn_type != O_LIMIT_PARENT || !q->count) {
1175 UNLINK_DYN_RULE(prev, V_ipfw_dyn_v[i], q);
1183 if (pass++ < max_pass)
1189 * lookup a dynamic rule.
1191 static ipfw_dyn_rule *
1192 lookup_dyn_rule_locked(struct ipfw_flow_id *pkt, int *match_direction,
1196 * stateful ipfw extensions.
1197 * Lookup into dynamic session queue
1199 #define MATCH_REVERSE 0
1200 #define MATCH_FORWARD 1
1201 #define MATCH_NONE 2
1202 #define MATCH_UNKNOWN 3
1203 int i, dir = MATCH_NONE;
1204 ipfw_dyn_rule *prev, *q=NULL;
1206 IPFW_DYN_LOCK_ASSERT();
1208 if (V_ipfw_dyn_v == NULL)
1209 goto done; /* not found */
1210 i = hash_packet( pkt );
1211 for (prev=NULL, q = V_ipfw_dyn_v[i] ; q != NULL ; ) {
1212 if (q->dyn_type == O_LIMIT_PARENT && q->count)
1214 if (TIME_LEQ( q->expire, time_uptime)) { /* expire entry */
1215 UNLINK_DYN_RULE(prev, V_ipfw_dyn_v[i], q);
1218 if (pkt->proto == q->id.proto &&
1219 q->dyn_type != O_LIMIT_PARENT) {
1220 if (IS_IP6_FLOW_ID(pkt)) {
1221 if (IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
1222 &(q->id.src_ip6)) &&
1223 IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
1224 &(q->id.dst_ip6)) &&
1225 pkt->src_port == q->id.src_port &&
1226 pkt->dst_port == q->id.dst_port ) {
1227 dir = MATCH_FORWARD;
1230 if (IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
1231 &(q->id.dst_ip6)) &&
1232 IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
1233 &(q->id.src_ip6)) &&
1234 pkt->src_port == q->id.dst_port &&
1235 pkt->dst_port == q->id.src_port ) {
1236 dir = MATCH_REVERSE;
1240 if (pkt->src_ip == q->id.src_ip &&
1241 pkt->dst_ip == q->id.dst_ip &&
1242 pkt->src_port == q->id.src_port &&
1243 pkt->dst_port == q->id.dst_port ) {
1244 dir = MATCH_FORWARD;
1247 if (pkt->src_ip == q->id.dst_ip &&
1248 pkt->dst_ip == q->id.src_ip &&
1249 pkt->src_port == q->id.dst_port &&
1250 pkt->dst_port == q->id.src_port ) {
1251 dir = MATCH_REVERSE;
1261 goto done; /* q = NULL, not found */
1263 if ( prev != NULL) { /* found and not in front */
1264 prev->next = q->next;
1265 q->next = V_ipfw_dyn_v[i];
1266 V_ipfw_dyn_v[i] = q;
1268 if (pkt->proto == IPPROTO_TCP) { /* update state according to flags */
1269 u_char flags = pkt->flags & (TH_FIN|TH_SYN|TH_RST);
1271 #define BOTH_SYN (TH_SYN | (TH_SYN << 8))
1272 #define BOTH_FIN (TH_FIN | (TH_FIN << 8))
1273 q->state |= (dir == MATCH_FORWARD ) ? flags : (flags << 8);
1275 case TH_SYN: /* opening */
1276 q->expire = time_uptime + V_dyn_syn_lifetime;
1279 case BOTH_SYN: /* move to established */
1280 case BOTH_SYN | TH_FIN : /* one side tries to close */
1281 case BOTH_SYN | (TH_FIN << 8) :
1283 #define _SEQ_GE(a,b) ((int)(a) - (int)(b) >= 0)
1284 u_int32_t ack = ntohl(tcp->th_ack);
1285 if (dir == MATCH_FORWARD) {
1286 if (q->ack_fwd == 0 || _SEQ_GE(ack, q->ack_fwd))
1288 else { /* ignore out-of-sequence */
1292 if (q->ack_rev == 0 || _SEQ_GE(ack, q->ack_rev))
1294 else { /* ignore out-of-sequence */
1299 q->expire = time_uptime + V_dyn_ack_lifetime;
1302 case BOTH_SYN | BOTH_FIN: /* both sides closed */
1303 if (V_dyn_fin_lifetime >= V_dyn_keepalive_period)
1304 V_dyn_fin_lifetime = V_dyn_keepalive_period - 1;
1305 q->expire = time_uptime + V_dyn_fin_lifetime;
1311 * reset or some invalid combination, but can also
1312 * occur if we use keep-state the wrong way.
1314 if ( (q->state & ((TH_RST << 8)|TH_RST)) == 0)
1315 printf("invalid state: 0x%x\n", q->state);
1317 if (V_dyn_rst_lifetime >= V_dyn_keepalive_period)
1318 V_dyn_rst_lifetime = V_dyn_keepalive_period - 1;
1319 q->expire = time_uptime + V_dyn_rst_lifetime;
1322 } else if (pkt->proto == IPPROTO_UDP) {
1323 q->expire = time_uptime + V_dyn_udp_lifetime;
1325 /* other protocols */
1326 q->expire = time_uptime + V_dyn_short_lifetime;
1329 if (match_direction)
1330 *match_direction = dir;
1334 static ipfw_dyn_rule *
1335 lookup_dyn_rule(struct ipfw_flow_id *pkt, int *match_direction,
1341 q = lookup_dyn_rule_locked(pkt, match_direction, tcp);
1344 /* NB: return table locked when q is not NULL */
1349 realloc_dynamic_table(void)
1351 IPFW_DYN_LOCK_ASSERT();
1354 * Try reallocation, make sure we have a power of 2 and do
1355 * not allow more than 64k entries. In case of overflow,
1359 if (V_dyn_buckets > 65536)
1360 V_dyn_buckets = 1024;
1361 if ((V_dyn_buckets & (V_dyn_buckets-1)) != 0) { /* not a power of 2 */
1362 V_dyn_buckets = V_curr_dyn_buckets; /* reset */
1365 V_curr_dyn_buckets = V_dyn_buckets;
1366 if (V_ipfw_dyn_v != NULL)
1367 free(V_ipfw_dyn_v, M_IPFW);
1369 V_ipfw_dyn_v = malloc(V_curr_dyn_buckets * sizeof(ipfw_dyn_rule *),
1370 M_IPFW, M_NOWAIT | M_ZERO);
1371 if (V_ipfw_dyn_v != NULL || V_curr_dyn_buckets <= 2)
1373 V_curr_dyn_buckets /= 2;
1378 * Install state of type 'type' for a dynamic session.
1379 * The hash table contains two type of rules:
1380 * - regular rules (O_KEEP_STATE)
1381 * - rules for sessions with limited number of sess per user
1382 * (O_LIMIT). When they are created, the parent is
1383 * increased by 1, and decreased on delete. In this case,
1384 * the third parameter is the parent rule and not the chain.
1385 * - "parent" rules for the above (O_LIMIT_PARENT).
1387 static ipfw_dyn_rule *
1388 add_dyn_rule(struct ipfw_flow_id *id, u_int8_t dyn_type, struct ip_fw *rule)
1393 IPFW_DYN_LOCK_ASSERT();
1395 if (V_ipfw_dyn_v == NULL ||
1396 (V_dyn_count == 0 && V_dyn_buckets != V_curr_dyn_buckets)) {
1397 realloc_dynamic_table();
1398 if (V_ipfw_dyn_v == NULL)
1399 return NULL; /* failed ! */
1401 i = hash_packet(id);
1403 r = uma_zalloc(ipfw_dyn_rule_zone, M_NOWAIT | M_ZERO);
1405 printf ("ipfw: sorry cannot allocate state\n");
1409 /* increase refcount on parent, and set pointer */
1410 if (dyn_type == O_LIMIT) {
1411 ipfw_dyn_rule *parent = (ipfw_dyn_rule *)rule;
1412 if ( parent->dyn_type != O_LIMIT_PARENT)
1413 panic("invalid parent");
1416 rule = parent->rule;
1420 r->expire = time_uptime + V_dyn_syn_lifetime;
1422 r->dyn_type = dyn_type;
1423 r->pcnt = r->bcnt = 0;
1427 r->next = V_ipfw_dyn_v[i];
1428 V_ipfw_dyn_v[i] = r;
1430 DEB(printf("ipfw: add dyn entry ty %d 0x%08x %d -> 0x%08x %d, total %d\n",
1432 (r->id.src_ip), (r->id.src_port),
1433 (r->id.dst_ip), (r->id.dst_port),
1439 * lookup dynamic parent rule using pkt and rule as search keys.
1440 * If the lookup fails, then install one.
1442 static ipfw_dyn_rule *
1443 lookup_dyn_parent(struct ipfw_flow_id *pkt, struct ip_fw *rule)
1448 IPFW_DYN_LOCK_ASSERT();
1451 int is_v6 = IS_IP6_FLOW_ID(pkt);
1452 i = hash_packet( pkt );
1453 for (q = V_ipfw_dyn_v[i] ; q != NULL ; q=q->next)
1454 if (q->dyn_type == O_LIMIT_PARENT &&
1456 pkt->proto == q->id.proto &&
1457 pkt->src_port == q->id.src_port &&
1458 pkt->dst_port == q->id.dst_port &&
1461 IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
1462 &(q->id.src_ip6)) &&
1463 IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
1464 &(q->id.dst_ip6))) ||
1466 pkt->src_ip == q->id.src_ip &&
1467 pkt->dst_ip == q->id.dst_ip)
1470 q->expire = time_uptime + V_dyn_short_lifetime;
1471 DEB(printf("ipfw: lookup_dyn_parent found 0x%p\n",q);)
1475 return add_dyn_rule(pkt, O_LIMIT_PARENT, rule);
1479 * Install dynamic state for rule type cmd->o.opcode
1481 * Returns 1 (failure) if state is not installed because of errors or because
1482 * session limitations are enforced.
1485 install_state(struct ip_fw *rule, ipfw_insn_limit *cmd,
1486 struct ip_fw_args *args, uint32_t tablearg)
1488 static int last_log;
1491 char src[48], dst[48];
1497 printf("ipfw: %s: type %d 0x%08x %u -> 0x%08x %u\n",
1498 __func__, cmd->o.opcode,
1499 (args->f_id.src_ip), (args->f_id.src_port),
1500 (args->f_id.dst_ip), (args->f_id.dst_port));
1505 q = lookup_dyn_rule_locked(&args->f_id, NULL, NULL);
1507 if (q != NULL) { /* should never occur */
1508 if (last_log != time_uptime) {
1509 last_log = time_uptime;
1510 printf("ipfw: %s: entry already present, done\n",
1517 if (V_dyn_count >= V_dyn_max)
1518 /* Run out of slots, try to remove any expired rule. */
1519 remove_dyn_rule(NULL, (ipfw_dyn_rule *)1);
1521 if (V_dyn_count >= V_dyn_max) {
1522 if (last_log != time_uptime) {
1523 last_log = time_uptime;
1524 printf("ipfw: %s: Too many dynamic rules\n", __func__);
1527 return (1); /* cannot install, notify caller */
1530 switch (cmd->o.opcode) {
1531 case O_KEEP_STATE: /* bidir rule */
1532 add_dyn_rule(&args->f_id, O_KEEP_STATE, rule);
1535 case O_LIMIT: { /* limit number of sessions */
1536 struct ipfw_flow_id id;
1537 ipfw_dyn_rule *parent;
1538 uint32_t conn_limit;
1539 uint16_t limit_mask = cmd->limit_mask;
1541 conn_limit = (cmd->conn_limit == IP_FW_TABLEARG) ?
1542 tablearg : cmd->conn_limit;
1545 if (cmd->conn_limit == IP_FW_TABLEARG)
1546 printf("ipfw: %s: O_LIMIT rule, conn_limit: %u "
1547 "(tablearg)\n", __func__, conn_limit);
1549 printf("ipfw: %s: O_LIMIT rule, conn_limit: %u\n",
1550 __func__, conn_limit);
1553 id.dst_ip = id.src_ip = id.dst_port = id.src_port = 0;
1554 id.proto = args->f_id.proto;
1555 id.addr_type = args->f_id.addr_type;
1556 id.fib = M_GETFIB(args->m);
1558 if (IS_IP6_FLOW_ID (&(args->f_id))) {
1559 if (limit_mask & DYN_SRC_ADDR)
1560 id.src_ip6 = args->f_id.src_ip6;
1561 if (limit_mask & DYN_DST_ADDR)
1562 id.dst_ip6 = args->f_id.dst_ip6;
1564 if (limit_mask & DYN_SRC_ADDR)
1565 id.src_ip = args->f_id.src_ip;
1566 if (limit_mask & DYN_DST_ADDR)
1567 id.dst_ip = args->f_id.dst_ip;
1569 if (limit_mask & DYN_SRC_PORT)
1570 id.src_port = args->f_id.src_port;
1571 if (limit_mask & DYN_DST_PORT)
1572 id.dst_port = args->f_id.dst_port;
1573 if ((parent = lookup_dyn_parent(&id, rule)) == NULL) {
1574 printf("ipfw: %s: add parent failed\n", __func__);
1579 if (parent->count >= conn_limit) {
1580 /* See if we can remove some expired rule. */
1581 remove_dyn_rule(rule, parent);
1582 if (parent->count >= conn_limit) {
1583 if (V_fw_verbose && last_log != time_uptime) {
1584 last_log = time_uptime;
1587 * XXX IPv6 flows are not
1590 if (IS_IP6_FLOW_ID(&(args->f_id))) {
1591 char ip6buf[INET6_ADDRSTRLEN];
1592 snprintf(src, sizeof(src),
1593 "[%s]", ip6_sprintf(ip6buf,
1594 &args->f_id.src_ip6));
1595 snprintf(dst, sizeof(dst),
1596 "[%s]", ip6_sprintf(ip6buf,
1597 &args->f_id.dst_ip6));
1602 htonl(args->f_id.src_ip);
1603 inet_ntoa_r(da, src);
1605 htonl(args->f_id.dst_ip);
1606 inet_ntoa_r(da, dst);
1608 log(LOG_SECURITY | LOG_DEBUG,
1609 "ipfw: %d %s %s:%u -> %s:%u, %s\n",
1610 parent->rule->rulenum,
1612 src, (args->f_id.src_port),
1613 dst, (args->f_id.dst_port),
1614 "too many entries");
1620 add_dyn_rule(&args->f_id, O_LIMIT, (struct ip_fw *)parent);
1624 printf("ipfw: %s: unknown dynamic rule type %u\n",
1625 __func__, cmd->o.opcode);
1630 /* XXX just set lifetime */
1631 lookup_dyn_rule_locked(&args->f_id, NULL, NULL);
1638 * Generate a TCP packet, containing either a RST or a keepalive.
1639 * When flags & TH_RST, we are sending a RST packet, because of a
1640 * "reset" action matched the packet.
1641 * Otherwise we are sending a keepalive, and flags & TH_
1642 * The 'replyto' mbuf is the mbuf being replied to, if any, and is required
1643 * so that MAC can label the reply appropriately.
1645 static struct mbuf *
1646 send_pkt(struct mbuf *replyto, struct ipfw_flow_id *id, u_int32_t seq,
1647 u_int32_t ack, int flags)
1653 MGETHDR(m, M_DONTWAIT, MT_DATA);
1656 m->m_pkthdr.rcvif = (struct ifnet *)0;
1658 M_SETFIB(m, id->fib);
1660 if (replyto != NULL)
1661 mac_netinet_firewall_reply(replyto, m);
1663 mac_netinet_firewall_send(m);
1665 (void)replyto; /* don't warn about unused arg */
1668 m->m_pkthdr.len = m->m_len = sizeof(struct ip) + sizeof(struct tcphdr);
1669 m->m_data += max_linkhdr;
1671 ip = mtod(m, struct ip *);
1672 bzero(ip, m->m_len);
1673 tcp = (struct tcphdr *)(ip + 1); /* no IP options */
1674 ip->ip_p = IPPROTO_TCP;
1677 * Assume we are sending a RST (or a keepalive in the reverse
1678 * direction), swap src and destination addresses and ports.
1680 ip->ip_src.s_addr = htonl(id->dst_ip);
1681 ip->ip_dst.s_addr = htonl(id->src_ip);
1682 tcp->th_sport = htons(id->dst_port);
1683 tcp->th_dport = htons(id->src_port);
1684 if (flags & TH_RST) { /* we are sending a RST */
1685 if (flags & TH_ACK) {
1686 tcp->th_seq = htonl(ack);
1687 tcp->th_ack = htonl(0);
1688 tcp->th_flags = TH_RST;
1692 tcp->th_seq = htonl(0);
1693 tcp->th_ack = htonl(seq);
1694 tcp->th_flags = TH_RST | TH_ACK;
1698 * We are sending a keepalive. flags & TH_SYN determines
1699 * the direction, forward if set, reverse if clear.
1700 * NOTE: seq and ack are always assumed to be correct
1701 * as set by the caller. This may be confusing...
1703 if (flags & TH_SYN) {
1705 * we have to rewrite the correct addresses!
1707 ip->ip_dst.s_addr = htonl(id->dst_ip);
1708 ip->ip_src.s_addr = htonl(id->src_ip);
1709 tcp->th_dport = htons(id->dst_port);
1710 tcp->th_sport = htons(id->src_port);
1712 tcp->th_seq = htonl(seq);
1713 tcp->th_ack = htonl(ack);
1714 tcp->th_flags = TH_ACK;
1717 * set ip_len to the payload size so we can compute
1718 * the tcp checksum on the pseudoheader
1719 * XXX check this, could save a couple of words ?
1721 ip->ip_len = htons(sizeof(struct tcphdr));
1722 tcp->th_sum = in_cksum(m, m->m_pkthdr.len);
1724 * now fill fields left out earlier
1726 ip->ip_ttl = V_ip_defttl;
1727 ip->ip_len = m->m_pkthdr.len;
1728 m->m_flags |= M_SKIP_FIREWALL;
1733 * sends a reject message, consuming the mbuf passed as an argument.
1736 send_reject(struct ip_fw_args *args, int code, int ip_len, struct ip *ip)
1740 /* XXX When ip is not guaranteed to be at mtod() we will
1741 * need to account for this */
1742 * The mbuf will however be thrown away so we can adjust it.
1743 * Remember we did an m_pullup on it already so we
1744 * can make some assumptions about contiguousness.
1747 m_adj(m, args->L3offset);
1749 if (code != ICMP_REJECT_RST) { /* Send an ICMP unreach */
1750 /* We need the IP header in host order for icmp_error(). */
1751 if (args->eh != NULL) {
1752 ip->ip_len = ntohs(ip->ip_len);
1753 ip->ip_off = ntohs(ip->ip_off);
1755 icmp_error(args->m, ICMP_UNREACH, code, 0L, 0);
1756 } else if (args->f_id.proto == IPPROTO_TCP) {
1757 struct tcphdr *const tcp =
1758 L3HDR(struct tcphdr, mtod(args->m, struct ip *));
1759 if ( (tcp->th_flags & TH_RST) == 0) {
1761 m = send_pkt(args->m, &(args->f_id),
1762 ntohl(tcp->th_seq), ntohl(tcp->th_ack),
1763 tcp->th_flags | TH_RST);
1765 ip_output(m, NULL, NULL, 0, NULL, NULL);
1775 * Given an ip_fw *, lookup_next_rule will return a pointer
1776 * to the next rule, which can be either the jump
1777 * target (for skipto instructions) or the next one in the list (in
1778 * all other cases including a missing jump target).
1779 * The result is also written in the "next_rule" field of the rule.
1780 * Backward jumps are not allowed, so start looking from the next
1783 * This never returns NULL -- in case we do not have an exact match,
1784 * the next rule is returned. When the ruleset is changed,
1785 * pointers are flushed so we are always correct.
1788 static struct ip_fw *
1789 lookup_next_rule(struct ip_fw *me, u_int32_t tablearg)
1791 struct ip_fw *rule = NULL;
1795 /* look for action, in case it is a skipto */
1796 cmd = ACTION_PTR(me);
1797 if (cmd->opcode == O_LOG)
1799 if (cmd->opcode == O_ALTQ)
1801 if (cmd->opcode == O_TAG)
1803 if (cmd->opcode == O_SKIPTO ) {
1804 if (tablearg != 0) {
1805 rulenum = (u_int16_t)tablearg;
1807 rulenum = cmd->arg1;
1809 for (rule = me->next; rule ; rule = rule->next) {
1810 if (rule->rulenum >= rulenum) {
1815 if (rule == NULL) /* failure or not a skipto */
1817 me->next_rule = rule;
1822 add_table_entry(struct ip_fw_chain *ch, uint16_t tbl, in_addr_t addr,
1823 uint8_t mlen, uint32_t value)
1825 struct radix_node_head *rnh;
1826 struct table_entry *ent;
1827 struct radix_node *rn;
1829 if (tbl >= IPFW_TABLES_MAX)
1831 rnh = ch->tables[tbl];
1832 ent = malloc(sizeof(*ent), M_IPFW_TBL, M_NOWAIT | M_ZERO);
1836 ent->addr.sin_len = ent->mask.sin_len = 8;
1837 ent->mask.sin_addr.s_addr = htonl(mlen ? ~((1 << (32 - mlen)) - 1) : 0);
1838 ent->addr.sin_addr.s_addr = addr & ent->mask.sin_addr.s_addr;
1840 rn = rnh->rnh_addaddr(&ent->addr, &ent->mask, rnh, (void *)ent);
1843 free(ent, M_IPFW_TBL);
1851 del_table_entry(struct ip_fw_chain *ch, uint16_t tbl, in_addr_t addr,
1854 struct radix_node_head *rnh;
1855 struct table_entry *ent;
1856 struct sockaddr_in sa, mask;
1858 if (tbl >= IPFW_TABLES_MAX)
1860 rnh = ch->tables[tbl];
1861 sa.sin_len = mask.sin_len = 8;
1862 mask.sin_addr.s_addr = htonl(mlen ? ~((1 << (32 - mlen)) - 1) : 0);
1863 sa.sin_addr.s_addr = addr & mask.sin_addr.s_addr;
1865 ent = (struct table_entry *)rnh->rnh_deladdr(&sa, &mask, rnh);
1871 free(ent, M_IPFW_TBL);
1876 flush_table_entry(struct radix_node *rn, void *arg)
1878 struct radix_node_head * const rnh = arg;
1879 struct table_entry *ent;
1881 ent = (struct table_entry *)
1882 rnh->rnh_deladdr(rn->rn_key, rn->rn_mask, rnh);
1884 free(ent, M_IPFW_TBL);
1889 flush_table(struct ip_fw_chain *ch, uint16_t tbl)
1891 struct radix_node_head *rnh;
1893 IPFW_WLOCK_ASSERT(ch);
1895 if (tbl >= IPFW_TABLES_MAX)
1897 rnh = ch->tables[tbl];
1898 KASSERT(rnh != NULL, ("NULL IPFW table"));
1899 rnh->rnh_walktree(rnh, flush_table_entry, rnh);
1904 flush_tables(struct ip_fw_chain *ch)
1908 IPFW_WLOCK_ASSERT(ch);
1910 for (tbl = 0; tbl < IPFW_TABLES_MAX; tbl++)
1911 flush_table(ch, tbl);
1915 init_tables(struct ip_fw_chain *ch)
1920 for (i = 0; i < IPFW_TABLES_MAX; i++) {
1921 if (!rn_inithead((void **)&ch->tables[i], 32)) {
1922 for (j = 0; j < i; j++) {
1923 (void) flush_table(ch, j);
1932 lookup_table(struct ip_fw_chain *ch, uint16_t tbl, in_addr_t addr,
1935 struct radix_node_head *rnh;
1936 struct table_entry *ent;
1937 struct sockaddr_in sa;
1939 if (tbl >= IPFW_TABLES_MAX)
1941 rnh = ch->tables[tbl];
1943 sa.sin_addr.s_addr = addr;
1944 ent = (struct table_entry *)(rnh->rnh_lookup(&sa, NULL, rnh));
1953 count_table_entry(struct radix_node *rn, void *arg)
1955 u_int32_t * const cnt = arg;
1962 count_table(struct ip_fw_chain *ch, uint32_t tbl, uint32_t *cnt)
1964 struct radix_node_head *rnh;
1966 if (tbl >= IPFW_TABLES_MAX)
1968 rnh = ch->tables[tbl];
1970 rnh->rnh_walktree(rnh, count_table_entry, cnt);
1975 dump_table_entry(struct radix_node *rn, void *arg)
1977 struct table_entry * const n = (struct table_entry *)rn;
1978 ipfw_table * const tbl = arg;
1979 ipfw_table_entry *ent;
1981 if (tbl->cnt == tbl->size)
1983 ent = &tbl->ent[tbl->cnt];
1984 ent->tbl = tbl->tbl;
1985 if (in_nullhost(n->mask.sin_addr))
1988 ent->masklen = 33 - ffs(ntohl(n->mask.sin_addr.s_addr));
1989 ent->addr = n->addr.sin_addr.s_addr;
1990 ent->value = n->value;
1996 dump_table(struct ip_fw_chain *ch, ipfw_table *tbl)
1998 struct radix_node_head *rnh;
2000 if (tbl->tbl >= IPFW_TABLES_MAX)
2002 rnh = ch->tables[tbl->tbl];
2004 rnh->rnh_walktree(rnh, dump_table_entry, tbl);
2009 check_uidgid(ipfw_insn_u32 *insn, int proto, struct ifnet *oif,
2010 struct in_addr dst_ip, u_int16_t dst_port, struct in_addr src_ip,
2011 u_int16_t src_port, struct ucred **uc, int *ugid_lookupp,
2014 struct inpcbinfo *pi;
2020 * Check to see if the UDP or TCP stack supplied us with
2021 * the PCB. If so, rather then holding a lock and looking
2022 * up the PCB, we can use the one that was supplied.
2024 if (inp && *ugid_lookupp == 0) {
2025 INP_LOCK_ASSERT(inp);
2026 if (inp->inp_socket != NULL) {
2027 *uc = crhold(inp->inp_cred);
2033 * If we have already been here and the packet has no
2034 * PCB entry associated with it, then we can safely
2035 * assume that this is a no match.
2037 if (*ugid_lookupp == -1)
2039 if (proto == IPPROTO_TCP) {
2042 } else if (proto == IPPROTO_UDP) {
2043 wildcard = INPLOOKUP_WILDCARD;
2048 if (*ugid_lookupp == 0) {
2051 in_pcblookup_hash(pi,
2052 dst_ip, htons(dst_port),
2053 src_ip, htons(src_port),
2055 in_pcblookup_hash(pi,
2056 src_ip, htons(src_port),
2057 dst_ip, htons(dst_port),
2060 *uc = crhold(inp->inp_cred);
2063 INP_INFO_RUNLOCK(pi);
2064 if (*ugid_lookupp == 0) {
2066 * If the lookup did not yield any results, there
2067 * is no sense in coming back and trying again. So
2068 * we can set lookup to -1 and ensure that we wont
2069 * bother the pcb system again.
2075 if (insn->o.opcode == O_UID)
2076 match = ((*uc)->cr_uid == (uid_t)insn->d[0]);
2077 else if (insn->o.opcode == O_GID)
2078 match = groupmember((gid_t)insn->d[0], *uc);
2079 else if (insn->o.opcode == O_JAIL)
2080 match = ((*uc)->cr_prison->pr_id == (int)insn->d[0]);
2085 * The main check routine for the firewall.
2087 * All arguments are in args so we can modify them and return them
2088 * back to the caller.
2092 * args->m (in/out) The packet; we set to NULL when/if we nuke it.
2093 * Starts with the IP header.
2094 * args->eh (in) Mac header if present, or NULL for layer3 packet.
2095 * args->L3offset Number of bytes bypassed if we came from L2.
2096 * e.g. often sizeof(eh) ** NOTYET **
2097 * args->oif Outgoing interface, or NULL if packet is incoming.
2098 * The incoming interface is in the mbuf. (in)
2099 * args->divert_rule (in/out)
2100 * Skip up to the first rule past this rule number;
2101 * upon return, non-zero port number for divert or tee.
2103 * args->rule Pointer to the last matching rule (in/out)
2104 * args->next_hop Socket we are forwarding to (out).
2105 * args->f_id Addresses grabbed from the packet (out)
2106 * args->cookie a cookie depending on rule action
2110 * IP_FW_PASS the packet must be accepted
2111 * IP_FW_DENY the packet must be dropped
2112 * IP_FW_DIVERT divert packet, port in m_tag
2113 * IP_FW_TEE tee packet, port in m_tag
2114 * IP_FW_DUMMYNET to dummynet, pipe in args->cookie
2115 * IP_FW_NETGRAPH into netgraph, cookie args->cookie
2119 ipfw_chk(struct ip_fw_args *args)
2123 * Local variables holding state during the processing of a packet:
2125 * IMPORTANT NOTE: to speed up the processing of rules, there
2126 * are some assumption on the values of the variables, which
2127 * are documented here. Should you change them, please check
2128 * the implementation of the various instructions to make sure
2129 * that they still work.
2131 * args->eh The MAC header. It is non-null for a layer2
2132 * packet, it is NULL for a layer-3 packet.
2134 * args->L3offset Offset in the packet to the L3 (IP or equiv.) header.
2136 * m | args->m Pointer to the mbuf, as received from the caller.
2137 * It may change if ipfw_chk() does an m_pullup, or if it
2138 * consumes the packet because it calls send_reject().
2139 * XXX This has to change, so that ipfw_chk() never modifies
2140 * or consumes the buffer.
2141 * ip is the beginning of the ip(4 or 6) header.
2142 * Calculated by adding the L3offset to the start of data.
2143 * (Until we start using L3offset, the packet is
2144 * supposed to start with the ip header).
2146 struct mbuf *m = args->m;
2147 struct ip *ip = mtod(m, struct ip *);
2150 * For rules which contain uid/gid or jail constraints, cache
2151 * a copy of the users credentials after the pcb lookup has been
2152 * executed. This will speed up the processing of rules with
2153 * these types of constraints, as well as decrease contention
2154 * on pcb related locks.
2156 struct ucred *ucred_cache = NULL;
2157 int ucred_lookup = 0;
2160 * divinput_flags If non-zero, set to the IP_FW_DIVERT_*_FLAG
2161 * associated with a packet input on a divert socket. This
2162 * will allow to distinguish traffic and its direction when
2163 * it originates from a divert socket.
2165 u_int divinput_flags = 0;
2168 * oif | args->oif If NULL, ipfw_chk has been called on the
2169 * inbound path (ether_input, ip_input).
2170 * If non-NULL, ipfw_chk has been called on the outbound path
2171 * (ether_output, ip_output).
2173 struct ifnet *oif = args->oif;
2175 struct ip_fw *f = NULL; /* matching rule */
2179 * hlen The length of the IP header.
2181 u_int hlen = 0; /* hlen >0 means we have an IP pkt */
2184 * offset The offset of a fragment. offset != 0 means that
2185 * we have a fragment at this offset of an IPv4 packet.
2186 * offset == 0 means that (if this is an IPv4 packet)
2187 * this is the first or only fragment.
2188 * For IPv6 offset == 0 means there is no Fragment Header.
2189 * If offset != 0 for IPv6 always use correct mask to
2190 * get the correct offset because we add IP6F_MORE_FRAG
2191 * to be able to dectect the first fragment which would
2192 * otherwise have offset = 0.
2197 * Local copies of addresses. They are only valid if we have
2200 * proto The protocol. Set to 0 for non-ip packets,
2201 * or to the protocol read from the packet otherwise.
2202 * proto != 0 means that we have an IPv4 packet.
2204 * src_port, dst_port port numbers, in HOST format. Only
2205 * valid for TCP and UDP packets.
2207 * src_ip, dst_ip ip addresses, in NETWORK format.
2208 * Only valid for IPv4 packets.
2211 u_int16_t src_port = 0, dst_port = 0; /* NOTE: host format */
2212 struct in_addr src_ip, dst_ip; /* NOTE: network format */
2215 u_int16_t etype = 0; /* Host order stored ether type */
2218 * dyn_dir = MATCH_UNKNOWN when rules unchecked,
2219 * MATCH_NONE when checked and not matched (q = NULL),
2220 * MATCH_FORWARD or MATCH_REVERSE otherwise (q != NULL)
2222 int dyn_dir = MATCH_UNKNOWN;
2223 ipfw_dyn_rule *q = NULL;
2224 struct ip_fw_chain *chain = &V_layer3_chain;
2228 * We store in ulp a pointer to the upper layer protocol header.
2229 * In the ipv4 case this is easy to determine from the header,
2230 * but for ipv6 we might have some additional headers in the middle.
2231 * ulp is NULL if not found.
2233 void *ulp = NULL; /* upper layer protocol pointer. */
2234 /* XXX ipv6 variables */
2236 u_int16_t ext_hd = 0; /* bits vector for extension header filtering */
2237 /* end of ipv6 variables */
2240 if (m->m_flags & M_SKIP_FIREWALL)
2241 return (IP_FW_PASS); /* accept */
2243 dst_ip.s_addr = 0; /* make sure it is initialized */
2244 pktlen = m->m_pkthdr.len;
2245 args->f_id.fib = M_GETFIB(m); /* note mbuf not altered) */
2246 proto = args->f_id.proto = 0; /* mark f_id invalid */
2247 /* XXX 0 is a valid proto: IP/IPv6 Hop-by-Hop Option */
2250 * PULLUP_TO(len, p, T) makes sure that len + sizeof(T) is contiguous,
2251 * then it sets p to point at the offset "len" in the mbuf. WARNING: the
2252 * pointer might become stale after other pullups (but we never use it
2255 #define PULLUP_TO(len, p, T) \
2257 int x = (len) + sizeof(T); \
2258 if ((m)->m_len < x) { \
2259 args->m = m = m_pullup(m, x); \
2261 goto pullup_failed; \
2263 p = (mtod(m, char *) + (len)); \
2267 * if we have an ether header,
2270 etype = ntohs(args->eh->ether_type);
2272 /* Identify IP packets and fill up variables. */
2273 if (pktlen >= sizeof(struct ip6_hdr) &&
2274 (args->eh == NULL || etype == ETHERTYPE_IPV6) && ip->ip_v == 6) {
2275 struct ip6_hdr *ip6 = (struct ip6_hdr *)ip;
2277 args->f_id.addr_type = 6;
2278 hlen = sizeof(struct ip6_hdr);
2279 proto = ip6->ip6_nxt;
2281 /* Search extension headers to find upper layer protocols */
2282 while (ulp == NULL) {
2284 case IPPROTO_ICMPV6:
2285 PULLUP_TO(hlen, ulp, struct icmp6_hdr);
2286 args->f_id.flags = ICMP6(ulp)->icmp6_type;
2290 PULLUP_TO(hlen, ulp, struct tcphdr);
2291 dst_port = TCP(ulp)->th_dport;
2292 src_port = TCP(ulp)->th_sport;
2293 args->f_id.flags = TCP(ulp)->th_flags;
2297 PULLUP_TO(hlen, ulp, struct sctphdr);
2298 src_port = SCTP(ulp)->src_port;
2299 dst_port = SCTP(ulp)->dest_port;
2303 PULLUP_TO(hlen, ulp, struct udphdr);
2304 dst_port = UDP(ulp)->uh_dport;
2305 src_port = UDP(ulp)->uh_sport;
2308 case IPPROTO_HOPOPTS: /* RFC 2460 */
2309 PULLUP_TO(hlen, ulp, struct ip6_hbh);
2310 ext_hd |= EXT_HOPOPTS;
2311 hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3;
2312 proto = ((struct ip6_hbh *)ulp)->ip6h_nxt;
2316 case IPPROTO_ROUTING: /* RFC 2460 */
2317 PULLUP_TO(hlen, ulp, struct ip6_rthdr);
2318 switch (((struct ip6_rthdr *)ulp)->ip6r_type) {
2320 ext_hd |= EXT_RTHDR0;
2323 ext_hd |= EXT_RTHDR2;
2326 printf("IPFW2: IPV6 - Unknown Routing "
2327 "Header type(%d)\n",
2328 ((struct ip6_rthdr *)ulp)->ip6r_type);
2329 if (V_fw_deny_unknown_exthdrs)
2330 return (IP_FW_DENY);
2333 ext_hd |= EXT_ROUTING;
2334 hlen += (((struct ip6_rthdr *)ulp)->ip6r_len + 1) << 3;
2335 proto = ((struct ip6_rthdr *)ulp)->ip6r_nxt;
2339 case IPPROTO_FRAGMENT: /* RFC 2460 */
2340 PULLUP_TO(hlen, ulp, struct ip6_frag);
2341 ext_hd |= EXT_FRAGMENT;
2342 hlen += sizeof (struct ip6_frag);
2343 proto = ((struct ip6_frag *)ulp)->ip6f_nxt;
2344 offset = ((struct ip6_frag *)ulp)->ip6f_offlg &
2346 /* Add IP6F_MORE_FRAG for offset of first
2347 * fragment to be != 0. */
2348 offset |= ((struct ip6_frag *)ulp)->ip6f_offlg &
2351 printf("IPFW2: IPV6 - Invalid Fragment "
2353 if (V_fw_deny_unknown_exthdrs)
2354 return (IP_FW_DENY);
2357 args->f_id.frag_id6 =
2358 ntohl(((struct ip6_frag *)ulp)->ip6f_ident);
2362 case IPPROTO_DSTOPTS: /* RFC 2460 */
2363 PULLUP_TO(hlen, ulp, struct ip6_hbh);
2364 ext_hd |= EXT_DSTOPTS;
2365 hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3;
2366 proto = ((struct ip6_hbh *)ulp)->ip6h_nxt;
2370 case IPPROTO_AH: /* RFC 2402 */
2371 PULLUP_TO(hlen, ulp, struct ip6_ext);
2373 hlen += (((struct ip6_ext *)ulp)->ip6e_len + 2) << 2;
2374 proto = ((struct ip6_ext *)ulp)->ip6e_nxt;
2378 case IPPROTO_ESP: /* RFC 2406 */
2379 PULLUP_TO(hlen, ulp, uint32_t); /* SPI, Seq# */
2380 /* Anything past Seq# is variable length and
2381 * data past this ext. header is encrypted. */
2385 case IPPROTO_NONE: /* RFC 2460 */
2387 * Packet ends here, and IPv6 header has
2388 * already been pulled up. If ip6e_len!=0
2389 * then octets must be ignored.
2391 ulp = ip; /* non-NULL to get out of loop. */
2394 case IPPROTO_OSPFIGP:
2395 /* XXX OSPF header check? */
2396 PULLUP_TO(hlen, ulp, struct ip6_ext);
2400 /* XXX PIM header check? */
2401 PULLUP_TO(hlen, ulp, struct pim);
2405 PULLUP_TO(hlen, ulp, struct carp_header);
2406 if (((struct carp_header *)ulp)->carp_version !=
2408 return (IP_FW_DENY);
2409 if (((struct carp_header *)ulp)->carp_type !=
2411 return (IP_FW_DENY);
2414 case IPPROTO_IPV6: /* RFC 2893 */
2415 PULLUP_TO(hlen, ulp, struct ip6_hdr);
2418 case IPPROTO_IPV4: /* RFC 2893 */
2419 PULLUP_TO(hlen, ulp, struct ip);
2423 printf("IPFW2: IPV6 - Unknown Extension "
2424 "Header(%d), ext_hd=%x\n", proto, ext_hd);
2425 if (V_fw_deny_unknown_exthdrs)
2426 return (IP_FW_DENY);
2427 PULLUP_TO(hlen, ulp, struct ip6_ext);
2431 ip = mtod(m, struct ip *);
2432 ip6 = (struct ip6_hdr *)ip;
2433 args->f_id.src_ip6 = ip6->ip6_src;
2434 args->f_id.dst_ip6 = ip6->ip6_dst;
2435 args->f_id.src_ip = 0;
2436 args->f_id.dst_ip = 0;
2437 args->f_id.flow_id6 = ntohl(ip6->ip6_flow);
2438 } else if (pktlen >= sizeof(struct ip) &&
2439 (args->eh == NULL || etype == ETHERTYPE_IP) && ip->ip_v == 4) {
2441 hlen = ip->ip_hl << 2;
2442 args->f_id.addr_type = 4;
2445 * Collect parameters into local variables for faster matching.
2448 src_ip = ip->ip_src;
2449 dst_ip = ip->ip_dst;
2450 if (args->eh != NULL) { /* layer 2 packets are as on the wire */
2451 offset = ntohs(ip->ip_off) & IP_OFFMASK;
2452 ip_len = ntohs(ip->ip_len);
2454 offset = ip->ip_off & IP_OFFMASK;
2455 ip_len = ip->ip_len;
2457 pktlen = ip_len < pktlen ? ip_len : pktlen;
2462 PULLUP_TO(hlen, ulp, struct tcphdr);
2463 dst_port = TCP(ulp)->th_dport;
2464 src_port = TCP(ulp)->th_sport;
2465 args->f_id.flags = TCP(ulp)->th_flags;
2469 PULLUP_TO(hlen, ulp, struct udphdr);
2470 dst_port = UDP(ulp)->uh_dport;
2471 src_port = UDP(ulp)->uh_sport;
2475 PULLUP_TO(hlen, ulp, struct icmphdr);
2476 args->f_id.flags = ICMP(ulp)->icmp_type;
2484 ip = mtod(m, struct ip *);
2485 args->f_id.src_ip = ntohl(src_ip.s_addr);
2486 args->f_id.dst_ip = ntohl(dst_ip.s_addr);
2489 if (proto) { /* we may have port numbers, store them */
2490 args->f_id.proto = proto;
2491 args->f_id.src_port = src_port = ntohs(src_port);
2492 args->f_id.dst_port = dst_port = ntohs(dst_port);
2496 mtag = m_tag_find(m, PACKET_TAG_DIVERT, NULL);
2499 * Packet has already been tagged. Look for the next rule
2500 * to restart processing. Make sure that args->rule still
2501 * exists and not changed.
2503 if (chain->id != args->chain_id) {
2504 for (f = chain->rules; f != NULL; f = f->next)
2505 if (f == args->rule && f->id == args->rule_id)
2511 f = ip_fw_default_rule;
2513 f = args->rule->next_rule;
2516 f = lookup_next_rule(args->rule, 0);
2519 * Find the starting rule. It can be either the first
2520 * one, or the one after divert_rule if asked so.
2522 int skipto = mtag ? divert_cookie(mtag) : 0;
2525 if (args->eh == NULL && skipto != 0) {
2526 if (skipto >= IPFW_DEFAULT_RULE) {
2527 IPFW_RUNLOCK(chain);
2528 return (IP_FW_DENY); /* invalid */
2530 while (f && f->rulenum <= skipto)
2532 if (f == NULL) { /* drop packet */
2533 IPFW_RUNLOCK(chain);
2534 return (IP_FW_DENY);
2538 /* reset divert rule to avoid confusion later */
2540 divinput_flags = divert_info(mtag) &
2541 (IP_FW_DIVERT_OUTPUT_FLAG | IP_FW_DIVERT_LOOPBACK_FLAG);
2542 m_tag_delete(m, mtag);
2546 * Now scan the rules, and parse microinstructions for each rule.
2548 for (; f; f = f->next) {
2550 uint32_t tablearg = 0;
2551 int l, cmdlen, skip_or; /* skip rest of OR block */
2554 if (V_set_disable & (1 << f->set) )
2558 for (l = f->cmd_len, cmd = f->cmd ; l > 0 ;
2559 l -= cmdlen, cmd += cmdlen) {
2563 * check_body is a jump target used when we find a
2564 * CHECK_STATE, and need to jump to the body of
2569 cmdlen = F_LEN(cmd);
2571 * An OR block (insn_1 || .. || insn_n) has the
2572 * F_OR bit set in all but the last instruction.
2573 * The first match will set "skip_or", and cause
2574 * the following instructions to be skipped until
2575 * past the one with the F_OR bit clear.
2577 if (skip_or) { /* skip this instruction */
2578 if ((cmd->len & F_OR) == 0)
2579 skip_or = 0; /* next one is good */
2582 match = 0; /* set to 1 if we succeed */
2584 switch (cmd->opcode) {
2586 * The first set of opcodes compares the packet's
2587 * fields with some pattern, setting 'match' if a
2588 * match is found. At the end of the loop there is
2589 * logic to deal with F_NOT and F_OR flags associated
2597 printf("ipfw: opcode %d unimplemented\n",
2605 * We only check offset == 0 && proto != 0,
2606 * as this ensures that we have a
2607 * packet with the ports info.
2611 if (is_ipv6) /* XXX to be fixed later */
2613 if (proto == IPPROTO_TCP ||
2614 proto == IPPROTO_UDP)
2615 match = check_uidgid(
2616 (ipfw_insn_u32 *)cmd,
2619 src_ip, src_port, &ucred_cache,
2620 &ucred_lookup, args->inp);
2624 match = iface_match(m->m_pkthdr.rcvif,
2625 (ipfw_insn_if *)cmd);
2629 match = iface_match(oif, (ipfw_insn_if *)cmd);
2633 match = iface_match(oif ? oif :
2634 m->m_pkthdr.rcvif, (ipfw_insn_if *)cmd);
2638 if (args->eh != NULL) { /* have MAC header */
2639 u_int32_t *want = (u_int32_t *)
2640 ((ipfw_insn_mac *)cmd)->addr;
2641 u_int32_t *mask = (u_int32_t *)
2642 ((ipfw_insn_mac *)cmd)->mask;
2643 u_int32_t *hdr = (u_int32_t *)args->eh;
2646 ( want[0] == (hdr[0] & mask[0]) &&
2647 want[1] == (hdr[1] & mask[1]) &&
2648 want[2] == (hdr[2] & mask[2]) );
2653 if (args->eh != NULL) {
2655 ((ipfw_insn_u16 *)cmd)->ports;
2658 for (i = cmdlen - 1; !match && i>0;
2660 match = (etype >= p[0] &&
2666 match = (offset != 0);
2669 case O_IN: /* "out" is "not in" */
2670 match = (oif == NULL);
2674 match = (args->eh != NULL);
2678 match = (cmd->arg1 & 1 && divinput_flags &
2679 IP_FW_DIVERT_LOOPBACK_FLAG) ||
2680 (cmd->arg1 & 2 && divinput_flags &
2681 IP_FW_DIVERT_OUTPUT_FLAG);
2686 * We do not allow an arg of 0 so the
2687 * check of "proto" only suffices.
2689 match = (proto == cmd->arg1);
2694 (((ipfw_insn_ip *)cmd)->addr.s_addr ==
2698 case O_IP_SRC_LOOKUP:
2699 case O_IP_DST_LOOKUP:
2702 (cmd->opcode == O_IP_DST_LOOKUP) ?
2703 dst_ip.s_addr : src_ip.s_addr;
2706 match = lookup_table(chain, cmd->arg1, a,
2710 if (cmdlen == F_INSN_SIZE(ipfw_insn_u32))
2712 ((ipfw_insn_u32 *)cmd)->d[0] == v;
2722 (cmd->opcode == O_IP_DST_MASK) ?
2723 dst_ip.s_addr : src_ip.s_addr;
2724 uint32_t *p = ((ipfw_insn_u32 *)cmd)->d;
2727 for (; !match && i>0; i-= 2, p+= 2)
2728 match = (p[0] == (a & p[1]));
2736 INADDR_TO_IFP(src_ip, tif);
2737 match = (tif != NULL);
2744 u_int32_t *d = (u_int32_t *)(cmd+1);
2746 cmd->opcode == O_IP_DST_SET ?
2752 addr -= d[0]; /* subtract base */
2753 match = (addr < cmd->arg1) &&
2754 ( d[ 1 + (addr>>5)] &
2755 (1<<(addr & 0x1f)) );
2761 (((ipfw_insn_ip *)cmd)->addr.s_addr ==
2769 INADDR_TO_IFP(dst_ip, tif);
2770 match = (tif != NULL);
2777 * offset == 0 && proto != 0 is enough
2778 * to guarantee that we have a
2779 * packet with port info.
2781 if ((proto==IPPROTO_UDP || proto==IPPROTO_TCP)
2784 (cmd->opcode == O_IP_SRCPORT) ?
2785 src_port : dst_port ;
2787 ((ipfw_insn_u16 *)cmd)->ports;
2790 for (i = cmdlen - 1; !match && i>0;
2792 match = (x>=p[0] && x<=p[1]);
2797 match = (offset == 0 && proto==IPPROTO_ICMP &&
2798 icmptype_match(ICMP(ulp), (ipfw_insn_u32 *)cmd) );
2803 match = is_ipv6 && offset == 0 &&
2804 proto==IPPROTO_ICMPV6 &&
2806 ICMP6(ulp)->icmp6_type,
2807 (ipfw_insn_u32 *)cmd);
2813 ipopts_match(ip, cmd) );
2818 cmd->arg1 == ip->ip_v);
2824 if (is_ipv4) { /* only for IP packets */
2829 if (cmd->opcode == O_IPLEN)
2831 else if (cmd->opcode == O_IPTTL)
2833 else /* must be IPID */
2834 x = ntohs(ip->ip_id);
2836 match = (cmd->arg1 == x);
2839 /* otherwise we have ranges */
2840 p = ((ipfw_insn_u16 *)cmd)->ports;
2842 for (; !match && i>0; i--, p += 2)
2843 match = (x >= p[0] && x <= p[1]);
2847 case O_IPPRECEDENCE:
2849 (cmd->arg1 == (ip->ip_tos & 0xe0)) );
2854 flags_match(cmd, ip->ip_tos));
2858 if (proto == IPPROTO_TCP && offset == 0) {
2866 ((ip->ip_hl + tcp->th_off) << 2);
2868 match = (cmd->arg1 == x);
2871 /* otherwise we have ranges */
2872 p = ((ipfw_insn_u16 *)cmd)->ports;
2874 for (; !match && i>0; i--, p += 2)
2875 match = (x >= p[0] && x <= p[1]);
2880 match = (proto == IPPROTO_TCP && offset == 0 &&
2881 flags_match(cmd, TCP(ulp)->th_flags));
2885 match = (proto == IPPROTO_TCP && offset == 0 &&
2886 tcpopts_match(TCP(ulp), cmd));
2890 match = (proto == IPPROTO_TCP && offset == 0 &&
2891 ((ipfw_insn_u32 *)cmd)->d[0] ==
2896 match = (proto == IPPROTO_TCP && offset == 0 &&
2897 ((ipfw_insn_u32 *)cmd)->d[0] ==
2902 match = (proto == IPPROTO_TCP && offset == 0 &&
2903 cmd->arg1 == TCP(ulp)->th_win);
2907 /* reject packets which have SYN only */
2908 /* XXX should i also check for TH_ACK ? */
2909 match = (proto == IPPROTO_TCP && offset == 0 &&
2910 (TCP(ulp)->th_flags &
2911 (TH_RST | TH_ACK | TH_SYN)) != TH_SYN);
2916 ipfw_insn_altq *altq = (ipfw_insn_altq *)cmd;
2919 at = pf_find_mtag(m);
2920 if (at != NULL && at->qid != 0)
2922 at = pf_get_mtag(m);
2925 * Let the packet fall back to the
2930 at->qid = altq->qid;
2941 ipfw_log(f, hlen, args, m,
2942 oif, offset, tablearg, ip);
2947 match = (random()<((ipfw_insn_u32 *)cmd)->d[0]);
2951 /* Outgoing packets automatically pass/match */
2952 match = ((oif != NULL) ||
2953 (m->m_pkthdr.rcvif == NULL) ||
2957 verify_path6(&(args->f_id.src_ip6),
2958 m->m_pkthdr.rcvif) :
2960 verify_path(src_ip, m->m_pkthdr.rcvif,
2965 /* Outgoing packets automatically pass/match */
2966 match = (hlen > 0 && ((oif != NULL) ||
2969 verify_path6(&(args->f_id.src_ip6),
2972 verify_path(src_ip, NULL, args->f_id.fib)));
2976 /* Outgoing packets automatically pass/match */
2977 if (oif == NULL && hlen > 0 &&
2978 ( (is_ipv4 && in_localaddr(src_ip))
2981 in6_localaddr(&(args->f_id.src_ip6)))
2986 is_ipv6 ? verify_path6(
2987 &(args->f_id.src_ip6),
2988 m->m_pkthdr.rcvif) :
2999 match = (m_tag_find(m,
3000 PACKET_TAG_IPSEC_IN_DONE, NULL) != NULL);
3002 /* otherwise no match */
3008 IN6_ARE_ADDR_EQUAL(&args->f_id.src_ip6,
3009 &((ipfw_insn_ip6 *)cmd)->addr6);
3014 IN6_ARE_ADDR_EQUAL(&args->f_id.dst_ip6,
3015 &((ipfw_insn_ip6 *)cmd)->addr6);
3017 case O_IP6_SRC_MASK:
3018 case O_IP6_DST_MASK:
3022 struct in6_addr *d =
3023 &((ipfw_insn_ip6 *)cmd)->addr6;
3025 for (; !match && i > 0; d += 2,
3026 i -= F_INSN_SIZE(struct in6_addr)
3032 APPLY_MASK(&p, &d[1]);
3034 IN6_ARE_ADDR_EQUAL(&d[0],
3041 match= is_ipv6 && search_ip6_addr_net(&args->f_id.src_ip6);
3045 match= is_ipv6 && search_ip6_addr_net(&args->f_id.dst_ip6);
3050 flow6id_match(args->f_id.flow_id6,
3051 (ipfw_insn_u32 *) cmd);
3056 (ext_hd & ((ipfw_insn *) cmd)->arg1);
3069 uint32_t tag = (cmd->arg1 == IP_FW_TABLEARG) ?
3070 tablearg : cmd->arg1;
3072 /* Packet is already tagged with this tag? */
3073 mtag = m_tag_locate(m, MTAG_IPFW, tag, NULL);
3075 /* We have `untag' action when F_NOT flag is
3076 * present. And we must remove this mtag from
3077 * mbuf and reset `match' to zero (`match' will
3078 * be inversed later).
3079 * Otherwise we should allocate new mtag and
3080 * push it into mbuf.
3082 if (cmd->len & F_NOT) { /* `untag' action */
3084 m_tag_delete(m, mtag);
3085 } else if (mtag == NULL) {
3086 if ((mtag = m_tag_alloc(MTAG_IPFW,
3087 tag, 0, M_NOWAIT)) != NULL)
3088 m_tag_prepend(m, mtag);
3090 match = (cmd->len & F_NOT) ? 0: 1;
3094 case O_FIB: /* try match the specified fib */
3095 if (args->f_id.fib == cmd->arg1)
3100 uint32_t tag = (cmd->arg1 == IP_FW_TABLEARG) ?
3101 tablearg : cmd->arg1;
3104 match = m_tag_locate(m, MTAG_IPFW,
3109 /* we have ranges */
3110 for (mtag = m_tag_first(m);
3111 mtag != NULL && !match;
3112 mtag = m_tag_next(m, mtag)) {
3116 if (mtag->m_tag_cookie != MTAG_IPFW)
3119 p = ((ipfw_insn_u16 *)cmd)->ports;
3121 for(; !match && i > 0; i--, p += 2)
3123 mtag->m_tag_id >= p[0] &&
3124 mtag->m_tag_id <= p[1];
3130 * The second set of opcodes represents 'actions',
3131 * i.e. the terminal part of a rule once the packet
3132 * matches all previous patterns.
3133 * Typically there is only one action for each rule,
3134 * and the opcode is stored at the end of the rule
3135 * (but there are exceptions -- see below).
3137 * In general, here we set retval and terminate the
3138 * outer loop (would be a 'break 3' in some language,
3139 * but we need to do a 'goto done').
3142 * O_COUNT and O_SKIPTO actions:
3143 * instead of terminating, we jump to the next rule
3144 * ('goto next_rule', equivalent to a 'break 2'),
3145 * or to the SKIPTO target ('goto again' after
3146 * having set f, cmd and l), respectively.
3148 * O_TAG, O_LOG and O_ALTQ action parameters:
3149 * perform some action and set match = 1;
3151 * O_LIMIT and O_KEEP_STATE: these opcodes are
3152 * not real 'actions', and are stored right
3153 * before the 'action' part of the rule.
3154 * These opcodes try to install an entry in the
3155 * state tables; if successful, we continue with
3156 * the next opcode (match=1; break;), otherwise
3157 * the packet * must be dropped
3158 * ('goto done' after setting retval);
3160 * O_PROBE_STATE and O_CHECK_STATE: these opcodes
3161 * cause a lookup of the state table, and a jump
3162 * to the 'action' part of the parent rule
3163 * ('goto check_body') if an entry is found, or
3164 * (CHECK_STATE only) a jump to the next rule if
3165 * the entry is not found ('goto next_rule').
3166 * The result of the lookup is cached to make
3167 * further instances of these opcodes are
3172 if (install_state(f,
3173 (ipfw_insn_limit *)cmd, args, tablearg)) {
3174 retval = IP_FW_DENY;
3175 goto done; /* error/limit violation */
3183 * dynamic rules are checked at the first
3184 * keep-state or check-state occurrence,
3185 * with the result being stored in dyn_dir.
3186 * The compiler introduces a PROBE_STATE
3187 * instruction for us when we have a
3188 * KEEP_STATE (because PROBE_STATE needs
3191 if (dyn_dir == MATCH_UNKNOWN &&
3192 (q = lookup_dyn_rule(&args->f_id,
3193 &dyn_dir, proto == IPPROTO_TCP ?
3197 * Found dynamic entry, update stats
3198 * and jump to the 'action' part of
3204 cmd = ACTION_PTR(f);
3205 l = f->cmd_len - f->act_ofs;
3210 * Dynamic entry not found. If CHECK_STATE,
3211 * skip to next rule, if PROBE_STATE just
3212 * ignore and continue with next opcode.
3214 if (cmd->opcode == O_CHECK_STATE)
3220 retval = 0; /* accept */
3225 args->rule = f; /* report matching rule */
3226 args->rule_id = f->id;
3227 args->chain_id = chain->id;
3228 if (cmd->arg1 == IP_FW_TABLEARG)
3229 args->cookie = tablearg;
3231 args->cookie = cmd->arg1;
3232 retval = IP_FW_DUMMYNET;
3237 struct divert_tag *dt;
3239 if (args->eh) /* not on layer 2 */
3241 mtag = m_tag_get(PACKET_TAG_DIVERT,
3242 sizeof(struct divert_tag),
3247 IPFW_RUNLOCK(chain);
3248 if (ucred_cache != NULL)
3249 crfree(ucred_cache);
3250 return (IP_FW_DENY);
3252 dt = (struct divert_tag *)(mtag+1);
3253 dt->cookie = f->rulenum;
3254 if (cmd->arg1 == IP_FW_TABLEARG)
3255 dt->info = tablearg;
3257 dt->info = cmd->arg1;
3258 m_tag_prepend(m, mtag);
3259 retval = (cmd->opcode == O_DIVERT) ?
3260 IP_FW_DIVERT : IP_FW_TEE;
3265 f->pcnt++; /* update stats */
3267 f->timestamp = time_uptime;
3268 if (cmd->opcode == O_COUNT)
3271 if (cmd->arg1 == IP_FW_TABLEARG) {
3272 f = lookup_next_rule(f, tablearg);
3274 if (f->next_rule == NULL)
3275 lookup_next_rule(f, 0);
3282 * Drop the packet and send a reject notice
3283 * if the packet is not ICMP (or is an ICMP
3284 * query), and it is not multicast/broadcast.
3286 if (hlen > 0 && is_ipv4 && offset == 0 &&
3287 (proto != IPPROTO_ICMP ||
3288 is_icmp_query(ICMP(ulp))) &&
3289 !(m->m_flags & (M_BCAST|M_MCAST)) &&
3290 !IN_MULTICAST(ntohl(dst_ip.s_addr))) {
3291 send_reject(args, cmd->arg1, ip_len, ip);
3297 if (hlen > 0 && is_ipv6 &&
3298 ((offset & IP6F_OFF_MASK) == 0) &&
3299 (proto != IPPROTO_ICMPV6 ||
3300 (is_icmp6_query(args->f_id.flags) == 1)) &&
3301 !(m->m_flags & (M_BCAST|M_MCAST)) &&
3302 !IN6_IS_ADDR_MULTICAST(&args->f_id.dst_ip6)) {
3304 args, cmd->arg1, hlen,
3305 (struct ip6_hdr *)ip);
3311 retval = IP_FW_DENY;
3314 case O_FORWARD_IP: {
3315 struct sockaddr_in *sa;
3316 sa = &(((ipfw_insn_sa *)cmd)->sa);
3317 if (args->eh) /* not valid on layer2 pkts */
3319 if (!q || dyn_dir == MATCH_FORWARD) {
3320 if (sa->sin_addr.s_addr == INADDR_ANY) {
3321 bcopy(sa, &args->hopstore,
3323 args->hopstore.sin_addr.s_addr =
3328 args->next_hop = sa;
3331 retval = IP_FW_PASS;
3337 args->rule = f; /* report matching rule */
3338 args->rule_id = f->id;
3339 args->chain_id = chain->id;
3340 if (cmd->arg1 == IP_FW_TABLEARG)
3341 args->cookie = tablearg;
3343 args->cookie = cmd->arg1;
3344 retval = (cmd->opcode == O_NETGRAPH) ?
3345 IP_FW_NETGRAPH : IP_FW_NGTEE;
3349 f->pcnt++; /* update stats */
3351 f->timestamp = time_uptime;
3352 M_SETFIB(m, cmd->arg1);
3353 args->f_id.fib = cmd->arg1;
3360 if (IPFW_NAT_LOADED) {
3361 args->rule = f; /* Report matching rule. */
3362 args->rule_id = f->id;
3363 args->chain_id = chain->id;
3364 t = ((ipfw_insn_nat *)cmd)->nat;
3366 nat_id = (cmd->arg1 == IP_FW_TABLEARG) ?
3367 tablearg : cmd->arg1;
3368 LOOKUP_NAT(V_layer3_chain, nat_id, t);
3370 retval = IP_FW_DENY;
3373 if (cmd->arg1 != IP_FW_TABLEARG)
3374 ((ipfw_insn_nat *)cmd)->nat = t;
3376 retval = ipfw_nat_ptr(args, t, m);
3378 retval = IP_FW_DENY;
3387 ip_off = (args->eh != NULL) ? ntohs(ip->ip_off) : ip->ip_off;
3388 if (ip_off & (IP_MF | IP_OFFMASK)) {
3390 * ip_reass() expects len & off in host
3391 * byte order: fix them in case we come
3394 if (args->eh != NULL) {
3395 ip->ip_len = ntohs(ip->ip_len);
3396 ip->ip_off = ntohs(ip->ip_off);
3403 * IP header checksum fixup after
3404 * reassembly and leave header
3405 * in network byte order.
3410 ip = mtod(m, struct ip *);
3411 hlen = ip->ip_hl << 2;
3412 /* revert len & off for layer2 pkts */
3413 if (args->eh != NULL)
3414 ip->ip_len = htons(ip->ip_len);
3416 if (hlen == sizeof(struct ip))
3417 ip->ip_sum = in_cksum_hdr(ip);
3419 ip->ip_sum = in_cksum(m, hlen);
3420 retval = IP_FW_REASS;
3422 args->rule_id = f->id;
3423 args->chain_id = chain->id;
3426 retval = IP_FW_DENY;
3434 panic("-- unknown opcode %d\n", cmd->opcode);
3435 } /* end of switch() on opcodes */
3437 if (cmd->len & F_NOT)
3441 if (cmd->len & F_OR)
3444 if (!(cmd->len & F_OR)) /* not an OR block, */
3445 break; /* try next rule */
3448 } /* end of inner for, scan opcodes */
3450 next_rule:; /* try next rule */
3452 } /* end of outer for, scan rules */
3453 printf("ipfw: ouch!, skip past end of rules, denying packet\n");
3454 IPFW_RUNLOCK(chain);
3455 if (ucred_cache != NULL)
3456 crfree(ucred_cache);
3457 return (IP_FW_DENY);
3460 /* Update statistics */
3463 f->timestamp = time_uptime;
3464 IPFW_RUNLOCK(chain);
3465 if (ucred_cache != NULL)
3466 crfree(ucred_cache);
3471 printf("ipfw: pullup failed\n");
3472 return (IP_FW_DENY);
3476 * When a rule is added/deleted, clear the next_rule pointers in all rules.
3477 * These will be reconstructed on the fly as packets are matched.
3480 flush_rule_ptrs(struct ip_fw_chain *chain)
3484 IPFW_WLOCK_ASSERT(chain);
3488 for (rule = chain->rules; rule; rule = rule->next)
3489 rule->next_rule = NULL;
3493 * Add a new rule to the list. Copy the rule into a malloc'ed area, then
3494 * possibly create a rule number and add the rule to the list.
3495 * Update the rule_number in the input struct so the caller knows it as well.
3498 add_rule(struct ip_fw_chain *chain, struct ip_fw *input_rule)
3500 struct ip_fw *rule, *f, *prev;
3501 int l = RULESIZE(input_rule);
3503 if (chain->rules == NULL && input_rule->rulenum != IPFW_DEFAULT_RULE)
3506 rule = malloc(l, M_IPFW, M_NOWAIT | M_ZERO);
3510 bcopy(input_rule, rule, l);
3513 rule->next_rule = NULL;
3517 rule->timestamp = 0;
3521 if (chain->rules == NULL) { /* default rule */
3522 chain->rules = rule;
3523 rule->id = ++chain->id;
3528 * If rulenum is 0, find highest numbered rule before the
3529 * default rule, and add autoinc_step
3531 if (V_autoinc_step < 1)
3533 else if (V_autoinc_step > 1000)
3534 V_autoinc_step = 1000;
3535 if (rule->rulenum == 0) {
3537 * locate the highest numbered rule before default
3539 for (f = chain->rules; f; f = f->next) {
3540 if (f->rulenum == IPFW_DEFAULT_RULE)
3542 rule->rulenum = f->rulenum;
3544 if (rule->rulenum < IPFW_DEFAULT_RULE - V_autoinc_step)
3545 rule->rulenum += V_autoinc_step;
3546 input_rule->rulenum = rule->rulenum;
3550 * Now insert the new rule in the right place in the sorted list.
3552 for (prev = NULL, f = chain->rules; f; prev = f, f = f->next) {
3553 if (f->rulenum > rule->rulenum) { /* found the location */
3557 } else { /* head insert */
3558 rule->next = chain->rules;
3559 chain->rules = rule;
3564 flush_rule_ptrs(chain);
3565 /* chain->id incremented inside flush_rule_ptrs() */
3566 rule->id = chain->id;
3570 IPFW_WUNLOCK(chain);
3571 DEB(printf("ipfw: installed rule %d, static count now %d\n",
3572 rule->rulenum, V_static_count);)
3577 * Remove a static rule (including derived * dynamic rules)
3578 * and place it on the ``reap list'' for later reclamation.
3579 * The caller is in charge of clearing rule pointers to avoid
3580 * dangling pointers.
3581 * @return a pointer to the next entry.
3582 * Arguments are not checked, so they better be correct.
3584 static struct ip_fw *
3585 remove_rule(struct ip_fw_chain *chain, struct ip_fw *rule,
3589 int l = RULESIZE(rule);
3591 IPFW_WLOCK_ASSERT(chain);
3595 remove_dyn_rule(rule, NULL /* force removal */);
3604 rule->next = chain->reap;
3611 * Reclaim storage associated with a list of rules. This is
3612 * typically the list created using remove_rule.
3613 * A NULL pointer on input is handled correctly.
3616 reap_rules(struct ip_fw *head)
3620 while ((rule = head) != NULL) {
3627 * Remove all rules from a chain (except rules in set RESVD_SET
3628 * unless kill_default = 1). The caller is responsible for
3629 * reclaiming storage for the rules left in chain->reap.
3632 free_chain(struct ip_fw_chain *chain, int kill_default)
3634 struct ip_fw *prev, *rule;
3636 IPFW_WLOCK_ASSERT(chain);
3639 flush_rule_ptrs(chain); /* more efficient to do outside the loop */
3640 for (prev = NULL, rule = chain->rules; rule ; )
3641 if (kill_default || rule->set != RESVD_SET)
3642 rule = remove_rule(chain, rule, prev);
3650 * Remove all rules with given number, and also do set manipulation.
3651 * Assumes chain != NULL && *chain != NULL.
3653 * The argument is an u_int32_t. The low 16 bit are the rule or set number,
3654 * the next 8 bits are the new set, the top 8 bits are the command:
3656 * 0 delete rules with given number
3657 * 1 delete rules with given set number
3658 * 2 move rules with given number to new set
3659 * 3 move rules with given set number to new set
3660 * 4 swap sets with given numbers
3661 * 5 delete rules with given number and with given set number
3664 del_entry(struct ip_fw_chain *chain, u_int32_t arg)
3666 struct ip_fw *prev = NULL, *rule;
3667 u_int16_t rulenum; /* rule or old_set */
3668 u_int8_t cmd, new_set;
3670 rulenum = arg & 0xffff;
3671 cmd = (arg >> 24) & 0xff;
3672 new_set = (arg >> 16) & 0xff;
3674 if (cmd > 5 || new_set > RESVD_SET)
3676 if (cmd == 0 || cmd == 2 || cmd == 5) {
3677 if (rulenum >= IPFW_DEFAULT_RULE)
3680 if (rulenum > RESVD_SET) /* old_set */
3685 rule = chain->rules; /* common starting point */
3686 chain->reap = NULL; /* prepare for deletions */
3688 case 0: /* delete rules with given number */
3690 * locate first rule to delete
3692 for (; rule->rulenum < rulenum; prev = rule, rule = rule->next)
3694 if (rule->rulenum != rulenum) {
3695 IPFW_WUNLOCK(chain);
3700 * flush pointers outside the loop, then delete all matching
3701 * rules. prev remains the same throughout the cycle.
3703 flush_rule_ptrs(chain);
3704 while (rule->rulenum == rulenum)
3705 rule = remove_rule(chain, rule, prev);
3708 case 1: /* delete all rules with given set number */
3709 flush_rule_ptrs(chain);
3710 while (rule->rulenum < IPFW_DEFAULT_RULE) {
3711 if (rule->set == rulenum)
3712 rule = remove_rule(chain, rule, prev);
3720 case 2: /* move rules with given number to new set */
3721 for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
3722 if (rule->rulenum == rulenum)
3723 rule->set = new_set;
3726 case 3: /* move rules with given set number to new set */
3727 for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
3728 if (rule->set == rulenum)
3729 rule->set = new_set;
3732 case 4: /* swap two sets */
3733 for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
3734 if (rule->set == rulenum)
3735 rule->set = new_set;
3736 else if (rule->set == new_set)
3737 rule->set = rulenum;
3740 case 5: /* delete rules with given number and with given set number.
3741 * rulenum - given rule number;
3742 * new_set - given set number.
3744 for (; rule->rulenum < rulenum; prev = rule, rule = rule->next)
3746 if (rule->rulenum != rulenum) {
3747 IPFW_WUNLOCK(chain);
3750 flush_rule_ptrs(chain);
3751 while (rule->rulenum == rulenum) {
3752 if (rule->set == new_set)
3753 rule = remove_rule(chain, rule, prev);
3761 * Look for rules to reclaim. We grab the list before
3762 * releasing the lock then reclaim them w/o the lock to
3763 * avoid a LOR with dummynet.
3766 IPFW_WUNLOCK(chain);
3772 * Clear counters for a specific rule.
3773 * The enclosing "table" is assumed locked.
3776 clear_counters(struct ip_fw *rule, int log_only)
3778 ipfw_insn_log *l = (ipfw_insn_log *)ACTION_PTR(rule);
3780 if (log_only == 0) {
3781 rule->bcnt = rule->pcnt = 0;
3782 rule->timestamp = 0;
3784 if (l->o.opcode == O_LOG)
3785 l->log_left = l->max_log;
3789 * Reset some or all counters on firewall rules.
3790 * The argument `arg' is an u_int32_t. The low 16 bit are the rule number,
3791 * the next 8 bits are the set number, the top 8 bits are the command:
3792 * 0 work with rules from all set's;
3793 * 1 work with rules only from specified set.
3794 * Specified rule number is zero if we want to clear all entries.
3795 * log_only is 1 if we only want to reset logs, zero otherwise.
3798 zero_entry(struct ip_fw_chain *chain, u_int32_t arg, int log_only)
3803 uint16_t rulenum = arg & 0xffff;
3804 uint8_t set = (arg >> 16) & 0xff;
3805 uint8_t cmd = (arg >> 24) & 0xff;
3809 if (cmd == 1 && set > RESVD_SET)
3814 V_norule_counter = 0;
3815 for (rule = chain->rules; rule; rule = rule->next) {
3816 /* Skip rules from another set. */
3817 if (cmd == 1 && rule->set != set)
3819 clear_counters(rule, log_only);
3821 msg = log_only ? "All logging counts reset" :
3822 "Accounting cleared";
3826 * We can have multiple rules with the same number, so we
3827 * need to clear them all.
3829 for (rule = chain->rules; rule; rule = rule->next)
3830 if (rule->rulenum == rulenum) {
3831 while (rule && rule->rulenum == rulenum) {
3832 if (cmd == 0 || rule->set == set)
3833 clear_counters(rule, log_only);
3839 if (!cleared) { /* we did not find any matching rules */
3840 IPFW_WUNLOCK(chain);
3843 msg = log_only ? "logging count reset" : "cleared";
3845 IPFW_WUNLOCK(chain);
3848 int lev = LOG_SECURITY | LOG_NOTICE;
3851 log(lev, "ipfw: Entry %d %s.\n", rulenum, msg);
3853 log(lev, "ipfw: %s.\n", msg);
3859 * Check validity of the structure before insert.
3860 * Fortunately rules are simple, so this mostly need to check rule sizes.
3863 check_ipfw_struct(struct ip_fw *rule, int size)
3869 if (size < sizeof(*rule)) {
3870 printf("ipfw: rule too short\n");
3873 /* first, check for valid size */
3876 printf("ipfw: size mismatch (have %d want %d)\n", size, l);
3879 if (rule->act_ofs >= rule->cmd_len) {
3880 printf("ipfw: bogus action offset (%u > %u)\n",
3881 rule->act_ofs, rule->cmd_len - 1);
3885 * Now go for the individual checks. Very simple ones, basically only
3886 * instruction sizes.
3888 for (l = rule->cmd_len, cmd = rule->cmd ;
3889 l > 0 ; l -= cmdlen, cmd += cmdlen) {
3890 cmdlen = F_LEN(cmd);
3892 printf("ipfw: opcode %d size truncated\n",
3896 DEB(printf("ipfw: opcode %d\n", cmd->opcode);)
3897 switch (cmd->opcode) {
3909 case O_IPPRECEDENCE:
3927 if (cmdlen != F_INSN_SIZE(ipfw_insn))
3932 if (cmdlen != F_INSN_SIZE(ipfw_insn))
3934 if (cmd->arg1 >= rt_numfibs) {
3935 printf("ipfw: invalid fib number %d\n",
3942 if (cmdlen != F_INSN_SIZE(ipfw_insn))
3944 if (cmd->arg1 >= rt_numfibs) {
3945 printf("ipfw: invalid fib number %d\n",
3960 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32))
3965 if (cmdlen != F_INSN_SIZE(ipfw_insn_limit))
3970 if (cmdlen != F_INSN_SIZE(ipfw_insn_log))
3973 ((ipfw_insn_log *)cmd)->log_left =
3974 ((ipfw_insn_log *)cmd)->max_log;
3980 /* only odd command lengths */
3981 if ( !(cmdlen & 1) || cmdlen > 31)
3987 if (cmd->arg1 == 0 || cmd->arg1 > 256) {
3988 printf("ipfw: invalid set size %d\n",
3992 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
3997 case O_IP_SRC_LOOKUP:
3998 case O_IP_DST_LOOKUP:
3999 if (cmd->arg1 >= IPFW_TABLES_MAX) {
4000 printf("ipfw: invalid table number %d\n",
4004 if (cmdlen != F_INSN_SIZE(ipfw_insn) &&
4005 cmdlen != F_INSN_SIZE(ipfw_insn_u32))
4010 if (cmdlen != F_INSN_SIZE(ipfw_insn_mac))
4020 if (cmdlen < 1 || cmdlen > 31)
4026 case O_IP_DSTPORT: /* XXX artificial limit, 30 port pairs */
4027 if (cmdlen < 2 || cmdlen > 31)
4034 if (cmdlen != F_INSN_SIZE(ipfw_insn_if))
4039 if (cmdlen != F_INSN_SIZE(ipfw_insn_altq))
4045 if (cmdlen != F_INSN_SIZE(ipfw_insn))
4050 #ifdef IPFIREWALL_FORWARD
4051 if (cmdlen != F_INSN_SIZE(ipfw_insn_sa))
4060 if (ip_divert_ptr == NULL)
4066 if (!NG_IPFW_LOADED)
4071 if (!IPFW_NAT_LOADED)
4073 if (cmdlen != F_INSN_SIZE(ipfw_insn_nat))
4076 case O_FORWARD_MAC: /* XXX not implemented yet */
4088 if (cmdlen != F_INSN_SIZE(ipfw_insn))
4092 printf("ipfw: opcode %d, multiple actions"
4099 printf("ipfw: opcode %d, action must be"
4108 if (cmdlen != F_INSN_SIZE(struct in6_addr) +
4109 F_INSN_SIZE(ipfw_insn))
4114 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
4115 ((ipfw_insn_u32 *)cmd)->o.arg1)
4119 case O_IP6_SRC_MASK:
4120 case O_IP6_DST_MASK:
4121 if ( !(cmdlen & 1) || cmdlen > 127)
4125 if( cmdlen != F_INSN_SIZE( ipfw_insn_icmp6 ) )
4131 switch (cmd->opcode) {
4141 case O_IP6_SRC_MASK:
4142 case O_IP6_DST_MASK:
4144 printf("ipfw: no IPv6 support in kernel\n");
4145 return EPROTONOSUPPORT;
4148 printf("ipfw: opcode %d, unknown opcode\n",
4154 if (have_action == 0) {
4155 printf("ipfw: missing action\n");
4161 printf("ipfw: opcode %d size %d wrong\n",
4162 cmd->opcode, cmdlen);
4167 * Copy the static and dynamic rules to the supplied buffer
4168 * and return the amount of space actually used.
4171 ipfw_getrules(struct ip_fw_chain *chain, void *buf, size_t space)
4174 char *ep = bp + space;
4177 time_t boot_seconds;
4179 boot_seconds = boottime.tv_sec;
4180 /* XXX this can take a long time and locking will block packet flow */
4182 for (rule = chain->rules; rule ; rule = rule->next) {
4184 * Verify the entry fits in the buffer in case the
4185 * rules changed between calculating buffer space and
4186 * now. This would be better done using a generation
4187 * number but should suffice for now.
4193 * XXX HACK. Store the disable mask in the "next"
4194 * pointer in a wild attempt to keep the ABI the same.
4195 * Why do we do this on EVERY rule?
4197 bcopy(&V_set_disable,
4198 &(((struct ip_fw *)bp)->next_rule),
4199 sizeof(V_set_disable));
4200 if (((struct ip_fw *)bp)->timestamp)
4201 ((struct ip_fw *)bp)->timestamp += boot_seconds;
4205 IPFW_RUNLOCK(chain);
4207 ipfw_dyn_rule *p, *last = NULL;
4210 for (i = 0 ; i < V_curr_dyn_buckets; i++)
4211 for (p = V_ipfw_dyn_v[i] ; p != NULL; p = p->next) {
4212 if (bp + sizeof *p <= ep) {
4213 ipfw_dyn_rule *dst =
4214 (ipfw_dyn_rule *)bp;
4215 bcopy(p, dst, sizeof *p);
4216 bcopy(&(p->rule->rulenum), &(dst->rule),
4217 sizeof(p->rule->rulenum));
4219 * store set number into high word of
4220 * dst->rule pointer.
4222 bcopy(&(p->rule->set),
4223 (char *)&dst->rule +
4224 sizeof(p->rule->rulenum),
4225 sizeof(p->rule->set));
4227 * store a non-null value in "next".
4228 * The userland code will interpret a
4229 * NULL here as a marker
4230 * for the last dynamic rule.
4232 bcopy(&dst, &dst->next, sizeof(dst));
4235 TIME_LEQ(dst->expire, time_uptime) ?
4236 0 : dst->expire - time_uptime ;
4237 bp += sizeof(ipfw_dyn_rule);
4241 if (last != NULL) /* mark last dynamic rule */
4242 bzero(&last->next, sizeof(last));
4244 return (bp - (char *)buf);
4249 * {set|get}sockopt parser.
4252 ipfw_ctl(struct sockopt *sopt)
4254 #define RULE_MAXSIZE (256*sizeof(u_int32_t))
4257 struct ip_fw *buf, *rule;
4258 u_int32_t rulenum[2];
4260 error = priv_check(sopt->sopt_td, PRIV_NETINET_IPFW);
4265 * Disallow modifications in really-really secure mode, but still allow
4266 * the logging counters to be reset.
4268 if (sopt->sopt_name == IP_FW_ADD ||
4269 (sopt->sopt_dir == SOPT_SET && sopt->sopt_name != IP_FW_RESETLOG)) {
4270 error = securelevel_ge(sopt->sopt_td->td_ucred, 3);
4277 switch (sopt->sopt_name) {
4280 * pass up a copy of the current rules. Static rules
4281 * come first (the last of which has number IPFW_DEFAULT_RULE),
4282 * followed by a possibly empty list of dynamic rule.
4283 * The last dynamic rule has NULL in the "next" field.
4285 * Note that the calculated size is used to bound the
4286 * amount of data returned to the user. The rule set may
4287 * change between calculating the size and returning the
4288 * data in which case we'll just return what fits.
4290 size = V_static_len; /* size of static rules */
4291 if (V_ipfw_dyn_v) /* add size of dyn.rules */
4292 size += (V_dyn_count * sizeof(ipfw_dyn_rule));
4294 if (size >= sopt->sopt_valsize)
4297 * XXX todo: if the user passes a short length just to know
4298 * how much room is needed, do not bother filling up the
4299 * buffer, just jump to the sooptcopyout.
4301 buf = malloc(size, M_TEMP, M_WAITOK);
4302 error = sooptcopyout(sopt, buf,
4303 ipfw_getrules(&V_layer3_chain, buf, size));
4309 * Normally we cannot release the lock on each iteration.
4310 * We could do it here only because we start from the head all
4311 * the times so there is no risk of missing some entries.
4312 * On the other hand, the risk is that we end up with
4313 * a very inconsistent ruleset, so better keep the lock
4314 * around the whole cycle.
4316 * XXX this code can be improved by resetting the head of
4317 * the list to point to the default rule, and then freeing
4318 * the old list without the need for a lock.
4321 IPFW_WLOCK(&V_layer3_chain);
4322 free_chain(&V_layer3_chain, 0 /* keep default rule */);
4323 rule = V_layer3_chain.reap;
4324 IPFW_WUNLOCK(&V_layer3_chain);
4329 rule = malloc(RULE_MAXSIZE, M_TEMP, M_WAITOK);
4330 error = sooptcopyin(sopt, rule, RULE_MAXSIZE,
4331 sizeof(struct ip_fw) );
4333 error = check_ipfw_struct(rule, sopt->sopt_valsize);
4335 error = add_rule(&V_layer3_chain, rule);
4336 size = RULESIZE(rule);
4337 if (!error && sopt->sopt_dir == SOPT_GET)
4338 error = sooptcopyout(sopt, rule, size);
4345 * IP_FW_DEL is used for deleting single rules or sets,
4346 * and (ab)used to atomically manipulate sets. Argument size
4347 * is used to distinguish between the two:
4349 * delete single rule or set of rules,
4350 * or reassign rules (or sets) to a different set.
4351 * 2*sizeof(u_int32_t)
4352 * atomic disable/enable sets.
4353 * first u_int32_t contains sets to be disabled,
4354 * second u_int32_t contains sets to be enabled.
4356 error = sooptcopyin(sopt, rulenum,
4357 2*sizeof(u_int32_t), sizeof(u_int32_t));
4360 size = sopt->sopt_valsize;
4361 if (size == sizeof(u_int32_t)) /* delete or reassign */
4362 error = del_entry(&V_layer3_chain, rulenum[0]);
4363 else if (size == 2*sizeof(u_int32_t)) /* set enable/disable */
4365 (V_set_disable | rulenum[0]) & ~rulenum[1] &
4366 ~(1<<RESVD_SET); /* set RESVD_SET always enabled */
4372 case IP_FW_RESETLOG: /* argument is an u_int_32, the rule number */
4374 if (sopt->sopt_val != 0) {
4375 error = sooptcopyin(sopt, rulenum,
4376 sizeof(u_int32_t), sizeof(u_int32_t));
4380 error = zero_entry(&V_layer3_chain, rulenum[0],
4381 sopt->sopt_name == IP_FW_RESETLOG);
4384 case IP_FW_TABLE_ADD:
4386 ipfw_table_entry ent;
4388 error = sooptcopyin(sopt, &ent,
4389 sizeof(ent), sizeof(ent));
4392 error = add_table_entry(&V_layer3_chain, ent.tbl,
4393 ent.addr, ent.masklen, ent.value);
4397 case IP_FW_TABLE_DEL:
4399 ipfw_table_entry ent;
4401 error = sooptcopyin(sopt, &ent,
4402 sizeof(ent), sizeof(ent));
4405 error = del_table_entry(&V_layer3_chain, ent.tbl,
4406 ent.addr, ent.masklen);
4410 case IP_FW_TABLE_FLUSH:
4414 error = sooptcopyin(sopt, &tbl,
4415 sizeof(tbl), sizeof(tbl));
4418 IPFW_WLOCK(&V_layer3_chain);
4419 error = flush_table(&V_layer3_chain, tbl);
4420 IPFW_WUNLOCK(&V_layer3_chain);
4424 case IP_FW_TABLE_GETSIZE:
4428 if ((error = sooptcopyin(sopt, &tbl, sizeof(tbl),
4431 IPFW_RLOCK(&V_layer3_chain);
4432 error = count_table(&V_layer3_chain, tbl, &cnt);
4433 IPFW_RUNLOCK(&V_layer3_chain);
4436 error = sooptcopyout(sopt, &cnt, sizeof(cnt));
4440 case IP_FW_TABLE_LIST:
4444 if (sopt->sopt_valsize < sizeof(*tbl)) {
4448 size = sopt->sopt_valsize;
4449 tbl = malloc(size, M_TEMP, M_WAITOK);
4450 error = sooptcopyin(sopt, tbl, size, sizeof(*tbl));
4455 tbl->size = (size - sizeof(*tbl)) /
4456 sizeof(ipfw_table_entry);
4457 IPFW_RLOCK(&V_layer3_chain);
4458 error = dump_table(&V_layer3_chain, tbl);
4459 IPFW_RUNLOCK(&V_layer3_chain);
4464 error = sooptcopyout(sopt, tbl, size);
4470 if (IPFW_NAT_LOADED)
4471 error = ipfw_nat_cfg_ptr(sopt);
4473 printf("IP_FW_NAT_CFG: %s\n",
4474 "ipfw_nat not present, please load it");
4480 if (IPFW_NAT_LOADED)
4481 error = ipfw_nat_del_ptr(sopt);
4483 printf("IP_FW_NAT_DEL: %s\n",
4484 "ipfw_nat not present, please load it");
4489 case IP_FW_NAT_GET_CONFIG:
4490 if (IPFW_NAT_LOADED)
4491 error = ipfw_nat_get_cfg_ptr(sopt);
4493 printf("IP_FW_NAT_GET_CFG: %s\n",
4494 "ipfw_nat not present, please load it");
4499 case IP_FW_NAT_GET_LOG:
4500 if (IPFW_NAT_LOADED)
4501 error = ipfw_nat_get_log_ptr(sopt);
4503 printf("IP_FW_NAT_GET_LOG: %s\n",
4504 "ipfw_nat not present, please load it");
4510 printf("ipfw: ipfw_ctl invalid option %d\n", sopt->sopt_name);
4520 * This procedure is only used to handle keepalives. It is invoked
4521 * every dyn_keepalive_period
4524 ipfw_tick(void * vnetx)
4526 struct mbuf *m0, *m, *mnext, **mtailp;
4530 struct vnet *vp = vnetx;
4534 if (V_dyn_keepalive == 0 || V_ipfw_dyn_v == NULL || V_dyn_count == 0)
4538 * We make a chain of packets to go out here -- not deferring
4539 * until after we drop the IPFW dynamic rule lock would result
4540 * in a lock order reversal with the normal packet input -> ipfw
4546 for (i = 0 ; i < V_curr_dyn_buckets ; i++) {
4547 for (q = V_ipfw_dyn_v[i] ; q ; q = q->next ) {
4548 if (q->dyn_type == O_LIMIT_PARENT)
4550 if (q->id.proto != IPPROTO_TCP)
4552 if ( (q->state & BOTH_SYN) != BOTH_SYN)
4554 if (TIME_LEQ(time_uptime + V_dyn_keepalive_interval,
4556 continue; /* too early */
4557 if (TIME_LEQ(q->expire, time_uptime))
4558 continue; /* too late, rule expired */
4560 *mtailp = send_pkt(NULL, &(q->id), q->ack_rev - 1,
4561 q->ack_fwd, TH_SYN);
4562 if (*mtailp != NULL)
4563 mtailp = &(*mtailp)->m_nextpkt;
4564 *mtailp = send_pkt(NULL, &(q->id), q->ack_fwd - 1,
4566 if (*mtailp != NULL)
4567 mtailp = &(*mtailp)->m_nextpkt;
4571 for (m = mnext = m0; m != NULL; m = mnext) {
4572 mnext = m->m_nextpkt;
4573 m->m_nextpkt = NULL;
4574 ip_output(m, NULL, NULL, 0, NULL, NULL);
4577 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 iattach()
4627 * may not have been called yet for the VIMGE case.
4628 * Tuneables will have been processed.
4630 if (V_fw_verbose == 0)
4631 printf("disabled\n");
4632 else if (V_verbose_limit == 0)
4633 printf("unlimited\n");
4635 printf("limited to %d packets/entry by default\n",
4639 * Other things that are only done the first time.
4640 * (now that we a re cuaranteed of success).
4642 ip_fw_ctl_ptr = ipfw_ctl;
4643 ip_fw_chk_ptr = ipfw_chk;
4648 * Stuff that must be initialised for every instance
4649 * (including the forst of course).
4652 vnet_ipfw_init(const void *unused)
4655 struct ip_fw default_rule;
4657 /* First set up some values that are compile time options */
4658 #ifdef IPFIREWALL_VERBOSE
4661 #ifdef IPFIREWALL_VERBOSE_LIMIT
4662 V_verbose_limit = IPFIREWALL_VERBOSE_LIMIT;
4665 error = init_tables(&V_layer3_chain);
4667 panic("init_tables"); /* XXX Marko fix this ! */
4669 #ifdef IPFIREWALL_NAT
4670 LIST_INIT(&V_layer3_chain.nat);
4673 V_autoinc_step = 100; /* bounded to 1..1000 in add_rule() */
4675 V_ipfw_dyn_v = NULL;
4676 V_dyn_buckets = 256; /* must be power of 2 */
4677 V_curr_dyn_buckets = 256; /* must be power of 2 */
4679 V_dyn_ack_lifetime = 300;
4680 V_dyn_syn_lifetime = 20;
4681 V_dyn_fin_lifetime = 1;
4682 V_dyn_rst_lifetime = 1;
4683 V_dyn_udp_lifetime = 10;
4684 V_dyn_short_lifetime = 5;
4686 V_dyn_keepalive_interval = 20;
4687 V_dyn_keepalive_period = 5;
4688 V_dyn_keepalive = 1; /* do send keepalives */
4690 V_dyn_max = 4096; /* max # of dynamic rules */
4692 V_fw_deny_unknown_exthdrs = 1;
4694 V_layer3_chain.rules = NULL;
4695 IPFW_LOCK_INIT(&V_layer3_chain);
4696 callout_init(&V_ipfw_timeout, CALLOUT_MPSAFE);
4698 bzero(&default_rule, sizeof default_rule);
4699 default_rule.act_ofs = 0;
4700 default_rule.rulenum = IPFW_DEFAULT_RULE;
4701 default_rule.cmd_len = 1;
4702 default_rule.set = RESVD_SET;
4703 default_rule.cmd[0].len = 1;
4704 default_rule.cmd[0].opcode = default_to_accept ? O_ACCEPT : O_DENY;
4705 error = add_rule(&V_layer3_chain, &default_rule);
4708 printf("ipfw2: error %u initializing default rule "
4709 "(support disabled)\n", error);
4710 IPFW_LOCK_DESTROY(&V_layer3_chain);
4711 printf("leaving ipfw_iattach (1) with error %d\n", error);
4715 ip_fw_default_rule = V_layer3_chain.rules;
4718 IPFW_LOCK_DESTROY(&V_layer3_chain);
4719 printf("leaving ipfw_iattach (2) with error %d\n", error);
4722 #ifdef VIMAGE /* want a better way to do this */
4723 callout_reset(&V_ipfw_timeout, hz, ipfw_tick, curvnet);
4725 callout_reset(&V_ipfw_timeout, hz, ipfw_tick, NULL);
4728 /* First set up some values that are compile time options */
4732 /**********************
4733 * Called for the removal of the last instance only on module unload.
4738 ip_fw_chk_ptr = NULL;
4739 ip_fw_ctl_ptr = NULL;
4740 uma_zdestroy(ipfw_dyn_rule_zone);
4741 IPFW_DYN_LOCK_DESTROY();
4742 printf("IP firewall unloaded\n");
4745 /***********************
4746 * Called for the removal of each instance.
4749 vnet_ipfw_uninit(const void *unused)
4753 callout_drain(&V_ipfw_timeout);
4754 IPFW_WLOCK(&V_layer3_chain);
4755 flush_tables(&V_layer3_chain);
4756 V_layer3_chain.reap = NULL;
4757 free_chain(&V_layer3_chain, 1 /* kill default rule */);
4758 reap = V_layer3_chain.reap;
4759 V_layer3_chain.reap = NULL;
4760 IPFW_WUNLOCK(&V_layer3_chain);
4763 IPFW_LOCK_DESTROY(&V_layer3_chain);
4764 if (V_ipfw_dyn_v != NULL)
4765 free(V_ipfw_dyn_v, M_IPFW);
4769 VNET_SYSINIT(vnet_ipfw_init, SI_SUB_PROTO_IFATTACHDOMAIN, SI_ORDER_ANY - 255,
4770 vnet_ipfw_init, NULL);
4772 VNET_SYSUNINIT(vnet_ipfw_uninit, SI_SUB_PROTO_IFATTACHDOMAIN, SI_ORDER_ANY - 255,
4773 vnet_ipfw_uninit, NULL);