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>
97 #include <netinet6/ip6_var.h>
100 #include <machine/in_cksum.h> /* XXX for in_cksum */
103 #include <security/mac/mac_framework.h>
106 static VNET_DEFINE(int, ipfw_vnet_ready) = 0;
107 #define V_ipfw_vnet_ready VNET(ipfw_vnet_ready)
109 * set_disable contains one bit per set value (0..31).
110 * If the bit is set, all rules with the corresponding set
111 * are disabled. Set RESVD_SET(31) is reserved for the default rule
112 * and rules that are not deleted by the flush command,
113 * and CANNOT be disabled.
114 * Rules in set RESVD_SET can only be deleted explicitly.
116 static VNET_DEFINE(u_int32_t, set_disable);
117 static VNET_DEFINE(int, fw_verbose);
118 static VNET_DEFINE(struct callout, ipfw_timeout);
119 static VNET_DEFINE(int, verbose_limit);
121 #define V_set_disable VNET(set_disable)
122 #define V_fw_verbose VNET(fw_verbose)
123 #define V_ipfw_timeout VNET(ipfw_timeout)
124 #define V_verbose_limit VNET(verbose_limit)
126 #ifdef IPFIREWALL_DEFAULT_TO_ACCEPT
127 static int default_to_accept = 1;
129 static int default_to_accept;
131 static uma_zone_t ipfw_dyn_rule_zone;
133 struct ip_fw *ip_fw_default_rule;
136 * list of rules for layer 3
138 VNET_DEFINE(struct ip_fw_chain, layer3_chain);
140 MALLOC_DEFINE(M_IPFW, "IpFw/IpAcct", "IpFw/IpAcct chain's");
141 MALLOC_DEFINE(M_IPFW_TBL, "ipfw_tbl", "IpFw tables");
142 #define IPFW_NAT_LOADED (ipfw_nat_ptr != NULL)
143 ipfw_nat_t *ipfw_nat_ptr = NULL;
144 ipfw_nat_cfg_t *ipfw_nat_cfg_ptr;
145 ipfw_nat_cfg_t *ipfw_nat_del_ptr;
146 ipfw_nat_cfg_t *ipfw_nat_get_cfg_ptr;
147 ipfw_nat_cfg_t *ipfw_nat_get_log_ptr;
150 struct radix_node rn[2];
151 struct sockaddr_in addr, mask;
155 static VNET_DEFINE(int, autoinc_step);
156 #define V_autoinc_step VNET(autoinc_step)
157 static VNET_DEFINE(int, fw_deny_unknown_exthdrs);
158 #define V_fw_deny_unknown_exthdrs VNET(fw_deny_unknown_exthdrs)
160 extern int ipfw_chg_hook(SYSCTL_HANDLER_ARGS);
163 SYSCTL_NODE(_net_inet_ip, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall");
164 SYSCTL_VNET_PROC(_net_inet_ip_fw, OID_AUTO, enable,
165 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE3, &VNET_NAME(fw_enable), 0,
166 ipfw_chg_hook, "I", "Enable ipfw");
167 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, autoinc_step,
168 CTLFLAG_RW, &VNET_NAME(autoinc_step), 0,
169 "Rule number auto-increment step");
170 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, one_pass,
171 CTLFLAG_RW | CTLFLAG_SECURE3, &VNET_NAME(fw_one_pass), 0,
172 "Only do a single pass through ipfw when using dummynet(4)");
173 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, verbose,
174 CTLFLAG_RW | CTLFLAG_SECURE3, &VNET_NAME(fw_verbose), 0,
175 "Log matches to ipfw rules");
176 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, verbose_limit,
177 CTLFLAG_RW, &VNET_NAME(verbose_limit), 0,
178 "Set upper limit of matches of ipfw rules logged");
179 SYSCTL_UINT(_net_inet_ip_fw, OID_AUTO, default_rule, CTLFLAG_RD,
180 NULL, IPFW_DEFAULT_RULE,
181 "The default/max possible rule number.");
182 SYSCTL_UINT(_net_inet_ip_fw, OID_AUTO, tables_max, CTLFLAG_RD,
183 NULL, IPFW_TABLES_MAX,
184 "The maximum number of tables.");
185 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, default_to_accept, CTLFLAG_RDTUN,
186 &default_to_accept, 0,
187 "Make the default rule accept all packets.");
188 TUNABLE_INT("net.inet.ip.fw.default_to_accept", &default_to_accept);
191 SYSCTL_DECL(_net_inet6_ip6);
192 SYSCTL_NODE(_net_inet6_ip6, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall");
193 SYSCTL_VNET_PROC(_net_inet6_ip6_fw, OID_AUTO, enable,
194 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE3, &VNET_NAME(fw6_enable), 0,
195 ipfw_chg_hook, "I", "Enable ipfw+6");
196 SYSCTL_VNET_INT(_net_inet6_ip6_fw, OID_AUTO, deny_unknown_exthdrs,
197 CTLFLAG_RW | CTLFLAG_SECURE, &VNET_NAME(fw_deny_unknown_exthdrs), 0,
198 "Deny packets with unknown IPv6 Extension Headers");
201 #endif /* SYSCTL_NODE */
204 * Description of dynamic rules.
206 * Dynamic rules are stored in lists accessed through a hash table
207 * (ipfw_dyn_v) whose size is curr_dyn_buckets. This value can
208 * be modified through the sysctl variable dyn_buckets which is
209 * updated when the table becomes empty.
211 * XXX currently there is only one list, ipfw_dyn.
213 * When a packet is received, its address fields are first masked
214 * with the mask defined for the rule, then hashed, then matched
215 * against the entries in the corresponding list.
216 * Dynamic rules can be used for different purposes:
218 * + enforcing limits on the number of sessions;
219 * + in-kernel NAT (not implemented yet)
221 * The lifetime of dynamic rules is regulated by dyn_*_lifetime,
222 * measured in seconds and depending on the flags.
224 * The total number of dynamic rules is stored in dyn_count.
225 * The max number of dynamic rules is dyn_max. When we reach
226 * the maximum number of rules we do not create anymore. This is
227 * done to avoid consuming too much memory, but also too much
228 * time when searching on each packet (ideally, we should try instead
229 * to put a limit on the length of the list on each bucket...).
231 * Each dynamic rule holds a pointer to the parent ipfw rule so
232 * we know what action to perform. Dynamic rules are removed when
233 * the parent rule is deleted. XXX we should make them survive.
235 * There are some limitations with dynamic rules -- we do not
236 * obey the 'randomized match', and we do not do multiple
237 * passes through the firewall. XXX check the latter!!!
239 static VNET_DEFINE(ipfw_dyn_rule **, ipfw_dyn_v);
240 static VNET_DEFINE(u_int32_t, dyn_buckets);
241 static VNET_DEFINE(u_int32_t, curr_dyn_buckets);
243 #define V_ipfw_dyn_v VNET(ipfw_dyn_v)
244 #define V_dyn_buckets VNET(dyn_buckets)
245 #define V_curr_dyn_buckets VNET(curr_dyn_buckets)
247 static struct mtx ipfw_dyn_mtx; /* mutex guarding dynamic rules */
248 #define IPFW_DYN_LOCK_INIT() \
249 mtx_init(&ipfw_dyn_mtx, "IPFW dynamic rules", NULL, MTX_DEF)
250 #define IPFW_DYN_LOCK_DESTROY() mtx_destroy(&ipfw_dyn_mtx)
251 #define IPFW_DYN_LOCK() mtx_lock(&ipfw_dyn_mtx)
252 #define IPFW_DYN_UNLOCK() mtx_unlock(&ipfw_dyn_mtx)
253 #define IPFW_DYN_LOCK_ASSERT() mtx_assert(&ipfw_dyn_mtx, MA_OWNED)
255 static struct mbuf *send_pkt(struct mbuf *, struct ipfw_flow_id *,
256 u_int32_t, u_int32_t, int);
260 * Timeouts for various events in handing dynamic rules.
262 static VNET_DEFINE(u_int32_t, dyn_ack_lifetime);
263 static VNET_DEFINE(u_int32_t, dyn_syn_lifetime);
264 static VNET_DEFINE(u_int32_t, dyn_fin_lifetime);
265 static VNET_DEFINE(u_int32_t, dyn_rst_lifetime);
266 static VNET_DEFINE(u_int32_t, dyn_udp_lifetime);
267 static VNET_DEFINE(u_int32_t, dyn_short_lifetime);
269 #define V_dyn_ack_lifetime VNET(dyn_ack_lifetime)
270 #define V_dyn_syn_lifetime VNET(dyn_syn_lifetime)
271 #define V_dyn_fin_lifetime VNET(dyn_fin_lifetime)
272 #define V_dyn_rst_lifetime VNET(dyn_rst_lifetime)
273 #define V_dyn_udp_lifetime VNET(dyn_udp_lifetime)
274 #define V_dyn_short_lifetime VNET(dyn_short_lifetime)
277 * Keepalives are sent if dyn_keepalive is set. They are sent every
278 * dyn_keepalive_period seconds, in the last dyn_keepalive_interval
279 * seconds of lifetime of a rule.
280 * dyn_rst_lifetime and dyn_fin_lifetime should be strictly lower
281 * than dyn_keepalive_period.
284 static VNET_DEFINE(u_int32_t, dyn_keepalive_interval);
285 static VNET_DEFINE(u_int32_t, dyn_keepalive_period);
286 static VNET_DEFINE(u_int32_t, dyn_keepalive);
288 #define V_dyn_keepalive_interval VNET(dyn_keepalive_interval)
289 #define V_dyn_keepalive_period VNET(dyn_keepalive_period)
290 #define V_dyn_keepalive VNET(dyn_keepalive)
292 static VNET_DEFINE(u_int32_t, static_count); /* # of static rules */
293 static VNET_DEFINE(u_int32_t, static_len); /* bytes of static rules */
294 static VNET_DEFINE(u_int32_t, dyn_count); /* # of dynamic rules */
295 static VNET_DEFINE(u_int32_t, dyn_max); /* max # of dynamic rules */
297 #define V_static_count VNET(static_count)
298 #define V_static_len VNET(static_len)
299 #define V_dyn_count VNET(dyn_count)
300 #define V_dyn_max VNET(dyn_max)
303 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_buckets,
304 CTLFLAG_RW, &VNET_NAME(dyn_buckets), 0,
305 "Number of dyn. buckets");
306 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, curr_dyn_buckets,
307 CTLFLAG_RD, &VNET_NAME(curr_dyn_buckets), 0,
308 "Current Number of dyn. buckets");
309 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_count,
310 CTLFLAG_RD, &VNET_NAME(dyn_count), 0,
311 "Number of dyn. rules");
312 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_max,
313 CTLFLAG_RW, &VNET_NAME(dyn_max), 0,
314 "Max number of dyn. rules");
315 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, static_count,
316 CTLFLAG_RD, &VNET_NAME(static_count), 0,
317 "Number of static rules");
318 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_ack_lifetime,
319 CTLFLAG_RW, &VNET_NAME(dyn_ack_lifetime), 0,
320 "Lifetime of dyn. rules for acks");
321 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_syn_lifetime,
322 CTLFLAG_RW, &VNET_NAME(dyn_syn_lifetime), 0,
323 "Lifetime of dyn. rules for syn");
324 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_fin_lifetime,
325 CTLFLAG_RW, &VNET_NAME(dyn_fin_lifetime), 0,
326 "Lifetime of dyn. rules for fin");
327 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_rst_lifetime,
328 CTLFLAG_RW, &VNET_NAME(dyn_rst_lifetime), 0,
329 "Lifetime of dyn. rules for rst");
330 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_udp_lifetime,
331 CTLFLAG_RW, &VNET_NAME(dyn_udp_lifetime), 0,
332 "Lifetime of dyn. rules for UDP");
333 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_short_lifetime,
334 CTLFLAG_RW, &VNET_NAME(dyn_short_lifetime), 0,
335 "Lifetime of dyn. rules for other situations");
336 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_keepalive,
337 CTLFLAG_RW, &VNET_NAME(dyn_keepalive), 0,
338 "Enable keepalives for dyn. rules");
339 #endif /* SYSCTL_NODE */
342 * L3HDR maps an ipv4 pointer into a layer3 header pointer of type T
343 * Other macros just cast void * into the appropriate type
345 #define L3HDR(T, ip) ((T *)((u_int32_t *)(ip) + (ip)->ip_hl))
346 #define TCP(p) ((struct tcphdr *)(p))
347 #define SCTP(p) ((struct sctphdr *)(p))
348 #define UDP(p) ((struct udphdr *)(p))
349 #define ICMP(p) ((struct icmphdr *)(p))
350 #define ICMP6(p) ((struct icmp6_hdr *)(p))
353 icmptype_match(struct icmphdr *icmp, ipfw_insn_u32 *cmd)
355 int type = icmp->icmp_type;
357 return (type <= ICMP_MAXTYPE && (cmd->d[0] & (1<<type)) );
360 #define TT ( (1 << ICMP_ECHO) | (1 << ICMP_ROUTERSOLICIT) | \
361 (1 << ICMP_TSTAMP) | (1 << ICMP_IREQ) | (1 << ICMP_MASKREQ) )
364 is_icmp_query(struct icmphdr *icmp)
366 int type = icmp->icmp_type;
368 return (type <= ICMP_MAXTYPE && (TT & (1<<type)) );
373 * The following checks use two arrays of 8 or 16 bits to store the
374 * bits that we want set or clear, respectively. They are in the
375 * low and high half of cmd->arg1 or cmd->d[0].
377 * We scan options and store the bits we find set. We succeed if
379 * (want_set & ~bits) == 0 && (want_clear & ~bits) == want_clear
381 * The code is sometimes optimized not to store additional variables.
385 flags_match(ipfw_insn *cmd, u_int8_t bits)
390 if ( ((cmd->arg1 & 0xff) & bits) != 0)
391 return 0; /* some bits we want set were clear */
392 want_clear = (cmd->arg1 >> 8) & 0xff;
393 if ( (want_clear & bits) != want_clear)
394 return 0; /* some bits we want clear were set */
399 ipopts_match(struct ip *ip, ipfw_insn *cmd)
401 int optlen, bits = 0;
402 u_char *cp = (u_char *)(ip + 1);
403 int x = (ip->ip_hl << 2) - sizeof (struct ip);
405 for (; x > 0; x -= optlen, cp += optlen) {
406 int opt = cp[IPOPT_OPTVAL];
408 if (opt == IPOPT_EOL)
410 if (opt == IPOPT_NOP)
413 optlen = cp[IPOPT_OLEN];
414 if (optlen <= 0 || optlen > x)
415 return 0; /* invalid or truncated */
423 bits |= IP_FW_IPOPT_LSRR;
427 bits |= IP_FW_IPOPT_SSRR;
431 bits |= IP_FW_IPOPT_RR;
435 bits |= IP_FW_IPOPT_TS;
439 return (flags_match(cmd, bits));
443 tcpopts_match(struct tcphdr *tcp, ipfw_insn *cmd)
445 int optlen, bits = 0;
446 u_char *cp = (u_char *)(tcp + 1);
447 int x = (tcp->th_off << 2) - sizeof(struct tcphdr);
449 for (; x > 0; x -= optlen, cp += optlen) {
451 if (opt == TCPOPT_EOL)
453 if (opt == TCPOPT_NOP)
467 bits |= IP_FW_TCPOPT_MSS;
471 bits |= IP_FW_TCPOPT_WINDOW;
474 case TCPOPT_SACK_PERMITTED:
476 bits |= IP_FW_TCPOPT_SACK;
479 case TCPOPT_TIMESTAMP:
480 bits |= IP_FW_TCPOPT_TS;
485 return (flags_match(cmd, bits));
489 iface_match(struct ifnet *ifp, ipfw_insn_if *cmd)
491 if (ifp == NULL) /* no iface with this packet, match fails */
493 /* Check by name or by IP address */
494 if (cmd->name[0] != '\0') { /* match by name */
497 if (fnmatch(cmd->name, ifp->if_xname, 0) == 0)
500 if (strncmp(ifp->if_xname, cmd->name, IFNAMSIZ) == 0)
507 TAILQ_FOREACH(ia, &ifp->if_addrhead, ifa_link) {
508 if (ia->ifa_addr->sa_family != AF_INET)
510 if (cmd->p.ip.s_addr == ((struct sockaddr_in *)
511 (ia->ifa_addr))->sin_addr.s_addr) {
512 if_addr_runlock(ifp);
513 return(1); /* match */
516 if_addr_runlock(ifp);
518 return(0); /* no match, fail ... */
522 * The verify_path function checks if a route to the src exists and
523 * if it is reachable via ifp (when provided).
525 * The 'verrevpath' option checks that the interface that an IP packet
526 * arrives on is the same interface that traffic destined for the
527 * packet's source address would be routed out of. The 'versrcreach'
528 * option just checks that the source address is reachable via any route
529 * (except default) in the routing table. These two are a measure to block
530 * forged packets. This is also commonly known as "anti-spoofing" or Unicast
531 * Reverse Path Forwarding (Unicast RFP) in Cisco-ese. The name of the knobs
532 * is purposely reminiscent of the Cisco IOS command,
534 * ip verify unicast reverse-path
535 * ip verify unicast source reachable-via any
537 * which implements the same functionality. But note that syntax is
538 * misleading. The check may be performed on all IP packets whether unicast,
539 * multicast, or broadcast.
542 verify_path(struct in_addr src, struct ifnet *ifp, u_int fib)
545 struct sockaddr_in *dst;
547 bzero(&ro, sizeof(ro));
549 dst = (struct sockaddr_in *)&(ro.ro_dst);
550 dst->sin_family = AF_INET;
551 dst->sin_len = sizeof(*dst);
553 in_rtalloc_ign(&ro, 0, fib);
555 if (ro.ro_rt == NULL)
559 * If ifp is provided, check for equality with rtentry.
560 * We should use rt->rt_ifa->ifa_ifp, instead of rt->rt_ifp,
561 * in order to pass packets injected back by if_simloop():
562 * if useloopback == 1 routing entry (via lo0) for our own address
563 * may exist, so we need to handle routing assymetry.
565 if (ifp != NULL && ro.ro_rt->rt_ifa->ifa_ifp != ifp) {
570 /* if no ifp provided, check if rtentry is not default route */
572 satosin(rt_key(ro.ro_rt))->sin_addr.s_addr == INADDR_ANY) {
577 /* or if this is a blackhole/reject route */
578 if (ifp == NULL && ro.ro_rt->rt_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
583 /* found valid route */
590 * ipv6 specific rules here...
593 icmp6type_match (int type, ipfw_insn_u32 *cmd)
595 return (type <= ICMP6_MAXTYPE && (cmd->d[type/32] & (1<<(type%32)) ) );
599 flow6id_match( int curr_flow, ipfw_insn_u32 *cmd )
602 for (i=0; i <= cmd->o.arg1; ++i )
603 if (curr_flow == cmd->d[i] )
608 /* support for IP6_*_ME opcodes */
610 search_ip6_addr_net (struct in6_addr * ip6_addr)
614 struct in6_ifaddr *fdm;
615 struct in6_addr copia;
617 TAILQ_FOREACH(mdc, &V_ifnet, if_link) {
619 TAILQ_FOREACH(mdc2, &mdc->if_addrhead, ifa_link) {
620 if (mdc2->ifa_addr->sa_family == AF_INET6) {
621 fdm = (struct in6_ifaddr *)mdc2;
622 copia = fdm->ia_addr.sin6_addr;
623 /* need for leaving scope_id in the sock_addr */
624 in6_clearscope(&copia);
625 if (IN6_ARE_ADDR_EQUAL(ip6_addr, &copia)) {
626 if_addr_runlock(mdc);
631 if_addr_runlock(mdc);
637 verify_path6(struct in6_addr *src, struct ifnet *ifp)
640 struct sockaddr_in6 *dst;
642 bzero(&ro, sizeof(ro));
644 dst = (struct sockaddr_in6 * )&(ro.ro_dst);
645 dst->sin6_family = AF_INET6;
646 dst->sin6_len = sizeof(*dst);
647 dst->sin6_addr = *src;
648 /* XXX MRT 0 for ipv6 at this time */
649 rtalloc_ign((struct route *)&ro, 0);
651 if (ro.ro_rt == NULL)
655 * if ifp is provided, check for equality with rtentry
656 * We should use rt->rt_ifa->ifa_ifp, instead of rt->rt_ifp,
657 * to support the case of sending packets to an address of our own.
658 * (where the former interface is the first argument of if_simloop()
659 * (=ifp), the latter is lo0)
661 if (ifp != NULL && ro.ro_rt->rt_ifa->ifa_ifp != ifp) {
666 /* if no ifp provided, check if rtentry is not default route */
668 IN6_IS_ADDR_UNSPECIFIED(&satosin6(rt_key(ro.ro_rt))->sin6_addr)) {
673 /* or if this is a blackhole/reject route */
674 if (ifp == NULL && ro.ro_rt->rt_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
679 /* found valid route */
685 hash_packet6(struct ipfw_flow_id *id)
688 i = (id->dst_ip6.__u6_addr.__u6_addr32[2]) ^
689 (id->dst_ip6.__u6_addr.__u6_addr32[3]) ^
690 (id->src_ip6.__u6_addr.__u6_addr32[2]) ^
691 (id->src_ip6.__u6_addr.__u6_addr32[3]) ^
692 (id->dst_port) ^ (id->src_port);
697 is_icmp6_query(int icmp6_type)
699 if ((icmp6_type <= ICMP6_MAXTYPE) &&
700 (icmp6_type == ICMP6_ECHO_REQUEST ||
701 icmp6_type == ICMP6_MEMBERSHIP_QUERY ||
702 icmp6_type == ICMP6_WRUREQUEST ||
703 icmp6_type == ICMP6_FQDN_QUERY ||
704 icmp6_type == ICMP6_NI_QUERY))
711 send_reject6(struct ip_fw_args *args, int code, u_int hlen, struct ip6_hdr *ip6)
716 if (code == ICMP6_UNREACH_RST && args->f_id.proto == IPPROTO_TCP) {
718 tcp = (struct tcphdr *)((char *)ip6 + hlen);
720 if ((tcp->th_flags & TH_RST) == 0) {
722 m0 = send_pkt(args->m, &(args->f_id),
723 ntohl(tcp->th_seq), ntohl(tcp->th_ack),
724 tcp->th_flags | TH_RST);
726 ip6_output(m0, NULL, NULL, 0, NULL, NULL,
730 } else if (code != ICMP6_UNREACH_RST) { /* Send an ICMPv6 unreach. */
733 * Unlike above, the mbufs need to line up with the ip6 hdr,
734 * as the contents are read. We need to m_adj() the
736 * The mbuf will however be thrown away so we can adjust it.
737 * Remember we did an m_pullup on it already so we
738 * can make some assumptions about contiguousness.
741 m_adj(m, args->L3offset);
743 icmp6_error(m, ICMP6_DST_UNREACH, code, 0);
752 /* counter for ipfw_log(NULL...) */
753 static VNET_DEFINE(u_int64_t, norule_counter);
754 #define V_norule_counter VNET(norule_counter)
756 #define SNPARGS(buf, len) buf + len, sizeof(buf) > len ? sizeof(buf) - len : 0
757 #define SNP(buf) buf, sizeof(buf)
760 * We enter here when we have a rule with O_LOG.
761 * XXX this function alone takes about 2Kbytes of code!
764 ipfw_log(struct ip_fw *f, u_int hlen, struct ip_fw_args *args,
765 struct mbuf *m, struct ifnet *oif, u_short offset, uint32_t tablearg,
768 struct ether_header *eh = args->eh;
770 int limit_reached = 0;
771 char action2[40], proto[128], fragment[32];
776 if (f == NULL) { /* bogus pkt */
777 if (V_verbose_limit != 0 && V_norule_counter >= V_verbose_limit)
780 if (V_norule_counter == V_verbose_limit)
781 limit_reached = V_verbose_limit;
783 } else { /* O_LOG is the first action, find the real one */
784 ipfw_insn *cmd = ACTION_PTR(f);
785 ipfw_insn_log *l = (ipfw_insn_log *)cmd;
787 if (l->max_log != 0 && l->log_left == 0)
790 if (l->log_left == 0)
791 limit_reached = l->max_log;
792 cmd += F_LEN(cmd); /* point to first action */
793 if (cmd->opcode == O_ALTQ) {
794 ipfw_insn_altq *altq = (ipfw_insn_altq *)cmd;
796 snprintf(SNPARGS(action2, 0), "Altq %d",
800 if (cmd->opcode == O_PROB)
803 if (cmd->opcode == O_TAG)
807 switch (cmd->opcode) {
813 if (cmd->arg1==ICMP_REJECT_RST)
815 else if (cmd->arg1==ICMP_UNREACH_HOST)
818 snprintf(SNPARGS(action2, 0), "Unreach %d",
823 if (cmd->arg1==ICMP6_UNREACH_RST)
826 snprintf(SNPARGS(action2, 0), "Unreach %d",
837 snprintf(SNPARGS(action2, 0), "Divert %d",
841 snprintf(SNPARGS(action2, 0), "Tee %d",
845 snprintf(SNPARGS(action2, 0), "SetFib %d",
849 snprintf(SNPARGS(action2, 0), "SkipTo %d",
853 snprintf(SNPARGS(action2, 0), "Pipe %d",
857 snprintf(SNPARGS(action2, 0), "Queue %d",
861 ipfw_insn_sa *sa = (ipfw_insn_sa *)cmd;
863 struct in_addr dummyaddr;
864 if (sa->sa.sin_addr.s_addr == INADDR_ANY)
865 dummyaddr.s_addr = htonl(tablearg);
867 dummyaddr.s_addr = sa->sa.sin_addr.s_addr;
869 len = snprintf(SNPARGS(action2, 0), "Forward to %s",
870 inet_ntoa(dummyaddr));
873 snprintf(SNPARGS(action2, len), ":%d",
878 snprintf(SNPARGS(action2, 0), "Netgraph %d",
882 snprintf(SNPARGS(action2, 0), "Ngtee %d",
897 if (hlen == 0) { /* non-ip */
898 snprintf(SNPARGS(proto, 0), "MAC");
902 char src[48], dst[48];
903 struct icmphdr *icmp;
907 struct ip6_hdr *ip6 = NULL;
908 struct icmp6_hdr *icmp6;
913 if (IS_IP6_FLOW_ID(&(args->f_id))) {
914 char ip6buf[INET6_ADDRSTRLEN];
915 snprintf(src, sizeof(src), "[%s]",
916 ip6_sprintf(ip6buf, &args->f_id.src_ip6));
917 snprintf(dst, sizeof(dst), "[%s]",
918 ip6_sprintf(ip6buf, &args->f_id.dst_ip6));
920 ip6 = (struct ip6_hdr *)ip;
921 tcp = (struct tcphdr *)(((char *)ip) + hlen);
922 udp = (struct udphdr *)(((char *)ip) + hlen);
926 tcp = L3HDR(struct tcphdr, ip);
927 udp = L3HDR(struct udphdr, ip);
929 inet_ntoa_r(ip->ip_src, src);
930 inet_ntoa_r(ip->ip_dst, dst);
933 switch (args->f_id.proto) {
935 len = snprintf(SNPARGS(proto, 0), "TCP %s", src);
937 snprintf(SNPARGS(proto, len), ":%d %s:%d",
938 ntohs(tcp->th_sport),
940 ntohs(tcp->th_dport));
942 snprintf(SNPARGS(proto, len), " %s", dst);
946 len = snprintf(SNPARGS(proto, 0), "UDP %s", src);
948 snprintf(SNPARGS(proto, len), ":%d %s:%d",
949 ntohs(udp->uh_sport),
951 ntohs(udp->uh_dport));
953 snprintf(SNPARGS(proto, len), " %s", dst);
957 icmp = L3HDR(struct icmphdr, ip);
959 len = snprintf(SNPARGS(proto, 0),
961 icmp->icmp_type, icmp->icmp_code);
963 len = snprintf(SNPARGS(proto, 0), "ICMP ");
964 len += snprintf(SNPARGS(proto, len), "%s", src);
965 snprintf(SNPARGS(proto, len), " %s", dst);
969 icmp6 = (struct icmp6_hdr *)(((char *)ip) + hlen);
971 len = snprintf(SNPARGS(proto, 0),
973 icmp6->icmp6_type, icmp6->icmp6_code);
975 len = snprintf(SNPARGS(proto, 0), "ICMPv6 ");
976 len += snprintf(SNPARGS(proto, len), "%s", src);
977 snprintf(SNPARGS(proto, len), " %s", dst);
981 len = snprintf(SNPARGS(proto, 0), "P:%d %s",
982 args->f_id.proto, src);
983 snprintf(SNPARGS(proto, len), " %s", dst);
988 if (IS_IP6_FLOW_ID(&(args->f_id))) {
989 if (offset & (IP6F_OFF_MASK | IP6F_MORE_FRAG))
990 snprintf(SNPARGS(fragment, 0),
991 " (frag %08x:%d@%d%s)",
993 ntohs(ip6->ip6_plen) - hlen,
994 ntohs(offset & IP6F_OFF_MASK) << 3,
995 (offset & IP6F_MORE_FRAG) ? "+" : "");
1000 if (eh != NULL) { /* layer 2 packets are as on the wire */
1001 ip_off = ntohs(ip->ip_off);
1002 ip_len = ntohs(ip->ip_len);
1004 ip_off = ip->ip_off;
1005 ip_len = ip->ip_len;
1007 if (ip_off & (IP_MF | IP_OFFMASK))
1008 snprintf(SNPARGS(fragment, 0),
1009 " (frag %d:%d@%d%s)",
1010 ntohs(ip->ip_id), ip_len - (ip->ip_hl << 2),
1012 (ip_off & IP_MF) ? "+" : "");
1015 if (oif || m->m_pkthdr.rcvif)
1016 log(LOG_SECURITY | LOG_INFO,
1017 "ipfw: %d %s %s %s via %s%s\n",
1018 f ? f->rulenum : -1,
1019 action, proto, oif ? "out" : "in",
1020 oif ? oif->if_xname : m->m_pkthdr.rcvif->if_xname,
1023 log(LOG_SECURITY | LOG_INFO,
1024 "ipfw: %d %s %s [no if info]%s\n",
1025 f ? f->rulenum : -1,
1026 action, proto, fragment);
1028 log(LOG_SECURITY | LOG_NOTICE,
1029 "ipfw: limit %d reached on entry %d\n",
1030 limit_reached, f ? f->rulenum : -1);
1034 * IMPORTANT: the hash function for dynamic rules must be commutative
1035 * in source and destination (ip,port), because rules are bidirectional
1036 * and we want to find both in the same bucket.
1039 hash_packet(struct ipfw_flow_id *id)
1044 if (IS_IP6_FLOW_ID(id))
1045 i = hash_packet6(id);
1048 i = (id->dst_ip) ^ (id->src_ip) ^ (id->dst_port) ^ (id->src_port);
1049 i &= (V_curr_dyn_buckets - 1);
1054 * unlink a dynamic rule from a chain. prev is a pointer to
1055 * the previous one, q is a pointer to the rule to delete,
1056 * head is a pointer to the head of the queue.
1057 * Modifies q and potentially also head.
1059 #define UNLINK_DYN_RULE(prev, head, q) { \
1060 ipfw_dyn_rule *old_q = q; \
1062 /* remove a refcount to the parent */ \
1063 if (q->dyn_type == O_LIMIT) \
1064 q->parent->count--; \
1065 DEB(printf("ipfw: unlink entry 0x%08x %d -> 0x%08x %d, %d left\n",\
1066 (q->id.src_ip), (q->id.src_port), \
1067 (q->id.dst_ip), (q->id.dst_port), V_dyn_count-1 ); ) \
1069 prev->next = q = q->next; \
1071 head = q = q->next; \
1073 uma_zfree(ipfw_dyn_rule_zone, old_q); }
1075 #define TIME_LEQ(a,b) ((int)((a)-(b)) <= 0)
1078 * Remove dynamic rules pointing to "rule", or all of them if rule == NULL.
1080 * If keep_me == NULL, rules are deleted even if not expired,
1081 * otherwise only expired rules are removed.
1083 * The value of the second parameter is also used to point to identify
1084 * a rule we absolutely do not want to remove (e.g. because we are
1085 * holding a reference to it -- this is the case with O_LIMIT_PARENT
1086 * rules). The pointer is only used for comparison, so any non-null
1090 remove_dyn_rule(struct ip_fw *rule, ipfw_dyn_rule *keep_me)
1092 static u_int32_t last_remove = 0;
1094 #define FORCE (keep_me == NULL)
1096 ipfw_dyn_rule *prev, *q;
1097 int i, pass = 0, max_pass = 0;
1099 IPFW_DYN_LOCK_ASSERT();
1101 if (V_ipfw_dyn_v == NULL || V_dyn_count == 0)
1103 /* do not expire more than once per second, it is useless */
1104 if (!FORCE && last_remove == time_uptime)
1106 last_remove = time_uptime;
1109 * because O_LIMIT refer to parent rules, during the first pass only
1110 * remove child and mark any pending LIMIT_PARENT, and remove
1111 * them in a second pass.
1114 for (i = 0 ; i < V_curr_dyn_buckets ; i++) {
1115 for (prev=NULL, q = V_ipfw_dyn_v[i] ; q ; ) {
1117 * Logic can become complex here, so we split tests.
1121 if (rule != NULL && rule != q->rule)
1122 goto next; /* not the one we are looking for */
1123 if (q->dyn_type == O_LIMIT_PARENT) {
1125 * handle parent in the second pass,
1126 * record we need one.
1131 if (FORCE && q->count != 0 ) {
1132 /* XXX should not happen! */
1133 printf("ipfw: OUCH! cannot remove rule,"
1134 " count %d\n", q->count);
1138 !TIME_LEQ( q->expire, time_uptime ))
1141 if (q->dyn_type != O_LIMIT_PARENT || !q->count) {
1142 UNLINK_DYN_RULE(prev, V_ipfw_dyn_v[i], q);
1150 if (pass++ < max_pass)
1156 * lookup a dynamic rule.
1158 static ipfw_dyn_rule *
1159 lookup_dyn_rule_locked(struct ipfw_flow_id *pkt, int *match_direction,
1163 * stateful ipfw extensions.
1164 * Lookup into dynamic session queue
1166 #define MATCH_REVERSE 0
1167 #define MATCH_FORWARD 1
1168 #define MATCH_NONE 2
1169 #define MATCH_UNKNOWN 3
1170 int i, dir = MATCH_NONE;
1171 ipfw_dyn_rule *prev, *q=NULL;
1173 IPFW_DYN_LOCK_ASSERT();
1175 if (V_ipfw_dyn_v == NULL)
1176 goto done; /* not found */
1177 i = hash_packet( pkt );
1178 for (prev=NULL, q = V_ipfw_dyn_v[i] ; q != NULL ; ) {
1179 if (q->dyn_type == O_LIMIT_PARENT && q->count)
1181 if (TIME_LEQ( q->expire, time_uptime)) { /* expire entry */
1182 UNLINK_DYN_RULE(prev, V_ipfw_dyn_v[i], q);
1185 if (pkt->proto == q->id.proto &&
1186 q->dyn_type != O_LIMIT_PARENT) {
1187 if (IS_IP6_FLOW_ID(pkt)) {
1188 if (IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
1189 &(q->id.src_ip6)) &&
1190 IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
1191 &(q->id.dst_ip6)) &&
1192 pkt->src_port == q->id.src_port &&
1193 pkt->dst_port == q->id.dst_port ) {
1194 dir = MATCH_FORWARD;
1197 if (IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
1198 &(q->id.dst_ip6)) &&
1199 IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
1200 &(q->id.src_ip6)) &&
1201 pkt->src_port == q->id.dst_port &&
1202 pkt->dst_port == q->id.src_port ) {
1203 dir = MATCH_REVERSE;
1207 if (pkt->src_ip == q->id.src_ip &&
1208 pkt->dst_ip == q->id.dst_ip &&
1209 pkt->src_port == q->id.src_port &&
1210 pkt->dst_port == q->id.dst_port ) {
1211 dir = MATCH_FORWARD;
1214 if (pkt->src_ip == q->id.dst_ip &&
1215 pkt->dst_ip == q->id.src_ip &&
1216 pkt->src_port == q->id.dst_port &&
1217 pkt->dst_port == q->id.src_port ) {
1218 dir = MATCH_REVERSE;
1228 goto done; /* q = NULL, not found */
1230 if ( prev != NULL) { /* found and not in front */
1231 prev->next = q->next;
1232 q->next = V_ipfw_dyn_v[i];
1233 V_ipfw_dyn_v[i] = q;
1235 if (pkt->proto == IPPROTO_TCP) { /* update state according to flags */
1236 u_char flags = pkt->flags & (TH_FIN|TH_SYN|TH_RST);
1238 #define BOTH_SYN (TH_SYN | (TH_SYN << 8))
1239 #define BOTH_FIN (TH_FIN | (TH_FIN << 8))
1240 q->state |= (dir == MATCH_FORWARD ) ? flags : (flags << 8);
1242 case TH_SYN: /* opening */
1243 q->expire = time_uptime + V_dyn_syn_lifetime;
1246 case BOTH_SYN: /* move to established */
1247 case BOTH_SYN | TH_FIN : /* one side tries to close */
1248 case BOTH_SYN | (TH_FIN << 8) :
1250 #define _SEQ_GE(a,b) ((int)(a) - (int)(b) >= 0)
1251 u_int32_t ack = ntohl(tcp->th_ack);
1252 if (dir == MATCH_FORWARD) {
1253 if (q->ack_fwd == 0 || _SEQ_GE(ack, q->ack_fwd))
1255 else { /* ignore out-of-sequence */
1259 if (q->ack_rev == 0 || _SEQ_GE(ack, q->ack_rev))
1261 else { /* ignore out-of-sequence */
1266 q->expire = time_uptime + V_dyn_ack_lifetime;
1269 case BOTH_SYN | BOTH_FIN: /* both sides closed */
1270 if (V_dyn_fin_lifetime >= V_dyn_keepalive_period)
1271 V_dyn_fin_lifetime = V_dyn_keepalive_period - 1;
1272 q->expire = time_uptime + V_dyn_fin_lifetime;
1278 * reset or some invalid combination, but can also
1279 * occur if we use keep-state the wrong way.
1281 if ( (q->state & ((TH_RST << 8)|TH_RST)) == 0)
1282 printf("invalid state: 0x%x\n", q->state);
1284 if (V_dyn_rst_lifetime >= V_dyn_keepalive_period)
1285 V_dyn_rst_lifetime = V_dyn_keepalive_period - 1;
1286 q->expire = time_uptime + V_dyn_rst_lifetime;
1289 } else if (pkt->proto == IPPROTO_UDP) {
1290 q->expire = time_uptime + V_dyn_udp_lifetime;
1292 /* other protocols */
1293 q->expire = time_uptime + V_dyn_short_lifetime;
1296 if (match_direction)
1297 *match_direction = dir;
1301 static ipfw_dyn_rule *
1302 lookup_dyn_rule(struct ipfw_flow_id *pkt, int *match_direction,
1308 q = lookup_dyn_rule_locked(pkt, match_direction, tcp);
1311 /* NB: return table locked when q is not NULL */
1316 realloc_dynamic_table(void)
1318 IPFW_DYN_LOCK_ASSERT();
1321 * Try reallocation, make sure we have a power of 2 and do
1322 * not allow more than 64k entries. In case of overflow,
1326 if (V_dyn_buckets > 65536)
1327 V_dyn_buckets = 1024;
1328 if ((V_dyn_buckets & (V_dyn_buckets-1)) != 0) { /* not a power of 2 */
1329 V_dyn_buckets = V_curr_dyn_buckets; /* reset */
1332 V_curr_dyn_buckets = V_dyn_buckets;
1333 if (V_ipfw_dyn_v != NULL)
1334 free(V_ipfw_dyn_v, M_IPFW);
1336 V_ipfw_dyn_v = malloc(V_curr_dyn_buckets * sizeof(ipfw_dyn_rule *),
1337 M_IPFW, M_NOWAIT | M_ZERO);
1338 if (V_ipfw_dyn_v != NULL || V_curr_dyn_buckets <= 2)
1340 V_curr_dyn_buckets /= 2;
1345 * Install state of type 'type' for a dynamic session.
1346 * The hash table contains two type of rules:
1347 * - regular rules (O_KEEP_STATE)
1348 * - rules for sessions with limited number of sess per user
1349 * (O_LIMIT). When they are created, the parent is
1350 * increased by 1, and decreased on delete. In this case,
1351 * the third parameter is the parent rule and not the chain.
1352 * - "parent" rules for the above (O_LIMIT_PARENT).
1354 static ipfw_dyn_rule *
1355 add_dyn_rule(struct ipfw_flow_id *id, u_int8_t dyn_type, struct ip_fw *rule)
1360 IPFW_DYN_LOCK_ASSERT();
1362 if (V_ipfw_dyn_v == NULL ||
1363 (V_dyn_count == 0 && V_dyn_buckets != V_curr_dyn_buckets)) {
1364 realloc_dynamic_table();
1365 if (V_ipfw_dyn_v == NULL)
1366 return NULL; /* failed ! */
1368 i = hash_packet(id);
1370 r = uma_zalloc(ipfw_dyn_rule_zone, M_NOWAIT | M_ZERO);
1372 printf ("ipfw: sorry cannot allocate state\n");
1376 /* increase refcount on parent, and set pointer */
1377 if (dyn_type == O_LIMIT) {
1378 ipfw_dyn_rule *parent = (ipfw_dyn_rule *)rule;
1379 if ( parent->dyn_type != O_LIMIT_PARENT)
1380 panic("invalid parent");
1383 rule = parent->rule;
1387 r->expire = time_uptime + V_dyn_syn_lifetime;
1389 r->dyn_type = dyn_type;
1390 r->pcnt = r->bcnt = 0;
1394 r->next = V_ipfw_dyn_v[i];
1395 V_ipfw_dyn_v[i] = r;
1397 DEB(printf("ipfw: add dyn entry ty %d 0x%08x %d -> 0x%08x %d, total %d\n",
1399 (r->id.src_ip), (r->id.src_port),
1400 (r->id.dst_ip), (r->id.dst_port),
1406 * lookup dynamic parent rule using pkt and rule as search keys.
1407 * If the lookup fails, then install one.
1409 static ipfw_dyn_rule *
1410 lookup_dyn_parent(struct ipfw_flow_id *pkt, struct ip_fw *rule)
1415 IPFW_DYN_LOCK_ASSERT();
1418 int is_v6 = IS_IP6_FLOW_ID(pkt);
1419 i = hash_packet( pkt );
1420 for (q = V_ipfw_dyn_v[i] ; q != NULL ; q=q->next)
1421 if (q->dyn_type == O_LIMIT_PARENT &&
1423 pkt->proto == q->id.proto &&
1424 pkt->src_port == q->id.src_port &&
1425 pkt->dst_port == q->id.dst_port &&
1428 IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
1429 &(q->id.src_ip6)) &&
1430 IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
1431 &(q->id.dst_ip6))) ||
1433 pkt->src_ip == q->id.src_ip &&
1434 pkt->dst_ip == q->id.dst_ip)
1437 q->expire = time_uptime + V_dyn_short_lifetime;
1438 DEB(printf("ipfw: lookup_dyn_parent found 0x%p\n",q);)
1442 return add_dyn_rule(pkt, O_LIMIT_PARENT, rule);
1446 * Install dynamic state for rule type cmd->o.opcode
1448 * Returns 1 (failure) if state is not installed because of errors or because
1449 * session limitations are enforced.
1452 install_state(struct ip_fw *rule, ipfw_insn_limit *cmd,
1453 struct ip_fw_args *args, uint32_t tablearg)
1455 static int last_log;
1458 char src[48], dst[48];
1464 printf("ipfw: %s: type %d 0x%08x %u -> 0x%08x %u\n",
1465 __func__, cmd->o.opcode,
1466 (args->f_id.src_ip), (args->f_id.src_port),
1467 (args->f_id.dst_ip), (args->f_id.dst_port));
1472 q = lookup_dyn_rule_locked(&args->f_id, NULL, NULL);
1474 if (q != NULL) { /* should never occur */
1475 if (last_log != time_uptime) {
1476 last_log = time_uptime;
1477 printf("ipfw: %s: entry already present, done\n",
1484 if (V_dyn_count >= V_dyn_max)
1485 /* Run out of slots, try to remove any expired rule. */
1486 remove_dyn_rule(NULL, (ipfw_dyn_rule *)1);
1488 if (V_dyn_count >= V_dyn_max) {
1489 if (last_log != time_uptime) {
1490 last_log = time_uptime;
1491 printf("ipfw: %s: Too many dynamic rules\n", __func__);
1494 return (1); /* cannot install, notify caller */
1497 switch (cmd->o.opcode) {
1498 case O_KEEP_STATE: /* bidir rule */
1499 add_dyn_rule(&args->f_id, O_KEEP_STATE, rule);
1502 case O_LIMIT: { /* limit number of sessions */
1503 struct ipfw_flow_id id;
1504 ipfw_dyn_rule *parent;
1505 uint32_t conn_limit;
1506 uint16_t limit_mask = cmd->limit_mask;
1508 conn_limit = (cmd->conn_limit == IP_FW_TABLEARG) ?
1509 tablearg : cmd->conn_limit;
1512 if (cmd->conn_limit == IP_FW_TABLEARG)
1513 printf("ipfw: %s: O_LIMIT rule, conn_limit: %u "
1514 "(tablearg)\n", __func__, conn_limit);
1516 printf("ipfw: %s: O_LIMIT rule, conn_limit: %u\n",
1517 __func__, conn_limit);
1520 id.dst_ip = id.src_ip = id.dst_port = id.src_port = 0;
1521 id.proto = args->f_id.proto;
1522 id.addr_type = args->f_id.addr_type;
1523 id.fib = M_GETFIB(args->m);
1525 if (IS_IP6_FLOW_ID (&(args->f_id))) {
1526 if (limit_mask & DYN_SRC_ADDR)
1527 id.src_ip6 = args->f_id.src_ip6;
1528 if (limit_mask & DYN_DST_ADDR)
1529 id.dst_ip6 = args->f_id.dst_ip6;
1531 if (limit_mask & DYN_SRC_ADDR)
1532 id.src_ip = args->f_id.src_ip;
1533 if (limit_mask & DYN_DST_ADDR)
1534 id.dst_ip = args->f_id.dst_ip;
1536 if (limit_mask & DYN_SRC_PORT)
1537 id.src_port = args->f_id.src_port;
1538 if (limit_mask & DYN_DST_PORT)
1539 id.dst_port = args->f_id.dst_port;
1540 if ((parent = lookup_dyn_parent(&id, rule)) == NULL) {
1541 printf("ipfw: %s: add parent failed\n", __func__);
1546 if (parent->count >= conn_limit) {
1547 /* See if we can remove some expired rule. */
1548 remove_dyn_rule(rule, parent);
1549 if (parent->count >= conn_limit) {
1550 if (V_fw_verbose && last_log != time_uptime) {
1551 last_log = time_uptime;
1554 * XXX IPv6 flows are not
1557 if (IS_IP6_FLOW_ID(&(args->f_id))) {
1558 char ip6buf[INET6_ADDRSTRLEN];
1559 snprintf(src, sizeof(src),
1560 "[%s]", ip6_sprintf(ip6buf,
1561 &args->f_id.src_ip6));
1562 snprintf(dst, sizeof(dst),
1563 "[%s]", ip6_sprintf(ip6buf,
1564 &args->f_id.dst_ip6));
1569 htonl(args->f_id.src_ip);
1570 inet_ntoa_r(da, src);
1572 htonl(args->f_id.dst_ip);
1573 inet_ntoa_r(da, dst);
1575 log(LOG_SECURITY | LOG_DEBUG,
1576 "ipfw: %d %s %s:%u -> %s:%u, %s\n",
1577 parent->rule->rulenum,
1579 src, (args->f_id.src_port),
1580 dst, (args->f_id.dst_port),
1581 "too many entries");
1587 add_dyn_rule(&args->f_id, O_LIMIT, (struct ip_fw *)parent);
1591 printf("ipfw: %s: unknown dynamic rule type %u\n",
1592 __func__, cmd->o.opcode);
1597 /* XXX just set lifetime */
1598 lookup_dyn_rule_locked(&args->f_id, NULL, NULL);
1605 * Generate a TCP packet, containing either a RST or a keepalive.
1606 * When flags & TH_RST, we are sending a RST packet, because of a
1607 * "reset" action matched the packet.
1608 * Otherwise we are sending a keepalive, and flags & TH_
1609 * The 'replyto' mbuf is the mbuf being replied to, if any, and is required
1610 * so that MAC can label the reply appropriately.
1612 static struct mbuf *
1613 send_pkt(struct mbuf *replyto, struct ipfw_flow_id *id, u_int32_t seq,
1614 u_int32_t ack, int flags)
1618 struct ip *h = NULL; /* stupid compiler */
1620 struct ip6_hdr *h6 = NULL;
1622 struct tcphdr *th = NULL;
1624 MGETHDR(m, M_DONTWAIT, MT_DATA);
1628 M_SETFIB(m, id->fib);
1630 if (replyto != NULL)
1631 mac_netinet_firewall_reply(replyto, m);
1633 mac_netinet_firewall_send(m);
1635 (void)replyto; /* don't warn about unused arg */
1638 switch (id->addr_type) {
1640 len = sizeof(struct ip) + sizeof(struct tcphdr);
1644 len = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
1648 /* XXX: log me?!? */
1652 dir = ((flags & (TH_SYN | TH_RST)) == TH_SYN);
1654 m->m_data += max_linkhdr;
1655 m->m_flags |= M_SKIP_FIREWALL;
1656 m->m_pkthdr.len = m->m_len = len;
1657 m->m_pkthdr.rcvif = NULL;
1658 bzero(m->m_data, len);
1660 switch (id->addr_type) {
1662 h = mtod(m, struct ip *);
1664 /* prepare for checksum */
1665 h->ip_p = IPPROTO_TCP;
1666 h->ip_len = htons(sizeof(struct tcphdr));
1668 h->ip_src.s_addr = htonl(id->src_ip);
1669 h->ip_dst.s_addr = htonl(id->dst_ip);
1671 h->ip_src.s_addr = htonl(id->dst_ip);
1672 h->ip_dst.s_addr = htonl(id->src_ip);
1675 th = (struct tcphdr *)(h + 1);
1679 h6 = mtod(m, struct ip6_hdr *);
1681 /* prepare for checksum */
1682 h6->ip6_nxt = IPPROTO_TCP;
1683 h6->ip6_plen = htons(sizeof(struct tcphdr));
1685 h6->ip6_src = id->src_ip6;
1686 h6->ip6_dst = id->dst_ip6;
1688 h6->ip6_src = id->dst_ip6;
1689 h6->ip6_dst = id->src_ip6;
1692 th = (struct tcphdr *)(h6 + 1);
1698 th->th_sport = htons(id->src_port);
1699 th->th_dport = htons(id->dst_port);
1701 th->th_sport = htons(id->dst_port);
1702 th->th_dport = htons(id->src_port);
1704 th->th_off = sizeof(struct tcphdr) >> 2;
1706 if (flags & TH_RST) {
1707 if (flags & TH_ACK) {
1708 th->th_seq = htonl(ack);
1709 th->th_flags = TH_RST;
1713 th->th_ack = htonl(seq);
1714 th->th_flags = TH_RST | TH_ACK;
1718 * Keepalive - use caller provided sequence numbers
1720 th->th_seq = htonl(seq);
1721 th->th_ack = htonl(ack);
1722 th->th_flags = TH_ACK;
1725 switch (id->addr_type) {
1727 th->th_sum = in_cksum(m, len);
1729 /* finish the ip header */
1731 h->ip_hl = sizeof(*h) >> 2;
1732 h->ip_tos = IPTOS_LOWDELAY;
1735 h->ip_ttl = V_ip_defttl;
1740 th->th_sum = in6_cksum(m, IPPROTO_TCP, sizeof(*h6),
1741 sizeof(struct tcphdr));
1743 /* finish the ip6 header */
1744 h6->ip6_vfc |= IPV6_VERSION;
1745 h6->ip6_hlim = IPV6_DEFHLIM;
1754 * sends a reject message, consuming the mbuf passed as an argument.
1757 send_reject(struct ip_fw_args *args, int code, int ip_len, struct ip *ip)
1761 /* XXX When ip is not guaranteed to be at mtod() we will
1762 * need to account for this */
1763 * The mbuf will however be thrown away so we can adjust it.
1764 * Remember we did an m_pullup on it already so we
1765 * can make some assumptions about contiguousness.
1768 m_adj(m, args->L3offset);
1770 if (code != ICMP_REJECT_RST) { /* Send an ICMP unreach */
1771 /* We need the IP header in host order for icmp_error(). */
1772 if (args->eh != NULL) {
1773 ip->ip_len = ntohs(ip->ip_len);
1774 ip->ip_off = ntohs(ip->ip_off);
1776 icmp_error(args->m, ICMP_UNREACH, code, 0L, 0);
1777 } else if (args->f_id.proto == IPPROTO_TCP) {
1778 struct tcphdr *const tcp =
1779 L3HDR(struct tcphdr, mtod(args->m, struct ip *));
1780 if ( (tcp->th_flags & TH_RST) == 0) {
1782 m = send_pkt(args->m, &(args->f_id),
1783 ntohl(tcp->th_seq), ntohl(tcp->th_ack),
1784 tcp->th_flags | TH_RST);
1786 ip_output(m, NULL, NULL, 0, NULL, NULL);
1796 * Given an ip_fw *, lookup_next_rule will return a pointer
1797 * to the next rule, which can be either the jump
1798 * target (for skipto instructions) or the next one in the list (in
1799 * all other cases including a missing jump target).
1800 * The result is also written in the "next_rule" field of the rule.
1801 * Backward jumps are not allowed, so start looking from the next
1804 * This never returns NULL -- in case we do not have an exact match,
1805 * the next rule is returned. When the ruleset is changed,
1806 * pointers are flushed so we are always correct.
1809 static struct ip_fw *
1810 lookup_next_rule(struct ip_fw *me, u_int32_t tablearg)
1812 struct ip_fw *rule = NULL;
1816 /* look for action, in case it is a skipto */
1817 cmd = ACTION_PTR(me);
1818 if (cmd->opcode == O_LOG)
1820 if (cmd->opcode == O_ALTQ)
1822 if (cmd->opcode == O_TAG)
1824 if (cmd->opcode == O_SKIPTO ) {
1825 if (tablearg != 0) {
1826 rulenum = (u_int16_t)tablearg;
1828 rulenum = cmd->arg1;
1830 for (rule = me->next; rule ; rule = rule->next) {
1831 if (rule->rulenum >= rulenum) {
1836 if (rule == NULL) /* failure or not a skipto */
1838 me->next_rule = rule;
1843 add_table_entry(struct ip_fw_chain *ch, uint16_t tbl, in_addr_t addr,
1844 uint8_t mlen, uint32_t value)
1846 struct radix_node_head *rnh;
1847 struct table_entry *ent;
1848 struct radix_node *rn;
1850 if (tbl >= IPFW_TABLES_MAX)
1852 rnh = ch->tables[tbl];
1853 ent = malloc(sizeof(*ent), M_IPFW_TBL, M_NOWAIT | M_ZERO);
1857 ent->addr.sin_len = ent->mask.sin_len = 8;
1858 ent->mask.sin_addr.s_addr = htonl(mlen ? ~((1 << (32 - mlen)) - 1) : 0);
1859 ent->addr.sin_addr.s_addr = addr & ent->mask.sin_addr.s_addr;
1861 rn = rnh->rnh_addaddr(&ent->addr, &ent->mask, rnh, (void *)ent);
1864 free(ent, M_IPFW_TBL);
1872 del_table_entry(struct ip_fw_chain *ch, uint16_t tbl, in_addr_t addr,
1875 struct radix_node_head *rnh;
1876 struct table_entry *ent;
1877 struct sockaddr_in sa, mask;
1879 if (tbl >= IPFW_TABLES_MAX)
1881 rnh = ch->tables[tbl];
1882 sa.sin_len = mask.sin_len = 8;
1883 mask.sin_addr.s_addr = htonl(mlen ? ~((1 << (32 - mlen)) - 1) : 0);
1884 sa.sin_addr.s_addr = addr & mask.sin_addr.s_addr;
1886 ent = (struct table_entry *)rnh->rnh_deladdr(&sa, &mask, rnh);
1892 free(ent, M_IPFW_TBL);
1897 flush_table_entry(struct radix_node *rn, void *arg)
1899 struct radix_node_head * const rnh = arg;
1900 struct table_entry *ent;
1902 ent = (struct table_entry *)
1903 rnh->rnh_deladdr(rn->rn_key, rn->rn_mask, rnh);
1905 free(ent, M_IPFW_TBL);
1910 flush_table(struct ip_fw_chain *ch, uint16_t tbl)
1912 struct radix_node_head *rnh;
1914 IPFW_WLOCK_ASSERT(ch);
1916 if (tbl >= IPFW_TABLES_MAX)
1918 rnh = ch->tables[tbl];
1919 KASSERT(rnh != NULL, ("NULL IPFW table"));
1920 rnh->rnh_walktree(rnh, flush_table_entry, rnh);
1925 flush_tables(struct ip_fw_chain *ch)
1929 IPFW_WLOCK_ASSERT(ch);
1931 for (tbl = 0; tbl < IPFW_TABLES_MAX; tbl++)
1932 flush_table(ch, tbl);
1936 init_tables(struct ip_fw_chain *ch)
1941 for (i = 0; i < IPFW_TABLES_MAX; i++) {
1942 if (!rn_inithead((void **)&ch->tables[i], 32)) {
1943 for (j = 0; j < i; j++) {
1944 (void) flush_table(ch, j);
1953 lookup_table(struct ip_fw_chain *ch, uint16_t tbl, in_addr_t addr,
1956 struct radix_node_head *rnh;
1957 struct table_entry *ent;
1958 struct sockaddr_in sa;
1960 if (tbl >= IPFW_TABLES_MAX)
1962 rnh = ch->tables[tbl];
1964 sa.sin_addr.s_addr = addr;
1965 ent = (struct table_entry *)(rnh->rnh_lookup(&sa, NULL, rnh));
1974 count_table_entry(struct radix_node *rn, void *arg)
1976 u_int32_t * const cnt = arg;
1983 count_table(struct ip_fw_chain *ch, uint32_t tbl, uint32_t *cnt)
1985 struct radix_node_head *rnh;
1987 if (tbl >= IPFW_TABLES_MAX)
1989 rnh = ch->tables[tbl];
1991 rnh->rnh_walktree(rnh, count_table_entry, cnt);
1996 dump_table_entry(struct radix_node *rn, void *arg)
1998 struct table_entry * const n = (struct table_entry *)rn;
1999 ipfw_table * const tbl = arg;
2000 ipfw_table_entry *ent;
2002 if (tbl->cnt == tbl->size)
2004 ent = &tbl->ent[tbl->cnt];
2005 ent->tbl = tbl->tbl;
2006 if (in_nullhost(n->mask.sin_addr))
2009 ent->masklen = 33 - ffs(ntohl(n->mask.sin_addr.s_addr));
2010 ent->addr = n->addr.sin_addr.s_addr;
2011 ent->value = n->value;
2017 dump_table(struct ip_fw_chain *ch, ipfw_table *tbl)
2019 struct radix_node_head *rnh;
2021 if (tbl->tbl >= IPFW_TABLES_MAX)
2023 rnh = ch->tables[tbl->tbl];
2025 rnh->rnh_walktree(rnh, dump_table_entry, tbl);
2030 check_uidgid(ipfw_insn_u32 *insn, int proto, struct ifnet *oif,
2031 struct in_addr dst_ip, u_int16_t dst_port, struct in_addr src_ip,
2032 u_int16_t src_port, struct ucred **uc, int *ugid_lookupp,
2035 struct inpcbinfo *pi;
2041 * Check to see if the UDP or TCP stack supplied us with
2042 * the PCB. If so, rather then holding a lock and looking
2043 * up the PCB, we can use the one that was supplied.
2045 if (inp && *ugid_lookupp == 0) {
2046 INP_LOCK_ASSERT(inp);
2047 if (inp->inp_socket != NULL) {
2048 *uc = crhold(inp->inp_cred);
2054 * If we have already been here and the packet has no
2055 * PCB entry associated with it, then we can safely
2056 * assume that this is a no match.
2058 if (*ugid_lookupp == -1)
2060 if (proto == IPPROTO_TCP) {
2063 } else if (proto == IPPROTO_UDP) {
2064 wildcard = INPLOOKUP_WILDCARD;
2069 if (*ugid_lookupp == 0) {
2072 in_pcblookup_hash(pi,
2073 dst_ip, htons(dst_port),
2074 src_ip, htons(src_port),
2076 in_pcblookup_hash(pi,
2077 src_ip, htons(src_port),
2078 dst_ip, htons(dst_port),
2081 *uc = crhold(pcb->inp_cred);
2084 INP_INFO_RUNLOCK(pi);
2085 if (*ugid_lookupp == 0) {
2087 * If the lookup did not yield any results, there
2088 * is no sense in coming back and trying again. So
2089 * we can set lookup to -1 and ensure that we wont
2090 * bother the pcb system again.
2096 if (insn->o.opcode == O_UID)
2097 match = ((*uc)->cr_uid == (uid_t)insn->d[0]);
2098 else if (insn->o.opcode == O_GID)
2099 match = groupmember((gid_t)insn->d[0], *uc);
2100 else if (insn->o.opcode == O_JAIL)
2101 match = ((*uc)->cr_prison->pr_id == (int)insn->d[0]);
2106 * The main check routine for the firewall.
2108 * All arguments are in args so we can modify them and return them
2109 * back to the caller.
2113 * args->m (in/out) The packet; we set to NULL when/if we nuke it.
2114 * Starts with the IP header.
2115 * args->eh (in) Mac header if present, or NULL for layer3 packet.
2116 * args->L3offset Number of bytes bypassed if we came from L2.
2117 * e.g. often sizeof(eh) ** NOTYET **
2118 * args->oif Outgoing interface, or NULL if packet is incoming.
2119 * The incoming interface is in the mbuf. (in)
2120 * args->divert_rule (in/out)
2121 * Skip up to the first rule past this rule number;
2122 * upon return, non-zero port number for divert or tee.
2124 * args->rule Pointer to the last matching rule (in/out)
2125 * args->next_hop Socket we are forwarding to (out).
2126 * args->f_id Addresses grabbed from the packet (out)
2127 * args->cookie a cookie depending on rule action
2131 * IP_FW_PASS the packet must be accepted
2132 * IP_FW_DENY the packet must be dropped
2133 * IP_FW_DIVERT divert packet, port in m_tag
2134 * IP_FW_TEE tee packet, port in m_tag
2135 * IP_FW_DUMMYNET to dummynet, pipe in args->cookie
2136 * IP_FW_NETGRAPH into netgraph, cookie args->cookie
2140 ipfw_chk(struct ip_fw_args *args)
2144 * Local variables holding state during the processing of a packet:
2146 * IMPORTANT NOTE: to speed up the processing of rules, there
2147 * are some assumption on the values of the variables, which
2148 * are documented here. Should you change them, please check
2149 * the implementation of the various instructions to make sure
2150 * that they still work.
2152 * args->eh The MAC header. It is non-null for a layer2
2153 * packet, it is NULL for a layer-3 packet.
2155 * args->L3offset Offset in the packet to the L3 (IP or equiv.) header.
2157 * m | args->m Pointer to the mbuf, as received from the caller.
2158 * It may change if ipfw_chk() does an m_pullup, or if it
2159 * consumes the packet because it calls send_reject().
2160 * XXX This has to change, so that ipfw_chk() never modifies
2161 * or consumes the buffer.
2162 * ip is the beginning of the ip(4 or 6) header.
2163 * Calculated by adding the L3offset to the start of data.
2164 * (Until we start using L3offset, the packet is
2165 * supposed to start with the ip header).
2167 struct mbuf *m = args->m;
2168 struct ip *ip = mtod(m, struct ip *);
2171 * For rules which contain uid/gid or jail constraints, cache
2172 * a copy of the users credentials after the pcb lookup has been
2173 * executed. This will speed up the processing of rules with
2174 * these types of constraints, as well as decrease contention
2175 * on pcb related locks.
2177 struct ucred *ucred_cache = NULL;
2178 int ucred_lookup = 0;
2181 * divinput_flags If non-zero, set to the IP_FW_DIVERT_*_FLAG
2182 * associated with a packet input on a divert socket. This
2183 * will allow to distinguish traffic and its direction when
2184 * it originates from a divert socket.
2186 u_int divinput_flags = 0;
2189 * oif | args->oif If NULL, ipfw_chk has been called on the
2190 * inbound path (ether_input, ip_input).
2191 * If non-NULL, ipfw_chk has been called on the outbound path
2192 * (ether_output, ip_output).
2194 struct ifnet *oif = args->oif;
2196 struct ip_fw *f = NULL; /* matching rule */
2200 * hlen The length of the IP header.
2202 u_int hlen = 0; /* hlen >0 means we have an IP pkt */
2205 * offset The offset of a fragment. offset != 0 means that
2206 * we have a fragment at this offset of an IPv4 packet.
2207 * offset == 0 means that (if this is an IPv4 packet)
2208 * this is the first or only fragment.
2209 * For IPv6 offset == 0 means there is no Fragment Header.
2210 * If offset != 0 for IPv6 always use correct mask to
2211 * get the correct offset because we add IP6F_MORE_FRAG
2212 * to be able to dectect the first fragment which would
2213 * otherwise have offset = 0.
2218 * Local copies of addresses. They are only valid if we have
2221 * proto The protocol. Set to 0 for non-ip packets,
2222 * or to the protocol read from the packet otherwise.
2223 * proto != 0 means that we have an IPv4 packet.
2225 * src_port, dst_port port numbers, in HOST format. Only
2226 * valid for TCP and UDP packets.
2228 * src_ip, dst_ip ip addresses, in NETWORK format.
2229 * Only valid for IPv4 packets.
2232 u_int16_t src_port = 0, dst_port = 0; /* NOTE: host format */
2233 struct in_addr src_ip, dst_ip; /* NOTE: network format */
2236 u_int16_t etype = 0; /* Host order stored ether type */
2239 * dyn_dir = MATCH_UNKNOWN when rules unchecked,
2240 * MATCH_NONE when checked and not matched (q = NULL),
2241 * MATCH_FORWARD or MATCH_REVERSE otherwise (q != NULL)
2243 int dyn_dir = MATCH_UNKNOWN;
2244 ipfw_dyn_rule *q = NULL;
2245 struct ip_fw_chain *chain = &V_layer3_chain;
2249 * We store in ulp a pointer to the upper layer protocol header.
2250 * In the ipv4 case this is easy to determine from the header,
2251 * but for ipv6 we might have some additional headers in the middle.
2252 * ulp is NULL if not found.
2254 void *ulp = NULL; /* upper layer protocol pointer. */
2255 /* XXX ipv6 variables */
2257 u_int16_t ext_hd = 0; /* bits vector for extension header filtering */
2258 /* end of ipv6 variables */
2261 if (m->m_flags & M_SKIP_FIREWALL || (! V_ipfw_vnet_ready))
2262 return (IP_FW_PASS); /* accept */
2264 dst_ip.s_addr = 0; /* make sure it is initialized */
2265 src_ip.s_addr = 0; /* make sure it is initialized */
2266 pktlen = m->m_pkthdr.len;
2267 args->f_id.fib = M_GETFIB(m); /* note mbuf not altered) */
2268 proto = args->f_id.proto = 0; /* mark f_id invalid */
2269 /* XXX 0 is a valid proto: IP/IPv6 Hop-by-Hop Option */
2272 * PULLUP_TO(len, p, T) makes sure that len + sizeof(T) is contiguous,
2273 * then it sets p to point at the offset "len" in the mbuf. WARNING: the
2274 * pointer might become stale after other pullups (but we never use it
2277 #define PULLUP_TO(_len, p, T) \
2279 int x = (_len) + sizeof(T); \
2280 if ((m)->m_len < x) { \
2281 args->m = m = m_pullup(m, x); \
2283 goto pullup_failed; \
2285 p = (mtod(m, char *) + (_len)); \
2289 * if we have an ether header,
2292 etype = ntohs(args->eh->ether_type);
2294 /* Identify IP packets and fill up variables. */
2295 if (pktlen >= sizeof(struct ip6_hdr) &&
2296 (args->eh == NULL || etype == ETHERTYPE_IPV6) && ip->ip_v == 6) {
2297 struct ip6_hdr *ip6 = (struct ip6_hdr *)ip;
2299 args->f_id.addr_type = 6;
2300 hlen = sizeof(struct ip6_hdr);
2301 proto = ip6->ip6_nxt;
2303 /* Search extension headers to find upper layer protocols */
2304 while (ulp == NULL) {
2306 case IPPROTO_ICMPV6:
2307 PULLUP_TO(hlen, ulp, struct icmp6_hdr);
2308 args->f_id.flags = ICMP6(ulp)->icmp6_type;
2312 PULLUP_TO(hlen, ulp, struct tcphdr);
2313 dst_port = TCP(ulp)->th_dport;
2314 src_port = TCP(ulp)->th_sport;
2315 args->f_id.flags = TCP(ulp)->th_flags;
2319 PULLUP_TO(hlen, ulp, struct sctphdr);
2320 src_port = SCTP(ulp)->src_port;
2321 dst_port = SCTP(ulp)->dest_port;
2325 PULLUP_TO(hlen, ulp, struct udphdr);
2326 dst_port = UDP(ulp)->uh_dport;
2327 src_port = UDP(ulp)->uh_sport;
2330 case IPPROTO_HOPOPTS: /* RFC 2460 */
2331 PULLUP_TO(hlen, ulp, struct ip6_hbh);
2332 ext_hd |= EXT_HOPOPTS;
2333 hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3;
2334 proto = ((struct ip6_hbh *)ulp)->ip6h_nxt;
2338 case IPPROTO_ROUTING: /* RFC 2460 */
2339 PULLUP_TO(hlen, ulp, struct ip6_rthdr);
2340 switch (((struct ip6_rthdr *)ulp)->ip6r_type) {
2342 ext_hd |= EXT_RTHDR0;
2345 ext_hd |= EXT_RTHDR2;
2348 printf("IPFW2: IPV6 - Unknown Routing "
2349 "Header type(%d)\n",
2350 ((struct ip6_rthdr *)ulp)->ip6r_type);
2351 if (V_fw_deny_unknown_exthdrs)
2352 return (IP_FW_DENY);
2355 ext_hd |= EXT_ROUTING;
2356 hlen += (((struct ip6_rthdr *)ulp)->ip6r_len + 1) << 3;
2357 proto = ((struct ip6_rthdr *)ulp)->ip6r_nxt;
2361 case IPPROTO_FRAGMENT: /* RFC 2460 */
2362 PULLUP_TO(hlen, ulp, struct ip6_frag);
2363 ext_hd |= EXT_FRAGMENT;
2364 hlen += sizeof (struct ip6_frag);
2365 proto = ((struct ip6_frag *)ulp)->ip6f_nxt;
2366 offset = ((struct ip6_frag *)ulp)->ip6f_offlg &
2368 /* Add IP6F_MORE_FRAG for offset of first
2369 * fragment to be != 0. */
2370 offset |= ((struct ip6_frag *)ulp)->ip6f_offlg &
2373 printf("IPFW2: IPV6 - Invalid Fragment "
2375 if (V_fw_deny_unknown_exthdrs)
2376 return (IP_FW_DENY);
2379 args->f_id.frag_id6 =
2380 ntohl(((struct ip6_frag *)ulp)->ip6f_ident);
2384 case IPPROTO_DSTOPTS: /* RFC 2460 */
2385 PULLUP_TO(hlen, ulp, struct ip6_hbh);
2386 ext_hd |= EXT_DSTOPTS;
2387 hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3;
2388 proto = ((struct ip6_hbh *)ulp)->ip6h_nxt;
2392 case IPPROTO_AH: /* RFC 2402 */
2393 PULLUP_TO(hlen, ulp, struct ip6_ext);
2395 hlen += (((struct ip6_ext *)ulp)->ip6e_len + 2) << 2;
2396 proto = ((struct ip6_ext *)ulp)->ip6e_nxt;
2400 case IPPROTO_ESP: /* RFC 2406 */
2401 PULLUP_TO(hlen, ulp, uint32_t); /* SPI, Seq# */
2402 /* Anything past Seq# is variable length and
2403 * data past this ext. header is encrypted. */
2407 case IPPROTO_NONE: /* RFC 2460 */
2409 * Packet ends here, and IPv6 header has
2410 * already been pulled up. If ip6e_len!=0
2411 * then octets must be ignored.
2413 ulp = ip; /* non-NULL to get out of loop. */
2416 case IPPROTO_OSPFIGP:
2417 /* XXX OSPF header check? */
2418 PULLUP_TO(hlen, ulp, struct ip6_ext);
2422 /* XXX PIM header check? */
2423 PULLUP_TO(hlen, ulp, struct pim);
2427 PULLUP_TO(hlen, ulp, struct carp_header);
2428 if (((struct carp_header *)ulp)->carp_version !=
2430 return (IP_FW_DENY);
2431 if (((struct carp_header *)ulp)->carp_type !=
2433 return (IP_FW_DENY);
2436 case IPPROTO_IPV6: /* RFC 2893 */
2437 PULLUP_TO(hlen, ulp, struct ip6_hdr);
2440 case IPPROTO_IPV4: /* RFC 2893 */
2441 PULLUP_TO(hlen, ulp, struct ip);
2445 printf("IPFW2: IPV6 - Unknown Extension "
2446 "Header(%d), ext_hd=%x\n", proto, ext_hd);
2447 if (V_fw_deny_unknown_exthdrs)
2448 return (IP_FW_DENY);
2449 PULLUP_TO(hlen, ulp, struct ip6_ext);
2453 ip = mtod(m, struct ip *);
2454 ip6 = (struct ip6_hdr *)ip;
2455 args->f_id.src_ip6 = ip6->ip6_src;
2456 args->f_id.dst_ip6 = ip6->ip6_dst;
2457 args->f_id.src_ip = 0;
2458 args->f_id.dst_ip = 0;
2459 args->f_id.flow_id6 = ntohl(ip6->ip6_flow);
2460 } else if (pktlen >= sizeof(struct ip) &&
2461 (args->eh == NULL || etype == ETHERTYPE_IP) && ip->ip_v == 4) {
2463 hlen = ip->ip_hl << 2;
2464 args->f_id.addr_type = 4;
2467 * Collect parameters into local variables for faster matching.
2470 src_ip = ip->ip_src;
2471 dst_ip = ip->ip_dst;
2472 if (args->eh != NULL) { /* layer 2 packets are as on the wire */
2473 offset = ntohs(ip->ip_off) & IP_OFFMASK;
2474 ip_len = ntohs(ip->ip_len);
2476 offset = ip->ip_off & IP_OFFMASK;
2477 ip_len = ip->ip_len;
2479 pktlen = ip_len < pktlen ? ip_len : pktlen;
2484 PULLUP_TO(hlen, ulp, struct tcphdr);
2485 dst_port = TCP(ulp)->th_dport;
2486 src_port = TCP(ulp)->th_sport;
2487 args->f_id.flags = TCP(ulp)->th_flags;
2491 PULLUP_TO(hlen, ulp, struct udphdr);
2492 dst_port = UDP(ulp)->uh_dport;
2493 src_port = UDP(ulp)->uh_sport;
2497 PULLUP_TO(hlen, ulp, struct icmphdr);
2498 args->f_id.flags = ICMP(ulp)->icmp_type;
2506 ip = mtod(m, struct ip *);
2507 args->f_id.src_ip = ntohl(src_ip.s_addr);
2508 args->f_id.dst_ip = ntohl(dst_ip.s_addr);
2511 if (proto) { /* we may have port numbers, store them */
2512 args->f_id.proto = proto;
2513 args->f_id.src_port = src_port = ntohs(src_port);
2514 args->f_id.dst_port = dst_port = ntohs(dst_port);
2518 mtag = m_tag_find(m, PACKET_TAG_DIVERT, NULL);
2521 * Packet has already been tagged. Look for the next rule
2522 * to restart processing. Make sure that args->rule still
2523 * exists and not changed.
2525 if (chain->id != args->chain_id) {
2526 for (f = chain->rules; f != NULL; f = f->next)
2527 if (f == args->rule && f->id == args->rule_id)
2533 f = ip_fw_default_rule;
2535 f = args->rule->next_rule;
2538 f = lookup_next_rule(args->rule, 0);
2541 * Find the starting rule. It can be either the first
2542 * one, or the one after divert_rule if asked so.
2544 int skipto = mtag ? divert_cookie(mtag) : 0;
2547 if (args->eh == NULL && skipto != 0) {
2548 if (skipto >= IPFW_DEFAULT_RULE) {
2549 IPFW_RUNLOCK(chain);
2550 return (IP_FW_DENY); /* invalid */
2552 while (f && f->rulenum <= skipto)
2554 if (f == NULL) { /* drop packet */
2555 IPFW_RUNLOCK(chain);
2556 return (IP_FW_DENY);
2560 /* reset divert rule to avoid confusion later */
2562 divinput_flags = divert_info(mtag) &
2563 (IP_FW_DIVERT_OUTPUT_FLAG | IP_FW_DIVERT_LOOPBACK_FLAG);
2564 m_tag_delete(m, mtag);
2568 * Now scan the rules, and parse microinstructions for each rule.
2570 for (; f; f = f->next) {
2572 uint32_t tablearg = 0;
2573 int l, cmdlen, skip_or; /* skip rest of OR block */
2576 if (V_set_disable & (1 << f->set) )
2580 for (l = f->cmd_len, cmd = f->cmd ; l > 0 ;
2581 l -= cmdlen, cmd += cmdlen) {
2585 * check_body is a jump target used when we find a
2586 * CHECK_STATE, and need to jump to the body of
2591 cmdlen = F_LEN(cmd);
2593 * An OR block (insn_1 || .. || insn_n) has the
2594 * F_OR bit set in all but the last instruction.
2595 * The first match will set "skip_or", and cause
2596 * the following instructions to be skipped until
2597 * past the one with the F_OR bit clear.
2599 if (skip_or) { /* skip this instruction */
2600 if ((cmd->len & F_OR) == 0)
2601 skip_or = 0; /* next one is good */
2604 match = 0; /* set to 1 if we succeed */
2606 switch (cmd->opcode) {
2608 * The first set of opcodes compares the packet's
2609 * fields with some pattern, setting 'match' if a
2610 * match is found. At the end of the loop there is
2611 * logic to deal with F_NOT and F_OR flags associated
2619 printf("ipfw: opcode %d unimplemented\n",
2627 * We only check offset == 0 && proto != 0,
2628 * as this ensures that we have a
2629 * packet with the ports info.
2633 if (is_ipv6) /* XXX to be fixed later */
2635 if (proto == IPPROTO_TCP ||
2636 proto == IPPROTO_UDP)
2637 match = check_uidgid(
2638 (ipfw_insn_u32 *)cmd,
2641 src_ip, src_port, &ucred_cache,
2642 &ucred_lookup, args->inp);
2646 match = iface_match(m->m_pkthdr.rcvif,
2647 (ipfw_insn_if *)cmd);
2651 match = iface_match(oif, (ipfw_insn_if *)cmd);
2655 match = iface_match(oif ? oif :
2656 m->m_pkthdr.rcvif, (ipfw_insn_if *)cmd);
2660 if (args->eh != NULL) { /* have MAC header */
2661 u_int32_t *want = (u_int32_t *)
2662 ((ipfw_insn_mac *)cmd)->addr;
2663 u_int32_t *mask = (u_int32_t *)
2664 ((ipfw_insn_mac *)cmd)->mask;
2665 u_int32_t *hdr = (u_int32_t *)args->eh;
2668 ( want[0] == (hdr[0] & mask[0]) &&
2669 want[1] == (hdr[1] & mask[1]) &&
2670 want[2] == (hdr[2] & mask[2]) );
2675 if (args->eh != NULL) {
2677 ((ipfw_insn_u16 *)cmd)->ports;
2680 for (i = cmdlen - 1; !match && i>0;
2682 match = (etype >= p[0] &&
2688 match = (offset != 0);
2691 case O_IN: /* "out" is "not in" */
2692 match = (oif == NULL);
2696 match = (args->eh != NULL);
2700 match = (cmd->arg1 & 1 && divinput_flags &
2701 IP_FW_DIVERT_LOOPBACK_FLAG) ||
2702 (cmd->arg1 & 2 && divinput_flags &
2703 IP_FW_DIVERT_OUTPUT_FLAG);
2708 * We do not allow an arg of 0 so the
2709 * check of "proto" only suffices.
2711 match = (proto == cmd->arg1);
2716 (((ipfw_insn_ip *)cmd)->addr.s_addr ==
2720 case O_IP_SRC_LOOKUP:
2721 case O_IP_DST_LOOKUP:
2724 (cmd->opcode == O_IP_DST_LOOKUP) ?
2725 dst_ip.s_addr : src_ip.s_addr;
2728 match = lookup_table(chain, cmd->arg1, a,
2732 if (cmdlen == F_INSN_SIZE(ipfw_insn_u32))
2734 ((ipfw_insn_u32 *)cmd)->d[0] == v;
2744 (cmd->opcode == O_IP_DST_MASK) ?
2745 dst_ip.s_addr : src_ip.s_addr;
2746 uint32_t *p = ((ipfw_insn_u32 *)cmd)->d;
2749 for (; !match && i>0; i-= 2, p+= 2)
2750 match = (p[0] == (a & p[1]));
2758 INADDR_TO_IFP(src_ip, tif);
2759 match = (tif != NULL);
2766 u_int32_t *d = (u_int32_t *)(cmd+1);
2768 cmd->opcode == O_IP_DST_SET ?
2774 addr -= d[0]; /* subtract base */
2775 match = (addr < cmd->arg1) &&
2776 ( d[ 1 + (addr>>5)] &
2777 (1<<(addr & 0x1f)) );
2783 (((ipfw_insn_ip *)cmd)->addr.s_addr ==
2791 INADDR_TO_IFP(dst_ip, tif);
2792 match = (tif != NULL);
2799 * offset == 0 && proto != 0 is enough
2800 * to guarantee that we have a
2801 * packet with port info.
2803 if ((proto==IPPROTO_UDP || proto==IPPROTO_TCP)
2806 (cmd->opcode == O_IP_SRCPORT) ?
2807 src_port : dst_port ;
2809 ((ipfw_insn_u16 *)cmd)->ports;
2812 for (i = cmdlen - 1; !match && i>0;
2814 match = (x>=p[0] && x<=p[1]);
2819 match = (offset == 0 && proto==IPPROTO_ICMP &&
2820 icmptype_match(ICMP(ulp), (ipfw_insn_u32 *)cmd) );
2825 match = is_ipv6 && offset == 0 &&
2826 proto==IPPROTO_ICMPV6 &&
2828 ICMP6(ulp)->icmp6_type,
2829 (ipfw_insn_u32 *)cmd);
2835 ipopts_match(ip, cmd) );
2840 cmd->arg1 == ip->ip_v);
2846 if (is_ipv4) { /* only for IP packets */
2851 if (cmd->opcode == O_IPLEN)
2853 else if (cmd->opcode == O_IPTTL)
2855 else /* must be IPID */
2856 x = ntohs(ip->ip_id);
2858 match = (cmd->arg1 == x);
2861 /* otherwise we have ranges */
2862 p = ((ipfw_insn_u16 *)cmd)->ports;
2864 for (; !match && i>0; i--, p += 2)
2865 match = (x >= p[0] && x <= p[1]);
2869 case O_IPPRECEDENCE:
2871 (cmd->arg1 == (ip->ip_tos & 0xe0)) );
2876 flags_match(cmd, ip->ip_tos));
2880 if (proto == IPPROTO_TCP && offset == 0) {
2888 ((ip->ip_hl + tcp->th_off) << 2);
2890 match = (cmd->arg1 == x);
2893 /* otherwise we have ranges */
2894 p = ((ipfw_insn_u16 *)cmd)->ports;
2896 for (; !match && i>0; i--, p += 2)
2897 match = (x >= p[0] && x <= p[1]);
2902 match = (proto == IPPROTO_TCP && offset == 0 &&
2903 flags_match(cmd, TCP(ulp)->th_flags));
2907 match = (proto == IPPROTO_TCP && offset == 0 &&
2908 tcpopts_match(TCP(ulp), cmd));
2912 match = (proto == IPPROTO_TCP && offset == 0 &&
2913 ((ipfw_insn_u32 *)cmd)->d[0] ==
2918 match = (proto == IPPROTO_TCP && offset == 0 &&
2919 ((ipfw_insn_u32 *)cmd)->d[0] ==
2924 match = (proto == IPPROTO_TCP && offset == 0 &&
2925 cmd->arg1 == TCP(ulp)->th_win);
2929 /* reject packets which have SYN only */
2930 /* XXX should i also check for TH_ACK ? */
2931 match = (proto == IPPROTO_TCP && offset == 0 &&
2932 (TCP(ulp)->th_flags &
2933 (TH_RST | TH_ACK | TH_SYN)) != TH_SYN);
2938 ipfw_insn_altq *altq = (ipfw_insn_altq *)cmd;
2941 at = pf_find_mtag(m);
2942 if (at != NULL && at->qid != 0)
2944 at = pf_get_mtag(m);
2947 * Let the packet fall back to the
2952 at->qid = altq->qid;
2963 ipfw_log(f, hlen, args, m,
2964 oif, offset, tablearg, ip);
2969 match = (random()<((ipfw_insn_u32 *)cmd)->d[0]);
2973 /* Outgoing packets automatically pass/match */
2974 match = ((oif != NULL) ||
2975 (m->m_pkthdr.rcvif == NULL) ||
2979 verify_path6(&(args->f_id.src_ip6),
2980 m->m_pkthdr.rcvif) :
2982 verify_path(src_ip, m->m_pkthdr.rcvif,
2987 /* Outgoing packets automatically pass/match */
2988 match = (hlen > 0 && ((oif != NULL) ||
2991 verify_path6(&(args->f_id.src_ip6),
2994 verify_path(src_ip, NULL, args->f_id.fib)));
2998 /* Outgoing packets automatically pass/match */
2999 if (oif == NULL && hlen > 0 &&
3000 ( (is_ipv4 && in_localaddr(src_ip))
3003 in6_localaddr(&(args->f_id.src_ip6)))
3008 is_ipv6 ? verify_path6(
3009 &(args->f_id.src_ip6),
3010 m->m_pkthdr.rcvif) :
3021 match = (m_tag_find(m,
3022 PACKET_TAG_IPSEC_IN_DONE, NULL) != NULL);
3024 /* otherwise no match */
3030 IN6_ARE_ADDR_EQUAL(&args->f_id.src_ip6,
3031 &((ipfw_insn_ip6 *)cmd)->addr6);
3036 IN6_ARE_ADDR_EQUAL(&args->f_id.dst_ip6,
3037 &((ipfw_insn_ip6 *)cmd)->addr6);
3039 case O_IP6_SRC_MASK:
3040 case O_IP6_DST_MASK:
3044 struct in6_addr *d =
3045 &((ipfw_insn_ip6 *)cmd)->addr6;
3047 for (; !match && i > 0; d += 2,
3048 i -= F_INSN_SIZE(struct in6_addr)
3054 APPLY_MASK(&p, &d[1]);
3056 IN6_ARE_ADDR_EQUAL(&d[0],
3063 match= is_ipv6 && search_ip6_addr_net(&args->f_id.src_ip6);
3067 match= is_ipv6 && search_ip6_addr_net(&args->f_id.dst_ip6);
3072 flow6id_match(args->f_id.flow_id6,
3073 (ipfw_insn_u32 *) cmd);
3078 (ext_hd & ((ipfw_insn *) cmd)->arg1);
3091 uint32_t tag = (cmd->arg1 == IP_FW_TABLEARG) ?
3092 tablearg : cmd->arg1;
3094 /* Packet is already tagged with this tag? */
3095 mtag = m_tag_locate(m, MTAG_IPFW, tag, NULL);
3097 /* We have `untag' action when F_NOT flag is
3098 * present. And we must remove this mtag from
3099 * mbuf and reset `match' to zero (`match' will
3100 * be inversed later).
3101 * Otherwise we should allocate new mtag and
3102 * push it into mbuf.
3104 if (cmd->len & F_NOT) { /* `untag' action */
3106 m_tag_delete(m, mtag);
3107 } else if (mtag == NULL) {
3108 if ((mtag = m_tag_alloc(MTAG_IPFW,
3109 tag, 0, M_NOWAIT)) != NULL)
3110 m_tag_prepend(m, mtag);
3112 match = (cmd->len & F_NOT) ? 0: 1;
3116 case O_FIB: /* try match the specified fib */
3117 if (args->f_id.fib == cmd->arg1)
3122 uint32_t tag = (cmd->arg1 == IP_FW_TABLEARG) ?
3123 tablearg : cmd->arg1;
3126 match = m_tag_locate(m, MTAG_IPFW,
3131 /* we have ranges */
3132 for (mtag = m_tag_first(m);
3133 mtag != NULL && !match;
3134 mtag = m_tag_next(m, mtag)) {
3138 if (mtag->m_tag_cookie != MTAG_IPFW)
3141 p = ((ipfw_insn_u16 *)cmd)->ports;
3143 for(; !match && i > 0; i--, p += 2)
3145 mtag->m_tag_id >= p[0] &&
3146 mtag->m_tag_id <= p[1];
3152 * The second set of opcodes represents 'actions',
3153 * i.e. the terminal part of a rule once the packet
3154 * matches all previous patterns.
3155 * Typically there is only one action for each rule,
3156 * and the opcode is stored at the end of the rule
3157 * (but there are exceptions -- see below).
3159 * In general, here we set retval and terminate the
3160 * outer loop (would be a 'break 3' in some language,
3161 * but we need to do a 'goto done').
3164 * O_COUNT and O_SKIPTO actions:
3165 * instead of terminating, we jump to the next rule
3166 * ('goto next_rule', equivalent to a 'break 2'),
3167 * or to the SKIPTO target ('goto again' after
3168 * having set f, cmd and l), respectively.
3170 * O_TAG, O_LOG and O_ALTQ action parameters:
3171 * perform some action and set match = 1;
3173 * O_LIMIT and O_KEEP_STATE: these opcodes are
3174 * not real 'actions', and are stored right
3175 * before the 'action' part of the rule.
3176 * These opcodes try to install an entry in the
3177 * state tables; if successful, we continue with
3178 * the next opcode (match=1; break;), otherwise
3179 * the packet * must be dropped
3180 * ('goto done' after setting retval);
3182 * O_PROBE_STATE and O_CHECK_STATE: these opcodes
3183 * cause a lookup of the state table, and a jump
3184 * to the 'action' part of the parent rule
3185 * ('goto check_body') if an entry is found, or
3186 * (CHECK_STATE only) a jump to the next rule if
3187 * the entry is not found ('goto next_rule').
3188 * The result of the lookup is cached to make
3189 * further instances of these opcodes are
3194 if (install_state(f,
3195 (ipfw_insn_limit *)cmd, args, tablearg)) {
3196 retval = IP_FW_DENY;
3197 goto done; /* error/limit violation */
3205 * dynamic rules are checked at the first
3206 * keep-state or check-state occurrence,
3207 * with the result being stored in dyn_dir.
3208 * The compiler introduces a PROBE_STATE
3209 * instruction for us when we have a
3210 * KEEP_STATE (because PROBE_STATE needs
3213 if (dyn_dir == MATCH_UNKNOWN &&
3214 (q = lookup_dyn_rule(&args->f_id,
3215 &dyn_dir, proto == IPPROTO_TCP ?
3219 * Found dynamic entry, update stats
3220 * and jump to the 'action' part of
3226 cmd = ACTION_PTR(f);
3227 l = f->cmd_len - f->act_ofs;
3232 * Dynamic entry not found. If CHECK_STATE,
3233 * skip to next rule, if PROBE_STATE just
3234 * ignore and continue with next opcode.
3236 if (cmd->opcode == O_CHECK_STATE)
3242 retval = 0; /* accept */
3247 args->rule = f; /* report matching rule */
3248 args->rule_id = f->id;
3249 args->chain_id = chain->id;
3250 if (cmd->arg1 == IP_FW_TABLEARG)
3251 args->cookie = tablearg;
3253 args->cookie = cmd->arg1;
3254 retval = IP_FW_DUMMYNET;
3259 struct divert_tag *dt;
3261 if (args->eh) /* not on layer 2 */
3263 mtag = m_tag_get(PACKET_TAG_DIVERT,
3264 sizeof(struct divert_tag),
3269 IPFW_RUNLOCK(chain);
3270 if (ucred_cache != NULL)
3271 crfree(ucred_cache);
3272 return (IP_FW_DENY);
3274 dt = (struct divert_tag *)(mtag+1);
3275 dt->cookie = f->rulenum;
3276 if (cmd->arg1 == IP_FW_TABLEARG)
3277 dt->info = tablearg;
3279 dt->info = cmd->arg1;
3280 m_tag_prepend(m, mtag);
3281 retval = (cmd->opcode == O_DIVERT) ?
3282 IP_FW_DIVERT : IP_FW_TEE;
3287 f->pcnt++; /* update stats */
3289 f->timestamp = time_uptime;
3290 if (cmd->opcode == O_COUNT)
3293 if (cmd->arg1 == IP_FW_TABLEARG) {
3294 f = lookup_next_rule(f, tablearg);
3296 if (f->next_rule == NULL)
3297 lookup_next_rule(f, 0);
3304 * Drop the packet and send a reject notice
3305 * if the packet is not ICMP (or is an ICMP
3306 * query), and it is not multicast/broadcast.
3308 if (hlen > 0 && is_ipv4 && offset == 0 &&
3309 (proto != IPPROTO_ICMP ||
3310 is_icmp_query(ICMP(ulp))) &&
3311 !(m->m_flags & (M_BCAST|M_MCAST)) &&
3312 !IN_MULTICAST(ntohl(dst_ip.s_addr))) {
3313 send_reject(args, cmd->arg1, ip_len, ip);
3319 if (hlen > 0 && is_ipv6 &&
3320 ((offset & IP6F_OFF_MASK) == 0) &&
3321 (proto != IPPROTO_ICMPV6 ||
3322 (is_icmp6_query(args->f_id.flags) == 1)) &&
3323 !(m->m_flags & (M_BCAST|M_MCAST)) &&
3324 !IN6_IS_ADDR_MULTICAST(&args->f_id.dst_ip6)) {
3326 args, cmd->arg1, hlen,
3327 (struct ip6_hdr *)ip);
3333 retval = IP_FW_DENY;
3336 case O_FORWARD_IP: {
3337 struct sockaddr_in *sa;
3338 sa = &(((ipfw_insn_sa *)cmd)->sa);
3339 if (args->eh) /* not valid on layer2 pkts */
3341 if (!q || dyn_dir == MATCH_FORWARD) {
3342 if (sa->sin_addr.s_addr == INADDR_ANY) {
3343 bcopy(sa, &args->hopstore,
3345 args->hopstore.sin_addr.s_addr =
3350 args->next_hop = sa;
3353 retval = IP_FW_PASS;
3359 args->rule = f; /* report matching rule */
3360 args->rule_id = f->id;
3361 args->chain_id = chain->id;
3362 if (cmd->arg1 == IP_FW_TABLEARG)
3363 args->cookie = tablearg;
3365 args->cookie = cmd->arg1;
3366 retval = (cmd->opcode == O_NETGRAPH) ?
3367 IP_FW_NETGRAPH : IP_FW_NGTEE;
3371 f->pcnt++; /* update stats */
3373 f->timestamp = time_uptime;
3374 M_SETFIB(m, cmd->arg1);
3375 args->f_id.fib = cmd->arg1;
3382 if (IPFW_NAT_LOADED) {
3383 args->rule = f; /* Report matching rule. */
3384 args->rule_id = f->id;
3385 args->chain_id = chain->id;
3386 t = ((ipfw_insn_nat *)cmd)->nat;
3388 nat_id = (cmd->arg1 == IP_FW_TABLEARG) ?
3389 tablearg : cmd->arg1;
3390 LOOKUP_NAT(V_layer3_chain, nat_id, t);
3392 retval = IP_FW_DENY;
3395 if (cmd->arg1 != IP_FW_TABLEARG)
3396 ((ipfw_insn_nat *)cmd)->nat = t;
3398 retval = ipfw_nat_ptr(args, t, m);
3400 retval = IP_FW_DENY;
3409 ip_off = (args->eh != NULL) ? ntohs(ip->ip_off) : ip->ip_off;
3410 if (ip_off & (IP_MF | IP_OFFMASK)) {
3412 * ip_reass() expects len & off in host
3413 * byte order: fix them in case we come
3416 if (args->eh != NULL) {
3417 ip->ip_len = ntohs(ip->ip_len);
3418 ip->ip_off = ntohs(ip->ip_off);
3425 * IP header checksum fixup after
3426 * reassembly and leave header
3427 * in network byte order.
3432 ip = mtod(m, struct ip *);
3433 hlen = ip->ip_hl << 2;
3434 /* revert len & off for layer2 pkts */
3435 if (args->eh != NULL)
3436 ip->ip_len = htons(ip->ip_len);
3438 if (hlen == sizeof(struct ip))
3439 ip->ip_sum = in_cksum_hdr(ip);
3441 ip->ip_sum = in_cksum(m, hlen);
3442 retval = IP_FW_REASS;
3444 args->rule_id = f->id;
3445 args->chain_id = chain->id;
3448 retval = IP_FW_DENY;
3456 panic("-- unknown opcode %d\n", cmd->opcode);
3457 } /* end of switch() on opcodes */
3459 if (cmd->len & F_NOT)
3463 if (cmd->len & F_OR)
3466 if (!(cmd->len & F_OR)) /* not an OR block, */
3467 break; /* try next rule */
3470 } /* end of inner for, scan opcodes */
3472 next_rule:; /* try next rule */
3474 } /* end of outer for, scan rules */
3475 printf("ipfw: ouch!, skip past end of rules, denying packet\n");
3476 IPFW_RUNLOCK(chain);
3477 if (ucred_cache != NULL)
3478 crfree(ucred_cache);
3479 return (IP_FW_DENY);
3482 /* Update statistics */
3485 f->timestamp = time_uptime;
3486 IPFW_RUNLOCK(chain);
3487 if (ucred_cache != NULL)
3488 crfree(ucred_cache);
3493 printf("ipfw: pullup failed\n");
3494 return (IP_FW_DENY);
3498 * When a rule is added/deleted, clear the next_rule pointers in all rules.
3499 * These will be reconstructed on the fly as packets are matched.
3502 flush_rule_ptrs(struct ip_fw_chain *chain)
3506 IPFW_WLOCK_ASSERT(chain);
3510 for (rule = chain->rules; rule; rule = rule->next)
3511 rule->next_rule = NULL;
3515 * Add a new rule to the list. Copy the rule into a malloc'ed area, then
3516 * possibly create a rule number and add the rule to the list.
3517 * Update the rule_number in the input struct so the caller knows it as well.
3520 add_rule(struct ip_fw_chain *chain, struct ip_fw *input_rule)
3522 struct ip_fw *rule, *f, *prev;
3523 int l = RULESIZE(input_rule);
3525 if (chain->rules == NULL && input_rule->rulenum != IPFW_DEFAULT_RULE)
3528 rule = malloc(l, M_IPFW, M_NOWAIT | M_ZERO);
3532 bcopy(input_rule, rule, l);
3535 rule->next_rule = NULL;
3539 rule->timestamp = 0;
3543 if (chain->rules == NULL) { /* default rule */
3544 chain->rules = rule;
3545 rule->id = ++chain->id;
3550 * If rulenum is 0, find highest numbered rule before the
3551 * default rule, and add autoinc_step
3553 if (V_autoinc_step < 1)
3555 else if (V_autoinc_step > 1000)
3556 V_autoinc_step = 1000;
3557 if (rule->rulenum == 0) {
3559 * locate the highest numbered rule before default
3561 for (f = chain->rules; f; f = f->next) {
3562 if (f->rulenum == IPFW_DEFAULT_RULE)
3564 rule->rulenum = f->rulenum;
3566 if (rule->rulenum < IPFW_DEFAULT_RULE - V_autoinc_step)
3567 rule->rulenum += V_autoinc_step;
3568 input_rule->rulenum = rule->rulenum;
3572 * Now insert the new rule in the right place in the sorted list.
3574 for (prev = NULL, f = chain->rules; f; prev = f, f = f->next) {
3575 if (f->rulenum > rule->rulenum) { /* found the location */
3579 } else { /* head insert */
3580 rule->next = chain->rules;
3581 chain->rules = rule;
3586 flush_rule_ptrs(chain);
3587 /* chain->id incremented inside flush_rule_ptrs() */
3588 rule->id = chain->id;
3592 IPFW_WUNLOCK(chain);
3593 DEB(printf("ipfw: installed rule %d, static count now %d\n",
3594 rule->rulenum, V_static_count);)
3599 * Remove a static rule (including derived * dynamic rules)
3600 * and place it on the ``reap list'' for later reclamation.
3601 * The caller is in charge of clearing rule pointers to avoid
3602 * dangling pointers.
3603 * @return a pointer to the next entry.
3604 * Arguments are not checked, so they better be correct.
3606 static struct ip_fw *
3607 remove_rule(struct ip_fw_chain *chain, struct ip_fw *rule,
3611 int l = RULESIZE(rule);
3613 IPFW_WLOCK_ASSERT(chain);
3617 remove_dyn_rule(rule, NULL /* force removal */);
3626 rule->next = chain->reap;
3633 * Reclaim storage associated with a list of rules. This is
3634 * typically the list created using remove_rule.
3635 * A NULL pointer on input is handled correctly.
3638 reap_rules(struct ip_fw *head)
3642 while ((rule = head) != NULL) {
3649 * Remove all rules from a chain (except rules in set RESVD_SET
3650 * unless kill_default = 1). The caller is responsible for
3651 * reclaiming storage for the rules left in chain->reap.
3654 free_chain(struct ip_fw_chain *chain, int kill_default)
3656 struct ip_fw *prev, *rule;
3658 IPFW_WLOCK_ASSERT(chain);
3661 flush_rule_ptrs(chain); /* more efficient to do outside the loop */
3662 for (prev = NULL, rule = chain->rules; rule ; )
3663 if (kill_default || rule->set != RESVD_SET)
3664 rule = remove_rule(chain, rule, prev);
3672 * Remove all rules with given number, and also do set manipulation.
3673 * Assumes chain != NULL && *chain != NULL.
3675 * The argument is an u_int32_t. The low 16 bit are the rule or set number,
3676 * the next 8 bits are the new set, the top 8 bits are the command:
3678 * 0 delete rules with given number
3679 * 1 delete rules with given set number
3680 * 2 move rules with given number to new set
3681 * 3 move rules with given set number to new set
3682 * 4 swap sets with given numbers
3683 * 5 delete rules with given number and with given set number
3686 del_entry(struct ip_fw_chain *chain, u_int32_t arg)
3688 struct ip_fw *prev = NULL, *rule;
3689 u_int16_t rulenum; /* rule or old_set */
3690 u_int8_t cmd, new_set;
3692 rulenum = arg & 0xffff;
3693 cmd = (arg >> 24) & 0xff;
3694 new_set = (arg >> 16) & 0xff;
3696 if (cmd > 5 || new_set > RESVD_SET)
3698 if (cmd == 0 || cmd == 2 || cmd == 5) {
3699 if (rulenum >= IPFW_DEFAULT_RULE)
3702 if (rulenum > RESVD_SET) /* old_set */
3707 rule = chain->rules; /* common starting point */
3708 chain->reap = NULL; /* prepare for deletions */
3710 case 0: /* delete rules with given number */
3712 * locate first rule to delete
3714 for (; rule->rulenum < rulenum; prev = rule, rule = rule->next)
3716 if (rule->rulenum != rulenum) {
3717 IPFW_WUNLOCK(chain);
3722 * flush pointers outside the loop, then delete all matching
3723 * rules. prev remains the same throughout the cycle.
3725 flush_rule_ptrs(chain);
3726 while (rule->rulenum == rulenum)
3727 rule = remove_rule(chain, rule, prev);
3730 case 1: /* delete all rules with given set number */
3731 flush_rule_ptrs(chain);
3732 while (rule->rulenum < IPFW_DEFAULT_RULE) {
3733 if (rule->set == rulenum)
3734 rule = remove_rule(chain, rule, prev);
3742 case 2: /* move rules with given number to new set */
3743 for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
3744 if (rule->rulenum == rulenum)
3745 rule->set = new_set;
3748 case 3: /* move rules with given set number to new set */
3749 for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
3750 if (rule->set == rulenum)
3751 rule->set = new_set;
3754 case 4: /* swap two sets */
3755 for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
3756 if (rule->set == rulenum)
3757 rule->set = new_set;
3758 else if (rule->set == new_set)
3759 rule->set = rulenum;
3762 case 5: /* delete rules with given number and with given set number.
3763 * rulenum - given rule number;
3764 * new_set - given set number.
3766 for (; rule->rulenum < rulenum; prev = rule, rule = rule->next)
3768 if (rule->rulenum != rulenum) {
3769 IPFW_WUNLOCK(chain);
3772 flush_rule_ptrs(chain);
3773 while (rule->rulenum == rulenum) {
3774 if (rule->set == new_set)
3775 rule = remove_rule(chain, rule, prev);
3783 * Look for rules to reclaim. We grab the list before
3784 * releasing the lock then reclaim them w/o the lock to
3785 * avoid a LOR with dummynet.
3788 IPFW_WUNLOCK(chain);
3794 * Clear counters for a specific rule.
3795 * The enclosing "table" is assumed locked.
3798 clear_counters(struct ip_fw *rule, int log_only)
3800 ipfw_insn_log *l = (ipfw_insn_log *)ACTION_PTR(rule);
3802 if (log_only == 0) {
3803 rule->bcnt = rule->pcnt = 0;
3804 rule->timestamp = 0;
3806 if (l->o.opcode == O_LOG)
3807 l->log_left = l->max_log;
3811 * Reset some or all counters on firewall rules.
3812 * The argument `arg' is an u_int32_t. The low 16 bit are the rule number,
3813 * the next 8 bits are the set number, the top 8 bits are the command:
3814 * 0 work with rules from all set's;
3815 * 1 work with rules only from specified set.
3816 * Specified rule number is zero if we want to clear all entries.
3817 * log_only is 1 if we only want to reset logs, zero otherwise.
3820 zero_entry(struct ip_fw_chain *chain, u_int32_t arg, int log_only)
3825 uint16_t rulenum = arg & 0xffff;
3826 uint8_t set = (arg >> 16) & 0xff;
3827 uint8_t cmd = (arg >> 24) & 0xff;
3831 if (cmd == 1 && set > RESVD_SET)
3836 V_norule_counter = 0;
3837 for (rule = chain->rules; rule; rule = rule->next) {
3838 /* Skip rules from another set. */
3839 if (cmd == 1 && rule->set != set)
3841 clear_counters(rule, log_only);
3843 msg = log_only ? "All logging counts reset" :
3844 "Accounting cleared";
3848 * We can have multiple rules with the same number, so we
3849 * need to clear them all.
3851 for (rule = chain->rules; rule; rule = rule->next)
3852 if (rule->rulenum == rulenum) {
3853 while (rule && rule->rulenum == rulenum) {
3854 if (cmd == 0 || rule->set == set)
3855 clear_counters(rule, log_only);
3861 if (!cleared) { /* we did not find any matching rules */
3862 IPFW_WUNLOCK(chain);
3865 msg = log_only ? "logging count reset" : "cleared";
3867 IPFW_WUNLOCK(chain);
3870 int lev = LOG_SECURITY | LOG_NOTICE;
3873 log(lev, "ipfw: Entry %d %s.\n", rulenum, msg);
3875 log(lev, "ipfw: %s.\n", msg);
3881 * Check validity of the structure before insert.
3882 * Fortunately rules are simple, so this mostly need to check rule sizes.
3885 check_ipfw_struct(struct ip_fw *rule, int size)
3891 if (size < sizeof(*rule)) {
3892 printf("ipfw: rule too short\n");
3895 /* first, check for valid size */
3898 printf("ipfw: size mismatch (have %d want %d)\n", size, l);
3901 if (rule->act_ofs >= rule->cmd_len) {
3902 printf("ipfw: bogus action offset (%u > %u)\n",
3903 rule->act_ofs, rule->cmd_len - 1);
3907 * Now go for the individual checks. Very simple ones, basically only
3908 * instruction sizes.
3910 for (l = rule->cmd_len, cmd = rule->cmd ;
3911 l > 0 ; l -= cmdlen, cmd += cmdlen) {
3912 cmdlen = F_LEN(cmd);
3914 printf("ipfw: opcode %d size truncated\n",
3918 DEB(printf("ipfw: opcode %d\n", cmd->opcode);)
3919 switch (cmd->opcode) {
3931 case O_IPPRECEDENCE:
3949 if (cmdlen != F_INSN_SIZE(ipfw_insn))
3954 if (cmdlen != F_INSN_SIZE(ipfw_insn))
3956 if (cmd->arg1 >= rt_numfibs) {
3957 printf("ipfw: invalid fib number %d\n",
3964 if (cmdlen != F_INSN_SIZE(ipfw_insn))
3966 if (cmd->arg1 >= rt_numfibs) {
3967 printf("ipfw: invalid fib number %d\n",
3982 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32))
3987 if (cmdlen != F_INSN_SIZE(ipfw_insn_limit))
3992 if (cmdlen != F_INSN_SIZE(ipfw_insn_log))
3995 ((ipfw_insn_log *)cmd)->log_left =
3996 ((ipfw_insn_log *)cmd)->max_log;
4002 /* only odd command lengths */
4003 if ( !(cmdlen & 1) || cmdlen > 31)
4009 if (cmd->arg1 == 0 || cmd->arg1 > 256) {
4010 printf("ipfw: invalid set size %d\n",
4014 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
4019 case O_IP_SRC_LOOKUP:
4020 case O_IP_DST_LOOKUP:
4021 if (cmd->arg1 >= IPFW_TABLES_MAX) {
4022 printf("ipfw: invalid table number %d\n",
4026 if (cmdlen != F_INSN_SIZE(ipfw_insn) &&
4027 cmdlen != F_INSN_SIZE(ipfw_insn_u32))
4032 if (cmdlen != F_INSN_SIZE(ipfw_insn_mac))
4042 if (cmdlen < 1 || cmdlen > 31)
4048 case O_IP_DSTPORT: /* XXX artificial limit, 30 port pairs */
4049 if (cmdlen < 2 || cmdlen > 31)
4056 if (cmdlen != F_INSN_SIZE(ipfw_insn_if))
4061 if (cmdlen != F_INSN_SIZE(ipfw_insn_altq))
4067 if (cmdlen != F_INSN_SIZE(ipfw_insn))
4072 #ifdef IPFIREWALL_FORWARD
4073 if (cmdlen != F_INSN_SIZE(ipfw_insn_sa))
4082 if (ip_divert_ptr == NULL)
4088 if (!NG_IPFW_LOADED)
4093 if (!IPFW_NAT_LOADED)
4095 if (cmdlen != F_INSN_SIZE(ipfw_insn_nat))
4098 case O_FORWARD_MAC: /* XXX not implemented yet */
4110 if (cmdlen != F_INSN_SIZE(ipfw_insn))
4114 printf("ipfw: opcode %d, multiple actions"
4121 printf("ipfw: opcode %d, action must be"
4130 if (cmdlen != F_INSN_SIZE(struct in6_addr) +
4131 F_INSN_SIZE(ipfw_insn))
4136 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
4137 ((ipfw_insn_u32 *)cmd)->o.arg1)
4141 case O_IP6_SRC_MASK:
4142 case O_IP6_DST_MASK:
4143 if ( !(cmdlen & 1) || cmdlen > 127)
4147 if( cmdlen != F_INSN_SIZE( ipfw_insn_icmp6 ) )
4153 switch (cmd->opcode) {
4163 case O_IP6_SRC_MASK:
4164 case O_IP6_DST_MASK:
4166 printf("ipfw: no IPv6 support in kernel\n");
4167 return EPROTONOSUPPORT;
4170 printf("ipfw: opcode %d, unknown opcode\n",
4176 if (have_action == 0) {
4177 printf("ipfw: missing action\n");
4183 printf("ipfw: opcode %d size %d wrong\n",
4184 cmd->opcode, cmdlen);
4189 * Copy the static and dynamic rules to the supplied buffer
4190 * and return the amount of space actually used.
4193 ipfw_getrules(struct ip_fw_chain *chain, void *buf, size_t space)
4196 char *ep = bp + space;
4199 time_t boot_seconds;
4201 boot_seconds = boottime.tv_sec;
4202 /* XXX this can take a long time and locking will block packet flow */
4204 for (rule = chain->rules; rule ; rule = rule->next) {
4206 * Verify the entry fits in the buffer in case the
4207 * rules changed between calculating buffer space and
4208 * now. This would be better done using a generation
4209 * number but should suffice for now.
4215 * XXX HACK. Store the disable mask in the "next"
4216 * pointer in a wild attempt to keep the ABI the same.
4217 * Why do we do this on EVERY rule?
4219 bcopy(&V_set_disable,
4220 &(((struct ip_fw *)bp)->next_rule),
4221 sizeof(V_set_disable));
4222 if (((struct ip_fw *)bp)->timestamp)
4223 ((struct ip_fw *)bp)->timestamp += boot_seconds;
4227 IPFW_RUNLOCK(chain);
4229 ipfw_dyn_rule *p, *last = NULL;
4232 for (i = 0 ; i < V_curr_dyn_buckets; i++)
4233 for (p = V_ipfw_dyn_v[i] ; p != NULL; p = p->next) {
4234 if (bp + sizeof *p <= ep) {
4235 ipfw_dyn_rule *dst =
4236 (ipfw_dyn_rule *)bp;
4237 bcopy(p, dst, sizeof *p);
4238 bcopy(&(p->rule->rulenum), &(dst->rule),
4239 sizeof(p->rule->rulenum));
4241 * store set number into high word of
4242 * dst->rule pointer.
4244 bcopy(&(p->rule->set),
4245 (char *)&dst->rule +
4246 sizeof(p->rule->rulenum),
4247 sizeof(p->rule->set));
4249 * store a non-null value in "next".
4250 * The userland code will interpret a
4251 * NULL here as a marker
4252 * for the last dynamic rule.
4254 bcopy(&dst, &dst->next, sizeof(dst));
4257 TIME_LEQ(dst->expire, time_uptime) ?
4258 0 : dst->expire - time_uptime ;
4259 bp += sizeof(ipfw_dyn_rule);
4263 if (last != NULL) /* mark last dynamic rule */
4264 bzero(&last->next, sizeof(last));
4266 return (bp - (char *)buf);
4271 * {set|get}sockopt parser.
4274 ipfw_ctl(struct sockopt *sopt)
4276 #define RULE_MAXSIZE (256*sizeof(u_int32_t))
4279 struct ip_fw *buf, *rule;
4280 u_int32_t rulenum[2];
4282 error = priv_check(sopt->sopt_td, PRIV_NETINET_IPFW);
4287 * Disallow modifications in really-really secure mode, but still allow
4288 * the logging counters to be reset.
4290 if (sopt->sopt_name == IP_FW_ADD ||
4291 (sopt->sopt_dir == SOPT_SET && sopt->sopt_name != IP_FW_RESETLOG)) {
4292 error = securelevel_ge(sopt->sopt_td->td_ucred, 3);
4299 switch (sopt->sopt_name) {
4302 * pass up a copy of the current rules. Static rules
4303 * come first (the last of which has number IPFW_DEFAULT_RULE),
4304 * followed by a possibly empty list of dynamic rule.
4305 * The last dynamic rule has NULL in the "next" field.
4307 * Note that the calculated size is used to bound the
4308 * amount of data returned to the user. The rule set may
4309 * change between calculating the size and returning the
4310 * data in which case we'll just return what fits.
4312 size = V_static_len; /* size of static rules */
4313 if (V_ipfw_dyn_v) /* add size of dyn.rules */
4314 size += (V_dyn_count * sizeof(ipfw_dyn_rule));
4316 if (size >= sopt->sopt_valsize)
4319 * XXX todo: if the user passes a short length just to know
4320 * how much room is needed, do not bother filling up the
4321 * buffer, just jump to the sooptcopyout.
4323 buf = malloc(size, M_TEMP, M_WAITOK);
4324 error = sooptcopyout(sopt, buf,
4325 ipfw_getrules(&V_layer3_chain, buf, size));
4331 * Normally we cannot release the lock on each iteration.
4332 * We could do it here only because we start from the head all
4333 * the times so there is no risk of missing some entries.
4334 * On the other hand, the risk is that we end up with
4335 * a very inconsistent ruleset, so better keep the lock
4336 * around the whole cycle.
4338 * XXX this code can be improved by resetting the head of
4339 * the list to point to the default rule, and then freeing
4340 * the old list without the need for a lock.
4343 IPFW_WLOCK(&V_layer3_chain);
4344 free_chain(&V_layer3_chain, 0 /* keep default rule */);
4345 rule = V_layer3_chain.reap;
4346 IPFW_WUNLOCK(&V_layer3_chain);
4351 rule = malloc(RULE_MAXSIZE, M_TEMP, M_WAITOK);
4352 error = sooptcopyin(sopt, rule, RULE_MAXSIZE,
4353 sizeof(struct ip_fw) );
4355 error = check_ipfw_struct(rule, sopt->sopt_valsize);
4357 error = add_rule(&V_layer3_chain, rule);
4358 size = RULESIZE(rule);
4359 if (!error && sopt->sopt_dir == SOPT_GET)
4360 error = sooptcopyout(sopt, rule, size);
4367 * IP_FW_DEL is used for deleting single rules or sets,
4368 * and (ab)used to atomically manipulate sets. Argument size
4369 * is used to distinguish between the two:
4371 * delete single rule or set of rules,
4372 * or reassign rules (or sets) to a different set.
4373 * 2*sizeof(u_int32_t)
4374 * atomic disable/enable sets.
4375 * first u_int32_t contains sets to be disabled,
4376 * second u_int32_t contains sets to be enabled.
4378 error = sooptcopyin(sopt, rulenum,
4379 2*sizeof(u_int32_t), sizeof(u_int32_t));
4382 size = sopt->sopt_valsize;
4383 if (size == sizeof(u_int32_t)) /* delete or reassign */
4384 error = del_entry(&V_layer3_chain, rulenum[0]);
4385 else if (size == 2*sizeof(u_int32_t)) /* set enable/disable */
4387 (V_set_disable | rulenum[0]) & ~rulenum[1] &
4388 ~(1<<RESVD_SET); /* set RESVD_SET always enabled */
4394 case IP_FW_RESETLOG: /* argument is an u_int_32, the rule number */
4396 if (sopt->sopt_val != 0) {
4397 error = sooptcopyin(sopt, rulenum,
4398 sizeof(u_int32_t), sizeof(u_int32_t));
4402 error = zero_entry(&V_layer3_chain, rulenum[0],
4403 sopt->sopt_name == IP_FW_RESETLOG);
4406 case IP_FW_TABLE_ADD:
4408 ipfw_table_entry ent;
4410 error = sooptcopyin(sopt, &ent,
4411 sizeof(ent), sizeof(ent));
4414 error = add_table_entry(&V_layer3_chain, ent.tbl,
4415 ent.addr, ent.masklen, ent.value);
4419 case IP_FW_TABLE_DEL:
4421 ipfw_table_entry ent;
4423 error = sooptcopyin(sopt, &ent,
4424 sizeof(ent), sizeof(ent));
4427 error = del_table_entry(&V_layer3_chain, ent.tbl,
4428 ent.addr, ent.masklen);
4432 case IP_FW_TABLE_FLUSH:
4436 error = sooptcopyin(sopt, &tbl,
4437 sizeof(tbl), sizeof(tbl));
4440 IPFW_WLOCK(&V_layer3_chain);
4441 error = flush_table(&V_layer3_chain, tbl);
4442 IPFW_WUNLOCK(&V_layer3_chain);
4446 case IP_FW_TABLE_GETSIZE:
4450 if ((error = sooptcopyin(sopt, &tbl, sizeof(tbl),
4453 IPFW_RLOCK(&V_layer3_chain);
4454 error = count_table(&V_layer3_chain, tbl, &cnt);
4455 IPFW_RUNLOCK(&V_layer3_chain);
4458 error = sooptcopyout(sopt, &cnt, sizeof(cnt));
4462 case IP_FW_TABLE_LIST:
4466 if (sopt->sopt_valsize < sizeof(*tbl)) {
4470 size = sopt->sopt_valsize;
4471 tbl = malloc(size, M_TEMP, M_WAITOK);
4472 error = sooptcopyin(sopt, tbl, size, sizeof(*tbl));
4477 tbl->size = (size - sizeof(*tbl)) /
4478 sizeof(ipfw_table_entry);
4479 IPFW_RLOCK(&V_layer3_chain);
4480 error = dump_table(&V_layer3_chain, tbl);
4481 IPFW_RUNLOCK(&V_layer3_chain);
4486 error = sooptcopyout(sopt, tbl, size);
4492 if (IPFW_NAT_LOADED)
4493 error = ipfw_nat_cfg_ptr(sopt);
4495 printf("IP_FW_NAT_CFG: %s\n",
4496 "ipfw_nat not present, please load it");
4502 if (IPFW_NAT_LOADED)
4503 error = ipfw_nat_del_ptr(sopt);
4505 printf("IP_FW_NAT_DEL: %s\n",
4506 "ipfw_nat not present, please load it");
4511 case IP_FW_NAT_GET_CONFIG:
4512 if (IPFW_NAT_LOADED)
4513 error = ipfw_nat_get_cfg_ptr(sopt);
4515 printf("IP_FW_NAT_GET_CFG: %s\n",
4516 "ipfw_nat not present, please load it");
4521 case IP_FW_NAT_GET_LOG:
4522 if (IPFW_NAT_LOADED)
4523 error = ipfw_nat_get_log_ptr(sopt);
4525 printf("IP_FW_NAT_GET_LOG: %s\n",
4526 "ipfw_nat not present, please load it");
4532 printf("ipfw: ipfw_ctl invalid option %d\n", sopt->sopt_name);
4542 * This procedure is only used to handle keepalives. It is invoked
4543 * every dyn_keepalive_period
4546 ipfw_tick(void * vnetx)
4548 struct mbuf *m0, *m, *mnext, **mtailp;
4550 struct mbuf *m6, **m6_tailp;
4555 struct vnet *vp = vnetx;
4559 if (V_dyn_keepalive == 0 || V_ipfw_dyn_v == NULL || V_dyn_count == 0)
4563 * We make a chain of packets to go out here -- not deferring
4564 * until after we drop the IPFW dynamic rule lock would result
4565 * in a lock order reversal with the normal packet input -> ipfw
4575 for (i = 0 ; i < V_curr_dyn_buckets ; i++) {
4576 for (q = V_ipfw_dyn_v[i] ; q ; q = q->next ) {
4577 if (q->dyn_type == O_LIMIT_PARENT)
4579 if (q->id.proto != IPPROTO_TCP)
4581 if ( (q->state & BOTH_SYN) != BOTH_SYN)
4583 if (TIME_LEQ(time_uptime + V_dyn_keepalive_interval,
4585 continue; /* too early */
4586 if (TIME_LEQ(q->expire, time_uptime))
4587 continue; /* too late, rule expired */
4589 m = send_pkt(NULL, &(q->id), q->ack_rev - 1,
4590 q->ack_fwd, TH_SYN);
4591 mnext = send_pkt(NULL, &(q->id), q->ack_fwd - 1,
4594 switch (q->id.addr_type) {
4598 mtailp = &(*mtailp)->m_nextpkt;
4600 if (mnext != NULL) {
4602 mtailp = &(*mtailp)->m_nextpkt;
4609 m6_tailp = &(*m6_tailp)->m_nextpkt;
4611 if (mnext != NULL) {
4613 m6_tailp = &(*m6_tailp)->m_nextpkt;
4623 for (m = mnext = m0; m != NULL; m = mnext) {
4624 mnext = m->m_nextpkt;
4625 m->m_nextpkt = NULL;
4626 ip_output(m, NULL, NULL, 0, NULL, NULL);
4629 for (m = mnext = m6; m != NULL; m = mnext) {
4630 mnext = m->m_nextpkt;
4631 m->m_nextpkt = NULL;
4632 ip6_output(m, NULL, NULL, 0, NULL, NULL, NULL);
4636 callout_reset(&V_ipfw_timeout, V_dyn_keepalive_period * hz,
4642 * Stuff that must be initialised only on boot or module load
4649 ipfw_dyn_rule_zone = uma_zcreate("IPFW dynamic rule",
4650 sizeof(ipfw_dyn_rule), NULL, NULL, NULL, NULL,
4653 IPFW_DYN_LOCK_INIT();
4655 * Only print out this stuff the first time around,
4656 * when called from the sysinit code.
4662 "initialized, divert %s, nat %s, "
4663 "rule-based forwarding "
4664 #ifdef IPFIREWALL_FORWARD
4669 "default to %s, logging ",
4675 #ifdef IPFIREWALL_NAT
4680 default_to_accept ? "accept" : "deny");
4683 * Note: V_xxx variables can be accessed here but the vnet specific
4684 * initializer may not have been called yet for the VIMAGE case.
4685 * Tuneables will have been processed. We will print out values for
4687 * XXX This should all be rationalized AFTER 8.0
4689 if (V_fw_verbose == 0)
4690 printf("disabled\n");
4691 else if (V_verbose_limit == 0)
4692 printf("unlimited\n");
4694 printf("limited to %d packets/entry by default\n",
4698 * Hook us up to pfil.
4699 * Eventually pfil will be per vnet.
4701 if ((error = ipfw_hook()) != 0) {
4702 printf("ipfw_hook() error\n");
4706 if ((error = ipfw6_hook()) != 0) {
4707 printf("ipfw6_hook() error\n");
4712 * Other things that are only done the first time.
4713 * (now that we a re cuaranteed of success).
4715 ip_fw_ctl_ptr = ipfw_ctl;
4716 ip_fw_chk_ptr = ipfw_chk;
4721 * Stuff that must be initialized for every instance
4722 * (including the first of course).
4725 vnet_ipfw_init(const void *unused)
4728 struct ip_fw default_rule;
4730 /* First set up some values that are compile time options */
4731 #ifdef IPFIREWALL_VERBOSE
4734 #ifdef IPFIREWALL_VERBOSE_LIMIT
4735 V_verbose_limit = IPFIREWALL_VERBOSE_LIMIT;
4738 error = init_tables(&V_layer3_chain);
4740 panic("init_tables"); /* XXX Marko fix this ! */
4742 #ifdef IPFIREWALL_NAT
4743 LIST_INIT(&V_layer3_chain.nat);
4746 V_autoinc_step = 100; /* bounded to 1..1000 in add_rule() */
4748 V_ipfw_dyn_v = NULL;
4749 V_dyn_buckets = 256; /* must be power of 2 */
4750 V_curr_dyn_buckets = 256; /* must be power of 2 */
4752 V_dyn_ack_lifetime = 300;
4753 V_dyn_syn_lifetime = 20;
4754 V_dyn_fin_lifetime = 1;
4755 V_dyn_rst_lifetime = 1;
4756 V_dyn_udp_lifetime = 10;
4757 V_dyn_short_lifetime = 5;
4759 V_dyn_keepalive_interval = 20;
4760 V_dyn_keepalive_period = 5;
4761 V_dyn_keepalive = 1; /* do send keepalives */
4763 V_dyn_max = 4096; /* max # of dynamic rules */
4765 V_fw_deny_unknown_exthdrs = 1;
4767 V_layer3_chain.rules = NULL;
4768 IPFW_LOCK_INIT(&V_layer3_chain);
4769 callout_init(&V_ipfw_timeout, CALLOUT_MPSAFE);
4771 bzero(&default_rule, sizeof default_rule);
4772 default_rule.act_ofs = 0;
4773 default_rule.rulenum = IPFW_DEFAULT_RULE;
4774 default_rule.cmd_len = 1;
4775 default_rule.set = RESVD_SET;
4776 default_rule.cmd[0].len = 1;
4777 default_rule.cmd[0].opcode = default_to_accept ? O_ACCEPT : O_DENY;
4778 error = add_rule(&V_layer3_chain, &default_rule);
4781 printf("ipfw2: error %u initializing default rule "
4782 "(support disabled)\n", error);
4783 IPFW_LOCK_DESTROY(&V_layer3_chain);
4784 printf("leaving ipfw_iattach (1) with error %d\n", error);
4788 ip_fw_default_rule = V_layer3_chain.rules;
4791 IPFW_LOCK_DESTROY(&V_layer3_chain);
4792 printf("leaving ipfw_iattach (2) with error %d\n", error);
4795 #ifdef VIMAGE /* want a better way to do this */
4796 callout_reset(&V_ipfw_timeout, hz, ipfw_tick, curvnet);
4798 callout_reset(&V_ipfw_timeout, hz, ipfw_tick, NULL);
4801 /* First set up some values that are compile time options */
4802 V_ipfw_vnet_ready = 1; /* Open for business */
4806 /**********************
4807 * Called for the removal of the last instance only on module unload.
4813 uma_zdestroy(ipfw_dyn_rule_zone);
4814 IPFW_DYN_LOCK_DESTROY();
4815 printf("IP firewall unloaded\n");
4818 /***********************
4819 * Called for the removal of each instance.
4822 vnet_ipfw_uninit(const void *unused)
4826 V_ipfw_vnet_ready = 0; /* tell new callers to go away */
4827 callout_drain(&V_ipfw_timeout);
4828 /* We wait on the wlock here until the last user leaves */
4829 IPFW_WLOCK(&V_layer3_chain);
4830 flush_tables(&V_layer3_chain);
4831 V_layer3_chain.reap = NULL;
4832 free_chain(&V_layer3_chain, 1 /* kill default rule */);
4833 reap = V_layer3_chain.reap;
4834 V_layer3_chain.reap = NULL;
4835 IPFW_WUNLOCK(&V_layer3_chain);
4838 IPFW_LOCK_DESTROY(&V_layer3_chain);
4839 if (V_ipfw_dyn_v != NULL)
4840 free(V_ipfw_dyn_v, M_IPFW);
4845 * Module event handler.
4846 * In general we have the choice of handling most of these events by the
4847 * event handler or by the (VNET_)SYS(UN)INIT handlers. I have chosen to
4848 * use the SYSINIT handlers as they are more capable of expressing the
4849 * flow of control during module and vnet operations, so this is just
4850 * a skeleton. Note there is no SYSINIT equivalent of the module
4851 * SHUTDOWN handler, but we don't have anything to do in that case anyhow.
4854 ipfw_modevent(module_t mod, int type, void *unused)
4860 /* Called once at module load or
4861 * system boot if compiled in. */
4866 /* Yes, the unhooks can return errors, we can safely ignore
4867 * them. Eventually these will be done per jail as they
4868 * shut down. We will wait on each vnet's l3 lock as existing
4875 /* layer2 and other entrypoints still come in this way. */
4876 ip_fw_chk_ptr = NULL;
4877 ip_fw_ctl_ptr = NULL;
4878 /* Called during unload. */
4881 /* Called during system shutdown. */
4890 static moduledata_t ipfwmod = {
4896 /* Define startup order. */
4897 #define IPFW_SI_SUB_FIREWALL SI_SUB_PROTO_IFATTACHDOMAIN
4898 #define IPFW_MODEVENT_ORDER (SI_ORDER_ANY - 255) /* On boot slot in here. */
4899 #define IPFW_MODULE_ORDER (IPFW_MODEVENT_ORDER + 1) /* A little later. */
4900 #define IPFW_VNET_ORDER (IPFW_MODEVENT_ORDER + 2) /* Later still. */
4902 DECLARE_MODULE(ipfw, ipfwmod, IPFW_SI_SUB_FIREWALL, IPFW_MODEVENT_ORDER);
4903 MODULE_VERSION(ipfw, 2);
4904 /* should declare some dependencies here */
4907 * Starting up. Done in order after ipfwmod() has been called.
4908 * VNET_SYSINIT is also called for each existing vnet and each new vnet.
4910 SYSINIT(ipfw_init, IPFW_SI_SUB_FIREWALL, IPFW_MODULE_ORDER,
4912 VNET_SYSINIT(vnet_ipfw_init, IPFW_SI_SUB_FIREWALL, IPFW_VNET_ORDER,
4913 vnet_ipfw_init, NULL);
4916 * Closing up shop. These are done in REVERSE ORDER, but still
4917 * after ipfwmod() has been called. Not called on reboot.
4918 * VNET_SYSUNINIT is also called for each exiting vnet as it exits.
4919 * or when the module is unloaded.
4921 SYSUNINIT(ipfw_destroy, IPFW_SI_SUB_FIREWALL, IPFW_MODULE_ORDER,
4922 ipfw_destroy, NULL);
4923 VNET_SYSUNINIT(vnet_ipfw_uninit, IPFW_SI_SUB_FIREWALL, IPFW_VNET_ORDER,
4924 vnet_ipfw_uninit, NULL);