2 * Copyright (c) 2002 Luigi Rizzo, Universita` di Pisa
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
13 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
14 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
16 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
17 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
19 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
20 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
21 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 #include <sys/cdefs.h>
27 __FBSDID("$FreeBSD$");
33 * Implement IP packet firewall (new version)
36 #if !defined(KLD_MODULE)
38 #include "opt_ipdivert.h"
42 #error IPFIREWALL requires INET.
45 #include "opt_inet6.h"
46 #include "opt_ipsec.h"
49 #include <sys/param.h>
50 #include <sys/systm.h>
51 #include <sys/condvar.h>
52 #include <sys/eventhandler.h>
53 #include <sys/malloc.h>
55 #include <sys/kernel.h>
58 #include <sys/module.h>
61 #include <sys/rwlock.h>
62 #include <sys/socket.h>
63 #include <sys/socketvar.h>
64 #include <sys/sysctl.h>
65 #include <sys/syslog.h>
66 #include <sys/ucred.h>
68 #include <net/radix.h>
69 #include <net/route.h>
70 #include <net/pf_mtag.h>
72 #define IPFW_INTERNAL /* Access to protected data structures in ip_fw.h. */
74 #include <netinet/in.h>
75 #include <netinet/in_systm.h>
76 #include <netinet/in_var.h>
77 #include <netinet/in_pcb.h>
78 #include <netinet/ip.h>
79 #include <netinet/ip_var.h>
80 #include <netinet/ip_icmp.h>
81 #include <netinet/ip_fw.h>
82 #include <netinet/ip_divert.h>
83 #include <netinet/ip_dummynet.h>
84 #include <netinet/ip_carp.h>
85 #include <netinet/pim.h>
86 #include <netinet/tcp.h>
87 #include <netinet/tcp_timer.h>
88 #include <netinet/tcp_var.h>
89 #include <netinet/tcpip.h>
90 #include <netinet/udp.h>
91 #include <netinet/udp_var.h>
92 #include <netinet/sctp.h>
94 #include <netinet/libalias/alias.h>
95 #include <netinet/libalias/alias_local.h>
97 #include <netgraph/ng_ipfw.h>
99 #include <altq/if_altq.h>
101 #include <netinet/ip6.h>
102 #include <netinet/icmp6.h>
104 #include <netinet6/scope6_var.h>
107 #include <netinet/if_ether.h> /* XXX for ETHERTYPE_IP */
109 #include <machine/in_cksum.h> /* XXX for in_cksum */
111 #include <security/mac/mac_framework.h>
114 * set_disable contains one bit per set value (0..31).
115 * If the bit is set, all rules with the corresponding set
116 * are disabled. Set RESVD_SET(31) is reserved for the default rule
117 * and rules that are not deleted by the flush command,
118 * and CANNOT be disabled.
119 * Rules in set RESVD_SET can only be deleted explicitly.
121 static u_int32_t set_disable;
123 static int fw_verbose;
124 static int verbose_limit;
126 static struct callout ipfw_timeout;
127 static uma_zone_t ipfw_dyn_rule_zone;
128 #define IPFW_DEFAULT_RULE 65535
131 * Data structure to cache our ucred related
132 * information. This structure only gets used if
133 * the user specified UID/GID based constraints in
137 gid_t fw_groups[NGROUPS];
143 #define IPFW_TABLES_MAX 128
145 struct ip_fw *rules; /* list of rules */
146 struct ip_fw *reap; /* list of rules to reap */
147 LIST_HEAD(, cfg_nat) nat; /* list of nat entries */
148 struct radix_node_head *tables[IPFW_TABLES_MAX];
151 #define IPFW_LOCK_INIT(_chain) \
152 rw_init(&(_chain)->rwmtx, "IPFW static rules")
153 #define IPFW_LOCK_DESTROY(_chain) rw_destroy(&(_chain)->rwmtx)
154 #define IPFW_WLOCK_ASSERT(_chain) rw_assert(&(_chain)->rwmtx, RA_WLOCKED)
156 #define IPFW_RLOCK(p) rw_rlock(&(p)->rwmtx)
157 #define IPFW_RUNLOCK(p) rw_runlock(&(p)->rwmtx)
158 #define IPFW_WLOCK(p) rw_wlock(&(p)->rwmtx)
159 #define IPFW_WUNLOCK(p) rw_wunlock(&(p)->rwmtx)
162 * list of rules for layer 3
164 static struct ip_fw_chain layer3_chain;
166 MALLOC_DEFINE(M_IPFW, "IpFw/IpAcct", "IpFw/IpAcct chain's");
167 MALLOC_DEFINE(M_IPFW_TBL, "ipfw_tbl", "IpFw tables");
170 struct radix_node rn[2];
171 struct sockaddr_in addr, mask;
175 static int fw_debug = 1;
176 static int autoinc_step = 100; /* bounded to 1..1000 in add_rule() */
178 extern int ipfw_chg_hook(SYSCTL_HANDLER_ARGS);
181 SYSCTL_NODE(_net_inet_ip, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall");
182 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, enable,
183 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE3, &fw_enable, 0,
184 ipfw_chg_hook, "I", "Enable ipfw");
185 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, autoinc_step, CTLFLAG_RW,
186 &autoinc_step, 0, "Rule number autincrement step");
187 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, one_pass,
188 CTLFLAG_RW | CTLFLAG_SECURE3,
190 "Only do a single pass through ipfw when using dummynet(4)");
191 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, debug, CTLFLAG_RW,
192 &fw_debug, 0, "Enable printing of debug ip_fw statements");
193 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose,
194 CTLFLAG_RW | CTLFLAG_SECURE3,
195 &fw_verbose, 0, "Log matches to ipfw rules");
196 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose_limit, CTLFLAG_RW,
197 &verbose_limit, 0, "Set upper limit of matches of ipfw rules logged");
200 * Description of dynamic rules.
202 * Dynamic rules are stored in lists accessed through a hash table
203 * (ipfw_dyn_v) whose size is curr_dyn_buckets. This value can
204 * be modified through the sysctl variable dyn_buckets which is
205 * updated when the table becomes empty.
207 * XXX currently there is only one list, ipfw_dyn.
209 * When a packet is received, its address fields are first masked
210 * with the mask defined for the rule, then hashed, then matched
211 * against the entries in the corresponding list.
212 * Dynamic rules can be used for different purposes:
214 * + enforcing limits on the number of sessions;
215 * + in-kernel NAT (not implemented yet)
217 * The lifetime of dynamic rules is regulated by dyn_*_lifetime,
218 * measured in seconds and depending on the flags.
220 * The total number of dynamic rules is stored in dyn_count.
221 * The max number of dynamic rules is dyn_max. When we reach
222 * the maximum number of rules we do not create anymore. This is
223 * done to avoid consuming too much memory, but also too much
224 * time when searching on each packet (ideally, we should try instead
225 * to put a limit on the length of the list on each bucket...).
227 * Each dynamic rule holds a pointer to the parent ipfw rule so
228 * we know what action to perform. Dynamic rules are removed when
229 * the parent rule is deleted. XXX we should make them survive.
231 * There are some limitations with dynamic rules -- we do not
232 * obey the 'randomized match', and we do not do multiple
233 * passes through the firewall. XXX check the latter!!!
235 static ipfw_dyn_rule **ipfw_dyn_v = NULL;
236 static u_int32_t dyn_buckets = 256; /* must be power of 2 */
237 static u_int32_t curr_dyn_buckets = 256; /* must be power of 2 */
239 static struct mtx ipfw_dyn_mtx; /* mutex guarding dynamic rules */
240 #define IPFW_DYN_LOCK_INIT() \
241 mtx_init(&ipfw_dyn_mtx, "IPFW dynamic rules", NULL, MTX_DEF)
242 #define IPFW_DYN_LOCK_DESTROY() mtx_destroy(&ipfw_dyn_mtx)
243 #define IPFW_DYN_LOCK() mtx_lock(&ipfw_dyn_mtx)
244 #define IPFW_DYN_UNLOCK() mtx_unlock(&ipfw_dyn_mtx)
245 #define IPFW_DYN_LOCK_ASSERT() mtx_assert(&ipfw_dyn_mtx, MA_OWNED)
248 * Timeouts for various events in handing dynamic rules.
250 static u_int32_t dyn_ack_lifetime = 300;
251 static u_int32_t dyn_syn_lifetime = 20;
252 static u_int32_t dyn_fin_lifetime = 1;
253 static u_int32_t dyn_rst_lifetime = 1;
254 static u_int32_t dyn_udp_lifetime = 10;
255 static u_int32_t dyn_short_lifetime = 5;
258 * Keepalives are sent if dyn_keepalive is set. They are sent every
259 * dyn_keepalive_period seconds, in the last dyn_keepalive_interval
260 * seconds of lifetime of a rule.
261 * dyn_rst_lifetime and dyn_fin_lifetime should be strictly lower
262 * than dyn_keepalive_period.
265 static u_int32_t dyn_keepalive_interval = 20;
266 static u_int32_t dyn_keepalive_period = 5;
267 static u_int32_t dyn_keepalive = 1; /* do send keepalives */
269 static u_int32_t static_count; /* # of static rules */
270 static u_int32_t static_len; /* size in bytes of static rules */
271 static u_int32_t dyn_count; /* # of dynamic rules */
272 static u_int32_t dyn_max = 4096; /* max # of dynamic rules */
274 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_buckets, CTLFLAG_RW,
275 &dyn_buckets, 0, "Number of dyn. buckets");
276 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, curr_dyn_buckets, CTLFLAG_RD,
277 &curr_dyn_buckets, 0, "Current Number of dyn. buckets");
278 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_count, CTLFLAG_RD,
279 &dyn_count, 0, "Number of dyn. rules");
280 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_max, CTLFLAG_RW,
281 &dyn_max, 0, "Max number of dyn. rules");
282 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, static_count, CTLFLAG_RD,
283 &static_count, 0, "Number of static rules");
284 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_ack_lifetime, CTLFLAG_RW,
285 &dyn_ack_lifetime, 0, "Lifetime of dyn. rules for acks");
286 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_syn_lifetime, CTLFLAG_RW,
287 &dyn_syn_lifetime, 0, "Lifetime of dyn. rules for syn");
288 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_fin_lifetime, CTLFLAG_RW,
289 &dyn_fin_lifetime, 0, "Lifetime of dyn. rules for fin");
290 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_rst_lifetime, CTLFLAG_RW,
291 &dyn_rst_lifetime, 0, "Lifetime of dyn. rules for rst");
292 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_udp_lifetime, CTLFLAG_RW,
293 &dyn_udp_lifetime, 0, "Lifetime of dyn. rules for UDP");
294 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_short_lifetime, CTLFLAG_RW,
295 &dyn_short_lifetime, 0, "Lifetime of dyn. rules for other situations");
296 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_keepalive, CTLFLAG_RW,
297 &dyn_keepalive, 0, "Enable keepalives for dyn. rules");
301 * IPv6 specific variables
303 SYSCTL_DECL(_net_inet6_ip6);
305 static struct sysctl_ctx_list ip6_fw_sysctl_ctx;
306 static struct sysctl_oid *ip6_fw_sysctl_tree;
308 #endif /* SYSCTL_NODE */
310 #ifdef IPFIREWALL_NAT
311 MODULE_DEPEND(ipfw, libalias, 1, 1, 1);
313 static int fw_deny_unknown_exthdrs = 1;
317 * L3HDR maps an ipv4 pointer into a layer3 header pointer of type T
318 * Other macros just cast void * into the appropriate type
320 #define L3HDR(T, ip) ((T *)((u_int32_t *)(ip) + (ip)->ip_hl))
321 #define TCP(p) ((struct tcphdr *)(p))
322 #define SCTP(p) ((struct sctphdr *)(p))
323 #define UDP(p) ((struct udphdr *)(p))
324 #define ICMP(p) ((struct icmphdr *)(p))
325 #define ICMP6(p) ((struct icmp6_hdr *)(p))
328 icmptype_match(struct icmphdr *icmp, ipfw_insn_u32 *cmd)
330 int type = icmp->icmp_type;
332 return (type <= ICMP_MAXTYPE && (cmd->d[0] & (1<<type)) );
335 #define TT ( (1 << ICMP_ECHO) | (1 << ICMP_ROUTERSOLICIT) | \
336 (1 << ICMP_TSTAMP) | (1 << ICMP_IREQ) | (1 << ICMP_MASKREQ) )
339 is_icmp_query(struct icmphdr *icmp)
341 int type = icmp->icmp_type;
343 return (type <= ICMP_MAXTYPE && (TT & (1<<type)) );
348 * The following checks use two arrays of 8 or 16 bits to store the
349 * bits that we want set or clear, respectively. They are in the
350 * low and high half of cmd->arg1 or cmd->d[0].
352 * We scan options and store the bits we find set. We succeed if
354 * (want_set & ~bits) == 0 && (want_clear & ~bits) == want_clear
356 * The code is sometimes optimized not to store additional variables.
360 flags_match(ipfw_insn *cmd, u_int8_t bits)
365 if ( ((cmd->arg1 & 0xff) & bits) != 0)
366 return 0; /* some bits we want set were clear */
367 want_clear = (cmd->arg1 >> 8) & 0xff;
368 if ( (want_clear & bits) != want_clear)
369 return 0; /* some bits we want clear were set */
374 ipopts_match(struct ip *ip, ipfw_insn *cmd)
376 int optlen, bits = 0;
377 u_char *cp = (u_char *)(ip + 1);
378 int x = (ip->ip_hl << 2) - sizeof (struct ip);
380 for (; x > 0; x -= optlen, cp += optlen) {
381 int opt = cp[IPOPT_OPTVAL];
383 if (opt == IPOPT_EOL)
385 if (opt == IPOPT_NOP)
388 optlen = cp[IPOPT_OLEN];
389 if (optlen <= 0 || optlen > x)
390 return 0; /* invalid or truncated */
398 bits |= IP_FW_IPOPT_LSRR;
402 bits |= IP_FW_IPOPT_SSRR;
406 bits |= IP_FW_IPOPT_RR;
410 bits |= IP_FW_IPOPT_TS;
414 return (flags_match(cmd, bits));
418 tcpopts_match(struct tcphdr *tcp, ipfw_insn *cmd)
420 int optlen, bits = 0;
421 u_char *cp = (u_char *)(tcp + 1);
422 int x = (tcp->th_off << 2) - sizeof(struct tcphdr);
424 for (; x > 0; x -= optlen, cp += optlen) {
426 if (opt == TCPOPT_EOL)
428 if (opt == TCPOPT_NOP)
442 bits |= IP_FW_TCPOPT_MSS;
446 bits |= IP_FW_TCPOPT_WINDOW;
449 case TCPOPT_SACK_PERMITTED:
451 bits |= IP_FW_TCPOPT_SACK;
454 case TCPOPT_TIMESTAMP:
455 bits |= IP_FW_TCPOPT_TS;
460 return (flags_match(cmd, bits));
464 iface_match(struct ifnet *ifp, ipfw_insn_if *cmd)
466 if (ifp == NULL) /* no iface with this packet, match fails */
468 /* Check by name or by IP address */
469 if (cmd->name[0] != '\0') { /* match by name */
472 if (fnmatch(cmd->name, ifp->if_xname, 0) == 0)
475 if (strncmp(ifp->if_xname, cmd->name, IFNAMSIZ) == 0)
482 TAILQ_FOREACH(ia, &ifp->if_addrhead, ifa_link) {
483 if (ia->ifa_addr->sa_family != AF_INET)
485 if (cmd->p.ip.s_addr == ((struct sockaddr_in *)
486 (ia->ifa_addr))->sin_addr.s_addr)
487 return(1); /* match */
490 return(0); /* no match, fail ... */
494 * The verify_path function checks if a route to the src exists and
495 * if it is reachable via ifp (when provided).
497 * The 'verrevpath' option checks that the interface that an IP packet
498 * arrives on is the same interface that traffic destined for the
499 * packet's source address would be routed out of. The 'versrcreach'
500 * option just checks that the source address is reachable via any route
501 * (except default) in the routing table. These two are a measure to block
502 * forged packets. This is also commonly known as "anti-spoofing" or Unicast
503 * Reverse Path Forwarding (Unicast RFP) in Cisco-ese. The name of the knobs
504 * is purposely reminiscent of the Cisco IOS command,
506 * ip verify unicast reverse-path
507 * ip verify unicast source reachable-via any
509 * which implements the same functionality. But note that syntax is
510 * misleading. The check may be performed on all IP packets whether unicast,
511 * multicast, or broadcast.
514 verify_path(struct in_addr src, struct ifnet *ifp)
517 struct sockaddr_in *dst;
519 bzero(&ro, sizeof(ro));
521 dst = (struct sockaddr_in *)&(ro.ro_dst);
522 dst->sin_family = AF_INET;
523 dst->sin_len = sizeof(*dst);
525 rtalloc_ign(&ro, RTF_CLONING);
527 if (ro.ro_rt == NULL)
531 * If ifp is provided, check for equality with rtentry.
532 * We should use rt->rt_ifa->ifa_ifp, instead of rt->rt_ifp,
533 * in order to pass packets injected back by if_simloop():
534 * if useloopback == 1 routing entry (via lo0) for our own address
535 * may exist, so we need to handle routing assymetry.
537 if (ifp != NULL && ro.ro_rt->rt_ifa->ifa_ifp != ifp) {
542 /* if no ifp provided, check if rtentry is not default route */
544 satosin(rt_key(ro.ro_rt))->sin_addr.s_addr == INADDR_ANY) {
549 /* or if this is a blackhole/reject route */
550 if (ifp == NULL && ro.ro_rt->rt_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
555 /* found valid route */
562 * ipv6 specific rules here...
565 icmp6type_match (int type, ipfw_insn_u32 *cmd)
567 return (type <= ICMP6_MAXTYPE && (cmd->d[type/32] & (1<<(type%32)) ) );
571 flow6id_match( int curr_flow, ipfw_insn_u32 *cmd )
574 for (i=0; i <= cmd->o.arg1; ++i )
575 if (curr_flow == cmd->d[i] )
580 /* support for IP6_*_ME opcodes */
582 search_ip6_addr_net (struct in6_addr * ip6_addr)
586 struct in6_ifaddr *fdm;
587 struct in6_addr copia;
589 TAILQ_FOREACH(mdc, &ifnet, if_link)
590 TAILQ_FOREACH(mdc2, &mdc->if_addrlist, ifa_list) {
591 if (mdc2->ifa_addr->sa_family == AF_INET6) {
592 fdm = (struct in6_ifaddr *)mdc2;
593 copia = fdm->ia_addr.sin6_addr;
594 /* need for leaving scope_id in the sock_addr */
595 in6_clearscope(&copia);
596 if (IN6_ARE_ADDR_EQUAL(ip6_addr, &copia))
604 verify_path6(struct in6_addr *src, struct ifnet *ifp)
607 struct sockaddr_in6 *dst;
609 bzero(&ro, sizeof(ro));
611 dst = (struct sockaddr_in6 * )&(ro.ro_dst);
612 dst->sin6_family = AF_INET6;
613 dst->sin6_len = sizeof(*dst);
614 dst->sin6_addr = *src;
615 rtalloc_ign((struct route *)&ro, RTF_CLONING);
617 if (ro.ro_rt == NULL)
621 * if ifp is provided, check for equality with rtentry
622 * We should use rt->rt_ifa->ifa_ifp, instead of rt->rt_ifp,
623 * to support the case of sending packets to an address of our own.
624 * (where the former interface is the first argument of if_simloop()
625 * (=ifp), the latter is lo0)
627 if (ifp != NULL && ro.ro_rt->rt_ifa->ifa_ifp != ifp) {
632 /* if no ifp provided, check if rtentry is not default route */
634 IN6_IS_ADDR_UNSPECIFIED(&satosin6(rt_key(ro.ro_rt))->sin6_addr)) {
639 /* or if this is a blackhole/reject route */
640 if (ifp == NULL && ro.ro_rt->rt_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
645 /* found valid route */
651 hash_packet6(struct ipfw_flow_id *id)
654 i = (id->dst_ip6.__u6_addr.__u6_addr32[2]) ^
655 (id->dst_ip6.__u6_addr.__u6_addr32[3]) ^
656 (id->src_ip6.__u6_addr.__u6_addr32[2]) ^
657 (id->src_ip6.__u6_addr.__u6_addr32[3]) ^
658 (id->dst_port) ^ (id->src_port);
663 is_icmp6_query(int icmp6_type)
665 if ((icmp6_type <= ICMP6_MAXTYPE) &&
666 (icmp6_type == ICMP6_ECHO_REQUEST ||
667 icmp6_type == ICMP6_MEMBERSHIP_QUERY ||
668 icmp6_type == ICMP6_WRUREQUEST ||
669 icmp6_type == ICMP6_FQDN_QUERY ||
670 icmp6_type == ICMP6_NI_QUERY))
677 send_reject6(struct ip_fw_args *args, int code, u_int hlen, struct ip6_hdr *ip6)
682 if (code == ICMP6_UNREACH_RST && args->f_id.proto == IPPROTO_TCP) {
690 tcp = (struct tcphdr *)((char *)ip6 + hlen);
692 if ((tcp->th_flags & TH_RST) != 0) {
700 ti.th.th_seq = ntohl(ti.th.th_seq);
701 ti.th.th_ack = ntohl(ti.th.th_ack);
702 ti.ip6.ip6_nxt = IPPROTO_TCP;
704 if (ti.th.th_flags & TH_ACK) {
710 if ((m->m_flags & M_PKTHDR) != 0) {
712 * total new data to ACK is:
713 * total packet length,
714 * minus the header length,
715 * minus the tcp header length.
717 ack += m->m_pkthdr.len - hlen
718 - (ti.th.th_off << 2);
719 } else if (ip6->ip6_plen) {
720 ack += ntohs(ip6->ip6_plen) + sizeof(*ip6) -
721 hlen - (ti.th.th_off << 2);
726 if (tcp->th_flags & TH_SYN)
729 flags = TH_RST|TH_ACK;
731 bcopy(&ti, ip6, sizeof(ti));
733 * m is only used to recycle the mbuf
734 * The data in it is never read so we don't need
735 * to correct the offsets or anything
737 tcp_respond(NULL, ip6, tcp, m, ack, seq, flags);
738 } else if (code != ICMP6_UNREACH_RST) { /* Send an ICMPv6 unreach. */
741 * Unlike above, the mbufs need to line up with the ip6 hdr,
742 * as the contents are read. We need to m_adj() the
744 * The mbuf will however be thrown away so we can adjust it.
745 * Remember we did an m_pullup on it already so we
746 * can make some assumptions about contiguousness.
749 m_adj(m, args->L3offset);
751 icmp6_error(m, ICMP6_DST_UNREACH, code, 0);
760 static u_int64_t norule_counter; /* counter for ipfw_log(NULL...) */
762 #define SNPARGS(buf, len) buf + len, sizeof(buf) > len ? sizeof(buf) - len : 0
763 #define SNP(buf) buf, sizeof(buf)
766 * We enter here when we have a rule with O_LOG.
767 * XXX this function alone takes about 2Kbytes of code!
770 ipfw_log(struct ip_fw *f, u_int hlen, struct ip_fw_args *args,
771 struct mbuf *m, struct ifnet *oif, u_short offset, uint32_t tablearg,
774 struct ether_header *eh = args->eh;
776 int limit_reached = 0;
777 char action2[40], proto[128], fragment[32];
782 if (f == NULL) { /* bogus pkt */
783 if (verbose_limit != 0 && norule_counter >= verbose_limit)
786 if (norule_counter == verbose_limit)
787 limit_reached = verbose_limit;
789 } else { /* O_LOG is the first action, find the real one */
790 ipfw_insn *cmd = ACTION_PTR(f);
791 ipfw_insn_log *l = (ipfw_insn_log *)cmd;
793 if (l->max_log != 0 && l->log_left == 0)
796 if (l->log_left == 0)
797 limit_reached = l->max_log;
798 cmd += F_LEN(cmd); /* point to first action */
799 if (cmd->opcode == O_ALTQ) {
800 ipfw_insn_altq *altq = (ipfw_insn_altq *)cmd;
802 snprintf(SNPARGS(action2, 0), "Altq %d",
806 if (cmd->opcode == O_PROB)
809 if (cmd->opcode == O_TAG)
813 switch (cmd->opcode) {
819 if (cmd->arg1==ICMP_REJECT_RST)
821 else if (cmd->arg1==ICMP_UNREACH_HOST)
824 snprintf(SNPARGS(action2, 0), "Unreach %d",
829 if (cmd->arg1==ICMP6_UNREACH_RST)
832 snprintf(SNPARGS(action2, 0), "Unreach %d",
843 snprintf(SNPARGS(action2, 0), "Divert %d",
847 snprintf(SNPARGS(action2, 0), "Tee %d",
851 snprintf(SNPARGS(action2, 0), "SkipTo %d",
855 snprintf(SNPARGS(action2, 0), "Pipe %d",
859 snprintf(SNPARGS(action2, 0), "Queue %d",
863 ipfw_insn_sa *sa = (ipfw_insn_sa *)cmd;
865 struct in_addr dummyaddr;
866 if (sa->sa.sin_addr.s_addr == INADDR_ANY)
867 dummyaddr.s_addr = htonl(tablearg);
869 dummyaddr.s_addr = sa->sa.sin_addr.s_addr;
871 len = snprintf(SNPARGS(action2, 0), "Forward to %s",
872 inet_ntoa(dummyaddr));
875 snprintf(SNPARGS(action2, len), ":%d",
880 snprintf(SNPARGS(action2, 0), "Netgraph %d",
884 snprintf(SNPARGS(action2, 0), "Ngtee %d",
896 if (hlen == 0) { /* non-ip */
897 snprintf(SNPARGS(proto, 0), "MAC");
901 char src[48], dst[48];
902 struct icmphdr *icmp;
906 struct ip6_hdr *ip6 = NULL;
907 struct icmp6_hdr *icmp6;
912 if (IS_IP6_FLOW_ID(&(args->f_id))) {
913 char ip6buf[INET6_ADDRSTRLEN];
914 snprintf(src, sizeof(src), "[%s]",
915 ip6_sprintf(ip6buf, &args->f_id.src_ip6));
916 snprintf(dst, sizeof(dst), "[%s]",
917 ip6_sprintf(ip6buf, &args->f_id.dst_ip6));
919 ip6 = (struct ip6_hdr *)ip;
920 tcp = (struct tcphdr *)(((char *)ip) + hlen);
921 udp = (struct udphdr *)(((char *)ip) + hlen);
925 tcp = L3HDR(struct tcphdr, ip);
926 udp = L3HDR(struct udphdr, ip);
928 inet_ntoa_r(ip->ip_src, src);
929 inet_ntoa_r(ip->ip_dst, dst);
932 switch (args->f_id.proto) {
934 len = snprintf(SNPARGS(proto, 0), "TCP %s", src);
936 snprintf(SNPARGS(proto, len), ":%d %s:%d",
937 ntohs(tcp->th_sport),
939 ntohs(tcp->th_dport));
941 snprintf(SNPARGS(proto, len), " %s", dst);
945 len = snprintf(SNPARGS(proto, 0), "UDP %s", src);
947 snprintf(SNPARGS(proto, len), ":%d %s:%d",
948 ntohs(udp->uh_sport),
950 ntohs(udp->uh_dport));
952 snprintf(SNPARGS(proto, len), " %s", dst);
956 icmp = L3HDR(struct icmphdr, ip);
958 len = snprintf(SNPARGS(proto, 0),
960 icmp->icmp_type, icmp->icmp_code);
962 len = snprintf(SNPARGS(proto, 0), "ICMP ");
963 len += snprintf(SNPARGS(proto, len), "%s", src);
964 snprintf(SNPARGS(proto, len), " %s", dst);
968 icmp6 = (struct icmp6_hdr *)(((char *)ip) + hlen);
970 len = snprintf(SNPARGS(proto, 0),
972 icmp6->icmp6_type, icmp6->icmp6_code);
974 len = snprintf(SNPARGS(proto, 0), "ICMPv6 ");
975 len += snprintf(SNPARGS(proto, len), "%s", src);
976 snprintf(SNPARGS(proto, len), " %s", dst);
980 len = snprintf(SNPARGS(proto, 0), "P:%d %s",
981 args->f_id.proto, src);
982 snprintf(SNPARGS(proto, len), " %s", dst);
987 if (IS_IP6_FLOW_ID(&(args->f_id))) {
988 if (offset & (IP6F_OFF_MASK | IP6F_MORE_FRAG))
989 snprintf(SNPARGS(fragment, 0),
990 " (frag %08x:%d@%d%s)",
992 ntohs(ip6->ip6_plen) - hlen,
993 ntohs(offset & IP6F_OFF_MASK) << 3,
994 (offset & IP6F_MORE_FRAG) ? "+" : "");
999 if (eh != NULL) { /* layer 2 packets are as on the wire */
1000 ip_off = ntohs(ip->ip_off);
1001 ip_len = ntohs(ip->ip_len);
1003 ip_off = ip->ip_off;
1004 ip_len = ip->ip_len;
1006 if (ip_off & (IP_MF | IP_OFFMASK))
1007 snprintf(SNPARGS(fragment, 0),
1008 " (frag %d:%d@%d%s)",
1009 ntohs(ip->ip_id), ip_len - (ip->ip_hl << 2),
1011 (ip_off & IP_MF) ? "+" : "");
1014 if (oif || m->m_pkthdr.rcvif)
1015 log(LOG_SECURITY | LOG_INFO,
1016 "ipfw: %d %s %s %s via %s%s\n",
1017 f ? f->rulenum : -1,
1018 action, proto, oif ? "out" : "in",
1019 oif ? oif->if_xname : m->m_pkthdr.rcvif->if_xname,
1022 log(LOG_SECURITY | LOG_INFO,
1023 "ipfw: %d %s %s [no if info]%s\n",
1024 f ? f->rulenum : -1,
1025 action, proto, fragment);
1027 log(LOG_SECURITY | LOG_NOTICE,
1028 "ipfw: limit %d reached on entry %d\n",
1029 limit_reached, f ? f->rulenum : -1);
1033 * IMPORTANT: the hash function for dynamic rules must be commutative
1034 * in source and destination (ip,port), because rules are bidirectional
1035 * and we want to find both in the same bucket.
1038 hash_packet(struct ipfw_flow_id *id)
1043 if (IS_IP6_FLOW_ID(id))
1044 i = hash_packet6(id);
1047 i = (id->dst_ip) ^ (id->src_ip) ^ (id->dst_port) ^ (id->src_port);
1048 i &= (curr_dyn_buckets - 1);
1053 * unlink a dynamic rule from a chain. prev is a pointer to
1054 * the previous one, q is a pointer to the rule to delete,
1055 * head is a pointer to the head of the queue.
1056 * Modifies q and potentially also head.
1058 #define UNLINK_DYN_RULE(prev, head, q) { \
1059 ipfw_dyn_rule *old_q = q; \
1061 /* remove a refcount to the parent */ \
1062 if (q->dyn_type == O_LIMIT) \
1063 q->parent->count--; \
1064 DEB(printf("ipfw: unlink entry 0x%08x %d -> 0x%08x %d, %d left\n",\
1065 (q->id.src_ip), (q->id.src_port), \
1066 (q->id.dst_ip), (q->id.dst_port), dyn_count-1 ); ) \
1068 prev->next = q = q->next; \
1070 head = q = q->next; \
1072 uma_zfree(ipfw_dyn_rule_zone, old_q); }
1074 #define TIME_LEQ(a,b) ((int)((a)-(b)) <= 0)
1077 * Remove dynamic rules pointing to "rule", or all of them if rule == NULL.
1079 * If keep_me == NULL, rules are deleted even if not expired,
1080 * otherwise only expired rules are removed.
1082 * The value of the second parameter is also used to point to identify
1083 * a rule we absolutely do not want to remove (e.g. because we are
1084 * holding a reference to it -- this is the case with O_LIMIT_PARENT
1085 * rules). The pointer is only used for comparison, so any non-null
1089 remove_dyn_rule(struct ip_fw *rule, ipfw_dyn_rule *keep_me)
1091 static u_int32_t last_remove = 0;
1093 #define FORCE (keep_me == NULL)
1095 ipfw_dyn_rule *prev, *q;
1096 int i, pass = 0, max_pass = 0;
1098 IPFW_DYN_LOCK_ASSERT();
1100 if (ipfw_dyn_v == NULL || dyn_count == 0)
1102 /* do not expire more than once per second, it is useless */
1103 if (!FORCE && last_remove == time_uptime)
1105 last_remove = time_uptime;
1108 * because O_LIMIT refer to parent rules, during the first pass only
1109 * remove child and mark any pending LIMIT_PARENT, and remove
1110 * them in a second pass.
1113 for (i = 0 ; i < curr_dyn_buckets ; i++) {
1114 for (prev=NULL, q = ipfw_dyn_v[i] ; q ; ) {
1116 * Logic can become complex here, so we split tests.
1120 if (rule != NULL && rule != q->rule)
1121 goto next; /* not the one we are looking for */
1122 if (q->dyn_type == O_LIMIT_PARENT) {
1124 * handle parent in the second pass,
1125 * record we need one.
1130 if (FORCE && q->count != 0 ) {
1131 /* XXX should not happen! */
1132 printf("ipfw: OUCH! cannot remove rule,"
1133 " count %d\n", q->count);
1137 !TIME_LEQ( q->expire, time_uptime ))
1140 if (q->dyn_type != O_LIMIT_PARENT || !q->count) {
1141 UNLINK_DYN_RULE(prev, ipfw_dyn_v[i], q);
1149 if (pass++ < max_pass)
1155 * lookup a dynamic rule.
1157 static ipfw_dyn_rule *
1158 lookup_dyn_rule_locked(struct ipfw_flow_id *pkt, int *match_direction,
1162 * stateful ipfw extensions.
1163 * Lookup into dynamic session queue
1165 #define MATCH_REVERSE 0
1166 #define MATCH_FORWARD 1
1167 #define MATCH_NONE 2
1168 #define MATCH_UNKNOWN 3
1169 int i, dir = MATCH_NONE;
1170 ipfw_dyn_rule *prev, *q=NULL;
1172 IPFW_DYN_LOCK_ASSERT();
1174 if (ipfw_dyn_v == NULL)
1175 goto done; /* not found */
1176 i = hash_packet( pkt );
1177 for (prev=NULL, q = ipfw_dyn_v[i] ; q != NULL ; ) {
1178 if (q->dyn_type == O_LIMIT_PARENT && q->count)
1180 if (TIME_LEQ( q->expire, time_uptime)) { /* expire entry */
1181 UNLINK_DYN_RULE(prev, ipfw_dyn_v[i], q);
1184 if (pkt->proto == q->id.proto &&
1185 q->dyn_type != O_LIMIT_PARENT) {
1186 if (IS_IP6_FLOW_ID(pkt)) {
1187 if (IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
1188 &(q->id.src_ip6)) &&
1189 IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
1190 &(q->id.dst_ip6)) &&
1191 pkt->src_port == q->id.src_port &&
1192 pkt->dst_port == q->id.dst_port ) {
1193 dir = MATCH_FORWARD;
1196 if (IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
1197 &(q->id.dst_ip6)) &&
1198 IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
1199 &(q->id.src_ip6)) &&
1200 pkt->src_port == q->id.dst_port &&
1201 pkt->dst_port == q->id.src_port ) {
1202 dir = MATCH_REVERSE;
1206 if (pkt->src_ip == q->id.src_ip &&
1207 pkt->dst_ip == q->id.dst_ip &&
1208 pkt->src_port == q->id.src_port &&
1209 pkt->dst_port == q->id.dst_port ) {
1210 dir = MATCH_FORWARD;
1213 if (pkt->src_ip == q->id.dst_ip &&
1214 pkt->dst_ip == q->id.src_ip &&
1215 pkt->src_port == q->id.dst_port &&
1216 pkt->dst_port == q->id.src_port ) {
1217 dir = MATCH_REVERSE;
1227 goto done; /* q = NULL, not found */
1229 if ( prev != NULL) { /* found and not in front */
1230 prev->next = q->next;
1231 q->next = ipfw_dyn_v[i];
1234 if (pkt->proto == IPPROTO_TCP) { /* update state according to flags */
1235 u_char flags = pkt->flags & (TH_FIN|TH_SYN|TH_RST);
1237 #define BOTH_SYN (TH_SYN | (TH_SYN << 8))
1238 #define BOTH_FIN (TH_FIN | (TH_FIN << 8))
1239 q->state |= (dir == MATCH_FORWARD ) ? flags : (flags << 8);
1241 case TH_SYN: /* opening */
1242 q->expire = time_uptime + dyn_syn_lifetime;
1245 case BOTH_SYN: /* move to established */
1246 case BOTH_SYN | TH_FIN : /* one side tries to close */
1247 case BOTH_SYN | (TH_FIN << 8) :
1249 #define _SEQ_GE(a,b) ((int)(a) - (int)(b) >= 0)
1250 u_int32_t ack = ntohl(tcp->th_ack);
1251 if (dir == MATCH_FORWARD) {
1252 if (q->ack_fwd == 0 || _SEQ_GE(ack, q->ack_fwd))
1254 else { /* ignore out-of-sequence */
1258 if (q->ack_rev == 0 || _SEQ_GE(ack, q->ack_rev))
1260 else { /* ignore out-of-sequence */
1265 q->expire = time_uptime + dyn_ack_lifetime;
1268 case BOTH_SYN | BOTH_FIN: /* both sides closed */
1269 if (dyn_fin_lifetime >= dyn_keepalive_period)
1270 dyn_fin_lifetime = dyn_keepalive_period - 1;
1271 q->expire = time_uptime + dyn_fin_lifetime;
1277 * reset or some invalid combination, but can also
1278 * occur if we use keep-state the wrong way.
1280 if ( (q->state & ((TH_RST << 8)|TH_RST)) == 0)
1281 printf("invalid state: 0x%x\n", q->state);
1283 if (dyn_rst_lifetime >= dyn_keepalive_period)
1284 dyn_rst_lifetime = dyn_keepalive_period - 1;
1285 q->expire = time_uptime + dyn_rst_lifetime;
1288 } else if (pkt->proto == IPPROTO_UDP) {
1289 q->expire = time_uptime + dyn_udp_lifetime;
1291 /* other protocols */
1292 q->expire = time_uptime + dyn_short_lifetime;
1295 if (match_direction)
1296 *match_direction = dir;
1300 static ipfw_dyn_rule *
1301 lookup_dyn_rule(struct ipfw_flow_id *pkt, int *match_direction,
1307 q = lookup_dyn_rule_locked(pkt, match_direction, tcp);
1310 /* NB: return table locked when q is not NULL */
1315 realloc_dynamic_table(void)
1317 IPFW_DYN_LOCK_ASSERT();
1320 * Try reallocation, make sure we have a power of 2 and do
1321 * not allow more than 64k entries. In case of overflow,
1325 if (dyn_buckets > 65536)
1327 if ((dyn_buckets & (dyn_buckets-1)) != 0) { /* not a power of 2 */
1328 dyn_buckets = curr_dyn_buckets; /* reset */
1331 curr_dyn_buckets = dyn_buckets;
1332 if (ipfw_dyn_v != NULL)
1333 free(ipfw_dyn_v, M_IPFW);
1335 ipfw_dyn_v = malloc(curr_dyn_buckets * sizeof(ipfw_dyn_rule *),
1336 M_IPFW, M_NOWAIT | M_ZERO);
1337 if (ipfw_dyn_v != NULL || curr_dyn_buckets <= 2)
1339 curr_dyn_buckets /= 2;
1344 * Install state of type 'type' for a dynamic session.
1345 * The hash table contains two type of rules:
1346 * - regular rules (O_KEEP_STATE)
1347 * - rules for sessions with limited number of sess per user
1348 * (O_LIMIT). When they are created, the parent is
1349 * increased by 1, and decreased on delete. In this case,
1350 * the third parameter is the parent rule and not the chain.
1351 * - "parent" rules for the above (O_LIMIT_PARENT).
1353 static ipfw_dyn_rule *
1354 add_dyn_rule(struct ipfw_flow_id *id, u_int8_t dyn_type, struct ip_fw *rule)
1359 IPFW_DYN_LOCK_ASSERT();
1361 if (ipfw_dyn_v == NULL ||
1362 (dyn_count == 0 && dyn_buckets != curr_dyn_buckets)) {
1363 realloc_dynamic_table();
1364 if (ipfw_dyn_v == NULL)
1365 return NULL; /* failed ! */
1367 i = hash_packet(id);
1369 r = uma_zalloc(ipfw_dyn_rule_zone, M_NOWAIT | M_ZERO);
1371 printf ("ipfw: sorry cannot allocate state\n");
1375 /* increase refcount on parent, and set pointer */
1376 if (dyn_type == O_LIMIT) {
1377 ipfw_dyn_rule *parent = (ipfw_dyn_rule *)rule;
1378 if ( parent->dyn_type != O_LIMIT_PARENT)
1379 panic("invalid parent");
1382 rule = parent->rule;
1386 r->expire = time_uptime + dyn_syn_lifetime;
1388 r->dyn_type = dyn_type;
1389 r->pcnt = r->bcnt = 0;
1393 r->next = ipfw_dyn_v[i];
1396 DEB(printf("ipfw: add dyn entry ty %d 0x%08x %d -> 0x%08x %d, total %d\n",
1398 (r->id.src_ip), (r->id.src_port),
1399 (r->id.dst_ip), (r->id.dst_port),
1405 * lookup dynamic parent rule using pkt and rule as search keys.
1406 * If the lookup fails, then install one.
1408 static ipfw_dyn_rule *
1409 lookup_dyn_parent(struct ipfw_flow_id *pkt, struct ip_fw *rule)
1414 IPFW_DYN_LOCK_ASSERT();
1417 int is_v6 = IS_IP6_FLOW_ID(pkt);
1418 i = hash_packet( pkt );
1419 for (q = ipfw_dyn_v[i] ; q != NULL ; q=q->next)
1420 if (q->dyn_type == O_LIMIT_PARENT &&
1422 pkt->proto == q->id.proto &&
1423 pkt->src_port == q->id.src_port &&
1424 pkt->dst_port == q->id.dst_port &&
1427 IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
1428 &(q->id.src_ip6)) &&
1429 IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
1430 &(q->id.dst_ip6))) ||
1432 pkt->src_ip == q->id.src_ip &&
1433 pkt->dst_ip == q->id.dst_ip)
1436 q->expire = time_uptime + dyn_short_lifetime;
1437 DEB(printf("ipfw: lookup_dyn_parent found 0x%p\n",q);)
1441 return add_dyn_rule(pkt, O_LIMIT_PARENT, rule);
1445 * Install dynamic state for rule type cmd->o.opcode
1447 * Returns 1 (failure) if state is not installed because of errors or because
1448 * session limitations are enforced.
1451 install_state(struct ip_fw *rule, ipfw_insn_limit *cmd,
1452 struct ip_fw_args *args, uint32_t tablearg)
1454 static int last_log;
1457 char src[48], dst[48];
1463 printf("ipfw: %s: type %d 0x%08x %u -> 0x%08x %u\n",
1464 __func__, cmd->o.opcode,
1465 (args->f_id.src_ip), (args->f_id.src_port),
1466 (args->f_id.dst_ip), (args->f_id.dst_port));
1471 q = lookup_dyn_rule_locked(&args->f_id, NULL, NULL);
1473 if (q != NULL) { /* should never occur */
1474 if (last_log != time_uptime) {
1475 last_log = time_uptime;
1476 printf("ipfw: %s: entry already present, done\n",
1483 if (dyn_count >= dyn_max)
1484 /* Run out of slots, try to remove any expired rule. */
1485 remove_dyn_rule(NULL, (ipfw_dyn_rule *)1);
1487 if (dyn_count >= dyn_max) {
1488 if (last_log != time_uptime) {
1489 last_log = time_uptime;
1490 printf("ipfw: %s: Too many dynamic rules\n", __func__);
1493 return (1); /* cannot install, notify caller */
1496 switch (cmd->o.opcode) {
1497 case O_KEEP_STATE: /* bidir rule */
1498 add_dyn_rule(&args->f_id, O_KEEP_STATE, rule);
1501 case O_LIMIT: { /* limit number of sessions */
1502 struct ipfw_flow_id id;
1503 ipfw_dyn_rule *parent;
1504 uint32_t conn_limit;
1505 uint16_t limit_mask = cmd->limit_mask;
1507 conn_limit = (cmd->conn_limit == IP_FW_TABLEARG) ?
1508 tablearg : cmd->conn_limit;
1511 if (cmd->conn_limit == IP_FW_TABLEARG)
1512 printf("ipfw: %s: O_LIMIT rule, conn_limit: %u "
1513 "(tablearg)\n", __func__, conn_limit);
1515 printf("ipfw: %s: O_LIMIT rule, conn_limit: %u\n",
1516 __func__, conn_limit);
1519 id.dst_ip = id.src_ip = id.dst_port = id.src_port = 0;
1520 id.proto = args->f_id.proto;
1521 id.addr_type = args->f_id.addr_type;
1523 if (IS_IP6_FLOW_ID (&(args->f_id))) {
1524 if (limit_mask & DYN_SRC_ADDR)
1525 id.src_ip6 = args->f_id.src_ip6;
1526 if (limit_mask & DYN_DST_ADDR)
1527 id.dst_ip6 = args->f_id.dst_ip6;
1529 if (limit_mask & DYN_SRC_ADDR)
1530 id.src_ip = args->f_id.src_ip;
1531 if (limit_mask & DYN_DST_ADDR)
1532 id.dst_ip = args->f_id.dst_ip;
1534 if (limit_mask & DYN_SRC_PORT)
1535 id.src_port = args->f_id.src_port;
1536 if (limit_mask & DYN_DST_PORT)
1537 id.dst_port = args->f_id.dst_port;
1538 if ((parent = lookup_dyn_parent(&id, rule)) == NULL) {
1539 printf("ipfw: %s: add parent failed\n", __func__);
1544 if (parent->count >= conn_limit) {
1545 /* See if we can remove some expired rule. */
1546 remove_dyn_rule(rule, parent);
1547 if (parent->count >= conn_limit) {
1548 if (fw_verbose && last_log != time_uptime) {
1549 last_log = time_uptime;
1552 * XXX IPv6 flows are not
1555 if (IS_IP6_FLOW_ID(&(args->f_id))) {
1556 char ip6buf[INET6_ADDRSTRLEN];
1557 snprintf(src, sizeof(src),
1558 "[%s]", ip6_sprintf(ip6buf,
1559 &args->f_id.src_ip6));
1560 snprintf(dst, sizeof(dst),
1561 "[%s]", ip6_sprintf(ip6buf,
1562 &args->f_id.dst_ip6));
1567 htonl(args->f_id.src_ip);
1568 inet_ntoa_r(da, src);
1570 htonl(args->f_id.dst_ip);
1571 inet_ntoa_r(da, dst);
1573 log(LOG_SECURITY | LOG_DEBUG,
1574 "ipfw: %d %s %s:%u -> %s:%u, %s\n",
1575 parent->rule->rulenum,
1577 src, (args->f_id.src_port),
1578 dst, (args->f_id.dst_port),
1579 "too many entries");
1585 add_dyn_rule(&args->f_id, O_LIMIT, (struct ip_fw *)parent);
1589 printf("ipfw: %s: unknown dynamic rule type %u\n",
1590 __func__, cmd->o.opcode);
1595 /* XXX just set lifetime */
1596 lookup_dyn_rule_locked(&args->f_id, NULL, NULL);
1603 * Generate a TCP packet, containing either a RST or a keepalive.
1604 * When flags & TH_RST, we are sending a RST packet, because of a
1605 * "reset" action matched the packet.
1606 * Otherwise we are sending a keepalive, and flags & TH_
1607 * The 'replyto' mbuf is the mbuf being replied to, if any, and is required
1608 * so that MAC can label the reply appropriately.
1610 static struct mbuf *
1611 send_pkt(struct mbuf *replyto, struct ipfw_flow_id *id, u_int32_t seq,
1612 u_int32_t ack, int flags)
1618 MGETHDR(m, M_DONTWAIT, MT_DATA);
1621 m->m_pkthdr.rcvif = (struct ifnet *)0;
1624 if (replyto != NULL)
1625 mac_netinet_firewall_reply(replyto, m);
1627 mac_netinet_firewall_send(m);
1629 (void)replyto; /* don't warn about unused arg */
1632 m->m_pkthdr.len = m->m_len = sizeof(struct ip) + sizeof(struct tcphdr);
1633 m->m_data += max_linkhdr;
1635 ip = mtod(m, struct ip *);
1636 bzero(ip, m->m_len);
1637 tcp = (struct tcphdr *)(ip + 1); /* no IP options */
1638 ip->ip_p = IPPROTO_TCP;
1641 * Assume we are sending a RST (or a keepalive in the reverse
1642 * direction), swap src and destination addresses and ports.
1644 ip->ip_src.s_addr = htonl(id->dst_ip);
1645 ip->ip_dst.s_addr = htonl(id->src_ip);
1646 tcp->th_sport = htons(id->dst_port);
1647 tcp->th_dport = htons(id->src_port);
1648 if (flags & TH_RST) { /* we are sending a RST */
1649 if (flags & TH_ACK) {
1650 tcp->th_seq = htonl(ack);
1651 tcp->th_ack = htonl(0);
1652 tcp->th_flags = TH_RST;
1656 tcp->th_seq = htonl(0);
1657 tcp->th_ack = htonl(seq);
1658 tcp->th_flags = TH_RST | TH_ACK;
1662 * We are sending a keepalive. flags & TH_SYN determines
1663 * the direction, forward if set, reverse if clear.
1664 * NOTE: seq and ack are always assumed to be correct
1665 * as set by the caller. This may be confusing...
1667 if (flags & TH_SYN) {
1669 * we have to rewrite the correct addresses!
1671 ip->ip_dst.s_addr = htonl(id->dst_ip);
1672 ip->ip_src.s_addr = htonl(id->src_ip);
1673 tcp->th_dport = htons(id->dst_port);
1674 tcp->th_sport = htons(id->src_port);
1676 tcp->th_seq = htonl(seq);
1677 tcp->th_ack = htonl(ack);
1678 tcp->th_flags = TH_ACK;
1681 * set ip_len to the payload size so we can compute
1682 * the tcp checksum on the pseudoheader
1683 * XXX check this, could save a couple of words ?
1685 ip->ip_len = htons(sizeof(struct tcphdr));
1686 tcp->th_sum = in_cksum(m, m->m_pkthdr.len);
1688 * now fill fields left out earlier
1690 ip->ip_ttl = ip_defttl;
1691 ip->ip_len = m->m_pkthdr.len;
1692 m->m_flags |= M_SKIP_FIREWALL;
1697 * sends a reject message, consuming the mbuf passed as an argument.
1700 send_reject(struct ip_fw_args *args, int code, int ip_len, struct ip *ip)
1704 /* XXX When ip is not guaranteed to be at mtod() we will
1705 * need to account for this */
1706 * The mbuf will however be thrown away so we can adjust it.
1707 * Remember we did an m_pullup on it already so we
1708 * can make some assumptions about contiguousness.
1711 m_adj(m, args->L3offset);
1713 if (code != ICMP_REJECT_RST) { /* Send an ICMP unreach */
1714 /* We need the IP header in host order for icmp_error(). */
1715 if (args->eh != NULL) {
1716 ip->ip_len = ntohs(ip->ip_len);
1717 ip->ip_off = ntohs(ip->ip_off);
1719 icmp_error(args->m, ICMP_UNREACH, code, 0L, 0);
1720 } else if (args->f_id.proto == IPPROTO_TCP) {
1721 struct tcphdr *const tcp =
1722 L3HDR(struct tcphdr, mtod(args->m, struct ip *));
1723 if ( (tcp->th_flags & TH_RST) == 0) {
1725 m = send_pkt(args->m, &(args->f_id),
1726 ntohl(tcp->th_seq), ntohl(tcp->th_ack),
1727 tcp->th_flags | TH_RST);
1729 ip_output(m, NULL, NULL, 0, NULL, NULL);
1739 * Given an ip_fw *, lookup_next_rule will return a pointer
1740 * to the next rule, which can be either the jump
1741 * target (for skipto instructions) or the next one in the list (in
1742 * all other cases including a missing jump target).
1743 * The result is also written in the "next_rule" field of the rule.
1744 * Backward jumps are not allowed, so start looking from the next
1747 * This never returns NULL -- in case we do not have an exact match,
1748 * the next rule is returned. When the ruleset is changed,
1749 * pointers are flushed so we are always correct.
1752 static struct ip_fw *
1753 lookup_next_rule(struct ip_fw *me)
1755 struct ip_fw *rule = NULL;
1758 /* look for action, in case it is a skipto */
1759 cmd = ACTION_PTR(me);
1760 if (cmd->opcode == O_LOG)
1762 if (cmd->opcode == O_ALTQ)
1764 if (cmd->opcode == O_TAG)
1766 if ( cmd->opcode == O_SKIPTO )
1767 for (rule = me->next; rule ; rule = rule->next)
1768 if (rule->rulenum >= cmd->arg1)
1770 if (rule == NULL) /* failure or not a skipto */
1772 me->next_rule = rule;
1777 add_table_entry(struct ip_fw_chain *ch, uint16_t tbl, in_addr_t addr,
1778 uint8_t mlen, uint32_t value)
1780 struct radix_node_head *rnh;
1781 struct table_entry *ent;
1783 if (tbl >= IPFW_TABLES_MAX)
1785 rnh = ch->tables[tbl];
1786 ent = malloc(sizeof(*ent), M_IPFW_TBL, M_NOWAIT | M_ZERO);
1790 ent->addr.sin_len = ent->mask.sin_len = 8;
1791 ent->mask.sin_addr.s_addr = htonl(mlen ? ~((1 << (32 - mlen)) - 1) : 0);
1792 ent->addr.sin_addr.s_addr = addr & ent->mask.sin_addr.s_addr;
1793 IPFW_WLOCK(&layer3_chain);
1794 if (rnh->rnh_addaddr(&ent->addr, &ent->mask, rnh, (void *)ent) ==
1796 IPFW_WUNLOCK(&layer3_chain);
1797 free(ent, M_IPFW_TBL);
1800 IPFW_WUNLOCK(&layer3_chain);
1805 del_table_entry(struct ip_fw_chain *ch, uint16_t tbl, in_addr_t addr,
1808 struct radix_node_head *rnh;
1809 struct table_entry *ent;
1810 struct sockaddr_in sa, mask;
1812 if (tbl >= IPFW_TABLES_MAX)
1814 rnh = ch->tables[tbl];
1815 sa.sin_len = mask.sin_len = 8;
1816 mask.sin_addr.s_addr = htonl(mlen ? ~((1 << (32 - mlen)) - 1) : 0);
1817 sa.sin_addr.s_addr = addr & mask.sin_addr.s_addr;
1819 ent = (struct table_entry *)rnh->rnh_deladdr(&sa, &mask, rnh);
1825 free(ent, M_IPFW_TBL);
1830 flush_table_entry(struct radix_node *rn, void *arg)
1832 struct radix_node_head * const rnh = arg;
1833 struct table_entry *ent;
1835 ent = (struct table_entry *)
1836 rnh->rnh_deladdr(rn->rn_key, rn->rn_mask, rnh);
1838 free(ent, M_IPFW_TBL);
1843 flush_table(struct ip_fw_chain *ch, uint16_t tbl)
1845 struct radix_node_head *rnh;
1847 IPFW_WLOCK_ASSERT(ch);
1849 if (tbl >= IPFW_TABLES_MAX)
1851 rnh = ch->tables[tbl];
1852 KASSERT(rnh != NULL, ("NULL IPFW table"));
1853 rnh->rnh_walktree(rnh, flush_table_entry, rnh);
1858 flush_tables(struct ip_fw_chain *ch)
1862 IPFW_WLOCK_ASSERT(ch);
1864 for (tbl = 0; tbl < IPFW_TABLES_MAX; tbl++)
1865 flush_table(ch, tbl);
1869 init_tables(struct ip_fw_chain *ch)
1874 for (i = 0; i < IPFW_TABLES_MAX; i++) {
1875 if (!rn_inithead((void **)&ch->tables[i], 32)) {
1876 for (j = 0; j < i; j++) {
1877 (void) flush_table(ch, j);
1886 lookup_table(struct ip_fw_chain *ch, uint16_t tbl, in_addr_t addr,
1889 struct radix_node_head *rnh;
1890 struct table_entry *ent;
1891 struct sockaddr_in sa;
1893 if (tbl >= IPFW_TABLES_MAX)
1895 rnh = ch->tables[tbl];
1897 sa.sin_addr.s_addr = addr;
1898 ent = (struct table_entry *)(rnh->rnh_lookup(&sa, NULL, rnh));
1907 count_table_entry(struct radix_node *rn, void *arg)
1909 u_int32_t * const cnt = arg;
1916 count_table(struct ip_fw_chain *ch, uint32_t tbl, uint32_t *cnt)
1918 struct radix_node_head *rnh;
1920 if (tbl >= IPFW_TABLES_MAX)
1922 rnh = ch->tables[tbl];
1924 rnh->rnh_walktree(rnh, count_table_entry, cnt);
1929 dump_table_entry(struct radix_node *rn, void *arg)
1931 struct table_entry * const n = (struct table_entry *)rn;
1932 ipfw_table * const tbl = arg;
1933 ipfw_table_entry *ent;
1935 if (tbl->cnt == tbl->size)
1937 ent = &tbl->ent[tbl->cnt];
1938 ent->tbl = tbl->tbl;
1939 if (in_nullhost(n->mask.sin_addr))
1942 ent->masklen = 33 - ffs(ntohl(n->mask.sin_addr.s_addr));
1943 ent->addr = n->addr.sin_addr.s_addr;
1944 ent->value = n->value;
1950 dump_table(struct ip_fw_chain *ch, ipfw_table *tbl)
1952 struct radix_node_head *rnh;
1954 if (tbl->tbl >= IPFW_TABLES_MAX)
1956 rnh = ch->tables[tbl->tbl];
1958 rnh->rnh_walktree(rnh, dump_table_entry, tbl);
1963 fill_ugid_cache(struct inpcb *inp, struct ip_fw_ugid *ugp)
1967 if (inp->inp_socket != NULL) {
1968 cr = inp->inp_socket->so_cred;
1969 ugp->fw_prid = jailed(cr) ?
1970 cr->cr_prison->pr_id : -1;
1971 ugp->fw_uid = cr->cr_uid;
1972 ugp->fw_ngroups = cr->cr_ngroups;
1973 bcopy(cr->cr_groups, ugp->fw_groups,
1974 sizeof(ugp->fw_groups));
1979 check_uidgid(ipfw_insn_u32 *insn, int proto, struct ifnet *oif,
1980 struct in_addr dst_ip, u_int16_t dst_port, struct in_addr src_ip,
1981 u_int16_t src_port, struct ip_fw_ugid *ugp, int *lookup,
1984 struct inpcbinfo *pi;
1991 * Check to see if the UDP or TCP stack supplied us with
1992 * the PCB. If so, rather then holding a lock and looking
1993 * up the PCB, we can use the one that was supplied.
1995 if (inp && *lookup == 0) {
1996 INP_LOCK_ASSERT(inp);
1997 if (inp->inp_socket != NULL) {
1998 fill_ugid_cache(inp, ugp);
2003 * If we have already been here and the packet has no
2004 * PCB entry associated with it, then we can safely
2005 * assume that this is a no match.
2009 if (proto == IPPROTO_TCP) {
2012 } else if (proto == IPPROTO_UDP) {
2013 wildcard = INPLOOKUP_WILDCARD;
2021 in_pcblookup_hash(pi,
2022 dst_ip, htons(dst_port),
2023 src_ip, htons(src_port),
2025 in_pcblookup_hash(pi,
2026 src_ip, htons(src_port),
2027 dst_ip, htons(dst_port),
2031 if (pcb->inp_socket != NULL) {
2032 fill_ugid_cache(pcb, ugp);
2037 INP_INFO_RUNLOCK(pi);
2040 * If the lookup did not yield any results, there
2041 * is no sense in coming back and trying again. So
2042 * we can set lookup to -1 and ensure that we wont
2043 * bother the pcb system again.
2049 if (insn->o.opcode == O_UID)
2050 match = (ugp->fw_uid == (uid_t)insn->d[0]);
2051 else if (insn->o.opcode == O_GID) {
2052 for (gp = ugp->fw_groups;
2053 gp < &ugp->fw_groups[ugp->fw_ngroups]; gp++)
2054 if (*gp == (gid_t)insn->d[0]) {
2058 } else if (insn->o.opcode == O_JAIL)
2059 match = (ugp->fw_prid == (int)insn->d[0]);
2063 #ifdef IPFIREWALL_NAT
2064 static eventhandler_tag ifaddr_event_tag;
2067 ifaddr_change(void *arg __unused, struct ifnet *ifp)
2069 struct cfg_nat *ptr;
2072 IPFW_WLOCK(&layer3_chain);
2073 /* Check every nat entry... */
2074 LIST_FOREACH(ptr, &layer3_chain.nat, _next) {
2075 /* ...using nic 'ifp->if_xname' as dynamic alias address. */
2076 if (strncmp(ptr->if_name, ifp->if_xname, IF_NAMESIZE) == 0) {
2077 mtx_lock(&ifp->if_addr_mtx);
2078 TAILQ_FOREACH(ifa, &ifp->if_addrlist, ifa_list) {
2079 if (ifa->ifa_addr == NULL)
2081 if (ifa->ifa_addr->sa_family != AF_INET)
2083 ptr->ip = ((struct sockaddr_in *)
2084 (ifa->ifa_addr))->sin_addr;
2085 LibAliasSetAddress(ptr->lib, ptr->ip);
2087 mtx_unlock(&ifp->if_addr_mtx);
2090 IPFW_WUNLOCK(&layer3_chain);
2094 flush_nat_ptrs(const int i)
2098 IPFW_WLOCK_ASSERT(&layer3_chain);
2099 for (rule = layer3_chain.rules; rule; rule = rule->next) {
2100 ipfw_insn_nat *cmd = (ipfw_insn_nat *)ACTION_PTR(rule);
2101 if (cmd->o.opcode != O_NAT)
2103 if (cmd->nat != NULL && cmd->nat->id == i)
2108 static struct cfg_nat *
2109 lookup_nat(const int i)
2111 struct cfg_nat *ptr;
2113 LIST_FOREACH(ptr, &layer3_chain.nat, _next)
2119 #define HOOK_NAT(b, p) do { \
2120 IPFW_WLOCK_ASSERT(&layer3_chain); \
2121 LIST_INSERT_HEAD(b, p, _next); \
2124 #define UNHOOK_NAT(p) do { \
2125 IPFW_WLOCK_ASSERT(&layer3_chain); \
2126 LIST_REMOVE(p, _next); \
2129 #define HOOK_REDIR(b, p) do { \
2130 LIST_INSERT_HEAD(b, p, _next); \
2133 #define HOOK_SPOOL(b, p) do { \
2134 LIST_INSERT_HEAD(b, p, _next); \
2138 del_redir_spool_cfg(struct cfg_nat *n, struct redir_chain *head)
2140 struct cfg_redir *r, *tmp_r;
2141 struct cfg_spool *s, *tmp_s;
2144 LIST_FOREACH_SAFE(r, head, _next, tmp_r) {
2145 num = 1; /* Number of alias_link to delete. */
2152 /* Delete all libalias redirect entry. */
2153 for (i = 0; i < num; i++)
2154 LibAliasRedirectDelete(n->lib, r->alink[i]);
2155 /* Del spool cfg if any. */
2156 LIST_FOREACH_SAFE(s, &r->spool_chain, _next, tmp_s) {
2157 LIST_REMOVE(s, _next);
2160 free(r->alink, M_IPFW);
2161 LIST_REMOVE(r, _next);
2165 printf("unknown redirect mode: %u\n", r->mode);
2166 /* XXX - panic?!?!? */
2173 add_redir_spool_cfg(char *buf, struct cfg_nat *ptr)
2175 struct cfg_redir *r, *ser_r;
2176 struct cfg_spool *s, *ser_s;
2180 for (cnt = 0, off = 0; cnt < ptr->redir_cnt; cnt++) {
2181 ser_r = (struct cfg_redir *)&buf[off];
2182 r = malloc(SOF_REDIR, M_IPFW, M_WAITOK | M_ZERO);
2183 memcpy(r, ser_r, SOF_REDIR);
2184 LIST_INIT(&r->spool_chain);
2186 r->alink = malloc(sizeof(struct alias_link *) * r->pport_cnt,
2187 M_IPFW, M_WAITOK | M_ZERO);
2190 r->alink[0] = LibAliasRedirectAddr(ptr->lib, r->laddr,
2194 for (i = 0 ; i < r->pport_cnt; i++) {
2195 /* If remotePort is all ports, set it to 0. */
2196 u_short remotePortCopy = r->rport + i;
2197 if (r->rport_cnt == 1 && r->rport == 0)
2199 r->alink[i] = LibAliasRedirectPort(ptr->lib,
2200 r->laddr, htons(r->lport + i), r->raddr,
2201 htons(remotePortCopy), r->paddr,
2202 htons(r->pport + i), r->proto);
2203 if (r->alink[i] == NULL) {
2210 r->alink[0] = LibAliasRedirectProto(ptr->lib ,r->laddr,
2211 r->raddr, r->paddr, r->proto);
2214 printf("unknown redirect mode: %u\n", r->mode);
2217 if (r->alink[0] == NULL) {
2218 panic_err = "LibAliasRedirect* returned NULL";
2220 } else /* LSNAT handling. */
2221 for (i = 0; i < r->spool_cnt; i++) {
2222 ser_s = (struct cfg_spool *)&buf[off];
2223 s = malloc(SOF_REDIR, M_IPFW,
2225 memcpy(s, ser_s, SOF_SPOOL);
2226 LibAliasAddServer(ptr->lib, r->alink[0],
2227 s->addr, htons(s->port));
2229 /* Hook spool entry. */
2230 HOOK_SPOOL(&r->spool_chain, s);
2232 /* And finally hook this redir entry. */
2233 HOOK_REDIR(&ptr->redir_chain, r);
2237 /* something really bad happened: panic! */
2238 panic("%s\n", panic_err);
2243 * The main check routine for the firewall.
2245 * All arguments are in args so we can modify them and return them
2246 * back to the caller.
2250 * args->m (in/out) The packet; we set to NULL when/if we nuke it.
2251 * Starts with the IP header.
2252 * args->eh (in) Mac header if present, or NULL for layer3 packet.
2253 * args->L3offset Number of bytes bypassed if we came from L2.
2254 * e.g. often sizeof(eh) ** NOTYET **
2255 * args->oif Outgoing interface, or NULL if packet is incoming.
2256 * The incoming interface is in the mbuf. (in)
2257 * args->divert_rule (in/out)
2258 * Skip up to the first rule past this rule number;
2259 * upon return, non-zero port number for divert or tee.
2261 * args->rule Pointer to the last matching rule (in/out)
2262 * args->next_hop Socket we are forwarding to (out).
2263 * args->f_id Addresses grabbed from the packet (out)
2264 * args->cookie a cookie depending on rule action
2268 * IP_FW_PASS the packet must be accepted
2269 * IP_FW_DENY the packet must be dropped
2270 * IP_FW_DIVERT divert packet, port in m_tag
2271 * IP_FW_TEE tee packet, port in m_tag
2272 * IP_FW_DUMMYNET to dummynet, pipe in args->cookie
2273 * IP_FW_NETGRAPH into netgraph, cookie args->cookie
2277 ipfw_chk(struct ip_fw_args *args)
2280 * Local variables holding state during the processing of a packet:
2282 * IMPORTANT NOTE: to speed up the processing of rules, there
2283 * are some assumption on the values of the variables, which
2284 * are documented here. Should you change them, please check
2285 * the implementation of the various instructions to make sure
2286 * that they still work.
2288 * args->eh The MAC header. It is non-null for a layer2
2289 * packet, it is NULL for a layer-3 packet.
2291 * args->L3offset Offset in the packet to the L3 (IP or equiv.) header.
2293 * m | args->m Pointer to the mbuf, as received from the caller.
2294 * It may change if ipfw_chk() does an m_pullup, or if it
2295 * consumes the packet because it calls send_reject().
2296 * XXX This has to change, so that ipfw_chk() never modifies
2297 * or consumes the buffer.
2298 * ip is the beginning of the ip(4 or 6) header.
2299 * Calculated by adding the L3offset to the start of data.
2300 * (Until we start using L3offset, the packet is
2301 * supposed to start with the ip header).
2303 struct mbuf *m = args->m;
2304 struct ip *ip = mtod(m, struct ip *);
2307 * For rules which contain uid/gid or jail constraints, cache
2308 * a copy of the users credentials after the pcb lookup has been
2309 * executed. This will speed up the processing of rules with
2310 * these types of constraints, as well as decrease contention
2311 * on pcb related locks.
2313 struct ip_fw_ugid fw_ugid_cache;
2314 int ugid_lookup = 0;
2317 * divinput_flags If non-zero, set to the IP_FW_DIVERT_*_FLAG
2318 * associated with a packet input on a divert socket. This
2319 * will allow to distinguish traffic and its direction when
2320 * it originates from a divert socket.
2322 u_int divinput_flags = 0;
2325 * oif | args->oif If NULL, ipfw_chk has been called on the
2326 * inbound path (ether_input, ip_input).
2327 * If non-NULL, ipfw_chk has been called on the outbound path
2328 * (ether_output, ip_output).
2330 struct ifnet *oif = args->oif;
2332 struct ip_fw *f = NULL; /* matching rule */
2336 * hlen The length of the IP header.
2338 u_int hlen = 0; /* hlen >0 means we have an IP pkt */
2341 * offset The offset of a fragment. offset != 0 means that
2342 * we have a fragment at this offset of an IPv4 packet.
2343 * offset == 0 means that (if this is an IPv4 packet)
2344 * this is the first or only fragment.
2345 * For IPv6 offset == 0 means there is no Fragment Header.
2346 * If offset != 0 for IPv6 always use correct mask to
2347 * get the correct offset because we add IP6F_MORE_FRAG
2348 * to be able to dectect the first fragment which would
2349 * otherwise have offset = 0.
2354 * Local copies of addresses. They are only valid if we have
2357 * proto The protocol. Set to 0 for non-ip packets,
2358 * or to the protocol read from the packet otherwise.
2359 * proto != 0 means that we have an IPv4 packet.
2361 * src_port, dst_port port numbers, in HOST format. Only
2362 * valid for TCP and UDP packets.
2364 * src_ip, dst_ip ip addresses, in NETWORK format.
2365 * Only valid for IPv4 packets.
2368 u_int16_t src_port = 0, dst_port = 0; /* NOTE: host format */
2369 struct in_addr src_ip, dst_ip; /* NOTE: network format */
2372 u_int16_t etype = 0; /* Host order stored ether type */
2375 * dyn_dir = MATCH_UNKNOWN when rules unchecked,
2376 * MATCH_NONE when checked and not matched (q = NULL),
2377 * MATCH_FORWARD or MATCH_REVERSE otherwise (q != NULL)
2379 int dyn_dir = MATCH_UNKNOWN;
2380 ipfw_dyn_rule *q = NULL;
2381 struct ip_fw_chain *chain = &layer3_chain;
2385 * We store in ulp a pointer to the upper layer protocol header.
2386 * In the ipv4 case this is easy to determine from the header,
2387 * but for ipv6 we might have some additional headers in the middle.
2388 * ulp is NULL if not found.
2390 void *ulp = NULL; /* upper layer protocol pointer. */
2391 /* XXX ipv6 variables */
2393 u_int16_t ext_hd = 0; /* bits vector for extension header filtering */
2394 /* end of ipv6 variables */
2397 if (m->m_flags & M_SKIP_FIREWALL)
2398 return (IP_FW_PASS); /* accept */
2400 pktlen = m->m_pkthdr.len;
2401 proto = args->f_id.proto = 0; /* mark f_id invalid */
2402 /* XXX 0 is a valid proto: IP/IPv6 Hop-by-Hop Option */
2405 * PULLUP_TO(len, p, T) makes sure that len + sizeof(T) is contiguous,
2406 * then it sets p to point at the offset "len" in the mbuf. WARNING: the
2407 * pointer might become stale after other pullups (but we never use it
2410 #define PULLUP_TO(len, p, T) \
2412 int x = (len) + sizeof(T); \
2413 if ((m)->m_len < x) { \
2414 args->m = m = m_pullup(m, x); \
2416 goto pullup_failed; \
2418 p = (mtod(m, char *) + (len)); \
2422 * if we have an ether header,
2425 etype = ntohs(args->eh->ether_type);
2427 /* Identify IP packets and fill up variables. */
2428 if (pktlen >= sizeof(struct ip6_hdr) &&
2429 (args->eh == NULL || etype == ETHERTYPE_IPV6) && ip->ip_v == 6) {
2430 struct ip6_hdr *ip6 = (struct ip6_hdr *)ip;
2432 args->f_id.addr_type = 6;
2433 hlen = sizeof(struct ip6_hdr);
2434 proto = ip6->ip6_nxt;
2436 /* Search extension headers to find upper layer protocols */
2437 while (ulp == NULL) {
2439 case IPPROTO_ICMPV6:
2440 PULLUP_TO(hlen, ulp, struct icmp6_hdr);
2441 args->f_id.flags = ICMP6(ulp)->icmp6_type;
2445 PULLUP_TO(hlen, ulp, struct tcphdr);
2446 dst_port = TCP(ulp)->th_dport;
2447 src_port = TCP(ulp)->th_sport;
2448 args->f_id.flags = TCP(ulp)->th_flags;
2452 PULLUP_TO(hlen, ulp, struct sctphdr);
2453 src_port = SCTP(ulp)->src_port;
2454 dst_port = SCTP(ulp)->dest_port;
2458 PULLUP_TO(hlen, ulp, struct udphdr);
2459 dst_port = UDP(ulp)->uh_dport;
2460 src_port = UDP(ulp)->uh_sport;
2463 case IPPROTO_HOPOPTS: /* RFC 2460 */
2464 PULLUP_TO(hlen, ulp, struct ip6_hbh);
2465 ext_hd |= EXT_HOPOPTS;
2466 hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3;
2467 proto = ((struct ip6_hbh *)ulp)->ip6h_nxt;
2471 case IPPROTO_ROUTING: /* RFC 2460 */
2472 PULLUP_TO(hlen, ulp, struct ip6_rthdr);
2473 switch (((struct ip6_rthdr *)ulp)->ip6r_type) {
2475 ext_hd |= EXT_RTHDR0;
2478 ext_hd |= EXT_RTHDR2;
2481 printf("IPFW2: IPV6 - Unknown Routing "
2482 "Header type(%d)\n",
2483 ((struct ip6_rthdr *)ulp)->ip6r_type);
2484 if (fw_deny_unknown_exthdrs)
2485 return (IP_FW_DENY);
2488 ext_hd |= EXT_ROUTING;
2489 hlen += (((struct ip6_rthdr *)ulp)->ip6r_len + 1) << 3;
2490 proto = ((struct ip6_rthdr *)ulp)->ip6r_nxt;
2494 case IPPROTO_FRAGMENT: /* RFC 2460 */
2495 PULLUP_TO(hlen, ulp, struct ip6_frag);
2496 ext_hd |= EXT_FRAGMENT;
2497 hlen += sizeof (struct ip6_frag);
2498 proto = ((struct ip6_frag *)ulp)->ip6f_nxt;
2499 offset = ((struct ip6_frag *)ulp)->ip6f_offlg &
2501 /* Add IP6F_MORE_FRAG for offset of first
2502 * fragment to be != 0. */
2503 offset |= ((struct ip6_frag *)ulp)->ip6f_offlg &
2506 printf("IPFW2: IPV6 - Invalid Fragment "
2508 if (fw_deny_unknown_exthdrs)
2509 return (IP_FW_DENY);
2512 args->f_id.frag_id6 =
2513 ntohl(((struct ip6_frag *)ulp)->ip6f_ident);
2517 case IPPROTO_DSTOPTS: /* RFC 2460 */
2518 PULLUP_TO(hlen, ulp, struct ip6_hbh);
2519 ext_hd |= EXT_DSTOPTS;
2520 hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3;
2521 proto = ((struct ip6_hbh *)ulp)->ip6h_nxt;
2525 case IPPROTO_AH: /* RFC 2402 */
2526 PULLUP_TO(hlen, ulp, struct ip6_ext);
2528 hlen += (((struct ip6_ext *)ulp)->ip6e_len + 2) << 2;
2529 proto = ((struct ip6_ext *)ulp)->ip6e_nxt;
2533 case IPPROTO_ESP: /* RFC 2406 */
2534 PULLUP_TO(hlen, ulp, uint32_t); /* SPI, Seq# */
2535 /* Anything past Seq# is variable length and
2536 * data past this ext. header is encrypted. */
2540 case IPPROTO_NONE: /* RFC 2460 */
2542 * Packet ends here, and IPv6 header has
2543 * already been pulled up. If ip6e_len!=0
2544 * then octets must be ignored.
2546 ulp = ip; /* non-NULL to get out of loop. */
2549 case IPPROTO_OSPFIGP:
2550 /* XXX OSPF header check? */
2551 PULLUP_TO(hlen, ulp, struct ip6_ext);
2555 /* XXX PIM header check? */
2556 PULLUP_TO(hlen, ulp, struct pim);
2560 PULLUP_TO(hlen, ulp, struct carp_header);
2561 if (((struct carp_header *)ulp)->carp_version !=
2563 return (IP_FW_DENY);
2564 if (((struct carp_header *)ulp)->carp_type !=
2566 return (IP_FW_DENY);
2569 case IPPROTO_IPV6: /* RFC 2893 */
2570 PULLUP_TO(hlen, ulp, struct ip6_hdr);
2573 case IPPROTO_IPV4: /* RFC 2893 */
2574 PULLUP_TO(hlen, ulp, struct ip);
2578 printf("IPFW2: IPV6 - Unknown Extension "
2579 "Header(%d), ext_hd=%x\n", proto, ext_hd);
2580 if (fw_deny_unknown_exthdrs)
2581 return (IP_FW_DENY);
2582 PULLUP_TO(hlen, ulp, struct ip6_ext);
2586 ip = mtod(m, struct ip *);
2587 ip6 = (struct ip6_hdr *)ip;
2588 args->f_id.src_ip6 = ip6->ip6_src;
2589 args->f_id.dst_ip6 = ip6->ip6_dst;
2590 args->f_id.src_ip = 0;
2591 args->f_id.dst_ip = 0;
2592 args->f_id.flow_id6 = ntohl(ip6->ip6_flow);
2593 } else if (pktlen >= sizeof(struct ip) &&
2594 (args->eh == NULL || etype == ETHERTYPE_IP) && ip->ip_v == 4) {
2596 hlen = ip->ip_hl << 2;
2597 args->f_id.addr_type = 4;
2600 * Collect parameters into local variables for faster matching.
2603 src_ip = ip->ip_src;
2604 dst_ip = ip->ip_dst;
2605 if (args->eh != NULL) { /* layer 2 packets are as on the wire */
2606 offset = ntohs(ip->ip_off) & IP_OFFMASK;
2607 ip_len = ntohs(ip->ip_len);
2609 offset = ip->ip_off & IP_OFFMASK;
2610 ip_len = ip->ip_len;
2612 pktlen = ip_len < pktlen ? ip_len : pktlen;
2617 PULLUP_TO(hlen, ulp, struct tcphdr);
2618 dst_port = TCP(ulp)->th_dport;
2619 src_port = TCP(ulp)->th_sport;
2620 args->f_id.flags = TCP(ulp)->th_flags;
2624 PULLUP_TO(hlen, ulp, struct udphdr);
2625 dst_port = UDP(ulp)->uh_dport;
2626 src_port = UDP(ulp)->uh_sport;
2630 PULLUP_TO(hlen, ulp, struct icmphdr);
2631 args->f_id.flags = ICMP(ulp)->icmp_type;
2639 ip = mtod(m, struct ip *);
2640 args->f_id.src_ip = ntohl(src_ip.s_addr);
2641 args->f_id.dst_ip = ntohl(dst_ip.s_addr);
2644 if (proto) { /* we may have port numbers, store them */
2645 args->f_id.proto = proto;
2646 args->f_id.src_port = src_port = ntohs(src_port);
2647 args->f_id.dst_port = dst_port = ntohs(dst_port);
2651 mtag = m_tag_find(m, PACKET_TAG_DIVERT, NULL);
2654 * Packet has already been tagged. Look for the next rule
2655 * to restart processing.
2657 * If fw_one_pass != 0 then just accept it.
2658 * XXX should not happen here, but optimized out in
2662 IPFW_RUNLOCK(chain);
2663 return (IP_FW_PASS);
2666 f = args->rule->next_rule;
2668 f = lookup_next_rule(args->rule);
2671 * Find the starting rule. It can be either the first
2672 * one, or the one after divert_rule if asked so.
2674 int skipto = mtag ? divert_cookie(mtag) : 0;
2677 if (args->eh == NULL && skipto != 0) {
2678 if (skipto >= IPFW_DEFAULT_RULE) {
2679 IPFW_RUNLOCK(chain);
2680 return (IP_FW_DENY); /* invalid */
2682 while (f && f->rulenum <= skipto)
2684 if (f == NULL) { /* drop packet */
2685 IPFW_RUNLOCK(chain);
2686 return (IP_FW_DENY);
2690 /* reset divert rule to avoid confusion later */
2692 divinput_flags = divert_info(mtag) &
2693 (IP_FW_DIVERT_OUTPUT_FLAG | IP_FW_DIVERT_LOOPBACK_FLAG);
2694 m_tag_delete(m, mtag);
2698 * Now scan the rules, and parse microinstructions for each rule.
2700 for (; f; f = f->next) {
2702 uint32_t tablearg = 0;
2703 int l, cmdlen, skip_or; /* skip rest of OR block */
2706 if (set_disable & (1 << f->set) )
2710 for (l = f->cmd_len, cmd = f->cmd ; l > 0 ;
2711 l -= cmdlen, cmd += cmdlen) {
2715 * check_body is a jump target used when we find a
2716 * CHECK_STATE, and need to jump to the body of
2721 cmdlen = F_LEN(cmd);
2723 * An OR block (insn_1 || .. || insn_n) has the
2724 * F_OR bit set in all but the last instruction.
2725 * The first match will set "skip_or", and cause
2726 * the following instructions to be skipped until
2727 * past the one with the F_OR bit clear.
2729 if (skip_or) { /* skip this instruction */
2730 if ((cmd->len & F_OR) == 0)
2731 skip_or = 0; /* next one is good */
2734 match = 0; /* set to 1 if we succeed */
2736 switch (cmd->opcode) {
2738 * The first set of opcodes compares the packet's
2739 * fields with some pattern, setting 'match' if a
2740 * match is found. At the end of the loop there is
2741 * logic to deal with F_NOT and F_OR flags associated
2749 printf("ipfw: opcode %d unimplemented\n",
2757 * We only check offset == 0 && proto != 0,
2758 * as this ensures that we have a
2759 * packet with the ports info.
2763 if (is_ipv6) /* XXX to be fixed later */
2765 if (proto == IPPROTO_TCP ||
2766 proto == IPPROTO_UDP)
2767 match = check_uidgid(
2768 (ipfw_insn_u32 *)cmd,
2771 src_ip, src_port, &fw_ugid_cache,
2772 &ugid_lookup, args->inp);
2776 match = iface_match(m->m_pkthdr.rcvif,
2777 (ipfw_insn_if *)cmd);
2781 match = iface_match(oif, (ipfw_insn_if *)cmd);
2785 match = iface_match(oif ? oif :
2786 m->m_pkthdr.rcvif, (ipfw_insn_if *)cmd);
2790 if (args->eh != NULL) { /* have MAC header */
2791 u_int32_t *want = (u_int32_t *)
2792 ((ipfw_insn_mac *)cmd)->addr;
2793 u_int32_t *mask = (u_int32_t *)
2794 ((ipfw_insn_mac *)cmd)->mask;
2795 u_int32_t *hdr = (u_int32_t *)args->eh;
2798 ( want[0] == (hdr[0] & mask[0]) &&
2799 want[1] == (hdr[1] & mask[1]) &&
2800 want[2] == (hdr[2] & mask[2]) );
2805 if (args->eh != NULL) {
2807 ((ipfw_insn_u16 *)cmd)->ports;
2810 for (i = cmdlen - 1; !match && i>0;
2812 match = (etype >= p[0] &&
2818 match = (offset != 0);
2821 case O_IN: /* "out" is "not in" */
2822 match = (oif == NULL);
2826 match = (args->eh != NULL);
2830 match = (cmd->arg1 & 1 && divinput_flags &
2831 IP_FW_DIVERT_LOOPBACK_FLAG) ||
2832 (cmd->arg1 & 2 && divinput_flags &
2833 IP_FW_DIVERT_OUTPUT_FLAG);
2838 * We do not allow an arg of 0 so the
2839 * check of "proto" only suffices.
2841 match = (proto == cmd->arg1);
2846 (((ipfw_insn_ip *)cmd)->addr.s_addr ==
2850 case O_IP_SRC_LOOKUP:
2851 case O_IP_DST_LOOKUP:
2854 (cmd->opcode == O_IP_DST_LOOKUP) ?
2855 dst_ip.s_addr : src_ip.s_addr;
2858 match = lookup_table(chain, cmd->arg1, a,
2862 if (cmdlen == F_INSN_SIZE(ipfw_insn_u32))
2864 ((ipfw_insn_u32 *)cmd)->d[0] == v;
2874 (cmd->opcode == O_IP_DST_MASK) ?
2875 dst_ip.s_addr : src_ip.s_addr;
2876 uint32_t *p = ((ipfw_insn_u32 *)cmd)->d;
2879 for (; !match && i>0; i-= 2, p+= 2)
2880 match = (p[0] == (a & p[1]));
2888 INADDR_TO_IFP(src_ip, tif);
2889 match = (tif != NULL);
2896 u_int32_t *d = (u_int32_t *)(cmd+1);
2898 cmd->opcode == O_IP_DST_SET ?
2904 addr -= d[0]; /* subtract base */
2905 match = (addr < cmd->arg1) &&
2906 ( d[ 1 + (addr>>5)] &
2907 (1<<(addr & 0x1f)) );
2913 (((ipfw_insn_ip *)cmd)->addr.s_addr ==
2921 INADDR_TO_IFP(dst_ip, tif);
2922 match = (tif != NULL);
2929 * offset == 0 && proto != 0 is enough
2930 * to guarantee that we have a
2931 * packet with port info.
2933 if ((proto==IPPROTO_UDP || proto==IPPROTO_TCP)
2936 (cmd->opcode == O_IP_SRCPORT) ?
2937 src_port : dst_port ;
2939 ((ipfw_insn_u16 *)cmd)->ports;
2942 for (i = cmdlen - 1; !match && i>0;
2944 match = (x>=p[0] && x<=p[1]);
2949 match = (offset == 0 && proto==IPPROTO_ICMP &&
2950 icmptype_match(ICMP(ulp), (ipfw_insn_u32 *)cmd) );
2955 match = is_ipv6 && offset == 0 &&
2956 proto==IPPROTO_ICMPV6 &&
2958 ICMP6(ulp)->icmp6_type,
2959 (ipfw_insn_u32 *)cmd);
2965 ipopts_match(ip, cmd) );
2970 cmd->arg1 == ip->ip_v);
2976 if (is_ipv4) { /* only for IP packets */
2981 if (cmd->opcode == O_IPLEN)
2983 else if (cmd->opcode == O_IPTTL)
2985 else /* must be IPID */
2986 x = ntohs(ip->ip_id);
2988 match = (cmd->arg1 == x);
2991 /* otherwise we have ranges */
2992 p = ((ipfw_insn_u16 *)cmd)->ports;
2994 for (; !match && i>0; i--, p += 2)
2995 match = (x >= p[0] && x <= p[1]);
2999 case O_IPPRECEDENCE:
3001 (cmd->arg1 == (ip->ip_tos & 0xe0)) );
3006 flags_match(cmd, ip->ip_tos));
3010 if (proto == IPPROTO_TCP && offset == 0) {
3018 ((ip->ip_hl + tcp->th_off) << 2);
3020 match = (cmd->arg1 == x);
3023 /* otherwise we have ranges */
3024 p = ((ipfw_insn_u16 *)cmd)->ports;
3026 for (; !match && i>0; i--, p += 2)
3027 match = (x >= p[0] && x <= p[1]);
3032 match = (proto == IPPROTO_TCP && offset == 0 &&
3033 flags_match(cmd, TCP(ulp)->th_flags));
3037 match = (proto == IPPROTO_TCP && offset == 0 &&
3038 tcpopts_match(TCP(ulp), cmd));
3042 match = (proto == IPPROTO_TCP && offset == 0 &&
3043 ((ipfw_insn_u32 *)cmd)->d[0] ==
3048 match = (proto == IPPROTO_TCP && offset == 0 &&
3049 ((ipfw_insn_u32 *)cmd)->d[0] ==
3054 match = (proto == IPPROTO_TCP && offset == 0 &&
3055 cmd->arg1 == TCP(ulp)->th_win);
3059 /* reject packets which have SYN only */
3060 /* XXX should i also check for TH_ACK ? */
3061 match = (proto == IPPROTO_TCP && offset == 0 &&
3062 (TCP(ulp)->th_flags &
3063 (TH_RST | TH_ACK | TH_SYN)) != TH_SYN);
3068 ipfw_insn_altq *altq = (ipfw_insn_altq *)cmd;
3071 at = pf_find_mtag(m);
3072 if (at != NULL && at->qid != 0)
3074 at = pf_get_mtag(m);
3077 * Let the packet fall back to the
3082 at->qid = altq->qid;
3093 ipfw_log(f, hlen, args, m,
3094 oif, offset, tablearg, ip);
3099 match = (random()<((ipfw_insn_u32 *)cmd)->d[0]);
3103 /* Outgoing packets automatically pass/match */
3104 match = ((oif != NULL) ||
3105 (m->m_pkthdr.rcvif == NULL) ||
3109 verify_path6(&(args->f_id.src_ip6),
3110 m->m_pkthdr.rcvif) :
3112 verify_path(src_ip, m->m_pkthdr.rcvif)));
3116 /* Outgoing packets automatically pass/match */
3117 match = (hlen > 0 && ((oif != NULL) ||
3120 verify_path6(&(args->f_id.src_ip6),
3123 verify_path(src_ip, NULL)));
3127 /* Outgoing packets automatically pass/match */
3128 if (oif == NULL && hlen > 0 &&
3129 ( (is_ipv4 && in_localaddr(src_ip))
3132 in6_localaddr(&(args->f_id.src_ip6)))
3137 is_ipv6 ? verify_path6(
3138 &(args->f_id.src_ip6),
3139 m->m_pkthdr.rcvif) :
3149 match = (m_tag_find(m,
3150 PACKET_TAG_IPSEC_IN_DONE, NULL) != NULL);
3152 /* otherwise no match */
3158 IN6_ARE_ADDR_EQUAL(&args->f_id.src_ip6,
3159 &((ipfw_insn_ip6 *)cmd)->addr6);
3164 IN6_ARE_ADDR_EQUAL(&args->f_id.dst_ip6,
3165 &((ipfw_insn_ip6 *)cmd)->addr6);
3167 case O_IP6_SRC_MASK:
3168 case O_IP6_DST_MASK:
3172 struct in6_addr *d =
3173 &((ipfw_insn_ip6 *)cmd)->addr6;
3175 for (; !match && i > 0; d += 2,
3176 i -= F_INSN_SIZE(struct in6_addr)
3182 APPLY_MASK(&p, &d[1]);
3184 IN6_ARE_ADDR_EQUAL(&d[0],
3191 match= is_ipv6 && search_ip6_addr_net(&args->f_id.src_ip6);
3195 match= is_ipv6 && search_ip6_addr_net(&args->f_id.dst_ip6);
3200 flow6id_match(args->f_id.flow_id6,
3201 (ipfw_insn_u32 *) cmd);
3206 (ext_hd & ((ipfw_insn *) cmd)->arg1);
3219 uint32_t tag = (cmd->arg1 == IP_FW_TABLEARG) ?
3220 tablearg : cmd->arg1;
3222 /* Packet is already tagged with this tag? */
3223 mtag = m_tag_locate(m, MTAG_IPFW, tag, NULL);
3225 /* We have `untag' action when F_NOT flag is
3226 * present. And we must remove this mtag from
3227 * mbuf and reset `match' to zero (`match' will
3228 * be inversed later).
3229 * Otherwise we should allocate new mtag and
3230 * push it into mbuf.
3232 if (cmd->len & F_NOT) { /* `untag' action */
3234 m_tag_delete(m, mtag);
3235 } else if (mtag == NULL) {
3236 if ((mtag = m_tag_alloc(MTAG_IPFW,
3237 tag, 0, M_NOWAIT)) != NULL)
3238 m_tag_prepend(m, mtag);
3240 match = (cmd->len & F_NOT) ? 0: 1;
3245 uint32_t tag = (cmd->arg1 == IP_FW_TABLEARG) ?
3246 tablearg : cmd->arg1;
3249 match = m_tag_locate(m, MTAG_IPFW,
3254 /* we have ranges */
3255 for (mtag = m_tag_first(m);
3256 mtag != NULL && !match;
3257 mtag = m_tag_next(m, mtag)) {
3261 if (mtag->m_tag_cookie != MTAG_IPFW)
3264 p = ((ipfw_insn_u16 *)cmd)->ports;
3266 for(; !match && i > 0; i--, p += 2)
3268 mtag->m_tag_id >= p[0] &&
3269 mtag->m_tag_id <= p[1];
3275 * The second set of opcodes represents 'actions',
3276 * i.e. the terminal part of a rule once the packet
3277 * matches all previous patterns.
3278 * Typically there is only one action for each rule,
3279 * and the opcode is stored at the end of the rule
3280 * (but there are exceptions -- see below).
3282 * In general, here we set retval and terminate the
3283 * outer loop (would be a 'break 3' in some language,
3284 * but we need to do a 'goto done').
3287 * O_COUNT and O_SKIPTO actions:
3288 * instead of terminating, we jump to the next rule
3289 * ('goto next_rule', equivalent to a 'break 2'),
3290 * or to the SKIPTO target ('goto again' after
3291 * having set f, cmd and l), respectively.
3293 * O_TAG, O_LOG and O_ALTQ action parameters:
3294 * perform some action and set match = 1;
3296 * O_LIMIT and O_KEEP_STATE: these opcodes are
3297 * not real 'actions', and are stored right
3298 * before the 'action' part of the rule.
3299 * These opcodes try to install an entry in the
3300 * state tables; if successful, we continue with
3301 * the next opcode (match=1; break;), otherwise
3302 * the packet * must be dropped
3303 * ('goto done' after setting retval);
3305 * O_PROBE_STATE and O_CHECK_STATE: these opcodes
3306 * cause a lookup of the state table, and a jump
3307 * to the 'action' part of the parent rule
3308 * ('goto check_body') if an entry is found, or
3309 * (CHECK_STATE only) a jump to the next rule if
3310 * the entry is not found ('goto next_rule').
3311 * The result of the lookup is cached to make
3312 * further instances of these opcodes are
3317 if (install_state(f,
3318 (ipfw_insn_limit *)cmd, args, tablearg)) {
3319 retval = IP_FW_DENY;
3320 goto done; /* error/limit violation */
3328 * dynamic rules are checked at the first
3329 * keep-state or check-state occurrence,
3330 * with the result being stored in dyn_dir.
3331 * The compiler introduces a PROBE_STATE
3332 * instruction for us when we have a
3333 * KEEP_STATE (because PROBE_STATE needs
3336 if (dyn_dir == MATCH_UNKNOWN &&
3337 (q = lookup_dyn_rule(&args->f_id,
3338 &dyn_dir, proto == IPPROTO_TCP ?
3342 * Found dynamic entry, update stats
3343 * and jump to the 'action' part of
3349 cmd = ACTION_PTR(f);
3350 l = f->cmd_len - f->act_ofs;
3355 * Dynamic entry not found. If CHECK_STATE,
3356 * skip to next rule, if PROBE_STATE just
3357 * ignore and continue with next opcode.
3359 if (cmd->opcode == O_CHECK_STATE)
3365 retval = 0; /* accept */
3370 args->rule = f; /* report matching rule */
3371 if (cmd->arg1 == IP_FW_TABLEARG)
3372 args->cookie = tablearg;
3374 args->cookie = cmd->arg1;
3375 retval = IP_FW_DUMMYNET;
3380 struct divert_tag *dt;
3382 if (args->eh) /* not on layer 2 */
3384 mtag = m_tag_get(PACKET_TAG_DIVERT,
3385 sizeof(struct divert_tag),
3390 IPFW_RUNLOCK(chain);
3391 return (IP_FW_DENY);
3393 dt = (struct divert_tag *)(mtag+1);
3394 dt->cookie = f->rulenum;
3395 if (cmd->arg1 == IP_FW_TABLEARG)
3396 dt->info = tablearg;
3398 dt->info = cmd->arg1;
3399 m_tag_prepend(m, mtag);
3400 retval = (cmd->opcode == O_DIVERT) ?
3401 IP_FW_DIVERT : IP_FW_TEE;
3407 f->pcnt++; /* update stats */
3409 f->timestamp = time_uptime;
3410 if (cmd->opcode == O_COUNT)
3413 if (f->next_rule == NULL)
3414 lookup_next_rule(f);
3420 * Drop the packet and send a reject notice
3421 * if the packet is not ICMP (or is an ICMP
3422 * query), and it is not multicast/broadcast.
3424 if (hlen > 0 && is_ipv4 && offset == 0 &&
3425 (proto != IPPROTO_ICMP ||
3426 is_icmp_query(ICMP(ulp))) &&
3427 !(m->m_flags & (M_BCAST|M_MCAST)) &&
3428 !IN_MULTICAST(ntohl(dst_ip.s_addr))) {
3429 send_reject(args, cmd->arg1, ip_len, ip);
3435 if (hlen > 0 && is_ipv6 &&
3436 ((offset & IP6F_OFF_MASK) == 0) &&
3437 (proto != IPPROTO_ICMPV6 ||
3438 (is_icmp6_query(args->f_id.flags) == 1)) &&
3439 !(m->m_flags & (M_BCAST|M_MCAST)) &&
3440 !IN6_IS_ADDR_MULTICAST(&args->f_id.dst_ip6)) {
3442 args, cmd->arg1, hlen,
3443 (struct ip6_hdr *)ip);
3449 retval = IP_FW_DENY;
3452 case O_FORWARD_IP: {
3453 struct sockaddr_in *sa;
3454 sa = &(((ipfw_insn_sa *)cmd)->sa);
3455 if (args->eh) /* not valid on layer2 pkts */
3457 if (!q || dyn_dir == MATCH_FORWARD) {
3458 if (sa->sin_addr.s_addr == INADDR_ANY) {
3459 bcopy(sa, &args->hopstore,
3461 args->hopstore.sin_addr.s_addr =
3466 args->next_hop = sa;
3469 retval = IP_FW_PASS;
3475 args->rule = f; /* report matching rule */
3476 if (cmd->arg1 == IP_FW_TABLEARG)
3477 args->cookie = tablearg;
3479 args->cookie = cmd->arg1;
3480 retval = (cmd->opcode == O_NETGRAPH) ?
3481 IP_FW_NETGRAPH : IP_FW_NGTEE;
3484 #ifdef IPFIREWALL_NAT
3488 /* XXX - libalias duct tape */
3493 args->rule = f; /* Report matching rule. */
3495 t = ((ipfw_insn_nat *)cmd)->nat;
3497 t = lookup_nat(cmd->arg1);
3499 retval = IP_FW_DENY;
3502 ((ipfw_insn_nat *)cmd)->nat =
3505 if ((mcl = m_megapullup(m, m->m_pkthdr.len)) ==
3508 ip = mtod(mcl, struct ip *);
3509 if (args->eh == NULL) {
3510 ip->ip_len = htons(ip->ip_len);
3511 ip->ip_off = htons(ip->ip_off);
3515 * XXX - Libalias checksum offload 'duct tape':
3517 * locally generated packets have only
3518 * pseudo-header checksum calculated
3519 * and libalias will screw it[1], so
3520 * mark them for later fix. Moreover
3521 * there are cases when libalias
3522 * modify tcp packet data[2], mark it
3523 * for later fix too.
3525 * [1] libalias was never meant to run
3526 * in kernel, so it doesn't have any
3527 * knowledge about checksum
3528 * offloading, and it expects a packet
3529 * with a full internet
3530 * checksum. Unfortunately, packets
3531 * generated locally will have just the
3532 * pseudo header calculated, and when
3533 * libalias tries to adjust the
3534 * checksum it will actually screw it.
3536 * [2] when libalias modify tcp's data
3537 * content, full TCP checksum has to
3538 * be recomputed: the problem is that
3539 * libalias doesn't have any idea
3540 * about checksum offloading To
3541 * workaround this, we do not do
3542 * checksumming in LibAlias, but only
3543 * mark the packets in th_x2 field. If
3544 * we receive a marked packet, we
3545 * calculate correct checksum for it
3546 * aware of offloading. Why such a
3547 * terrible hack instead of
3548 * recalculating checksum for each
3549 * packet? Because the previous
3550 * checksum was not checked!
3551 * Recalculating checksums for EVERY
3552 * packet will hide ALL transmission
3553 * errors. Yes, marked packets still
3554 * suffer from this problem. But,
3555 * sigh, natd(8) has this problem,
3558 * TODO: -make libalias mbuf aware (so
3559 * it can handle delayed checksum and tso)
3562 if (mcl->m_pkthdr.rcvif == NULL &&
3563 mcl->m_pkthdr.csum_flags &
3567 c = mtod(mcl, char *);
3569 retval = LibAliasIn(t->lib, c,
3572 retval = LibAliasOut(t->lib, c,
3574 if (retval != PKT_ALIAS_OK) {
3575 /* XXX - should i add some logging? */
3579 retval = IP_FW_DENY;
3582 mcl->m_pkthdr.len = mcl->m_len =
3586 * XXX - libalias checksum offload
3587 * 'duct tape' (see above)
3590 if ((ip->ip_off & htons(IP_OFFMASK)) == 0 &&
3591 ip->ip_p == IPPROTO_TCP) {
3594 th = (struct tcphdr *)(ip + 1);
3604 ip->ip_len = ntohs(ip->ip_len);
3608 htons(ip->ip_p + ip->ip_len -
3614 th = (struct tcphdr *)(ip + 1);
3616 * Maybe it was set in
3621 mcl->m_pkthdr.csum_data =
3622 offsetof(struct tcphdr,
3626 uh = (struct udphdr *)(ip + 1);
3628 mcl->m_pkthdr.csum_data =
3629 offsetof(struct udphdr,
3634 * No hw checksum offloading: do it
3637 if ((mcl->m_pkthdr.csum_flags &
3638 CSUM_DELAY_DATA) == 0) {
3639 in_delayed_cksum(mcl);
3640 mcl->m_pkthdr.csum_flags &=
3643 ip->ip_len = htons(ip->ip_len);
3646 if (args->eh == NULL) {
3647 ip->ip_len = ntohs(ip->ip_len);
3648 ip->ip_off = ntohs(ip->ip_off);
3658 panic("-- unknown opcode %d\n", cmd->opcode);
3659 } /* end of switch() on opcodes */
3661 if (cmd->len & F_NOT)
3665 if (cmd->len & F_OR)
3668 if (!(cmd->len & F_OR)) /* not an OR block, */
3669 break; /* try next rule */
3672 } /* end of inner for, scan opcodes */
3674 next_rule:; /* try next rule */
3676 } /* end of outer for, scan rules */
3677 printf("ipfw: ouch!, skip past end of rules, denying packet\n");
3678 IPFW_RUNLOCK(chain);
3679 return (IP_FW_DENY);
3682 /* Update statistics */
3685 f->timestamp = time_uptime;
3686 IPFW_RUNLOCK(chain);
3691 printf("ipfw: pullup failed\n");
3692 return (IP_FW_DENY);
3696 * When a rule is added/deleted, clear the next_rule pointers in all rules.
3697 * These will be reconstructed on the fly as packets are matched.
3700 flush_rule_ptrs(struct ip_fw_chain *chain)
3704 IPFW_WLOCK_ASSERT(chain);
3706 for (rule = chain->rules; rule; rule = rule->next)
3707 rule->next_rule = NULL;
3711 * Add a new rule to the list. Copy the rule into a malloc'ed area, then
3712 * possibly create a rule number and add the rule to the list.
3713 * Update the rule_number in the input struct so the caller knows it as well.
3716 add_rule(struct ip_fw_chain *chain, struct ip_fw *input_rule)
3718 struct ip_fw *rule, *f, *prev;
3719 int l = RULESIZE(input_rule);
3721 if (chain->rules == NULL && input_rule->rulenum != IPFW_DEFAULT_RULE)
3724 rule = malloc(l, M_IPFW, M_NOWAIT | M_ZERO);
3728 bcopy(input_rule, rule, l);
3731 rule->next_rule = NULL;
3735 rule->timestamp = 0;
3739 if (chain->rules == NULL) { /* default rule */
3740 chain->rules = rule;
3745 * If rulenum is 0, find highest numbered rule before the
3746 * default rule, and add autoinc_step
3748 if (autoinc_step < 1)
3750 else if (autoinc_step > 1000)
3751 autoinc_step = 1000;
3752 if (rule->rulenum == 0) {
3754 * locate the highest numbered rule before default
3756 for (f = chain->rules; f; f = f->next) {
3757 if (f->rulenum == IPFW_DEFAULT_RULE)
3759 rule->rulenum = f->rulenum;
3761 if (rule->rulenum < IPFW_DEFAULT_RULE - autoinc_step)
3762 rule->rulenum += autoinc_step;
3763 input_rule->rulenum = rule->rulenum;
3767 * Now insert the new rule in the right place in the sorted list.
3769 for (prev = NULL, f = chain->rules; f; prev = f, f = f->next) {
3770 if (f->rulenum > rule->rulenum) { /* found the location */
3774 } else { /* head insert */
3775 rule->next = chain->rules;
3776 chain->rules = rule;
3781 flush_rule_ptrs(chain);
3785 IPFW_WUNLOCK(chain);
3786 DEB(printf("ipfw: installed rule %d, static count now %d\n",
3787 rule->rulenum, static_count);)
3792 * Remove a static rule (including derived * dynamic rules)
3793 * and place it on the ``reap list'' for later reclamation.
3794 * The caller is in charge of clearing rule pointers to avoid
3795 * dangling pointers.
3796 * @return a pointer to the next entry.
3797 * Arguments are not checked, so they better be correct.
3799 static struct ip_fw *
3800 remove_rule(struct ip_fw_chain *chain, struct ip_fw *rule,
3804 int l = RULESIZE(rule);
3806 IPFW_WLOCK_ASSERT(chain);
3810 remove_dyn_rule(rule, NULL /* force removal */);
3819 rule->next = chain->reap;
3826 * Reclaim storage associated with a list of rules. This is
3827 * typically the list created using remove_rule.
3830 reap_rules(struct ip_fw *head)
3834 while ((rule = head) != NULL) {
3836 if (DUMMYNET_LOADED)
3837 ip_dn_ruledel_ptr(rule);
3843 * Remove all rules from a chain (except rules in set RESVD_SET
3844 * unless kill_default = 1). The caller is responsible for
3845 * reclaiming storage for the rules left in chain->reap.
3848 free_chain(struct ip_fw_chain *chain, int kill_default)
3850 struct ip_fw *prev, *rule;
3852 IPFW_WLOCK_ASSERT(chain);
3854 flush_rule_ptrs(chain); /* more efficient to do outside the loop */
3855 for (prev = NULL, rule = chain->rules; rule ; )
3856 if (kill_default || rule->set != RESVD_SET)
3857 rule = remove_rule(chain, rule, prev);
3865 * Remove all rules with given number, and also do set manipulation.
3866 * Assumes chain != NULL && *chain != NULL.
3868 * The argument is an u_int32_t. The low 16 bit are the rule or set number,
3869 * the next 8 bits are the new set, the top 8 bits are the command:
3871 * 0 delete rules with given number
3872 * 1 delete rules with given set number
3873 * 2 move rules with given number to new set
3874 * 3 move rules with given set number to new set
3875 * 4 swap sets with given numbers
3876 * 5 delete rules with given number and with given set number
3879 del_entry(struct ip_fw_chain *chain, u_int32_t arg)
3881 struct ip_fw *prev = NULL, *rule;
3882 u_int16_t rulenum; /* rule or old_set */
3883 u_int8_t cmd, new_set;
3885 rulenum = arg & 0xffff;
3886 cmd = (arg >> 24) & 0xff;
3887 new_set = (arg >> 16) & 0xff;
3889 if (cmd > 5 || new_set > RESVD_SET)
3891 if (cmd == 0 || cmd == 2 || cmd == 5) {
3892 if (rulenum >= IPFW_DEFAULT_RULE)
3895 if (rulenum > RESVD_SET) /* old_set */
3900 rule = chain->rules;
3903 case 0: /* delete rules with given number */
3905 * locate first rule to delete
3907 for (; rule->rulenum < rulenum; prev = rule, rule = rule->next)
3909 if (rule->rulenum != rulenum) {
3910 IPFW_WUNLOCK(chain);
3915 * flush pointers outside the loop, then delete all matching
3916 * rules. prev remains the same throughout the cycle.
3918 flush_rule_ptrs(chain);
3919 while (rule->rulenum == rulenum)
3920 rule = remove_rule(chain, rule, prev);
3923 case 1: /* delete all rules with given set number */
3924 flush_rule_ptrs(chain);
3925 rule = chain->rules;
3926 while (rule->rulenum < IPFW_DEFAULT_RULE)
3927 if (rule->set == rulenum)
3928 rule = remove_rule(chain, rule, prev);
3935 case 2: /* move rules with given number to new set */
3936 rule = chain->rules;
3937 for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
3938 if (rule->rulenum == rulenum)
3939 rule->set = new_set;
3942 case 3: /* move rules with given set number to new set */
3943 for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
3944 if (rule->set == rulenum)
3945 rule->set = new_set;
3948 case 4: /* swap two sets */
3949 for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
3950 if (rule->set == rulenum)
3951 rule->set = new_set;
3952 else if (rule->set == new_set)
3953 rule->set = rulenum;
3955 case 5: /* delete rules with given number and with given set number.
3956 * rulenum - given rule number;
3957 * new_set - given set number.
3959 for (; rule->rulenum < rulenum; prev = rule, rule = rule->next)
3961 if (rule->rulenum != rulenum) {
3962 IPFW_WUNLOCK(chain);
3965 flush_rule_ptrs(chain);
3966 while (rule->rulenum == rulenum) {
3967 if (rule->set == new_set)
3968 rule = remove_rule(chain, rule, prev);
3976 * Look for rules to reclaim. We grab the list before
3977 * releasing the lock then reclaim them w/o the lock to
3978 * avoid a LOR with dummynet.
3982 IPFW_WUNLOCK(chain);
3989 * Clear counters for a specific rule.
3990 * The enclosing "table" is assumed locked.
3993 clear_counters(struct ip_fw *rule, int log_only)
3995 ipfw_insn_log *l = (ipfw_insn_log *)ACTION_PTR(rule);
3997 if (log_only == 0) {
3998 rule->bcnt = rule->pcnt = 0;
3999 rule->timestamp = 0;
4001 if (l->o.opcode == O_LOG)
4002 l->log_left = l->max_log;
4006 * Reset some or all counters on firewall rules.
4007 * The argument `arg' is an u_int32_t. The low 16 bit are the rule number,
4008 * the next 8 bits are the set number, the top 8 bits are the command:
4009 * 0 work with rules from all set's;
4010 * 1 work with rules only from specified set.
4011 * Specified rule number is zero if we want to clear all entries.
4012 * log_only is 1 if we only want to reset logs, zero otherwise.
4015 zero_entry(struct ip_fw_chain *chain, u_int32_t arg, int log_only)
4020 uint16_t rulenum = arg & 0xffff;
4021 uint8_t set = (arg >> 16) & 0xff;
4022 uint8_t cmd = (arg >> 24) & 0xff;
4026 if (cmd == 1 && set > RESVD_SET)
4032 for (rule = chain->rules; rule; rule = rule->next) {
4033 /* Skip rules from another set. */
4034 if (cmd == 1 && rule->set != set)
4036 clear_counters(rule, log_only);
4038 msg = log_only ? "ipfw: All logging counts reset.\n" :
4039 "ipfw: Accounting cleared.\n";
4043 * We can have multiple rules with the same number, so we
4044 * need to clear them all.
4046 for (rule = chain->rules; rule; rule = rule->next)
4047 if (rule->rulenum == rulenum) {
4048 while (rule && rule->rulenum == rulenum) {
4049 if (cmd == 0 || rule->set == set)
4050 clear_counters(rule, log_only);
4056 if (!cleared) { /* we did not find any matching rules */
4057 IPFW_WUNLOCK(chain);
4060 msg = log_only ? "ipfw: Entry %d logging count reset.\n" :
4061 "ipfw: Entry %d cleared.\n";
4063 IPFW_WUNLOCK(chain);
4066 log(LOG_SECURITY | LOG_NOTICE, msg, rulenum);
4071 * Check validity of the structure before insert.
4072 * Fortunately rules are simple, so this mostly need to check rule sizes.
4075 check_ipfw_struct(struct ip_fw *rule, int size)
4081 if (size < sizeof(*rule)) {
4082 printf("ipfw: rule too short\n");
4085 /* first, check for valid size */
4088 printf("ipfw: size mismatch (have %d want %d)\n", size, l);
4091 if (rule->act_ofs >= rule->cmd_len) {
4092 printf("ipfw: bogus action offset (%u > %u)\n",
4093 rule->act_ofs, rule->cmd_len - 1);
4097 * Now go for the individual checks. Very simple ones, basically only
4098 * instruction sizes.
4100 for (l = rule->cmd_len, cmd = rule->cmd ;
4101 l > 0 ; l -= cmdlen, cmd += cmdlen) {
4102 cmdlen = F_LEN(cmd);
4104 printf("ipfw: opcode %d size truncated\n",
4108 DEB(printf("ipfw: opcode %d\n", cmd->opcode);)
4109 switch (cmd->opcode) {
4121 case O_IPPRECEDENCE:
4139 if (cmdlen != F_INSN_SIZE(ipfw_insn))
4152 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32))
4157 if (cmdlen != F_INSN_SIZE(ipfw_insn_limit))
4162 if (cmdlen != F_INSN_SIZE(ipfw_insn_log))
4165 ((ipfw_insn_log *)cmd)->log_left =
4166 ((ipfw_insn_log *)cmd)->max_log;
4172 /* only odd command lengths */
4173 if ( !(cmdlen & 1) || cmdlen > 31)
4179 if (cmd->arg1 == 0 || cmd->arg1 > 256) {
4180 printf("ipfw: invalid set size %d\n",
4184 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
4189 case O_IP_SRC_LOOKUP:
4190 case O_IP_DST_LOOKUP:
4191 if (cmd->arg1 >= IPFW_TABLES_MAX) {
4192 printf("ipfw: invalid table number %d\n",
4196 if (cmdlen != F_INSN_SIZE(ipfw_insn) &&
4197 cmdlen != F_INSN_SIZE(ipfw_insn_u32))
4202 if (cmdlen != F_INSN_SIZE(ipfw_insn_mac))
4212 if (cmdlen < 1 || cmdlen > 31)
4218 case O_IP_DSTPORT: /* XXX artificial limit, 30 port pairs */
4219 if (cmdlen < 2 || cmdlen > 31)
4226 if (cmdlen != F_INSN_SIZE(ipfw_insn_if))
4231 if (cmdlen != F_INSN_SIZE(ipfw_insn_altq))
4237 if (cmdlen != F_INSN_SIZE(ipfw_insn))
4242 #ifdef IPFIREWALL_FORWARD
4243 if (cmdlen != F_INSN_SIZE(ipfw_insn_sa))
4252 if (ip_divert_ptr == NULL)
4258 if (!NG_IPFW_LOADED)
4263 #ifdef IPFIREWALL_NAT
4264 if (cmdlen != F_INSN_SIZE(ipfw_insn_nat))
4270 case O_FORWARD_MAC: /* XXX not implemented yet */
4281 if (cmdlen != F_INSN_SIZE(ipfw_insn))
4285 printf("ipfw: opcode %d, multiple actions"
4292 printf("ipfw: opcode %d, action must be"
4301 if (cmdlen != F_INSN_SIZE(struct in6_addr) +
4302 F_INSN_SIZE(ipfw_insn))
4307 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
4308 ((ipfw_insn_u32 *)cmd)->o.arg1)
4312 case O_IP6_SRC_MASK:
4313 case O_IP6_DST_MASK:
4314 if ( !(cmdlen & 1) || cmdlen > 127)
4318 if( cmdlen != F_INSN_SIZE( ipfw_insn_icmp6 ) )
4324 switch (cmd->opcode) {
4334 case O_IP6_SRC_MASK:
4335 case O_IP6_DST_MASK:
4337 printf("ipfw: no IPv6 support in kernel\n");
4338 return EPROTONOSUPPORT;
4341 printf("ipfw: opcode %d, unknown opcode\n",
4347 if (have_action == 0) {
4348 printf("ipfw: missing action\n");
4354 printf("ipfw: opcode %d size %d wrong\n",
4355 cmd->opcode, cmdlen);
4360 * Copy the static and dynamic rules to the supplied buffer
4361 * and return the amount of space actually used.
4364 ipfw_getrules(struct ip_fw_chain *chain, void *buf, size_t space)
4367 char *ep = bp + space;
4370 time_t boot_seconds;
4372 boot_seconds = boottime.tv_sec;
4373 /* XXX this can take a long time and locking will block packet flow */
4375 for (rule = chain->rules; rule ; rule = rule->next) {
4377 * Verify the entry fits in the buffer in case the
4378 * rules changed between calculating buffer space and
4379 * now. This would be better done using a generation
4380 * number but should suffice for now.
4386 * XXX HACK. Store the disable mask in the "next" pointer
4387 * in a wild attempt to keep the ABI the same.
4388 * Why do we do this on EVERY rule?
4390 bcopy(&set_disable, &(((struct ip_fw *)bp)->next_rule),
4391 sizeof(set_disable));
4392 if (((struct ip_fw *)bp)->timestamp)
4393 ((struct ip_fw *)bp)->timestamp += boot_seconds;
4397 IPFW_RUNLOCK(chain);
4399 ipfw_dyn_rule *p, *last = NULL;
4402 for (i = 0 ; i < curr_dyn_buckets; i++)
4403 for (p = ipfw_dyn_v[i] ; p != NULL; p = p->next) {
4404 if (bp + sizeof *p <= ep) {
4405 ipfw_dyn_rule *dst =
4406 (ipfw_dyn_rule *)bp;
4407 bcopy(p, dst, sizeof *p);
4408 bcopy(&(p->rule->rulenum), &(dst->rule),
4409 sizeof(p->rule->rulenum));
4411 * store set number into high word of
4412 * dst->rule pointer.
4414 bcopy(&(p->rule->set),
4415 (char *)&dst->rule +
4416 sizeof(p->rule->rulenum),
4417 sizeof(p->rule->set));
4419 * store a non-null value in "next".
4420 * The userland code will interpret a
4421 * NULL here as a marker
4422 * for the last dynamic rule.
4424 bcopy(&dst, &dst->next, sizeof(dst));
4427 TIME_LEQ(dst->expire, time_uptime) ?
4428 0 : dst->expire - time_uptime ;
4429 bp += sizeof(ipfw_dyn_rule);
4433 if (last != NULL) /* mark last dynamic rule */
4434 bzero(&last->next, sizeof(last));
4436 return (bp - (char *)buf);
4441 * {set|get}sockopt parser.
4444 ipfw_ctl(struct sockopt *sopt)
4446 #define RULE_MAXSIZE (256*sizeof(u_int32_t))
4449 struct ip_fw *buf, *rule;
4450 u_int32_t rulenum[2];
4452 error = priv_check(sopt->sopt_td, PRIV_NETINET_IPFW);
4457 * Disallow modifications in really-really secure mode, but still allow
4458 * the logging counters to be reset.
4460 if (sopt->sopt_name == IP_FW_ADD ||
4461 (sopt->sopt_dir == SOPT_SET && sopt->sopt_name != IP_FW_RESETLOG)) {
4462 error = securelevel_ge(sopt->sopt_td->td_ucred, 3);
4469 switch (sopt->sopt_name) {
4472 * pass up a copy of the current rules. Static rules
4473 * come first (the last of which has number IPFW_DEFAULT_RULE),
4474 * followed by a possibly empty list of dynamic rule.
4475 * The last dynamic rule has NULL in the "next" field.
4477 * Note that the calculated size is used to bound the
4478 * amount of data returned to the user. The rule set may
4479 * change between calculating the size and returning the
4480 * data in which case we'll just return what fits.
4482 size = static_len; /* size of static rules */
4483 if (ipfw_dyn_v) /* add size of dyn.rules */
4484 size += (dyn_count * sizeof(ipfw_dyn_rule));
4487 * XXX todo: if the user passes a short length just to know
4488 * how much room is needed, do not bother filling up the
4489 * buffer, just jump to the sooptcopyout.
4491 buf = malloc(size, M_TEMP, M_WAITOK);
4492 error = sooptcopyout(sopt, buf,
4493 ipfw_getrules(&layer3_chain, buf, size));
4499 * Normally we cannot release the lock on each iteration.
4500 * We could do it here only because we start from the head all
4501 * the times so there is no risk of missing some entries.
4502 * On the other hand, the risk is that we end up with
4503 * a very inconsistent ruleset, so better keep the lock
4504 * around the whole cycle.
4506 * XXX this code can be improved by resetting the head of
4507 * the list to point to the default rule, and then freeing
4508 * the old list without the need for a lock.
4511 IPFW_WLOCK(&layer3_chain);
4512 layer3_chain.reap = NULL;
4513 free_chain(&layer3_chain, 0 /* keep default rule */);
4514 rule = layer3_chain.reap;
4515 layer3_chain.reap = NULL;
4516 IPFW_WUNLOCK(&layer3_chain);
4522 rule = malloc(RULE_MAXSIZE, M_TEMP, M_WAITOK);
4523 error = sooptcopyin(sopt, rule, RULE_MAXSIZE,
4524 sizeof(struct ip_fw) );
4526 error = check_ipfw_struct(rule, sopt->sopt_valsize);
4528 error = add_rule(&layer3_chain, rule);
4529 size = RULESIZE(rule);
4530 if (!error && sopt->sopt_dir == SOPT_GET)
4531 error = sooptcopyout(sopt, rule, size);
4538 * IP_FW_DEL is used for deleting single rules or sets,
4539 * and (ab)used to atomically manipulate sets. Argument size
4540 * is used to distinguish between the two:
4542 * delete single rule or set of rules,
4543 * or reassign rules (or sets) to a different set.
4544 * 2*sizeof(u_int32_t)
4545 * atomic disable/enable sets.
4546 * first u_int32_t contains sets to be disabled,
4547 * second u_int32_t contains sets to be enabled.
4549 error = sooptcopyin(sopt, rulenum,
4550 2*sizeof(u_int32_t), sizeof(u_int32_t));
4553 size = sopt->sopt_valsize;
4554 if (size == sizeof(u_int32_t)) /* delete or reassign */
4555 error = del_entry(&layer3_chain, rulenum[0]);
4556 else if (size == 2*sizeof(u_int32_t)) /* set enable/disable */
4558 (set_disable | rulenum[0]) & ~rulenum[1] &
4559 ~(1<<RESVD_SET); /* set RESVD_SET always enabled */
4565 case IP_FW_RESETLOG: /* argument is an u_int_32, the rule number */
4567 if (sopt->sopt_val != 0) {
4568 error = sooptcopyin(sopt, rulenum,
4569 sizeof(u_int32_t), sizeof(u_int32_t));
4573 error = zero_entry(&layer3_chain, rulenum[0],
4574 sopt->sopt_name == IP_FW_RESETLOG);
4577 case IP_FW_TABLE_ADD:
4579 ipfw_table_entry ent;
4581 error = sooptcopyin(sopt, &ent,
4582 sizeof(ent), sizeof(ent));
4585 error = add_table_entry(&layer3_chain, ent.tbl,
4586 ent.addr, ent.masklen, ent.value);
4590 case IP_FW_TABLE_DEL:
4592 ipfw_table_entry ent;
4594 error = sooptcopyin(sopt, &ent,
4595 sizeof(ent), sizeof(ent));
4598 error = del_table_entry(&layer3_chain, ent.tbl,
4599 ent.addr, ent.masklen);
4603 case IP_FW_TABLE_FLUSH:
4607 error = sooptcopyin(sopt, &tbl,
4608 sizeof(tbl), sizeof(tbl));
4611 IPFW_WLOCK(&layer3_chain);
4612 error = flush_table(&layer3_chain, tbl);
4613 IPFW_WUNLOCK(&layer3_chain);
4617 case IP_FW_TABLE_GETSIZE:
4621 if ((error = sooptcopyin(sopt, &tbl, sizeof(tbl),
4624 IPFW_RLOCK(&layer3_chain);
4625 error = count_table(&layer3_chain, tbl, &cnt);
4626 IPFW_RUNLOCK(&layer3_chain);
4629 error = sooptcopyout(sopt, &cnt, sizeof(cnt));
4633 case IP_FW_TABLE_LIST:
4637 if (sopt->sopt_valsize < sizeof(*tbl)) {
4641 size = sopt->sopt_valsize;
4642 tbl = malloc(size, M_TEMP, M_WAITOK);
4643 error = sooptcopyin(sopt, tbl, size, sizeof(*tbl));
4648 tbl->size = (size - sizeof(*tbl)) /
4649 sizeof(ipfw_table_entry);
4650 IPFW_RLOCK(&layer3_chain);
4651 error = dump_table(&layer3_chain, tbl);
4652 IPFW_RUNLOCK(&layer3_chain);
4657 error = sooptcopyout(sopt, tbl, size);
4662 #ifdef IPFIREWALL_NAT
4665 struct cfg_nat *ptr, *ser_n;
4668 buf = malloc(NAT_BUF_LEN, M_IPFW, M_WAITOK | M_ZERO);
4669 error = sooptcopyin(sopt, buf, NAT_BUF_LEN,
4670 sizeof(struct cfg_nat));
4671 ser_n = (struct cfg_nat *)buf;
4674 * Find/create nat rule.
4676 IPFW_WLOCK(&layer3_chain);
4677 ptr = lookup_nat(ser_n->id);
4679 /* New rule: allocate and init new instance. */
4680 ptr = malloc(sizeof(struct cfg_nat),
4681 M_IPFW, M_NOWAIT | M_ZERO);
4683 IPFW_WUNLOCK(&layer3_chain);
4687 ptr->lib = LibAliasInit(NULL);
4688 if (ptr->lib == NULL) {
4689 IPFW_WUNLOCK(&layer3_chain);
4694 LIST_INIT(&ptr->redir_chain);
4696 /* Entry already present: temporarly unhook it. */
4698 flush_nat_ptrs(ser_n->id);
4700 IPFW_WUNLOCK(&layer3_chain);
4703 * Basic nat configuration.
4705 ptr->id = ser_n->id;
4707 * XXX - what if this rule doesn't nat any ip and just
4709 * do we set aliasaddress to 0.0.0.0?
4711 ptr->ip = ser_n->ip;
4712 ptr->redir_cnt = ser_n->redir_cnt;
4713 ptr->mode = ser_n->mode;
4714 LibAliasSetMode(ptr->lib, ser_n->mode, ser_n->mode);
4715 LibAliasSetAddress(ptr->lib, ptr->ip);
4716 memcpy(ptr->if_name, ser_n->if_name, IF_NAMESIZE);
4719 * Redir and LSNAT configuration.
4721 /* Delete old cfgs. */
4722 del_redir_spool_cfg(ptr, &ptr->redir_chain);
4723 /* Add new entries. */
4724 add_redir_spool_cfg(&buf[(sizeof(struct cfg_nat))], ptr);
4726 IPFW_WLOCK(&layer3_chain);
4727 HOOK_NAT(&layer3_chain.nat, ptr);
4728 IPFW_WUNLOCK(&layer3_chain);
4734 struct cfg_nat *ptr;
4737 error = sooptcopyin(sopt, &i, sizeof i, sizeof i);
4738 IPFW_WLOCK(&layer3_chain);
4739 ptr = lookup_nat(i);
4742 IPFW_WUNLOCK(&layer3_chain);
4747 IPFW_WUNLOCK(&layer3_chain);
4748 del_redir_spool_cfg(ptr, &ptr->redir_chain);
4749 LibAliasUninit(ptr->lib);
4754 case IP_FW_NAT_GET_CONFIG:
4758 struct cfg_redir *r;
4759 struct cfg_spool *s;
4763 off = sizeof(nat_cnt);
4765 data = malloc(NAT_BUF_LEN, M_IPFW, M_WAITOK | M_ZERO);
4766 IPFW_RLOCK(&layer3_chain);
4767 /* Serialize all the data. */
4768 LIST_FOREACH(n, &layer3_chain.nat, _next) {
4770 if (off + SOF_NAT < NAT_BUF_LEN) {
4771 bcopy(n, &data[off], SOF_NAT);
4773 LIST_FOREACH(r, &n->redir_chain, _next) {
4774 if (off + SOF_REDIR < NAT_BUF_LEN) {
4775 bcopy(r, &data[off],
4778 LIST_FOREACH(s, &r->spool_chain,
4780 if (off + SOF_SPOOL <
4796 bcopy(&nat_cnt, data, sizeof(nat_cnt));
4797 IPFW_RUNLOCK(&layer3_chain);
4798 error = sooptcopyout(sopt, data, NAT_BUF_LEN);
4802 IPFW_RUNLOCK(&layer3_chain);
4803 printf("serialized data buffer not big enough:"
4804 "please increase NAT_BUF_LEN\n");
4809 case IP_FW_NAT_GET_LOG:
4812 struct cfg_nat *ptr;
4813 int i, size, cnt, sof;
4816 sof = LIBALIAS_BUF_SIZE;
4819 IPFW_RLOCK(&layer3_chain);
4821 LIST_FOREACH(ptr, &layer3_chain.nat, _next) {
4822 if (ptr->lib->logDesc == NULL)
4825 size = cnt * (sof + sizeof(int));
4826 data = realloc(data, size, M_IPFW, M_NOWAIT | M_ZERO);
4828 IPFW_RUNLOCK(&layer3_chain);
4831 bcopy(&ptr->id, &data[i], sizeof(int));
4833 bcopy(ptr->lib->logDesc, &data[i], sof);
4836 IPFW_RUNLOCK(&layer3_chain);
4837 error = sooptcopyout(sopt, data, size);
4844 printf("ipfw: ipfw_ctl invalid option %d\n", sopt->sopt_name);
4853 * dummynet needs a reference to the default rule, because rules can be
4854 * deleted while packets hold a reference to them. When this happens,
4855 * dummynet changes the reference to the default rule (it could well be a
4856 * NULL pointer, but this way we do not need to check for the special
4857 * case, plus here he have info on the default behaviour).
4859 struct ip_fw *ip_fw_default_rule;
4862 * This procedure is only used to handle keepalives. It is invoked
4863 * every dyn_keepalive_period
4866 ipfw_tick(void * __unused unused)
4868 struct mbuf *m0, *m, *mnext, **mtailp;
4872 if (dyn_keepalive == 0 || ipfw_dyn_v == NULL || dyn_count == 0)
4876 * We make a chain of packets to go out here -- not deferring
4877 * until after we drop the IPFW dynamic rule lock would result
4878 * in a lock order reversal with the normal packet input -> ipfw
4884 for (i = 0 ; i < curr_dyn_buckets ; i++) {
4885 for (q = ipfw_dyn_v[i] ; q ; q = q->next ) {
4886 if (q->dyn_type == O_LIMIT_PARENT)
4888 if (q->id.proto != IPPROTO_TCP)
4890 if ( (q->state & BOTH_SYN) != BOTH_SYN)
4892 if (TIME_LEQ( time_uptime+dyn_keepalive_interval,
4894 continue; /* too early */
4895 if (TIME_LEQ(q->expire, time_uptime))
4896 continue; /* too late, rule expired */
4898 *mtailp = send_pkt(NULL, &(q->id), q->ack_rev - 1,
4899 q->ack_fwd, TH_SYN);
4900 if (*mtailp != NULL)
4901 mtailp = &(*mtailp)->m_nextpkt;
4902 *mtailp = send_pkt(NULL, &(q->id), q->ack_fwd - 1,
4904 if (*mtailp != NULL)
4905 mtailp = &(*mtailp)->m_nextpkt;
4909 for (m = mnext = m0; m != NULL; m = mnext) {
4910 mnext = m->m_nextpkt;
4911 m->m_nextpkt = NULL;
4912 ip_output(m, NULL, NULL, 0, NULL, NULL);
4915 callout_reset(&ipfw_timeout, dyn_keepalive_period*hz, ipfw_tick, NULL);
4921 struct ip_fw default_rule;
4925 /* Setup IPv6 fw sysctl tree. */
4926 sysctl_ctx_init(&ip6_fw_sysctl_ctx);
4927 ip6_fw_sysctl_tree = SYSCTL_ADD_NODE(&ip6_fw_sysctl_ctx,
4928 SYSCTL_STATIC_CHILDREN(_net_inet6_ip6), OID_AUTO, "fw",
4929 CTLFLAG_RW | CTLFLAG_SECURE, 0, "Firewall");
4930 SYSCTL_ADD_PROC(&ip6_fw_sysctl_ctx, SYSCTL_CHILDREN(ip6_fw_sysctl_tree),
4931 OID_AUTO, "enable", CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE3,
4932 &fw6_enable, 0, ipfw_chg_hook, "I", "Enable ipfw+6");
4933 SYSCTL_ADD_INT(&ip6_fw_sysctl_ctx, SYSCTL_CHILDREN(ip6_fw_sysctl_tree),
4934 OID_AUTO, "deny_unknown_exthdrs", CTLFLAG_RW | CTLFLAG_SECURE,
4935 &fw_deny_unknown_exthdrs, 0,
4936 "Deny packets with unknown IPv6 Extension Headers");
4939 layer3_chain.rules = NULL;
4940 IPFW_LOCK_INIT(&layer3_chain);
4941 ipfw_dyn_rule_zone = uma_zcreate("IPFW dynamic rule",
4942 sizeof(ipfw_dyn_rule), NULL, NULL, NULL, NULL,
4944 IPFW_DYN_LOCK_INIT();
4945 callout_init(&ipfw_timeout, CALLOUT_MPSAFE);
4947 bzero(&default_rule, sizeof default_rule);
4949 default_rule.act_ofs = 0;
4950 default_rule.rulenum = IPFW_DEFAULT_RULE;
4951 default_rule.cmd_len = 1;
4952 default_rule.set = RESVD_SET;
4954 default_rule.cmd[0].len = 1;
4955 default_rule.cmd[0].opcode =
4956 #ifdef IPFIREWALL_DEFAULT_TO_ACCEPT
4961 error = add_rule(&layer3_chain, &default_rule);
4963 printf("ipfw2: error %u initializing default rule "
4964 "(support disabled)\n", error);
4965 IPFW_DYN_LOCK_DESTROY();
4966 IPFW_LOCK_DESTROY(&layer3_chain);
4967 uma_zdestroy(ipfw_dyn_rule_zone);
4971 ip_fw_default_rule = layer3_chain.rules;
4976 "initialized, divert %s, "
4977 "rule-based forwarding "
4978 #ifdef IPFIREWALL_FORWARD
4983 "default to %s, logging ",
4989 default_rule.cmd[0].opcode == O_ACCEPT ? "accept" : "deny");
4991 #ifdef IPFIREWALL_VERBOSE
4994 #ifdef IPFIREWALL_VERBOSE_LIMIT
4995 verbose_limit = IPFIREWALL_VERBOSE_LIMIT;
4997 if (fw_verbose == 0)
4998 printf("disabled\n");
4999 else if (verbose_limit == 0)
5000 printf("unlimited\n");
5002 printf("limited to %d packets/entry by default\n",
5005 error = init_tables(&layer3_chain);
5007 IPFW_DYN_LOCK_DESTROY();
5008 IPFW_LOCK_DESTROY(&layer3_chain);
5009 uma_zdestroy(ipfw_dyn_rule_zone);
5012 ip_fw_ctl_ptr = ipfw_ctl;
5013 ip_fw_chk_ptr = ipfw_chk;
5014 callout_reset(&ipfw_timeout, hz, ipfw_tick, NULL);
5015 #ifdef IPFIREWALL_NAT
5016 LIST_INIT(&layer3_chain.nat);
5017 ifaddr_event_tag = EVENTHANDLER_REGISTER(ifaddr_event, ifaddr_change,
5018 NULL, EVENTHANDLER_PRI_ANY);
5027 #ifdef IPFIREWALL_NAT
5028 struct cfg_nat *ptr, *ptr_temp;
5031 ip_fw_chk_ptr = NULL;
5032 ip_fw_ctl_ptr = NULL;
5033 callout_drain(&ipfw_timeout);
5034 IPFW_WLOCK(&layer3_chain);
5035 flush_tables(&layer3_chain);
5036 #ifdef IPFIREWALL_NAT
5037 LIST_FOREACH_SAFE(ptr, &layer3_chain.nat, _next, ptr_temp) {
5038 LIST_REMOVE(ptr, _next);
5039 del_redir_spool_cfg(ptr, &ptr->redir_chain);
5040 LibAliasUninit(ptr->lib);
5043 EVENTHANDLER_DEREGISTER(ifaddr_event, ifaddr_event_tag);
5045 layer3_chain.reap = NULL;
5046 free_chain(&layer3_chain, 1 /* kill default rule */);
5047 reap = layer3_chain.reap, layer3_chain.reap = NULL;
5048 IPFW_WUNLOCK(&layer3_chain);
5051 IPFW_DYN_LOCK_DESTROY();
5052 uma_zdestroy(ipfw_dyn_rule_zone);
5053 if (ipfw_dyn_v != NULL)
5054 free(ipfw_dyn_v, M_IPFW);
5055 IPFW_LOCK_DESTROY(&layer3_chain);
5058 /* Free IPv6 fw sysctl tree. */
5059 sysctl_ctx_free(&ip6_fw_sysctl_ctx);
5062 printf("IP firewall unloaded\n");