2 * Copyright (c) 2002 Luigi Rizzo, Universita` di Pisa
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
13 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
14 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
16 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
17 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
19 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
20 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
21 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * Implement IP packet firewall (new version)
35 #if !defined(KLD_MODULE)
40 #error IPFIREWALL requires INET.
43 #include "opt_inet6.h"
44 #include "opt_ipsec.h"
46 #include <sys/param.h>
47 #include <sys/systm.h>
48 #include <sys/condvar.h>
49 #include <sys/malloc.h>
51 #include <sys/kernel.h>
54 #include <sys/module.h>
56 #include <sys/rwlock.h>
57 #include <sys/socket.h>
58 #include <sys/socketvar.h>
59 #include <sys/sysctl.h>
60 #include <sys/syslog.h>
61 #include <sys/ucred.h>
63 #include <net/radix.h>
64 #include <net/route.h>
65 #include <netinet/in.h>
66 #include <netinet/in_systm.h>
67 #include <netinet/in_var.h>
68 #include <netinet/in_pcb.h>
69 #include <netinet/ip.h>
70 #include <netinet/ip_var.h>
71 #include <netinet/ip_icmp.h>
72 #include <netinet/ip_fw.h>
73 #include <netinet/ip_divert.h>
74 #include <netinet/ip_dummynet.h>
75 #include <netinet/tcp.h>
76 #include <netinet/tcp_timer.h>
77 #include <netinet/tcp_var.h>
78 #include <netinet/tcpip.h>
79 #include <netinet/udp.h>
80 #include <netinet/udp_var.h>
82 #include <netgraph/ng_ipfw.h>
84 #include <altq/if_altq.h>
87 #include <netinet6/ipsec.h>
90 #include <netinet/ip6.h>
91 #include <netinet/icmp6.h>
93 #include <netinet6/scope6_var.h>
96 #include <netinet/if_ether.h> /* XXX for ETHERTYPE_IP */
98 #include <machine/in_cksum.h> /* XXX for in_cksum */
101 * set_disable contains one bit per set value (0..31).
102 * If the bit is set, all rules with the corresponding set
103 * are disabled. Set RESVD_SET(31) is reserved for the default rule
104 * and rules that are not deleted by the flush command,
105 * and CANNOT be disabled.
106 * Rules in set RESVD_SET can only be deleted explicitly.
108 static u_int32_t set_disable;
110 static int fw_verbose;
111 static int verbose_limit;
113 static struct callout ipfw_timeout;
114 static uma_zone_t ipfw_dyn_rule_zone;
115 #define IPFW_DEFAULT_RULE 65535
118 * Data structure to cache our ucred related
119 * information. This structure only gets used if
120 * the user specified UID/GID based constraints in
124 gid_t fw_groups[NGROUPS];
130 #define IPFW_TABLES_MAX 128
132 struct ip_fw *rules; /* list of rules */
133 struct ip_fw *reap; /* list of rules to reap */
134 struct radix_node_head *tables[IPFW_TABLES_MAX];
137 #define IPFW_LOCK_INIT(_chain) \
138 rw_init(&(_chain)->rwmtx, "IPFW static rules")
139 #define IPFW_LOCK_DESTROY(_chain) rw_destroy(&(_chain)->rwmtx)
140 #define IPFW_WLOCK_ASSERT(_chain) do { \
141 rw_assert(&(_chain)->rwmtx, RA_WLOCKED); \
142 NET_ASSERT_GIANT(); \
145 #define IPFW_RLOCK(p) rw_rlock(&(p)->rwmtx)
146 #define IPFW_RUNLOCK(p) rw_runlock(&(p)->rwmtx)
147 #define IPFW_WLOCK(p) rw_wlock(&(p)->rwmtx)
148 #define IPFW_WUNLOCK(p) rw_wunlock(&(p)->rwmtx)
151 * list of rules for layer 3
153 static struct ip_fw_chain layer3_chain;
155 MALLOC_DEFINE(M_IPFW, "IpFw/IpAcct", "IpFw/IpAcct chain's");
156 MALLOC_DEFINE(M_IPFW_TBL, "ipfw_tbl", "IpFw tables");
159 struct radix_node rn[2];
160 struct sockaddr_in addr, mask;
164 static int fw_debug = 1;
165 static int autoinc_step = 100; /* bounded to 1..1000 in add_rule() */
167 extern int ipfw_chg_hook(SYSCTL_HANDLER_ARGS);
170 SYSCTL_NODE(_net_inet_ip, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall");
171 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, enable,
172 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE3, &fw_enable, 0,
173 ipfw_chg_hook, "I", "Enable ipfw");
174 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, autoinc_step, CTLFLAG_RW,
175 &autoinc_step, 0, "Rule number autincrement step");
176 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, one_pass,
177 CTLFLAG_RW | CTLFLAG_SECURE3,
179 "Only do a single pass through ipfw when using dummynet(4)");
180 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, debug, CTLFLAG_RW,
181 &fw_debug, 0, "Enable printing of debug ip_fw statements");
182 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose,
183 CTLFLAG_RW | CTLFLAG_SECURE3,
184 &fw_verbose, 0, "Log matches to ipfw rules");
185 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose_limit, CTLFLAG_RW,
186 &verbose_limit, 0, "Set upper limit of matches of ipfw rules logged");
189 * Description of dynamic rules.
191 * Dynamic rules are stored in lists accessed through a hash table
192 * (ipfw_dyn_v) whose size is curr_dyn_buckets. This value can
193 * be modified through the sysctl variable dyn_buckets which is
194 * updated when the table becomes empty.
196 * XXX currently there is only one list, ipfw_dyn.
198 * When a packet is received, its address fields are first masked
199 * with the mask defined for the rule, then hashed, then matched
200 * against the entries in the corresponding list.
201 * Dynamic rules can be used for different purposes:
203 * + enforcing limits on the number of sessions;
204 * + in-kernel NAT (not implemented yet)
206 * The lifetime of dynamic rules is regulated by dyn_*_lifetime,
207 * measured in seconds and depending on the flags.
209 * The total number of dynamic rules is stored in dyn_count.
210 * The max number of dynamic rules is dyn_max. When we reach
211 * the maximum number of rules we do not create anymore. This is
212 * done to avoid consuming too much memory, but also too much
213 * time when searching on each packet (ideally, we should try instead
214 * to put a limit on the length of the list on each bucket...).
216 * Each dynamic rule holds a pointer to the parent ipfw rule so
217 * we know what action to perform. Dynamic rules are removed when
218 * the parent rule is deleted. XXX we should make them survive.
220 * There are some limitations with dynamic rules -- we do not
221 * obey the 'randomized match', and we do not do multiple
222 * passes through the firewall. XXX check the latter!!!
224 static ipfw_dyn_rule **ipfw_dyn_v = NULL;
225 static u_int32_t dyn_buckets = 256; /* must be power of 2 */
226 static u_int32_t curr_dyn_buckets = 256; /* must be power of 2 */
228 static struct mtx ipfw_dyn_mtx; /* mutex guarding dynamic rules */
229 #define IPFW_DYN_LOCK_INIT() \
230 mtx_init(&ipfw_dyn_mtx, "IPFW dynamic rules", NULL, MTX_DEF)
231 #define IPFW_DYN_LOCK_DESTROY() mtx_destroy(&ipfw_dyn_mtx)
232 #define IPFW_DYN_LOCK() mtx_lock(&ipfw_dyn_mtx)
233 #define IPFW_DYN_UNLOCK() mtx_unlock(&ipfw_dyn_mtx)
234 #define IPFW_DYN_LOCK_ASSERT() mtx_assert(&ipfw_dyn_mtx, MA_OWNED)
237 * Timeouts for various events in handing dynamic rules.
239 static u_int32_t dyn_ack_lifetime = 300;
240 static u_int32_t dyn_syn_lifetime = 20;
241 static u_int32_t dyn_fin_lifetime = 1;
242 static u_int32_t dyn_rst_lifetime = 1;
243 static u_int32_t dyn_udp_lifetime = 10;
244 static u_int32_t dyn_short_lifetime = 5;
247 * Keepalives are sent if dyn_keepalive is set. They are sent every
248 * dyn_keepalive_period seconds, in the last dyn_keepalive_interval
249 * seconds of lifetime of a rule.
250 * dyn_rst_lifetime and dyn_fin_lifetime should be strictly lower
251 * than dyn_keepalive_period.
254 static u_int32_t dyn_keepalive_interval = 20;
255 static u_int32_t dyn_keepalive_period = 5;
256 static u_int32_t dyn_keepalive = 1; /* do send keepalives */
258 static u_int32_t static_count; /* # of static rules */
259 static u_int32_t static_len; /* size in bytes of static rules */
260 static u_int32_t dyn_count; /* # of dynamic rules */
261 static u_int32_t dyn_max = 4096; /* max # of dynamic rules */
263 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_buckets, CTLFLAG_RW,
264 &dyn_buckets, 0, "Number of dyn. buckets");
265 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, curr_dyn_buckets, CTLFLAG_RD,
266 &curr_dyn_buckets, 0, "Current Number of dyn. buckets");
267 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_count, CTLFLAG_RD,
268 &dyn_count, 0, "Number of dyn. rules");
269 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_max, CTLFLAG_RW,
270 &dyn_max, 0, "Max number of dyn. rules");
271 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, static_count, CTLFLAG_RD,
272 &static_count, 0, "Number of static rules");
273 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_ack_lifetime, CTLFLAG_RW,
274 &dyn_ack_lifetime, 0, "Lifetime of dyn. rules for acks");
275 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_syn_lifetime, CTLFLAG_RW,
276 &dyn_syn_lifetime, 0, "Lifetime of dyn. rules for syn");
277 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_fin_lifetime, CTLFLAG_RW,
278 &dyn_fin_lifetime, 0, "Lifetime of dyn. rules for fin");
279 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_rst_lifetime, CTLFLAG_RW,
280 &dyn_rst_lifetime, 0, "Lifetime of dyn. rules for rst");
281 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_udp_lifetime, CTLFLAG_RW,
282 &dyn_udp_lifetime, 0, "Lifetime of dyn. rules for UDP");
283 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_short_lifetime, CTLFLAG_RW,
284 &dyn_short_lifetime, 0, "Lifetime of dyn. rules for other situations");
285 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_keepalive, CTLFLAG_RW,
286 &dyn_keepalive, 0, "Enable keepalives for dyn. rules");
290 * IPv6 specific variables
292 SYSCTL_DECL(_net_inet6_ip6);
294 static struct sysctl_ctx_list ip6_fw_sysctl_ctx;
295 static struct sysctl_oid *ip6_fw_sysctl_tree;
297 #endif /* SYSCTL_NODE */
299 static int fw_deny_unknown_exthdrs = 1;
303 * L3HDR maps an ipv4 pointer into a layer3 header pointer of type T
304 * Other macros just cast void * into the appropriate type
306 #define L3HDR(T, ip) ((T *)((u_int32_t *)(ip) + (ip)->ip_hl))
307 #define TCP(p) ((struct tcphdr *)(p))
308 #define UDP(p) ((struct udphdr *)(p))
309 #define ICMP(p) ((struct icmphdr *)(p))
310 #define ICMP6(p) ((struct icmp6_hdr *)(p))
313 icmptype_match(struct icmphdr *icmp, ipfw_insn_u32 *cmd)
315 int type = icmp->icmp_type;
317 return (type <= ICMP_MAXTYPE && (cmd->d[0] & (1<<type)) );
320 #define TT ( (1 << ICMP_ECHO) | (1 << ICMP_ROUTERSOLICIT) | \
321 (1 << ICMP_TSTAMP) | (1 << ICMP_IREQ) | (1 << ICMP_MASKREQ) )
324 is_icmp_query(struct icmphdr *icmp)
326 int type = icmp->icmp_type;
328 return (type <= ICMP_MAXTYPE && (TT & (1<<type)) );
333 * The following checks use two arrays of 8 or 16 bits to store the
334 * bits that we want set or clear, respectively. They are in the
335 * low and high half of cmd->arg1 or cmd->d[0].
337 * We scan options and store the bits we find set. We succeed if
339 * (want_set & ~bits) == 0 && (want_clear & ~bits) == want_clear
341 * The code is sometimes optimized not to store additional variables.
345 flags_match(ipfw_insn *cmd, u_int8_t bits)
350 if ( ((cmd->arg1 & 0xff) & bits) != 0)
351 return 0; /* some bits we want set were clear */
352 want_clear = (cmd->arg1 >> 8) & 0xff;
353 if ( (want_clear & bits) != want_clear)
354 return 0; /* some bits we want clear were set */
359 ipopts_match(struct ip *ip, ipfw_insn *cmd)
361 int optlen, bits = 0;
362 u_char *cp = (u_char *)(ip + 1);
363 int x = (ip->ip_hl << 2) - sizeof (struct ip);
365 for (; x > 0; x -= optlen, cp += optlen) {
366 int opt = cp[IPOPT_OPTVAL];
368 if (opt == IPOPT_EOL)
370 if (opt == IPOPT_NOP)
373 optlen = cp[IPOPT_OLEN];
374 if (optlen <= 0 || optlen > x)
375 return 0; /* invalid or truncated */
383 bits |= IP_FW_IPOPT_LSRR;
387 bits |= IP_FW_IPOPT_SSRR;
391 bits |= IP_FW_IPOPT_RR;
395 bits |= IP_FW_IPOPT_TS;
399 return (flags_match(cmd, bits));
403 tcpopts_match(struct tcphdr *tcp, ipfw_insn *cmd)
405 int optlen, bits = 0;
406 u_char *cp = (u_char *)(tcp + 1);
407 int x = (tcp->th_off << 2) - sizeof(struct tcphdr);
409 for (; x > 0; x -= optlen, cp += optlen) {
411 if (opt == TCPOPT_EOL)
413 if (opt == TCPOPT_NOP)
427 bits |= IP_FW_TCPOPT_MSS;
431 bits |= IP_FW_TCPOPT_WINDOW;
434 case TCPOPT_SACK_PERMITTED:
436 bits |= IP_FW_TCPOPT_SACK;
439 case TCPOPT_TIMESTAMP:
440 bits |= IP_FW_TCPOPT_TS;
445 return (flags_match(cmd, bits));
449 iface_match(struct ifnet *ifp, ipfw_insn_if *cmd)
451 if (ifp == NULL) /* no iface with this packet, match fails */
453 /* Check by name or by IP address */
454 if (cmd->name[0] != '\0') { /* match by name */
457 if (fnmatch(cmd->name, ifp->if_xname, 0) == 0)
460 if (strncmp(ifp->if_xname, cmd->name, IFNAMSIZ) == 0)
467 TAILQ_FOREACH(ia, &ifp->if_addrhead, ifa_link) {
468 if (ia->ifa_addr->sa_family != AF_INET)
470 if (cmd->p.ip.s_addr == ((struct sockaddr_in *)
471 (ia->ifa_addr))->sin_addr.s_addr)
472 return(1); /* match */
475 return(0); /* no match, fail ... */
479 * The verify_path function checks if a route to the src exists and
480 * if it is reachable via ifp (when provided).
482 * The 'verrevpath' option checks that the interface that an IP packet
483 * arrives on is the same interface that traffic destined for the
484 * packet's source address would be routed out of. The 'versrcreach'
485 * option just checks that the source address is reachable via any route
486 * (except default) in the routing table. These two are a measure to block
487 * forged packets. This is also commonly known as "anti-spoofing" or Unicast
488 * Reverse Path Forwarding (Unicast RFP) in Cisco-ese. The name of the knobs
489 * is purposely reminiscent of the Cisco IOS command,
491 * ip verify unicast reverse-path
492 * ip verify unicast source reachable-via any
494 * which implements the same functionality. But note that syntax is
495 * misleading. The check may be performed on all IP packets whether unicast,
496 * multicast, or broadcast.
499 verify_path(struct in_addr src, struct ifnet *ifp)
502 struct sockaddr_in *dst;
504 bzero(&ro, sizeof(ro));
506 dst = (struct sockaddr_in *)&(ro.ro_dst);
507 dst->sin_family = AF_INET;
508 dst->sin_len = sizeof(*dst);
510 rtalloc_ign(&ro, RTF_CLONING);
512 if (ro.ro_rt == NULL)
516 * If ifp is provided, check for equality with rtentry.
517 * We should use rt->rt_ifa->ifa_ifp, instead of rt->rt_ifp,
518 * in order to pass packets injected back by if_simloop():
519 * if useloopback == 1 routing entry (via lo0) for our own address
520 * may exist, so we need to handle routing assymetry.
522 if (ifp != NULL && ro.ro_rt->rt_ifa->ifa_ifp != ifp) {
527 /* if no ifp provided, check if rtentry is not default route */
529 satosin(rt_key(ro.ro_rt))->sin_addr.s_addr == INADDR_ANY) {
534 /* or if this is a blackhole/reject route */
535 if (ifp == NULL && ro.ro_rt->rt_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
540 /* found valid route */
547 * ipv6 specific rules here...
550 icmp6type_match (int type, ipfw_insn_u32 *cmd)
552 return (type <= ICMP6_MAXTYPE && (cmd->d[type/32] & (1<<(type%32)) ) );
556 flow6id_match( int curr_flow, ipfw_insn_u32 *cmd )
559 for (i=0; i <= cmd->o.arg1; ++i )
560 if (curr_flow == cmd->d[i] )
565 /* support for IP6_*_ME opcodes */
567 search_ip6_addr_net (struct in6_addr * ip6_addr)
571 struct in6_ifaddr *fdm;
572 struct in6_addr copia;
574 TAILQ_FOREACH(mdc, &ifnet, if_link)
575 TAILQ_FOREACH(mdc2, &mdc->if_addrlist, ifa_list) {
576 if (mdc2->ifa_addr->sa_family == AF_INET6) {
577 fdm = (struct in6_ifaddr *)mdc2;
578 copia = fdm->ia_addr.sin6_addr;
579 /* need for leaving scope_id in the sock_addr */
580 in6_clearscope(&copia);
581 if (IN6_ARE_ADDR_EQUAL(ip6_addr, &copia))
589 verify_path6(struct in6_addr *src, struct ifnet *ifp)
592 struct sockaddr_in6 *dst;
594 bzero(&ro, sizeof(ro));
596 dst = (struct sockaddr_in6 * )&(ro.ro_dst);
597 dst->sin6_family = AF_INET6;
598 dst->sin6_len = sizeof(*dst);
599 dst->sin6_addr = *src;
600 rtalloc_ign((struct route *)&ro, RTF_CLONING);
602 if (ro.ro_rt == NULL)
606 * if ifp is provided, check for equality with rtentry
607 * We should use rt->rt_ifa->ifa_ifp, instead of rt->rt_ifp,
608 * to support the case of sending packets to an address of our own.
609 * (where the former interface is the first argument of if_simloop()
610 * (=ifp), the latter is lo0)
612 if (ifp != NULL && ro.ro_rt->rt_ifa->ifa_ifp != ifp) {
617 /* if no ifp provided, check if rtentry is not default route */
619 IN6_IS_ADDR_UNSPECIFIED(&satosin6(rt_key(ro.ro_rt))->sin6_addr)) {
624 /* or if this is a blackhole/reject route */
625 if (ifp == NULL && ro.ro_rt->rt_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
630 /* found valid route */
636 hash_packet6(struct ipfw_flow_id *id)
639 i = (id->dst_ip6.__u6_addr.__u6_addr32[2]) ^
640 (id->dst_ip6.__u6_addr.__u6_addr32[3]) ^
641 (id->src_ip6.__u6_addr.__u6_addr32[2]) ^
642 (id->src_ip6.__u6_addr.__u6_addr32[3]) ^
643 (id->dst_port) ^ (id->src_port);
648 is_icmp6_query(int icmp6_type)
650 if ((icmp6_type <= ICMP6_MAXTYPE) &&
651 (icmp6_type == ICMP6_ECHO_REQUEST ||
652 icmp6_type == ICMP6_MEMBERSHIP_QUERY ||
653 icmp6_type == ICMP6_WRUREQUEST ||
654 icmp6_type == ICMP6_FQDN_QUERY ||
655 icmp6_type == ICMP6_NI_QUERY))
662 send_reject6(struct ip_fw_args *args, int code, u_int hlen)
664 if (code == ICMP6_UNREACH_RST && args->f_id.proto == IPPROTO_TCP) {
674 if (args->m->m_len < (hlen+sizeof(struct tcphdr))) {
675 args->m = m_pullup(args->m, hlen+sizeof(struct tcphdr));
680 ip6 = mtod(args->m, struct ip6_hdr *);
681 tcp = (struct tcphdr *)(mtod(args->m, char *) + hlen);
683 if ((tcp->th_flags & TH_RST) != 0) {
690 ti.th.th_seq = ntohl(ti.th.th_seq);
691 ti.th.th_ack = ntohl(ti.th.th_ack);
692 ti.ip6.ip6_nxt = IPPROTO_TCP;
694 if (ti.th.th_flags & TH_ACK) {
700 if (((args->m)->m_flags & M_PKTHDR) != 0) {
701 ack += (args->m)->m_pkthdr.len - hlen
702 - (ti.th.th_off << 2);
703 } else if (ip6->ip6_plen) {
704 ack += ntohs(ip6->ip6_plen) + sizeof(*ip6)
705 - hlen - (ti.th.th_off << 2);
710 if (tcp->th_flags & TH_SYN)
713 flags = TH_RST|TH_ACK;
715 bcopy(&ti, ip6, sizeof(ti));
716 tcp_respond(NULL, ip6, (struct tcphdr *)(ip6 + 1),
717 args->m, ack, seq, flags);
719 } else if (code != ICMP6_UNREACH_RST) { /* Send an ICMPv6 unreach. */
720 icmp6_error(args->m, ICMP6_DST_UNREACH, code, 0);
730 static u_int64_t norule_counter; /* counter for ipfw_log(NULL...) */
732 #define SNPARGS(buf, len) buf + len, sizeof(buf) > len ? sizeof(buf) - len : 0
733 #define SNP(buf) buf, sizeof(buf)
736 * We enter here when we have a rule with O_LOG.
737 * XXX this function alone takes about 2Kbytes of code!
740 ipfw_log(struct ip_fw *f, u_int hlen, struct ip_fw_args *args,
741 struct mbuf *m, struct ifnet *oif, u_short offset, uint32_t tablearg)
743 struct ether_header *eh = args->eh;
745 int limit_reached = 0;
746 char action2[40], proto[128], fragment[32];
751 if (f == NULL) { /* bogus pkt */
752 if (verbose_limit != 0 && norule_counter >= verbose_limit)
755 if (norule_counter == verbose_limit)
756 limit_reached = verbose_limit;
758 } else { /* O_LOG is the first action, find the real one */
759 ipfw_insn *cmd = ACTION_PTR(f);
760 ipfw_insn_log *l = (ipfw_insn_log *)cmd;
762 if (l->max_log != 0 && l->log_left == 0)
765 if (l->log_left == 0)
766 limit_reached = l->max_log;
767 cmd += F_LEN(cmd); /* point to first action */
768 if (cmd->opcode == O_ALTQ) {
769 ipfw_insn_altq *altq = (ipfw_insn_altq *)cmd;
771 snprintf(SNPARGS(action2, 0), "Altq %d",
775 if (cmd->opcode == O_PROB)
778 if (cmd->opcode == O_TAG)
782 switch (cmd->opcode) {
788 if (cmd->arg1==ICMP_REJECT_RST)
790 else if (cmd->arg1==ICMP_UNREACH_HOST)
793 snprintf(SNPARGS(action2, 0), "Unreach %d",
798 if (cmd->arg1==ICMP6_UNREACH_RST)
801 snprintf(SNPARGS(action2, 0), "Unreach %d",
812 snprintf(SNPARGS(action2, 0), "Divert %d",
816 snprintf(SNPARGS(action2, 0), "Tee %d",
820 snprintf(SNPARGS(action2, 0), "SkipTo %d",
824 snprintf(SNPARGS(action2, 0), "Pipe %d",
828 snprintf(SNPARGS(action2, 0), "Queue %d",
832 ipfw_insn_sa *sa = (ipfw_insn_sa *)cmd;
834 struct in_addr dummyaddr;
835 if (sa->sa.sin_addr.s_addr == INADDR_ANY)
836 dummyaddr.s_addr = htonl(tablearg);
838 dummyaddr.s_addr = sa->sa.sin_addr.s_addr;
840 len = snprintf(SNPARGS(action2, 0), "Forward to %s",
841 inet_ntoa(dummyaddr));
844 snprintf(SNPARGS(action2, len), ":%d",
849 snprintf(SNPARGS(action2, 0), "Netgraph %d",
853 snprintf(SNPARGS(action2, 0), "Ngtee %d",
862 if (hlen == 0) { /* non-ip */
863 snprintf(SNPARGS(proto, 0), "MAC");
867 char src[48], dst[48];
868 struct icmphdr *icmp;
871 /* Initialize to make compiler happy. */
872 struct ip *ip = NULL;
874 struct ip6_hdr *ip6 = NULL;
875 struct icmp6_hdr *icmp6;
880 if (args->f_id.addr_type == 6) {
881 snprintf(src, sizeof(src), "[%s]",
882 ip6_sprintf(&args->f_id.src_ip6));
883 snprintf(dst, sizeof(dst), "[%s]",
884 ip6_sprintf(&args->f_id.dst_ip6));
886 ip6 = (struct ip6_hdr *)mtod(m, struct ip6_hdr *);
887 tcp = (struct tcphdr *)(mtod(args->m, char *) + hlen);
888 udp = (struct udphdr *)(mtod(args->m, char *) + hlen);
892 ip = mtod(m, struct ip *);
893 tcp = L3HDR(struct tcphdr, ip);
894 udp = L3HDR(struct udphdr, ip);
896 inet_ntoa_r(ip->ip_src, src);
897 inet_ntoa_r(ip->ip_dst, dst);
900 switch (args->f_id.proto) {
902 len = snprintf(SNPARGS(proto, 0), "TCP %s", src);
904 snprintf(SNPARGS(proto, len), ":%d %s:%d",
905 ntohs(tcp->th_sport),
907 ntohs(tcp->th_dport));
909 snprintf(SNPARGS(proto, len), " %s", dst);
913 len = snprintf(SNPARGS(proto, 0), "UDP %s", src);
915 snprintf(SNPARGS(proto, len), ":%d %s:%d",
916 ntohs(udp->uh_sport),
918 ntohs(udp->uh_dport));
920 snprintf(SNPARGS(proto, len), " %s", dst);
924 icmp = L3HDR(struct icmphdr, ip);
926 len = snprintf(SNPARGS(proto, 0),
928 icmp->icmp_type, icmp->icmp_code);
930 len = snprintf(SNPARGS(proto, 0), "ICMP ");
931 len += snprintf(SNPARGS(proto, len), "%s", src);
932 snprintf(SNPARGS(proto, len), " %s", dst);
936 icmp6 = (struct icmp6_hdr *)(mtod(args->m, char *) + hlen);
938 len = snprintf(SNPARGS(proto, 0),
940 icmp6->icmp6_type, icmp6->icmp6_code);
942 len = snprintf(SNPARGS(proto, 0), "ICMPv6 ");
943 len += snprintf(SNPARGS(proto, len), "%s", src);
944 snprintf(SNPARGS(proto, len), " %s", dst);
948 len = snprintf(SNPARGS(proto, 0), "P:%d %s",
949 args->f_id.proto, src);
950 snprintf(SNPARGS(proto, len), " %s", dst);
955 if (args->f_id.addr_type == 6) {
956 if (offset & (IP6F_OFF_MASK | IP6F_MORE_FRAG))
957 snprintf(SNPARGS(fragment, 0),
958 " (frag %08x:%d@%d%s)",
960 ntohs(ip6->ip6_plen) - hlen,
961 ntohs(offset & IP6F_OFF_MASK) << 3,
962 (offset & IP6F_MORE_FRAG) ? "+" : "");
967 if (eh != NULL) { /* layer 2 packets are as on the wire */
968 ip_off = ntohs(ip->ip_off);
969 ip_len = ntohs(ip->ip_len);
974 if (ip_off & (IP_MF | IP_OFFMASK))
975 snprintf(SNPARGS(fragment, 0),
976 " (frag %d:%d@%d%s)",
977 ntohs(ip->ip_id), ip_len - (ip->ip_hl << 2),
979 (ip_off & IP_MF) ? "+" : "");
982 if (oif || m->m_pkthdr.rcvif)
983 log(LOG_SECURITY | LOG_INFO,
984 "ipfw: %d %s %s %s via %s%s\n",
986 action, proto, oif ? "out" : "in",
987 oif ? oif->if_xname : m->m_pkthdr.rcvif->if_xname,
990 log(LOG_SECURITY | LOG_INFO,
991 "ipfw: %d %s %s [no if info]%s\n",
993 action, proto, fragment);
995 log(LOG_SECURITY | LOG_NOTICE,
996 "ipfw: limit %d reached on entry %d\n",
997 limit_reached, f ? f->rulenum : -1);
1001 * IMPORTANT: the hash function for dynamic rules must be commutative
1002 * in source and destination (ip,port), because rules are bidirectional
1003 * and we want to find both in the same bucket.
1006 hash_packet(struct ipfw_flow_id *id)
1011 if (IS_IP6_FLOW_ID(id))
1012 i = hash_packet6(id);
1015 i = (id->dst_ip) ^ (id->src_ip) ^ (id->dst_port) ^ (id->src_port);
1016 i &= (curr_dyn_buckets - 1);
1021 * unlink a dynamic rule from a chain. prev is a pointer to
1022 * the previous one, q is a pointer to the rule to delete,
1023 * head is a pointer to the head of the queue.
1024 * Modifies q and potentially also head.
1026 #define UNLINK_DYN_RULE(prev, head, q) { \
1027 ipfw_dyn_rule *old_q = q; \
1029 /* remove a refcount to the parent */ \
1030 if (q->dyn_type == O_LIMIT) \
1031 q->parent->count--; \
1032 DEB(printf("ipfw: unlink entry 0x%08x %d -> 0x%08x %d, %d left\n",\
1033 (q->id.src_ip), (q->id.src_port), \
1034 (q->id.dst_ip), (q->id.dst_port), dyn_count-1 ); ) \
1036 prev->next = q = q->next; \
1038 head = q = q->next; \
1040 uma_zfree(ipfw_dyn_rule_zone, old_q); }
1042 #define TIME_LEQ(a,b) ((int)((a)-(b)) <= 0)
1045 * Remove dynamic rules pointing to "rule", or all of them if rule == NULL.
1047 * If keep_me == NULL, rules are deleted even if not expired,
1048 * otherwise only expired rules are removed.
1050 * The value of the second parameter is also used to point to identify
1051 * a rule we absolutely do not want to remove (e.g. because we are
1052 * holding a reference to it -- this is the case with O_LIMIT_PARENT
1053 * rules). The pointer is only used for comparison, so any non-null
1057 remove_dyn_rule(struct ip_fw *rule, ipfw_dyn_rule *keep_me)
1059 static u_int32_t last_remove = 0;
1061 #define FORCE (keep_me == NULL)
1063 ipfw_dyn_rule *prev, *q;
1064 int i, pass = 0, max_pass = 0;
1066 IPFW_DYN_LOCK_ASSERT();
1068 if (ipfw_dyn_v == NULL || dyn_count == 0)
1070 /* do not expire more than once per second, it is useless */
1071 if (!FORCE && last_remove == time_uptime)
1073 last_remove = time_uptime;
1076 * because O_LIMIT refer to parent rules, during the first pass only
1077 * remove child and mark any pending LIMIT_PARENT, and remove
1078 * them in a second pass.
1081 for (i = 0 ; i < curr_dyn_buckets ; i++) {
1082 for (prev=NULL, q = ipfw_dyn_v[i] ; q ; ) {
1084 * Logic can become complex here, so we split tests.
1088 if (rule != NULL && rule != q->rule)
1089 goto next; /* not the one we are looking for */
1090 if (q->dyn_type == O_LIMIT_PARENT) {
1092 * handle parent in the second pass,
1093 * record we need one.
1098 if (FORCE && q->count != 0 ) {
1099 /* XXX should not happen! */
1100 printf("ipfw: OUCH! cannot remove rule,"
1101 " count %d\n", q->count);
1105 !TIME_LEQ( q->expire, time_uptime ))
1108 if (q->dyn_type != O_LIMIT_PARENT || !q->count) {
1109 UNLINK_DYN_RULE(prev, ipfw_dyn_v[i], q);
1117 if (pass++ < max_pass)
1123 * lookup a dynamic rule.
1125 static ipfw_dyn_rule *
1126 lookup_dyn_rule_locked(struct ipfw_flow_id *pkt, int *match_direction,
1130 * stateful ipfw extensions.
1131 * Lookup into dynamic session queue
1133 #define MATCH_REVERSE 0
1134 #define MATCH_FORWARD 1
1135 #define MATCH_NONE 2
1136 #define MATCH_UNKNOWN 3
1137 int i, dir = MATCH_NONE;
1138 ipfw_dyn_rule *prev, *q=NULL;
1140 IPFW_DYN_LOCK_ASSERT();
1142 if (ipfw_dyn_v == NULL)
1143 goto done; /* not found */
1144 i = hash_packet( pkt );
1145 for (prev=NULL, q = ipfw_dyn_v[i] ; q != NULL ; ) {
1146 if (q->dyn_type == O_LIMIT_PARENT && q->count)
1148 if (TIME_LEQ( q->expire, time_uptime)) { /* expire entry */
1149 UNLINK_DYN_RULE(prev, ipfw_dyn_v[i], q);
1152 if (pkt->proto == q->id.proto &&
1153 q->dyn_type != O_LIMIT_PARENT) {
1154 if (IS_IP6_FLOW_ID(pkt)) {
1155 if (IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
1156 &(q->id.src_ip6)) &&
1157 IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
1158 &(q->id.dst_ip6)) &&
1159 pkt->src_port == q->id.src_port &&
1160 pkt->dst_port == q->id.dst_port ) {
1161 dir = MATCH_FORWARD;
1164 if (IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
1165 &(q->id.dst_ip6)) &&
1166 IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
1167 &(q->id.src_ip6)) &&
1168 pkt->src_port == q->id.dst_port &&
1169 pkt->dst_port == q->id.src_port ) {
1170 dir = MATCH_REVERSE;
1174 if (pkt->src_ip == q->id.src_ip &&
1175 pkt->dst_ip == q->id.dst_ip &&
1176 pkt->src_port == q->id.src_port &&
1177 pkt->dst_port == q->id.dst_port ) {
1178 dir = MATCH_FORWARD;
1181 if (pkt->src_ip == q->id.dst_ip &&
1182 pkt->dst_ip == q->id.src_ip &&
1183 pkt->src_port == q->id.dst_port &&
1184 pkt->dst_port == q->id.src_port ) {
1185 dir = MATCH_REVERSE;
1195 goto done; /* q = NULL, not found */
1197 if ( prev != NULL) { /* found and not in front */
1198 prev->next = q->next;
1199 q->next = ipfw_dyn_v[i];
1202 if (pkt->proto == IPPROTO_TCP) { /* update state according to flags */
1203 u_char flags = pkt->flags & (TH_FIN|TH_SYN|TH_RST);
1205 #define BOTH_SYN (TH_SYN | (TH_SYN << 8))
1206 #define BOTH_FIN (TH_FIN | (TH_FIN << 8))
1207 q->state |= (dir == MATCH_FORWARD ) ? flags : (flags << 8);
1209 case TH_SYN: /* opening */
1210 q->expire = time_uptime + dyn_syn_lifetime;
1213 case BOTH_SYN: /* move to established */
1214 case BOTH_SYN | TH_FIN : /* one side tries to close */
1215 case BOTH_SYN | (TH_FIN << 8) :
1217 #define _SEQ_GE(a,b) ((int)(a) - (int)(b) >= 0)
1218 u_int32_t ack = ntohl(tcp->th_ack);
1219 if (dir == MATCH_FORWARD) {
1220 if (q->ack_fwd == 0 || _SEQ_GE(ack, q->ack_fwd))
1222 else { /* ignore out-of-sequence */
1226 if (q->ack_rev == 0 || _SEQ_GE(ack, q->ack_rev))
1228 else { /* ignore out-of-sequence */
1233 q->expire = time_uptime + dyn_ack_lifetime;
1236 case BOTH_SYN | BOTH_FIN: /* both sides closed */
1237 if (dyn_fin_lifetime >= dyn_keepalive_period)
1238 dyn_fin_lifetime = dyn_keepalive_period - 1;
1239 q->expire = time_uptime + dyn_fin_lifetime;
1245 * reset or some invalid combination, but can also
1246 * occur if we use keep-state the wrong way.
1248 if ( (q->state & ((TH_RST << 8)|TH_RST)) == 0)
1249 printf("invalid state: 0x%x\n", q->state);
1251 if (dyn_rst_lifetime >= dyn_keepalive_period)
1252 dyn_rst_lifetime = dyn_keepalive_period - 1;
1253 q->expire = time_uptime + dyn_rst_lifetime;
1256 } else if (pkt->proto == IPPROTO_UDP) {
1257 q->expire = time_uptime + dyn_udp_lifetime;
1259 /* other protocols */
1260 q->expire = time_uptime + dyn_short_lifetime;
1263 if (match_direction)
1264 *match_direction = dir;
1268 static ipfw_dyn_rule *
1269 lookup_dyn_rule(struct ipfw_flow_id *pkt, int *match_direction,
1275 q = lookup_dyn_rule_locked(pkt, match_direction, tcp);
1278 /* NB: return table locked when q is not NULL */
1283 realloc_dynamic_table(void)
1285 IPFW_DYN_LOCK_ASSERT();
1288 * Try reallocation, make sure we have a power of 2 and do
1289 * not allow more than 64k entries. In case of overflow,
1293 if (dyn_buckets > 65536)
1295 if ((dyn_buckets & (dyn_buckets-1)) != 0) { /* not a power of 2 */
1296 dyn_buckets = curr_dyn_buckets; /* reset */
1299 curr_dyn_buckets = dyn_buckets;
1300 if (ipfw_dyn_v != NULL)
1301 free(ipfw_dyn_v, M_IPFW);
1303 ipfw_dyn_v = malloc(curr_dyn_buckets * sizeof(ipfw_dyn_rule *),
1304 M_IPFW, M_NOWAIT | M_ZERO);
1305 if (ipfw_dyn_v != NULL || curr_dyn_buckets <= 2)
1307 curr_dyn_buckets /= 2;
1312 * Install state of type 'type' for a dynamic session.
1313 * The hash table contains two type of rules:
1314 * - regular rules (O_KEEP_STATE)
1315 * - rules for sessions with limited number of sess per user
1316 * (O_LIMIT). When they are created, the parent is
1317 * increased by 1, and decreased on delete. In this case,
1318 * the third parameter is the parent rule and not the chain.
1319 * - "parent" rules for the above (O_LIMIT_PARENT).
1321 static ipfw_dyn_rule *
1322 add_dyn_rule(struct ipfw_flow_id *id, u_int8_t dyn_type, struct ip_fw *rule)
1327 IPFW_DYN_LOCK_ASSERT();
1329 if (ipfw_dyn_v == NULL ||
1330 (dyn_count == 0 && dyn_buckets != curr_dyn_buckets)) {
1331 realloc_dynamic_table();
1332 if (ipfw_dyn_v == NULL)
1333 return NULL; /* failed ! */
1335 i = hash_packet(id);
1337 r = uma_zalloc(ipfw_dyn_rule_zone, M_NOWAIT | M_ZERO);
1339 printf ("ipfw: sorry cannot allocate state\n");
1343 /* increase refcount on parent, and set pointer */
1344 if (dyn_type == O_LIMIT) {
1345 ipfw_dyn_rule *parent = (ipfw_dyn_rule *)rule;
1346 if ( parent->dyn_type != O_LIMIT_PARENT)
1347 panic("invalid parent");
1350 rule = parent->rule;
1354 r->expire = time_uptime + dyn_syn_lifetime;
1356 r->dyn_type = dyn_type;
1357 r->pcnt = r->bcnt = 0;
1361 r->next = ipfw_dyn_v[i];
1364 DEB(printf("ipfw: add dyn entry ty %d 0x%08x %d -> 0x%08x %d, total %d\n",
1366 (r->id.src_ip), (r->id.src_port),
1367 (r->id.dst_ip), (r->id.dst_port),
1373 * lookup dynamic parent rule using pkt and rule as search keys.
1374 * If the lookup fails, then install one.
1376 static ipfw_dyn_rule *
1377 lookup_dyn_parent(struct ipfw_flow_id *pkt, struct ip_fw *rule)
1382 IPFW_DYN_LOCK_ASSERT();
1385 int is_v6 = IS_IP6_FLOW_ID(pkt);
1386 i = hash_packet( pkt );
1387 for (q = ipfw_dyn_v[i] ; q != NULL ; q=q->next)
1388 if (q->dyn_type == O_LIMIT_PARENT &&
1390 pkt->proto == q->id.proto &&
1391 pkt->src_port == q->id.src_port &&
1392 pkt->dst_port == q->id.dst_port &&
1395 IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
1396 &(q->id.src_ip6)) &&
1397 IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
1398 &(q->id.dst_ip6))) ||
1400 pkt->src_ip == q->id.src_ip &&
1401 pkt->dst_ip == q->id.dst_ip)
1404 q->expire = time_uptime + dyn_short_lifetime;
1405 DEB(printf("ipfw: lookup_dyn_parent found 0x%p\n",q);)
1409 return add_dyn_rule(pkt, O_LIMIT_PARENT, rule);
1413 * Install dynamic state for rule type cmd->o.opcode
1415 * Returns 1 (failure) if state is not installed because of errors or because
1416 * session limitations are enforced.
1419 install_state(struct ip_fw *rule, ipfw_insn_limit *cmd,
1420 struct ip_fw_args *args, uint32_t tablearg)
1422 static int last_log;
1427 printf("ipfw: %s: type %d 0x%08x %u -> 0x%08x %u\n",
1428 __func__, cmd->o.opcode,
1429 (args->f_id.src_ip), (args->f_id.src_port),
1430 (args->f_id.dst_ip), (args->f_id.dst_port));
1435 q = lookup_dyn_rule_locked(&args->f_id, NULL, NULL);
1437 if (q != NULL) { /* should never occur */
1438 if (last_log != time_uptime) {
1439 last_log = time_uptime;
1440 printf("ipfw: %s: entry already present, done\n",
1447 if (dyn_count >= dyn_max)
1448 /* Run out of slots, try to remove any expired rule. */
1449 remove_dyn_rule(NULL, (ipfw_dyn_rule *)1);
1451 if (dyn_count >= dyn_max) {
1452 if (last_log != time_uptime) {
1453 last_log = time_uptime;
1454 printf("ipfw: %s: Too many dynamic rules\n", __func__);
1457 return (1); /* cannot install, notify caller */
1460 switch (cmd->o.opcode) {
1461 case O_KEEP_STATE: /* bidir rule */
1462 add_dyn_rule(&args->f_id, O_KEEP_STATE, rule);
1465 case O_LIMIT: { /* limit number of sessions */
1466 struct ipfw_flow_id id;
1467 ipfw_dyn_rule *parent;
1468 uint32_t conn_limit;
1469 uint16_t limit_mask = cmd->limit_mask;
1471 conn_limit = (cmd->conn_limit == IP_FW_TABLEARG) ?
1472 tablearg : cmd->conn_limit;
1475 if (cmd->conn_limit == IP_FW_TABLEARG)
1476 printf("ipfw: %s: O_LIMIT rule, conn_limit: %u "
1477 "(tablearg)\n", __func__, conn_limit);
1479 printf("ipfw: %s: O_LIMIT rule, conn_limit: %u\n",
1480 __func__, conn_limit);
1483 id.dst_ip = id.src_ip = id.dst_port = id.src_port = 0;
1484 id.proto = args->f_id.proto;
1485 id.addr_type = args->f_id.addr_type;
1487 if (IS_IP6_FLOW_ID (&(args->f_id))) {
1488 if (limit_mask & DYN_SRC_ADDR)
1489 id.src_ip6 = args->f_id.src_ip6;
1490 if (limit_mask & DYN_DST_ADDR)
1491 id.dst_ip6 = args->f_id.dst_ip6;
1493 if (limit_mask & DYN_SRC_ADDR)
1494 id.src_ip = args->f_id.src_ip;
1495 if (limit_mask & DYN_DST_ADDR)
1496 id.dst_ip = args->f_id.dst_ip;
1498 if (limit_mask & DYN_SRC_PORT)
1499 id.src_port = args->f_id.src_port;
1500 if (limit_mask & DYN_DST_PORT)
1501 id.dst_port = args->f_id.dst_port;
1502 if ((parent = lookup_dyn_parent(&id, rule)) == NULL) {
1503 printf("ipfw: %s: add parent failed\n", __func__);
1508 if (parent->count >= conn_limit) {
1509 /* See if we can remove some expired rule. */
1510 remove_dyn_rule(rule, parent);
1511 if (parent->count >= conn_limit) {
1512 if (fw_verbose && last_log != time_uptime) {
1513 last_log = time_uptime;
1514 log(LOG_SECURITY | LOG_DEBUG,
1515 "drop session, too many entries\n");
1521 add_dyn_rule(&args->f_id, O_LIMIT, (struct ip_fw *)parent);
1525 printf("ipfw: %s: unknown dynamic rule type %u\n",
1526 __func__, cmd->o.opcode);
1531 /* XXX just set lifetime */
1532 lookup_dyn_rule_locked(&args->f_id, NULL, NULL);
1539 * Generate a TCP packet, containing either a RST or a keepalive.
1540 * When flags & TH_RST, we are sending a RST packet, because of a
1541 * "reset" action matched the packet.
1542 * Otherwise we are sending a keepalive, and flags & TH_
1544 static struct mbuf *
1545 send_pkt(struct ipfw_flow_id *id, u_int32_t seq, u_int32_t ack, int flags)
1551 MGETHDR(m, M_DONTWAIT, MT_DATA);
1554 m->m_pkthdr.rcvif = (struct ifnet *)0;
1555 m->m_pkthdr.len = m->m_len = sizeof(struct ip) + sizeof(struct tcphdr);
1556 m->m_data += max_linkhdr;
1558 ip = mtod(m, struct ip *);
1559 bzero(ip, m->m_len);
1560 tcp = (struct tcphdr *)(ip + 1); /* no IP options */
1561 ip->ip_p = IPPROTO_TCP;
1564 * Assume we are sending a RST (or a keepalive in the reverse
1565 * direction), swap src and destination addresses and ports.
1567 ip->ip_src.s_addr = htonl(id->dst_ip);
1568 ip->ip_dst.s_addr = htonl(id->src_ip);
1569 tcp->th_sport = htons(id->dst_port);
1570 tcp->th_dport = htons(id->src_port);
1571 if (flags & TH_RST) { /* we are sending a RST */
1572 if (flags & TH_ACK) {
1573 tcp->th_seq = htonl(ack);
1574 tcp->th_ack = htonl(0);
1575 tcp->th_flags = TH_RST;
1579 tcp->th_seq = htonl(0);
1580 tcp->th_ack = htonl(seq);
1581 tcp->th_flags = TH_RST | TH_ACK;
1585 * We are sending a keepalive. flags & TH_SYN determines
1586 * the direction, forward if set, reverse if clear.
1587 * NOTE: seq and ack are always assumed to be correct
1588 * as set by the caller. This may be confusing...
1590 if (flags & TH_SYN) {
1592 * we have to rewrite the correct addresses!
1594 ip->ip_dst.s_addr = htonl(id->dst_ip);
1595 ip->ip_src.s_addr = htonl(id->src_ip);
1596 tcp->th_dport = htons(id->dst_port);
1597 tcp->th_sport = htons(id->src_port);
1599 tcp->th_seq = htonl(seq);
1600 tcp->th_ack = htonl(ack);
1601 tcp->th_flags = TH_ACK;
1604 * set ip_len to the payload size so we can compute
1605 * the tcp checksum on the pseudoheader
1606 * XXX check this, could save a couple of words ?
1608 ip->ip_len = htons(sizeof(struct tcphdr));
1609 tcp->th_sum = in_cksum(m, m->m_pkthdr.len);
1611 * now fill fields left out earlier
1613 ip->ip_ttl = ip_defttl;
1614 ip->ip_len = m->m_pkthdr.len;
1615 m->m_flags |= M_SKIP_FIREWALL;
1620 * sends a reject message, consuming the mbuf passed as an argument.
1623 send_reject(struct ip_fw_args *args, int code, int ip_len)
1626 if (code != ICMP_REJECT_RST) { /* Send an ICMP unreach */
1627 /* We need the IP header in host order for icmp_error(). */
1628 if (args->eh != NULL) {
1629 struct ip *ip = mtod(args->m, struct ip *);
1630 ip->ip_len = ntohs(ip->ip_len);
1631 ip->ip_off = ntohs(ip->ip_off);
1633 icmp_error(args->m, ICMP_UNREACH, code, 0L, 0);
1634 } else if (args->f_id.proto == IPPROTO_TCP) {
1635 struct tcphdr *const tcp =
1636 L3HDR(struct tcphdr, mtod(args->m, struct ip *));
1637 if ( (tcp->th_flags & TH_RST) == 0) {
1639 m = send_pkt(&(args->f_id), ntohl(tcp->th_seq),
1641 tcp->th_flags | TH_RST);
1643 ip_output(m, NULL, NULL, 0, NULL, NULL);
1653 * Given an ip_fw *, lookup_next_rule will return a pointer
1654 * to the next rule, which can be either the jump
1655 * target (for skipto instructions) or the next one in the list (in
1656 * all other cases including a missing jump target).
1657 * The result is also written in the "next_rule" field of the rule.
1658 * Backward jumps are not allowed, so start looking from the next
1661 * This never returns NULL -- in case we do not have an exact match,
1662 * the next rule is returned. When the ruleset is changed,
1663 * pointers are flushed so we are always correct.
1666 static struct ip_fw *
1667 lookup_next_rule(struct ip_fw *me)
1669 struct ip_fw *rule = NULL;
1672 /* look for action, in case it is a skipto */
1673 cmd = ACTION_PTR(me);
1674 if (cmd->opcode == O_LOG)
1676 if (cmd->opcode == O_ALTQ)
1678 if (cmd->opcode == O_TAG)
1680 if ( cmd->opcode == O_SKIPTO )
1681 for (rule = me->next; rule ; rule = rule->next)
1682 if (rule->rulenum >= cmd->arg1)
1684 if (rule == NULL) /* failure or not a skipto */
1686 me->next_rule = rule;
1691 add_table_entry(struct ip_fw_chain *ch, uint16_t tbl, in_addr_t addr,
1692 uint8_t mlen, uint32_t value)
1694 struct radix_node_head *rnh;
1695 struct table_entry *ent;
1697 if (tbl >= IPFW_TABLES_MAX)
1699 rnh = ch->tables[tbl];
1700 ent = malloc(sizeof(*ent), M_IPFW_TBL, M_NOWAIT | M_ZERO);
1704 ent->addr.sin_len = ent->mask.sin_len = 8;
1705 ent->mask.sin_addr.s_addr = htonl(mlen ? ~((1 << (32 - mlen)) - 1) : 0);
1706 ent->addr.sin_addr.s_addr = addr & ent->mask.sin_addr.s_addr;
1707 IPFW_WLOCK(&layer3_chain);
1708 if (rnh->rnh_addaddr(&ent->addr, &ent->mask, rnh, (void *)ent) ==
1710 IPFW_WUNLOCK(&layer3_chain);
1711 free(ent, M_IPFW_TBL);
1714 IPFW_WUNLOCK(&layer3_chain);
1719 del_table_entry(struct ip_fw_chain *ch, uint16_t tbl, in_addr_t addr,
1722 struct radix_node_head *rnh;
1723 struct table_entry *ent;
1724 struct sockaddr_in sa, mask;
1726 if (tbl >= IPFW_TABLES_MAX)
1728 rnh = ch->tables[tbl];
1729 sa.sin_len = mask.sin_len = 8;
1730 mask.sin_addr.s_addr = htonl(mlen ? ~((1 << (32 - mlen)) - 1) : 0);
1731 sa.sin_addr.s_addr = addr & mask.sin_addr.s_addr;
1733 ent = (struct table_entry *)rnh->rnh_deladdr(&sa, &mask, rnh);
1739 free(ent, M_IPFW_TBL);
1744 flush_table_entry(struct radix_node *rn, void *arg)
1746 struct radix_node_head * const rnh = arg;
1747 struct table_entry *ent;
1749 ent = (struct table_entry *)
1750 rnh->rnh_deladdr(rn->rn_key, rn->rn_mask, rnh);
1752 free(ent, M_IPFW_TBL);
1757 flush_table(struct ip_fw_chain *ch, uint16_t tbl)
1759 struct radix_node_head *rnh;
1761 IPFW_WLOCK_ASSERT(ch);
1763 if (tbl >= IPFW_TABLES_MAX)
1765 rnh = ch->tables[tbl];
1766 KASSERT(rnh != NULL, ("NULL IPFW table"));
1767 rnh->rnh_walktree(rnh, flush_table_entry, rnh);
1772 flush_tables(struct ip_fw_chain *ch)
1776 IPFW_WLOCK_ASSERT(ch);
1778 for (tbl = 0; tbl < IPFW_TABLES_MAX; tbl++)
1779 flush_table(ch, tbl);
1783 init_tables(struct ip_fw_chain *ch)
1788 for (i = 0; i < IPFW_TABLES_MAX; i++) {
1789 if (!rn_inithead((void **)&ch->tables[i], 32)) {
1790 for (j = 0; j < i; j++) {
1791 (void) flush_table(ch, j);
1800 lookup_table(struct ip_fw_chain *ch, uint16_t tbl, in_addr_t addr,
1803 struct radix_node_head *rnh;
1804 struct table_entry *ent;
1805 struct sockaddr_in sa;
1807 if (tbl >= IPFW_TABLES_MAX)
1809 rnh = ch->tables[tbl];
1811 sa.sin_addr.s_addr = addr;
1812 ent = (struct table_entry *)(rnh->rnh_lookup(&sa, NULL, rnh));
1821 count_table_entry(struct radix_node *rn, void *arg)
1823 u_int32_t * const cnt = arg;
1830 count_table(struct ip_fw_chain *ch, uint32_t tbl, uint32_t *cnt)
1832 struct radix_node_head *rnh;
1834 if (tbl >= IPFW_TABLES_MAX)
1836 rnh = ch->tables[tbl];
1838 rnh->rnh_walktree(rnh, count_table_entry, cnt);
1843 dump_table_entry(struct radix_node *rn, void *arg)
1845 struct table_entry * const n = (struct table_entry *)rn;
1846 ipfw_table * const tbl = arg;
1847 ipfw_table_entry *ent;
1849 if (tbl->cnt == tbl->size)
1851 ent = &tbl->ent[tbl->cnt];
1852 ent->tbl = tbl->tbl;
1853 if (in_nullhost(n->mask.sin_addr))
1856 ent->masklen = 33 - ffs(ntohl(n->mask.sin_addr.s_addr));
1857 ent->addr = n->addr.sin_addr.s_addr;
1858 ent->value = n->value;
1864 dump_table(struct ip_fw_chain *ch, ipfw_table *tbl)
1866 struct radix_node_head *rnh;
1868 if (tbl->tbl >= IPFW_TABLES_MAX)
1870 rnh = ch->tables[tbl->tbl];
1872 rnh->rnh_walktree(rnh, dump_table_entry, tbl);
1877 fill_ugid_cache(struct inpcb *inp, struct ip_fw_ugid *ugp)
1881 if (inp->inp_socket != NULL) {
1882 cr = inp->inp_socket->so_cred;
1883 ugp->fw_prid = jailed(cr) ?
1884 cr->cr_prison->pr_id : -1;
1885 ugp->fw_uid = cr->cr_uid;
1886 ugp->fw_ngroups = cr->cr_ngroups;
1887 bcopy(cr->cr_groups, ugp->fw_groups,
1888 sizeof(ugp->fw_groups));
1893 check_uidgid(ipfw_insn_u32 *insn,
1894 int proto, struct ifnet *oif,
1895 struct in_addr dst_ip, u_int16_t dst_port,
1896 struct in_addr src_ip, u_int16_t src_port,
1897 struct ip_fw_ugid *ugp, int *lookup, struct inpcb *inp)
1899 struct inpcbinfo *pi;
1906 * Check to see if the UDP or TCP stack supplied us with
1907 * the PCB. If so, rather then holding a lock and looking
1908 * up the PCB, we can use the one that was supplied.
1910 if (inp && *lookup == 0) {
1911 INP_LOCK_ASSERT(inp);
1912 if (inp->inp_socket != NULL) {
1913 fill_ugid_cache(inp, ugp);
1918 * If we have already been here and the packet has no
1919 * PCB entry associated with it, then we can safely
1920 * assume that this is a no match.
1924 if (proto == IPPROTO_TCP) {
1927 } else if (proto == IPPROTO_UDP) {
1928 wildcard = INPLOOKUP_WILDCARD;
1936 in_pcblookup_hash(pi,
1937 dst_ip, htons(dst_port),
1938 src_ip, htons(src_port),
1940 in_pcblookup_hash(pi,
1941 src_ip, htons(src_port),
1942 dst_ip, htons(dst_port),
1946 if (pcb->inp_socket != NULL) {
1947 fill_ugid_cache(pcb, ugp);
1952 INP_INFO_RUNLOCK(pi);
1955 * If the lookup did not yield any results, there
1956 * is no sense in coming back and trying again. So
1957 * we can set lookup to -1 and ensure that we wont
1958 * bother the pcb system again.
1964 if (insn->o.opcode == O_UID)
1965 match = (ugp->fw_uid == (uid_t)insn->d[0]);
1966 else if (insn->o.opcode == O_GID) {
1967 for (gp = ugp->fw_groups;
1968 gp < &ugp->fw_groups[ugp->fw_ngroups]; gp++)
1969 if (*gp == (gid_t)insn->d[0]) {
1973 } else if (insn->o.opcode == O_JAIL)
1974 match = (ugp->fw_prid == (int)insn->d[0]);
1979 * The main check routine for the firewall.
1981 * All arguments are in args so we can modify them and return them
1982 * back to the caller.
1986 * args->m (in/out) The packet; we set to NULL when/if we nuke it.
1987 * Starts with the IP header.
1988 * args->eh (in) Mac header if present, or NULL for layer3 packet.
1989 * args->oif Outgoing interface, or NULL if packet is incoming.
1990 * The incoming interface is in the mbuf. (in)
1991 * args->divert_rule (in/out)
1992 * Skip up to the first rule past this rule number;
1993 * upon return, non-zero port number for divert or tee.
1995 * args->rule Pointer to the last matching rule (in/out)
1996 * args->next_hop Socket we are forwarding to (out).
1997 * args->f_id Addresses grabbed from the packet (out)
1998 * args->cookie a cookie depending on rule action
2002 * IP_FW_PASS the packet must be accepted
2003 * IP_FW_DENY the packet must be dropped
2004 * IP_FW_DIVERT divert packet, port in m_tag
2005 * IP_FW_TEE tee packet, port in m_tag
2006 * IP_FW_DUMMYNET to dummynet, pipe in args->cookie
2007 * IP_FW_NETGRAPH into netgraph, cookie args->cookie
2012 ipfw_chk(struct ip_fw_args *args)
2015 * Local variables hold state during the processing of a packet.
2017 * IMPORTANT NOTE: to speed up the processing of rules, there
2018 * are some assumption on the values of the variables, which
2019 * are documented here. Should you change them, please check
2020 * the implementation of the various instructions to make sure
2021 * that they still work.
2023 * args->eh The MAC header. It is non-null for a layer2
2024 * packet, it is NULL for a layer-3 packet.
2026 * m | args->m Pointer to the mbuf, as received from the caller.
2027 * It may change if ipfw_chk() does an m_pullup, or if it
2028 * consumes the packet because it calls send_reject().
2029 * XXX This has to change, so that ipfw_chk() never modifies
2030 * or consumes the buffer.
2031 * ip is simply an alias of the value of m, and it is kept
2032 * in sync with it (the packet is supposed to start with
2035 struct mbuf *m = args->m;
2036 struct ip *ip = mtod(m, struct ip *);
2039 * For rules which contain uid/gid or jail constraints, cache
2040 * a copy of the users credentials after the pcb lookup has been
2041 * executed. This will speed up the processing of rules with
2042 * these types of constraints, as well as decrease contention
2043 * on pcb related locks.
2045 struct ip_fw_ugid fw_ugid_cache;
2046 int ugid_lookup = 0;
2049 * divinput_flags If non-zero, set to the IP_FW_DIVERT_*_FLAG
2050 * associated with a packet input on a divert socket. This
2051 * will allow to distinguish traffic and its direction when
2052 * it originates from a divert socket.
2054 u_int divinput_flags = 0;
2057 * oif | args->oif If NULL, ipfw_chk has been called on the
2058 * inbound path (ether_input, ip_input).
2059 * If non-NULL, ipfw_chk has been called on the outbound path
2060 * (ether_output, ip_output).
2062 struct ifnet *oif = args->oif;
2064 struct ip_fw *f = NULL; /* matching rule */
2068 * hlen The length of the IP header.
2070 u_int hlen = 0; /* hlen >0 means we have an IP pkt */
2073 * offset The offset of a fragment. offset != 0 means that
2074 * we have a fragment at this offset of an IPv4 packet.
2075 * offset == 0 means that (if this is an IPv4 packet)
2076 * this is the first or only fragment.
2077 * For IPv6 offset == 0 means there is no Fragment Header.
2078 * If offset != 0 for IPv6 always use correct mask to
2079 * get the correct offset because we add IP6F_MORE_FRAG
2080 * to be able to dectect the first fragment which would
2081 * otherwise have offset = 0.
2086 * Local copies of addresses. They are only valid if we have
2089 * proto The protocol. Set to 0 for non-ip packets,
2090 * or to the protocol read from the packet otherwise.
2091 * proto != 0 means that we have an IPv4 packet.
2093 * src_port, dst_port port numbers, in HOST format. Only
2094 * valid for TCP and UDP packets.
2096 * src_ip, dst_ip ip addresses, in NETWORK format.
2097 * Only valid for IPv4 packets.
2100 u_int16_t src_port = 0, dst_port = 0; /* NOTE: host format */
2101 struct in_addr src_ip, dst_ip; /* NOTE: network format */
2106 * dyn_dir = MATCH_UNKNOWN when rules unchecked,
2107 * MATCH_NONE when checked and not matched (q = NULL),
2108 * MATCH_FORWARD or MATCH_REVERSE otherwise (q != NULL)
2110 int dyn_dir = MATCH_UNKNOWN;
2111 ipfw_dyn_rule *q = NULL;
2112 struct ip_fw_chain *chain = &layer3_chain;
2116 * We store in ulp a pointer to the upper layer protocol header.
2117 * In the ipv4 case this is easy to determine from the header,
2118 * but for ipv6 we might have some additional headers in the middle.
2119 * ulp is NULL if not found.
2121 void *ulp = NULL; /* upper layer protocol pointer. */
2122 /* XXX ipv6 variables */
2124 u_int16_t ext_hd = 0; /* bits vector for extension header filtering */
2125 /* end of ipv6 variables */
2128 if (m->m_flags & M_SKIP_FIREWALL)
2129 return (IP_FW_PASS); /* accept */
2131 pktlen = m->m_pkthdr.len;
2132 proto = args->f_id.proto = 0; /* mark f_id invalid */
2133 /* XXX 0 is a valid proto: IP/IPv6 Hop-by-Hop Option */
2136 * PULLUP_TO(len, p, T) makes sure that len + sizeof(T) is contiguous,
2137 * then it sets p to point at the offset "len" in the mbuf. WARNING: the
2138 * pointer might become stale after other pullups (but we never use it
2141 #define PULLUP_TO(len, p, T) \
2143 int x = (len) + sizeof(T); \
2144 if ((m)->m_len < x) { \
2145 args->m = m = m_pullup(m, x); \
2147 goto pullup_failed; \
2149 p = (mtod(m, char *) + (len)); \
2152 /* Identify IP packets and fill up variables. */
2153 if (pktlen >= sizeof(struct ip6_hdr) &&
2154 (args->eh == NULL || ntohs(args->eh->ether_type)==ETHERTYPE_IPV6) &&
2155 mtod(m, struct ip *)->ip_v == 6) {
2157 args->f_id.addr_type = 6;
2158 hlen = sizeof(struct ip6_hdr);
2159 proto = mtod(m, struct ip6_hdr *)->ip6_nxt;
2161 /* Search extension headers to find upper layer protocols */
2162 while (ulp == NULL) {
2164 case IPPROTO_ICMPV6:
2165 PULLUP_TO(hlen, ulp, struct icmp6_hdr);
2166 args->f_id.flags = ICMP6(ulp)->icmp6_type;
2170 PULLUP_TO(hlen, ulp, struct tcphdr);
2171 dst_port = TCP(ulp)->th_dport;
2172 src_port = TCP(ulp)->th_sport;
2173 args->f_id.flags = TCP(ulp)->th_flags;
2177 PULLUP_TO(hlen, ulp, struct udphdr);
2178 dst_port = UDP(ulp)->uh_dport;
2179 src_port = UDP(ulp)->uh_sport;
2182 case IPPROTO_HOPOPTS: /* RFC 2460 */
2183 PULLUP_TO(hlen, ulp, struct ip6_hbh);
2184 ext_hd |= EXT_HOPOPTS;
2185 hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3;
2186 proto = ((struct ip6_hbh *)ulp)->ip6h_nxt;
2190 case IPPROTO_ROUTING: /* RFC 2460 */
2191 PULLUP_TO(hlen, ulp, struct ip6_rthdr);
2192 switch (((struct ip6_rthdr *)ulp)->ip6r_type) {
2196 printf("IPFW2: IPV6 - Unknown Routing "
2197 "Header type(%d)\n",
2198 ((struct ip6_rthdr *)ulp)->ip6r_type);
2199 if (fw_deny_unknown_exthdrs)
2200 return (IP_FW_DENY);
2203 ext_hd |= EXT_ROUTING;
2204 hlen += (((struct ip6_rthdr *)ulp)->ip6r_len + 1) << 3;
2205 proto = ((struct ip6_rthdr *)ulp)->ip6r_nxt;
2209 case IPPROTO_FRAGMENT: /* RFC 2460 */
2210 PULLUP_TO(hlen, ulp, struct ip6_frag);
2211 ext_hd |= EXT_FRAGMENT;
2212 hlen += sizeof (struct ip6_frag);
2213 proto = ((struct ip6_frag *)ulp)->ip6f_nxt;
2214 offset = ((struct ip6_frag *)ulp)->ip6f_offlg &
2216 /* Add IP6F_MORE_FRAG for offset of first
2217 * fragment to be != 0. */
2218 offset |= ((struct ip6_frag *)ulp)->ip6f_offlg &
2221 printf("IPFW2: IPV6 - Invalid Fragment "
2223 if (fw_deny_unknown_exthdrs)
2224 return (IP_FW_DENY);
2227 args->f_id.frag_id6 =
2228 ntohl(((struct ip6_frag *)ulp)->ip6f_ident);
2232 case IPPROTO_DSTOPTS: /* RFC 2460 */
2233 PULLUP_TO(hlen, ulp, struct ip6_hbh);
2234 ext_hd |= EXT_DSTOPTS;
2235 hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3;
2236 proto = ((struct ip6_hbh *)ulp)->ip6h_nxt;
2240 case IPPROTO_AH: /* RFC 2402 */
2241 PULLUP_TO(hlen, ulp, struct ip6_ext);
2243 hlen += (((struct ip6_ext *)ulp)->ip6e_len + 2) << 2;
2244 proto = ((struct ip6_ext *)ulp)->ip6e_nxt;
2248 case IPPROTO_ESP: /* RFC 2406 */
2249 PULLUP_TO(hlen, ulp, uint32_t); /* SPI, Seq# */
2250 /* Anything past Seq# is variable length and
2251 * data past this ext. header is encrypted. */
2255 case IPPROTO_NONE: /* RFC 2460 */
2256 PULLUP_TO(hlen, ulp, struct ip6_ext);
2257 /* Packet ends here. if ip6e_len!=0 octets
2258 * must be ignored. */
2261 case IPPROTO_OSPFIGP:
2262 /* XXX OSPF header check? */
2263 PULLUP_TO(hlen, ulp, struct ip6_ext);
2266 case IPPROTO_IPV6: /* RFC 2893 */
2267 PULLUP_TO(hlen, ulp, struct ip6_hdr);
2270 case IPPROTO_IPV4: /* RFC 2893 */
2271 PULLUP_TO(hlen, ulp, struct ip);
2275 printf("IPFW2: IPV6 - Unknown Extension "
2276 "Header(%d), ext_hd=%x\n", proto, ext_hd);
2277 if (fw_deny_unknown_exthdrs)
2278 return (IP_FW_DENY);
2279 PULLUP_TO(hlen, ulp, struct ip6_ext);
2283 args->f_id.src_ip6 = mtod(m,struct ip6_hdr *)->ip6_src;
2284 args->f_id.dst_ip6 = mtod(m,struct ip6_hdr *)->ip6_dst;
2285 args->f_id.src_ip = 0;
2286 args->f_id.dst_ip = 0;
2287 args->f_id.flow_id6 = ntohl(mtod(m, struct ip6_hdr *)->ip6_flow);
2288 } else if (pktlen >= sizeof(struct ip) &&
2289 (args->eh == NULL || ntohs(args->eh->ether_type) == ETHERTYPE_IP) &&
2290 mtod(m, struct ip *)->ip_v == 4) {
2292 ip = mtod(m, struct ip *);
2293 hlen = ip->ip_hl << 2;
2294 args->f_id.addr_type = 4;
2297 * Collect parameters into local variables for faster matching.
2300 src_ip = ip->ip_src;
2301 dst_ip = ip->ip_dst;
2302 if (args->eh != NULL) { /* layer 2 packets are as on the wire */
2303 offset = ntohs(ip->ip_off) & IP_OFFMASK;
2304 ip_len = ntohs(ip->ip_len);
2306 offset = ip->ip_off & IP_OFFMASK;
2307 ip_len = ip->ip_len;
2309 pktlen = ip_len < pktlen ? ip_len : pktlen;
2314 PULLUP_TO(hlen, ulp, struct tcphdr);
2315 dst_port = TCP(ulp)->th_dport;
2316 src_port = TCP(ulp)->th_sport;
2317 args->f_id.flags = TCP(ulp)->th_flags;
2321 PULLUP_TO(hlen, ulp, struct udphdr);
2322 dst_port = UDP(ulp)->uh_dport;
2323 src_port = UDP(ulp)->uh_sport;
2327 PULLUP_TO(hlen, ulp, struct icmphdr);
2328 args->f_id.flags = ICMP(ulp)->icmp_type;
2336 args->f_id.src_ip = ntohl(src_ip.s_addr);
2337 args->f_id.dst_ip = ntohl(dst_ip.s_addr);
2340 if (proto) { /* we may have port numbers, store them */
2341 args->f_id.proto = proto;
2342 args->f_id.src_port = src_port = ntohs(src_port);
2343 args->f_id.dst_port = dst_port = ntohs(dst_port);
2347 mtag = m_tag_find(m, PACKET_TAG_DIVERT, NULL);
2350 * Packet has already been tagged. Look for the next rule
2351 * to restart processing.
2353 * If fw_one_pass != 0 then just accept it.
2354 * XXX should not happen here, but optimized out in
2358 IPFW_RUNLOCK(chain);
2359 return (IP_FW_PASS);
2362 f = args->rule->next_rule;
2364 f = lookup_next_rule(args->rule);
2367 * Find the starting rule. It can be either the first
2368 * one, or the one after divert_rule if asked so.
2370 int skipto = mtag ? divert_cookie(mtag) : 0;
2373 if (args->eh == NULL && skipto != 0) {
2374 if (skipto >= IPFW_DEFAULT_RULE) {
2375 IPFW_RUNLOCK(chain);
2376 return (IP_FW_DENY); /* invalid */
2378 while (f && f->rulenum <= skipto)
2380 if (f == NULL) { /* drop packet */
2381 IPFW_RUNLOCK(chain);
2382 return (IP_FW_DENY);
2386 /* reset divert rule to avoid confusion later */
2388 divinput_flags = divert_info(mtag) &
2389 (IP_FW_DIVERT_OUTPUT_FLAG | IP_FW_DIVERT_LOOPBACK_FLAG);
2390 m_tag_delete(m, mtag);
2394 * Now scan the rules, and parse microinstructions for each rule.
2396 for (; f; f = f->next) {
2398 uint32_t tablearg = 0;
2399 int l, cmdlen, skip_or; /* skip rest of OR block */
2402 if (set_disable & (1 << f->set) )
2406 for (l = f->cmd_len, cmd = f->cmd ; l > 0 ;
2407 l -= cmdlen, cmd += cmdlen) {
2411 * check_body is a jump target used when we find a
2412 * CHECK_STATE, and need to jump to the body of
2417 cmdlen = F_LEN(cmd);
2419 * An OR block (insn_1 || .. || insn_n) has the
2420 * F_OR bit set in all but the last instruction.
2421 * The first match will set "skip_or", and cause
2422 * the following instructions to be skipped until
2423 * past the one with the F_OR bit clear.
2425 if (skip_or) { /* skip this instruction */
2426 if ((cmd->len & F_OR) == 0)
2427 skip_or = 0; /* next one is good */
2430 match = 0; /* set to 1 if we succeed */
2432 switch (cmd->opcode) {
2434 * The first set of opcodes compares the packet's
2435 * fields with some pattern, setting 'match' if a
2436 * match is found. At the end of the loop there is
2437 * logic to deal with F_NOT and F_OR flags associated
2445 printf("ipfw: opcode %d unimplemented\n",
2453 * We only check offset == 0 && proto != 0,
2454 * as this ensures that we have a
2455 * packet with the ports info.
2459 if (is_ipv6) /* XXX to be fixed later */
2461 if (proto == IPPROTO_TCP ||
2462 proto == IPPROTO_UDP)
2463 match = check_uidgid(
2464 (ipfw_insn_u32 *)cmd,
2467 src_ip, src_port, &fw_ugid_cache,
2468 &ugid_lookup, args->inp);
2472 match = iface_match(m->m_pkthdr.rcvif,
2473 (ipfw_insn_if *)cmd);
2477 match = iface_match(oif, (ipfw_insn_if *)cmd);
2481 match = iface_match(oif ? oif :
2482 m->m_pkthdr.rcvif, (ipfw_insn_if *)cmd);
2486 if (args->eh != NULL) { /* have MAC header */
2487 u_int32_t *want = (u_int32_t *)
2488 ((ipfw_insn_mac *)cmd)->addr;
2489 u_int32_t *mask = (u_int32_t *)
2490 ((ipfw_insn_mac *)cmd)->mask;
2491 u_int32_t *hdr = (u_int32_t *)args->eh;
2494 ( want[0] == (hdr[0] & mask[0]) &&
2495 want[1] == (hdr[1] & mask[1]) &&
2496 want[2] == (hdr[2] & mask[2]) );
2501 if (args->eh != NULL) {
2503 ntohs(args->eh->ether_type);
2505 ((ipfw_insn_u16 *)cmd)->ports;
2508 for (i = cmdlen - 1; !match && i>0;
2510 match = (t>=p[0] && t<=p[1]);
2515 match = (offset != 0);
2518 case O_IN: /* "out" is "not in" */
2519 match = (oif == NULL);
2523 match = (args->eh != NULL);
2527 match = (cmd->arg1 & 1 && divinput_flags &
2528 IP_FW_DIVERT_LOOPBACK_FLAG) ||
2529 (cmd->arg1 & 2 && divinput_flags &
2530 IP_FW_DIVERT_OUTPUT_FLAG);
2535 * We do not allow an arg of 0 so the
2536 * check of "proto" only suffices.
2538 match = (proto == cmd->arg1);
2543 (((ipfw_insn_ip *)cmd)->addr.s_addr ==
2547 case O_IP_SRC_LOOKUP:
2548 case O_IP_DST_LOOKUP:
2551 (cmd->opcode == O_IP_DST_LOOKUP) ?
2552 dst_ip.s_addr : src_ip.s_addr;
2555 match = lookup_table(chain, cmd->arg1, a,
2559 if (cmdlen == F_INSN_SIZE(ipfw_insn_u32))
2561 ((ipfw_insn_u32 *)cmd)->d[0] == v;
2571 (cmd->opcode == O_IP_DST_MASK) ?
2572 dst_ip.s_addr : src_ip.s_addr;
2573 uint32_t *p = ((ipfw_insn_u32 *)cmd)->d;
2576 for (; !match && i>0; i-= 2, p+= 2)
2577 match = (p[0] == (a & p[1]));
2585 INADDR_TO_IFP(src_ip, tif);
2586 match = (tif != NULL);
2593 u_int32_t *d = (u_int32_t *)(cmd+1);
2595 cmd->opcode == O_IP_DST_SET ?
2601 addr -= d[0]; /* subtract base */
2602 match = (addr < cmd->arg1) &&
2603 ( d[ 1 + (addr>>5)] &
2604 (1<<(addr & 0x1f)) );
2610 (((ipfw_insn_ip *)cmd)->addr.s_addr ==
2618 INADDR_TO_IFP(dst_ip, tif);
2619 match = (tif != NULL);
2626 * offset == 0 && proto != 0 is enough
2627 * to guarantee that we have a
2628 * packet with port info.
2630 if ((proto==IPPROTO_UDP || proto==IPPROTO_TCP)
2633 (cmd->opcode == O_IP_SRCPORT) ?
2634 src_port : dst_port ;
2636 ((ipfw_insn_u16 *)cmd)->ports;
2639 for (i = cmdlen - 1; !match && i>0;
2641 match = (x>=p[0] && x<=p[1]);
2646 match = (offset == 0 && proto==IPPROTO_ICMP &&
2647 icmptype_match(ICMP(ulp), (ipfw_insn_u32 *)cmd) );
2652 match = is_ipv6 && offset == 0 &&
2653 proto==IPPROTO_ICMPV6 &&
2655 ICMP6(ulp)->icmp6_type,
2656 (ipfw_insn_u32 *)cmd);
2662 ipopts_match(mtod(m, struct ip *), cmd) );
2667 cmd->arg1 == mtod(m, struct ip *)->ip_v);
2673 if (is_ipv4) { /* only for IP packets */
2678 if (cmd->opcode == O_IPLEN)
2680 else if (cmd->opcode == O_IPTTL)
2681 x = mtod(m, struct ip *)->ip_ttl;
2682 else /* must be IPID */
2683 x = ntohs(mtod(m, struct ip *)->ip_id);
2685 match = (cmd->arg1 == x);
2688 /* otherwise we have ranges */
2689 p = ((ipfw_insn_u16 *)cmd)->ports;
2691 for (; !match && i>0; i--, p += 2)
2692 match = (x >= p[0] && x <= p[1]);
2696 case O_IPPRECEDENCE:
2698 (cmd->arg1 == (mtod(m, struct ip *)->ip_tos & 0xe0)) );
2703 flags_match(cmd, mtod(m, struct ip *)->ip_tos));
2707 if (proto == IPPROTO_TCP && offset == 0) {
2715 ((ip->ip_hl + tcp->th_off) << 2);
2717 match = (cmd->arg1 == x);
2720 /* otherwise we have ranges */
2721 p = ((ipfw_insn_u16 *)cmd)->ports;
2723 for (; !match && i>0; i--, p += 2)
2724 match = (x >= p[0] && x <= p[1]);
2729 match = (proto == IPPROTO_TCP && offset == 0 &&
2730 flags_match(cmd, TCP(ulp)->th_flags));
2734 match = (proto == IPPROTO_TCP && offset == 0 &&
2735 tcpopts_match(TCP(ulp), cmd));
2739 match = (proto == IPPROTO_TCP && offset == 0 &&
2740 ((ipfw_insn_u32 *)cmd)->d[0] ==
2745 match = (proto == IPPROTO_TCP && offset == 0 &&
2746 ((ipfw_insn_u32 *)cmd)->d[0] ==
2751 match = (proto == IPPROTO_TCP && offset == 0 &&
2752 cmd->arg1 == TCP(ulp)->th_win);
2756 /* reject packets which have SYN only */
2757 /* XXX should i also check for TH_ACK ? */
2758 match = (proto == IPPROTO_TCP && offset == 0 &&
2759 (TCP(ulp)->th_flags &
2760 (TH_RST | TH_ACK | TH_SYN)) != TH_SYN);
2764 struct altq_tag *at;
2765 ipfw_insn_altq *altq = (ipfw_insn_altq *)cmd;
2768 mtag = m_tag_find(m, PACKET_TAG_PF_QID, NULL);
2771 mtag = m_tag_get(PACKET_TAG_PF_QID,
2772 sizeof(struct altq_tag),
2776 * Let the packet fall back to the
2781 at = (struct altq_tag *)(mtag+1);
2782 at->qid = altq->qid;
2788 m_tag_prepend(m, mtag);
2794 ipfw_log(f, hlen, args, m,
2795 oif, offset, tablearg);
2800 match = (random()<((ipfw_insn_u32 *)cmd)->d[0]);
2804 /* Outgoing packets automatically pass/match */
2805 match = ((oif != NULL) ||
2806 (m->m_pkthdr.rcvif == NULL) ||
2810 verify_path6(&(args->f_id.src_ip6),
2811 m->m_pkthdr.rcvif) :
2813 verify_path(src_ip, m->m_pkthdr.rcvif)));
2817 /* Outgoing packets automatically pass/match */
2818 match = (hlen > 0 && ((oif != NULL) ||
2821 verify_path6(&(args->f_id.src_ip6),
2824 verify_path(src_ip, NULL)));
2828 /* Outgoing packets automatically pass/match */
2829 if (oif == NULL && hlen > 0 &&
2830 ( (is_ipv4 && in_localaddr(src_ip))
2833 in6_localaddr(&(args->f_id.src_ip6)))
2838 is_ipv6 ? verify_path6(
2839 &(args->f_id.src_ip6),
2840 m->m_pkthdr.rcvif) :
2850 match = (m_tag_find(m,
2851 PACKET_TAG_IPSEC_IN_DONE, NULL) != NULL);
2854 match = (ipsec_getnhist(m) != 0);
2856 /* otherwise no match */
2862 IN6_ARE_ADDR_EQUAL(&args->f_id.src_ip6,
2863 &((ipfw_insn_ip6 *)cmd)->addr6);
2868 IN6_ARE_ADDR_EQUAL(&args->f_id.dst_ip6,
2869 &((ipfw_insn_ip6 *)cmd)->addr6);
2871 case O_IP6_SRC_MASK:
2873 ipfw_insn_ip6 *te = (ipfw_insn_ip6 *)cmd;
2874 struct in6_addr p = args->f_id.src_ip6;
2876 APPLY_MASK(&p, &te->mask6);
2877 match = IN6_ARE_ADDR_EQUAL(&te->addr6, &p);
2881 case O_IP6_DST_MASK:
2883 ipfw_insn_ip6 *te = (ipfw_insn_ip6 *)cmd;
2884 struct in6_addr p = args->f_id.dst_ip6;
2886 APPLY_MASK(&p, &te->mask6);
2887 match = IN6_ARE_ADDR_EQUAL(&te->addr6, &p);
2892 match= is_ipv6 && search_ip6_addr_net(&args->f_id.src_ip6);
2896 match= is_ipv6 && search_ip6_addr_net(&args->f_id.dst_ip6);
2901 flow6id_match(args->f_id.flow_id6,
2902 (ipfw_insn_u32 *) cmd);
2907 (ext_hd & ((ipfw_insn *) cmd)->arg1);
2920 uint32_t tag = (cmd->arg1 == IP_FW_TABLEARG) ?
2921 tablearg : cmd->arg1;
2923 /* Packet is already tagged with this tag? */
2924 mtag = m_tag_locate(m, MTAG_IPFW, tag, NULL);
2926 /* We have `untag' action when F_NOT flag is
2927 * present. And we must remove this mtag from
2928 * mbuf and reset `match' to zero (`match' will
2929 * be inversed later).
2930 * Otherwise we should allocate new mtag and
2931 * push it into mbuf.
2933 if (cmd->len & F_NOT) { /* `untag' action */
2935 m_tag_delete(m, mtag);
2936 } else if (mtag == NULL) {
2937 if ((mtag = m_tag_alloc(MTAG_IPFW,
2938 tag, 0, M_NOWAIT)) != NULL)
2939 m_tag_prepend(m, mtag);
2941 match = (cmd->len & F_NOT) ? 0: 1;
2946 uint32_t tag = (cmd->arg1 == IP_FW_TABLEARG) ?
2947 tablearg : cmd->arg1;
2950 match = m_tag_locate(m, MTAG_IPFW,
2955 /* we have ranges */
2956 for (mtag = m_tag_first(m);
2957 mtag != NULL && !match;
2958 mtag = m_tag_next(m, mtag)) {
2962 if (mtag->m_tag_cookie != MTAG_IPFW)
2965 p = ((ipfw_insn_u16 *)cmd)->ports;
2967 for(; !match && i > 0; i--, p += 2)
2969 mtag->m_tag_id >= p[0] &&
2970 mtag->m_tag_id <= p[1];
2976 * The second set of opcodes represents 'actions',
2977 * i.e. the terminal part of a rule once the packet
2978 * matches all previous patterns.
2979 * Typically there is only one action for each rule,
2980 * and the opcode is stored at the end of the rule
2981 * (but there are exceptions -- see below).
2983 * In general, here we set retval and terminate the
2984 * outer loop (would be a 'break 3' in some language,
2985 * but we need to do a 'goto done').
2988 * O_COUNT and O_SKIPTO actions:
2989 * instead of terminating, we jump to the next rule
2990 * ('goto next_rule', equivalent to a 'break 2'),
2991 * or to the SKIPTO target ('goto again' after
2992 * having set f, cmd and l), respectively.
2994 * O_TAG, O_LOG and O_ALTQ action parameters:
2995 * perform some action and set match = 1;
2997 * O_LIMIT and O_KEEP_STATE: these opcodes are
2998 * not real 'actions', and are stored right
2999 * before the 'action' part of the rule.
3000 * These opcodes try to install an entry in the
3001 * state tables; if successful, we continue with
3002 * the next opcode (match=1; break;), otherwise
3003 * the packet * must be dropped
3004 * ('goto done' after setting retval);
3006 * O_PROBE_STATE and O_CHECK_STATE: these opcodes
3007 * cause a lookup of the state table, and a jump
3008 * to the 'action' part of the parent rule
3009 * ('goto check_body') if an entry is found, or
3010 * (CHECK_STATE only) a jump to the next rule if
3011 * the entry is not found ('goto next_rule').
3012 * The result of the lookup is cached to make
3013 * further instances of these opcodes are
3018 if (install_state(f,
3019 (ipfw_insn_limit *)cmd, args, tablearg)) {
3020 retval = IP_FW_DENY;
3021 goto done; /* error/limit violation */
3029 * dynamic rules are checked at the first
3030 * keep-state or check-state occurrence,
3031 * with the result being stored in dyn_dir.
3032 * The compiler introduces a PROBE_STATE
3033 * instruction for us when we have a
3034 * KEEP_STATE (because PROBE_STATE needs
3037 if (dyn_dir == MATCH_UNKNOWN &&
3038 (q = lookup_dyn_rule(&args->f_id,
3039 &dyn_dir, proto == IPPROTO_TCP ?
3043 * Found dynamic entry, update stats
3044 * and jump to the 'action' part of
3050 cmd = ACTION_PTR(f);
3051 l = f->cmd_len - f->act_ofs;
3056 * Dynamic entry not found. If CHECK_STATE,
3057 * skip to next rule, if PROBE_STATE just
3058 * ignore and continue with next opcode.
3060 if (cmd->opcode == O_CHECK_STATE)
3066 retval = 0; /* accept */
3071 args->rule = f; /* report matching rule */
3072 if (cmd->arg1 == IP_FW_TABLEARG)
3073 args->cookie = tablearg;
3075 args->cookie = cmd->arg1;
3076 retval = IP_FW_DUMMYNET;
3081 struct divert_tag *dt;
3083 if (args->eh) /* not on layer 2 */
3085 mtag = m_tag_get(PACKET_TAG_DIVERT,
3086 sizeof(struct divert_tag),
3091 IPFW_RUNLOCK(chain);
3092 return (IP_FW_DENY);
3094 dt = (struct divert_tag *)(mtag+1);
3095 dt->cookie = f->rulenum;
3096 if (cmd->arg1 == IP_FW_TABLEARG)
3097 dt->info = tablearg;
3099 dt->info = cmd->arg1;
3100 m_tag_prepend(m, mtag);
3101 retval = (cmd->opcode == O_DIVERT) ?
3102 IP_FW_DIVERT : IP_FW_TEE;
3108 f->pcnt++; /* update stats */
3110 f->timestamp = time_uptime;
3111 if (cmd->opcode == O_COUNT)
3114 if (f->next_rule == NULL)
3115 lookup_next_rule(f);
3121 * Drop the packet and send a reject notice
3122 * if the packet is not ICMP (or is an ICMP
3123 * query), and it is not multicast/broadcast.
3125 if (hlen > 0 && is_ipv4 && offset == 0 &&
3126 (proto != IPPROTO_ICMP ||
3127 is_icmp_query(ICMP(ulp))) &&
3128 !(m->m_flags & (M_BCAST|M_MCAST)) &&
3129 !IN_MULTICAST(ntohl(dst_ip.s_addr))) {
3130 send_reject(args, cmd->arg1, ip_len);
3136 if (hlen > 0 && is_ipv6 &&
3137 ((offset & IP6F_OFF_MASK) == 0) &&
3138 (proto != IPPROTO_ICMPV6 ||
3139 (is_icmp6_query(args->f_id.flags) == 1)) &&
3140 !(m->m_flags & (M_BCAST|M_MCAST)) &&
3141 !IN6_IS_ADDR_MULTICAST(&args->f_id.dst_ip6)) {
3142 send_reject6(args, cmd->arg1, hlen);
3148 retval = IP_FW_DENY;
3151 case O_FORWARD_IP: {
3152 struct sockaddr_in *sa;
3153 sa = &(((ipfw_insn_sa *)cmd)->sa);
3154 if (args->eh) /* not valid on layer2 pkts */
3156 if (!q || dyn_dir == MATCH_FORWARD) {
3157 if (sa->sin_addr.s_addr == INADDR_ANY) {
3158 bcopy(sa, &args->hopstore,
3160 args->hopstore.sin_addr.s_addr =
3165 args->next_hop = sa;
3168 retval = IP_FW_PASS;
3174 args->rule = f; /* report matching rule */
3175 if (cmd->arg1 == IP_FW_TABLEARG)
3176 args->cookie = tablearg;
3178 args->cookie = cmd->arg1;
3179 retval = (cmd->opcode == O_NETGRAPH) ?
3180 IP_FW_NETGRAPH : IP_FW_NGTEE;
3184 panic("-- unknown opcode %d\n", cmd->opcode);
3185 } /* end of switch() on opcodes */
3187 if (cmd->len & F_NOT)
3191 if (cmd->len & F_OR)
3194 if (!(cmd->len & F_OR)) /* not an OR block, */
3195 break; /* try next rule */
3198 } /* end of inner for, scan opcodes */
3200 next_rule:; /* try next rule */
3202 } /* end of outer for, scan rules */
3203 printf("ipfw: ouch!, skip past end of rules, denying packet\n");
3204 IPFW_RUNLOCK(chain);
3205 return (IP_FW_DENY);
3208 /* Update statistics */
3211 f->timestamp = time_uptime;
3212 IPFW_RUNLOCK(chain);
3217 printf("ipfw: pullup failed\n");
3218 return (IP_FW_DENY);
3222 * When a rule is added/deleted, clear the next_rule pointers in all rules.
3223 * These will be reconstructed on the fly as packets are matched.
3226 flush_rule_ptrs(struct ip_fw_chain *chain)
3230 IPFW_WLOCK_ASSERT(chain);
3232 for (rule = chain->rules; rule; rule = rule->next)
3233 rule->next_rule = NULL;
3237 * Add a new rule to the list. Copy the rule into a malloc'ed area, then
3238 * possibly create a rule number and add the rule to the list.
3239 * Update the rule_number in the input struct so the caller knows it as well.
3242 add_rule(struct ip_fw_chain *chain, struct ip_fw *input_rule)
3244 struct ip_fw *rule, *f, *prev;
3245 int l = RULESIZE(input_rule);
3247 if (chain->rules == NULL && input_rule->rulenum != IPFW_DEFAULT_RULE)
3250 rule = malloc(l, M_IPFW, M_NOWAIT | M_ZERO);
3254 bcopy(input_rule, rule, l);
3257 rule->next_rule = NULL;
3261 rule->timestamp = 0;
3265 if (chain->rules == NULL) { /* default rule */
3266 chain->rules = rule;
3271 * If rulenum is 0, find highest numbered rule before the
3272 * default rule, and add autoinc_step
3274 if (autoinc_step < 1)
3276 else if (autoinc_step > 1000)
3277 autoinc_step = 1000;
3278 if (rule->rulenum == 0) {
3280 * locate the highest numbered rule before default
3282 for (f = chain->rules; f; f = f->next) {
3283 if (f->rulenum == IPFW_DEFAULT_RULE)
3285 rule->rulenum = f->rulenum;
3287 if (rule->rulenum < IPFW_DEFAULT_RULE - autoinc_step)
3288 rule->rulenum += autoinc_step;
3289 input_rule->rulenum = rule->rulenum;
3293 * Now insert the new rule in the right place in the sorted list.
3295 for (prev = NULL, f = chain->rules; f; prev = f, f = f->next) {
3296 if (f->rulenum > rule->rulenum) { /* found the location */
3300 } else { /* head insert */
3301 rule->next = chain->rules;
3302 chain->rules = rule;
3307 flush_rule_ptrs(chain);
3311 IPFW_WUNLOCK(chain);
3312 DEB(printf("ipfw: installed rule %d, static count now %d\n",
3313 rule->rulenum, static_count);)
3318 * Remove a static rule (including derived * dynamic rules)
3319 * and place it on the ``reap list'' for later reclamation.
3320 * The caller is in charge of clearing rule pointers to avoid
3321 * dangling pointers.
3322 * @return a pointer to the next entry.
3323 * Arguments are not checked, so they better be correct.
3325 static struct ip_fw *
3326 remove_rule(struct ip_fw_chain *chain, struct ip_fw *rule, struct ip_fw *prev)
3329 int l = RULESIZE(rule);
3331 IPFW_WLOCK_ASSERT(chain);
3335 remove_dyn_rule(rule, NULL /* force removal */);
3344 rule->next = chain->reap;
3351 * Reclaim storage associated with a list of rules. This is
3352 * typically the list created using remove_rule.
3355 reap_rules(struct ip_fw *head)
3359 while ((rule = head) != NULL) {
3361 if (DUMMYNET_LOADED)
3362 ip_dn_ruledel_ptr(rule);
3368 * Remove all rules from a chain (except rules in set RESVD_SET
3369 * unless kill_default = 1). The caller is responsible for
3370 * reclaiming storage for the rules left in chain->reap.
3373 free_chain(struct ip_fw_chain *chain, int kill_default)
3375 struct ip_fw *prev, *rule;
3377 IPFW_WLOCK_ASSERT(chain);
3379 flush_rule_ptrs(chain); /* more efficient to do outside the loop */
3380 for (prev = NULL, rule = chain->rules; rule ; )
3381 if (kill_default || rule->set != RESVD_SET)
3382 rule = remove_rule(chain, rule, prev);
3390 * Remove all rules with given number, and also do set manipulation.
3391 * Assumes chain != NULL && *chain != NULL.
3393 * The argument is an u_int32_t. The low 16 bit are the rule or set number,
3394 * the next 8 bits are the new set, the top 8 bits are the command:
3396 * 0 delete rules with given number
3397 * 1 delete rules with given set number
3398 * 2 move rules with given number to new set
3399 * 3 move rules with given set number to new set
3400 * 4 swap sets with given numbers
3403 del_entry(struct ip_fw_chain *chain, u_int32_t arg)
3405 struct ip_fw *prev = NULL, *rule;
3406 u_int16_t rulenum; /* rule or old_set */
3407 u_int8_t cmd, new_set;
3409 rulenum = arg & 0xffff;
3410 cmd = (arg >> 24) & 0xff;
3411 new_set = (arg >> 16) & 0xff;
3415 if (new_set > RESVD_SET)
3417 if (cmd == 0 || cmd == 2) {
3418 if (rulenum >= IPFW_DEFAULT_RULE)
3421 if (rulenum > RESVD_SET) /* old_set */
3426 rule = chain->rules;
3429 case 0: /* delete rules with given number */
3431 * locate first rule to delete
3433 for (; rule->rulenum < rulenum; prev = rule, rule = rule->next)
3435 if (rule->rulenum != rulenum) {
3436 IPFW_WUNLOCK(chain);
3441 * flush pointers outside the loop, then delete all matching
3442 * rules. prev remains the same throughout the cycle.
3444 flush_rule_ptrs(chain);
3445 while (rule->rulenum == rulenum)
3446 rule = remove_rule(chain, rule, prev);
3449 case 1: /* delete all rules with given set number */
3450 flush_rule_ptrs(chain);
3451 rule = chain->rules;
3452 while (rule->rulenum < IPFW_DEFAULT_RULE)
3453 if (rule->set == rulenum)
3454 rule = remove_rule(chain, rule, prev);
3461 case 2: /* move rules with given number to new set */
3462 rule = chain->rules;
3463 for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
3464 if (rule->rulenum == rulenum)
3465 rule->set = new_set;
3468 case 3: /* move rules with given set number to new set */
3469 for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
3470 if (rule->set == rulenum)
3471 rule->set = new_set;
3474 case 4: /* swap two sets */
3475 for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
3476 if (rule->set == rulenum)
3477 rule->set = new_set;
3478 else if (rule->set == new_set)
3479 rule->set = rulenum;
3483 * Look for rules to reclaim. We grab the list before
3484 * releasing the lock then reclaim them w/o the lock to
3485 * avoid a LOR with dummynet.
3489 IPFW_WUNLOCK(chain);
3496 * Clear counters for a specific rule.
3497 * The enclosing "table" is assumed locked.
3500 clear_counters(struct ip_fw *rule, int log_only)
3502 ipfw_insn_log *l = (ipfw_insn_log *)ACTION_PTR(rule);
3504 if (log_only == 0) {
3505 rule->bcnt = rule->pcnt = 0;
3506 rule->timestamp = 0;
3508 if (l->o.opcode == O_LOG)
3509 l->log_left = l->max_log;
3513 * Reset some or all counters on firewall rules.
3514 * @arg frwl is null to clear all entries, or contains a specific
3516 * @arg log_only is 1 if we only want to reset logs, zero otherwise.
3519 zero_entry(struct ip_fw_chain *chain, int rulenum, int log_only)
3527 for (rule = chain->rules; rule; rule = rule->next)
3528 clear_counters(rule, log_only);
3529 msg = log_only ? "ipfw: All logging counts reset.\n" :
3530 "ipfw: Accounting cleared.\n";
3534 * We can have multiple rules with the same number, so we
3535 * need to clear them all.
3537 for (rule = chain->rules; rule; rule = rule->next)
3538 if (rule->rulenum == rulenum) {
3539 while (rule && rule->rulenum == rulenum) {
3540 clear_counters(rule, log_only);
3546 if (!cleared) { /* we did not find any matching rules */
3547 IPFW_WUNLOCK(chain);
3550 msg = log_only ? "ipfw: Entry %d logging count reset.\n" :
3551 "ipfw: Entry %d cleared.\n";
3553 IPFW_WUNLOCK(chain);
3556 log(LOG_SECURITY | LOG_NOTICE, msg, rulenum);
3561 * Check validity of the structure before insert.
3562 * Fortunately rules are simple, so this mostly need to check rule sizes.
3565 check_ipfw_struct(struct ip_fw *rule, int size)
3571 if (size < sizeof(*rule)) {
3572 printf("ipfw: rule too short\n");
3575 /* first, check for valid size */
3578 printf("ipfw: size mismatch (have %d want %d)\n", size, l);
3581 if (rule->act_ofs >= rule->cmd_len) {
3582 printf("ipfw: bogus action offset (%u > %u)\n",
3583 rule->act_ofs, rule->cmd_len - 1);
3587 * Now go for the individual checks. Very simple ones, basically only
3588 * instruction sizes.
3590 for (l = rule->cmd_len, cmd = rule->cmd ;
3591 l > 0 ; l -= cmdlen, cmd += cmdlen) {
3592 cmdlen = F_LEN(cmd);
3594 printf("ipfw: opcode %d size truncated\n",
3598 DEB(printf("ipfw: opcode %d\n", cmd->opcode);)
3599 switch (cmd->opcode) {
3611 case O_IPPRECEDENCE:
3629 if (cmdlen != F_INSN_SIZE(ipfw_insn))
3642 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32))
3647 if (cmdlen != F_INSN_SIZE(ipfw_insn_limit))
3652 if (cmdlen != F_INSN_SIZE(ipfw_insn_log))
3655 ((ipfw_insn_log *)cmd)->log_left =
3656 ((ipfw_insn_log *)cmd)->max_log;
3662 /* only odd command lengths */
3663 if ( !(cmdlen & 1) || cmdlen > 31)
3669 if (cmd->arg1 == 0 || cmd->arg1 > 256) {
3670 printf("ipfw: invalid set size %d\n",
3674 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
3679 case O_IP_SRC_LOOKUP:
3680 case O_IP_DST_LOOKUP:
3681 if (cmd->arg1 >= IPFW_TABLES_MAX) {
3682 printf("ipfw: invalid table number %d\n",
3686 if (cmdlen != F_INSN_SIZE(ipfw_insn) &&
3687 cmdlen != F_INSN_SIZE(ipfw_insn_u32))
3692 if (cmdlen != F_INSN_SIZE(ipfw_insn_mac))
3702 if (cmdlen < 1 || cmdlen > 31)
3708 case O_IP_DSTPORT: /* XXX artificial limit, 30 port pairs */
3709 if (cmdlen < 2 || cmdlen > 31)
3716 if (cmdlen != F_INSN_SIZE(ipfw_insn_if))
3721 if (cmdlen != F_INSN_SIZE(ipfw_insn_altq))
3727 if (cmdlen != F_INSN_SIZE(ipfw_insn))
3732 #ifdef IPFIREWALL_FORWARD
3733 if (cmdlen != F_INSN_SIZE(ipfw_insn_sa))
3742 if (ip_divert_ptr == NULL)
3748 if (!NG_IPFW_LOADED)
3752 case O_FORWARD_MAC: /* XXX not implemented yet */
3763 if (cmdlen != F_INSN_SIZE(ipfw_insn))
3767 printf("ipfw: opcode %d, multiple actions"
3774 printf("ipfw: opcode %d, action must be"
3783 if (cmdlen != F_INSN_SIZE(struct in6_addr) +
3784 F_INSN_SIZE(ipfw_insn))
3789 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
3790 ((ipfw_insn_u32 *)cmd)->o.arg1)
3794 case O_IP6_SRC_MASK:
3795 case O_IP6_DST_MASK:
3796 if ( !(cmdlen & 1) || cmdlen > 127)
3800 if( cmdlen != F_INSN_SIZE( ipfw_insn_icmp6 ) )
3806 switch (cmd->opcode) {
3816 case O_IP6_SRC_MASK:
3817 case O_IP6_DST_MASK:
3819 printf("ipfw: no IPv6 support in kernel\n");
3820 return EPROTONOSUPPORT;
3823 printf("ipfw: opcode %d, unknown opcode\n",
3829 if (have_action == 0) {
3830 printf("ipfw: missing action\n");
3836 printf("ipfw: opcode %d size %d wrong\n",
3837 cmd->opcode, cmdlen);
3842 * Copy the static and dynamic rules to the supplied buffer
3843 * and return the amount of space actually used.
3846 ipfw_getrules(struct ip_fw_chain *chain, void *buf, size_t space)
3849 char *ep = bp + space;
3853 /* XXX this can take a long time and locking will block packet flow */
3855 for (rule = chain->rules; rule ; rule = rule->next) {
3857 * Verify the entry fits in the buffer in case the
3858 * rules changed between calculating buffer space and
3859 * now. This would be better done using a generation
3860 * number but should suffice for now.
3865 bcopy(&set_disable, &(((struct ip_fw *)bp)->next_rule),
3866 sizeof(set_disable));
3870 IPFW_RUNLOCK(chain);
3872 ipfw_dyn_rule *p, *last = NULL;
3875 for (i = 0 ; i < curr_dyn_buckets; i++)
3876 for (p = ipfw_dyn_v[i] ; p != NULL; p = p->next) {
3877 if (bp + sizeof *p <= ep) {
3878 ipfw_dyn_rule *dst =
3879 (ipfw_dyn_rule *)bp;
3880 bcopy(p, dst, sizeof *p);
3881 bcopy(&(p->rule->rulenum), &(dst->rule),
3882 sizeof(p->rule->rulenum));
3884 * store a non-null value in "next".
3885 * The userland code will interpret a
3886 * NULL here as a marker
3887 * for the last dynamic rule.
3889 bcopy(&dst, &dst->next, sizeof(dst));
3892 TIME_LEQ(dst->expire, time_uptime) ?
3893 0 : dst->expire - time_uptime ;
3894 bp += sizeof(ipfw_dyn_rule);
3898 if (last != NULL) /* mark last dynamic rule */
3899 bzero(&last->next, sizeof(last));
3901 return (bp - (char *)buf);
3906 * {set|get}sockopt parser.
3909 ipfw_ctl(struct sockopt *sopt)
3911 #define RULE_MAXSIZE (256*sizeof(u_int32_t))
3912 int error, rule_num;
3914 struct ip_fw *buf, *rule;
3915 u_int32_t rulenum[2];
3917 error = suser(sopt->sopt_td);
3922 * Disallow modifications in really-really secure mode, but still allow
3923 * the logging counters to be reset.
3925 if (sopt->sopt_name == IP_FW_ADD ||
3926 (sopt->sopt_dir == SOPT_SET && sopt->sopt_name != IP_FW_RESETLOG)) {
3927 error = securelevel_ge(sopt->sopt_td->td_ucred, 3);
3934 switch (sopt->sopt_name) {
3937 * pass up a copy of the current rules. Static rules
3938 * come first (the last of which has number IPFW_DEFAULT_RULE),
3939 * followed by a possibly empty list of dynamic rule.
3940 * The last dynamic rule has NULL in the "next" field.
3942 * Note that the calculated size is used to bound the
3943 * amount of data returned to the user. The rule set may
3944 * change between calculating the size and returning the
3945 * data in which case we'll just return what fits.
3947 size = static_len; /* size of static rules */
3948 if (ipfw_dyn_v) /* add size of dyn.rules */
3949 size += (dyn_count * sizeof(ipfw_dyn_rule));
3952 * XXX todo: if the user passes a short length just to know
3953 * how much room is needed, do not bother filling up the
3954 * buffer, just jump to the sooptcopyout.
3956 buf = malloc(size, M_TEMP, M_WAITOK);
3957 error = sooptcopyout(sopt, buf,
3958 ipfw_getrules(&layer3_chain, buf, size));
3964 * Normally we cannot release the lock on each iteration.
3965 * We could do it here only because we start from the head all
3966 * the times so there is no risk of missing some entries.
3967 * On the other hand, the risk is that we end up with
3968 * a very inconsistent ruleset, so better keep the lock
3969 * around the whole cycle.
3971 * XXX this code can be improved by resetting the head of
3972 * the list to point to the default rule, and then freeing
3973 * the old list without the need for a lock.
3976 IPFW_WLOCK(&layer3_chain);
3977 layer3_chain.reap = NULL;
3978 free_chain(&layer3_chain, 0 /* keep default rule */);
3979 rule = layer3_chain.reap;
3980 layer3_chain.reap = NULL;
3981 IPFW_WUNLOCK(&layer3_chain);
3987 rule = malloc(RULE_MAXSIZE, M_TEMP, M_WAITOK);
3988 error = sooptcopyin(sopt, rule, RULE_MAXSIZE,
3989 sizeof(struct ip_fw) );
3991 error = check_ipfw_struct(rule, sopt->sopt_valsize);
3993 error = add_rule(&layer3_chain, rule);
3994 size = RULESIZE(rule);
3995 if (!error && sopt->sopt_dir == SOPT_GET)
3996 error = sooptcopyout(sopt, rule, size);
4003 * IP_FW_DEL is used for deleting single rules or sets,
4004 * and (ab)used to atomically manipulate sets. Argument size
4005 * is used to distinguish between the two:
4007 * delete single rule or set of rules,
4008 * or reassign rules (or sets) to a different set.
4009 * 2*sizeof(u_int32_t)
4010 * atomic disable/enable sets.
4011 * first u_int32_t contains sets to be disabled,
4012 * second u_int32_t contains sets to be enabled.
4014 error = sooptcopyin(sopt, rulenum,
4015 2*sizeof(u_int32_t), sizeof(u_int32_t));
4018 size = sopt->sopt_valsize;
4019 if (size == sizeof(u_int32_t)) /* delete or reassign */
4020 error = del_entry(&layer3_chain, rulenum[0]);
4021 else if (size == 2*sizeof(u_int32_t)) /* set enable/disable */
4023 (set_disable | rulenum[0]) & ~rulenum[1] &
4024 ~(1<<RESVD_SET); /* set RESVD_SET always enabled */
4030 case IP_FW_RESETLOG: /* argument is an int, the rule number */
4032 if (sopt->sopt_val != 0) {
4033 error = sooptcopyin(sopt, &rule_num,
4034 sizeof(int), sizeof(int));
4038 error = zero_entry(&layer3_chain, rule_num,
4039 sopt->sopt_name == IP_FW_RESETLOG);
4042 case IP_FW_TABLE_ADD:
4044 ipfw_table_entry ent;
4046 error = sooptcopyin(sopt, &ent,
4047 sizeof(ent), sizeof(ent));
4050 error = add_table_entry(&layer3_chain, ent.tbl,
4051 ent.addr, ent.masklen, ent.value);
4055 case IP_FW_TABLE_DEL:
4057 ipfw_table_entry ent;
4059 error = sooptcopyin(sopt, &ent,
4060 sizeof(ent), sizeof(ent));
4063 error = del_table_entry(&layer3_chain, ent.tbl,
4064 ent.addr, ent.masklen);
4068 case IP_FW_TABLE_FLUSH:
4072 error = sooptcopyin(sopt, &tbl,
4073 sizeof(tbl), sizeof(tbl));
4076 IPFW_WLOCK(&layer3_chain);
4077 error = flush_table(&layer3_chain, tbl);
4078 IPFW_WUNLOCK(&layer3_chain);
4082 case IP_FW_TABLE_GETSIZE:
4086 if ((error = sooptcopyin(sopt, &tbl, sizeof(tbl),
4089 IPFW_RLOCK(&layer3_chain);
4090 error = count_table(&layer3_chain, tbl, &cnt);
4091 IPFW_RUNLOCK(&layer3_chain);
4094 error = sooptcopyout(sopt, &cnt, sizeof(cnt));
4098 case IP_FW_TABLE_LIST:
4102 if (sopt->sopt_valsize < sizeof(*tbl)) {
4106 size = sopt->sopt_valsize;
4107 tbl = malloc(size, M_TEMP, M_WAITOK);
4108 error = sooptcopyin(sopt, tbl, size, sizeof(*tbl));
4113 tbl->size = (size - sizeof(*tbl)) /
4114 sizeof(ipfw_table_entry);
4115 IPFW_RLOCK(&layer3_chain);
4116 error = dump_table(&layer3_chain, tbl);
4117 IPFW_RUNLOCK(&layer3_chain);
4122 error = sooptcopyout(sopt, tbl, size);
4128 printf("ipfw: ipfw_ctl invalid option %d\n", sopt->sopt_name);
4137 * dummynet needs a reference to the default rule, because rules can be
4138 * deleted while packets hold a reference to them. When this happens,
4139 * dummynet changes the reference to the default rule (it could well be a
4140 * NULL pointer, but this way we do not need to check for the special
4141 * case, plus here he have info on the default behaviour).
4143 struct ip_fw *ip_fw_default_rule;
4146 * This procedure is only used to handle keepalives. It is invoked
4147 * every dyn_keepalive_period
4150 ipfw_tick(void * __unused unused)
4152 struct mbuf *m0, *m, *mnext, **mtailp;
4156 if (dyn_keepalive == 0 || ipfw_dyn_v == NULL || dyn_count == 0)
4160 * We make a chain of packets to go out here -- not deferring
4161 * until after we drop the IPFW dynamic rule lock would result
4162 * in a lock order reversal with the normal packet input -> ipfw
4168 for (i = 0 ; i < curr_dyn_buckets ; i++) {
4169 for (q = ipfw_dyn_v[i] ; q ; q = q->next ) {
4170 if (q->dyn_type == O_LIMIT_PARENT)
4172 if (q->id.proto != IPPROTO_TCP)
4174 if ( (q->state & BOTH_SYN) != BOTH_SYN)
4176 if (TIME_LEQ( time_uptime+dyn_keepalive_interval,
4178 continue; /* too early */
4179 if (TIME_LEQ(q->expire, time_uptime))
4180 continue; /* too late, rule expired */
4182 *mtailp = send_pkt(&(q->id), q->ack_rev - 1,
4183 q->ack_fwd, TH_SYN);
4184 if (*mtailp != NULL)
4185 mtailp = &(*mtailp)->m_nextpkt;
4186 *mtailp = send_pkt(&(q->id), q->ack_fwd - 1,
4188 if (*mtailp != NULL)
4189 mtailp = &(*mtailp)->m_nextpkt;
4193 for (m = mnext = m0; m != NULL; m = mnext) {
4194 mnext = m->m_nextpkt;
4195 m->m_nextpkt = NULL;
4196 ip_output(m, NULL, NULL, 0, NULL, NULL);
4199 callout_reset(&ipfw_timeout, dyn_keepalive_period*hz, ipfw_tick, NULL);
4205 struct ip_fw default_rule;
4209 /* Setup IPv6 fw sysctl tree. */
4210 sysctl_ctx_init(&ip6_fw_sysctl_ctx);
4211 ip6_fw_sysctl_tree = SYSCTL_ADD_NODE(&ip6_fw_sysctl_ctx,
4212 SYSCTL_STATIC_CHILDREN(_net_inet6_ip6), OID_AUTO, "fw",
4213 CTLFLAG_RW | CTLFLAG_SECURE, 0, "Firewall");
4214 SYSCTL_ADD_PROC(&ip6_fw_sysctl_ctx, SYSCTL_CHILDREN(ip6_fw_sysctl_tree),
4215 OID_AUTO, "enable", CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE3,
4216 &fw6_enable, 0, ipfw_chg_hook, "I", "Enable ipfw+6");
4217 SYSCTL_ADD_INT(&ip6_fw_sysctl_ctx, SYSCTL_CHILDREN(ip6_fw_sysctl_tree),
4218 OID_AUTO, "deny_unknown_exthdrs", CTLFLAG_RW | CTLFLAG_SECURE,
4219 &fw_deny_unknown_exthdrs, 0,
4220 "Deny packets with unknown IPv6 Extension Headers");
4223 layer3_chain.rules = NULL;
4224 IPFW_LOCK_INIT(&layer3_chain);
4225 ipfw_dyn_rule_zone = uma_zcreate("IPFW dynamic rule zone",
4226 sizeof(ipfw_dyn_rule), NULL, NULL, NULL, NULL,
4228 IPFW_DYN_LOCK_INIT();
4229 callout_init(&ipfw_timeout, NET_CALLOUT_MPSAFE);
4231 bzero(&default_rule, sizeof default_rule);
4233 default_rule.act_ofs = 0;
4234 default_rule.rulenum = IPFW_DEFAULT_RULE;
4235 default_rule.cmd_len = 1;
4236 default_rule.set = RESVD_SET;
4238 default_rule.cmd[0].len = 1;
4239 default_rule.cmd[0].opcode =
4240 #ifdef IPFIREWALL_DEFAULT_TO_ACCEPT
4245 error = add_rule(&layer3_chain, &default_rule);
4247 printf("ipfw2: error %u initializing default rule "
4248 "(support disabled)\n", error);
4249 IPFW_DYN_LOCK_DESTROY();
4250 IPFW_LOCK_DESTROY(&layer3_chain);
4251 uma_zdestroy(ipfw_dyn_rule_zone);
4255 ip_fw_default_rule = layer3_chain.rules;
4260 "initialized, divert %s, "
4261 "rule-based forwarding "
4262 #ifdef IPFIREWALL_FORWARD
4267 "default to %s, logging ",
4273 default_rule.cmd[0].opcode == O_ACCEPT ? "accept" : "deny");
4275 #ifdef IPFIREWALL_VERBOSE
4278 #ifdef IPFIREWALL_VERBOSE_LIMIT
4279 verbose_limit = IPFIREWALL_VERBOSE_LIMIT;
4281 if (fw_verbose == 0)
4282 printf("disabled\n");
4283 else if (verbose_limit == 0)
4284 printf("unlimited\n");
4286 printf("limited to %d packets/entry by default\n",
4289 error = init_tables(&layer3_chain);
4291 IPFW_DYN_LOCK_DESTROY();
4292 IPFW_LOCK_DESTROY(&layer3_chain);
4293 uma_zdestroy(ipfw_dyn_rule_zone);
4296 ip_fw_ctl_ptr = ipfw_ctl;
4297 ip_fw_chk_ptr = ipfw_chk;
4298 callout_reset(&ipfw_timeout, hz, ipfw_tick, NULL);
4308 ip_fw_chk_ptr = NULL;
4309 ip_fw_ctl_ptr = NULL;
4310 callout_drain(&ipfw_timeout);
4311 IPFW_WLOCK(&layer3_chain);
4312 flush_tables(&layer3_chain);
4313 layer3_chain.reap = NULL;
4314 free_chain(&layer3_chain, 1 /* kill default rule */);
4315 reap = layer3_chain.reap, layer3_chain.reap = NULL;
4316 IPFW_WUNLOCK(&layer3_chain);
4319 IPFW_DYN_LOCK_DESTROY();
4320 uma_zdestroy(ipfw_dyn_rule_zone);
4321 IPFW_LOCK_DESTROY(&layer3_chain);
4324 /* Free IPv6 fw sysctl tree. */
4325 sysctl_ctx_free(&ip6_fw_sysctl_ctx);
4328 printf("IP firewall unloaded\n");