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
32 * Implement IP packet firewall (new version)
35 #if !defined(KLD_MODULE)
37 #include "opt_ipdivert.h"
41 #error IPFIREWALL requires INET.
44 #include "opt_inet6.h"
45 #include "opt_ipsec.h"
48 #include <sys/param.h>
49 #include <sys/systm.h>
50 #include <sys/condvar.h>
51 #include <sys/eventhandler.h>
52 #include <sys/malloc.h>
54 #include <sys/kernel.h>
57 #include <sys/module.h>
60 #include <sys/rwlock.h>
61 #include <sys/socket.h>
62 #include <sys/socketvar.h>
63 #include <sys/sysctl.h>
64 #include <sys/syslog.h>
65 #include <sys/ucred.h>
67 #include <net/radix.h>
68 #include <net/route.h>
69 #include <netinet/in.h>
70 #include <netinet/in_systm.h>
71 #include <netinet/in_var.h>
72 #include <netinet/in_pcb.h>
73 #include <netinet/ip.h>
74 #include <netinet/ip_var.h>
75 #include <netinet/ip_icmp.h>
76 #include <netinet/ip_fw.h>
77 #include <netinet/ip_divert.h>
78 #include <netinet/ip_dummynet.h>
79 #include <netinet/ip_carp.h>
80 #include <netinet/pim.h>
81 #include <netinet/tcp.h>
82 #include <netinet/tcp_timer.h>
83 #include <netinet/tcp_var.h>
84 #include <netinet/tcpip.h>
85 #include <netinet/udp.h>
86 #include <netinet/udp_var.h>
87 #include <netinet/sctp.h>
89 #include <netinet/libalias/alias.h>
90 #include <netinet/libalias/alias_local.h>
92 #include <netgraph/ng_ipfw.h>
94 #include <altq/if_altq.h>
97 #include <netinet6/ipsec.h>
100 #include <netinet/ip6.h>
101 #include <netinet/icmp6.h>
103 #include <netinet6/scope6_var.h>
106 #include <netinet/if_ether.h> /* XXX for ETHERTYPE_IP */
108 #include <machine/in_cksum.h> /* XXX for in_cksum */
110 #include <security/mac/mac_framework.h>
113 * set_disable contains one bit per set value (0..31).
114 * If the bit is set, all rules with the corresponding set
115 * are disabled. Set RESVD_SET(31) is reserved for the default rule
116 * and rules that are not deleted by the flush command,
117 * and CANNOT be disabled.
118 * Rules in set RESVD_SET can only be deleted explicitly.
120 static u_int32_t set_disable;
122 static int fw_verbose;
123 static int verbose_limit;
125 static struct callout ipfw_timeout;
126 static uma_zone_t ipfw_dyn_rule_zone;
127 #define IPFW_DEFAULT_RULE 65535
130 * Data structure to cache our ucred related
131 * information. This structure only gets used if
132 * the user specified UID/GID based constraints in
136 gid_t fw_groups[NGROUPS];
142 #define IPFW_TABLES_MAX 128
144 struct ip_fw *rules; /* list of rules */
145 struct ip_fw *reap; /* list of rules to reap */
146 LIST_HEAD(, cfg_nat) nat; /* list of nat entries */
147 struct radix_node_head *tables[IPFW_TABLES_MAX];
150 #define IPFW_LOCK_INIT(_chain) \
151 rw_init(&(_chain)->rwmtx, "IPFW static rules")
152 #define IPFW_LOCK_DESTROY(_chain) rw_destroy(&(_chain)->rwmtx)
153 #define IPFW_WLOCK_ASSERT(_chain) do { \
154 rw_assert(&(_chain)->rwmtx, RA_WLOCKED); \
155 NET_ASSERT_GIANT(); \
158 #define IPFW_RLOCK(p) rw_rlock(&(p)->rwmtx)
159 #define IPFW_RUNLOCK(p) rw_runlock(&(p)->rwmtx)
160 #define IPFW_WLOCK(p) rw_wlock(&(p)->rwmtx)
161 #define IPFW_WUNLOCK(p) rw_wunlock(&(p)->rwmtx)
164 * list of rules for layer 3
166 static struct ip_fw_chain layer3_chain;
168 MALLOC_DEFINE(M_IPFW, "IpFw/IpAcct", "IpFw/IpAcct chain's");
169 MALLOC_DEFINE(M_IPFW_TBL, "ipfw_tbl", "IpFw tables");
172 struct radix_node rn[2];
173 struct sockaddr_in addr, mask;
177 static int fw_debug = 1;
178 static int autoinc_step = 100; /* bounded to 1..1000 in add_rule() */
180 extern int ipfw_chg_hook(SYSCTL_HANDLER_ARGS);
183 SYSCTL_NODE(_net_inet_ip, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall");
184 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, enable,
185 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE3, &fw_enable, 0,
186 ipfw_chg_hook, "I", "Enable ipfw");
187 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, autoinc_step, CTLFLAG_RW,
188 &autoinc_step, 0, "Rule number autincrement step");
189 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, one_pass,
190 CTLFLAG_RW | CTLFLAG_SECURE3,
192 "Only do a single pass through ipfw when using dummynet(4)");
193 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, debug, CTLFLAG_RW,
194 &fw_debug, 0, "Enable printing of debug ip_fw statements");
195 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose,
196 CTLFLAG_RW | CTLFLAG_SECURE3,
197 &fw_verbose, 0, "Log matches to ipfw rules");
198 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose_limit, CTLFLAG_RW,
199 &verbose_limit, 0, "Set upper limit of matches of ipfw rules logged");
202 * Description of dynamic rules.
204 * Dynamic rules are stored in lists accessed through a hash table
205 * (ipfw_dyn_v) whose size is curr_dyn_buckets. This value can
206 * be modified through the sysctl variable dyn_buckets which is
207 * updated when the table becomes empty.
209 * XXX currently there is only one list, ipfw_dyn.
211 * When a packet is received, its address fields are first masked
212 * with the mask defined for the rule, then hashed, then matched
213 * against the entries in the corresponding list.
214 * Dynamic rules can be used for different purposes:
216 * + enforcing limits on the number of sessions;
217 * + in-kernel NAT (not implemented yet)
219 * The lifetime of dynamic rules is regulated by dyn_*_lifetime,
220 * measured in seconds and depending on the flags.
222 * The total number of dynamic rules is stored in dyn_count.
223 * The max number of dynamic rules is dyn_max. When we reach
224 * the maximum number of rules we do not create anymore. This is
225 * done to avoid consuming too much memory, but also too much
226 * time when searching on each packet (ideally, we should try instead
227 * to put a limit on the length of the list on each bucket...).
229 * Each dynamic rule holds a pointer to the parent ipfw rule so
230 * we know what action to perform. Dynamic rules are removed when
231 * the parent rule is deleted. XXX we should make them survive.
233 * There are some limitations with dynamic rules -- we do not
234 * obey the 'randomized match', and we do not do multiple
235 * passes through the firewall. XXX check the latter!!!
237 static ipfw_dyn_rule **ipfw_dyn_v = NULL;
238 static u_int32_t dyn_buckets = 256; /* must be power of 2 */
239 static u_int32_t curr_dyn_buckets = 256; /* must be power of 2 */
241 static struct mtx ipfw_dyn_mtx; /* mutex guarding dynamic rules */
242 #define IPFW_DYN_LOCK_INIT() \
243 mtx_init(&ipfw_dyn_mtx, "IPFW dynamic rules", NULL, MTX_DEF)
244 #define IPFW_DYN_LOCK_DESTROY() mtx_destroy(&ipfw_dyn_mtx)
245 #define IPFW_DYN_LOCK() mtx_lock(&ipfw_dyn_mtx)
246 #define IPFW_DYN_UNLOCK() mtx_unlock(&ipfw_dyn_mtx)
247 #define IPFW_DYN_LOCK_ASSERT() mtx_assert(&ipfw_dyn_mtx, MA_OWNED)
250 * Timeouts for various events in handing dynamic rules.
252 static u_int32_t dyn_ack_lifetime = 300;
253 static u_int32_t dyn_syn_lifetime = 20;
254 static u_int32_t dyn_fin_lifetime = 1;
255 static u_int32_t dyn_rst_lifetime = 1;
256 static u_int32_t dyn_udp_lifetime = 10;
257 static u_int32_t dyn_short_lifetime = 5;
260 * Keepalives are sent if dyn_keepalive is set. They are sent every
261 * dyn_keepalive_period seconds, in the last dyn_keepalive_interval
262 * seconds of lifetime of a rule.
263 * dyn_rst_lifetime and dyn_fin_lifetime should be strictly lower
264 * than dyn_keepalive_period.
267 static u_int32_t dyn_keepalive_interval = 20;
268 static u_int32_t dyn_keepalive_period = 5;
269 static u_int32_t dyn_keepalive = 1; /* do send keepalives */
271 static u_int32_t static_count; /* # of static rules */
272 static u_int32_t static_len; /* size in bytes of static rules */
273 static u_int32_t dyn_count; /* # of dynamic rules */
274 static u_int32_t dyn_max = 4096; /* max # of dynamic rules */
276 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_buckets, CTLFLAG_RW,
277 &dyn_buckets, 0, "Number of dyn. buckets");
278 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, curr_dyn_buckets, CTLFLAG_RD,
279 &curr_dyn_buckets, 0, "Current Number of dyn. buckets");
280 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_count, CTLFLAG_RD,
281 &dyn_count, 0, "Number of dyn. rules");
282 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_max, CTLFLAG_RW,
283 &dyn_max, 0, "Max number of dyn. rules");
284 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, static_count, CTLFLAG_RD,
285 &static_count, 0, "Number of static rules");
286 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_ack_lifetime, CTLFLAG_RW,
287 &dyn_ack_lifetime, 0, "Lifetime of dyn. rules for acks");
288 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_syn_lifetime, CTLFLAG_RW,
289 &dyn_syn_lifetime, 0, "Lifetime of dyn. rules for syn");
290 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_fin_lifetime, CTLFLAG_RW,
291 &dyn_fin_lifetime, 0, "Lifetime of dyn. rules for fin");
292 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_rst_lifetime, CTLFLAG_RW,
293 &dyn_rst_lifetime, 0, "Lifetime of dyn. rules for rst");
294 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_udp_lifetime, CTLFLAG_RW,
295 &dyn_udp_lifetime, 0, "Lifetime of dyn. rules for UDP");
296 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_short_lifetime, CTLFLAG_RW,
297 &dyn_short_lifetime, 0, "Lifetime of dyn. rules for other situations");
298 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_keepalive, CTLFLAG_RW,
299 &dyn_keepalive, 0, "Enable keepalives for dyn. rules");
303 * IPv6 specific variables
305 SYSCTL_DECL(_net_inet6_ip6);
307 static struct sysctl_ctx_list ip6_fw_sysctl_ctx;
308 static struct sysctl_oid *ip6_fw_sysctl_tree;
310 #endif /* SYSCTL_NODE */
312 #ifdef IPFIREWALL_NAT
313 MODULE_DEPEND(ipfw, libalias, 1, 1, 1);
315 static int fw_deny_unknown_exthdrs = 1;
319 * L3HDR maps an ipv4 pointer into a layer3 header pointer of type T
320 * Other macros just cast void * into the appropriate type
322 #define L3HDR(T, ip) ((T *)((u_int32_t *)(ip) + (ip)->ip_hl))
323 #define TCP(p) ((struct tcphdr *)(p))
324 #define SCTP(p) ((struct sctphdr *)(p))
325 #define UDP(p) ((struct udphdr *)(p))
326 #define ICMP(p) ((struct icmphdr *)(p))
327 #define ICMP6(p) ((struct icmp6_hdr *)(p))
330 icmptype_match(struct icmphdr *icmp, ipfw_insn_u32 *cmd)
332 int type = icmp->icmp_type;
334 return (type <= ICMP_MAXTYPE && (cmd->d[0] & (1<<type)) );
337 #define TT ( (1 << ICMP_ECHO) | (1 << ICMP_ROUTERSOLICIT) | \
338 (1 << ICMP_TSTAMP) | (1 << ICMP_IREQ) | (1 << ICMP_MASKREQ) )
341 is_icmp_query(struct icmphdr *icmp)
343 int type = icmp->icmp_type;
345 return (type <= ICMP_MAXTYPE && (TT & (1<<type)) );
350 * The following checks use two arrays of 8 or 16 bits to store the
351 * bits that we want set or clear, respectively. They are in the
352 * low and high half of cmd->arg1 or cmd->d[0].
354 * We scan options and store the bits we find set. We succeed if
356 * (want_set & ~bits) == 0 && (want_clear & ~bits) == want_clear
358 * The code is sometimes optimized not to store additional variables.
362 flags_match(ipfw_insn *cmd, u_int8_t bits)
367 if ( ((cmd->arg1 & 0xff) & bits) != 0)
368 return 0; /* some bits we want set were clear */
369 want_clear = (cmd->arg1 >> 8) & 0xff;
370 if ( (want_clear & bits) != want_clear)
371 return 0; /* some bits we want clear were set */
376 ipopts_match(struct ip *ip, ipfw_insn *cmd)
378 int optlen, bits = 0;
379 u_char *cp = (u_char *)(ip + 1);
380 int x = (ip->ip_hl << 2) - sizeof (struct ip);
382 for (; x > 0; x -= optlen, cp += optlen) {
383 int opt = cp[IPOPT_OPTVAL];
385 if (opt == IPOPT_EOL)
387 if (opt == IPOPT_NOP)
390 optlen = cp[IPOPT_OLEN];
391 if (optlen <= 0 || optlen > x)
392 return 0; /* invalid or truncated */
400 bits |= IP_FW_IPOPT_LSRR;
404 bits |= IP_FW_IPOPT_SSRR;
408 bits |= IP_FW_IPOPT_RR;
412 bits |= IP_FW_IPOPT_TS;
416 return (flags_match(cmd, bits));
420 tcpopts_match(struct tcphdr *tcp, ipfw_insn *cmd)
422 int optlen, bits = 0;
423 u_char *cp = (u_char *)(tcp + 1);
424 int x = (tcp->th_off << 2) - sizeof(struct tcphdr);
426 for (; x > 0; x -= optlen, cp += optlen) {
428 if (opt == TCPOPT_EOL)
430 if (opt == TCPOPT_NOP)
444 bits |= IP_FW_TCPOPT_MSS;
448 bits |= IP_FW_TCPOPT_WINDOW;
451 case TCPOPT_SACK_PERMITTED:
453 bits |= IP_FW_TCPOPT_SACK;
456 case TCPOPT_TIMESTAMP:
457 bits |= IP_FW_TCPOPT_TS;
462 return (flags_match(cmd, bits));
466 iface_match(struct ifnet *ifp, ipfw_insn_if *cmd)
468 if (ifp == NULL) /* no iface with this packet, match fails */
470 /* Check by name or by IP address */
471 if (cmd->name[0] != '\0') { /* match by name */
474 if (fnmatch(cmd->name, ifp->if_xname, 0) == 0)
477 if (strncmp(ifp->if_xname, cmd->name, IFNAMSIZ) == 0)
484 TAILQ_FOREACH(ia, &ifp->if_addrhead, ifa_link) {
485 if (ia->ifa_addr->sa_family != AF_INET)
487 if (cmd->p.ip.s_addr == ((struct sockaddr_in *)
488 (ia->ifa_addr))->sin_addr.s_addr)
489 return(1); /* match */
492 return(0); /* no match, fail ... */
496 * The verify_path function checks if a route to the src exists and
497 * if it is reachable via ifp (when provided).
499 * The 'verrevpath' option checks that the interface that an IP packet
500 * arrives on is the same interface that traffic destined for the
501 * packet's source address would be routed out of. The 'versrcreach'
502 * option just checks that the source address is reachable via any route
503 * (except default) in the routing table. These two are a measure to block
504 * forged packets. This is also commonly known as "anti-spoofing" or Unicast
505 * Reverse Path Forwarding (Unicast RFP) in Cisco-ese. The name of the knobs
506 * is purposely reminiscent of the Cisco IOS command,
508 * ip verify unicast reverse-path
509 * ip verify unicast source reachable-via any
511 * which implements the same functionality. But note that syntax is
512 * misleading. The check may be performed on all IP packets whether unicast,
513 * multicast, or broadcast.
516 verify_path(struct in_addr src, struct ifnet *ifp)
519 struct sockaddr_in *dst;
521 bzero(&ro, sizeof(ro));
523 dst = (struct sockaddr_in *)&(ro.ro_dst);
524 dst->sin_family = AF_INET;
525 dst->sin_len = sizeof(*dst);
527 rtalloc_ign(&ro, RTF_CLONING);
529 if (ro.ro_rt == NULL)
533 * If ifp is provided, check for equality with rtentry.
534 * We should use rt->rt_ifa->ifa_ifp, instead of rt->rt_ifp,
535 * in order to pass packets injected back by if_simloop():
536 * if useloopback == 1 routing entry (via lo0) for our own address
537 * may exist, so we need to handle routing assymetry.
539 if (ifp != NULL && ro.ro_rt->rt_ifa->ifa_ifp != ifp) {
544 /* if no ifp provided, check if rtentry is not default route */
546 satosin(rt_key(ro.ro_rt))->sin_addr.s_addr == INADDR_ANY) {
551 /* or if this is a blackhole/reject route */
552 if (ifp == NULL && ro.ro_rt->rt_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
557 /* found valid route */
564 * ipv6 specific rules here...
567 icmp6type_match (int type, ipfw_insn_u32 *cmd)
569 return (type <= ICMP6_MAXTYPE && (cmd->d[type/32] & (1<<(type%32)) ) );
573 flow6id_match( int curr_flow, ipfw_insn_u32 *cmd )
576 for (i=0; i <= cmd->o.arg1; ++i )
577 if (curr_flow == cmd->d[i] )
582 /* support for IP6_*_ME opcodes */
584 search_ip6_addr_net (struct in6_addr * ip6_addr)
588 struct in6_ifaddr *fdm;
589 struct in6_addr copia;
591 TAILQ_FOREACH(mdc, &ifnet, if_link)
592 TAILQ_FOREACH(mdc2, &mdc->if_addrlist, ifa_list) {
593 if (mdc2->ifa_addr->sa_family == AF_INET6) {
594 fdm = (struct in6_ifaddr *)mdc2;
595 copia = fdm->ia_addr.sin6_addr;
596 /* need for leaving scope_id in the sock_addr */
597 in6_clearscope(&copia);
598 if (IN6_ARE_ADDR_EQUAL(ip6_addr, &copia))
606 verify_path6(struct in6_addr *src, struct ifnet *ifp)
609 struct sockaddr_in6 *dst;
611 bzero(&ro, sizeof(ro));
613 dst = (struct sockaddr_in6 * )&(ro.ro_dst);
614 dst->sin6_family = AF_INET6;
615 dst->sin6_len = sizeof(*dst);
616 dst->sin6_addr = *src;
617 rtalloc_ign((struct route *)&ro, RTF_CLONING);
619 if (ro.ro_rt == NULL)
623 * if ifp is provided, check for equality with rtentry
624 * We should use rt->rt_ifa->ifa_ifp, instead of rt->rt_ifp,
625 * to support the case of sending packets to an address of our own.
626 * (where the former interface is the first argument of if_simloop()
627 * (=ifp), the latter is lo0)
629 if (ifp != NULL && ro.ro_rt->rt_ifa->ifa_ifp != ifp) {
634 /* if no ifp provided, check if rtentry is not default route */
636 IN6_IS_ADDR_UNSPECIFIED(&satosin6(rt_key(ro.ro_rt))->sin6_addr)) {
641 /* or if this is a blackhole/reject route */
642 if (ifp == NULL && ro.ro_rt->rt_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
647 /* found valid route */
653 hash_packet6(struct ipfw_flow_id *id)
656 i = (id->dst_ip6.__u6_addr.__u6_addr32[2]) ^
657 (id->dst_ip6.__u6_addr.__u6_addr32[3]) ^
658 (id->src_ip6.__u6_addr.__u6_addr32[2]) ^
659 (id->src_ip6.__u6_addr.__u6_addr32[3]) ^
660 (id->dst_port) ^ (id->src_port);
665 is_icmp6_query(int icmp6_type)
667 if ((icmp6_type <= ICMP6_MAXTYPE) &&
668 (icmp6_type == ICMP6_ECHO_REQUEST ||
669 icmp6_type == ICMP6_MEMBERSHIP_QUERY ||
670 icmp6_type == ICMP6_WRUREQUEST ||
671 icmp6_type == ICMP6_FQDN_QUERY ||
672 icmp6_type == ICMP6_NI_QUERY))
679 send_reject6(struct ip_fw_args *args, int code, u_int hlen, struct ip6_hdr *ip6)
684 if (code == ICMP6_UNREACH_RST && args->f_id.proto == IPPROTO_TCP) {
692 tcp = (struct tcphdr *)((char *)ip6 + hlen);
694 if ((tcp->th_flags & TH_RST) != 0) {
702 ti.th.th_seq = ntohl(ti.th.th_seq);
703 ti.th.th_ack = ntohl(ti.th.th_ack);
704 ti.ip6.ip6_nxt = IPPROTO_TCP;
706 if (ti.th.th_flags & TH_ACK) {
712 if ((m->m_flags & M_PKTHDR) != 0) {
714 * total new data to ACK is:
715 * total packet length,
716 * minus the header length,
717 * minus the tcp header length.
719 ack += m->m_pkthdr.len - hlen
720 - (ti.th.th_off << 2);
721 } else if (ip6->ip6_plen) {
722 ack += ntohs(ip6->ip6_plen) + sizeof(*ip6) -
723 hlen - (ti.th.th_off << 2);
728 if (tcp->th_flags & TH_SYN)
731 flags = TH_RST|TH_ACK;
733 bcopy(&ti, ip6, sizeof(ti));
735 * m is only used to recycle the mbuf
736 * The data in it is never read so we don't need
737 * to correct the offsets or anything
739 tcp_respond(NULL, ip6, tcp, m, ack, seq, flags);
740 } else if (code != ICMP6_UNREACH_RST) { /* Send an ICMPv6 unreach. */
743 * Unlike above, the mbufs need to line up with the ip6 hdr,
744 * as the contents are read. We need to m_adj() the
746 * The mbuf will however be thrown away so we can adjust it.
747 * Remember we did an m_pullup on it already so we
748 * can make some assumptions about contiguousness.
751 m_adj(m, args->L3offset);
753 icmp6_error(m, ICMP6_DST_UNREACH, code, 0);
762 static u_int64_t norule_counter; /* counter for ipfw_log(NULL...) */
764 #define SNPARGS(buf, len) buf + len, sizeof(buf) > len ? sizeof(buf) - len : 0
765 #define SNP(buf) buf, sizeof(buf)
768 * We enter here when we have a rule with O_LOG.
769 * XXX this function alone takes about 2Kbytes of code!
772 ipfw_log(struct ip_fw *f, u_int hlen, struct ip_fw_args *args,
773 struct mbuf *m, struct ifnet *oif, u_short offset, uint32_t tablearg,
776 struct ether_header *eh = args->eh;
778 int limit_reached = 0;
779 char action2[40], proto[128], fragment[32];
784 if (f == NULL) { /* bogus pkt */
785 if (verbose_limit != 0 && norule_counter >= verbose_limit)
788 if (norule_counter == verbose_limit)
789 limit_reached = verbose_limit;
791 } else { /* O_LOG is the first action, find the real one */
792 ipfw_insn *cmd = ACTION_PTR(f);
793 ipfw_insn_log *l = (ipfw_insn_log *)cmd;
795 if (l->max_log != 0 && l->log_left == 0)
798 if (l->log_left == 0)
799 limit_reached = l->max_log;
800 cmd += F_LEN(cmd); /* point to first action */
801 if (cmd->opcode == O_ALTQ) {
802 ipfw_insn_altq *altq = (ipfw_insn_altq *)cmd;
804 snprintf(SNPARGS(action2, 0), "Altq %d",
808 if (cmd->opcode == O_PROB)
811 if (cmd->opcode == O_TAG)
815 switch (cmd->opcode) {
821 if (cmd->arg1==ICMP_REJECT_RST)
823 else if (cmd->arg1==ICMP_UNREACH_HOST)
826 snprintf(SNPARGS(action2, 0), "Unreach %d",
831 if (cmd->arg1==ICMP6_UNREACH_RST)
834 snprintf(SNPARGS(action2, 0), "Unreach %d",
845 snprintf(SNPARGS(action2, 0), "Divert %d",
849 snprintf(SNPARGS(action2, 0), "Tee %d",
853 snprintf(SNPARGS(action2, 0), "SkipTo %d",
857 snprintf(SNPARGS(action2, 0), "Pipe %d",
861 snprintf(SNPARGS(action2, 0), "Queue %d",
865 ipfw_insn_sa *sa = (ipfw_insn_sa *)cmd;
867 struct in_addr dummyaddr;
868 if (sa->sa.sin_addr.s_addr == INADDR_ANY)
869 dummyaddr.s_addr = htonl(tablearg);
871 dummyaddr.s_addr = sa->sa.sin_addr.s_addr;
873 len = snprintf(SNPARGS(action2, 0), "Forward to %s",
874 inet_ntoa(dummyaddr));
877 snprintf(SNPARGS(action2, len), ":%d",
882 snprintf(SNPARGS(action2, 0), "Netgraph %d",
886 snprintf(SNPARGS(action2, 0), "Ngtee %d",
898 if (hlen == 0) { /* non-ip */
899 snprintf(SNPARGS(proto, 0), "MAC");
903 char src[48], dst[48];
904 struct icmphdr *icmp;
908 struct ip6_hdr *ip6 = NULL;
909 struct icmp6_hdr *icmp6;
914 if (IS_IP6_FLOW_ID(&(args->f_id))) {
915 char ip6buf[INET6_ADDRSTRLEN];
916 snprintf(src, sizeof(src), "[%s]",
917 ip6_sprintf(ip6buf, &args->f_id.src_ip6));
918 snprintf(dst, sizeof(dst), "[%s]",
919 ip6_sprintf(ip6buf, &args->f_id.dst_ip6));
921 ip6 = (struct ip6_hdr *)ip;
922 tcp = (struct tcphdr *)(((char *)ip) + hlen);
923 udp = (struct udphdr *)(((char *)ip) + hlen);
927 tcp = L3HDR(struct tcphdr, ip);
928 udp = L3HDR(struct udphdr, ip);
930 inet_ntoa_r(ip->ip_src, src);
931 inet_ntoa_r(ip->ip_dst, dst);
934 switch (args->f_id.proto) {
936 len = snprintf(SNPARGS(proto, 0), "TCP %s", src);
938 snprintf(SNPARGS(proto, len), ":%d %s:%d",
939 ntohs(tcp->th_sport),
941 ntohs(tcp->th_dport));
943 snprintf(SNPARGS(proto, len), " %s", dst);
947 len = snprintf(SNPARGS(proto, 0), "UDP %s", src);
949 snprintf(SNPARGS(proto, len), ":%d %s:%d",
950 ntohs(udp->uh_sport),
952 ntohs(udp->uh_dport));
954 snprintf(SNPARGS(proto, len), " %s", dst);
958 icmp = L3HDR(struct icmphdr, ip);
960 len = snprintf(SNPARGS(proto, 0),
962 icmp->icmp_type, icmp->icmp_code);
964 len = snprintf(SNPARGS(proto, 0), "ICMP ");
965 len += snprintf(SNPARGS(proto, len), "%s", src);
966 snprintf(SNPARGS(proto, len), " %s", dst);
970 icmp6 = (struct icmp6_hdr *)(((char *)ip) + hlen);
972 len = snprintf(SNPARGS(proto, 0),
974 icmp6->icmp6_type, icmp6->icmp6_code);
976 len = snprintf(SNPARGS(proto, 0), "ICMPv6 ");
977 len += snprintf(SNPARGS(proto, len), "%s", src);
978 snprintf(SNPARGS(proto, len), " %s", dst);
982 len = snprintf(SNPARGS(proto, 0), "P:%d %s",
983 args->f_id.proto, src);
984 snprintf(SNPARGS(proto, len), " %s", dst);
989 if (IS_IP6_FLOW_ID(&(args->f_id))) {
990 if (offset & (IP6F_OFF_MASK | IP6F_MORE_FRAG))
991 snprintf(SNPARGS(fragment, 0),
992 " (frag %08x:%d@%d%s)",
994 ntohs(ip6->ip6_plen) - hlen,
995 ntohs(offset & IP6F_OFF_MASK) << 3,
996 (offset & IP6F_MORE_FRAG) ? "+" : "");
1001 if (eh != NULL) { /* layer 2 packets are as on the wire */
1002 ip_off = ntohs(ip->ip_off);
1003 ip_len = ntohs(ip->ip_len);
1005 ip_off = ip->ip_off;
1006 ip_len = ip->ip_len;
1008 if (ip_off & (IP_MF | IP_OFFMASK))
1009 snprintf(SNPARGS(fragment, 0),
1010 " (frag %d:%d@%d%s)",
1011 ntohs(ip->ip_id), ip_len - (ip->ip_hl << 2),
1013 (ip_off & IP_MF) ? "+" : "");
1016 if (oif || m->m_pkthdr.rcvif)
1017 log(LOG_SECURITY | LOG_INFO,
1018 "ipfw: %d %s %s %s via %s%s\n",
1019 f ? f->rulenum : -1,
1020 action, proto, oif ? "out" : "in",
1021 oif ? oif->if_xname : m->m_pkthdr.rcvif->if_xname,
1024 log(LOG_SECURITY | LOG_INFO,
1025 "ipfw: %d %s %s [no if info]%s\n",
1026 f ? f->rulenum : -1,
1027 action, proto, fragment);
1029 log(LOG_SECURITY | LOG_NOTICE,
1030 "ipfw: limit %d reached on entry %d\n",
1031 limit_reached, f ? f->rulenum : -1);
1035 * IMPORTANT: the hash function for dynamic rules must be commutative
1036 * in source and destination (ip,port), because rules are bidirectional
1037 * and we want to find both in the same bucket.
1040 hash_packet(struct ipfw_flow_id *id)
1045 if (IS_IP6_FLOW_ID(id))
1046 i = hash_packet6(id);
1049 i = (id->dst_ip) ^ (id->src_ip) ^ (id->dst_port) ^ (id->src_port);
1050 i &= (curr_dyn_buckets - 1);
1055 * unlink a dynamic rule from a chain. prev is a pointer to
1056 * the previous one, q is a pointer to the rule to delete,
1057 * head is a pointer to the head of the queue.
1058 * Modifies q and potentially also head.
1060 #define UNLINK_DYN_RULE(prev, head, q) { \
1061 ipfw_dyn_rule *old_q = q; \
1063 /* remove a refcount to the parent */ \
1064 if (q->dyn_type == O_LIMIT) \
1065 q->parent->count--; \
1066 DEB(printf("ipfw: unlink entry 0x%08x %d -> 0x%08x %d, %d left\n",\
1067 (q->id.src_ip), (q->id.src_port), \
1068 (q->id.dst_ip), (q->id.dst_port), dyn_count-1 ); ) \
1070 prev->next = q = q->next; \
1072 head = q = q->next; \
1074 uma_zfree(ipfw_dyn_rule_zone, old_q); }
1076 #define TIME_LEQ(a,b) ((int)((a)-(b)) <= 0)
1079 * Remove dynamic rules pointing to "rule", or all of them if rule == NULL.
1081 * If keep_me == NULL, rules are deleted even if not expired,
1082 * otherwise only expired rules are removed.
1084 * The value of the second parameter is also used to point to identify
1085 * a rule we absolutely do not want to remove (e.g. because we are
1086 * holding a reference to it -- this is the case with O_LIMIT_PARENT
1087 * rules). The pointer is only used for comparison, so any non-null
1091 remove_dyn_rule(struct ip_fw *rule, ipfw_dyn_rule *keep_me)
1093 static u_int32_t last_remove = 0;
1095 #define FORCE (keep_me == NULL)
1097 ipfw_dyn_rule *prev, *q;
1098 int i, pass = 0, max_pass = 0;
1100 IPFW_DYN_LOCK_ASSERT();
1102 if (ipfw_dyn_v == NULL || dyn_count == 0)
1104 /* do not expire more than once per second, it is useless */
1105 if (!FORCE && last_remove == time_uptime)
1107 last_remove = time_uptime;
1110 * because O_LIMIT refer to parent rules, during the first pass only
1111 * remove child and mark any pending LIMIT_PARENT, and remove
1112 * them in a second pass.
1115 for (i = 0 ; i < curr_dyn_buckets ; i++) {
1116 for (prev=NULL, q = ipfw_dyn_v[i] ; q ; ) {
1118 * Logic can become complex here, so we split tests.
1122 if (rule != NULL && rule != q->rule)
1123 goto next; /* not the one we are looking for */
1124 if (q->dyn_type == O_LIMIT_PARENT) {
1126 * handle parent in the second pass,
1127 * record we need one.
1132 if (FORCE && q->count != 0 ) {
1133 /* XXX should not happen! */
1134 printf("ipfw: OUCH! cannot remove rule,"
1135 " count %d\n", q->count);
1139 !TIME_LEQ( q->expire, time_uptime ))
1142 if (q->dyn_type != O_LIMIT_PARENT || !q->count) {
1143 UNLINK_DYN_RULE(prev, ipfw_dyn_v[i], q);
1151 if (pass++ < max_pass)
1157 * lookup a dynamic rule.
1159 static ipfw_dyn_rule *
1160 lookup_dyn_rule_locked(struct ipfw_flow_id *pkt, int *match_direction,
1164 * stateful ipfw extensions.
1165 * Lookup into dynamic session queue
1167 #define MATCH_REVERSE 0
1168 #define MATCH_FORWARD 1
1169 #define MATCH_NONE 2
1170 #define MATCH_UNKNOWN 3
1171 int i, dir = MATCH_NONE;
1172 ipfw_dyn_rule *prev, *q=NULL;
1174 IPFW_DYN_LOCK_ASSERT();
1176 if (ipfw_dyn_v == NULL)
1177 goto done; /* not found */
1178 i = hash_packet( pkt );
1179 for (prev=NULL, q = ipfw_dyn_v[i] ; q != NULL ; ) {
1180 if (q->dyn_type == O_LIMIT_PARENT && q->count)
1182 if (TIME_LEQ( q->expire, time_uptime)) { /* expire entry */
1183 UNLINK_DYN_RULE(prev, ipfw_dyn_v[i], q);
1186 if (pkt->proto == q->id.proto &&
1187 q->dyn_type != O_LIMIT_PARENT) {
1188 if (IS_IP6_FLOW_ID(pkt)) {
1189 if (IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
1190 &(q->id.src_ip6)) &&
1191 IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
1192 &(q->id.dst_ip6)) &&
1193 pkt->src_port == q->id.src_port &&
1194 pkt->dst_port == q->id.dst_port ) {
1195 dir = MATCH_FORWARD;
1198 if (IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
1199 &(q->id.dst_ip6)) &&
1200 IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
1201 &(q->id.src_ip6)) &&
1202 pkt->src_port == q->id.dst_port &&
1203 pkt->dst_port == q->id.src_port ) {
1204 dir = MATCH_REVERSE;
1208 if (pkt->src_ip == q->id.src_ip &&
1209 pkt->dst_ip == q->id.dst_ip &&
1210 pkt->src_port == q->id.src_port &&
1211 pkt->dst_port == q->id.dst_port ) {
1212 dir = MATCH_FORWARD;
1215 if (pkt->src_ip == q->id.dst_ip &&
1216 pkt->dst_ip == q->id.src_ip &&
1217 pkt->src_port == q->id.dst_port &&
1218 pkt->dst_port == q->id.src_port ) {
1219 dir = MATCH_REVERSE;
1229 goto done; /* q = NULL, not found */
1231 if ( prev != NULL) { /* found and not in front */
1232 prev->next = q->next;
1233 q->next = ipfw_dyn_v[i];
1236 if (pkt->proto == IPPROTO_TCP) { /* update state according to flags */
1237 u_char flags = pkt->flags & (TH_FIN|TH_SYN|TH_RST);
1239 #define BOTH_SYN (TH_SYN | (TH_SYN << 8))
1240 #define BOTH_FIN (TH_FIN | (TH_FIN << 8))
1241 q->state |= (dir == MATCH_FORWARD ) ? flags : (flags << 8);
1243 case TH_SYN: /* opening */
1244 q->expire = time_uptime + dyn_syn_lifetime;
1247 case BOTH_SYN: /* move to established */
1248 case BOTH_SYN | TH_FIN : /* one side tries to close */
1249 case BOTH_SYN | (TH_FIN << 8) :
1251 #define _SEQ_GE(a,b) ((int)(a) - (int)(b) >= 0)
1252 u_int32_t ack = ntohl(tcp->th_ack);
1253 if (dir == MATCH_FORWARD) {
1254 if (q->ack_fwd == 0 || _SEQ_GE(ack, q->ack_fwd))
1256 else { /* ignore out-of-sequence */
1260 if (q->ack_rev == 0 || _SEQ_GE(ack, q->ack_rev))
1262 else { /* ignore out-of-sequence */
1267 q->expire = time_uptime + dyn_ack_lifetime;
1270 case BOTH_SYN | BOTH_FIN: /* both sides closed */
1271 if (dyn_fin_lifetime >= dyn_keepalive_period)
1272 dyn_fin_lifetime = dyn_keepalive_period - 1;
1273 q->expire = time_uptime + dyn_fin_lifetime;
1279 * reset or some invalid combination, but can also
1280 * occur if we use keep-state the wrong way.
1282 if ( (q->state & ((TH_RST << 8)|TH_RST)) == 0)
1283 printf("invalid state: 0x%x\n", q->state);
1285 if (dyn_rst_lifetime >= dyn_keepalive_period)
1286 dyn_rst_lifetime = dyn_keepalive_period - 1;
1287 q->expire = time_uptime + dyn_rst_lifetime;
1290 } else if (pkt->proto == IPPROTO_UDP) {
1291 q->expire = time_uptime + dyn_udp_lifetime;
1293 /* other protocols */
1294 q->expire = time_uptime + dyn_short_lifetime;
1297 if (match_direction)
1298 *match_direction = dir;
1302 static ipfw_dyn_rule *
1303 lookup_dyn_rule(struct ipfw_flow_id *pkt, int *match_direction,
1309 q = lookup_dyn_rule_locked(pkt, match_direction, tcp);
1312 /* NB: return table locked when q is not NULL */
1317 realloc_dynamic_table(void)
1319 IPFW_DYN_LOCK_ASSERT();
1322 * Try reallocation, make sure we have a power of 2 and do
1323 * not allow more than 64k entries. In case of overflow,
1327 if (dyn_buckets > 65536)
1329 if ((dyn_buckets & (dyn_buckets-1)) != 0) { /* not a power of 2 */
1330 dyn_buckets = curr_dyn_buckets; /* reset */
1333 curr_dyn_buckets = dyn_buckets;
1334 if (ipfw_dyn_v != NULL)
1335 free(ipfw_dyn_v, M_IPFW);
1337 ipfw_dyn_v = malloc(curr_dyn_buckets * sizeof(ipfw_dyn_rule *),
1338 M_IPFW, M_NOWAIT | M_ZERO);
1339 if (ipfw_dyn_v != NULL || curr_dyn_buckets <= 2)
1341 curr_dyn_buckets /= 2;
1346 * Install state of type 'type' for a dynamic session.
1347 * The hash table contains two type of rules:
1348 * - regular rules (O_KEEP_STATE)
1349 * - rules for sessions with limited number of sess per user
1350 * (O_LIMIT). When they are created, the parent is
1351 * increased by 1, and decreased on delete. In this case,
1352 * the third parameter is the parent rule and not the chain.
1353 * - "parent" rules for the above (O_LIMIT_PARENT).
1355 static ipfw_dyn_rule *
1356 add_dyn_rule(struct ipfw_flow_id *id, u_int8_t dyn_type, struct ip_fw *rule)
1361 IPFW_DYN_LOCK_ASSERT();
1363 if (ipfw_dyn_v == NULL ||
1364 (dyn_count == 0 && dyn_buckets != curr_dyn_buckets)) {
1365 realloc_dynamic_table();
1366 if (ipfw_dyn_v == NULL)
1367 return NULL; /* failed ! */
1369 i = hash_packet(id);
1371 r = uma_zalloc(ipfw_dyn_rule_zone, M_NOWAIT | M_ZERO);
1373 printf ("ipfw: sorry cannot allocate state\n");
1377 /* increase refcount on parent, and set pointer */
1378 if (dyn_type == O_LIMIT) {
1379 ipfw_dyn_rule *parent = (ipfw_dyn_rule *)rule;
1380 if ( parent->dyn_type != O_LIMIT_PARENT)
1381 panic("invalid parent");
1384 rule = parent->rule;
1388 r->expire = time_uptime + dyn_syn_lifetime;
1390 r->dyn_type = dyn_type;
1391 r->pcnt = r->bcnt = 0;
1395 r->next = ipfw_dyn_v[i];
1398 DEB(printf("ipfw: add dyn entry ty %d 0x%08x %d -> 0x%08x %d, total %d\n",
1400 (r->id.src_ip), (r->id.src_port),
1401 (r->id.dst_ip), (r->id.dst_port),
1407 * lookup dynamic parent rule using pkt and rule as search keys.
1408 * If the lookup fails, then install one.
1410 static ipfw_dyn_rule *
1411 lookup_dyn_parent(struct ipfw_flow_id *pkt, struct ip_fw *rule)
1416 IPFW_DYN_LOCK_ASSERT();
1419 int is_v6 = IS_IP6_FLOW_ID(pkt);
1420 i = hash_packet( pkt );
1421 for (q = ipfw_dyn_v[i] ; q != NULL ; q=q->next)
1422 if (q->dyn_type == O_LIMIT_PARENT &&
1424 pkt->proto == q->id.proto &&
1425 pkt->src_port == q->id.src_port &&
1426 pkt->dst_port == q->id.dst_port &&
1429 IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
1430 &(q->id.src_ip6)) &&
1431 IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
1432 &(q->id.dst_ip6))) ||
1434 pkt->src_ip == q->id.src_ip &&
1435 pkt->dst_ip == q->id.dst_ip)
1438 q->expire = time_uptime + dyn_short_lifetime;
1439 DEB(printf("ipfw: lookup_dyn_parent found 0x%p\n",q);)
1443 return add_dyn_rule(pkt, O_LIMIT_PARENT, rule);
1447 * Install dynamic state for rule type cmd->o.opcode
1449 * Returns 1 (failure) if state is not installed because of errors or because
1450 * session limitations are enforced.
1453 install_state(struct ip_fw *rule, ipfw_insn_limit *cmd,
1454 struct ip_fw_args *args, uint32_t tablearg)
1456 static int last_log;
1459 char src[48], dst[48];
1465 printf("ipfw: %s: type %d 0x%08x %u -> 0x%08x %u\n",
1466 __func__, cmd->o.opcode,
1467 (args->f_id.src_ip), (args->f_id.src_port),
1468 (args->f_id.dst_ip), (args->f_id.dst_port));
1473 q = lookup_dyn_rule_locked(&args->f_id, NULL, NULL);
1475 if (q != NULL) { /* should never occur */
1476 if (last_log != time_uptime) {
1477 last_log = time_uptime;
1478 printf("ipfw: %s: entry already present, done\n",
1485 if (dyn_count >= dyn_max)
1486 /* Run out of slots, try to remove any expired rule. */
1487 remove_dyn_rule(NULL, (ipfw_dyn_rule *)1);
1489 if (dyn_count >= dyn_max) {
1490 if (last_log != time_uptime) {
1491 last_log = time_uptime;
1492 printf("ipfw: %s: Too many dynamic rules\n", __func__);
1495 return (1); /* cannot install, notify caller */
1498 switch (cmd->o.opcode) {
1499 case O_KEEP_STATE: /* bidir rule */
1500 add_dyn_rule(&args->f_id, O_KEEP_STATE, rule);
1503 case O_LIMIT: { /* limit number of sessions */
1504 struct ipfw_flow_id id;
1505 ipfw_dyn_rule *parent;
1506 uint32_t conn_limit;
1507 uint16_t limit_mask = cmd->limit_mask;
1509 conn_limit = (cmd->conn_limit == IP_FW_TABLEARG) ?
1510 tablearg : cmd->conn_limit;
1513 if (cmd->conn_limit == IP_FW_TABLEARG)
1514 printf("ipfw: %s: O_LIMIT rule, conn_limit: %u "
1515 "(tablearg)\n", __func__, conn_limit);
1517 printf("ipfw: %s: O_LIMIT rule, conn_limit: %u\n",
1518 __func__, conn_limit);
1521 id.dst_ip = id.src_ip = id.dst_port = id.src_port = 0;
1522 id.proto = args->f_id.proto;
1523 id.addr_type = args->f_id.addr_type;
1525 if (IS_IP6_FLOW_ID (&(args->f_id))) {
1526 if (limit_mask & DYN_SRC_ADDR)
1527 id.src_ip6 = args->f_id.src_ip6;
1528 if (limit_mask & DYN_DST_ADDR)
1529 id.dst_ip6 = args->f_id.dst_ip6;
1531 if (limit_mask & DYN_SRC_ADDR)
1532 id.src_ip = args->f_id.src_ip;
1533 if (limit_mask & DYN_DST_ADDR)
1534 id.dst_ip = args->f_id.dst_ip;
1536 if (limit_mask & DYN_SRC_PORT)
1537 id.src_port = args->f_id.src_port;
1538 if (limit_mask & DYN_DST_PORT)
1539 id.dst_port = args->f_id.dst_port;
1540 if ((parent = lookup_dyn_parent(&id, rule)) == NULL) {
1541 printf("ipfw: %s: add parent failed\n", __func__);
1546 if (parent->count >= conn_limit) {
1547 /* See if we can remove some expired rule. */
1548 remove_dyn_rule(rule, parent);
1549 if (parent->count >= conn_limit) {
1550 if (fw_verbose && last_log != time_uptime) {
1551 last_log = time_uptime;
1554 * XXX IPv6 flows are not
1557 if (IS_IP6_FLOW_ID(&(args->f_id))) {
1558 char ip6buf[INET6_ADDRSTRLEN];
1559 snprintf(src, sizeof(src),
1560 "[%s]", ip6_sprintf(ip6buf,
1561 &args->f_id.src_ip6));
1562 snprintf(dst, sizeof(dst),
1563 "[%s]", ip6_sprintf(ip6buf,
1564 &args->f_id.dst_ip6));
1569 htonl(args->f_id.src_ip);
1570 inet_ntoa_r(da, src);
1572 htonl(args->f_id.dst_ip);
1573 inet_ntoa_r(da, dst);
1575 log(LOG_SECURITY | LOG_DEBUG,
1576 "%s %s:%u -> %s:%u, %s\n",
1578 src, (args->f_id.src_port),
1579 dst, (args->f_id.dst_port),
1580 "too many entries");
1586 add_dyn_rule(&args->f_id, O_LIMIT, (struct ip_fw *)parent);
1590 printf("ipfw: %s: unknown dynamic rule type %u\n",
1591 __func__, cmd->o.opcode);
1596 /* XXX just set lifetime */
1597 lookup_dyn_rule_locked(&args->f_id, NULL, NULL);
1604 * Generate a TCP packet, containing either a RST or a keepalive.
1605 * When flags & TH_RST, we are sending a RST packet, because of a
1606 * "reset" action matched the packet.
1607 * Otherwise we are sending a keepalive, and flags & TH_
1608 * The 'replyto' mbuf is the mbuf being replied to, if any, and is required
1609 * so that MAC can label the reply appropriately.
1611 static struct mbuf *
1612 send_pkt(struct mbuf *replyto, struct ipfw_flow_id *id, u_int32_t seq,
1613 u_int32_t ack, int flags)
1619 MGETHDR(m, M_DONTWAIT, MT_DATA);
1622 m->m_pkthdr.rcvif = (struct ifnet *)0;
1625 if (replyto != NULL)
1626 mac_create_mbuf_netlayer(replyto, m);
1628 mac_create_mbuf_from_firewall(m);
1630 (void)replyto; /* don't warn about unused arg */
1633 m->m_pkthdr.len = m->m_len = sizeof(struct ip) + sizeof(struct tcphdr);
1634 m->m_data += max_linkhdr;
1636 ip = mtod(m, struct ip *);
1637 bzero(ip, m->m_len);
1638 tcp = (struct tcphdr *)(ip + 1); /* no IP options */
1639 ip->ip_p = IPPROTO_TCP;
1642 * Assume we are sending a RST (or a keepalive in the reverse
1643 * direction), swap src and destination addresses and ports.
1645 ip->ip_src.s_addr = htonl(id->dst_ip);
1646 ip->ip_dst.s_addr = htonl(id->src_ip);
1647 tcp->th_sport = htons(id->dst_port);
1648 tcp->th_dport = htons(id->src_port);
1649 if (flags & TH_RST) { /* we are sending a RST */
1650 if (flags & TH_ACK) {
1651 tcp->th_seq = htonl(ack);
1652 tcp->th_ack = htonl(0);
1653 tcp->th_flags = TH_RST;
1657 tcp->th_seq = htonl(0);
1658 tcp->th_ack = htonl(seq);
1659 tcp->th_flags = TH_RST | TH_ACK;
1663 * We are sending a keepalive. flags & TH_SYN determines
1664 * the direction, forward if set, reverse if clear.
1665 * NOTE: seq and ack are always assumed to be correct
1666 * as set by the caller. This may be confusing...
1668 if (flags & TH_SYN) {
1670 * we have to rewrite the correct addresses!
1672 ip->ip_dst.s_addr = htonl(id->dst_ip);
1673 ip->ip_src.s_addr = htonl(id->src_ip);
1674 tcp->th_dport = htons(id->dst_port);
1675 tcp->th_sport = htons(id->src_port);
1677 tcp->th_seq = htonl(seq);
1678 tcp->th_ack = htonl(ack);
1679 tcp->th_flags = TH_ACK;
1682 * set ip_len to the payload size so we can compute
1683 * the tcp checksum on the pseudoheader
1684 * XXX check this, could save a couple of words ?
1686 ip->ip_len = htons(sizeof(struct tcphdr));
1687 tcp->th_sum = in_cksum(m, m->m_pkthdr.len);
1689 * now fill fields left out earlier
1691 ip->ip_ttl = ip_defttl;
1692 ip->ip_len = m->m_pkthdr.len;
1693 m->m_flags |= M_SKIP_FIREWALL;
1698 * sends a reject message, consuming the mbuf passed as an argument.
1701 send_reject(struct ip_fw_args *args, int code, int ip_len, struct ip *ip)
1705 /* XXX When ip is not guaranteed to be at mtod() we will
1706 * need to account for this */
1707 * The mbuf will however be thrown away so we can adjust it.
1708 * Remember we did an m_pullup on it already so we
1709 * can make some assumptions about contiguousness.
1712 m_adj(m, args->L3offset);
1714 if (code != ICMP_REJECT_RST) { /* Send an ICMP unreach */
1715 /* We need the IP header in host order for icmp_error(). */
1716 if (args->eh != NULL) {
1717 ip->ip_len = ntohs(ip->ip_len);
1718 ip->ip_off = ntohs(ip->ip_off);
1720 icmp_error(args->m, ICMP_UNREACH, code, 0L, 0);
1721 } else if (args->f_id.proto == IPPROTO_TCP) {
1722 struct tcphdr *const tcp =
1723 L3HDR(struct tcphdr, mtod(args->m, struct ip *));
1724 if ( (tcp->th_flags & TH_RST) == 0) {
1726 m = send_pkt(args->m, &(args->f_id),
1727 ntohl(tcp->th_seq), ntohl(tcp->th_ack),
1728 tcp->th_flags | TH_RST);
1730 ip_output(m, NULL, NULL, 0, NULL, NULL);
1740 * Given an ip_fw *, lookup_next_rule will return a pointer
1741 * to the next rule, which can be either the jump
1742 * target (for skipto instructions) or the next one in the list (in
1743 * all other cases including a missing jump target).
1744 * The result is also written in the "next_rule" field of the rule.
1745 * Backward jumps are not allowed, so start looking from the next
1748 * This never returns NULL -- in case we do not have an exact match,
1749 * the next rule is returned. When the ruleset is changed,
1750 * pointers are flushed so we are always correct.
1753 static struct ip_fw *
1754 lookup_next_rule(struct ip_fw *me)
1756 struct ip_fw *rule = NULL;
1759 /* look for action, in case it is a skipto */
1760 cmd = ACTION_PTR(me);
1761 if (cmd->opcode == O_LOG)
1763 if (cmd->opcode == O_ALTQ)
1765 if (cmd->opcode == O_TAG)
1767 if ( cmd->opcode == O_SKIPTO )
1768 for (rule = me->next; rule ; rule = rule->next)
1769 if (rule->rulenum >= cmd->arg1)
1771 if (rule == NULL) /* failure or not a skipto */
1773 me->next_rule = rule;
1778 add_table_entry(struct ip_fw_chain *ch, uint16_t tbl, in_addr_t addr,
1779 uint8_t mlen, uint32_t value)
1781 struct radix_node_head *rnh;
1782 struct table_entry *ent;
1784 if (tbl >= IPFW_TABLES_MAX)
1786 rnh = ch->tables[tbl];
1787 ent = malloc(sizeof(*ent), M_IPFW_TBL, M_NOWAIT | M_ZERO);
1791 ent->addr.sin_len = ent->mask.sin_len = 8;
1792 ent->mask.sin_addr.s_addr = htonl(mlen ? ~((1 << (32 - mlen)) - 1) : 0);
1793 ent->addr.sin_addr.s_addr = addr & ent->mask.sin_addr.s_addr;
1794 IPFW_WLOCK(&layer3_chain);
1795 if (rnh->rnh_addaddr(&ent->addr, &ent->mask, rnh, (void *)ent) ==
1797 IPFW_WUNLOCK(&layer3_chain);
1798 free(ent, M_IPFW_TBL);
1801 IPFW_WUNLOCK(&layer3_chain);
1806 del_table_entry(struct ip_fw_chain *ch, uint16_t tbl, in_addr_t addr,
1809 struct radix_node_head *rnh;
1810 struct table_entry *ent;
1811 struct sockaddr_in sa, mask;
1813 if (tbl >= IPFW_TABLES_MAX)
1815 rnh = ch->tables[tbl];
1816 sa.sin_len = mask.sin_len = 8;
1817 mask.sin_addr.s_addr = htonl(mlen ? ~((1 << (32 - mlen)) - 1) : 0);
1818 sa.sin_addr.s_addr = addr & mask.sin_addr.s_addr;
1820 ent = (struct table_entry *)rnh->rnh_deladdr(&sa, &mask, rnh);
1826 free(ent, M_IPFW_TBL);
1831 flush_table_entry(struct radix_node *rn, void *arg)
1833 struct radix_node_head * const rnh = arg;
1834 struct table_entry *ent;
1836 ent = (struct table_entry *)
1837 rnh->rnh_deladdr(rn->rn_key, rn->rn_mask, rnh);
1839 free(ent, M_IPFW_TBL);
1844 flush_table(struct ip_fw_chain *ch, uint16_t tbl)
1846 struct radix_node_head *rnh;
1848 IPFW_WLOCK_ASSERT(ch);
1850 if (tbl >= IPFW_TABLES_MAX)
1852 rnh = ch->tables[tbl];
1853 KASSERT(rnh != NULL, ("NULL IPFW table"));
1854 rnh->rnh_walktree(rnh, flush_table_entry, rnh);
1859 flush_tables(struct ip_fw_chain *ch)
1863 IPFW_WLOCK_ASSERT(ch);
1865 for (tbl = 0; tbl < IPFW_TABLES_MAX; tbl++)
1866 flush_table(ch, tbl);
1870 init_tables(struct ip_fw_chain *ch)
1875 for (i = 0; i < IPFW_TABLES_MAX; i++) {
1876 if (!rn_inithead((void **)&ch->tables[i], 32)) {
1877 for (j = 0; j < i; j++) {
1878 (void) flush_table(ch, j);
1887 lookup_table(struct ip_fw_chain *ch, uint16_t tbl, in_addr_t addr,
1890 struct radix_node_head *rnh;
1891 struct table_entry *ent;
1892 struct sockaddr_in sa;
1894 if (tbl >= IPFW_TABLES_MAX)
1896 rnh = ch->tables[tbl];
1898 sa.sin_addr.s_addr = addr;
1899 ent = (struct table_entry *)(rnh->rnh_lookup(&sa, NULL, rnh));
1908 count_table_entry(struct radix_node *rn, void *arg)
1910 u_int32_t * const cnt = arg;
1917 count_table(struct ip_fw_chain *ch, uint32_t tbl, uint32_t *cnt)
1919 struct radix_node_head *rnh;
1921 if (tbl >= IPFW_TABLES_MAX)
1923 rnh = ch->tables[tbl];
1925 rnh->rnh_walktree(rnh, count_table_entry, cnt);
1930 dump_table_entry(struct radix_node *rn, void *arg)
1932 struct table_entry * const n = (struct table_entry *)rn;
1933 ipfw_table * const tbl = arg;
1934 ipfw_table_entry *ent;
1936 if (tbl->cnt == tbl->size)
1938 ent = &tbl->ent[tbl->cnt];
1939 ent->tbl = tbl->tbl;
1940 if (in_nullhost(n->mask.sin_addr))
1943 ent->masklen = 33 - ffs(ntohl(n->mask.sin_addr.s_addr));
1944 ent->addr = n->addr.sin_addr.s_addr;
1945 ent->value = n->value;
1951 dump_table(struct ip_fw_chain *ch, ipfw_table *tbl)
1953 struct radix_node_head *rnh;
1955 if (tbl->tbl >= IPFW_TABLES_MAX)
1957 rnh = ch->tables[tbl->tbl];
1959 rnh->rnh_walktree(rnh, dump_table_entry, tbl);
1964 fill_ugid_cache(struct inpcb *inp, struct ip_fw_ugid *ugp)
1968 if (inp->inp_socket != NULL) {
1969 cr = inp->inp_socket->so_cred;
1970 ugp->fw_prid = jailed(cr) ?
1971 cr->cr_prison->pr_id : -1;
1972 ugp->fw_uid = cr->cr_uid;
1973 ugp->fw_ngroups = cr->cr_ngroups;
1974 bcopy(cr->cr_groups, ugp->fw_groups,
1975 sizeof(ugp->fw_groups));
1980 check_uidgid(ipfw_insn_u32 *insn, int proto, struct ifnet *oif,
1981 struct in_addr dst_ip, u_int16_t dst_port, struct in_addr src_ip,
1982 u_int16_t src_port, struct ip_fw_ugid *ugp, int *lookup,
1985 struct inpcbinfo *pi;
1992 * Check to see if the UDP or TCP stack supplied us with
1993 * the PCB. If so, rather then holding a lock and looking
1994 * up the PCB, we can use the one that was supplied.
1996 if (inp && *lookup == 0) {
1997 INP_LOCK_ASSERT(inp);
1998 if (inp->inp_socket != NULL) {
1999 fill_ugid_cache(inp, ugp);
2004 * If we have already been here and the packet has no
2005 * PCB entry associated with it, then we can safely
2006 * assume that this is a no match.
2010 if (proto == IPPROTO_TCP) {
2013 } else if (proto == IPPROTO_UDP) {
2014 wildcard = INPLOOKUP_WILDCARD;
2022 in_pcblookup_hash(pi,
2023 dst_ip, htons(dst_port),
2024 src_ip, htons(src_port),
2026 in_pcblookup_hash(pi,
2027 src_ip, htons(src_port),
2028 dst_ip, htons(dst_port),
2032 if (pcb->inp_socket != NULL) {
2033 fill_ugid_cache(pcb, ugp);
2038 INP_INFO_RUNLOCK(pi);
2041 * If the lookup did not yield any results, there
2042 * is no sense in coming back and trying again. So
2043 * we can set lookup to -1 and ensure that we wont
2044 * bother the pcb system again.
2050 if (insn->o.opcode == O_UID)
2051 match = (ugp->fw_uid == (uid_t)insn->d[0]);
2052 else if (insn->o.opcode == O_GID) {
2053 for (gp = ugp->fw_groups;
2054 gp < &ugp->fw_groups[ugp->fw_ngroups]; gp++)
2055 if (*gp == (gid_t)insn->d[0]) {
2059 } else if (insn->o.opcode == O_JAIL)
2060 match = (ugp->fw_prid == (int)insn->d[0]);
2064 #ifdef IPFIREWALL_NAT
2065 static eventhandler_tag ifaddr_event_tag;
2068 ifaddr_change(void *arg __unused, struct ifnet *ifp)
2070 struct cfg_nat *ptr;
2073 IPFW_WLOCK(&layer3_chain);
2074 /* Check every nat entry... */
2075 LIST_FOREACH(ptr, &layer3_chain.nat, _next) {
2076 /* ...using nic 'ifp->if_xname' as dynamic alias address. */
2077 if (strncmp(ptr->if_name, ifp->if_xname, IF_NAMESIZE) == 0) {
2078 mtx_lock(&ifp->if_addr_mtx);
2079 TAILQ_FOREACH(ifa, &ifp->if_addrlist, ifa_list) {
2080 if (ifa->ifa_addr == NULL)
2082 if (ifa->ifa_addr->sa_family != AF_INET)
2084 ptr->ip = ((struct sockaddr_in *)
2085 (ifa->ifa_addr))->sin_addr;
2086 LibAliasSetAddress(ptr->lib, ptr->ip);
2088 mtx_unlock(&ifp->if_addr_mtx);
2091 IPFW_WUNLOCK(&layer3_chain);
2095 flush_nat_ptrs(const int i)
2099 IPFW_WLOCK_ASSERT(&layer3_chain);
2100 for (rule = layer3_chain.rules; rule; rule = rule->next) {
2101 ipfw_insn_nat *cmd = (ipfw_insn_nat *)ACTION_PTR(rule);
2102 if (cmd->o.opcode != O_NAT)
2104 if (cmd->nat != NULL && cmd->nat->id == i)
2109 static struct cfg_nat *
2110 lookup_nat(const int i)
2112 struct cfg_nat *ptr;
2114 LIST_FOREACH(ptr, &layer3_chain.nat, _next)
2120 #define HOOK_NAT(b, p) do { \
2121 IPFW_WLOCK_ASSERT(&layer3_chain); \
2122 LIST_INSERT_HEAD(b, p, _next); \
2125 #define UNHOOK_NAT(p) do { \
2126 IPFW_WLOCK_ASSERT(&layer3_chain); \
2127 LIST_REMOVE(p, _next); \
2130 #define HOOK_REDIR(b, p) do { \
2131 LIST_INSERT_HEAD(b, p, _next); \
2134 #define HOOK_SPOOL(b, p) do { \
2135 LIST_INSERT_HEAD(b, p, _next); \
2139 del_redir_spool_cfg(struct cfg_nat *n, struct redir_chain *head)
2141 struct cfg_redir *r, *tmp_r;
2142 struct cfg_spool *s, *tmp_s;
2145 LIST_FOREACH_SAFE(r, head, _next, tmp_r) {
2146 num = 1; /* Number of alias_link to delete. */
2153 /* Delete all libalias redirect entry. */
2154 for (i = 0; i < num; i++)
2155 LibAliasRedirectDelete(n->lib, r->alink[i]);
2156 /* Del spool cfg if any. */
2157 LIST_FOREACH_SAFE(s, &r->spool_chain, _next, tmp_s) {
2158 LIST_REMOVE(s, _next);
2161 free(r->alink, M_IPFW);
2162 LIST_REMOVE(r, _next);
2166 printf("unknown redirect mode: %u\n", r->mode);
2167 /* XXX - panic?!?!? */
2174 add_redir_spool_cfg(char *buf, struct cfg_nat *ptr)
2176 struct cfg_redir *r, *ser_r;
2177 struct cfg_spool *s, *ser_s;
2181 for (cnt = 0, off = 0; cnt < ptr->redir_cnt; cnt++) {
2182 ser_r = (struct cfg_redir *)&buf[off];
2183 r = malloc(SOF_REDIR, M_IPFW, M_WAITOK | M_ZERO);
2184 memcpy(r, ser_r, SOF_REDIR);
2185 LIST_INIT(&r->spool_chain);
2187 r->alink = malloc(sizeof(struct alias_link *) * r->pport_cnt,
2188 M_IPFW, M_WAITOK | M_ZERO);
2191 r->alink[0] = LibAliasRedirectAddr(ptr->lib, r->laddr,
2195 for (i = 0 ; i < r->pport_cnt; i++) {
2196 /* If remotePort is all ports, set it to 0. */
2197 u_short remotePortCopy = r->rport + i;
2198 if (r->rport_cnt == 1 && r->rport == 0)
2200 r->alink[i] = LibAliasRedirectPort(ptr->lib,
2201 r->laddr, htons(r->lport + i), r->raddr,
2202 htons(remotePortCopy), r->paddr,
2203 htons(r->pport + i), r->proto);
2204 if (r->alink[i] == NULL) {
2211 r->alink[0] = LibAliasRedirectProto(ptr->lib ,r->laddr,
2212 r->raddr, r->paddr, r->proto);
2215 printf("unknown redirect mode: %u\n", r->mode);
2218 if (r->alink[0] == NULL) {
2219 panic_err = "LibAliasRedirect* returned NULL";
2221 } else /* LSNAT handling. */
2222 for (i = 0; i < r->spool_cnt; i++) {
2223 ser_s = (struct cfg_spool *)&buf[off];
2224 s = malloc(SOF_REDIR, M_IPFW,
2226 memcpy(s, ser_s, SOF_SPOOL);
2227 LibAliasAddServer(ptr->lib, r->alink[0],
2228 s->addr, htons(s->port));
2230 /* Hook spool entry. */
2231 HOOK_SPOOL(&r->spool_chain, s);
2233 /* And finally hook this redir entry. */
2234 HOOK_REDIR(&ptr->redir_chain, r);
2238 /* something really bad happened: panic! */
2239 panic("%s\n", panic_err);
2244 * The main check routine for the firewall.
2246 * All arguments are in args so we can modify them and return them
2247 * back to the caller.
2251 * args->m (in/out) The packet; we set to NULL when/if we nuke it.
2252 * Starts with the IP header.
2253 * args->eh (in) Mac header if present, or NULL for layer3 packet.
2254 * args->L3offset Number of bytes bypassed if we came from L2.
2255 * e.g. often sizeof(eh) ** NOTYET **
2256 * args->oif Outgoing interface, or NULL if packet is incoming.
2257 * The incoming interface is in the mbuf. (in)
2258 * args->divert_rule (in/out)
2259 * Skip up to the first rule past this rule number;
2260 * upon return, non-zero port number for divert or tee.
2262 * args->rule Pointer to the last matching rule (in/out)
2263 * args->next_hop Socket we are forwarding to (out).
2264 * args->f_id Addresses grabbed from the packet (out)
2265 * args->cookie a cookie depending on rule action
2269 * IP_FW_PASS the packet must be accepted
2270 * IP_FW_DENY the packet must be dropped
2271 * IP_FW_DIVERT divert packet, port in m_tag
2272 * IP_FW_TEE tee packet, port in m_tag
2273 * IP_FW_DUMMYNET to dummynet, pipe in args->cookie
2274 * IP_FW_NETGRAPH into netgraph, cookie args->cookie
2278 ipfw_chk(struct ip_fw_args *args)
2281 * Local variables holding state during the processing of a packet:
2283 * IMPORTANT NOTE: to speed up the processing of rules, there
2284 * are some assumption on the values of the variables, which
2285 * are documented here. Should you change them, please check
2286 * the implementation of the various instructions to make sure
2287 * that they still work.
2289 * args->eh The MAC header. It is non-null for a layer2
2290 * packet, it is NULL for a layer-3 packet.
2292 * args->L3offset Offset in the packet to the L3 (IP or equiv.) header.
2294 * m | args->m Pointer to the mbuf, as received from the caller.
2295 * It may change if ipfw_chk() does an m_pullup, or if it
2296 * consumes the packet because it calls send_reject().
2297 * XXX This has to change, so that ipfw_chk() never modifies
2298 * or consumes the buffer.
2299 * ip is the beginning of the ip(4 or 6) header.
2300 * Calculated by adding the L3offset to the start of data.
2301 * (Until we start using L3offset, the packet is
2302 * supposed to start with the ip header).
2304 struct mbuf *m = args->m;
2305 struct ip *ip = mtod(m, struct ip *);
2308 * For rules which contain uid/gid or jail constraints, cache
2309 * a copy of the users credentials after the pcb lookup has been
2310 * executed. This will speed up the processing of rules with
2311 * these types of constraints, as well as decrease contention
2312 * on pcb related locks.
2314 struct ip_fw_ugid fw_ugid_cache;
2315 int ugid_lookup = 0;
2318 * divinput_flags If non-zero, set to the IP_FW_DIVERT_*_FLAG
2319 * associated with a packet input on a divert socket. This
2320 * will allow to distinguish traffic and its direction when
2321 * it originates from a divert socket.
2323 u_int divinput_flags = 0;
2326 * oif | args->oif If NULL, ipfw_chk has been called on the
2327 * inbound path (ether_input, ip_input).
2328 * If non-NULL, ipfw_chk has been called on the outbound path
2329 * (ether_output, ip_output).
2331 struct ifnet *oif = args->oif;
2333 struct ip_fw *f = NULL; /* matching rule */
2337 * hlen The length of the IP header.
2339 u_int hlen = 0; /* hlen >0 means we have an IP pkt */
2342 * offset The offset of a fragment. offset != 0 means that
2343 * we have a fragment at this offset of an IPv4 packet.
2344 * offset == 0 means that (if this is an IPv4 packet)
2345 * this is the first or only fragment.
2346 * For IPv6 offset == 0 means there is no Fragment Header.
2347 * If offset != 0 for IPv6 always use correct mask to
2348 * get the correct offset because we add IP6F_MORE_FRAG
2349 * to be able to dectect the first fragment which would
2350 * otherwise have offset = 0.
2355 * Local copies of addresses. They are only valid if we have
2358 * proto The protocol. Set to 0 for non-ip packets,
2359 * or to the protocol read from the packet otherwise.
2360 * proto != 0 means that we have an IPv4 packet.
2362 * src_port, dst_port port numbers, in HOST format. Only
2363 * valid for TCP and UDP packets.
2365 * src_ip, dst_ip ip addresses, in NETWORK format.
2366 * Only valid for IPv4 packets.
2369 u_int16_t src_port = 0, dst_port = 0; /* NOTE: host format */
2370 struct in_addr src_ip, dst_ip; /* NOTE: network format */
2373 u_int16_t etype = 0; /* Host order stored ether type */
2376 * dyn_dir = MATCH_UNKNOWN when rules unchecked,
2377 * MATCH_NONE when checked and not matched (q = NULL),
2378 * MATCH_FORWARD or MATCH_REVERSE otherwise (q != NULL)
2380 int dyn_dir = MATCH_UNKNOWN;
2381 ipfw_dyn_rule *q = NULL;
2382 struct ip_fw_chain *chain = &layer3_chain;
2386 * We store in ulp a pointer to the upper layer protocol header.
2387 * In the ipv4 case this is easy to determine from the header,
2388 * but for ipv6 we might have some additional headers in the middle.
2389 * ulp is NULL if not found.
2391 void *ulp = NULL; /* upper layer protocol pointer. */
2392 /* XXX ipv6 variables */
2394 u_int16_t ext_hd = 0; /* bits vector for extension header filtering */
2395 /* end of ipv6 variables */
2398 if (m->m_flags & M_SKIP_FIREWALL)
2399 return (IP_FW_PASS); /* accept */
2401 pktlen = m->m_pkthdr.len;
2402 proto = args->f_id.proto = 0; /* mark f_id invalid */
2403 /* XXX 0 is a valid proto: IP/IPv6 Hop-by-Hop Option */
2406 * PULLUP_TO(len, p, T) makes sure that len + sizeof(T) is contiguous,
2407 * then it sets p to point at the offset "len" in the mbuf. WARNING: the
2408 * pointer might become stale after other pullups (but we never use it
2411 #define PULLUP_TO(len, p, T) \
2413 int x = (len) + sizeof(T); \
2414 if ((m)->m_len < x) { \
2415 args->m = m = m_pullup(m, x); \
2417 goto pullup_failed; \
2419 p = (mtod(m, char *) + (len)); \
2423 * if we have an ether header,
2426 etype = ntohs(args->eh->ether_type);
2428 /* Identify IP packets and fill up variables. */
2429 if (pktlen >= sizeof(struct ip6_hdr) &&
2430 (args->eh == NULL || etype == ETHERTYPE_IPV6) && ip->ip_v == 6) {
2431 struct ip6_hdr *ip6 = (struct ip6_hdr *)ip;
2433 args->f_id.addr_type = 6;
2434 hlen = sizeof(struct ip6_hdr);
2435 proto = ip6->ip6_nxt;
2437 /* Search extension headers to find upper layer protocols */
2438 while (ulp == NULL) {
2440 case IPPROTO_ICMPV6:
2441 PULLUP_TO(hlen, ulp, struct icmp6_hdr);
2442 args->f_id.flags = ICMP6(ulp)->icmp6_type;
2446 PULLUP_TO(hlen, ulp, struct tcphdr);
2447 dst_port = TCP(ulp)->th_dport;
2448 src_port = TCP(ulp)->th_sport;
2449 args->f_id.flags = TCP(ulp)->th_flags;
2453 PULLUP_TO(hlen, ulp, struct sctphdr);
2454 src_port = SCTP(ulp)->src_port;
2455 dst_port = SCTP(ulp)->dest_port;
2459 PULLUP_TO(hlen, ulp, struct udphdr);
2460 dst_port = UDP(ulp)->uh_dport;
2461 src_port = UDP(ulp)->uh_sport;
2464 case IPPROTO_HOPOPTS: /* RFC 2460 */
2465 PULLUP_TO(hlen, ulp, struct ip6_hbh);
2466 ext_hd |= EXT_HOPOPTS;
2467 hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3;
2468 proto = ((struct ip6_hbh *)ulp)->ip6h_nxt;
2472 case IPPROTO_ROUTING: /* RFC 2460 */
2473 PULLUP_TO(hlen, ulp, struct ip6_rthdr);
2474 switch (((struct ip6_rthdr *)ulp)->ip6r_type) {
2476 ext_hd |= EXT_RTHDR0;
2479 ext_hd |= EXT_RTHDR2;
2482 printf("IPFW2: IPV6 - Unknown Routing "
2483 "Header type(%d)\n",
2484 ((struct ip6_rthdr *)ulp)->ip6r_type);
2485 if (fw_deny_unknown_exthdrs)
2486 return (IP_FW_DENY);
2489 ext_hd |= EXT_ROUTING;
2490 hlen += (((struct ip6_rthdr *)ulp)->ip6r_len + 1) << 3;
2491 proto = ((struct ip6_rthdr *)ulp)->ip6r_nxt;
2495 case IPPROTO_FRAGMENT: /* RFC 2460 */
2496 PULLUP_TO(hlen, ulp, struct ip6_frag);
2497 ext_hd |= EXT_FRAGMENT;
2498 hlen += sizeof (struct ip6_frag);
2499 proto = ((struct ip6_frag *)ulp)->ip6f_nxt;
2500 offset = ((struct ip6_frag *)ulp)->ip6f_offlg &
2502 /* Add IP6F_MORE_FRAG for offset of first
2503 * fragment to be != 0. */
2504 offset |= ((struct ip6_frag *)ulp)->ip6f_offlg &
2507 printf("IPFW2: IPV6 - Invalid Fragment "
2509 if (fw_deny_unknown_exthdrs)
2510 return (IP_FW_DENY);
2513 args->f_id.frag_id6 =
2514 ntohl(((struct ip6_frag *)ulp)->ip6f_ident);
2518 case IPPROTO_DSTOPTS: /* RFC 2460 */
2519 PULLUP_TO(hlen, ulp, struct ip6_hbh);
2520 ext_hd |= EXT_DSTOPTS;
2521 hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3;
2522 proto = ((struct ip6_hbh *)ulp)->ip6h_nxt;
2526 case IPPROTO_AH: /* RFC 2402 */
2527 PULLUP_TO(hlen, ulp, struct ip6_ext);
2529 hlen += (((struct ip6_ext *)ulp)->ip6e_len + 2) << 2;
2530 proto = ((struct ip6_ext *)ulp)->ip6e_nxt;
2534 case IPPROTO_ESP: /* RFC 2406 */
2535 PULLUP_TO(hlen, ulp, uint32_t); /* SPI, Seq# */
2536 /* Anything past Seq# is variable length and
2537 * data past this ext. header is encrypted. */
2541 case IPPROTO_NONE: /* RFC 2460 */
2542 PULLUP_TO(hlen, ulp, struct ip6_ext);
2543 /* Packet ends here. if ip6e_len!=0 octets
2544 * must be ignored. */
2547 case IPPROTO_OSPFIGP:
2548 /* XXX OSPF header check? */
2549 PULLUP_TO(hlen, ulp, struct ip6_ext);
2553 /* XXX PIM header check? */
2554 PULLUP_TO(hlen, ulp, struct pim);
2558 PULLUP_TO(hlen, ulp, struct carp_header);
2559 if (((struct carp_header *)ulp)->carp_version !=
2561 return (IP_FW_DENY);
2562 if (((struct carp_header *)ulp)->carp_type !=
2564 return (IP_FW_DENY);
2567 case IPPROTO_IPV6: /* RFC 2893 */
2568 PULLUP_TO(hlen, ulp, struct ip6_hdr);
2571 case IPPROTO_IPV4: /* RFC 2893 */
2572 PULLUP_TO(hlen, ulp, struct ip);
2576 printf("IPFW2: IPV6 - Unknown Extension "
2577 "Header(%d), ext_hd=%x\n", proto, ext_hd);
2578 if (fw_deny_unknown_exthdrs)
2579 return (IP_FW_DENY);
2580 PULLUP_TO(hlen, ulp, struct ip6_ext);
2584 ip = mtod(m, struct ip *);
2585 ip6 = (struct ip6_hdr *)ip;
2586 args->f_id.src_ip6 = ip6->ip6_src;
2587 args->f_id.dst_ip6 = ip6->ip6_dst;
2588 args->f_id.src_ip = 0;
2589 args->f_id.dst_ip = 0;
2590 args->f_id.flow_id6 = ntohl(ip6->ip6_flow);
2591 } else if (pktlen >= sizeof(struct ip) &&
2592 (args->eh == NULL || etype == ETHERTYPE_IP) && ip->ip_v == 4) {
2594 hlen = ip->ip_hl << 2;
2595 args->f_id.addr_type = 4;
2598 * Collect parameters into local variables for faster matching.
2601 src_ip = ip->ip_src;
2602 dst_ip = ip->ip_dst;
2603 if (args->eh != NULL) { /* layer 2 packets are as on the wire */
2604 offset = ntohs(ip->ip_off) & IP_OFFMASK;
2605 ip_len = ntohs(ip->ip_len);
2607 offset = ip->ip_off & IP_OFFMASK;
2608 ip_len = ip->ip_len;
2610 pktlen = ip_len < pktlen ? ip_len : pktlen;
2615 PULLUP_TO(hlen, ulp, struct tcphdr);
2616 dst_port = TCP(ulp)->th_dport;
2617 src_port = TCP(ulp)->th_sport;
2618 args->f_id.flags = TCP(ulp)->th_flags;
2622 PULLUP_TO(hlen, ulp, struct udphdr);
2623 dst_port = UDP(ulp)->uh_dport;
2624 src_port = UDP(ulp)->uh_sport;
2628 PULLUP_TO(hlen, ulp, struct icmphdr);
2629 args->f_id.flags = ICMP(ulp)->icmp_type;
2637 ip = mtod(m, struct ip *);
2638 args->f_id.src_ip = ntohl(src_ip.s_addr);
2639 args->f_id.dst_ip = ntohl(dst_ip.s_addr);
2642 if (proto) { /* we may have port numbers, store them */
2643 args->f_id.proto = proto;
2644 args->f_id.src_port = src_port = ntohs(src_port);
2645 args->f_id.dst_port = dst_port = ntohs(dst_port);
2649 mtag = m_tag_find(m, PACKET_TAG_DIVERT, NULL);
2652 * Packet has already been tagged. Look for the next rule
2653 * to restart processing.
2655 * If fw_one_pass != 0 then just accept it.
2656 * XXX should not happen here, but optimized out in
2660 IPFW_RUNLOCK(chain);
2661 return (IP_FW_PASS);
2664 f = args->rule->next_rule;
2666 f = lookup_next_rule(args->rule);
2669 * Find the starting rule. It can be either the first
2670 * one, or the one after divert_rule if asked so.
2672 int skipto = mtag ? divert_cookie(mtag) : 0;
2675 if (args->eh == NULL && skipto != 0) {
2676 if (skipto >= IPFW_DEFAULT_RULE) {
2677 IPFW_RUNLOCK(chain);
2678 return (IP_FW_DENY); /* invalid */
2680 while (f && f->rulenum <= skipto)
2682 if (f == NULL) { /* drop packet */
2683 IPFW_RUNLOCK(chain);
2684 return (IP_FW_DENY);
2688 /* reset divert rule to avoid confusion later */
2690 divinput_flags = divert_info(mtag) &
2691 (IP_FW_DIVERT_OUTPUT_FLAG | IP_FW_DIVERT_LOOPBACK_FLAG);
2692 m_tag_delete(m, mtag);
2696 * Now scan the rules, and parse microinstructions for each rule.
2698 for (; f; f = f->next) {
2700 uint32_t tablearg = 0;
2701 int l, cmdlen, skip_or; /* skip rest of OR block */
2704 if (set_disable & (1 << f->set) )
2708 for (l = f->cmd_len, cmd = f->cmd ; l > 0 ;
2709 l -= cmdlen, cmd += cmdlen) {
2713 * check_body is a jump target used when we find a
2714 * CHECK_STATE, and need to jump to the body of
2719 cmdlen = F_LEN(cmd);
2721 * An OR block (insn_1 || .. || insn_n) has the
2722 * F_OR bit set in all but the last instruction.
2723 * The first match will set "skip_or", and cause
2724 * the following instructions to be skipped until
2725 * past the one with the F_OR bit clear.
2727 if (skip_or) { /* skip this instruction */
2728 if ((cmd->len & F_OR) == 0)
2729 skip_or = 0; /* next one is good */
2732 match = 0; /* set to 1 if we succeed */
2734 switch (cmd->opcode) {
2736 * The first set of opcodes compares the packet's
2737 * fields with some pattern, setting 'match' if a
2738 * match is found. At the end of the loop there is
2739 * logic to deal with F_NOT and F_OR flags associated
2747 printf("ipfw: opcode %d unimplemented\n",
2755 * We only check offset == 0 && proto != 0,
2756 * as this ensures that we have a
2757 * packet with the ports info.
2761 if (is_ipv6) /* XXX to be fixed later */
2763 if (proto == IPPROTO_TCP ||
2764 proto == IPPROTO_UDP)
2765 match = check_uidgid(
2766 (ipfw_insn_u32 *)cmd,
2769 src_ip, src_port, &fw_ugid_cache,
2770 &ugid_lookup, args->inp);
2774 match = iface_match(m->m_pkthdr.rcvif,
2775 (ipfw_insn_if *)cmd);
2779 match = iface_match(oif, (ipfw_insn_if *)cmd);
2783 match = iface_match(oif ? oif :
2784 m->m_pkthdr.rcvif, (ipfw_insn_if *)cmd);
2788 if (args->eh != NULL) { /* have MAC header */
2789 u_int32_t *want = (u_int32_t *)
2790 ((ipfw_insn_mac *)cmd)->addr;
2791 u_int32_t *mask = (u_int32_t *)
2792 ((ipfw_insn_mac *)cmd)->mask;
2793 u_int32_t *hdr = (u_int32_t *)args->eh;
2796 ( want[0] == (hdr[0] & mask[0]) &&
2797 want[1] == (hdr[1] & mask[1]) &&
2798 want[2] == (hdr[2] & mask[2]) );
2803 if (args->eh != NULL) {
2805 ((ipfw_insn_u16 *)cmd)->ports;
2808 for (i = cmdlen - 1; !match && i>0;
2810 match = (etype >= p[0] &&
2816 match = (offset != 0);
2819 case O_IN: /* "out" is "not in" */
2820 match = (oif == NULL);
2824 match = (args->eh != NULL);
2828 match = (cmd->arg1 & 1 && divinput_flags &
2829 IP_FW_DIVERT_LOOPBACK_FLAG) ||
2830 (cmd->arg1 & 2 && divinput_flags &
2831 IP_FW_DIVERT_OUTPUT_FLAG);
2836 * We do not allow an arg of 0 so the
2837 * check of "proto" only suffices.
2839 match = (proto == cmd->arg1);
2844 (((ipfw_insn_ip *)cmd)->addr.s_addr ==
2848 case O_IP_SRC_LOOKUP:
2849 case O_IP_DST_LOOKUP:
2852 (cmd->opcode == O_IP_DST_LOOKUP) ?
2853 dst_ip.s_addr : src_ip.s_addr;
2856 match = lookup_table(chain, cmd->arg1, a,
2860 if (cmdlen == F_INSN_SIZE(ipfw_insn_u32))
2862 ((ipfw_insn_u32 *)cmd)->d[0] == v;
2872 (cmd->opcode == O_IP_DST_MASK) ?
2873 dst_ip.s_addr : src_ip.s_addr;
2874 uint32_t *p = ((ipfw_insn_u32 *)cmd)->d;
2877 for (; !match && i>0; i-= 2, p+= 2)
2878 match = (p[0] == (a & p[1]));
2886 INADDR_TO_IFP(src_ip, tif);
2887 match = (tif != NULL);
2894 u_int32_t *d = (u_int32_t *)(cmd+1);
2896 cmd->opcode == O_IP_DST_SET ?
2902 addr -= d[0]; /* subtract base */
2903 match = (addr < cmd->arg1) &&
2904 ( d[ 1 + (addr>>5)] &
2905 (1<<(addr & 0x1f)) );
2911 (((ipfw_insn_ip *)cmd)->addr.s_addr ==
2919 INADDR_TO_IFP(dst_ip, tif);
2920 match = (tif != NULL);
2927 * offset == 0 && proto != 0 is enough
2928 * to guarantee that we have a
2929 * packet with port info.
2931 if ((proto==IPPROTO_UDP || proto==IPPROTO_TCP)
2934 (cmd->opcode == O_IP_SRCPORT) ?
2935 src_port : dst_port ;
2937 ((ipfw_insn_u16 *)cmd)->ports;
2940 for (i = cmdlen - 1; !match && i>0;
2942 match = (x>=p[0] && x<=p[1]);
2947 match = (offset == 0 && proto==IPPROTO_ICMP &&
2948 icmptype_match(ICMP(ulp), (ipfw_insn_u32 *)cmd) );
2953 match = is_ipv6 && offset == 0 &&
2954 proto==IPPROTO_ICMPV6 &&
2956 ICMP6(ulp)->icmp6_type,
2957 (ipfw_insn_u32 *)cmd);
2963 ipopts_match(ip, cmd) );
2968 cmd->arg1 == ip->ip_v);
2974 if (is_ipv4) { /* only for IP packets */
2979 if (cmd->opcode == O_IPLEN)
2981 else if (cmd->opcode == O_IPTTL)
2983 else /* must be IPID */
2984 x = ntohs(ip->ip_id);
2986 match = (cmd->arg1 == x);
2989 /* otherwise we have ranges */
2990 p = ((ipfw_insn_u16 *)cmd)->ports;
2992 for (; !match && i>0; i--, p += 2)
2993 match = (x >= p[0] && x <= p[1]);
2997 case O_IPPRECEDENCE:
2999 (cmd->arg1 == (ip->ip_tos & 0xe0)) );
3004 flags_match(cmd, ip->ip_tos));
3008 if (proto == IPPROTO_TCP && offset == 0) {
3016 ((ip->ip_hl + tcp->th_off) << 2);
3018 match = (cmd->arg1 == x);
3021 /* otherwise we have ranges */
3022 p = ((ipfw_insn_u16 *)cmd)->ports;
3024 for (; !match && i>0; i--, p += 2)
3025 match = (x >= p[0] && x <= p[1]);
3030 match = (proto == IPPROTO_TCP && offset == 0 &&
3031 flags_match(cmd, TCP(ulp)->th_flags));
3035 match = (proto == IPPROTO_TCP && offset == 0 &&
3036 tcpopts_match(TCP(ulp), cmd));
3040 match = (proto == IPPROTO_TCP && offset == 0 &&
3041 ((ipfw_insn_u32 *)cmd)->d[0] ==
3046 match = (proto == IPPROTO_TCP && offset == 0 &&
3047 ((ipfw_insn_u32 *)cmd)->d[0] ==
3052 match = (proto == IPPROTO_TCP && offset == 0 &&
3053 cmd->arg1 == TCP(ulp)->th_win);
3057 /* reject packets which have SYN only */
3058 /* XXX should i also check for TH_ACK ? */
3059 match = (proto == IPPROTO_TCP && offset == 0 &&
3060 (TCP(ulp)->th_flags &
3061 (TH_RST | TH_ACK | TH_SYN)) != TH_SYN);
3065 struct altq_tag *at;
3066 ipfw_insn_altq *altq = (ipfw_insn_altq *)cmd;
3069 mtag = m_tag_find(m, PACKET_TAG_PF_QID, NULL);
3072 mtag = m_tag_get(PACKET_TAG_PF_QID,
3073 sizeof(struct altq_tag),
3077 * Let the packet fall back to the
3082 at = (struct altq_tag *)(mtag+1);
3083 at->qid = altq->qid;
3089 m_tag_prepend(m, mtag);
3095 ipfw_log(f, hlen, args, m,
3096 oif, offset, tablearg, ip);
3101 match = (random()<((ipfw_insn_u32 *)cmd)->d[0]);
3105 /* Outgoing packets automatically pass/match */
3106 match = ((oif != NULL) ||
3107 (m->m_pkthdr.rcvif == NULL) ||
3111 verify_path6(&(args->f_id.src_ip6),
3112 m->m_pkthdr.rcvif) :
3114 verify_path(src_ip, m->m_pkthdr.rcvif)));
3118 /* Outgoing packets automatically pass/match */
3119 match = (hlen > 0 && ((oif != NULL) ||
3122 verify_path6(&(args->f_id.src_ip6),
3125 verify_path(src_ip, NULL)));
3129 /* Outgoing packets automatically pass/match */
3130 if (oif == NULL && hlen > 0 &&
3131 ( (is_ipv4 && in_localaddr(src_ip))
3134 in6_localaddr(&(args->f_id.src_ip6)))
3139 is_ipv6 ? verify_path6(
3140 &(args->f_id.src_ip6),
3141 m->m_pkthdr.rcvif) :
3151 match = (m_tag_find(m,
3152 PACKET_TAG_IPSEC_IN_DONE, NULL) != NULL);
3155 match = (ipsec_getnhist(m) != 0);
3157 /* otherwise no match */
3163 IN6_ARE_ADDR_EQUAL(&args->f_id.src_ip6,
3164 &((ipfw_insn_ip6 *)cmd)->addr6);
3169 IN6_ARE_ADDR_EQUAL(&args->f_id.dst_ip6,
3170 &((ipfw_insn_ip6 *)cmd)->addr6);
3172 case O_IP6_SRC_MASK:
3173 case O_IP6_DST_MASK:
3177 struct in6_addr *d =
3178 &((ipfw_insn_ip6 *)cmd)->addr6;
3180 for (; !match && i > 0; d += 2,
3181 i -= F_INSN_SIZE(struct in6_addr)
3187 APPLY_MASK(&p, &d[1]);
3189 IN6_ARE_ADDR_EQUAL(&d[0],
3196 match= is_ipv6 && search_ip6_addr_net(&args->f_id.src_ip6);
3200 match= is_ipv6 && search_ip6_addr_net(&args->f_id.dst_ip6);
3205 flow6id_match(args->f_id.flow_id6,
3206 (ipfw_insn_u32 *) cmd);
3211 (ext_hd & ((ipfw_insn *) cmd)->arg1);
3224 uint32_t tag = (cmd->arg1 == IP_FW_TABLEARG) ?
3225 tablearg : cmd->arg1;
3227 /* Packet is already tagged with this tag? */
3228 mtag = m_tag_locate(m, MTAG_IPFW, tag, NULL);
3230 /* We have `untag' action when F_NOT flag is
3231 * present. And we must remove this mtag from
3232 * mbuf and reset `match' to zero (`match' will
3233 * be inversed later).
3234 * Otherwise we should allocate new mtag and
3235 * push it into mbuf.
3237 if (cmd->len & F_NOT) { /* `untag' action */
3239 m_tag_delete(m, mtag);
3240 } else if (mtag == NULL) {
3241 if ((mtag = m_tag_alloc(MTAG_IPFW,
3242 tag, 0, M_NOWAIT)) != NULL)
3243 m_tag_prepend(m, mtag);
3245 match = (cmd->len & F_NOT) ? 0: 1;
3250 uint32_t tag = (cmd->arg1 == IP_FW_TABLEARG) ?
3251 tablearg : cmd->arg1;
3254 match = m_tag_locate(m, MTAG_IPFW,
3259 /* we have ranges */
3260 for (mtag = m_tag_first(m);
3261 mtag != NULL && !match;
3262 mtag = m_tag_next(m, mtag)) {
3266 if (mtag->m_tag_cookie != MTAG_IPFW)
3269 p = ((ipfw_insn_u16 *)cmd)->ports;
3271 for(; !match && i > 0; i--, p += 2)
3273 mtag->m_tag_id >= p[0] &&
3274 mtag->m_tag_id <= p[1];
3280 * The second set of opcodes represents 'actions',
3281 * i.e. the terminal part of a rule once the packet
3282 * matches all previous patterns.
3283 * Typically there is only one action for each rule,
3284 * and the opcode is stored at the end of the rule
3285 * (but there are exceptions -- see below).
3287 * In general, here we set retval and terminate the
3288 * outer loop (would be a 'break 3' in some language,
3289 * but we need to do a 'goto done').
3292 * O_COUNT and O_SKIPTO actions:
3293 * instead of terminating, we jump to the next rule
3294 * ('goto next_rule', equivalent to a 'break 2'),
3295 * or to the SKIPTO target ('goto again' after
3296 * having set f, cmd and l), respectively.
3298 * O_TAG, O_LOG and O_ALTQ action parameters:
3299 * perform some action and set match = 1;
3301 * O_LIMIT and O_KEEP_STATE: these opcodes are
3302 * not real 'actions', and are stored right
3303 * before the 'action' part of the rule.
3304 * These opcodes try to install an entry in the
3305 * state tables; if successful, we continue with
3306 * the next opcode (match=1; break;), otherwise
3307 * the packet * must be dropped
3308 * ('goto done' after setting retval);
3310 * O_PROBE_STATE and O_CHECK_STATE: these opcodes
3311 * cause a lookup of the state table, and a jump
3312 * to the 'action' part of the parent rule
3313 * ('goto check_body') if an entry is found, or
3314 * (CHECK_STATE only) a jump to the next rule if
3315 * the entry is not found ('goto next_rule').
3316 * The result of the lookup is cached to make
3317 * further instances of these opcodes are
3322 if (install_state(f,
3323 (ipfw_insn_limit *)cmd, args, tablearg)) {
3324 retval = IP_FW_DENY;
3325 goto done; /* error/limit violation */
3333 * dynamic rules are checked at the first
3334 * keep-state or check-state occurrence,
3335 * with the result being stored in dyn_dir.
3336 * The compiler introduces a PROBE_STATE
3337 * instruction for us when we have a
3338 * KEEP_STATE (because PROBE_STATE needs
3341 if (dyn_dir == MATCH_UNKNOWN &&
3342 (q = lookup_dyn_rule(&args->f_id,
3343 &dyn_dir, proto == IPPROTO_TCP ?
3347 * Found dynamic entry, update stats
3348 * and jump to the 'action' part of
3354 cmd = ACTION_PTR(f);
3355 l = f->cmd_len - f->act_ofs;
3360 * Dynamic entry not found. If CHECK_STATE,
3361 * skip to next rule, if PROBE_STATE just
3362 * ignore and continue with next opcode.
3364 if (cmd->opcode == O_CHECK_STATE)
3370 retval = 0; /* accept */
3375 args->rule = f; /* report matching rule */
3376 if (cmd->arg1 == IP_FW_TABLEARG)
3377 args->cookie = tablearg;
3379 args->cookie = cmd->arg1;
3380 retval = IP_FW_DUMMYNET;
3385 struct divert_tag *dt;
3387 if (args->eh) /* not on layer 2 */
3389 mtag = m_tag_get(PACKET_TAG_DIVERT,
3390 sizeof(struct divert_tag),
3395 IPFW_RUNLOCK(chain);
3396 return (IP_FW_DENY);
3398 dt = (struct divert_tag *)(mtag+1);
3399 dt->cookie = f->rulenum;
3400 if (cmd->arg1 == IP_FW_TABLEARG)
3401 dt->info = tablearg;
3403 dt->info = cmd->arg1;
3404 m_tag_prepend(m, mtag);
3405 retval = (cmd->opcode == O_DIVERT) ?
3406 IP_FW_DIVERT : IP_FW_TEE;
3412 f->pcnt++; /* update stats */
3414 f->timestamp = time_uptime;
3415 if (cmd->opcode == O_COUNT)
3418 if (f->next_rule == NULL)
3419 lookup_next_rule(f);
3425 * Drop the packet and send a reject notice
3426 * if the packet is not ICMP (or is an ICMP
3427 * query), and it is not multicast/broadcast.
3429 if (hlen > 0 && is_ipv4 && offset == 0 &&
3430 (proto != IPPROTO_ICMP ||
3431 is_icmp_query(ICMP(ulp))) &&
3432 !(m->m_flags & (M_BCAST|M_MCAST)) &&
3433 !IN_MULTICAST(ntohl(dst_ip.s_addr))) {
3434 send_reject(args, cmd->arg1, ip_len, ip);
3440 if (hlen > 0 && is_ipv6 &&
3441 ((offset & IP6F_OFF_MASK) == 0) &&
3442 (proto != IPPROTO_ICMPV6 ||
3443 (is_icmp6_query(args->f_id.flags) == 1)) &&
3444 !(m->m_flags & (M_BCAST|M_MCAST)) &&
3445 !IN6_IS_ADDR_MULTICAST(&args->f_id.dst_ip6)) {
3447 args, cmd->arg1, hlen,
3448 (struct ip6_hdr *)ip);
3454 retval = IP_FW_DENY;
3457 case O_FORWARD_IP: {
3458 struct sockaddr_in *sa;
3459 sa = &(((ipfw_insn_sa *)cmd)->sa);
3460 if (args->eh) /* not valid on layer2 pkts */
3462 if (!q || dyn_dir == MATCH_FORWARD) {
3463 if (sa->sin_addr.s_addr == INADDR_ANY) {
3464 bcopy(sa, &args->hopstore,
3466 args->hopstore.sin_addr.s_addr =
3471 args->next_hop = sa;
3474 retval = IP_FW_PASS;
3480 args->rule = f; /* report matching rule */
3481 if (cmd->arg1 == IP_FW_TABLEARG)
3482 args->cookie = tablearg;
3484 args->cookie = cmd->arg1;
3485 retval = (cmd->opcode == O_NETGRAPH) ?
3486 IP_FW_NETGRAPH : IP_FW_NGTEE;
3489 #ifdef IPFIREWALL_NAT
3493 /* XXX - libalias duct tape */
3498 args->rule = f; /* Report matching rule. */
3500 t = ((ipfw_insn_nat *)cmd)->nat;
3502 t = lookup_nat(cmd->arg1);
3504 retval = IP_FW_DENY;
3507 ((ipfw_insn_nat *)cmd)->nat =
3510 if ((mcl = m_megapullup(m, m->m_pkthdr.len)) ==
3513 ip = mtod(mcl, struct ip *);
3514 if (args->eh == NULL) {
3515 ip->ip_len = htons(ip->ip_len);
3516 ip->ip_off = htons(ip->ip_off);
3520 * XXX - Libalias checksum offload 'duct tape':
3522 * locally generated packets have only
3523 * pseudo-header checksum calculated
3524 * and libalias will screw it[1], so
3525 * mark them for later fix. Moreover
3526 * there are cases when libalias
3527 * modify tcp packet data[2], mark it
3528 * for later fix too.
3530 * [1] libalias was never meant to run
3531 * in kernel, so it doesn't have any
3532 * knowledge about checksum
3533 * offloading, and it expects a packet
3534 * with a full internet
3535 * checksum. Unfortunately, packets
3536 * generated locally will have just the
3537 * pseudo header calculated, and when
3538 * libalias tries to adjust the
3539 * checksum it will actually screw it.
3541 * [2] when libalias modify tcp's data
3542 * content, full TCP checksum has to
3543 * be recomputed: the problem is that
3544 * libalias doesn't have any idea
3545 * about checksum offloading To
3546 * workaround this, we do not do
3547 * checksumming in LibAlias, but only
3548 * mark the packets in th_x2 field. If
3549 * we receive a marked packet, we
3550 * calculate correct checksum for it
3551 * aware of offloading. Why such a
3552 * terrible hack instead of
3553 * recalculating checksum for each
3554 * packet? Because the previous
3555 * checksum was not checked!
3556 * Recalculating checksums for EVERY
3557 * packet will hide ALL transmission
3558 * errors. Yes, marked packets still
3559 * suffer from this problem. But,
3560 * sigh, natd(8) has this problem,
3563 * TODO: -make libalias mbuf aware (so
3564 * it can handle delayed checksum and tso)
3567 if (mcl->m_pkthdr.rcvif == NULL &&
3568 mcl->m_pkthdr.csum_flags &
3572 c = mtod(mcl, char *);
3574 retval = LibAliasIn(t->lib, c,
3577 retval = LibAliasOut(t->lib, c,
3579 if (retval != PKT_ALIAS_OK) {
3580 /* XXX - should i add some logging? */
3584 retval = IP_FW_DENY;
3587 mcl->m_pkthdr.len = mcl->m_len =
3591 * XXX - libalias checksum offload
3592 * 'duct tape' (see above)
3595 if ((ip->ip_off & htons(IP_OFFMASK)) == 0 &&
3596 ip->ip_p == IPPROTO_TCP) {
3599 th = (struct tcphdr *)(ip + 1);
3609 ip->ip_len = ntohs(ip->ip_len);
3613 htons(ip->ip_p + ip->ip_len -
3619 th = (struct tcphdr *)(ip + 1);
3621 * Maybe it was set in
3626 mcl->m_pkthdr.csum_data =
3627 offsetof(struct tcphdr,
3631 uh = (struct udphdr *)(ip + 1);
3633 mcl->m_pkthdr.csum_data =
3634 offsetof(struct udphdr,
3639 * No hw checksum offloading: do it
3642 if ((mcl->m_pkthdr.csum_flags &
3643 CSUM_DELAY_DATA) == 0) {
3644 in_delayed_cksum(mcl);
3645 mcl->m_pkthdr.csum_flags &=
3648 ip->ip_len = htons(ip->ip_len);
3651 if (args->eh == NULL) {
3652 ip->ip_len = ntohs(ip->ip_len);
3653 ip->ip_off = ntohs(ip->ip_off);
3663 panic("-- unknown opcode %d\n", cmd->opcode);
3664 } /* end of switch() on opcodes */
3666 if (cmd->len & F_NOT)
3670 if (cmd->len & F_OR)
3673 if (!(cmd->len & F_OR)) /* not an OR block, */
3674 break; /* try next rule */
3677 } /* end of inner for, scan opcodes */
3679 next_rule:; /* try next rule */
3681 } /* end of outer for, scan rules */
3682 printf("ipfw: ouch!, skip past end of rules, denying packet\n");
3683 IPFW_RUNLOCK(chain);
3684 return (IP_FW_DENY);
3687 /* Update statistics */
3690 f->timestamp = time_uptime;
3691 IPFW_RUNLOCK(chain);
3696 printf("ipfw: pullup failed\n");
3697 return (IP_FW_DENY);
3701 * When a rule is added/deleted, clear the next_rule pointers in all rules.
3702 * These will be reconstructed on the fly as packets are matched.
3705 flush_rule_ptrs(struct ip_fw_chain *chain)
3709 IPFW_WLOCK_ASSERT(chain);
3711 for (rule = chain->rules; rule; rule = rule->next)
3712 rule->next_rule = NULL;
3716 * Add a new rule to the list. Copy the rule into a malloc'ed area, then
3717 * possibly create a rule number and add the rule to the list.
3718 * Update the rule_number in the input struct so the caller knows it as well.
3721 add_rule(struct ip_fw_chain *chain, struct ip_fw *input_rule)
3723 struct ip_fw *rule, *f, *prev;
3724 int l = RULESIZE(input_rule);
3726 if (chain->rules == NULL && input_rule->rulenum != IPFW_DEFAULT_RULE)
3729 rule = malloc(l, M_IPFW, M_NOWAIT | M_ZERO);
3733 bcopy(input_rule, rule, l);
3736 rule->next_rule = NULL;
3740 rule->timestamp = 0;
3744 if (chain->rules == NULL) { /* default rule */
3745 chain->rules = rule;
3750 * If rulenum is 0, find highest numbered rule before the
3751 * default rule, and add autoinc_step
3753 if (autoinc_step < 1)
3755 else if (autoinc_step > 1000)
3756 autoinc_step = 1000;
3757 if (rule->rulenum == 0) {
3759 * locate the highest numbered rule before default
3761 for (f = chain->rules; f; f = f->next) {
3762 if (f->rulenum == IPFW_DEFAULT_RULE)
3764 rule->rulenum = f->rulenum;
3766 if (rule->rulenum < IPFW_DEFAULT_RULE - autoinc_step)
3767 rule->rulenum += autoinc_step;
3768 input_rule->rulenum = rule->rulenum;
3772 * Now insert the new rule in the right place in the sorted list.
3774 for (prev = NULL, f = chain->rules; f; prev = f, f = f->next) {
3775 if (f->rulenum > rule->rulenum) { /* found the location */
3779 } else { /* head insert */
3780 rule->next = chain->rules;
3781 chain->rules = rule;
3786 flush_rule_ptrs(chain);
3790 IPFW_WUNLOCK(chain);
3791 DEB(printf("ipfw: installed rule %d, static count now %d\n",
3792 rule->rulenum, static_count);)
3797 * Remove a static rule (including derived * dynamic rules)
3798 * and place it on the ``reap list'' for later reclamation.
3799 * The caller is in charge of clearing rule pointers to avoid
3800 * dangling pointers.
3801 * @return a pointer to the next entry.
3802 * Arguments are not checked, so they better be correct.
3804 static struct ip_fw *
3805 remove_rule(struct ip_fw_chain *chain, struct ip_fw *rule,
3809 int l = RULESIZE(rule);
3811 IPFW_WLOCK_ASSERT(chain);
3815 remove_dyn_rule(rule, NULL /* force removal */);
3824 rule->next = chain->reap;
3831 * Reclaim storage associated with a list of rules. This is
3832 * typically the list created using remove_rule.
3835 reap_rules(struct ip_fw *head)
3839 while ((rule = head) != NULL) {
3841 if (DUMMYNET_LOADED)
3842 ip_dn_ruledel_ptr(rule);
3848 * Remove all rules from a chain (except rules in set RESVD_SET
3849 * unless kill_default = 1). The caller is responsible for
3850 * reclaiming storage for the rules left in chain->reap.
3853 free_chain(struct ip_fw_chain *chain, int kill_default)
3855 struct ip_fw *prev, *rule;
3857 IPFW_WLOCK_ASSERT(chain);
3859 flush_rule_ptrs(chain); /* more efficient to do outside the loop */
3860 for (prev = NULL, rule = chain->rules; rule ; )
3861 if (kill_default || rule->set != RESVD_SET)
3862 rule = remove_rule(chain, rule, prev);
3870 * Remove all rules with given number, and also do set manipulation.
3871 * Assumes chain != NULL && *chain != NULL.
3873 * The argument is an u_int32_t. The low 16 bit are the rule or set number,
3874 * the next 8 bits are the new set, the top 8 bits are the command:
3876 * 0 delete rules with given number
3877 * 1 delete rules with given set number
3878 * 2 move rules with given number to new set
3879 * 3 move rules with given set number to new set
3880 * 4 swap sets with given numbers
3883 del_entry(struct ip_fw_chain *chain, u_int32_t arg)
3885 struct ip_fw *prev = NULL, *rule;
3886 u_int16_t rulenum; /* rule or old_set */
3887 u_int8_t cmd, new_set;
3889 rulenum = arg & 0xffff;
3890 cmd = (arg >> 24) & 0xff;
3891 new_set = (arg >> 16) & 0xff;
3895 if (new_set > RESVD_SET)
3897 if (cmd == 0 || cmd == 2) {
3898 if (rulenum >= IPFW_DEFAULT_RULE)
3901 if (rulenum > RESVD_SET) /* old_set */
3906 rule = chain->rules;
3909 case 0: /* delete rules with given number */
3911 * locate first rule to delete
3913 for (; rule->rulenum < rulenum; prev = rule, rule = rule->next)
3915 if (rule->rulenum != rulenum) {
3916 IPFW_WUNLOCK(chain);
3921 * flush pointers outside the loop, then delete all matching
3922 * rules. prev remains the same throughout the cycle.
3924 flush_rule_ptrs(chain);
3925 while (rule->rulenum == rulenum)
3926 rule = remove_rule(chain, rule, prev);
3929 case 1: /* delete all rules with given set number */
3930 flush_rule_ptrs(chain);
3931 rule = chain->rules;
3932 while (rule->rulenum < IPFW_DEFAULT_RULE)
3933 if (rule->set == rulenum)
3934 rule = remove_rule(chain, rule, prev);
3941 case 2: /* move rules with given number to new set */
3942 rule = chain->rules;
3943 for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
3944 if (rule->rulenum == rulenum)
3945 rule->set = new_set;
3948 case 3: /* move rules with given set number to new set */
3949 for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
3950 if (rule->set == rulenum)
3951 rule->set = new_set;
3954 case 4: /* swap two sets */
3955 for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
3956 if (rule->set == rulenum)
3957 rule->set = new_set;
3958 else if (rule->set == new_set)
3959 rule->set = rulenum;
3963 * Look for rules to reclaim. We grab the list before
3964 * releasing the lock then reclaim them w/o the lock to
3965 * avoid a LOR with dummynet.
3969 IPFW_WUNLOCK(chain);
3976 * Clear counters for a specific rule.
3977 * The enclosing "table" is assumed locked.
3980 clear_counters(struct ip_fw *rule, int log_only)
3982 ipfw_insn_log *l = (ipfw_insn_log *)ACTION_PTR(rule);
3984 if (log_only == 0) {
3985 rule->bcnt = rule->pcnt = 0;
3986 rule->timestamp = 0;
3988 if (l->o.opcode == O_LOG)
3989 l->log_left = l->max_log;
3993 * Reset some or all counters on firewall rules.
3994 * @arg frwl is null to clear all entries, or contains a specific
3996 * @arg log_only is 1 if we only want to reset logs, zero otherwise.
3999 zero_entry(struct ip_fw_chain *chain, int rulenum, int log_only)
4007 for (rule = chain->rules; rule; rule = rule->next)
4008 clear_counters(rule, log_only);
4009 msg = log_only ? "ipfw: All logging counts reset.\n" :
4010 "ipfw: Accounting cleared.\n";
4014 * We can have multiple rules with the same number, so we
4015 * need to clear them all.
4017 for (rule = chain->rules; rule; rule = rule->next)
4018 if (rule->rulenum == rulenum) {
4019 while (rule && rule->rulenum == rulenum) {
4020 clear_counters(rule, log_only);
4026 if (!cleared) { /* we did not find any matching rules */
4027 IPFW_WUNLOCK(chain);
4030 msg = log_only ? "ipfw: Entry %d logging count reset.\n" :
4031 "ipfw: Entry %d cleared.\n";
4033 IPFW_WUNLOCK(chain);
4036 log(LOG_SECURITY | LOG_NOTICE, msg, rulenum);
4041 * Check validity of the structure before insert.
4042 * Fortunately rules are simple, so this mostly need to check rule sizes.
4045 check_ipfw_struct(struct ip_fw *rule, int size)
4051 if (size < sizeof(*rule)) {
4052 printf("ipfw: rule too short\n");
4055 /* first, check for valid size */
4058 printf("ipfw: size mismatch (have %d want %d)\n", size, l);
4061 if (rule->act_ofs >= rule->cmd_len) {
4062 printf("ipfw: bogus action offset (%u > %u)\n",
4063 rule->act_ofs, rule->cmd_len - 1);
4067 * Now go for the individual checks. Very simple ones, basically only
4068 * instruction sizes.
4070 for (l = rule->cmd_len, cmd = rule->cmd ;
4071 l > 0 ; l -= cmdlen, cmd += cmdlen) {
4072 cmdlen = F_LEN(cmd);
4074 printf("ipfw: opcode %d size truncated\n",
4078 DEB(printf("ipfw: opcode %d\n", cmd->opcode);)
4079 switch (cmd->opcode) {
4091 case O_IPPRECEDENCE:
4109 if (cmdlen != F_INSN_SIZE(ipfw_insn))
4122 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32))
4127 if (cmdlen != F_INSN_SIZE(ipfw_insn_limit))
4132 if (cmdlen != F_INSN_SIZE(ipfw_insn_log))
4135 ((ipfw_insn_log *)cmd)->log_left =
4136 ((ipfw_insn_log *)cmd)->max_log;
4142 /* only odd command lengths */
4143 if ( !(cmdlen & 1) || cmdlen > 31)
4149 if (cmd->arg1 == 0 || cmd->arg1 > 256) {
4150 printf("ipfw: invalid set size %d\n",
4154 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
4159 case O_IP_SRC_LOOKUP:
4160 case O_IP_DST_LOOKUP:
4161 if (cmd->arg1 >= IPFW_TABLES_MAX) {
4162 printf("ipfw: invalid table number %d\n",
4166 if (cmdlen != F_INSN_SIZE(ipfw_insn) &&
4167 cmdlen != F_INSN_SIZE(ipfw_insn_u32))
4172 if (cmdlen != F_INSN_SIZE(ipfw_insn_mac))
4182 if (cmdlen < 1 || cmdlen > 31)
4188 case O_IP_DSTPORT: /* XXX artificial limit, 30 port pairs */
4189 if (cmdlen < 2 || cmdlen > 31)
4196 if (cmdlen != F_INSN_SIZE(ipfw_insn_if))
4201 if (cmdlen != F_INSN_SIZE(ipfw_insn_altq))
4207 if (cmdlen != F_INSN_SIZE(ipfw_insn))
4212 #ifdef IPFIREWALL_FORWARD
4213 if (cmdlen != F_INSN_SIZE(ipfw_insn_sa))
4222 if (ip_divert_ptr == NULL)
4228 if (!NG_IPFW_LOADED)
4233 #ifdef IPFIREWALL_NAT
4234 if (cmdlen != F_INSN_SIZE(ipfw_insn_nat))
4240 case O_FORWARD_MAC: /* XXX not implemented yet */
4251 if (cmdlen != F_INSN_SIZE(ipfw_insn))
4255 printf("ipfw: opcode %d, multiple actions"
4262 printf("ipfw: opcode %d, action must be"
4271 if (cmdlen != F_INSN_SIZE(struct in6_addr) +
4272 F_INSN_SIZE(ipfw_insn))
4277 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
4278 ((ipfw_insn_u32 *)cmd)->o.arg1)
4282 case O_IP6_SRC_MASK:
4283 case O_IP6_DST_MASK:
4284 if ( !(cmdlen & 1) || cmdlen > 127)
4288 if( cmdlen != F_INSN_SIZE( ipfw_insn_icmp6 ) )
4294 switch (cmd->opcode) {
4304 case O_IP6_SRC_MASK:
4305 case O_IP6_DST_MASK:
4307 printf("ipfw: no IPv6 support in kernel\n");
4308 return EPROTONOSUPPORT;
4311 printf("ipfw: opcode %d, unknown opcode\n",
4317 if (have_action == 0) {
4318 printf("ipfw: missing action\n");
4324 printf("ipfw: opcode %d size %d wrong\n",
4325 cmd->opcode, cmdlen);
4330 * Copy the static and dynamic rules to the supplied buffer
4331 * and return the amount of space actually used.
4334 ipfw_getrules(struct ip_fw_chain *chain, void *buf, size_t space)
4337 char *ep = bp + space;
4340 time_t boot_seconds;
4342 boot_seconds = boottime.tv_sec;
4343 /* XXX this can take a long time and locking will block packet flow */
4345 for (rule = chain->rules; rule ; rule = rule->next) {
4347 * Verify the entry fits in the buffer in case the
4348 * rules changed between calculating buffer space and
4349 * now. This would be better done using a generation
4350 * number but should suffice for now.
4356 * XXX HACK. Store the disable mask in the "next" pointer
4357 * in a wild attempt to keep the ABI the same.
4358 * Why do we do this on EVERY rule?
4360 bcopy(&set_disable, &(((struct ip_fw *)bp)->next_rule),
4361 sizeof(set_disable));
4362 if (((struct ip_fw *)bp)->timestamp)
4363 ((struct ip_fw *)bp)->timestamp += boot_seconds;
4367 IPFW_RUNLOCK(chain);
4369 ipfw_dyn_rule *p, *last = NULL;
4372 for (i = 0 ; i < curr_dyn_buckets; i++)
4373 for (p = ipfw_dyn_v[i] ; p != NULL; p = p->next) {
4374 if (bp + sizeof *p <= ep) {
4375 ipfw_dyn_rule *dst =
4376 (ipfw_dyn_rule *)bp;
4377 bcopy(p, dst, sizeof *p);
4378 bcopy(&(p->rule->rulenum), &(dst->rule),
4379 sizeof(p->rule->rulenum));
4381 * store a non-null value in "next".
4382 * The userland code will interpret a
4383 * NULL here as a marker
4384 * for the last dynamic rule.
4386 bcopy(&dst, &dst->next, sizeof(dst));
4389 TIME_LEQ(dst->expire, time_uptime) ?
4390 0 : dst->expire - time_uptime ;
4391 bp += sizeof(ipfw_dyn_rule);
4395 if (last != NULL) /* mark last dynamic rule */
4396 bzero(&last->next, sizeof(last));
4398 return (bp - (char *)buf);
4403 * {set|get}sockopt parser.
4406 ipfw_ctl(struct sockopt *sopt)
4408 #define RULE_MAXSIZE (256*sizeof(u_int32_t))
4409 int error, rule_num;
4411 struct ip_fw *buf, *rule;
4412 u_int32_t rulenum[2];
4414 error = priv_check(sopt->sopt_td, PRIV_NETINET_IPFW);
4419 * Disallow modifications in really-really secure mode, but still allow
4420 * the logging counters to be reset.
4422 if (sopt->sopt_name == IP_FW_ADD ||
4423 (sopt->sopt_dir == SOPT_SET && sopt->sopt_name != IP_FW_RESETLOG)) {
4424 error = securelevel_ge(sopt->sopt_td->td_ucred, 3);
4431 switch (sopt->sopt_name) {
4434 * pass up a copy of the current rules. Static rules
4435 * come first (the last of which has number IPFW_DEFAULT_RULE),
4436 * followed by a possibly empty list of dynamic rule.
4437 * The last dynamic rule has NULL in the "next" field.
4439 * Note that the calculated size is used to bound the
4440 * amount of data returned to the user. The rule set may
4441 * change between calculating the size and returning the
4442 * data in which case we'll just return what fits.
4444 size = static_len; /* size of static rules */
4445 if (ipfw_dyn_v) /* add size of dyn.rules */
4446 size += (dyn_count * sizeof(ipfw_dyn_rule));
4449 * XXX todo: if the user passes a short length just to know
4450 * how much room is needed, do not bother filling up the
4451 * buffer, just jump to the sooptcopyout.
4453 buf = malloc(size, M_TEMP, M_WAITOK);
4454 error = sooptcopyout(sopt, buf,
4455 ipfw_getrules(&layer3_chain, buf, size));
4461 * Normally we cannot release the lock on each iteration.
4462 * We could do it here only because we start from the head all
4463 * the times so there is no risk of missing some entries.
4464 * On the other hand, the risk is that we end up with
4465 * a very inconsistent ruleset, so better keep the lock
4466 * around the whole cycle.
4468 * XXX this code can be improved by resetting the head of
4469 * the list to point to the default rule, and then freeing
4470 * the old list without the need for a lock.
4473 IPFW_WLOCK(&layer3_chain);
4474 layer3_chain.reap = NULL;
4475 free_chain(&layer3_chain, 0 /* keep default rule */);
4476 rule = layer3_chain.reap;
4477 layer3_chain.reap = NULL;
4478 IPFW_WUNLOCK(&layer3_chain);
4484 rule = malloc(RULE_MAXSIZE, M_TEMP, M_WAITOK);
4485 error = sooptcopyin(sopt, rule, RULE_MAXSIZE,
4486 sizeof(struct ip_fw) );
4488 error = check_ipfw_struct(rule, sopt->sopt_valsize);
4490 error = add_rule(&layer3_chain, rule);
4491 size = RULESIZE(rule);
4492 if (!error && sopt->sopt_dir == SOPT_GET)
4493 error = sooptcopyout(sopt, rule, size);
4500 * IP_FW_DEL is used for deleting single rules or sets,
4501 * and (ab)used to atomically manipulate sets. Argument size
4502 * is used to distinguish between the two:
4504 * delete single rule or set of rules,
4505 * or reassign rules (or sets) to a different set.
4506 * 2*sizeof(u_int32_t)
4507 * atomic disable/enable sets.
4508 * first u_int32_t contains sets to be disabled,
4509 * second u_int32_t contains sets to be enabled.
4511 error = sooptcopyin(sopt, rulenum,
4512 2*sizeof(u_int32_t), sizeof(u_int32_t));
4515 size = sopt->sopt_valsize;
4516 if (size == sizeof(u_int32_t)) /* delete or reassign */
4517 error = del_entry(&layer3_chain, rulenum[0]);
4518 else if (size == 2*sizeof(u_int32_t)) /* set enable/disable */
4520 (set_disable | rulenum[0]) & ~rulenum[1] &
4521 ~(1<<RESVD_SET); /* set RESVD_SET always enabled */
4527 case IP_FW_RESETLOG: /* argument is an int, the rule number */
4529 if (sopt->sopt_val != 0) {
4530 error = sooptcopyin(sopt, &rule_num,
4531 sizeof(int), sizeof(int));
4535 error = zero_entry(&layer3_chain, rule_num,
4536 sopt->sopt_name == IP_FW_RESETLOG);
4539 case IP_FW_TABLE_ADD:
4541 ipfw_table_entry ent;
4543 error = sooptcopyin(sopt, &ent,
4544 sizeof(ent), sizeof(ent));
4547 error = add_table_entry(&layer3_chain, ent.tbl,
4548 ent.addr, ent.masklen, ent.value);
4552 case IP_FW_TABLE_DEL:
4554 ipfw_table_entry ent;
4556 error = sooptcopyin(sopt, &ent,
4557 sizeof(ent), sizeof(ent));
4560 error = del_table_entry(&layer3_chain, ent.tbl,
4561 ent.addr, ent.masklen);
4565 case IP_FW_TABLE_FLUSH:
4569 error = sooptcopyin(sopt, &tbl,
4570 sizeof(tbl), sizeof(tbl));
4573 IPFW_WLOCK(&layer3_chain);
4574 error = flush_table(&layer3_chain, tbl);
4575 IPFW_WUNLOCK(&layer3_chain);
4579 case IP_FW_TABLE_GETSIZE:
4583 if ((error = sooptcopyin(sopt, &tbl, sizeof(tbl),
4586 IPFW_RLOCK(&layer3_chain);
4587 error = count_table(&layer3_chain, tbl, &cnt);
4588 IPFW_RUNLOCK(&layer3_chain);
4591 error = sooptcopyout(sopt, &cnt, sizeof(cnt));
4595 case IP_FW_TABLE_LIST:
4599 if (sopt->sopt_valsize < sizeof(*tbl)) {
4603 size = sopt->sopt_valsize;
4604 tbl = malloc(size, M_TEMP, M_WAITOK);
4605 error = sooptcopyin(sopt, tbl, size, sizeof(*tbl));
4610 tbl->size = (size - sizeof(*tbl)) /
4611 sizeof(ipfw_table_entry);
4612 IPFW_RLOCK(&layer3_chain);
4613 error = dump_table(&layer3_chain, tbl);
4614 IPFW_RUNLOCK(&layer3_chain);
4619 error = sooptcopyout(sopt, tbl, size);
4624 #ifdef IPFIREWALL_NAT
4627 struct cfg_nat *ptr, *ser_n;
4630 buf = malloc(NAT_BUF_LEN, M_IPFW, M_WAITOK | M_ZERO);
4631 error = sooptcopyin(sopt, buf, NAT_BUF_LEN,
4632 sizeof(struct cfg_nat));
4633 ser_n = (struct cfg_nat *)buf;
4636 * Find/create nat rule.
4638 IPFW_WLOCK(&layer3_chain);
4639 ptr = lookup_nat(ser_n->id);
4641 /* New rule: allocate and init new instance. */
4642 ptr = malloc(sizeof(struct cfg_nat),
4643 M_IPFW, M_NOWAIT | M_ZERO);
4645 IPFW_WUNLOCK(&layer3_chain);
4649 ptr->lib = LibAliasInit(NULL);
4650 if (ptr->lib == NULL) {
4651 IPFW_WUNLOCK(&layer3_chain);
4656 LIST_INIT(&ptr->redir_chain);
4658 /* Entry already present: temporarly unhook it. */
4660 flush_nat_ptrs(ser_n->id);
4662 IPFW_WUNLOCK(&layer3_chain);
4665 * Basic nat configuration.
4667 ptr->id = ser_n->id;
4669 * XXX - what if this rule doesn't nat any ip and just
4671 * do we set aliasaddress to 0.0.0.0?
4673 ptr->ip = ser_n->ip;
4674 ptr->redir_cnt = ser_n->redir_cnt;
4675 ptr->mode = ser_n->mode;
4676 LibAliasSetMode(ptr->lib, ser_n->mode, ser_n->mode);
4677 LibAliasSetAddress(ptr->lib, ptr->ip);
4678 memcpy(ptr->if_name, ser_n->if_name, IF_NAMESIZE);
4681 * Redir and LSNAT configuration.
4683 /* Delete old cfgs. */
4684 del_redir_spool_cfg(ptr, &ptr->redir_chain);
4685 /* Add new entries. */
4686 add_redir_spool_cfg(&buf[(sizeof(struct cfg_nat))], ptr);
4688 IPFW_WLOCK(&layer3_chain);
4689 HOOK_NAT(&layer3_chain.nat, ptr);
4690 IPFW_WUNLOCK(&layer3_chain);
4696 struct cfg_nat *ptr;
4699 error = sooptcopyin(sopt, &i, sizeof i, sizeof i);
4700 IPFW_WLOCK(&layer3_chain);
4701 ptr = lookup_nat(i);
4704 IPFW_WUNLOCK(&layer3_chain);
4709 IPFW_WUNLOCK(&layer3_chain);
4710 del_redir_spool_cfg(ptr, &ptr->redir_chain);
4711 LibAliasUninit(ptr->lib);
4716 case IP_FW_NAT_GET_CONFIG:
4720 struct cfg_redir *r;
4721 struct cfg_spool *s;
4725 off = sizeof(nat_cnt);
4727 data = malloc(NAT_BUF_LEN, M_IPFW, M_WAITOK | M_ZERO);
4728 IPFW_RLOCK(&layer3_chain);
4729 /* Serialize all the data. */
4730 LIST_FOREACH(n, &layer3_chain.nat, _next) {
4732 if (off + SOF_NAT < NAT_BUF_LEN) {
4733 bcopy(n, &data[off], SOF_NAT);
4735 LIST_FOREACH(r, &n->redir_chain, _next) {
4736 if (off + SOF_REDIR < NAT_BUF_LEN) {
4737 bcopy(r, &data[off],
4740 LIST_FOREACH(s, &r->spool_chain,
4742 if (off + SOF_SPOOL <
4758 bcopy(&nat_cnt, data, sizeof(nat_cnt));
4759 IPFW_RUNLOCK(&layer3_chain);
4760 error = sooptcopyout(sopt, data, NAT_BUF_LEN);
4764 IPFW_RUNLOCK(&layer3_chain);
4765 printf("serialized data buffer not big enough:"
4766 "please increase NAT_BUF_LEN\n");
4771 case IP_FW_NAT_GET_LOG:
4774 struct cfg_nat *ptr;
4775 int i, size, cnt, sof;
4778 sof = LIBALIAS_BUF_SIZE;
4781 IPFW_RLOCK(&layer3_chain);
4783 LIST_FOREACH(ptr, &layer3_chain.nat, _next) {
4784 if (ptr->lib->logDesc == NULL)
4787 size = cnt * (sof + sizeof(int));
4788 data = realloc(data, size, M_IPFW, M_NOWAIT | M_ZERO);
4790 IPFW_RUNLOCK(&layer3_chain);
4793 bcopy(&ptr->id, &data[i], sizeof(int));
4795 bcopy(ptr->lib->logDesc, &data[i], sof);
4798 IPFW_RUNLOCK(&layer3_chain);
4799 error = sooptcopyout(sopt, data, size);
4806 printf("ipfw: ipfw_ctl invalid option %d\n", sopt->sopt_name);
4815 * dummynet needs a reference to the default rule, because rules can be
4816 * deleted while packets hold a reference to them. When this happens,
4817 * dummynet changes the reference to the default rule (it could well be a
4818 * NULL pointer, but this way we do not need to check for the special
4819 * case, plus here he have info on the default behaviour).
4821 struct ip_fw *ip_fw_default_rule;
4824 * This procedure is only used to handle keepalives. It is invoked
4825 * every dyn_keepalive_period
4828 ipfw_tick(void * __unused unused)
4830 struct mbuf *m0, *m, *mnext, **mtailp;
4834 if (dyn_keepalive == 0 || ipfw_dyn_v == NULL || dyn_count == 0)
4838 * We make a chain of packets to go out here -- not deferring
4839 * until after we drop the IPFW dynamic rule lock would result
4840 * in a lock order reversal with the normal packet input -> ipfw
4846 for (i = 0 ; i < curr_dyn_buckets ; i++) {
4847 for (q = ipfw_dyn_v[i] ; q ; q = q->next ) {
4848 if (q->dyn_type == O_LIMIT_PARENT)
4850 if (q->id.proto != IPPROTO_TCP)
4852 if ( (q->state & BOTH_SYN) != BOTH_SYN)
4854 if (TIME_LEQ( time_uptime+dyn_keepalive_interval,
4856 continue; /* too early */
4857 if (TIME_LEQ(q->expire, time_uptime))
4858 continue; /* too late, rule expired */
4860 *mtailp = send_pkt(NULL, &(q->id), q->ack_rev - 1,
4861 q->ack_fwd, TH_SYN);
4862 if (*mtailp != NULL)
4863 mtailp = &(*mtailp)->m_nextpkt;
4864 *mtailp = send_pkt(NULL, &(q->id), q->ack_fwd - 1,
4866 if (*mtailp != NULL)
4867 mtailp = &(*mtailp)->m_nextpkt;
4871 for (m = mnext = m0; m != NULL; m = mnext) {
4872 mnext = m->m_nextpkt;
4873 m->m_nextpkt = NULL;
4874 ip_output(m, NULL, NULL, 0, NULL, NULL);
4877 callout_reset(&ipfw_timeout, dyn_keepalive_period*hz, ipfw_tick, NULL);
4883 struct ip_fw default_rule;
4887 /* Setup IPv6 fw sysctl tree. */
4888 sysctl_ctx_init(&ip6_fw_sysctl_ctx);
4889 ip6_fw_sysctl_tree = SYSCTL_ADD_NODE(&ip6_fw_sysctl_ctx,
4890 SYSCTL_STATIC_CHILDREN(_net_inet6_ip6), OID_AUTO, "fw",
4891 CTLFLAG_RW | CTLFLAG_SECURE, 0, "Firewall");
4892 SYSCTL_ADD_PROC(&ip6_fw_sysctl_ctx, SYSCTL_CHILDREN(ip6_fw_sysctl_tree),
4893 OID_AUTO, "enable", CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE3,
4894 &fw6_enable, 0, ipfw_chg_hook, "I", "Enable ipfw+6");
4895 SYSCTL_ADD_INT(&ip6_fw_sysctl_ctx, SYSCTL_CHILDREN(ip6_fw_sysctl_tree),
4896 OID_AUTO, "deny_unknown_exthdrs", CTLFLAG_RW | CTLFLAG_SECURE,
4897 &fw_deny_unknown_exthdrs, 0,
4898 "Deny packets with unknown IPv6 Extension Headers");
4901 layer3_chain.rules = NULL;
4902 IPFW_LOCK_INIT(&layer3_chain);
4903 ipfw_dyn_rule_zone = uma_zcreate("IPFW dynamic rule",
4904 sizeof(ipfw_dyn_rule), NULL, NULL, NULL, NULL,
4906 IPFW_DYN_LOCK_INIT();
4907 callout_init(&ipfw_timeout, NET_CALLOUT_MPSAFE);
4909 bzero(&default_rule, sizeof default_rule);
4911 default_rule.act_ofs = 0;
4912 default_rule.rulenum = IPFW_DEFAULT_RULE;
4913 default_rule.cmd_len = 1;
4914 default_rule.set = RESVD_SET;
4916 default_rule.cmd[0].len = 1;
4917 default_rule.cmd[0].opcode =
4918 #ifdef IPFIREWALL_DEFAULT_TO_ACCEPT
4923 error = add_rule(&layer3_chain, &default_rule);
4925 printf("ipfw2: error %u initializing default rule "
4926 "(support disabled)\n", error);
4927 IPFW_DYN_LOCK_DESTROY();
4928 IPFW_LOCK_DESTROY(&layer3_chain);
4929 uma_zdestroy(ipfw_dyn_rule_zone);
4933 ip_fw_default_rule = layer3_chain.rules;
4938 "initialized, divert %s, "
4939 "rule-based forwarding "
4940 #ifdef IPFIREWALL_FORWARD
4945 "default to %s, logging ",
4951 default_rule.cmd[0].opcode == O_ACCEPT ? "accept" : "deny");
4953 #ifdef IPFIREWALL_VERBOSE
4956 #ifdef IPFIREWALL_VERBOSE_LIMIT
4957 verbose_limit = IPFIREWALL_VERBOSE_LIMIT;
4959 if (fw_verbose == 0)
4960 printf("disabled\n");
4961 else if (verbose_limit == 0)
4962 printf("unlimited\n");
4964 printf("limited to %d packets/entry by default\n",
4967 error = init_tables(&layer3_chain);
4969 IPFW_DYN_LOCK_DESTROY();
4970 IPFW_LOCK_DESTROY(&layer3_chain);
4971 uma_zdestroy(ipfw_dyn_rule_zone);
4974 ip_fw_ctl_ptr = ipfw_ctl;
4975 ip_fw_chk_ptr = ipfw_chk;
4976 callout_reset(&ipfw_timeout, hz, ipfw_tick, NULL);
4977 #ifdef IPFIREWALL_NAT
4978 LIST_INIT(&layer3_chain.nat);
4979 ifaddr_event_tag = EVENTHANDLER_REGISTER(ifaddr_event, ifaddr_change,
4980 NULL, EVENTHANDLER_PRI_ANY);
4989 #ifdef IPFIREWALL_NAT
4990 struct cfg_nat *ptr, *ptr_temp;
4993 ip_fw_chk_ptr = NULL;
4994 ip_fw_ctl_ptr = NULL;
4995 callout_drain(&ipfw_timeout);
4996 IPFW_WLOCK(&layer3_chain);
4997 flush_tables(&layer3_chain);
4998 #ifdef IPFIREWALL_NAT
4999 LIST_FOREACH_SAFE(ptr, &layer3_chain.nat, _next, ptr_temp) {
5000 LIST_REMOVE(ptr, _next);
5001 del_redir_spool_cfg(ptr, &ptr->redir_chain);
5002 LibAliasUninit(ptr->lib);
5005 EVENTHANDLER_DEREGISTER(ifaddr_event, ifaddr_event_tag);
5007 layer3_chain.reap = NULL;
5008 free_chain(&layer3_chain, 1 /* kill default rule */);
5009 reap = layer3_chain.reap, layer3_chain.reap = NULL;
5010 IPFW_WUNLOCK(&layer3_chain);
5013 IPFW_DYN_LOCK_DESTROY();
5014 uma_zdestroy(ipfw_dyn_rule_zone);
5015 IPFW_LOCK_DESTROY(&layer3_chain);
5018 /* Free IPv6 fw sysctl tree. */
5019 sysctl_ctx_free(&ip6_fw_sysctl_ctx);
5022 printf("IP firewall unloaded\n");