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"
49 #include <sys/param.h>
50 #include <sys/systm.h>
51 #include <sys/condvar.h>
52 #include <sys/eventhandler.h>
53 #include <sys/malloc.h>
55 #include <sys/kernel.h>
58 #include <sys/module.h>
61 #include <sys/rwlock.h>
62 #include <sys/socket.h>
63 #include <sys/socketvar.h>
64 #include <sys/sysctl.h>
65 #include <sys/syslog.h>
66 #include <sys/ucred.h>
68 #include <net/radix.h>
69 #include <net/route.h>
70 #include <net/pf_mtag.h>
71 #include <netinet/in.h>
72 #include <netinet/in_systm.h>
73 #include <netinet/in_var.h>
74 #include <netinet/in_pcb.h>
75 #include <netinet/ip.h>
76 #include <netinet/ip_var.h>
77 #include <netinet/ip_icmp.h>
78 #include <netinet/ip_fw.h>
79 #include <netinet/ip_divert.h>
80 #include <netinet/ip_dummynet.h>
81 #include <netinet/ip_carp.h>
82 #include <netinet/pim.h>
83 #include <netinet/tcp.h>
84 #include <netinet/tcp_timer.h>
85 #include <netinet/tcp_var.h>
86 #include <netinet/tcpip.h>
87 #include <netinet/udp.h>
88 #include <netinet/udp_var.h>
89 #include <netinet/sctp.h>
91 #include <netinet/libalias/alias.h>
92 #include <netinet/libalias/alias_local.h>
94 #include <netgraph/ng_ipfw.h>
96 #include <altq/if_altq.h>
98 #include <netinet/ip6.h>
99 #include <netinet/icmp6.h>
101 #include <netinet6/scope6_var.h>
104 #include <netinet/if_ether.h> /* XXX for ETHERTYPE_IP */
106 #include <machine/in_cksum.h> /* XXX for in_cksum */
108 #include <security/mac/mac_framework.h>
111 * set_disable contains one bit per set value (0..31).
112 * If the bit is set, all rules with the corresponding set
113 * are disabled. Set RESVD_SET(31) is reserved for the default rule
114 * and rules that are not deleted by the flush command,
115 * and CANNOT be disabled.
116 * Rules in set RESVD_SET can only be deleted explicitly.
118 static u_int32_t set_disable;
120 static int fw_verbose;
121 static int verbose_limit;
123 static struct callout ipfw_timeout;
124 static uma_zone_t ipfw_dyn_rule_zone;
125 #define IPFW_DEFAULT_RULE 65535
128 * Data structure to cache our ucred related
129 * information. This structure only gets used if
130 * the user specified UID/GID based constraints in
134 gid_t fw_groups[NGROUPS];
140 #define IPFW_TABLES_MAX 128
142 struct ip_fw *rules; /* list of rules */
143 struct ip_fw *reap; /* list of rules to reap */
144 LIST_HEAD(, cfg_nat) nat; /* list of nat entries */
145 struct radix_node_head *tables[IPFW_TABLES_MAX];
148 #define IPFW_LOCK_INIT(_chain) \
149 rw_init(&(_chain)->rwmtx, "IPFW static rules")
150 #define IPFW_LOCK_DESTROY(_chain) rw_destroy(&(_chain)->rwmtx)
151 #define IPFW_WLOCK_ASSERT(_chain) rw_assert(&(_chain)->rwmtx, RA_WLOCKED)
153 #define IPFW_RLOCK(p) rw_rlock(&(p)->rwmtx)
154 #define IPFW_RUNLOCK(p) rw_runlock(&(p)->rwmtx)
155 #define IPFW_WLOCK(p) rw_wlock(&(p)->rwmtx)
156 #define IPFW_WUNLOCK(p) rw_wunlock(&(p)->rwmtx)
159 * list of rules for layer 3
161 static struct ip_fw_chain layer3_chain;
163 MALLOC_DEFINE(M_IPFW, "IpFw/IpAcct", "IpFw/IpAcct chain's");
164 MALLOC_DEFINE(M_IPFW_TBL, "ipfw_tbl", "IpFw tables");
167 struct radix_node rn[2];
168 struct sockaddr_in addr, mask;
172 static int fw_debug = 1;
173 static int autoinc_step = 100; /* bounded to 1..1000 in add_rule() */
175 extern int ipfw_chg_hook(SYSCTL_HANDLER_ARGS);
178 SYSCTL_NODE(_net_inet_ip, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall");
179 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, enable,
180 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE3, &fw_enable, 0,
181 ipfw_chg_hook, "I", "Enable ipfw");
182 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, autoinc_step, CTLFLAG_RW,
183 &autoinc_step, 0, "Rule number autincrement step");
184 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, one_pass,
185 CTLFLAG_RW | CTLFLAG_SECURE3,
187 "Only do a single pass through ipfw when using dummynet(4)");
188 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, debug, CTLFLAG_RW,
189 &fw_debug, 0, "Enable printing of debug ip_fw statements");
190 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose,
191 CTLFLAG_RW | CTLFLAG_SECURE3,
192 &fw_verbose, 0, "Log matches to ipfw rules");
193 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose_limit, CTLFLAG_RW,
194 &verbose_limit, 0, "Set upper limit of matches of ipfw rules logged");
197 * Description of dynamic rules.
199 * Dynamic rules are stored in lists accessed through a hash table
200 * (ipfw_dyn_v) whose size is curr_dyn_buckets. This value can
201 * be modified through the sysctl variable dyn_buckets which is
202 * updated when the table becomes empty.
204 * XXX currently there is only one list, ipfw_dyn.
206 * When a packet is received, its address fields are first masked
207 * with the mask defined for the rule, then hashed, then matched
208 * against the entries in the corresponding list.
209 * Dynamic rules can be used for different purposes:
211 * + enforcing limits on the number of sessions;
212 * + in-kernel NAT (not implemented yet)
214 * The lifetime of dynamic rules is regulated by dyn_*_lifetime,
215 * measured in seconds and depending on the flags.
217 * The total number of dynamic rules is stored in dyn_count.
218 * The max number of dynamic rules is dyn_max. When we reach
219 * the maximum number of rules we do not create anymore. This is
220 * done to avoid consuming too much memory, but also too much
221 * time when searching on each packet (ideally, we should try instead
222 * to put a limit on the length of the list on each bucket...).
224 * Each dynamic rule holds a pointer to the parent ipfw rule so
225 * we know what action to perform. Dynamic rules are removed when
226 * the parent rule is deleted. XXX we should make them survive.
228 * There are some limitations with dynamic rules -- we do not
229 * obey the 'randomized match', and we do not do multiple
230 * passes through the firewall. XXX check the latter!!!
232 static ipfw_dyn_rule **ipfw_dyn_v = NULL;
233 static u_int32_t dyn_buckets = 256; /* must be power of 2 */
234 static u_int32_t curr_dyn_buckets = 256; /* must be power of 2 */
236 static struct mtx ipfw_dyn_mtx; /* mutex guarding dynamic rules */
237 #define IPFW_DYN_LOCK_INIT() \
238 mtx_init(&ipfw_dyn_mtx, "IPFW dynamic rules", NULL, MTX_DEF)
239 #define IPFW_DYN_LOCK_DESTROY() mtx_destroy(&ipfw_dyn_mtx)
240 #define IPFW_DYN_LOCK() mtx_lock(&ipfw_dyn_mtx)
241 #define IPFW_DYN_UNLOCK() mtx_unlock(&ipfw_dyn_mtx)
242 #define IPFW_DYN_LOCK_ASSERT() mtx_assert(&ipfw_dyn_mtx, MA_OWNED)
245 * Timeouts for various events in handing dynamic rules.
247 static u_int32_t dyn_ack_lifetime = 300;
248 static u_int32_t dyn_syn_lifetime = 20;
249 static u_int32_t dyn_fin_lifetime = 1;
250 static u_int32_t dyn_rst_lifetime = 1;
251 static u_int32_t dyn_udp_lifetime = 10;
252 static u_int32_t dyn_short_lifetime = 5;
255 * Keepalives are sent if dyn_keepalive is set. They are sent every
256 * dyn_keepalive_period seconds, in the last dyn_keepalive_interval
257 * seconds of lifetime of a rule.
258 * dyn_rst_lifetime and dyn_fin_lifetime should be strictly lower
259 * than dyn_keepalive_period.
262 static u_int32_t dyn_keepalive_interval = 20;
263 static u_int32_t dyn_keepalive_period = 5;
264 static u_int32_t dyn_keepalive = 1; /* do send keepalives */
266 static u_int32_t static_count; /* # of static rules */
267 static u_int32_t static_len; /* size in bytes of static rules */
268 static u_int32_t dyn_count; /* # of dynamic rules */
269 static u_int32_t dyn_max = 4096; /* max # of dynamic rules */
271 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_buckets, CTLFLAG_RW,
272 &dyn_buckets, 0, "Number of dyn. buckets");
273 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, curr_dyn_buckets, CTLFLAG_RD,
274 &curr_dyn_buckets, 0, "Current Number of dyn. buckets");
275 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_count, CTLFLAG_RD,
276 &dyn_count, 0, "Number of dyn. rules");
277 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_max, CTLFLAG_RW,
278 &dyn_max, 0, "Max number of dyn. rules");
279 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, static_count, CTLFLAG_RD,
280 &static_count, 0, "Number of static rules");
281 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_ack_lifetime, CTLFLAG_RW,
282 &dyn_ack_lifetime, 0, "Lifetime of dyn. rules for acks");
283 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_syn_lifetime, CTLFLAG_RW,
284 &dyn_syn_lifetime, 0, "Lifetime of dyn. rules for syn");
285 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_fin_lifetime, CTLFLAG_RW,
286 &dyn_fin_lifetime, 0, "Lifetime of dyn. rules for fin");
287 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_rst_lifetime, CTLFLAG_RW,
288 &dyn_rst_lifetime, 0, "Lifetime of dyn. rules for rst");
289 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_udp_lifetime, CTLFLAG_RW,
290 &dyn_udp_lifetime, 0, "Lifetime of dyn. rules for UDP");
291 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_short_lifetime, CTLFLAG_RW,
292 &dyn_short_lifetime, 0, "Lifetime of dyn. rules for other situations");
293 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_keepalive, CTLFLAG_RW,
294 &dyn_keepalive, 0, "Enable keepalives for dyn. rules");
298 * IPv6 specific variables
300 SYSCTL_DECL(_net_inet6_ip6);
302 static struct sysctl_ctx_list ip6_fw_sysctl_ctx;
303 static struct sysctl_oid *ip6_fw_sysctl_tree;
305 #endif /* SYSCTL_NODE */
307 #ifdef IPFIREWALL_NAT
308 MODULE_DEPEND(ipfw, libalias, 1, 1, 1);
310 static int fw_deny_unknown_exthdrs = 1;
314 * L3HDR maps an ipv4 pointer into a layer3 header pointer of type T
315 * Other macros just cast void * into the appropriate type
317 #define L3HDR(T, ip) ((T *)((u_int32_t *)(ip) + (ip)->ip_hl))
318 #define TCP(p) ((struct tcphdr *)(p))
319 #define SCTP(p) ((struct sctphdr *)(p))
320 #define UDP(p) ((struct udphdr *)(p))
321 #define ICMP(p) ((struct icmphdr *)(p))
322 #define ICMP6(p) ((struct icmp6_hdr *)(p))
325 icmptype_match(struct icmphdr *icmp, ipfw_insn_u32 *cmd)
327 int type = icmp->icmp_type;
329 return (type <= ICMP_MAXTYPE && (cmd->d[0] & (1<<type)) );
332 #define TT ( (1 << ICMP_ECHO) | (1 << ICMP_ROUTERSOLICIT) | \
333 (1 << ICMP_TSTAMP) | (1 << ICMP_IREQ) | (1 << ICMP_MASKREQ) )
336 is_icmp_query(struct icmphdr *icmp)
338 int type = icmp->icmp_type;
340 return (type <= ICMP_MAXTYPE && (TT & (1<<type)) );
345 * The following checks use two arrays of 8 or 16 bits to store the
346 * bits that we want set or clear, respectively. They are in the
347 * low and high half of cmd->arg1 or cmd->d[0].
349 * We scan options and store the bits we find set. We succeed if
351 * (want_set & ~bits) == 0 && (want_clear & ~bits) == want_clear
353 * The code is sometimes optimized not to store additional variables.
357 flags_match(ipfw_insn *cmd, u_int8_t bits)
362 if ( ((cmd->arg1 & 0xff) & bits) != 0)
363 return 0; /* some bits we want set were clear */
364 want_clear = (cmd->arg1 >> 8) & 0xff;
365 if ( (want_clear & bits) != want_clear)
366 return 0; /* some bits we want clear were set */
371 ipopts_match(struct ip *ip, ipfw_insn *cmd)
373 int optlen, bits = 0;
374 u_char *cp = (u_char *)(ip + 1);
375 int x = (ip->ip_hl << 2) - sizeof (struct ip);
377 for (; x > 0; x -= optlen, cp += optlen) {
378 int opt = cp[IPOPT_OPTVAL];
380 if (opt == IPOPT_EOL)
382 if (opt == IPOPT_NOP)
385 optlen = cp[IPOPT_OLEN];
386 if (optlen <= 0 || optlen > x)
387 return 0; /* invalid or truncated */
395 bits |= IP_FW_IPOPT_LSRR;
399 bits |= IP_FW_IPOPT_SSRR;
403 bits |= IP_FW_IPOPT_RR;
407 bits |= IP_FW_IPOPT_TS;
411 return (flags_match(cmd, bits));
415 tcpopts_match(struct tcphdr *tcp, ipfw_insn *cmd)
417 int optlen, bits = 0;
418 u_char *cp = (u_char *)(tcp + 1);
419 int x = (tcp->th_off << 2) - sizeof(struct tcphdr);
421 for (; x > 0; x -= optlen, cp += optlen) {
423 if (opt == TCPOPT_EOL)
425 if (opt == TCPOPT_NOP)
439 bits |= IP_FW_TCPOPT_MSS;
443 bits |= IP_FW_TCPOPT_WINDOW;
446 case TCPOPT_SACK_PERMITTED:
448 bits |= IP_FW_TCPOPT_SACK;
451 case TCPOPT_TIMESTAMP:
452 bits |= IP_FW_TCPOPT_TS;
457 return (flags_match(cmd, bits));
461 iface_match(struct ifnet *ifp, ipfw_insn_if *cmd)
463 if (ifp == NULL) /* no iface with this packet, match fails */
465 /* Check by name or by IP address */
466 if (cmd->name[0] != '\0') { /* match by name */
469 if (fnmatch(cmd->name, ifp->if_xname, 0) == 0)
472 if (strncmp(ifp->if_xname, cmd->name, IFNAMSIZ) == 0)
479 TAILQ_FOREACH(ia, &ifp->if_addrhead, ifa_link) {
480 if (ia->ifa_addr->sa_family != AF_INET)
482 if (cmd->p.ip.s_addr == ((struct sockaddr_in *)
483 (ia->ifa_addr))->sin_addr.s_addr)
484 return(1); /* match */
487 return(0); /* no match, fail ... */
491 * The verify_path function checks if a route to the src exists and
492 * if it is reachable via ifp (when provided).
494 * The 'verrevpath' option checks that the interface that an IP packet
495 * arrives on is the same interface that traffic destined for the
496 * packet's source address would be routed out of. The 'versrcreach'
497 * option just checks that the source address is reachable via any route
498 * (except default) in the routing table. These two are a measure to block
499 * forged packets. This is also commonly known as "anti-spoofing" or Unicast
500 * Reverse Path Forwarding (Unicast RFP) in Cisco-ese. The name of the knobs
501 * is purposely reminiscent of the Cisco IOS command,
503 * ip verify unicast reverse-path
504 * ip verify unicast source reachable-via any
506 * which implements the same functionality. But note that syntax is
507 * misleading. The check may be performed on all IP packets whether unicast,
508 * multicast, or broadcast.
511 verify_path(struct in_addr src, struct ifnet *ifp)
514 struct sockaddr_in *dst;
516 bzero(&ro, sizeof(ro));
518 dst = (struct sockaddr_in *)&(ro.ro_dst);
519 dst->sin_family = AF_INET;
520 dst->sin_len = sizeof(*dst);
522 rtalloc_ign(&ro, RTF_CLONING);
524 if (ro.ro_rt == NULL)
528 * If ifp is provided, check for equality with rtentry.
529 * We should use rt->rt_ifa->ifa_ifp, instead of rt->rt_ifp,
530 * in order to pass packets injected back by if_simloop():
531 * if useloopback == 1 routing entry (via lo0) for our own address
532 * may exist, so we need to handle routing assymetry.
534 if (ifp != NULL && ro.ro_rt->rt_ifa->ifa_ifp != ifp) {
539 /* if no ifp provided, check if rtentry is not default route */
541 satosin(rt_key(ro.ro_rt))->sin_addr.s_addr == INADDR_ANY) {
546 /* or if this is a blackhole/reject route */
547 if (ifp == NULL && ro.ro_rt->rt_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
552 /* found valid route */
559 * ipv6 specific rules here...
562 icmp6type_match (int type, ipfw_insn_u32 *cmd)
564 return (type <= ICMP6_MAXTYPE && (cmd->d[type/32] & (1<<(type%32)) ) );
568 flow6id_match( int curr_flow, ipfw_insn_u32 *cmd )
571 for (i=0; i <= cmd->o.arg1; ++i )
572 if (curr_flow == cmd->d[i] )
577 /* support for IP6_*_ME opcodes */
579 search_ip6_addr_net (struct in6_addr * ip6_addr)
583 struct in6_ifaddr *fdm;
584 struct in6_addr copia;
586 TAILQ_FOREACH(mdc, &ifnet, if_link)
587 TAILQ_FOREACH(mdc2, &mdc->if_addrlist, ifa_list) {
588 if (mdc2->ifa_addr->sa_family == AF_INET6) {
589 fdm = (struct in6_ifaddr *)mdc2;
590 copia = fdm->ia_addr.sin6_addr;
591 /* need for leaving scope_id in the sock_addr */
592 in6_clearscope(&copia);
593 if (IN6_ARE_ADDR_EQUAL(ip6_addr, &copia))
601 verify_path6(struct in6_addr *src, struct ifnet *ifp)
604 struct sockaddr_in6 *dst;
606 bzero(&ro, sizeof(ro));
608 dst = (struct sockaddr_in6 * )&(ro.ro_dst);
609 dst->sin6_family = AF_INET6;
610 dst->sin6_len = sizeof(*dst);
611 dst->sin6_addr = *src;
612 rtalloc_ign((struct route *)&ro, RTF_CLONING);
614 if (ro.ro_rt == NULL)
618 * if ifp is provided, check for equality with rtentry
619 * We should use rt->rt_ifa->ifa_ifp, instead of rt->rt_ifp,
620 * to support the case of sending packets to an address of our own.
621 * (where the former interface is the first argument of if_simloop()
622 * (=ifp), the latter is lo0)
624 if (ifp != NULL && ro.ro_rt->rt_ifa->ifa_ifp != ifp) {
629 /* if no ifp provided, check if rtentry is not default route */
631 IN6_IS_ADDR_UNSPECIFIED(&satosin6(rt_key(ro.ro_rt))->sin6_addr)) {
636 /* or if this is a blackhole/reject route */
637 if (ifp == NULL && ro.ro_rt->rt_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
642 /* found valid route */
648 hash_packet6(struct ipfw_flow_id *id)
651 i = (id->dst_ip6.__u6_addr.__u6_addr32[2]) ^
652 (id->dst_ip6.__u6_addr.__u6_addr32[3]) ^
653 (id->src_ip6.__u6_addr.__u6_addr32[2]) ^
654 (id->src_ip6.__u6_addr.__u6_addr32[3]) ^
655 (id->dst_port) ^ (id->src_port);
660 is_icmp6_query(int icmp6_type)
662 if ((icmp6_type <= ICMP6_MAXTYPE) &&
663 (icmp6_type == ICMP6_ECHO_REQUEST ||
664 icmp6_type == ICMP6_MEMBERSHIP_QUERY ||
665 icmp6_type == ICMP6_WRUREQUEST ||
666 icmp6_type == ICMP6_FQDN_QUERY ||
667 icmp6_type == ICMP6_NI_QUERY))
674 send_reject6(struct ip_fw_args *args, int code, u_int hlen, struct ip6_hdr *ip6)
679 if (code == ICMP6_UNREACH_RST && args->f_id.proto == IPPROTO_TCP) {
687 tcp = (struct tcphdr *)((char *)ip6 + hlen);
689 if ((tcp->th_flags & TH_RST) != 0) {
697 ti.th.th_seq = ntohl(ti.th.th_seq);
698 ti.th.th_ack = ntohl(ti.th.th_ack);
699 ti.ip6.ip6_nxt = IPPROTO_TCP;
701 if (ti.th.th_flags & TH_ACK) {
707 if ((m->m_flags & M_PKTHDR) != 0) {
709 * total new data to ACK is:
710 * total packet length,
711 * minus the header length,
712 * minus the tcp header length.
714 ack += m->m_pkthdr.len - hlen
715 - (ti.th.th_off << 2);
716 } else if (ip6->ip6_plen) {
717 ack += ntohs(ip6->ip6_plen) + sizeof(*ip6) -
718 hlen - (ti.th.th_off << 2);
723 if (tcp->th_flags & TH_SYN)
726 flags = TH_RST|TH_ACK;
728 bcopy(&ti, ip6, sizeof(ti));
730 * m is only used to recycle the mbuf
731 * The data in it is never read so we don't need
732 * to correct the offsets or anything
734 tcp_respond(NULL, ip6, tcp, m, ack, seq, flags);
735 } else if (code != ICMP6_UNREACH_RST) { /* Send an ICMPv6 unreach. */
738 * Unlike above, the mbufs need to line up with the ip6 hdr,
739 * as the contents are read. We need to m_adj() the
741 * The mbuf will however be thrown away so we can adjust it.
742 * Remember we did an m_pullup on it already so we
743 * can make some assumptions about contiguousness.
746 m_adj(m, args->L3offset);
748 icmp6_error(m, ICMP6_DST_UNREACH, code, 0);
757 static u_int64_t norule_counter; /* counter for ipfw_log(NULL...) */
759 #define SNPARGS(buf, len) buf + len, sizeof(buf) > len ? sizeof(buf) - len : 0
760 #define SNP(buf) buf, sizeof(buf)
763 * We enter here when we have a rule with O_LOG.
764 * XXX this function alone takes about 2Kbytes of code!
767 ipfw_log(struct ip_fw *f, u_int hlen, struct ip_fw_args *args,
768 struct mbuf *m, struct ifnet *oif, u_short offset, uint32_t tablearg,
771 struct ether_header *eh = args->eh;
773 int limit_reached = 0;
774 char action2[40], proto[128], fragment[32];
779 if (f == NULL) { /* bogus pkt */
780 if (verbose_limit != 0 && norule_counter >= verbose_limit)
783 if (norule_counter == verbose_limit)
784 limit_reached = verbose_limit;
786 } else { /* O_LOG is the first action, find the real one */
787 ipfw_insn *cmd = ACTION_PTR(f);
788 ipfw_insn_log *l = (ipfw_insn_log *)cmd;
790 if (l->max_log != 0 && l->log_left == 0)
793 if (l->log_left == 0)
794 limit_reached = l->max_log;
795 cmd += F_LEN(cmd); /* point to first action */
796 if (cmd->opcode == O_ALTQ) {
797 ipfw_insn_altq *altq = (ipfw_insn_altq *)cmd;
799 snprintf(SNPARGS(action2, 0), "Altq %d",
803 if (cmd->opcode == O_PROB)
806 if (cmd->opcode == O_TAG)
810 switch (cmd->opcode) {
816 if (cmd->arg1==ICMP_REJECT_RST)
818 else if (cmd->arg1==ICMP_UNREACH_HOST)
821 snprintf(SNPARGS(action2, 0), "Unreach %d",
826 if (cmd->arg1==ICMP6_UNREACH_RST)
829 snprintf(SNPARGS(action2, 0), "Unreach %d",
840 snprintf(SNPARGS(action2, 0), "Divert %d",
844 snprintf(SNPARGS(action2, 0), "Tee %d",
848 snprintf(SNPARGS(action2, 0), "SkipTo %d",
852 snprintf(SNPARGS(action2, 0), "Pipe %d",
856 snprintf(SNPARGS(action2, 0), "Queue %d",
860 ipfw_insn_sa *sa = (ipfw_insn_sa *)cmd;
862 struct in_addr dummyaddr;
863 if (sa->sa.sin_addr.s_addr == INADDR_ANY)
864 dummyaddr.s_addr = htonl(tablearg);
866 dummyaddr.s_addr = sa->sa.sin_addr.s_addr;
868 len = snprintf(SNPARGS(action2, 0), "Forward to %s",
869 inet_ntoa(dummyaddr));
872 snprintf(SNPARGS(action2, len), ":%d",
877 snprintf(SNPARGS(action2, 0), "Netgraph %d",
881 snprintf(SNPARGS(action2, 0), "Ngtee %d",
893 if (hlen == 0) { /* non-ip */
894 snprintf(SNPARGS(proto, 0), "MAC");
898 char src[48], dst[48];
899 struct icmphdr *icmp;
903 struct ip6_hdr *ip6 = NULL;
904 struct icmp6_hdr *icmp6;
909 if (IS_IP6_FLOW_ID(&(args->f_id))) {
910 char ip6buf[INET6_ADDRSTRLEN];
911 snprintf(src, sizeof(src), "[%s]",
912 ip6_sprintf(ip6buf, &args->f_id.src_ip6));
913 snprintf(dst, sizeof(dst), "[%s]",
914 ip6_sprintf(ip6buf, &args->f_id.dst_ip6));
916 ip6 = (struct ip6_hdr *)ip;
917 tcp = (struct tcphdr *)(((char *)ip) + hlen);
918 udp = (struct udphdr *)(((char *)ip) + hlen);
922 tcp = L3HDR(struct tcphdr, ip);
923 udp = L3HDR(struct udphdr, ip);
925 inet_ntoa_r(ip->ip_src, src);
926 inet_ntoa_r(ip->ip_dst, dst);
929 switch (args->f_id.proto) {
931 len = snprintf(SNPARGS(proto, 0), "TCP %s", src);
933 snprintf(SNPARGS(proto, len), ":%d %s:%d",
934 ntohs(tcp->th_sport),
936 ntohs(tcp->th_dport));
938 snprintf(SNPARGS(proto, len), " %s", dst);
942 len = snprintf(SNPARGS(proto, 0), "UDP %s", src);
944 snprintf(SNPARGS(proto, len), ":%d %s:%d",
945 ntohs(udp->uh_sport),
947 ntohs(udp->uh_dport));
949 snprintf(SNPARGS(proto, len), " %s", dst);
953 icmp = L3HDR(struct icmphdr, ip);
955 len = snprintf(SNPARGS(proto, 0),
957 icmp->icmp_type, icmp->icmp_code);
959 len = snprintf(SNPARGS(proto, 0), "ICMP ");
960 len += snprintf(SNPARGS(proto, len), "%s", src);
961 snprintf(SNPARGS(proto, len), " %s", dst);
965 icmp6 = (struct icmp6_hdr *)(((char *)ip) + hlen);
967 len = snprintf(SNPARGS(proto, 0),
969 icmp6->icmp6_type, icmp6->icmp6_code);
971 len = snprintf(SNPARGS(proto, 0), "ICMPv6 ");
972 len += snprintf(SNPARGS(proto, len), "%s", src);
973 snprintf(SNPARGS(proto, len), " %s", dst);
977 len = snprintf(SNPARGS(proto, 0), "P:%d %s",
978 args->f_id.proto, src);
979 snprintf(SNPARGS(proto, len), " %s", dst);
984 if (IS_IP6_FLOW_ID(&(args->f_id))) {
985 if (offset & (IP6F_OFF_MASK | IP6F_MORE_FRAG))
986 snprintf(SNPARGS(fragment, 0),
987 " (frag %08x:%d@%d%s)",
989 ntohs(ip6->ip6_plen) - hlen,
990 ntohs(offset & IP6F_OFF_MASK) << 3,
991 (offset & IP6F_MORE_FRAG) ? "+" : "");
996 if (eh != NULL) { /* layer 2 packets are as on the wire */
997 ip_off = ntohs(ip->ip_off);
998 ip_len = ntohs(ip->ip_len);
1000 ip_off = ip->ip_off;
1001 ip_len = ip->ip_len;
1003 if (ip_off & (IP_MF | IP_OFFMASK))
1004 snprintf(SNPARGS(fragment, 0),
1005 " (frag %d:%d@%d%s)",
1006 ntohs(ip->ip_id), ip_len - (ip->ip_hl << 2),
1008 (ip_off & IP_MF) ? "+" : "");
1011 if (oif || m->m_pkthdr.rcvif)
1012 log(LOG_SECURITY | LOG_INFO,
1013 "ipfw: %d %s %s %s via %s%s\n",
1014 f ? f->rulenum : -1,
1015 action, proto, oif ? "out" : "in",
1016 oif ? oif->if_xname : m->m_pkthdr.rcvif->if_xname,
1019 log(LOG_SECURITY | LOG_INFO,
1020 "ipfw: %d %s %s [no if info]%s\n",
1021 f ? f->rulenum : -1,
1022 action, proto, fragment);
1024 log(LOG_SECURITY | LOG_NOTICE,
1025 "ipfw: limit %d reached on entry %d\n",
1026 limit_reached, f ? f->rulenum : -1);
1030 * IMPORTANT: the hash function for dynamic rules must be commutative
1031 * in source and destination (ip,port), because rules are bidirectional
1032 * and we want to find both in the same bucket.
1035 hash_packet(struct ipfw_flow_id *id)
1040 if (IS_IP6_FLOW_ID(id))
1041 i = hash_packet6(id);
1044 i = (id->dst_ip) ^ (id->src_ip) ^ (id->dst_port) ^ (id->src_port);
1045 i &= (curr_dyn_buckets - 1);
1050 * unlink a dynamic rule from a chain. prev is a pointer to
1051 * the previous one, q is a pointer to the rule to delete,
1052 * head is a pointer to the head of the queue.
1053 * Modifies q and potentially also head.
1055 #define UNLINK_DYN_RULE(prev, head, q) { \
1056 ipfw_dyn_rule *old_q = q; \
1058 /* remove a refcount to the parent */ \
1059 if (q->dyn_type == O_LIMIT) \
1060 q->parent->count--; \
1061 DEB(printf("ipfw: unlink entry 0x%08x %d -> 0x%08x %d, %d left\n",\
1062 (q->id.src_ip), (q->id.src_port), \
1063 (q->id.dst_ip), (q->id.dst_port), dyn_count-1 ); ) \
1065 prev->next = q = q->next; \
1067 head = q = q->next; \
1069 uma_zfree(ipfw_dyn_rule_zone, old_q); }
1071 #define TIME_LEQ(a,b) ((int)((a)-(b)) <= 0)
1074 * Remove dynamic rules pointing to "rule", or all of them if rule == NULL.
1076 * If keep_me == NULL, rules are deleted even if not expired,
1077 * otherwise only expired rules are removed.
1079 * The value of the second parameter is also used to point to identify
1080 * a rule we absolutely do not want to remove (e.g. because we are
1081 * holding a reference to it -- this is the case with O_LIMIT_PARENT
1082 * rules). The pointer is only used for comparison, so any non-null
1086 remove_dyn_rule(struct ip_fw *rule, ipfw_dyn_rule *keep_me)
1088 static u_int32_t last_remove = 0;
1090 #define FORCE (keep_me == NULL)
1092 ipfw_dyn_rule *prev, *q;
1093 int i, pass = 0, max_pass = 0;
1095 IPFW_DYN_LOCK_ASSERT();
1097 if (ipfw_dyn_v == NULL || dyn_count == 0)
1099 /* do not expire more than once per second, it is useless */
1100 if (!FORCE && last_remove == time_uptime)
1102 last_remove = time_uptime;
1105 * because O_LIMIT refer to parent rules, during the first pass only
1106 * remove child and mark any pending LIMIT_PARENT, and remove
1107 * them in a second pass.
1110 for (i = 0 ; i < curr_dyn_buckets ; i++) {
1111 for (prev=NULL, q = ipfw_dyn_v[i] ; q ; ) {
1113 * Logic can become complex here, so we split tests.
1117 if (rule != NULL && rule != q->rule)
1118 goto next; /* not the one we are looking for */
1119 if (q->dyn_type == O_LIMIT_PARENT) {
1121 * handle parent in the second pass,
1122 * record we need one.
1127 if (FORCE && q->count != 0 ) {
1128 /* XXX should not happen! */
1129 printf("ipfw: OUCH! cannot remove rule,"
1130 " count %d\n", q->count);
1134 !TIME_LEQ( q->expire, time_uptime ))
1137 if (q->dyn_type != O_LIMIT_PARENT || !q->count) {
1138 UNLINK_DYN_RULE(prev, ipfw_dyn_v[i], q);
1146 if (pass++ < max_pass)
1152 * lookup a dynamic rule.
1154 static ipfw_dyn_rule *
1155 lookup_dyn_rule_locked(struct ipfw_flow_id *pkt, int *match_direction,
1159 * stateful ipfw extensions.
1160 * Lookup into dynamic session queue
1162 #define MATCH_REVERSE 0
1163 #define MATCH_FORWARD 1
1164 #define MATCH_NONE 2
1165 #define MATCH_UNKNOWN 3
1166 int i, dir = MATCH_NONE;
1167 ipfw_dyn_rule *prev, *q=NULL;
1169 IPFW_DYN_LOCK_ASSERT();
1171 if (ipfw_dyn_v == NULL)
1172 goto done; /* not found */
1173 i = hash_packet( pkt );
1174 for (prev=NULL, q = ipfw_dyn_v[i] ; q != NULL ; ) {
1175 if (q->dyn_type == O_LIMIT_PARENT && q->count)
1177 if (TIME_LEQ( q->expire, time_uptime)) { /* expire entry */
1178 UNLINK_DYN_RULE(prev, ipfw_dyn_v[i], q);
1181 if (pkt->proto == q->id.proto &&
1182 q->dyn_type != O_LIMIT_PARENT) {
1183 if (IS_IP6_FLOW_ID(pkt)) {
1184 if (IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
1185 &(q->id.src_ip6)) &&
1186 IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
1187 &(q->id.dst_ip6)) &&
1188 pkt->src_port == q->id.src_port &&
1189 pkt->dst_port == q->id.dst_port ) {
1190 dir = MATCH_FORWARD;
1193 if (IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
1194 &(q->id.dst_ip6)) &&
1195 IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
1196 &(q->id.src_ip6)) &&
1197 pkt->src_port == q->id.dst_port &&
1198 pkt->dst_port == q->id.src_port ) {
1199 dir = MATCH_REVERSE;
1203 if (pkt->src_ip == q->id.src_ip &&
1204 pkt->dst_ip == q->id.dst_ip &&
1205 pkt->src_port == q->id.src_port &&
1206 pkt->dst_port == q->id.dst_port ) {
1207 dir = MATCH_FORWARD;
1210 if (pkt->src_ip == q->id.dst_ip &&
1211 pkt->dst_ip == q->id.src_ip &&
1212 pkt->src_port == q->id.dst_port &&
1213 pkt->dst_port == q->id.src_port ) {
1214 dir = MATCH_REVERSE;
1224 goto done; /* q = NULL, not found */
1226 if ( prev != NULL) { /* found and not in front */
1227 prev->next = q->next;
1228 q->next = ipfw_dyn_v[i];
1231 if (pkt->proto == IPPROTO_TCP) { /* update state according to flags */
1232 u_char flags = pkt->flags & (TH_FIN|TH_SYN|TH_RST);
1234 #define BOTH_SYN (TH_SYN | (TH_SYN << 8))
1235 #define BOTH_FIN (TH_FIN | (TH_FIN << 8))
1236 q->state |= (dir == MATCH_FORWARD ) ? flags : (flags << 8);
1238 case TH_SYN: /* opening */
1239 q->expire = time_uptime + dyn_syn_lifetime;
1242 case BOTH_SYN: /* move to established */
1243 case BOTH_SYN | TH_FIN : /* one side tries to close */
1244 case BOTH_SYN | (TH_FIN << 8) :
1246 #define _SEQ_GE(a,b) ((int)(a) - (int)(b) >= 0)
1247 u_int32_t ack = ntohl(tcp->th_ack);
1248 if (dir == MATCH_FORWARD) {
1249 if (q->ack_fwd == 0 || _SEQ_GE(ack, q->ack_fwd))
1251 else { /* ignore out-of-sequence */
1255 if (q->ack_rev == 0 || _SEQ_GE(ack, q->ack_rev))
1257 else { /* ignore out-of-sequence */
1262 q->expire = time_uptime + dyn_ack_lifetime;
1265 case BOTH_SYN | BOTH_FIN: /* both sides closed */
1266 if (dyn_fin_lifetime >= dyn_keepalive_period)
1267 dyn_fin_lifetime = dyn_keepalive_period - 1;
1268 q->expire = time_uptime + dyn_fin_lifetime;
1274 * reset or some invalid combination, but can also
1275 * occur if we use keep-state the wrong way.
1277 if ( (q->state & ((TH_RST << 8)|TH_RST)) == 0)
1278 printf("invalid state: 0x%x\n", q->state);
1280 if (dyn_rst_lifetime >= dyn_keepalive_period)
1281 dyn_rst_lifetime = dyn_keepalive_period - 1;
1282 q->expire = time_uptime + dyn_rst_lifetime;
1285 } else if (pkt->proto == IPPROTO_UDP) {
1286 q->expire = time_uptime + dyn_udp_lifetime;
1288 /* other protocols */
1289 q->expire = time_uptime + dyn_short_lifetime;
1292 if (match_direction)
1293 *match_direction = dir;
1297 static ipfw_dyn_rule *
1298 lookup_dyn_rule(struct ipfw_flow_id *pkt, int *match_direction,
1304 q = lookup_dyn_rule_locked(pkt, match_direction, tcp);
1307 /* NB: return table locked when q is not NULL */
1312 realloc_dynamic_table(void)
1314 IPFW_DYN_LOCK_ASSERT();
1317 * Try reallocation, make sure we have a power of 2 and do
1318 * not allow more than 64k entries. In case of overflow,
1322 if (dyn_buckets > 65536)
1324 if ((dyn_buckets & (dyn_buckets-1)) != 0) { /* not a power of 2 */
1325 dyn_buckets = curr_dyn_buckets; /* reset */
1328 curr_dyn_buckets = dyn_buckets;
1329 if (ipfw_dyn_v != NULL)
1330 free(ipfw_dyn_v, M_IPFW);
1332 ipfw_dyn_v = malloc(curr_dyn_buckets * sizeof(ipfw_dyn_rule *),
1333 M_IPFW, M_NOWAIT | M_ZERO);
1334 if (ipfw_dyn_v != NULL || curr_dyn_buckets <= 2)
1336 curr_dyn_buckets /= 2;
1341 * Install state of type 'type' for a dynamic session.
1342 * The hash table contains two type of rules:
1343 * - regular rules (O_KEEP_STATE)
1344 * - rules for sessions with limited number of sess per user
1345 * (O_LIMIT). When they are created, the parent is
1346 * increased by 1, and decreased on delete. In this case,
1347 * the third parameter is the parent rule and not the chain.
1348 * - "parent" rules for the above (O_LIMIT_PARENT).
1350 static ipfw_dyn_rule *
1351 add_dyn_rule(struct ipfw_flow_id *id, u_int8_t dyn_type, struct ip_fw *rule)
1356 IPFW_DYN_LOCK_ASSERT();
1358 if (ipfw_dyn_v == NULL ||
1359 (dyn_count == 0 && dyn_buckets != curr_dyn_buckets)) {
1360 realloc_dynamic_table();
1361 if (ipfw_dyn_v == NULL)
1362 return NULL; /* failed ! */
1364 i = hash_packet(id);
1366 r = uma_zalloc(ipfw_dyn_rule_zone, M_NOWAIT | M_ZERO);
1368 printf ("ipfw: sorry cannot allocate state\n");
1372 /* increase refcount on parent, and set pointer */
1373 if (dyn_type == O_LIMIT) {
1374 ipfw_dyn_rule *parent = (ipfw_dyn_rule *)rule;
1375 if ( parent->dyn_type != O_LIMIT_PARENT)
1376 panic("invalid parent");
1379 rule = parent->rule;
1383 r->expire = time_uptime + dyn_syn_lifetime;
1385 r->dyn_type = dyn_type;
1386 r->pcnt = r->bcnt = 0;
1390 r->next = ipfw_dyn_v[i];
1393 DEB(printf("ipfw: add dyn entry ty %d 0x%08x %d -> 0x%08x %d, total %d\n",
1395 (r->id.src_ip), (r->id.src_port),
1396 (r->id.dst_ip), (r->id.dst_port),
1402 * lookup dynamic parent rule using pkt and rule as search keys.
1403 * If the lookup fails, then install one.
1405 static ipfw_dyn_rule *
1406 lookup_dyn_parent(struct ipfw_flow_id *pkt, struct ip_fw *rule)
1411 IPFW_DYN_LOCK_ASSERT();
1414 int is_v6 = IS_IP6_FLOW_ID(pkt);
1415 i = hash_packet( pkt );
1416 for (q = ipfw_dyn_v[i] ; q != NULL ; q=q->next)
1417 if (q->dyn_type == O_LIMIT_PARENT &&
1419 pkt->proto == q->id.proto &&
1420 pkt->src_port == q->id.src_port &&
1421 pkt->dst_port == q->id.dst_port &&
1424 IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
1425 &(q->id.src_ip6)) &&
1426 IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
1427 &(q->id.dst_ip6))) ||
1429 pkt->src_ip == q->id.src_ip &&
1430 pkt->dst_ip == q->id.dst_ip)
1433 q->expire = time_uptime + dyn_short_lifetime;
1434 DEB(printf("ipfw: lookup_dyn_parent found 0x%p\n",q);)
1438 return add_dyn_rule(pkt, O_LIMIT_PARENT, rule);
1442 * Install dynamic state for rule type cmd->o.opcode
1444 * Returns 1 (failure) if state is not installed because of errors or because
1445 * session limitations are enforced.
1448 install_state(struct ip_fw *rule, ipfw_insn_limit *cmd,
1449 struct ip_fw_args *args, uint32_t tablearg)
1451 static int last_log;
1454 char src[48], dst[48];
1460 printf("ipfw: %s: type %d 0x%08x %u -> 0x%08x %u\n",
1461 __func__, cmd->o.opcode,
1462 (args->f_id.src_ip), (args->f_id.src_port),
1463 (args->f_id.dst_ip), (args->f_id.dst_port));
1468 q = lookup_dyn_rule_locked(&args->f_id, NULL, NULL);
1470 if (q != NULL) { /* should never occur */
1471 if (last_log != time_uptime) {
1472 last_log = time_uptime;
1473 printf("ipfw: %s: entry already present, done\n",
1480 if (dyn_count >= dyn_max)
1481 /* Run out of slots, try to remove any expired rule. */
1482 remove_dyn_rule(NULL, (ipfw_dyn_rule *)1);
1484 if (dyn_count >= dyn_max) {
1485 if (last_log != time_uptime) {
1486 last_log = time_uptime;
1487 printf("ipfw: %s: Too many dynamic rules\n", __func__);
1490 return (1); /* cannot install, notify caller */
1493 switch (cmd->o.opcode) {
1494 case O_KEEP_STATE: /* bidir rule */
1495 add_dyn_rule(&args->f_id, O_KEEP_STATE, rule);
1498 case O_LIMIT: { /* limit number of sessions */
1499 struct ipfw_flow_id id;
1500 ipfw_dyn_rule *parent;
1501 uint32_t conn_limit;
1502 uint16_t limit_mask = cmd->limit_mask;
1504 conn_limit = (cmd->conn_limit == IP_FW_TABLEARG) ?
1505 tablearg : cmd->conn_limit;
1508 if (cmd->conn_limit == IP_FW_TABLEARG)
1509 printf("ipfw: %s: O_LIMIT rule, conn_limit: %u "
1510 "(tablearg)\n", __func__, conn_limit);
1512 printf("ipfw: %s: O_LIMIT rule, conn_limit: %u\n",
1513 __func__, conn_limit);
1516 id.dst_ip = id.src_ip = id.dst_port = id.src_port = 0;
1517 id.proto = args->f_id.proto;
1518 id.addr_type = args->f_id.addr_type;
1520 if (IS_IP6_FLOW_ID (&(args->f_id))) {
1521 if (limit_mask & DYN_SRC_ADDR)
1522 id.src_ip6 = args->f_id.src_ip6;
1523 if (limit_mask & DYN_DST_ADDR)
1524 id.dst_ip6 = args->f_id.dst_ip6;
1526 if (limit_mask & DYN_SRC_ADDR)
1527 id.src_ip = args->f_id.src_ip;
1528 if (limit_mask & DYN_DST_ADDR)
1529 id.dst_ip = args->f_id.dst_ip;
1531 if (limit_mask & DYN_SRC_PORT)
1532 id.src_port = args->f_id.src_port;
1533 if (limit_mask & DYN_DST_PORT)
1534 id.dst_port = args->f_id.dst_port;
1535 if ((parent = lookup_dyn_parent(&id, rule)) == NULL) {
1536 printf("ipfw: %s: add parent failed\n", __func__);
1541 if (parent->count >= conn_limit) {
1542 /* See if we can remove some expired rule. */
1543 remove_dyn_rule(rule, parent);
1544 if (parent->count >= conn_limit) {
1545 if (fw_verbose && last_log != time_uptime) {
1546 last_log = time_uptime;
1549 * XXX IPv6 flows are not
1552 if (IS_IP6_FLOW_ID(&(args->f_id))) {
1553 char ip6buf[INET6_ADDRSTRLEN];
1554 snprintf(src, sizeof(src),
1555 "[%s]", ip6_sprintf(ip6buf,
1556 &args->f_id.src_ip6));
1557 snprintf(dst, sizeof(dst),
1558 "[%s]", ip6_sprintf(ip6buf,
1559 &args->f_id.dst_ip6));
1564 htonl(args->f_id.src_ip);
1565 inet_ntoa_r(da, src);
1567 htonl(args->f_id.dst_ip);
1568 inet_ntoa_r(da, dst);
1570 log(LOG_SECURITY | LOG_DEBUG,
1571 "ipfw: %d %s %s:%u -> %s:%u, %s\n",
1572 parent->rule->rulenum,
1574 src, (args->f_id.src_port),
1575 dst, (args->f_id.dst_port),
1576 "too many entries");
1582 add_dyn_rule(&args->f_id, O_LIMIT, (struct ip_fw *)parent);
1586 printf("ipfw: %s: unknown dynamic rule type %u\n",
1587 __func__, cmd->o.opcode);
1592 /* XXX just set lifetime */
1593 lookup_dyn_rule_locked(&args->f_id, NULL, NULL);
1600 * Generate a TCP packet, containing either a RST or a keepalive.
1601 * When flags & TH_RST, we are sending a RST packet, because of a
1602 * "reset" action matched the packet.
1603 * Otherwise we are sending a keepalive, and flags & TH_
1604 * The 'replyto' mbuf is the mbuf being replied to, if any, and is required
1605 * so that MAC can label the reply appropriately.
1607 static struct mbuf *
1608 send_pkt(struct mbuf *replyto, struct ipfw_flow_id *id, u_int32_t seq,
1609 u_int32_t ack, int flags)
1615 MGETHDR(m, M_DONTWAIT, MT_DATA);
1618 m->m_pkthdr.rcvif = (struct ifnet *)0;
1621 if (replyto != NULL)
1622 mac_mbuf_create_netlayer(replyto, m);
1624 mac_mbuf_create_from_firewall(m);
1626 (void)replyto; /* don't warn about unused arg */
1629 m->m_pkthdr.len = m->m_len = sizeof(struct ip) + sizeof(struct tcphdr);
1630 m->m_data += max_linkhdr;
1632 ip = mtod(m, struct ip *);
1633 bzero(ip, m->m_len);
1634 tcp = (struct tcphdr *)(ip + 1); /* no IP options */
1635 ip->ip_p = IPPROTO_TCP;
1638 * Assume we are sending a RST (or a keepalive in the reverse
1639 * direction), swap src and destination addresses and ports.
1641 ip->ip_src.s_addr = htonl(id->dst_ip);
1642 ip->ip_dst.s_addr = htonl(id->src_ip);
1643 tcp->th_sport = htons(id->dst_port);
1644 tcp->th_dport = htons(id->src_port);
1645 if (flags & TH_RST) { /* we are sending a RST */
1646 if (flags & TH_ACK) {
1647 tcp->th_seq = htonl(ack);
1648 tcp->th_ack = htonl(0);
1649 tcp->th_flags = TH_RST;
1653 tcp->th_seq = htonl(0);
1654 tcp->th_ack = htonl(seq);
1655 tcp->th_flags = TH_RST | TH_ACK;
1659 * We are sending a keepalive. flags & TH_SYN determines
1660 * the direction, forward if set, reverse if clear.
1661 * NOTE: seq and ack are always assumed to be correct
1662 * as set by the caller. This may be confusing...
1664 if (flags & TH_SYN) {
1666 * we have to rewrite the correct addresses!
1668 ip->ip_dst.s_addr = htonl(id->dst_ip);
1669 ip->ip_src.s_addr = htonl(id->src_ip);
1670 tcp->th_dport = htons(id->dst_port);
1671 tcp->th_sport = htons(id->src_port);
1673 tcp->th_seq = htonl(seq);
1674 tcp->th_ack = htonl(ack);
1675 tcp->th_flags = TH_ACK;
1678 * set ip_len to the payload size so we can compute
1679 * the tcp checksum on the pseudoheader
1680 * XXX check this, could save a couple of words ?
1682 ip->ip_len = htons(sizeof(struct tcphdr));
1683 tcp->th_sum = in_cksum(m, m->m_pkthdr.len);
1685 * now fill fields left out earlier
1687 ip->ip_ttl = ip_defttl;
1688 ip->ip_len = m->m_pkthdr.len;
1689 m->m_flags |= M_SKIP_FIREWALL;
1694 * sends a reject message, consuming the mbuf passed as an argument.
1697 send_reject(struct ip_fw_args *args, int code, int ip_len, struct ip *ip)
1701 /* XXX When ip is not guaranteed to be at mtod() we will
1702 * need to account for this */
1703 * The mbuf will however be thrown away so we can adjust it.
1704 * Remember we did an m_pullup on it already so we
1705 * can make some assumptions about contiguousness.
1708 m_adj(m, args->L3offset);
1710 if (code != ICMP_REJECT_RST) { /* Send an ICMP unreach */
1711 /* We need the IP header in host order for icmp_error(). */
1712 if (args->eh != NULL) {
1713 ip->ip_len = ntohs(ip->ip_len);
1714 ip->ip_off = ntohs(ip->ip_off);
1716 icmp_error(args->m, ICMP_UNREACH, code, 0L, 0);
1717 } else if (args->f_id.proto == IPPROTO_TCP) {
1718 struct tcphdr *const tcp =
1719 L3HDR(struct tcphdr, mtod(args->m, struct ip *));
1720 if ( (tcp->th_flags & TH_RST) == 0) {
1722 m = send_pkt(args->m, &(args->f_id),
1723 ntohl(tcp->th_seq), ntohl(tcp->th_ack),
1724 tcp->th_flags | TH_RST);
1726 ip_output(m, NULL, NULL, 0, NULL, NULL);
1736 * Given an ip_fw *, lookup_next_rule will return a pointer
1737 * to the next rule, which can be either the jump
1738 * target (for skipto instructions) or the next one in the list (in
1739 * all other cases including a missing jump target).
1740 * The result is also written in the "next_rule" field of the rule.
1741 * Backward jumps are not allowed, so start looking from the next
1744 * This never returns NULL -- in case we do not have an exact match,
1745 * the next rule is returned. When the ruleset is changed,
1746 * pointers are flushed so we are always correct.
1749 static struct ip_fw *
1750 lookup_next_rule(struct ip_fw *me)
1752 struct ip_fw *rule = NULL;
1755 /* look for action, in case it is a skipto */
1756 cmd = ACTION_PTR(me);
1757 if (cmd->opcode == O_LOG)
1759 if (cmd->opcode == O_ALTQ)
1761 if (cmd->opcode == O_TAG)
1763 if ( cmd->opcode == O_SKIPTO )
1764 for (rule = me->next; rule ; rule = rule->next)
1765 if (rule->rulenum >= cmd->arg1)
1767 if (rule == NULL) /* failure or not a skipto */
1769 me->next_rule = rule;
1774 add_table_entry(struct ip_fw_chain *ch, uint16_t tbl, in_addr_t addr,
1775 uint8_t mlen, uint32_t value)
1777 struct radix_node_head *rnh;
1778 struct table_entry *ent;
1780 if (tbl >= IPFW_TABLES_MAX)
1782 rnh = ch->tables[tbl];
1783 ent = malloc(sizeof(*ent), M_IPFW_TBL, M_NOWAIT | M_ZERO);
1787 ent->addr.sin_len = ent->mask.sin_len = 8;
1788 ent->mask.sin_addr.s_addr = htonl(mlen ? ~((1 << (32 - mlen)) - 1) : 0);
1789 ent->addr.sin_addr.s_addr = addr & ent->mask.sin_addr.s_addr;
1790 IPFW_WLOCK(&layer3_chain);
1791 if (rnh->rnh_addaddr(&ent->addr, &ent->mask, rnh, (void *)ent) ==
1793 IPFW_WUNLOCK(&layer3_chain);
1794 free(ent, M_IPFW_TBL);
1797 IPFW_WUNLOCK(&layer3_chain);
1802 del_table_entry(struct ip_fw_chain *ch, uint16_t tbl, in_addr_t addr,
1805 struct radix_node_head *rnh;
1806 struct table_entry *ent;
1807 struct sockaddr_in sa, mask;
1809 if (tbl >= IPFW_TABLES_MAX)
1811 rnh = ch->tables[tbl];
1812 sa.sin_len = mask.sin_len = 8;
1813 mask.sin_addr.s_addr = htonl(mlen ? ~((1 << (32 - mlen)) - 1) : 0);
1814 sa.sin_addr.s_addr = addr & mask.sin_addr.s_addr;
1816 ent = (struct table_entry *)rnh->rnh_deladdr(&sa, &mask, rnh);
1822 free(ent, M_IPFW_TBL);
1827 flush_table_entry(struct radix_node *rn, void *arg)
1829 struct radix_node_head * const rnh = arg;
1830 struct table_entry *ent;
1832 ent = (struct table_entry *)
1833 rnh->rnh_deladdr(rn->rn_key, rn->rn_mask, rnh);
1835 free(ent, M_IPFW_TBL);
1840 flush_table(struct ip_fw_chain *ch, uint16_t tbl)
1842 struct radix_node_head *rnh;
1844 IPFW_WLOCK_ASSERT(ch);
1846 if (tbl >= IPFW_TABLES_MAX)
1848 rnh = ch->tables[tbl];
1849 KASSERT(rnh != NULL, ("NULL IPFW table"));
1850 rnh->rnh_walktree(rnh, flush_table_entry, rnh);
1855 flush_tables(struct ip_fw_chain *ch)
1859 IPFW_WLOCK_ASSERT(ch);
1861 for (tbl = 0; tbl < IPFW_TABLES_MAX; tbl++)
1862 flush_table(ch, tbl);
1866 init_tables(struct ip_fw_chain *ch)
1871 for (i = 0; i < IPFW_TABLES_MAX; i++) {
1872 if (!rn_inithead((void **)&ch->tables[i], 32)) {
1873 for (j = 0; j < i; j++) {
1874 (void) flush_table(ch, j);
1883 lookup_table(struct ip_fw_chain *ch, uint16_t tbl, in_addr_t addr,
1886 struct radix_node_head *rnh;
1887 struct table_entry *ent;
1888 struct sockaddr_in sa;
1890 if (tbl >= IPFW_TABLES_MAX)
1892 rnh = ch->tables[tbl];
1894 sa.sin_addr.s_addr = addr;
1895 ent = (struct table_entry *)(rnh->rnh_lookup(&sa, NULL, rnh));
1904 count_table_entry(struct radix_node *rn, void *arg)
1906 u_int32_t * const cnt = arg;
1913 count_table(struct ip_fw_chain *ch, uint32_t tbl, uint32_t *cnt)
1915 struct radix_node_head *rnh;
1917 if (tbl >= IPFW_TABLES_MAX)
1919 rnh = ch->tables[tbl];
1921 rnh->rnh_walktree(rnh, count_table_entry, cnt);
1926 dump_table_entry(struct radix_node *rn, void *arg)
1928 struct table_entry * const n = (struct table_entry *)rn;
1929 ipfw_table * const tbl = arg;
1930 ipfw_table_entry *ent;
1932 if (tbl->cnt == tbl->size)
1934 ent = &tbl->ent[tbl->cnt];
1935 ent->tbl = tbl->tbl;
1936 if (in_nullhost(n->mask.sin_addr))
1939 ent->masklen = 33 - ffs(ntohl(n->mask.sin_addr.s_addr));
1940 ent->addr = n->addr.sin_addr.s_addr;
1941 ent->value = n->value;
1947 dump_table(struct ip_fw_chain *ch, ipfw_table *tbl)
1949 struct radix_node_head *rnh;
1951 if (tbl->tbl >= IPFW_TABLES_MAX)
1953 rnh = ch->tables[tbl->tbl];
1955 rnh->rnh_walktree(rnh, dump_table_entry, tbl);
1960 fill_ugid_cache(struct inpcb *inp, struct ip_fw_ugid *ugp)
1964 if (inp->inp_socket != NULL) {
1965 cr = inp->inp_socket->so_cred;
1966 ugp->fw_prid = jailed(cr) ?
1967 cr->cr_prison->pr_id : -1;
1968 ugp->fw_uid = cr->cr_uid;
1969 ugp->fw_ngroups = cr->cr_ngroups;
1970 bcopy(cr->cr_groups, ugp->fw_groups,
1971 sizeof(ugp->fw_groups));
1976 check_uidgid(ipfw_insn_u32 *insn, int proto, struct ifnet *oif,
1977 struct in_addr dst_ip, u_int16_t dst_port, struct in_addr src_ip,
1978 u_int16_t src_port, struct ip_fw_ugid *ugp, int *lookup,
1981 struct inpcbinfo *pi;
1988 * Check to see if the UDP or TCP stack supplied us with
1989 * the PCB. If so, rather then holding a lock and looking
1990 * up the PCB, we can use the one that was supplied.
1992 if (inp && *lookup == 0) {
1993 INP_LOCK_ASSERT(inp);
1994 if (inp->inp_socket != NULL) {
1995 fill_ugid_cache(inp, ugp);
2000 * If we have already been here and the packet has no
2001 * PCB entry associated with it, then we can safely
2002 * assume that this is a no match.
2006 if (proto == IPPROTO_TCP) {
2009 } else if (proto == IPPROTO_UDP) {
2010 wildcard = INPLOOKUP_WILDCARD;
2018 in_pcblookup_hash(pi,
2019 dst_ip, htons(dst_port),
2020 src_ip, htons(src_port),
2022 in_pcblookup_hash(pi,
2023 src_ip, htons(src_port),
2024 dst_ip, htons(dst_port),
2028 if (pcb->inp_socket != NULL) {
2029 fill_ugid_cache(pcb, ugp);
2034 INP_INFO_RUNLOCK(pi);
2037 * If the lookup did not yield any results, there
2038 * is no sense in coming back and trying again. So
2039 * we can set lookup to -1 and ensure that we wont
2040 * bother the pcb system again.
2046 if (insn->o.opcode == O_UID)
2047 match = (ugp->fw_uid == (uid_t)insn->d[0]);
2048 else if (insn->o.opcode == O_GID) {
2049 for (gp = ugp->fw_groups;
2050 gp < &ugp->fw_groups[ugp->fw_ngroups]; gp++)
2051 if (*gp == (gid_t)insn->d[0]) {
2055 } else if (insn->o.opcode == O_JAIL)
2056 match = (ugp->fw_prid == (int)insn->d[0]);
2060 #ifdef IPFIREWALL_NAT
2061 static eventhandler_tag ifaddr_event_tag;
2064 ifaddr_change(void *arg __unused, struct ifnet *ifp)
2066 struct cfg_nat *ptr;
2069 IPFW_WLOCK(&layer3_chain);
2070 /* Check every nat entry... */
2071 LIST_FOREACH(ptr, &layer3_chain.nat, _next) {
2072 /* ...using nic 'ifp->if_xname' as dynamic alias address. */
2073 if (strncmp(ptr->if_name, ifp->if_xname, IF_NAMESIZE) == 0) {
2074 mtx_lock(&ifp->if_addr_mtx);
2075 TAILQ_FOREACH(ifa, &ifp->if_addrlist, ifa_list) {
2076 if (ifa->ifa_addr == NULL)
2078 if (ifa->ifa_addr->sa_family != AF_INET)
2080 ptr->ip = ((struct sockaddr_in *)
2081 (ifa->ifa_addr))->sin_addr;
2082 LibAliasSetAddress(ptr->lib, ptr->ip);
2084 mtx_unlock(&ifp->if_addr_mtx);
2087 IPFW_WUNLOCK(&layer3_chain);
2091 flush_nat_ptrs(const int i)
2095 IPFW_WLOCK_ASSERT(&layer3_chain);
2096 for (rule = layer3_chain.rules; rule; rule = rule->next) {
2097 ipfw_insn_nat *cmd = (ipfw_insn_nat *)ACTION_PTR(rule);
2098 if (cmd->o.opcode != O_NAT)
2100 if (cmd->nat != NULL && cmd->nat->id == i)
2105 static struct cfg_nat *
2106 lookup_nat(const int i)
2108 struct cfg_nat *ptr;
2110 LIST_FOREACH(ptr, &layer3_chain.nat, _next)
2116 #define HOOK_NAT(b, p) do { \
2117 IPFW_WLOCK_ASSERT(&layer3_chain); \
2118 LIST_INSERT_HEAD(b, p, _next); \
2121 #define UNHOOK_NAT(p) do { \
2122 IPFW_WLOCK_ASSERT(&layer3_chain); \
2123 LIST_REMOVE(p, _next); \
2126 #define HOOK_REDIR(b, p) do { \
2127 LIST_INSERT_HEAD(b, p, _next); \
2130 #define HOOK_SPOOL(b, p) do { \
2131 LIST_INSERT_HEAD(b, p, _next); \
2135 del_redir_spool_cfg(struct cfg_nat *n, struct redir_chain *head)
2137 struct cfg_redir *r, *tmp_r;
2138 struct cfg_spool *s, *tmp_s;
2141 LIST_FOREACH_SAFE(r, head, _next, tmp_r) {
2142 num = 1; /* Number of alias_link to delete. */
2149 /* Delete all libalias redirect entry. */
2150 for (i = 0; i < num; i++)
2151 LibAliasRedirectDelete(n->lib, r->alink[i]);
2152 /* Del spool cfg if any. */
2153 LIST_FOREACH_SAFE(s, &r->spool_chain, _next, tmp_s) {
2154 LIST_REMOVE(s, _next);
2157 free(r->alink, M_IPFW);
2158 LIST_REMOVE(r, _next);
2162 printf("unknown redirect mode: %u\n", r->mode);
2163 /* XXX - panic?!?!? */
2170 add_redir_spool_cfg(char *buf, struct cfg_nat *ptr)
2172 struct cfg_redir *r, *ser_r;
2173 struct cfg_spool *s, *ser_s;
2177 for (cnt = 0, off = 0; cnt < ptr->redir_cnt; cnt++) {
2178 ser_r = (struct cfg_redir *)&buf[off];
2179 r = malloc(SOF_REDIR, M_IPFW, M_WAITOK | M_ZERO);
2180 memcpy(r, ser_r, SOF_REDIR);
2181 LIST_INIT(&r->spool_chain);
2183 r->alink = malloc(sizeof(struct alias_link *) * r->pport_cnt,
2184 M_IPFW, M_WAITOK | M_ZERO);
2187 r->alink[0] = LibAliasRedirectAddr(ptr->lib, r->laddr,
2191 for (i = 0 ; i < r->pport_cnt; i++) {
2192 /* If remotePort is all ports, set it to 0. */
2193 u_short remotePortCopy = r->rport + i;
2194 if (r->rport_cnt == 1 && r->rport == 0)
2196 r->alink[i] = LibAliasRedirectPort(ptr->lib,
2197 r->laddr, htons(r->lport + i), r->raddr,
2198 htons(remotePortCopy), r->paddr,
2199 htons(r->pport + i), r->proto);
2200 if (r->alink[i] == NULL) {
2207 r->alink[0] = LibAliasRedirectProto(ptr->lib ,r->laddr,
2208 r->raddr, r->paddr, r->proto);
2211 printf("unknown redirect mode: %u\n", r->mode);
2214 if (r->alink[0] == NULL) {
2215 panic_err = "LibAliasRedirect* returned NULL";
2217 } else /* LSNAT handling. */
2218 for (i = 0; i < r->spool_cnt; i++) {
2219 ser_s = (struct cfg_spool *)&buf[off];
2220 s = malloc(SOF_REDIR, M_IPFW,
2222 memcpy(s, ser_s, SOF_SPOOL);
2223 LibAliasAddServer(ptr->lib, r->alink[0],
2224 s->addr, htons(s->port));
2226 /* Hook spool entry. */
2227 HOOK_SPOOL(&r->spool_chain, s);
2229 /* And finally hook this redir entry. */
2230 HOOK_REDIR(&ptr->redir_chain, r);
2234 /* something really bad happened: panic! */
2235 panic("%s\n", panic_err);
2240 * The main check routine for the firewall.
2242 * All arguments are in args so we can modify them and return them
2243 * back to the caller.
2247 * args->m (in/out) The packet; we set to NULL when/if we nuke it.
2248 * Starts with the IP header.
2249 * args->eh (in) Mac header if present, or NULL for layer3 packet.
2250 * args->L3offset Number of bytes bypassed if we came from L2.
2251 * e.g. often sizeof(eh) ** NOTYET **
2252 * args->oif Outgoing interface, or NULL if packet is incoming.
2253 * The incoming interface is in the mbuf. (in)
2254 * args->divert_rule (in/out)
2255 * Skip up to the first rule past this rule number;
2256 * upon return, non-zero port number for divert or tee.
2258 * args->rule Pointer to the last matching rule (in/out)
2259 * args->next_hop Socket we are forwarding to (out).
2260 * args->f_id Addresses grabbed from the packet (out)
2261 * args->cookie a cookie depending on rule action
2265 * IP_FW_PASS the packet must be accepted
2266 * IP_FW_DENY the packet must be dropped
2267 * IP_FW_DIVERT divert packet, port in m_tag
2268 * IP_FW_TEE tee packet, port in m_tag
2269 * IP_FW_DUMMYNET to dummynet, pipe in args->cookie
2270 * IP_FW_NETGRAPH into netgraph, cookie args->cookie
2274 ipfw_chk(struct ip_fw_args *args)
2277 * Local variables holding state during the processing of a packet:
2279 * IMPORTANT NOTE: to speed up the processing of rules, there
2280 * are some assumption on the values of the variables, which
2281 * are documented here. Should you change them, please check
2282 * the implementation of the various instructions to make sure
2283 * that they still work.
2285 * args->eh The MAC header. It is non-null for a layer2
2286 * packet, it is NULL for a layer-3 packet.
2288 * args->L3offset Offset in the packet to the L3 (IP or equiv.) header.
2290 * m | args->m Pointer to the mbuf, as received from the caller.
2291 * It may change if ipfw_chk() does an m_pullup, or if it
2292 * consumes the packet because it calls send_reject().
2293 * XXX This has to change, so that ipfw_chk() never modifies
2294 * or consumes the buffer.
2295 * ip is the beginning of the ip(4 or 6) header.
2296 * Calculated by adding the L3offset to the start of data.
2297 * (Until we start using L3offset, the packet is
2298 * supposed to start with the ip header).
2300 struct mbuf *m = args->m;
2301 struct ip *ip = mtod(m, struct ip *);
2304 * For rules which contain uid/gid or jail constraints, cache
2305 * a copy of the users credentials after the pcb lookup has been
2306 * executed. This will speed up the processing of rules with
2307 * these types of constraints, as well as decrease contention
2308 * on pcb related locks.
2310 struct ip_fw_ugid fw_ugid_cache;
2311 int ugid_lookup = 0;
2314 * divinput_flags If non-zero, set to the IP_FW_DIVERT_*_FLAG
2315 * associated with a packet input on a divert socket. This
2316 * will allow to distinguish traffic and its direction when
2317 * it originates from a divert socket.
2319 u_int divinput_flags = 0;
2322 * oif | args->oif If NULL, ipfw_chk has been called on the
2323 * inbound path (ether_input, ip_input).
2324 * If non-NULL, ipfw_chk has been called on the outbound path
2325 * (ether_output, ip_output).
2327 struct ifnet *oif = args->oif;
2329 struct ip_fw *f = NULL; /* matching rule */
2333 * hlen The length of the IP header.
2335 u_int hlen = 0; /* hlen >0 means we have an IP pkt */
2338 * offset The offset of a fragment. offset != 0 means that
2339 * we have a fragment at this offset of an IPv4 packet.
2340 * offset == 0 means that (if this is an IPv4 packet)
2341 * this is the first or only fragment.
2342 * For IPv6 offset == 0 means there is no Fragment Header.
2343 * If offset != 0 for IPv6 always use correct mask to
2344 * get the correct offset because we add IP6F_MORE_FRAG
2345 * to be able to dectect the first fragment which would
2346 * otherwise have offset = 0.
2351 * Local copies of addresses. They are only valid if we have
2354 * proto The protocol. Set to 0 for non-ip packets,
2355 * or to the protocol read from the packet otherwise.
2356 * proto != 0 means that we have an IPv4 packet.
2358 * src_port, dst_port port numbers, in HOST format. Only
2359 * valid for TCP and UDP packets.
2361 * src_ip, dst_ip ip addresses, in NETWORK format.
2362 * Only valid for IPv4 packets.
2365 u_int16_t src_port = 0, dst_port = 0; /* NOTE: host format */
2366 struct in_addr src_ip, dst_ip; /* NOTE: network format */
2369 u_int16_t etype = 0; /* Host order stored ether type */
2372 * dyn_dir = MATCH_UNKNOWN when rules unchecked,
2373 * MATCH_NONE when checked and not matched (q = NULL),
2374 * MATCH_FORWARD or MATCH_REVERSE otherwise (q != NULL)
2376 int dyn_dir = MATCH_UNKNOWN;
2377 ipfw_dyn_rule *q = NULL;
2378 struct ip_fw_chain *chain = &layer3_chain;
2382 * We store in ulp a pointer to the upper layer protocol header.
2383 * In the ipv4 case this is easy to determine from the header,
2384 * but for ipv6 we might have some additional headers in the middle.
2385 * ulp is NULL if not found.
2387 void *ulp = NULL; /* upper layer protocol pointer. */
2388 /* XXX ipv6 variables */
2390 u_int16_t ext_hd = 0; /* bits vector for extension header filtering */
2391 /* end of ipv6 variables */
2394 if (m->m_flags & M_SKIP_FIREWALL)
2395 return (IP_FW_PASS); /* accept */
2397 pktlen = m->m_pkthdr.len;
2398 proto = args->f_id.proto = 0; /* mark f_id invalid */
2399 /* XXX 0 is a valid proto: IP/IPv6 Hop-by-Hop Option */
2402 * PULLUP_TO(len, p, T) makes sure that len + sizeof(T) is contiguous,
2403 * then it sets p to point at the offset "len" in the mbuf. WARNING: the
2404 * pointer might become stale after other pullups (but we never use it
2407 #define PULLUP_TO(len, p, T) \
2409 int x = (len) + sizeof(T); \
2410 if ((m)->m_len < x) { \
2411 args->m = m = m_pullup(m, x); \
2413 goto pullup_failed; \
2415 p = (mtod(m, char *) + (len)); \
2419 * if we have an ether header,
2422 etype = ntohs(args->eh->ether_type);
2424 /* Identify IP packets and fill up variables. */
2425 if (pktlen >= sizeof(struct ip6_hdr) &&
2426 (args->eh == NULL || etype == ETHERTYPE_IPV6) && ip->ip_v == 6) {
2427 struct ip6_hdr *ip6 = (struct ip6_hdr *)ip;
2429 args->f_id.addr_type = 6;
2430 hlen = sizeof(struct ip6_hdr);
2431 proto = ip6->ip6_nxt;
2433 /* Search extension headers to find upper layer protocols */
2434 while (ulp == NULL) {
2436 case IPPROTO_ICMPV6:
2437 PULLUP_TO(hlen, ulp, struct icmp6_hdr);
2438 args->f_id.flags = ICMP6(ulp)->icmp6_type;
2442 PULLUP_TO(hlen, ulp, struct tcphdr);
2443 dst_port = TCP(ulp)->th_dport;
2444 src_port = TCP(ulp)->th_sport;
2445 args->f_id.flags = TCP(ulp)->th_flags;
2449 PULLUP_TO(hlen, ulp, struct sctphdr);
2450 src_port = SCTP(ulp)->src_port;
2451 dst_port = SCTP(ulp)->dest_port;
2455 PULLUP_TO(hlen, ulp, struct udphdr);
2456 dst_port = UDP(ulp)->uh_dport;
2457 src_port = UDP(ulp)->uh_sport;
2460 case IPPROTO_HOPOPTS: /* RFC 2460 */
2461 PULLUP_TO(hlen, ulp, struct ip6_hbh);
2462 ext_hd |= EXT_HOPOPTS;
2463 hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3;
2464 proto = ((struct ip6_hbh *)ulp)->ip6h_nxt;
2468 case IPPROTO_ROUTING: /* RFC 2460 */
2469 PULLUP_TO(hlen, ulp, struct ip6_rthdr);
2470 switch (((struct ip6_rthdr *)ulp)->ip6r_type) {
2472 ext_hd |= EXT_RTHDR0;
2475 ext_hd |= EXT_RTHDR2;
2478 printf("IPFW2: IPV6 - Unknown Routing "
2479 "Header type(%d)\n",
2480 ((struct ip6_rthdr *)ulp)->ip6r_type);
2481 if (fw_deny_unknown_exthdrs)
2482 return (IP_FW_DENY);
2485 ext_hd |= EXT_ROUTING;
2486 hlen += (((struct ip6_rthdr *)ulp)->ip6r_len + 1) << 3;
2487 proto = ((struct ip6_rthdr *)ulp)->ip6r_nxt;
2491 case IPPROTO_FRAGMENT: /* RFC 2460 */
2492 PULLUP_TO(hlen, ulp, struct ip6_frag);
2493 ext_hd |= EXT_FRAGMENT;
2494 hlen += sizeof (struct ip6_frag);
2495 proto = ((struct ip6_frag *)ulp)->ip6f_nxt;
2496 offset = ((struct ip6_frag *)ulp)->ip6f_offlg &
2498 /* Add IP6F_MORE_FRAG for offset of first
2499 * fragment to be != 0. */
2500 offset |= ((struct ip6_frag *)ulp)->ip6f_offlg &
2503 printf("IPFW2: IPV6 - Invalid Fragment "
2505 if (fw_deny_unknown_exthdrs)
2506 return (IP_FW_DENY);
2509 args->f_id.frag_id6 =
2510 ntohl(((struct ip6_frag *)ulp)->ip6f_ident);
2514 case IPPROTO_DSTOPTS: /* RFC 2460 */
2515 PULLUP_TO(hlen, ulp, struct ip6_hbh);
2516 ext_hd |= EXT_DSTOPTS;
2517 hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3;
2518 proto = ((struct ip6_hbh *)ulp)->ip6h_nxt;
2522 case IPPROTO_AH: /* RFC 2402 */
2523 PULLUP_TO(hlen, ulp, struct ip6_ext);
2525 hlen += (((struct ip6_ext *)ulp)->ip6e_len + 2) << 2;
2526 proto = ((struct ip6_ext *)ulp)->ip6e_nxt;
2530 case IPPROTO_ESP: /* RFC 2406 */
2531 PULLUP_TO(hlen, ulp, uint32_t); /* SPI, Seq# */
2532 /* Anything past Seq# is variable length and
2533 * data past this ext. header is encrypted. */
2537 case IPPROTO_NONE: /* RFC 2460 */
2538 PULLUP_TO(hlen, ulp, struct ip6_ext);
2539 /* Packet ends here. if ip6e_len!=0 octets
2540 * must be ignored. */
2543 case IPPROTO_OSPFIGP:
2544 /* XXX OSPF header check? */
2545 PULLUP_TO(hlen, ulp, struct ip6_ext);
2549 /* XXX PIM header check? */
2550 PULLUP_TO(hlen, ulp, struct pim);
2554 PULLUP_TO(hlen, ulp, struct carp_header);
2555 if (((struct carp_header *)ulp)->carp_version !=
2557 return (IP_FW_DENY);
2558 if (((struct carp_header *)ulp)->carp_type !=
2560 return (IP_FW_DENY);
2563 case IPPROTO_IPV6: /* RFC 2893 */
2564 PULLUP_TO(hlen, ulp, struct ip6_hdr);
2567 case IPPROTO_IPV4: /* RFC 2893 */
2568 PULLUP_TO(hlen, ulp, struct ip);
2572 printf("IPFW2: IPV6 - Unknown Extension "
2573 "Header(%d), ext_hd=%x\n", proto, ext_hd);
2574 if (fw_deny_unknown_exthdrs)
2575 return (IP_FW_DENY);
2576 PULLUP_TO(hlen, ulp, struct ip6_ext);
2580 ip = mtod(m, struct ip *);
2581 ip6 = (struct ip6_hdr *)ip;
2582 args->f_id.src_ip6 = ip6->ip6_src;
2583 args->f_id.dst_ip6 = ip6->ip6_dst;
2584 args->f_id.src_ip = 0;
2585 args->f_id.dst_ip = 0;
2586 args->f_id.flow_id6 = ntohl(ip6->ip6_flow);
2587 } else if (pktlen >= sizeof(struct ip) &&
2588 (args->eh == NULL || etype == ETHERTYPE_IP) && ip->ip_v == 4) {
2590 hlen = ip->ip_hl << 2;
2591 args->f_id.addr_type = 4;
2594 * Collect parameters into local variables for faster matching.
2597 src_ip = ip->ip_src;
2598 dst_ip = ip->ip_dst;
2599 if (args->eh != NULL) { /* layer 2 packets are as on the wire */
2600 offset = ntohs(ip->ip_off) & IP_OFFMASK;
2601 ip_len = ntohs(ip->ip_len);
2603 offset = ip->ip_off & IP_OFFMASK;
2604 ip_len = ip->ip_len;
2606 pktlen = ip_len < pktlen ? ip_len : pktlen;
2611 PULLUP_TO(hlen, ulp, struct tcphdr);
2612 dst_port = TCP(ulp)->th_dport;
2613 src_port = TCP(ulp)->th_sport;
2614 args->f_id.flags = TCP(ulp)->th_flags;
2618 PULLUP_TO(hlen, ulp, struct udphdr);
2619 dst_port = UDP(ulp)->uh_dport;
2620 src_port = UDP(ulp)->uh_sport;
2624 PULLUP_TO(hlen, ulp, struct icmphdr);
2625 args->f_id.flags = ICMP(ulp)->icmp_type;
2633 ip = mtod(m, struct ip *);
2634 args->f_id.src_ip = ntohl(src_ip.s_addr);
2635 args->f_id.dst_ip = ntohl(dst_ip.s_addr);
2638 if (proto) { /* we may have port numbers, store them */
2639 args->f_id.proto = proto;
2640 args->f_id.src_port = src_port = ntohs(src_port);
2641 args->f_id.dst_port = dst_port = ntohs(dst_port);
2645 mtag = m_tag_find(m, PACKET_TAG_DIVERT, NULL);
2648 * Packet has already been tagged. Look for the next rule
2649 * to restart processing.
2651 * If fw_one_pass != 0 then just accept it.
2652 * XXX should not happen here, but optimized out in
2656 IPFW_RUNLOCK(chain);
2657 return (IP_FW_PASS);
2660 f = args->rule->next_rule;
2662 f = lookup_next_rule(args->rule);
2665 * Find the starting rule. It can be either the first
2666 * one, or the one after divert_rule if asked so.
2668 int skipto = mtag ? divert_cookie(mtag) : 0;
2671 if (args->eh == NULL && skipto != 0) {
2672 if (skipto >= IPFW_DEFAULT_RULE) {
2673 IPFW_RUNLOCK(chain);
2674 return (IP_FW_DENY); /* invalid */
2676 while (f && f->rulenum <= skipto)
2678 if (f == NULL) { /* drop packet */
2679 IPFW_RUNLOCK(chain);
2680 return (IP_FW_DENY);
2684 /* reset divert rule to avoid confusion later */
2686 divinput_flags = divert_info(mtag) &
2687 (IP_FW_DIVERT_OUTPUT_FLAG | IP_FW_DIVERT_LOOPBACK_FLAG);
2688 m_tag_delete(m, mtag);
2692 * Now scan the rules, and parse microinstructions for each rule.
2694 for (; f; f = f->next) {
2696 uint32_t tablearg = 0;
2697 int l, cmdlen, skip_or; /* skip rest of OR block */
2700 if (set_disable & (1 << f->set) )
2704 for (l = f->cmd_len, cmd = f->cmd ; l > 0 ;
2705 l -= cmdlen, cmd += cmdlen) {
2709 * check_body is a jump target used when we find a
2710 * CHECK_STATE, and need to jump to the body of
2715 cmdlen = F_LEN(cmd);
2717 * An OR block (insn_1 || .. || insn_n) has the
2718 * F_OR bit set in all but the last instruction.
2719 * The first match will set "skip_or", and cause
2720 * the following instructions to be skipped until
2721 * past the one with the F_OR bit clear.
2723 if (skip_or) { /* skip this instruction */
2724 if ((cmd->len & F_OR) == 0)
2725 skip_or = 0; /* next one is good */
2728 match = 0; /* set to 1 if we succeed */
2730 switch (cmd->opcode) {
2732 * The first set of opcodes compares the packet's
2733 * fields with some pattern, setting 'match' if a
2734 * match is found. At the end of the loop there is
2735 * logic to deal with F_NOT and F_OR flags associated
2743 printf("ipfw: opcode %d unimplemented\n",
2751 * We only check offset == 0 && proto != 0,
2752 * as this ensures that we have a
2753 * packet with the ports info.
2757 if (is_ipv6) /* XXX to be fixed later */
2759 if (proto == IPPROTO_TCP ||
2760 proto == IPPROTO_UDP)
2761 match = check_uidgid(
2762 (ipfw_insn_u32 *)cmd,
2765 src_ip, src_port, &fw_ugid_cache,
2766 &ugid_lookup, args->inp);
2770 match = iface_match(m->m_pkthdr.rcvif,
2771 (ipfw_insn_if *)cmd);
2775 match = iface_match(oif, (ipfw_insn_if *)cmd);
2779 match = iface_match(oif ? oif :
2780 m->m_pkthdr.rcvif, (ipfw_insn_if *)cmd);
2784 if (args->eh != NULL) { /* have MAC header */
2785 u_int32_t *want = (u_int32_t *)
2786 ((ipfw_insn_mac *)cmd)->addr;
2787 u_int32_t *mask = (u_int32_t *)
2788 ((ipfw_insn_mac *)cmd)->mask;
2789 u_int32_t *hdr = (u_int32_t *)args->eh;
2792 ( want[0] == (hdr[0] & mask[0]) &&
2793 want[1] == (hdr[1] & mask[1]) &&
2794 want[2] == (hdr[2] & mask[2]) );
2799 if (args->eh != NULL) {
2801 ((ipfw_insn_u16 *)cmd)->ports;
2804 for (i = cmdlen - 1; !match && i>0;
2806 match = (etype >= p[0] &&
2812 match = (offset != 0);
2815 case O_IN: /* "out" is "not in" */
2816 match = (oif == NULL);
2820 match = (args->eh != NULL);
2824 match = (cmd->arg1 & 1 && divinput_flags &
2825 IP_FW_DIVERT_LOOPBACK_FLAG) ||
2826 (cmd->arg1 & 2 && divinput_flags &
2827 IP_FW_DIVERT_OUTPUT_FLAG);
2832 * We do not allow an arg of 0 so the
2833 * check of "proto" only suffices.
2835 match = (proto == cmd->arg1);
2840 (((ipfw_insn_ip *)cmd)->addr.s_addr ==
2844 case O_IP_SRC_LOOKUP:
2845 case O_IP_DST_LOOKUP:
2848 (cmd->opcode == O_IP_DST_LOOKUP) ?
2849 dst_ip.s_addr : src_ip.s_addr;
2852 match = lookup_table(chain, cmd->arg1, a,
2856 if (cmdlen == F_INSN_SIZE(ipfw_insn_u32))
2858 ((ipfw_insn_u32 *)cmd)->d[0] == v;
2868 (cmd->opcode == O_IP_DST_MASK) ?
2869 dst_ip.s_addr : src_ip.s_addr;
2870 uint32_t *p = ((ipfw_insn_u32 *)cmd)->d;
2873 for (; !match && i>0; i-= 2, p+= 2)
2874 match = (p[0] == (a & p[1]));
2882 INADDR_TO_IFP(src_ip, tif);
2883 match = (tif != NULL);
2890 u_int32_t *d = (u_int32_t *)(cmd+1);
2892 cmd->opcode == O_IP_DST_SET ?
2898 addr -= d[0]; /* subtract base */
2899 match = (addr < cmd->arg1) &&
2900 ( d[ 1 + (addr>>5)] &
2901 (1<<(addr & 0x1f)) );
2907 (((ipfw_insn_ip *)cmd)->addr.s_addr ==
2915 INADDR_TO_IFP(dst_ip, tif);
2916 match = (tif != NULL);
2923 * offset == 0 && proto != 0 is enough
2924 * to guarantee that we have a
2925 * packet with port info.
2927 if ((proto==IPPROTO_UDP || proto==IPPROTO_TCP)
2930 (cmd->opcode == O_IP_SRCPORT) ?
2931 src_port : dst_port ;
2933 ((ipfw_insn_u16 *)cmd)->ports;
2936 for (i = cmdlen - 1; !match && i>0;
2938 match = (x>=p[0] && x<=p[1]);
2943 match = (offset == 0 && proto==IPPROTO_ICMP &&
2944 icmptype_match(ICMP(ulp), (ipfw_insn_u32 *)cmd) );
2949 match = is_ipv6 && offset == 0 &&
2950 proto==IPPROTO_ICMPV6 &&
2952 ICMP6(ulp)->icmp6_type,
2953 (ipfw_insn_u32 *)cmd);
2959 ipopts_match(ip, cmd) );
2964 cmd->arg1 == ip->ip_v);
2970 if (is_ipv4) { /* only for IP packets */
2975 if (cmd->opcode == O_IPLEN)
2977 else if (cmd->opcode == O_IPTTL)
2979 else /* must be IPID */
2980 x = ntohs(ip->ip_id);
2982 match = (cmd->arg1 == x);
2985 /* otherwise we have ranges */
2986 p = ((ipfw_insn_u16 *)cmd)->ports;
2988 for (; !match && i>0; i--, p += 2)
2989 match = (x >= p[0] && x <= p[1]);
2993 case O_IPPRECEDENCE:
2995 (cmd->arg1 == (ip->ip_tos & 0xe0)) );
3000 flags_match(cmd, ip->ip_tos));
3004 if (proto == IPPROTO_TCP && offset == 0) {
3012 ((ip->ip_hl + tcp->th_off) << 2);
3014 match = (cmd->arg1 == x);
3017 /* otherwise we have ranges */
3018 p = ((ipfw_insn_u16 *)cmd)->ports;
3020 for (; !match && i>0; i--, p += 2)
3021 match = (x >= p[0] && x <= p[1]);
3026 match = (proto == IPPROTO_TCP && offset == 0 &&
3027 flags_match(cmd, TCP(ulp)->th_flags));
3031 match = (proto == IPPROTO_TCP && offset == 0 &&
3032 tcpopts_match(TCP(ulp), cmd));
3036 match = (proto == IPPROTO_TCP && offset == 0 &&
3037 ((ipfw_insn_u32 *)cmd)->d[0] ==
3042 match = (proto == IPPROTO_TCP && offset == 0 &&
3043 ((ipfw_insn_u32 *)cmd)->d[0] ==
3048 match = (proto == IPPROTO_TCP && offset == 0 &&
3049 cmd->arg1 == TCP(ulp)->th_win);
3053 /* reject packets which have SYN only */
3054 /* XXX should i also check for TH_ACK ? */
3055 match = (proto == IPPROTO_TCP && offset == 0 &&
3056 (TCP(ulp)->th_flags &
3057 (TH_RST | TH_ACK | TH_SYN)) != TH_SYN);
3062 ipfw_insn_altq *altq = (ipfw_insn_altq *)cmd;
3065 at = pf_find_mtag(m);
3066 if (at != NULL && at->qid != 0)
3068 at = pf_get_mtag(m);
3071 * Let the packet fall back to the
3076 at->qid = altq->qid;
3087 ipfw_log(f, hlen, args, m,
3088 oif, offset, tablearg, ip);
3093 match = (random()<((ipfw_insn_u32 *)cmd)->d[0]);
3097 /* Outgoing packets automatically pass/match */
3098 match = ((oif != NULL) ||
3099 (m->m_pkthdr.rcvif == NULL) ||
3103 verify_path6(&(args->f_id.src_ip6),
3104 m->m_pkthdr.rcvif) :
3106 verify_path(src_ip, m->m_pkthdr.rcvif)));
3110 /* Outgoing packets automatically pass/match */
3111 match = (hlen > 0 && ((oif != NULL) ||
3114 verify_path6(&(args->f_id.src_ip6),
3117 verify_path(src_ip, NULL)));
3121 /* Outgoing packets automatically pass/match */
3122 if (oif == NULL && hlen > 0 &&
3123 ( (is_ipv4 && in_localaddr(src_ip))
3126 in6_localaddr(&(args->f_id.src_ip6)))
3131 is_ipv6 ? verify_path6(
3132 &(args->f_id.src_ip6),
3133 m->m_pkthdr.rcvif) :
3143 match = (m_tag_find(m,
3144 PACKET_TAG_IPSEC_IN_DONE, NULL) != NULL);
3146 /* otherwise no match */
3152 IN6_ARE_ADDR_EQUAL(&args->f_id.src_ip6,
3153 &((ipfw_insn_ip6 *)cmd)->addr6);
3158 IN6_ARE_ADDR_EQUAL(&args->f_id.dst_ip6,
3159 &((ipfw_insn_ip6 *)cmd)->addr6);
3161 case O_IP6_SRC_MASK:
3162 case O_IP6_DST_MASK:
3166 struct in6_addr *d =
3167 &((ipfw_insn_ip6 *)cmd)->addr6;
3169 for (; !match && i > 0; d += 2,
3170 i -= F_INSN_SIZE(struct in6_addr)
3176 APPLY_MASK(&p, &d[1]);
3178 IN6_ARE_ADDR_EQUAL(&d[0],
3185 match= is_ipv6 && search_ip6_addr_net(&args->f_id.src_ip6);
3189 match= is_ipv6 && search_ip6_addr_net(&args->f_id.dst_ip6);
3194 flow6id_match(args->f_id.flow_id6,
3195 (ipfw_insn_u32 *) cmd);
3200 (ext_hd & ((ipfw_insn *) cmd)->arg1);
3213 uint32_t tag = (cmd->arg1 == IP_FW_TABLEARG) ?
3214 tablearg : cmd->arg1;
3216 /* Packet is already tagged with this tag? */
3217 mtag = m_tag_locate(m, MTAG_IPFW, tag, NULL);
3219 /* We have `untag' action when F_NOT flag is
3220 * present. And we must remove this mtag from
3221 * mbuf and reset `match' to zero (`match' will
3222 * be inversed later).
3223 * Otherwise we should allocate new mtag and
3224 * push it into mbuf.
3226 if (cmd->len & F_NOT) { /* `untag' action */
3228 m_tag_delete(m, mtag);
3229 } else if (mtag == NULL) {
3230 if ((mtag = m_tag_alloc(MTAG_IPFW,
3231 tag, 0, M_NOWAIT)) != NULL)
3232 m_tag_prepend(m, mtag);
3234 match = (cmd->len & F_NOT) ? 0: 1;
3239 uint32_t tag = (cmd->arg1 == IP_FW_TABLEARG) ?
3240 tablearg : cmd->arg1;
3243 match = m_tag_locate(m, MTAG_IPFW,
3248 /* we have ranges */
3249 for (mtag = m_tag_first(m);
3250 mtag != NULL && !match;
3251 mtag = m_tag_next(m, mtag)) {
3255 if (mtag->m_tag_cookie != MTAG_IPFW)
3258 p = ((ipfw_insn_u16 *)cmd)->ports;
3260 for(; !match && i > 0; i--, p += 2)
3262 mtag->m_tag_id >= p[0] &&
3263 mtag->m_tag_id <= p[1];
3269 * The second set of opcodes represents 'actions',
3270 * i.e. the terminal part of a rule once the packet
3271 * matches all previous patterns.
3272 * Typically there is only one action for each rule,
3273 * and the opcode is stored at the end of the rule
3274 * (but there are exceptions -- see below).
3276 * In general, here we set retval and terminate the
3277 * outer loop (would be a 'break 3' in some language,
3278 * but we need to do a 'goto done').
3281 * O_COUNT and O_SKIPTO actions:
3282 * instead of terminating, we jump to the next rule
3283 * ('goto next_rule', equivalent to a 'break 2'),
3284 * or to the SKIPTO target ('goto again' after
3285 * having set f, cmd and l), respectively.
3287 * O_TAG, O_LOG and O_ALTQ action parameters:
3288 * perform some action and set match = 1;
3290 * O_LIMIT and O_KEEP_STATE: these opcodes are
3291 * not real 'actions', and are stored right
3292 * before the 'action' part of the rule.
3293 * These opcodes try to install an entry in the
3294 * state tables; if successful, we continue with
3295 * the next opcode (match=1; break;), otherwise
3296 * the packet * must be dropped
3297 * ('goto done' after setting retval);
3299 * O_PROBE_STATE and O_CHECK_STATE: these opcodes
3300 * cause a lookup of the state table, and a jump
3301 * to the 'action' part of the parent rule
3302 * ('goto check_body') if an entry is found, or
3303 * (CHECK_STATE only) a jump to the next rule if
3304 * the entry is not found ('goto next_rule').
3305 * The result of the lookup is cached to make
3306 * further instances of these opcodes are
3311 if (install_state(f,
3312 (ipfw_insn_limit *)cmd, args, tablearg)) {
3313 retval = IP_FW_DENY;
3314 goto done; /* error/limit violation */
3322 * dynamic rules are checked at the first
3323 * keep-state or check-state occurrence,
3324 * with the result being stored in dyn_dir.
3325 * The compiler introduces a PROBE_STATE
3326 * instruction for us when we have a
3327 * KEEP_STATE (because PROBE_STATE needs
3330 if (dyn_dir == MATCH_UNKNOWN &&
3331 (q = lookup_dyn_rule(&args->f_id,
3332 &dyn_dir, proto == IPPROTO_TCP ?
3336 * Found dynamic entry, update stats
3337 * and jump to the 'action' part of
3343 cmd = ACTION_PTR(f);
3344 l = f->cmd_len - f->act_ofs;
3349 * Dynamic entry not found. If CHECK_STATE,
3350 * skip to next rule, if PROBE_STATE just
3351 * ignore and continue with next opcode.
3353 if (cmd->opcode == O_CHECK_STATE)
3359 retval = 0; /* accept */
3364 args->rule = f; /* report matching rule */
3365 if (cmd->arg1 == IP_FW_TABLEARG)
3366 args->cookie = tablearg;
3368 args->cookie = cmd->arg1;
3369 retval = IP_FW_DUMMYNET;
3374 struct divert_tag *dt;
3376 if (args->eh) /* not on layer 2 */
3378 mtag = m_tag_get(PACKET_TAG_DIVERT,
3379 sizeof(struct divert_tag),
3384 IPFW_RUNLOCK(chain);
3385 return (IP_FW_DENY);
3387 dt = (struct divert_tag *)(mtag+1);
3388 dt->cookie = f->rulenum;
3389 if (cmd->arg1 == IP_FW_TABLEARG)
3390 dt->info = tablearg;
3392 dt->info = cmd->arg1;
3393 m_tag_prepend(m, mtag);
3394 retval = (cmd->opcode == O_DIVERT) ?
3395 IP_FW_DIVERT : IP_FW_TEE;
3401 f->pcnt++; /* update stats */
3403 f->timestamp = time_uptime;
3404 if (cmd->opcode == O_COUNT)
3407 if (f->next_rule == NULL)
3408 lookup_next_rule(f);
3414 * Drop the packet and send a reject notice
3415 * if the packet is not ICMP (or is an ICMP
3416 * query), and it is not multicast/broadcast.
3418 if (hlen > 0 && is_ipv4 && offset == 0 &&
3419 (proto != IPPROTO_ICMP ||
3420 is_icmp_query(ICMP(ulp))) &&
3421 !(m->m_flags & (M_BCAST|M_MCAST)) &&
3422 !IN_MULTICAST(ntohl(dst_ip.s_addr))) {
3423 send_reject(args, cmd->arg1, ip_len, ip);
3429 if (hlen > 0 && is_ipv6 &&
3430 ((offset & IP6F_OFF_MASK) == 0) &&
3431 (proto != IPPROTO_ICMPV6 ||
3432 (is_icmp6_query(args->f_id.flags) == 1)) &&
3433 !(m->m_flags & (M_BCAST|M_MCAST)) &&
3434 !IN6_IS_ADDR_MULTICAST(&args->f_id.dst_ip6)) {
3436 args, cmd->arg1, hlen,
3437 (struct ip6_hdr *)ip);
3443 retval = IP_FW_DENY;
3446 case O_FORWARD_IP: {
3447 struct sockaddr_in *sa;
3448 sa = &(((ipfw_insn_sa *)cmd)->sa);
3449 if (args->eh) /* not valid on layer2 pkts */
3451 if (!q || dyn_dir == MATCH_FORWARD) {
3452 if (sa->sin_addr.s_addr == INADDR_ANY) {
3453 bcopy(sa, &args->hopstore,
3455 args->hopstore.sin_addr.s_addr =
3460 args->next_hop = sa;
3463 retval = IP_FW_PASS;
3469 args->rule = f; /* report matching rule */
3470 if (cmd->arg1 == IP_FW_TABLEARG)
3471 args->cookie = tablearg;
3473 args->cookie = cmd->arg1;
3474 retval = (cmd->opcode == O_NETGRAPH) ?
3475 IP_FW_NETGRAPH : IP_FW_NGTEE;
3478 #ifdef IPFIREWALL_NAT
3482 /* XXX - libalias duct tape */
3487 args->rule = f; /* Report matching rule. */
3489 t = ((ipfw_insn_nat *)cmd)->nat;
3491 t = lookup_nat(cmd->arg1);
3493 retval = IP_FW_DENY;
3496 ((ipfw_insn_nat *)cmd)->nat =
3499 if ((mcl = m_megapullup(m, m->m_pkthdr.len)) ==
3502 ip = mtod(mcl, struct ip *);
3503 if (args->eh == NULL) {
3504 ip->ip_len = htons(ip->ip_len);
3505 ip->ip_off = htons(ip->ip_off);
3509 * XXX - Libalias checksum offload 'duct tape':
3511 * locally generated packets have only
3512 * pseudo-header checksum calculated
3513 * and libalias will screw it[1], so
3514 * mark them for later fix. Moreover
3515 * there are cases when libalias
3516 * modify tcp packet data[2], mark it
3517 * for later fix too.
3519 * [1] libalias was never meant to run
3520 * in kernel, so it doesn't have any
3521 * knowledge about checksum
3522 * offloading, and it expects a packet
3523 * with a full internet
3524 * checksum. Unfortunately, packets
3525 * generated locally will have just the
3526 * pseudo header calculated, and when
3527 * libalias tries to adjust the
3528 * checksum it will actually screw it.
3530 * [2] when libalias modify tcp's data
3531 * content, full TCP checksum has to
3532 * be recomputed: the problem is that
3533 * libalias doesn't have any idea
3534 * about checksum offloading To
3535 * workaround this, we do not do
3536 * checksumming in LibAlias, but only
3537 * mark the packets in th_x2 field. If
3538 * we receive a marked packet, we
3539 * calculate correct checksum for it
3540 * aware of offloading. Why such a
3541 * terrible hack instead of
3542 * recalculating checksum for each
3543 * packet? Because the previous
3544 * checksum was not checked!
3545 * Recalculating checksums for EVERY
3546 * packet will hide ALL transmission
3547 * errors. Yes, marked packets still
3548 * suffer from this problem. But,
3549 * sigh, natd(8) has this problem,
3552 * TODO: -make libalias mbuf aware (so
3553 * it can handle delayed checksum and tso)
3556 if (mcl->m_pkthdr.rcvif == NULL &&
3557 mcl->m_pkthdr.csum_flags &
3561 c = mtod(mcl, char *);
3563 retval = LibAliasIn(t->lib, c,
3566 retval = LibAliasOut(t->lib, c,
3568 if (retval != PKT_ALIAS_OK) {
3569 /* XXX - should i add some logging? */
3573 retval = IP_FW_DENY;
3576 mcl->m_pkthdr.len = mcl->m_len =
3580 * XXX - libalias checksum offload
3581 * 'duct tape' (see above)
3584 if ((ip->ip_off & htons(IP_OFFMASK)) == 0 &&
3585 ip->ip_p == IPPROTO_TCP) {
3588 th = (struct tcphdr *)(ip + 1);
3598 ip->ip_len = ntohs(ip->ip_len);
3602 htons(ip->ip_p + ip->ip_len -
3608 th = (struct tcphdr *)(ip + 1);
3610 * Maybe it was set in
3615 mcl->m_pkthdr.csum_data =
3616 offsetof(struct tcphdr,
3620 uh = (struct udphdr *)(ip + 1);
3622 mcl->m_pkthdr.csum_data =
3623 offsetof(struct udphdr,
3628 * No hw checksum offloading: do it
3631 if ((mcl->m_pkthdr.csum_flags &
3632 CSUM_DELAY_DATA) == 0) {
3633 in_delayed_cksum(mcl);
3634 mcl->m_pkthdr.csum_flags &=
3637 ip->ip_len = htons(ip->ip_len);
3640 if (args->eh == NULL) {
3641 ip->ip_len = ntohs(ip->ip_len);
3642 ip->ip_off = ntohs(ip->ip_off);
3652 panic("-- unknown opcode %d\n", cmd->opcode);
3653 } /* end of switch() on opcodes */
3655 if (cmd->len & F_NOT)
3659 if (cmd->len & F_OR)
3662 if (!(cmd->len & F_OR)) /* not an OR block, */
3663 break; /* try next rule */
3666 } /* end of inner for, scan opcodes */
3668 next_rule:; /* try next rule */
3670 } /* end of outer for, scan rules */
3671 printf("ipfw: ouch!, skip past end of rules, denying packet\n");
3672 IPFW_RUNLOCK(chain);
3673 return (IP_FW_DENY);
3676 /* Update statistics */
3679 f->timestamp = time_uptime;
3680 IPFW_RUNLOCK(chain);
3685 printf("ipfw: pullup failed\n");
3686 return (IP_FW_DENY);
3690 * When a rule is added/deleted, clear the next_rule pointers in all rules.
3691 * These will be reconstructed on the fly as packets are matched.
3694 flush_rule_ptrs(struct ip_fw_chain *chain)
3698 IPFW_WLOCK_ASSERT(chain);
3700 for (rule = chain->rules; rule; rule = rule->next)
3701 rule->next_rule = NULL;
3705 * Add a new rule to the list. Copy the rule into a malloc'ed area, then
3706 * possibly create a rule number and add the rule to the list.
3707 * Update the rule_number in the input struct so the caller knows it as well.
3710 add_rule(struct ip_fw_chain *chain, struct ip_fw *input_rule)
3712 struct ip_fw *rule, *f, *prev;
3713 int l = RULESIZE(input_rule);
3715 if (chain->rules == NULL && input_rule->rulenum != IPFW_DEFAULT_RULE)
3718 rule = malloc(l, M_IPFW, M_NOWAIT | M_ZERO);
3722 bcopy(input_rule, rule, l);
3725 rule->next_rule = NULL;
3729 rule->timestamp = 0;
3733 if (chain->rules == NULL) { /* default rule */
3734 chain->rules = rule;
3739 * If rulenum is 0, find highest numbered rule before the
3740 * default rule, and add autoinc_step
3742 if (autoinc_step < 1)
3744 else if (autoinc_step > 1000)
3745 autoinc_step = 1000;
3746 if (rule->rulenum == 0) {
3748 * locate the highest numbered rule before default
3750 for (f = chain->rules; f; f = f->next) {
3751 if (f->rulenum == IPFW_DEFAULT_RULE)
3753 rule->rulenum = f->rulenum;
3755 if (rule->rulenum < IPFW_DEFAULT_RULE - autoinc_step)
3756 rule->rulenum += autoinc_step;
3757 input_rule->rulenum = rule->rulenum;
3761 * Now insert the new rule in the right place in the sorted list.
3763 for (prev = NULL, f = chain->rules; f; prev = f, f = f->next) {
3764 if (f->rulenum > rule->rulenum) { /* found the location */
3768 } else { /* head insert */
3769 rule->next = chain->rules;
3770 chain->rules = rule;
3775 flush_rule_ptrs(chain);
3779 IPFW_WUNLOCK(chain);
3780 DEB(printf("ipfw: installed rule %d, static count now %d\n",
3781 rule->rulenum, static_count);)
3786 * Remove a static rule (including derived * dynamic rules)
3787 * and place it on the ``reap list'' for later reclamation.
3788 * The caller is in charge of clearing rule pointers to avoid
3789 * dangling pointers.
3790 * @return a pointer to the next entry.
3791 * Arguments are not checked, so they better be correct.
3793 static struct ip_fw *
3794 remove_rule(struct ip_fw_chain *chain, struct ip_fw *rule,
3798 int l = RULESIZE(rule);
3800 IPFW_WLOCK_ASSERT(chain);
3804 remove_dyn_rule(rule, NULL /* force removal */);
3813 rule->next = chain->reap;
3820 * Reclaim storage associated with a list of rules. This is
3821 * typically the list created using remove_rule.
3824 reap_rules(struct ip_fw *head)
3828 while ((rule = head) != NULL) {
3830 if (DUMMYNET_LOADED)
3831 ip_dn_ruledel_ptr(rule);
3837 * Remove all rules from a chain (except rules in set RESVD_SET
3838 * unless kill_default = 1). The caller is responsible for
3839 * reclaiming storage for the rules left in chain->reap.
3842 free_chain(struct ip_fw_chain *chain, int kill_default)
3844 struct ip_fw *prev, *rule;
3846 IPFW_WLOCK_ASSERT(chain);
3848 flush_rule_ptrs(chain); /* more efficient to do outside the loop */
3849 for (prev = NULL, rule = chain->rules; rule ; )
3850 if (kill_default || rule->set != RESVD_SET)
3851 rule = remove_rule(chain, rule, prev);
3859 * Remove all rules with given number, and also do set manipulation.
3860 * Assumes chain != NULL && *chain != NULL.
3862 * The argument is an u_int32_t. The low 16 bit are the rule or set number,
3863 * the next 8 bits are the new set, the top 8 bits are the command:
3865 * 0 delete rules with given number
3866 * 1 delete rules with given set number
3867 * 2 move rules with given number to new set
3868 * 3 move rules with given set number to new set
3869 * 4 swap sets with given numbers
3870 * 5 delete rules with given number and with given set number
3873 del_entry(struct ip_fw_chain *chain, u_int32_t arg)
3875 struct ip_fw *prev = NULL, *rule;
3876 u_int16_t rulenum; /* rule or old_set */
3877 u_int8_t cmd, new_set;
3879 rulenum = arg & 0xffff;
3880 cmd = (arg >> 24) & 0xff;
3881 new_set = (arg >> 16) & 0xff;
3883 if (cmd > 5 || new_set > RESVD_SET)
3885 if (cmd == 0 || cmd == 2 || cmd == 5) {
3886 if (rulenum >= IPFW_DEFAULT_RULE)
3889 if (rulenum > RESVD_SET) /* old_set */
3894 rule = chain->rules;
3897 case 0: /* delete rules with given number */
3899 * locate first rule to delete
3901 for (; rule->rulenum < rulenum; prev = rule, rule = rule->next)
3903 if (rule->rulenum != rulenum) {
3904 IPFW_WUNLOCK(chain);
3909 * flush pointers outside the loop, then delete all matching
3910 * rules. prev remains the same throughout the cycle.
3912 flush_rule_ptrs(chain);
3913 while (rule->rulenum == rulenum)
3914 rule = remove_rule(chain, rule, prev);
3917 case 1: /* delete all rules with given set number */
3918 flush_rule_ptrs(chain);
3919 rule = chain->rules;
3920 while (rule->rulenum < IPFW_DEFAULT_RULE)
3921 if (rule->set == rulenum)
3922 rule = remove_rule(chain, rule, prev);
3929 case 2: /* move rules with given number to new set */
3930 rule = chain->rules;
3931 for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
3932 if (rule->rulenum == rulenum)
3933 rule->set = new_set;
3936 case 3: /* move rules with given set number to new set */
3937 for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
3938 if (rule->set == rulenum)
3939 rule->set = new_set;
3942 case 4: /* swap two sets */
3943 for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
3944 if (rule->set == rulenum)
3945 rule->set = new_set;
3946 else if (rule->set == new_set)
3947 rule->set = rulenum;
3949 case 5: /* delete rules with given number and with given set number.
3950 * rulenum - given rule number;
3951 * new_set - given set number.
3953 for (; rule->rulenum < rulenum; prev = rule, rule = rule->next)
3955 if (rule->rulenum != rulenum) {
3956 IPFW_WUNLOCK(chain);
3959 flush_rule_ptrs(chain);
3960 while (rule->rulenum == rulenum) {
3961 if (rule->set == new_set)
3962 rule = remove_rule(chain, rule, prev);
3970 * Look for rules to reclaim. We grab the list before
3971 * releasing the lock then reclaim them w/o the lock to
3972 * avoid a LOR with dummynet.
3976 IPFW_WUNLOCK(chain);
3983 * Clear counters for a specific rule.
3984 * The enclosing "table" is assumed locked.
3987 clear_counters(struct ip_fw *rule, int log_only)
3989 ipfw_insn_log *l = (ipfw_insn_log *)ACTION_PTR(rule);
3991 if (log_only == 0) {
3992 rule->bcnt = rule->pcnt = 0;
3993 rule->timestamp = 0;
3995 if (l->o.opcode == O_LOG)
3996 l->log_left = l->max_log;
4000 * Reset some or all counters on firewall rules.
4001 * The argument `arg' is an u_int32_t. The low 16 bit are the rule number,
4002 * the next 8 bits are the set number, the top 8 bits are the command:
4003 * 0 work with rules from all set's;
4004 * 1 work with rules only from specified set.
4005 * Specified rule number is zero if we want to clear all entries.
4006 * log_only is 1 if we only want to reset logs, zero otherwise.
4009 zero_entry(struct ip_fw_chain *chain, u_int32_t arg, int log_only)
4014 uint16_t rulenum = arg & 0xffff;
4015 uint8_t set = (arg >> 16) & 0xff;
4016 uint8_t cmd = (arg >> 24) & 0xff;
4020 if (cmd == 1 && set > RESVD_SET)
4026 for (rule = chain->rules; rule; rule = rule->next) {
4027 /* Skip rules from another set. */
4028 if (cmd == 1 && rule->set != set)
4030 clear_counters(rule, log_only);
4032 msg = log_only ? "ipfw: All logging counts reset.\n" :
4033 "ipfw: Accounting cleared.\n";
4037 * We can have multiple rules with the same number, so we
4038 * need to clear them all.
4040 for (rule = chain->rules; rule; rule = rule->next)
4041 if (rule->rulenum == rulenum) {
4042 while (rule && rule->rulenum == rulenum) {
4043 if (cmd == 0 || rule->set == set)
4044 clear_counters(rule, log_only);
4050 if (!cleared) { /* we did not find any matching rules */
4051 IPFW_WUNLOCK(chain);
4054 msg = log_only ? "ipfw: Entry %d logging count reset.\n" :
4055 "ipfw: Entry %d cleared.\n";
4057 IPFW_WUNLOCK(chain);
4060 log(LOG_SECURITY | LOG_NOTICE, msg, rulenum);
4065 * Check validity of the structure before insert.
4066 * Fortunately rules are simple, so this mostly need to check rule sizes.
4069 check_ipfw_struct(struct ip_fw *rule, int size)
4075 if (size < sizeof(*rule)) {
4076 printf("ipfw: rule too short\n");
4079 /* first, check for valid size */
4082 printf("ipfw: size mismatch (have %d want %d)\n", size, l);
4085 if (rule->act_ofs >= rule->cmd_len) {
4086 printf("ipfw: bogus action offset (%u > %u)\n",
4087 rule->act_ofs, rule->cmd_len - 1);
4091 * Now go for the individual checks. Very simple ones, basically only
4092 * instruction sizes.
4094 for (l = rule->cmd_len, cmd = rule->cmd ;
4095 l > 0 ; l -= cmdlen, cmd += cmdlen) {
4096 cmdlen = F_LEN(cmd);
4098 printf("ipfw: opcode %d size truncated\n",
4102 DEB(printf("ipfw: opcode %d\n", cmd->opcode);)
4103 switch (cmd->opcode) {
4115 case O_IPPRECEDENCE:
4133 if (cmdlen != F_INSN_SIZE(ipfw_insn))
4146 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32))
4151 if (cmdlen != F_INSN_SIZE(ipfw_insn_limit))
4156 if (cmdlen != F_INSN_SIZE(ipfw_insn_log))
4159 ((ipfw_insn_log *)cmd)->log_left =
4160 ((ipfw_insn_log *)cmd)->max_log;
4166 /* only odd command lengths */
4167 if ( !(cmdlen & 1) || cmdlen > 31)
4173 if (cmd->arg1 == 0 || cmd->arg1 > 256) {
4174 printf("ipfw: invalid set size %d\n",
4178 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
4183 case O_IP_SRC_LOOKUP:
4184 case O_IP_DST_LOOKUP:
4185 if (cmd->arg1 >= IPFW_TABLES_MAX) {
4186 printf("ipfw: invalid table number %d\n",
4190 if (cmdlen != F_INSN_SIZE(ipfw_insn) &&
4191 cmdlen != F_INSN_SIZE(ipfw_insn_u32))
4196 if (cmdlen != F_INSN_SIZE(ipfw_insn_mac))
4206 if (cmdlen < 1 || cmdlen > 31)
4212 case O_IP_DSTPORT: /* XXX artificial limit, 30 port pairs */
4213 if (cmdlen < 2 || cmdlen > 31)
4220 if (cmdlen != F_INSN_SIZE(ipfw_insn_if))
4225 if (cmdlen != F_INSN_SIZE(ipfw_insn_altq))
4231 if (cmdlen != F_INSN_SIZE(ipfw_insn))
4236 #ifdef IPFIREWALL_FORWARD
4237 if (cmdlen != F_INSN_SIZE(ipfw_insn_sa))
4246 if (ip_divert_ptr == NULL)
4252 if (!NG_IPFW_LOADED)
4257 #ifdef IPFIREWALL_NAT
4258 if (cmdlen != F_INSN_SIZE(ipfw_insn_nat))
4264 case O_FORWARD_MAC: /* XXX not implemented yet */
4275 if (cmdlen != F_INSN_SIZE(ipfw_insn))
4279 printf("ipfw: opcode %d, multiple actions"
4286 printf("ipfw: opcode %d, action must be"
4295 if (cmdlen != F_INSN_SIZE(struct in6_addr) +
4296 F_INSN_SIZE(ipfw_insn))
4301 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
4302 ((ipfw_insn_u32 *)cmd)->o.arg1)
4306 case O_IP6_SRC_MASK:
4307 case O_IP6_DST_MASK:
4308 if ( !(cmdlen & 1) || cmdlen > 127)
4312 if( cmdlen != F_INSN_SIZE( ipfw_insn_icmp6 ) )
4318 switch (cmd->opcode) {
4328 case O_IP6_SRC_MASK:
4329 case O_IP6_DST_MASK:
4331 printf("ipfw: no IPv6 support in kernel\n");
4332 return EPROTONOSUPPORT;
4335 printf("ipfw: opcode %d, unknown opcode\n",
4341 if (have_action == 0) {
4342 printf("ipfw: missing action\n");
4348 printf("ipfw: opcode %d size %d wrong\n",
4349 cmd->opcode, cmdlen);
4354 * Copy the static and dynamic rules to the supplied buffer
4355 * and return the amount of space actually used.
4358 ipfw_getrules(struct ip_fw_chain *chain, void *buf, size_t space)
4361 char *ep = bp + space;
4364 time_t boot_seconds;
4366 boot_seconds = boottime.tv_sec;
4367 /* XXX this can take a long time and locking will block packet flow */
4369 for (rule = chain->rules; rule ; rule = rule->next) {
4371 * Verify the entry fits in the buffer in case the
4372 * rules changed between calculating buffer space and
4373 * now. This would be better done using a generation
4374 * number but should suffice for now.
4380 * XXX HACK. Store the disable mask in the "next" pointer
4381 * in a wild attempt to keep the ABI the same.
4382 * Why do we do this on EVERY rule?
4384 bcopy(&set_disable, &(((struct ip_fw *)bp)->next_rule),
4385 sizeof(set_disable));
4386 if (((struct ip_fw *)bp)->timestamp)
4387 ((struct ip_fw *)bp)->timestamp += boot_seconds;
4391 IPFW_RUNLOCK(chain);
4393 ipfw_dyn_rule *p, *last = NULL;
4396 for (i = 0 ; i < curr_dyn_buckets; i++)
4397 for (p = ipfw_dyn_v[i] ; p != NULL; p = p->next) {
4398 if (bp + sizeof *p <= ep) {
4399 ipfw_dyn_rule *dst =
4400 (ipfw_dyn_rule *)bp;
4401 bcopy(p, dst, sizeof *p);
4402 bcopy(&(p->rule->rulenum), &(dst->rule),
4403 sizeof(p->rule->rulenum));
4405 * store set number into high word of
4406 * dst->rule pointer.
4408 bcopy(&(p->rule->set),
4409 (char *)&dst->rule +
4410 sizeof(p->rule->rulenum),
4411 sizeof(p->rule->set));
4413 * store a non-null value in "next".
4414 * The userland code will interpret a
4415 * NULL here as a marker
4416 * for the last dynamic rule.
4418 bcopy(&dst, &dst->next, sizeof(dst));
4421 TIME_LEQ(dst->expire, time_uptime) ?
4422 0 : dst->expire - time_uptime ;
4423 bp += sizeof(ipfw_dyn_rule);
4427 if (last != NULL) /* mark last dynamic rule */
4428 bzero(&last->next, sizeof(last));
4430 return (bp - (char *)buf);
4435 * {set|get}sockopt parser.
4438 ipfw_ctl(struct sockopt *sopt)
4440 #define RULE_MAXSIZE (256*sizeof(u_int32_t))
4443 struct ip_fw *buf, *rule;
4444 u_int32_t rulenum[2];
4446 error = priv_check(sopt->sopt_td, PRIV_NETINET_IPFW);
4451 * Disallow modifications in really-really secure mode, but still allow
4452 * the logging counters to be reset.
4454 if (sopt->sopt_name == IP_FW_ADD ||
4455 (sopt->sopt_dir == SOPT_SET && sopt->sopt_name != IP_FW_RESETLOG)) {
4456 error = securelevel_ge(sopt->sopt_td->td_ucred, 3);
4463 switch (sopt->sopt_name) {
4466 * pass up a copy of the current rules. Static rules
4467 * come first (the last of which has number IPFW_DEFAULT_RULE),
4468 * followed by a possibly empty list of dynamic rule.
4469 * The last dynamic rule has NULL in the "next" field.
4471 * Note that the calculated size is used to bound the
4472 * amount of data returned to the user. The rule set may
4473 * change between calculating the size and returning the
4474 * data in which case we'll just return what fits.
4476 size = static_len; /* size of static rules */
4477 if (ipfw_dyn_v) /* add size of dyn.rules */
4478 size += (dyn_count * sizeof(ipfw_dyn_rule));
4481 * XXX todo: if the user passes a short length just to know
4482 * how much room is needed, do not bother filling up the
4483 * buffer, just jump to the sooptcopyout.
4485 buf = malloc(size, M_TEMP, M_WAITOK);
4486 error = sooptcopyout(sopt, buf,
4487 ipfw_getrules(&layer3_chain, buf, size));
4493 * Normally we cannot release the lock on each iteration.
4494 * We could do it here only because we start from the head all
4495 * the times so there is no risk of missing some entries.
4496 * On the other hand, the risk is that we end up with
4497 * a very inconsistent ruleset, so better keep the lock
4498 * around the whole cycle.
4500 * XXX this code can be improved by resetting the head of
4501 * the list to point to the default rule, and then freeing
4502 * the old list without the need for a lock.
4505 IPFW_WLOCK(&layer3_chain);
4506 layer3_chain.reap = NULL;
4507 free_chain(&layer3_chain, 0 /* keep default rule */);
4508 rule = layer3_chain.reap;
4509 layer3_chain.reap = NULL;
4510 IPFW_WUNLOCK(&layer3_chain);
4516 rule = malloc(RULE_MAXSIZE, M_TEMP, M_WAITOK);
4517 error = sooptcopyin(sopt, rule, RULE_MAXSIZE,
4518 sizeof(struct ip_fw) );
4520 error = check_ipfw_struct(rule, sopt->sopt_valsize);
4522 error = add_rule(&layer3_chain, rule);
4523 size = RULESIZE(rule);
4524 if (!error && sopt->sopt_dir == SOPT_GET)
4525 error = sooptcopyout(sopt, rule, size);
4532 * IP_FW_DEL is used for deleting single rules or sets,
4533 * and (ab)used to atomically manipulate sets. Argument size
4534 * is used to distinguish between the two:
4536 * delete single rule or set of rules,
4537 * or reassign rules (or sets) to a different set.
4538 * 2*sizeof(u_int32_t)
4539 * atomic disable/enable sets.
4540 * first u_int32_t contains sets to be disabled,
4541 * second u_int32_t contains sets to be enabled.
4543 error = sooptcopyin(sopt, rulenum,
4544 2*sizeof(u_int32_t), sizeof(u_int32_t));
4547 size = sopt->sopt_valsize;
4548 if (size == sizeof(u_int32_t)) /* delete or reassign */
4549 error = del_entry(&layer3_chain, rulenum[0]);
4550 else if (size == 2*sizeof(u_int32_t)) /* set enable/disable */
4552 (set_disable | rulenum[0]) & ~rulenum[1] &
4553 ~(1<<RESVD_SET); /* set RESVD_SET always enabled */
4559 case IP_FW_RESETLOG: /* argument is an u_int_32, the rule number */
4561 if (sopt->sopt_val != 0) {
4562 error = sooptcopyin(sopt, rulenum,
4563 sizeof(u_int32_t), sizeof(u_int32_t));
4567 error = zero_entry(&layer3_chain, rulenum[0],
4568 sopt->sopt_name == IP_FW_RESETLOG);
4571 case IP_FW_TABLE_ADD:
4573 ipfw_table_entry ent;
4575 error = sooptcopyin(sopt, &ent,
4576 sizeof(ent), sizeof(ent));
4579 error = add_table_entry(&layer3_chain, ent.tbl,
4580 ent.addr, ent.masklen, ent.value);
4584 case IP_FW_TABLE_DEL:
4586 ipfw_table_entry ent;
4588 error = sooptcopyin(sopt, &ent,
4589 sizeof(ent), sizeof(ent));
4592 error = del_table_entry(&layer3_chain, ent.tbl,
4593 ent.addr, ent.masklen);
4597 case IP_FW_TABLE_FLUSH:
4601 error = sooptcopyin(sopt, &tbl,
4602 sizeof(tbl), sizeof(tbl));
4605 IPFW_WLOCK(&layer3_chain);
4606 error = flush_table(&layer3_chain, tbl);
4607 IPFW_WUNLOCK(&layer3_chain);
4611 case IP_FW_TABLE_GETSIZE:
4615 if ((error = sooptcopyin(sopt, &tbl, sizeof(tbl),
4618 IPFW_RLOCK(&layer3_chain);
4619 error = count_table(&layer3_chain, tbl, &cnt);
4620 IPFW_RUNLOCK(&layer3_chain);
4623 error = sooptcopyout(sopt, &cnt, sizeof(cnt));
4627 case IP_FW_TABLE_LIST:
4631 if (sopt->sopt_valsize < sizeof(*tbl)) {
4635 size = sopt->sopt_valsize;
4636 tbl = malloc(size, M_TEMP, M_WAITOK);
4637 error = sooptcopyin(sopt, tbl, size, sizeof(*tbl));
4642 tbl->size = (size - sizeof(*tbl)) /
4643 sizeof(ipfw_table_entry);
4644 IPFW_RLOCK(&layer3_chain);
4645 error = dump_table(&layer3_chain, tbl);
4646 IPFW_RUNLOCK(&layer3_chain);
4651 error = sooptcopyout(sopt, tbl, size);
4656 #ifdef IPFIREWALL_NAT
4659 struct cfg_nat *ptr, *ser_n;
4662 buf = malloc(NAT_BUF_LEN, M_IPFW, M_WAITOK | M_ZERO);
4663 error = sooptcopyin(sopt, buf, NAT_BUF_LEN,
4664 sizeof(struct cfg_nat));
4665 ser_n = (struct cfg_nat *)buf;
4668 * Find/create nat rule.
4670 IPFW_WLOCK(&layer3_chain);
4671 ptr = lookup_nat(ser_n->id);
4673 /* New rule: allocate and init new instance. */
4674 ptr = malloc(sizeof(struct cfg_nat),
4675 M_IPFW, M_NOWAIT | M_ZERO);
4677 IPFW_WUNLOCK(&layer3_chain);
4681 ptr->lib = LibAliasInit(NULL);
4682 if (ptr->lib == NULL) {
4683 IPFW_WUNLOCK(&layer3_chain);
4688 LIST_INIT(&ptr->redir_chain);
4690 /* Entry already present: temporarly unhook it. */
4692 flush_nat_ptrs(ser_n->id);
4694 IPFW_WUNLOCK(&layer3_chain);
4697 * Basic nat configuration.
4699 ptr->id = ser_n->id;
4701 * XXX - what if this rule doesn't nat any ip and just
4703 * do we set aliasaddress to 0.0.0.0?
4705 ptr->ip = ser_n->ip;
4706 ptr->redir_cnt = ser_n->redir_cnt;
4707 ptr->mode = ser_n->mode;
4708 LibAliasSetMode(ptr->lib, ser_n->mode, ser_n->mode);
4709 LibAliasSetAddress(ptr->lib, ptr->ip);
4710 memcpy(ptr->if_name, ser_n->if_name, IF_NAMESIZE);
4713 * Redir and LSNAT configuration.
4715 /* Delete old cfgs. */
4716 del_redir_spool_cfg(ptr, &ptr->redir_chain);
4717 /* Add new entries. */
4718 add_redir_spool_cfg(&buf[(sizeof(struct cfg_nat))], ptr);
4720 IPFW_WLOCK(&layer3_chain);
4721 HOOK_NAT(&layer3_chain.nat, ptr);
4722 IPFW_WUNLOCK(&layer3_chain);
4728 struct cfg_nat *ptr;
4731 error = sooptcopyin(sopt, &i, sizeof i, sizeof i);
4732 IPFW_WLOCK(&layer3_chain);
4733 ptr = lookup_nat(i);
4736 IPFW_WUNLOCK(&layer3_chain);
4741 IPFW_WUNLOCK(&layer3_chain);
4742 del_redir_spool_cfg(ptr, &ptr->redir_chain);
4743 LibAliasUninit(ptr->lib);
4748 case IP_FW_NAT_GET_CONFIG:
4752 struct cfg_redir *r;
4753 struct cfg_spool *s;
4757 off = sizeof(nat_cnt);
4759 data = malloc(NAT_BUF_LEN, M_IPFW, M_WAITOK | M_ZERO);
4760 IPFW_RLOCK(&layer3_chain);
4761 /* Serialize all the data. */
4762 LIST_FOREACH(n, &layer3_chain.nat, _next) {
4764 if (off + SOF_NAT < NAT_BUF_LEN) {
4765 bcopy(n, &data[off], SOF_NAT);
4767 LIST_FOREACH(r, &n->redir_chain, _next) {
4768 if (off + SOF_REDIR < NAT_BUF_LEN) {
4769 bcopy(r, &data[off],
4772 LIST_FOREACH(s, &r->spool_chain,
4774 if (off + SOF_SPOOL <
4790 bcopy(&nat_cnt, data, sizeof(nat_cnt));
4791 IPFW_RUNLOCK(&layer3_chain);
4792 error = sooptcopyout(sopt, data, NAT_BUF_LEN);
4796 IPFW_RUNLOCK(&layer3_chain);
4797 printf("serialized data buffer not big enough:"
4798 "please increase NAT_BUF_LEN\n");
4803 case IP_FW_NAT_GET_LOG:
4806 struct cfg_nat *ptr;
4807 int i, size, cnt, sof;
4810 sof = LIBALIAS_BUF_SIZE;
4813 IPFW_RLOCK(&layer3_chain);
4815 LIST_FOREACH(ptr, &layer3_chain.nat, _next) {
4816 if (ptr->lib->logDesc == NULL)
4819 size = cnt * (sof + sizeof(int));
4820 data = realloc(data, size, M_IPFW, M_NOWAIT | M_ZERO);
4822 IPFW_RUNLOCK(&layer3_chain);
4825 bcopy(&ptr->id, &data[i], sizeof(int));
4827 bcopy(ptr->lib->logDesc, &data[i], sof);
4830 IPFW_RUNLOCK(&layer3_chain);
4831 error = sooptcopyout(sopt, data, size);
4838 printf("ipfw: ipfw_ctl invalid option %d\n", sopt->sopt_name);
4847 * dummynet needs a reference to the default rule, because rules can be
4848 * deleted while packets hold a reference to them. When this happens,
4849 * dummynet changes the reference to the default rule (it could well be a
4850 * NULL pointer, but this way we do not need to check for the special
4851 * case, plus here he have info on the default behaviour).
4853 struct ip_fw *ip_fw_default_rule;
4856 * This procedure is only used to handle keepalives. It is invoked
4857 * every dyn_keepalive_period
4860 ipfw_tick(void * __unused unused)
4862 struct mbuf *m0, *m, *mnext, **mtailp;
4866 if (dyn_keepalive == 0 || ipfw_dyn_v == NULL || dyn_count == 0)
4870 * We make a chain of packets to go out here -- not deferring
4871 * until after we drop the IPFW dynamic rule lock would result
4872 * in a lock order reversal with the normal packet input -> ipfw
4878 for (i = 0 ; i < curr_dyn_buckets ; i++) {
4879 for (q = ipfw_dyn_v[i] ; q ; q = q->next ) {
4880 if (q->dyn_type == O_LIMIT_PARENT)
4882 if (q->id.proto != IPPROTO_TCP)
4884 if ( (q->state & BOTH_SYN) != BOTH_SYN)
4886 if (TIME_LEQ( time_uptime+dyn_keepalive_interval,
4888 continue; /* too early */
4889 if (TIME_LEQ(q->expire, time_uptime))
4890 continue; /* too late, rule expired */
4892 *mtailp = send_pkt(NULL, &(q->id), q->ack_rev - 1,
4893 q->ack_fwd, TH_SYN);
4894 if (*mtailp != NULL)
4895 mtailp = &(*mtailp)->m_nextpkt;
4896 *mtailp = send_pkt(NULL, &(q->id), q->ack_fwd - 1,
4898 if (*mtailp != NULL)
4899 mtailp = &(*mtailp)->m_nextpkt;
4903 for (m = mnext = m0; m != NULL; m = mnext) {
4904 mnext = m->m_nextpkt;
4905 m->m_nextpkt = NULL;
4906 ip_output(m, NULL, NULL, 0, NULL, NULL);
4909 callout_reset(&ipfw_timeout, dyn_keepalive_period*hz, ipfw_tick, NULL);
4915 struct ip_fw default_rule;
4919 /* Setup IPv6 fw sysctl tree. */
4920 sysctl_ctx_init(&ip6_fw_sysctl_ctx);
4921 ip6_fw_sysctl_tree = SYSCTL_ADD_NODE(&ip6_fw_sysctl_ctx,
4922 SYSCTL_STATIC_CHILDREN(_net_inet6_ip6), OID_AUTO, "fw",
4923 CTLFLAG_RW | CTLFLAG_SECURE, 0, "Firewall");
4924 SYSCTL_ADD_PROC(&ip6_fw_sysctl_ctx, SYSCTL_CHILDREN(ip6_fw_sysctl_tree),
4925 OID_AUTO, "enable", CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE3,
4926 &fw6_enable, 0, ipfw_chg_hook, "I", "Enable ipfw+6");
4927 SYSCTL_ADD_INT(&ip6_fw_sysctl_ctx, SYSCTL_CHILDREN(ip6_fw_sysctl_tree),
4928 OID_AUTO, "deny_unknown_exthdrs", CTLFLAG_RW | CTLFLAG_SECURE,
4929 &fw_deny_unknown_exthdrs, 0,
4930 "Deny packets with unknown IPv6 Extension Headers");
4933 layer3_chain.rules = NULL;
4934 IPFW_LOCK_INIT(&layer3_chain);
4935 ipfw_dyn_rule_zone = uma_zcreate("IPFW dynamic rule",
4936 sizeof(ipfw_dyn_rule), NULL, NULL, NULL, NULL,
4938 IPFW_DYN_LOCK_INIT();
4939 callout_init(&ipfw_timeout, CALLOUT_MPSAFE);
4941 bzero(&default_rule, sizeof default_rule);
4943 default_rule.act_ofs = 0;
4944 default_rule.rulenum = IPFW_DEFAULT_RULE;
4945 default_rule.cmd_len = 1;
4946 default_rule.set = RESVD_SET;
4948 default_rule.cmd[0].len = 1;
4949 default_rule.cmd[0].opcode =
4950 #ifdef IPFIREWALL_DEFAULT_TO_ACCEPT
4955 error = add_rule(&layer3_chain, &default_rule);
4957 printf("ipfw2: error %u initializing default rule "
4958 "(support disabled)\n", error);
4959 IPFW_DYN_LOCK_DESTROY();
4960 IPFW_LOCK_DESTROY(&layer3_chain);
4961 uma_zdestroy(ipfw_dyn_rule_zone);
4965 ip_fw_default_rule = layer3_chain.rules;
4970 "initialized, divert %s, "
4971 "rule-based forwarding "
4972 #ifdef IPFIREWALL_FORWARD
4977 "default to %s, logging ",
4983 default_rule.cmd[0].opcode == O_ACCEPT ? "accept" : "deny");
4985 #ifdef IPFIREWALL_VERBOSE
4988 #ifdef IPFIREWALL_VERBOSE_LIMIT
4989 verbose_limit = IPFIREWALL_VERBOSE_LIMIT;
4991 if (fw_verbose == 0)
4992 printf("disabled\n");
4993 else if (verbose_limit == 0)
4994 printf("unlimited\n");
4996 printf("limited to %d packets/entry by default\n",
4999 error = init_tables(&layer3_chain);
5001 IPFW_DYN_LOCK_DESTROY();
5002 IPFW_LOCK_DESTROY(&layer3_chain);
5003 uma_zdestroy(ipfw_dyn_rule_zone);
5006 ip_fw_ctl_ptr = ipfw_ctl;
5007 ip_fw_chk_ptr = ipfw_chk;
5008 callout_reset(&ipfw_timeout, hz, ipfw_tick, NULL);
5009 #ifdef IPFIREWALL_NAT
5010 LIST_INIT(&layer3_chain.nat);
5011 ifaddr_event_tag = EVENTHANDLER_REGISTER(ifaddr_event, ifaddr_change,
5012 NULL, EVENTHANDLER_PRI_ANY);
5021 #ifdef IPFIREWALL_NAT
5022 struct cfg_nat *ptr, *ptr_temp;
5025 ip_fw_chk_ptr = NULL;
5026 ip_fw_ctl_ptr = NULL;
5027 callout_drain(&ipfw_timeout);
5028 IPFW_WLOCK(&layer3_chain);
5029 flush_tables(&layer3_chain);
5030 #ifdef IPFIREWALL_NAT
5031 LIST_FOREACH_SAFE(ptr, &layer3_chain.nat, _next, ptr_temp) {
5032 LIST_REMOVE(ptr, _next);
5033 del_redir_spool_cfg(ptr, &ptr->redir_chain);
5034 LibAliasUninit(ptr->lib);
5037 EVENTHANDLER_DEREGISTER(ifaddr_event, ifaddr_event_tag);
5039 layer3_chain.reap = NULL;
5040 free_chain(&layer3_chain, 1 /* kill default rule */);
5041 reap = layer3_chain.reap, layer3_chain.reap = NULL;
5042 IPFW_WUNLOCK(&layer3_chain);
5045 IPFW_DYN_LOCK_DESTROY();
5046 uma_zdestroy(ipfw_dyn_rule_zone);
5047 if (ipfw_dyn_v != NULL)
5048 free(ipfw_dyn_v, M_IPFW);
5049 IPFW_LOCK_DESTROY(&layer3_chain);
5052 /* Free IPv6 fw sysctl tree. */
5053 sysctl_ctx_free(&ip6_fw_sysctl_ctx);
5056 printf("IP firewall unloaded\n");