2 * Copyright (c) 2002 Luigi Rizzo, Universita` di Pisa
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
13 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
14 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
16 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
17 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
19 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
20 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
21 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * Implement IP packet firewall (new version)
35 #if !defined(KLD_MODULE)
37 #include "opt_ip6fw.h"
40 #include "opt_inet6.h"
41 #include "opt_ipsec.h"
43 #error IPFIREWALL requires INET.
47 #include <sys/param.h>
48 #include <sys/systm.h>
49 #include <sys/condvar.h>
50 #include <sys/malloc.h>
52 #include <sys/kernel.h>
54 #include <sys/module.h>
56 #include <sys/socket.h>
57 #include <sys/socketvar.h>
58 #include <sys/sysctl.h>
59 #include <sys/syslog.h>
60 #include <sys/ucred.h>
62 #include <net/radix.h>
63 #include <net/route.h>
64 #include <netinet/in.h>
65 #include <netinet/in_systm.h>
66 #include <netinet/in_var.h>
67 #include <netinet/in_pcb.h>
68 #include <netinet/ip.h>
69 #include <netinet/ip_var.h>
70 #include <netinet/ip_icmp.h>
71 #include <netinet/ip_fw.h>
72 #include <netinet/ip_divert.h>
73 #include <netinet/ip_dummynet.h>
74 #include <netinet/tcp.h>
75 #include <netinet/tcp_timer.h>
76 #include <netinet/tcp_var.h>
77 #include <netinet/tcpip.h>
78 #include <netinet/udp.h>
79 #include <netinet/udp_var.h>
81 #include <netgraph/ng_ipfw.h>
83 #include <altq/if_altq.h>
86 #include <netinet6/ipsec.h>
89 #include <netinet/ip6.h>
90 #include <netinet/icmp6.h>
92 #include <netinet6/scope6_var.h>
95 #include <netinet/if_ether.h> /* XXX for ETHERTYPE_IP */
97 #include <machine/in_cksum.h> /* XXX for in_cksum */
100 * set_disable contains one bit per set value (0..31).
101 * If the bit is set, all rules with the corresponding set
102 * are disabled. Set RESVD_SET(31) is reserved for the default rule
103 * and rules that are not deleted by the flush command,
104 * and CANNOT be disabled.
105 * Rules in set RESVD_SET can only be deleted explicitly.
107 static u_int32_t set_disable;
109 static int fw_verbose;
110 static int verbose_limit;
112 static struct callout ipfw_timeout;
113 static uma_zone_t ipfw_dyn_rule_zone;
114 #define IPFW_DEFAULT_RULE 65535
117 * Data structure to cache our ucred related
118 * information. This structure only gets used if
119 * the user specified UID/GID based constraints in
123 gid_t fw_groups[NGROUPS];
130 struct ip_fw *rules; /* list of rules */
131 struct ip_fw *reap; /* list of rules to reap */
132 struct mtx mtx; /* lock guarding rule list */
133 int busy_count; /* busy count for rw locks */
137 #define IPFW_LOCK_INIT(_chain) \
138 mtx_init(&(_chain)->mtx, "IPFW static rules", NULL, \
139 MTX_DEF | MTX_RECURSE)
140 #define IPFW_LOCK_DESTROY(_chain) mtx_destroy(&(_chain)->mtx)
141 #define IPFW_WLOCK_ASSERT(_chain) do { \
142 mtx_assert(&(_chain)->mtx, MA_OWNED); \
143 NET_ASSERT_GIANT(); \
147 IPFW_RLOCK(struct ip_fw_chain *chain)
149 mtx_lock(&chain->mtx);
151 mtx_unlock(&chain->mtx);
155 IPFW_RUNLOCK(struct ip_fw_chain *chain)
157 mtx_lock(&chain->mtx);
159 if (chain->busy_count == 0 && chain->want_write)
160 cv_signal(&chain->cv);
161 mtx_unlock(&chain->mtx);
165 IPFW_WLOCK(struct ip_fw_chain *chain)
167 mtx_lock(&chain->mtx);
169 while (chain->busy_count > 0)
170 cv_wait(&chain->cv, &chain->mtx);
174 IPFW_WUNLOCK(struct ip_fw_chain *chain)
177 cv_signal(&chain->cv);
178 mtx_unlock(&chain->mtx);
182 * list of rules for layer 3
184 static struct ip_fw_chain layer3_chain;
186 MALLOC_DEFINE(M_IPFW, "IpFw/IpAcct", "IpFw/IpAcct chain's");
187 MALLOC_DEFINE(M_IPFW_TBL, "ipfw_tbl", "IpFw tables");
190 struct radix_node rn[2];
191 struct sockaddr_in addr, mask;
195 #define IPFW_TABLES_MAX 128
196 static struct ip_fw_table {
197 struct radix_node_head *rnh;
201 u_int32_t last_value;
202 } ipfw_tables[IPFW_TABLES_MAX];
204 static int fw_debug = 1;
205 static int autoinc_step = 100; /* bounded to 1..1000 in add_rule() */
208 SYSCTL_NODE(_net_inet_ip, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall");
209 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, enable,
210 CTLFLAG_RW | CTLFLAG_SECURE3,
211 &fw_enable, 0, "Enable ipfw");
212 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, autoinc_step, CTLFLAG_RW,
213 &autoinc_step, 0, "Rule number autincrement step");
214 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, one_pass,
215 CTLFLAG_RW | CTLFLAG_SECURE3,
217 "Only do a single pass through ipfw when using dummynet(4)");
218 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, debug, CTLFLAG_RW,
219 &fw_debug, 0, "Enable printing of debug ip_fw statements");
220 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose,
221 CTLFLAG_RW | CTLFLAG_SECURE3,
222 &fw_verbose, 0, "Log matches to ipfw rules");
223 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose_limit, CTLFLAG_RW,
224 &verbose_limit, 0, "Set upper limit of matches of ipfw rules logged");
227 * Description of dynamic rules.
229 * Dynamic rules are stored in lists accessed through a hash table
230 * (ipfw_dyn_v) whose size is curr_dyn_buckets. This value can
231 * be modified through the sysctl variable dyn_buckets which is
232 * updated when the table becomes empty.
234 * XXX currently there is only one list, ipfw_dyn.
236 * When a packet is received, its address fields are first masked
237 * with the mask defined for the rule, then hashed, then matched
238 * against the entries in the corresponding list.
239 * Dynamic rules can be used for different purposes:
241 * + enforcing limits on the number of sessions;
242 * + in-kernel NAT (not implemented yet)
244 * The lifetime of dynamic rules is regulated by dyn_*_lifetime,
245 * measured in seconds and depending on the flags.
247 * The total number of dynamic rules is stored in dyn_count.
248 * The max number of dynamic rules is dyn_max. When we reach
249 * the maximum number of rules we do not create anymore. This is
250 * done to avoid consuming too much memory, but also too much
251 * time when searching on each packet (ideally, we should try instead
252 * to put a limit on the length of the list on each bucket...).
254 * Each dynamic rule holds a pointer to the parent ipfw rule so
255 * we know what action to perform. Dynamic rules are removed when
256 * the parent rule is deleted. XXX we should make them survive.
258 * There are some limitations with dynamic rules -- we do not
259 * obey the 'randomized match', and we do not do multiple
260 * passes through the firewall. XXX check the latter!!!
262 static ipfw_dyn_rule **ipfw_dyn_v = NULL;
263 static u_int32_t dyn_buckets = 256; /* must be power of 2 */
264 static u_int32_t curr_dyn_buckets = 256; /* must be power of 2 */
266 static struct mtx ipfw_dyn_mtx; /* mutex guarding dynamic rules */
267 #define IPFW_DYN_LOCK_INIT() \
268 mtx_init(&ipfw_dyn_mtx, "IPFW dynamic rules", NULL, MTX_DEF)
269 #define IPFW_DYN_LOCK_DESTROY() mtx_destroy(&ipfw_dyn_mtx)
270 #define IPFW_DYN_LOCK() mtx_lock(&ipfw_dyn_mtx)
271 #define IPFW_DYN_UNLOCK() mtx_unlock(&ipfw_dyn_mtx)
272 #define IPFW_DYN_LOCK_ASSERT() mtx_assert(&ipfw_dyn_mtx, MA_OWNED)
275 * Timeouts for various events in handing dynamic rules.
277 static u_int32_t dyn_ack_lifetime = 300;
278 static u_int32_t dyn_syn_lifetime = 20;
279 static u_int32_t dyn_fin_lifetime = 1;
280 static u_int32_t dyn_rst_lifetime = 1;
281 static u_int32_t dyn_udp_lifetime = 10;
282 static u_int32_t dyn_short_lifetime = 5;
285 * Keepalives are sent if dyn_keepalive is set. They are sent every
286 * dyn_keepalive_period seconds, in the last dyn_keepalive_interval
287 * seconds of lifetime of a rule.
288 * dyn_rst_lifetime and dyn_fin_lifetime should be strictly lower
289 * than dyn_keepalive_period.
292 static u_int32_t dyn_keepalive_interval = 20;
293 static u_int32_t dyn_keepalive_period = 5;
294 static u_int32_t dyn_keepalive = 1; /* do send keepalives */
296 static u_int32_t static_count; /* # of static rules */
297 static u_int32_t static_len; /* size in bytes of static rules */
298 static u_int32_t dyn_count; /* # of dynamic rules */
299 static u_int32_t dyn_max = 4096; /* max # of dynamic rules */
301 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_buckets, CTLFLAG_RW,
302 &dyn_buckets, 0, "Number of dyn. buckets");
303 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, curr_dyn_buckets, CTLFLAG_RD,
304 &curr_dyn_buckets, 0, "Current Number of dyn. buckets");
305 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_count, CTLFLAG_RD,
306 &dyn_count, 0, "Number of dyn. rules");
307 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_max, CTLFLAG_RW,
308 &dyn_max, 0, "Max number of dyn. rules");
309 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, static_count, CTLFLAG_RD,
310 &static_count, 0, "Number of static rules");
311 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_ack_lifetime, CTLFLAG_RW,
312 &dyn_ack_lifetime, 0, "Lifetime of dyn. rules for acks");
313 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_syn_lifetime, CTLFLAG_RW,
314 &dyn_syn_lifetime, 0, "Lifetime of dyn. rules for syn");
315 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_fin_lifetime, CTLFLAG_RW,
316 &dyn_fin_lifetime, 0, "Lifetime of dyn. rules for fin");
317 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_rst_lifetime, CTLFLAG_RW,
318 &dyn_rst_lifetime, 0, "Lifetime of dyn. rules for rst");
319 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_udp_lifetime, CTLFLAG_RW,
320 &dyn_udp_lifetime, 0, "Lifetime of dyn. rules for UDP");
321 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_short_lifetime, CTLFLAG_RW,
322 &dyn_short_lifetime, 0, "Lifetime of dyn. rules for other situations");
323 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_keepalive, CTLFLAG_RW,
324 &dyn_keepalive, 0, "Enable keepalives for dyn. rules");
328 * IPv6 specific variables
330 SYSCTL_DECL(_net_inet6_ip6);
332 static struct sysctl_ctx_list ip6_fw_sysctl_ctx;
333 static struct sysctl_oid *ip6_fw_sysctl_tree;
335 #endif /* SYSCTL_NODE */
337 static int fw_deny_unknown_exthdrs = 1;
341 * L3HDR maps an ipv4 pointer into a layer3 header pointer of type T
342 * Other macros just cast void * into the appropriate type
344 #define L3HDR(T, ip) ((T *)((u_int32_t *)(ip) + (ip)->ip_hl))
345 #define TCP(p) ((struct tcphdr *)(p))
346 #define UDP(p) ((struct udphdr *)(p))
347 #define ICMP(p) ((struct icmphdr *)(p))
348 #define ICMP6(p) ((struct icmp6_hdr *)(p))
351 icmptype_match(struct icmphdr *icmp, ipfw_insn_u32 *cmd)
353 int type = icmp->icmp_type;
355 return (type <= ICMP_MAXTYPE && (cmd->d[0] & (1<<type)) );
358 #define TT ( (1 << ICMP_ECHO) | (1 << ICMP_ROUTERSOLICIT) | \
359 (1 << ICMP_TSTAMP) | (1 << ICMP_IREQ) | (1 << ICMP_MASKREQ) )
362 is_icmp_query(struct icmphdr *icmp)
364 int type = icmp->icmp_type;
366 return (type <= ICMP_MAXTYPE && (TT & (1<<type)) );
371 * The following checks use two arrays of 8 or 16 bits to store the
372 * bits that we want set or clear, respectively. They are in the
373 * low and high half of cmd->arg1 or cmd->d[0].
375 * We scan options and store the bits we find set. We succeed if
377 * (want_set & ~bits) == 0 && (want_clear & ~bits) == want_clear
379 * The code is sometimes optimized not to store additional variables.
383 flags_match(ipfw_insn *cmd, u_int8_t bits)
388 if ( ((cmd->arg1 & 0xff) & bits) != 0)
389 return 0; /* some bits we want set were clear */
390 want_clear = (cmd->arg1 >> 8) & 0xff;
391 if ( (want_clear & bits) != want_clear)
392 return 0; /* some bits we want clear were set */
397 ipopts_match(struct ip *ip, ipfw_insn *cmd)
399 int optlen, bits = 0;
400 u_char *cp = (u_char *)(ip + 1);
401 int x = (ip->ip_hl << 2) - sizeof (struct ip);
403 for (; x > 0; x -= optlen, cp += optlen) {
404 int opt = cp[IPOPT_OPTVAL];
406 if (opt == IPOPT_EOL)
408 if (opt == IPOPT_NOP)
411 optlen = cp[IPOPT_OLEN];
412 if (optlen <= 0 || optlen > x)
413 return 0; /* invalid or truncated */
421 bits |= IP_FW_IPOPT_LSRR;
425 bits |= IP_FW_IPOPT_SSRR;
429 bits |= IP_FW_IPOPT_RR;
433 bits |= IP_FW_IPOPT_TS;
437 return (flags_match(cmd, bits));
441 tcpopts_match(struct tcphdr *tcp, ipfw_insn *cmd)
443 int optlen, bits = 0;
444 u_char *cp = (u_char *)(tcp + 1);
445 int x = (tcp->th_off << 2) - sizeof(struct tcphdr);
447 for (; x > 0; x -= optlen, cp += optlen) {
449 if (opt == TCPOPT_EOL)
451 if (opt == TCPOPT_NOP)
465 bits |= IP_FW_TCPOPT_MSS;
469 bits |= IP_FW_TCPOPT_WINDOW;
472 case TCPOPT_SACK_PERMITTED:
474 bits |= IP_FW_TCPOPT_SACK;
477 case TCPOPT_TIMESTAMP:
478 bits |= IP_FW_TCPOPT_TS;
483 return (flags_match(cmd, bits));
487 iface_match(struct ifnet *ifp, ipfw_insn_if *cmd)
489 if (ifp == NULL) /* no iface with this packet, match fails */
491 /* Check by name or by IP address */
492 if (cmd->name[0] != '\0') { /* match by name */
495 if (fnmatch(cmd->name, ifp->if_xname, 0) == 0)
498 if (strncmp(ifp->if_xname, cmd->name, IFNAMSIZ) == 0)
505 TAILQ_FOREACH(ia, &ifp->if_addrhead, ifa_link) {
506 if (ia->ifa_addr == NULL)
508 if (ia->ifa_addr->sa_family != AF_INET)
510 if (cmd->p.ip.s_addr == ((struct sockaddr_in *)
511 (ia->ifa_addr))->sin_addr.s_addr)
512 return(1); /* match */
515 return(0); /* no match, fail ... */
519 * The verify_path function checks if a route to the src exists and
520 * if it is reachable via ifp (when provided).
522 * The 'verrevpath' option checks that the interface that an IP packet
523 * arrives on is the same interface that traffic destined for the
524 * packet's source address would be routed out of. The 'versrcreach'
525 * option just checks that the source address is reachable via any route
526 * (except default) in the routing table. These two are a measure to block
527 * forged packets. This is also commonly known as "anti-spoofing" or Unicast
528 * Reverse Path Forwarding (Unicast RFP) in Cisco-ese. The name of the knobs
529 * is purposely reminiscent of the Cisco IOS command,
531 * ip verify unicast reverse-path
532 * ip verify unicast source reachable-via any
534 * which implements the same functionality. But note that syntax is
535 * misleading. The check may be performed on all IP packets whether unicast,
536 * multicast, or broadcast.
539 verify_path(struct in_addr src, struct ifnet *ifp)
542 struct sockaddr_in *dst;
544 bzero(&ro, sizeof(ro));
546 dst = (struct sockaddr_in *)&(ro.ro_dst);
547 dst->sin_family = AF_INET;
548 dst->sin_len = sizeof(*dst);
550 rtalloc_ign(&ro, RTF_CLONING);
552 if (ro.ro_rt == NULL)
555 /* if ifp is provided, check for equality with rtentry */
556 if (ifp != NULL && ro.ro_rt->rt_ifp != ifp) {
561 /* if no ifp provided, check if rtentry is not default route */
563 satosin(rt_key(ro.ro_rt))->sin_addr.s_addr == INADDR_ANY) {
568 /* or if this is a blackhole/reject route */
569 if (ifp == NULL && ro.ro_rt->rt_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
574 /* found valid route */
581 * ipv6 specific rules here...
584 icmp6type_match (int type, ipfw_insn_u32 *cmd)
586 return (type <= ICMP6_MAXTYPE && (cmd->d[type/32] & (1<<(type%32)) ) );
590 flow6id_match( int curr_flow, ipfw_insn_u32 *cmd )
593 for (i=0; i <= cmd->o.arg1; ++i )
594 if (curr_flow == cmd->d[i] )
599 /* support for IP6_*_ME opcodes */
601 search_ip6_addr_net (struct in6_addr * ip6_addr)
605 struct in6_ifaddr *fdm;
606 struct in6_addr copia;
608 TAILQ_FOREACH(mdc, &ifnet, if_link)
609 for (mdc2 = mdc->if_addrlist.tqh_first; mdc2;
610 mdc2 = mdc2->ifa_list.tqe_next) {
613 if (mdc2->ifa_addr->sa_family == AF_INET6) {
614 fdm = (struct in6_ifaddr *)mdc2;
615 copia = fdm->ia_addr.sin6_addr;
616 /* need for leaving scope_id in the sock_addr */
617 in6_clearscope(&copia);
618 if (IN6_ARE_ADDR_EQUAL(ip6_addr, &copia))
626 verify_path6(struct in6_addr *src, struct ifnet *ifp)
629 struct sockaddr_in6 *dst;
631 bzero(&ro, sizeof(ro));
633 dst = (struct sockaddr_in6 * )&(ro.ro_dst);
634 dst->sin6_family = AF_INET6;
635 dst->sin6_len = sizeof(*dst);
636 dst->sin6_addr = *src;
637 rtalloc_ign((struct route *)&ro, RTF_CLONING);
639 if (ro.ro_rt == NULL)
642 /* if ifp is provided, check for equality with rtentry */
643 if (ifp != NULL && ro.ro_rt->rt_ifp != ifp) {
648 /* if no ifp provided, check if rtentry is not default route */
650 IN6_IS_ADDR_UNSPECIFIED(&satosin6(rt_key(ro.ro_rt))->sin6_addr)) {
655 /* or if this is a blackhole/reject route */
656 if (ifp == NULL && ro.ro_rt->rt_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
661 /* found valid route */
667 hash_packet6(struct ipfw_flow_id *id)
670 i = (id->dst_ip6.__u6_addr.__u6_addr32[0]) ^
671 (id->dst_ip6.__u6_addr.__u6_addr32[1]) ^
672 (id->dst_ip6.__u6_addr.__u6_addr32[2]) ^
673 (id->dst_ip6.__u6_addr.__u6_addr32[3]) ^
674 (id->dst_port) ^ (id->src_port) ^ (id->flow_id6);
679 is_icmp6_query(int icmp6_type)
681 if ((icmp6_type <= ICMP6_MAXTYPE) &&
682 (icmp6_type == ICMP6_ECHO_REQUEST ||
683 icmp6_type == ICMP6_MEMBERSHIP_QUERY ||
684 icmp6_type == ICMP6_WRUREQUEST ||
685 icmp6_type == ICMP6_FQDN_QUERY ||
686 icmp6_type == ICMP6_NI_QUERY))
693 send_reject6(struct ip_fw_args *args, int code, u_short offset, u_int hlen)
695 if (code == ICMP6_UNREACH_RST && offset == 0 &&
696 args->f_id.proto == IPPROTO_TCP) {
706 if (args->m->m_len < (hlen+sizeof(struct tcphdr))) {
707 args->m = m_pullup(args->m, hlen+sizeof(struct tcphdr));
712 ip6 = mtod(args->m, struct ip6_hdr *);
713 tcp = (struct tcphdr *)(mtod(args->m, char *) + hlen);
715 if ((tcp->th_flags & TH_RST) != 0) {
722 ti.th.th_seq = ntohl(ti.th.th_seq);
723 ti.th.th_ack = ntohl(ti.th.th_ack);
724 ti.ip6.ip6_nxt = IPPROTO_TCP;
726 if (ti.th.th_flags & TH_ACK) {
732 if (((args->m)->m_flags & M_PKTHDR) != 0) {
733 ack += (args->m)->m_pkthdr.len - hlen
734 - (ti.th.th_off << 2);
735 } else if (ip6->ip6_plen) {
736 ack += ntohs(ip6->ip6_plen) + sizeof(*ip6)
737 - hlen - (ti.th.th_off << 2);
742 if (tcp->th_flags & TH_SYN)
745 flags = TH_RST|TH_ACK;
747 bcopy(&ti, ip6, sizeof(ti));
748 tcp_respond(NULL, ip6, (struct tcphdr *)(ip6 + 1),
749 args->m, ack, seq, flags);
751 } else if (code != ICMP6_UNREACH_RST) { /* Send an ICMPv6 unreach. */
752 icmp6_error(args->m, ICMP6_DST_UNREACH, code, 0);
762 static u_int64_t norule_counter; /* counter for ipfw_log(NULL...) */
764 #define SNPARGS(buf, len) buf + len, sizeof(buf) > len ? sizeof(buf) - len : 0
765 #define SNP(buf) buf, sizeof(buf)
768 * We enter here when we have a rule with O_LOG.
769 * XXX this function alone takes about 2Kbytes of code!
772 ipfw_log(struct ip_fw *f, u_int hlen, struct ip_fw_args *args,
773 struct mbuf *m, struct ifnet *oif, u_short offset)
775 struct ether_header *eh = args->eh;
777 int limit_reached = 0;
778 char action2[40], proto[128], fragment[32];
783 if (f == NULL) { /* bogus pkt */
784 if (verbose_limit != 0 && norule_counter >= verbose_limit)
787 if (norule_counter == verbose_limit)
788 limit_reached = verbose_limit;
790 } else { /* O_LOG is the first action, find the real one */
791 ipfw_insn *cmd = ACTION_PTR(f);
792 ipfw_insn_log *l = (ipfw_insn_log *)cmd;
794 if (l->max_log != 0 && l->log_left == 0)
797 if (l->log_left == 0)
798 limit_reached = l->max_log;
799 cmd += F_LEN(cmd); /* point to first action */
800 if (cmd->opcode == O_ALTQ) {
801 ipfw_insn_altq *altq = (ipfw_insn_altq *)cmd;
803 snprintf(SNPARGS(action2, 0), "Altq %d",
807 if (cmd->opcode == O_PROB)
811 switch (cmd->opcode) {
817 if (cmd->arg1==ICMP_REJECT_RST)
819 else if (cmd->arg1==ICMP_UNREACH_HOST)
822 snprintf(SNPARGS(action2, 0), "Unreach %d",
827 if (cmd->arg1==ICMP6_UNREACH_RST)
830 snprintf(SNPARGS(action2, 0), "Unreach %d",
841 snprintf(SNPARGS(action2, 0), "Divert %d",
845 snprintf(SNPARGS(action2, 0), "Tee %d",
849 snprintf(SNPARGS(action2, 0), "SkipTo %d",
853 snprintf(SNPARGS(action2, 0), "Pipe %d",
857 snprintf(SNPARGS(action2, 0), "Queue %d",
861 ipfw_insn_sa *sa = (ipfw_insn_sa *)cmd;
864 len = snprintf(SNPARGS(action2, 0), "Forward to %s",
865 inet_ntoa(sa->sa.sin_addr));
867 snprintf(SNPARGS(action2, len), ":%d",
872 snprintf(SNPARGS(action2, 0), "Netgraph %d",
876 snprintf(SNPARGS(action2, 0), "Ngtee %d",
885 if (hlen == 0) { /* non-ip */
886 snprintf(SNPARGS(proto, 0), "MAC");
890 char src[48], dst[48];
891 struct icmphdr *icmp;
894 /* Initialize to make compiler happy. */
895 struct ip *ip = NULL;
897 struct ip6_hdr *ip6 = NULL;
898 struct icmp6_hdr *icmp6;
903 if (args->f_id.addr_type == 6) {
904 snprintf(src, sizeof(src), "[%s]",
905 ip6_sprintf(&args->f_id.src_ip6));
906 snprintf(dst, sizeof(dst), "[%s]",
907 ip6_sprintf(&args->f_id.dst_ip6));
909 ip6 = (struct ip6_hdr *)mtod(m, struct ip6_hdr *);
910 tcp = (struct tcphdr *)(mtod(args->m, char *) + hlen);
911 udp = (struct udphdr *)(mtod(args->m, char *) + hlen);
915 ip = mtod(m, struct ip *);
916 tcp = L3HDR(struct tcphdr, ip);
917 udp = L3HDR(struct udphdr, ip);
919 inet_ntoa_r(ip->ip_src, src);
920 inet_ntoa_r(ip->ip_dst, dst);
923 switch (args->f_id.proto) {
925 len = snprintf(SNPARGS(proto, 0), "TCP %s", src);
927 snprintf(SNPARGS(proto, len), ":%d %s:%d",
928 ntohs(tcp->th_sport),
930 ntohs(tcp->th_dport));
932 snprintf(SNPARGS(proto, len), " %s", dst);
936 len = snprintf(SNPARGS(proto, 0), "UDP %s", src);
938 snprintf(SNPARGS(proto, len), ":%d %s:%d",
939 ntohs(udp->uh_sport),
941 ntohs(udp->uh_dport));
943 snprintf(SNPARGS(proto, len), " %s", dst);
947 icmp = L3HDR(struct icmphdr, ip);
949 len = snprintf(SNPARGS(proto, 0),
951 icmp->icmp_type, icmp->icmp_code);
953 len = snprintf(SNPARGS(proto, 0), "ICMP ");
954 len += snprintf(SNPARGS(proto, len), "%s", src);
955 snprintf(SNPARGS(proto, len), " %s", dst);
959 icmp6 = (struct icmp6_hdr *)(mtod(args->m, char *) + hlen);
961 len = snprintf(SNPARGS(proto, 0),
963 icmp6->icmp6_type, icmp6->icmp6_code);
965 len = snprintf(SNPARGS(proto, 0), "ICMPv6 ");
966 len += snprintf(SNPARGS(proto, len), "%s", src);
967 snprintf(SNPARGS(proto, len), " %s", dst);
971 len = snprintf(SNPARGS(proto, 0), "P:%d %s",
972 args->f_id.proto, src);
973 snprintf(SNPARGS(proto, len), " %s", dst);
978 if (args->f_id.addr_type == 6) {
979 if (offset & (IP6F_OFF_MASK | IP6F_MORE_FRAG))
980 snprintf(SNPARGS(fragment, 0),
981 " (frag %08x:%d@%d%s)",
983 ntohs(ip6->ip6_plen) - hlen,
984 ntohs(offset & IP6F_OFF_MASK) << 3,
985 (offset & IP6F_MORE_FRAG) ? "+" : "");
990 if (eh != NULL) { /* layer 2 packets are as on the wire */
991 ip_off = ntohs(ip->ip_off);
992 ip_len = ntohs(ip->ip_len);
997 if (ip_off & (IP_MF | IP_OFFMASK))
998 snprintf(SNPARGS(fragment, 0),
999 " (frag %d:%d@%d%s)",
1000 ntohs(ip->ip_id), ip_len - (ip->ip_hl << 2),
1002 (ip_off & IP_MF) ? "+" : "");
1005 if (oif || m->m_pkthdr.rcvif)
1006 log(LOG_SECURITY | LOG_INFO,
1007 "ipfw: %d %s %s %s via %s%s\n",
1008 f ? f->rulenum : -1,
1009 action, proto, oif ? "out" : "in",
1010 oif ? oif->if_xname : m->m_pkthdr.rcvif->if_xname,
1013 log(LOG_SECURITY | LOG_INFO,
1014 "ipfw: %d %s %s [no if info]%s\n",
1015 f ? f->rulenum : -1,
1016 action, proto, fragment);
1018 log(LOG_SECURITY | LOG_NOTICE,
1019 "ipfw: limit %d reached on entry %d\n",
1020 limit_reached, f ? f->rulenum : -1);
1024 * IMPORTANT: the hash function for dynamic rules must be commutative
1025 * in source and destination (ip,port), because rules are bidirectional
1026 * and we want to find both in the same bucket.
1029 hash_packet(struct ipfw_flow_id *id)
1034 if (IS_IP6_FLOW_ID(id))
1035 i = hash_packet6(id);
1038 i = (id->dst_ip) ^ (id->src_ip) ^ (id->dst_port) ^ (id->src_port);
1039 i &= (curr_dyn_buckets - 1);
1044 * unlink a dynamic rule from a chain. prev is a pointer to
1045 * the previous one, q is a pointer to the rule to delete,
1046 * head is a pointer to the head of the queue.
1047 * Modifies q and potentially also head.
1049 #define UNLINK_DYN_RULE(prev, head, q) { \
1050 ipfw_dyn_rule *old_q = q; \
1052 /* remove a refcount to the parent */ \
1053 if (q->dyn_type == O_LIMIT) \
1054 q->parent->count--; \
1055 DEB(printf("ipfw: unlink entry 0x%08x %d -> 0x%08x %d, %d left\n",\
1056 (q->id.src_ip), (q->id.src_port), \
1057 (q->id.dst_ip), (q->id.dst_port), dyn_count-1 ); ) \
1059 prev->next = q = q->next; \
1061 head = q = q->next; \
1063 uma_zfree(ipfw_dyn_rule_zone, old_q); }
1065 #define TIME_LEQ(a,b) ((int)((a)-(b)) <= 0)
1068 * Remove dynamic rules pointing to "rule", or all of them if rule == NULL.
1070 * If keep_me == NULL, rules are deleted even if not expired,
1071 * otherwise only expired rules are removed.
1073 * The value of the second parameter is also used to point to identify
1074 * a rule we absolutely do not want to remove (e.g. because we are
1075 * holding a reference to it -- this is the case with O_LIMIT_PARENT
1076 * rules). The pointer is only used for comparison, so any non-null
1080 remove_dyn_rule(struct ip_fw *rule, ipfw_dyn_rule *keep_me)
1082 static u_int32_t last_remove = 0;
1084 #define FORCE (keep_me == NULL)
1086 ipfw_dyn_rule *prev, *q;
1087 int i, pass = 0, max_pass = 0;
1089 IPFW_DYN_LOCK_ASSERT();
1091 if (ipfw_dyn_v == NULL || dyn_count == 0)
1093 /* do not expire more than once per second, it is useless */
1094 if (!FORCE && last_remove == time_uptime)
1096 last_remove = time_uptime;
1099 * because O_LIMIT refer to parent rules, during the first pass only
1100 * remove child and mark any pending LIMIT_PARENT, and remove
1101 * them in a second pass.
1104 for (i = 0 ; i < curr_dyn_buckets ; i++) {
1105 for (prev=NULL, q = ipfw_dyn_v[i] ; q ; ) {
1107 * Logic can become complex here, so we split tests.
1111 if (rule != NULL && rule != q->rule)
1112 goto next; /* not the one we are looking for */
1113 if (q->dyn_type == O_LIMIT_PARENT) {
1115 * handle parent in the second pass,
1116 * record we need one.
1121 if (FORCE && q->count != 0 ) {
1122 /* XXX should not happen! */
1123 printf("ipfw: OUCH! cannot remove rule,"
1124 " count %d\n", q->count);
1128 !TIME_LEQ( q->expire, time_uptime ))
1131 if (q->dyn_type != O_LIMIT_PARENT || !q->count) {
1132 UNLINK_DYN_RULE(prev, ipfw_dyn_v[i], q);
1140 if (pass++ < max_pass)
1146 * lookup a dynamic rule.
1148 static ipfw_dyn_rule *
1149 lookup_dyn_rule_locked(struct ipfw_flow_id *pkt, int *match_direction,
1153 * stateful ipfw extensions.
1154 * Lookup into dynamic session queue
1156 #define MATCH_REVERSE 0
1157 #define MATCH_FORWARD 1
1158 #define MATCH_NONE 2
1159 #define MATCH_UNKNOWN 3
1160 int i, dir = MATCH_NONE;
1161 ipfw_dyn_rule *prev, *q=NULL;
1163 IPFW_DYN_LOCK_ASSERT();
1165 if (ipfw_dyn_v == NULL)
1166 goto done; /* not found */
1167 i = hash_packet( pkt );
1168 for (prev=NULL, q = ipfw_dyn_v[i] ; q != NULL ; ) {
1169 if (q->dyn_type == O_LIMIT_PARENT && q->count)
1171 if (TIME_LEQ( q->expire, time_uptime)) { /* expire entry */
1172 UNLINK_DYN_RULE(prev, ipfw_dyn_v[i], q);
1175 if (pkt->proto == q->id.proto &&
1176 q->dyn_type != O_LIMIT_PARENT) {
1177 if (IS_IP6_FLOW_ID(pkt)) {
1178 if (IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
1179 &(q->id.src_ip6)) &&
1180 IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
1181 &(q->id.dst_ip6)) &&
1182 pkt->src_port == q->id.src_port &&
1183 pkt->dst_port == q->id.dst_port ) {
1184 dir = MATCH_FORWARD;
1187 if (IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
1188 &(q->id.dst_ip6)) &&
1189 IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
1190 &(q->id.src_ip6)) &&
1191 pkt->src_port == q->id.dst_port &&
1192 pkt->dst_port == q->id.src_port ) {
1193 dir = MATCH_REVERSE;
1197 if (pkt->src_ip == q->id.src_ip &&
1198 pkt->dst_ip == q->id.dst_ip &&
1199 pkt->src_port == q->id.src_port &&
1200 pkt->dst_port == q->id.dst_port ) {
1201 dir = MATCH_FORWARD;
1204 if (pkt->src_ip == q->id.dst_ip &&
1205 pkt->dst_ip == q->id.src_ip &&
1206 pkt->src_port == q->id.dst_port &&
1207 pkt->dst_port == q->id.src_port ) {
1208 dir = MATCH_REVERSE;
1218 goto done; /* q = NULL, not found */
1220 if ( prev != NULL) { /* found and not in front */
1221 prev->next = q->next;
1222 q->next = ipfw_dyn_v[i];
1225 if (pkt->proto == IPPROTO_TCP) { /* update state according to flags */
1226 u_char flags = pkt->flags & (TH_FIN|TH_SYN|TH_RST);
1228 #define BOTH_SYN (TH_SYN | (TH_SYN << 8))
1229 #define BOTH_FIN (TH_FIN | (TH_FIN << 8))
1230 q->state |= (dir == MATCH_FORWARD ) ? flags : (flags << 8);
1232 case TH_SYN: /* opening */
1233 q->expire = time_uptime + dyn_syn_lifetime;
1236 case BOTH_SYN: /* move to established */
1237 case BOTH_SYN | TH_FIN : /* one side tries to close */
1238 case BOTH_SYN | (TH_FIN << 8) :
1240 #define _SEQ_GE(a,b) ((int)(a) - (int)(b) >= 0)
1241 u_int32_t ack = ntohl(tcp->th_ack);
1242 if (dir == MATCH_FORWARD) {
1243 if (q->ack_fwd == 0 || _SEQ_GE(ack, q->ack_fwd))
1245 else { /* ignore out-of-sequence */
1249 if (q->ack_rev == 0 || _SEQ_GE(ack, q->ack_rev))
1251 else { /* ignore out-of-sequence */
1256 q->expire = time_uptime + dyn_ack_lifetime;
1259 case BOTH_SYN | BOTH_FIN: /* both sides closed */
1260 if (dyn_fin_lifetime >= dyn_keepalive_period)
1261 dyn_fin_lifetime = dyn_keepalive_period - 1;
1262 q->expire = time_uptime + dyn_fin_lifetime;
1268 * reset or some invalid combination, but can also
1269 * occur if we use keep-state the wrong way.
1271 if ( (q->state & ((TH_RST << 8)|TH_RST)) == 0)
1272 printf("invalid state: 0x%x\n", q->state);
1274 if (dyn_rst_lifetime >= dyn_keepalive_period)
1275 dyn_rst_lifetime = dyn_keepalive_period - 1;
1276 q->expire = time_uptime + dyn_rst_lifetime;
1279 } else if (pkt->proto == IPPROTO_UDP) {
1280 q->expire = time_uptime + dyn_udp_lifetime;
1282 /* other protocols */
1283 q->expire = time_uptime + dyn_short_lifetime;
1286 if (match_direction)
1287 *match_direction = dir;
1291 static ipfw_dyn_rule *
1292 lookup_dyn_rule(struct ipfw_flow_id *pkt, int *match_direction,
1298 q = lookup_dyn_rule_locked(pkt, match_direction, tcp);
1301 /* NB: return table locked when q is not NULL */
1306 realloc_dynamic_table(void)
1308 IPFW_DYN_LOCK_ASSERT();
1311 * Try reallocation, make sure we have a power of 2 and do
1312 * not allow more than 64k entries. In case of overflow,
1316 if (dyn_buckets > 65536)
1318 if ((dyn_buckets & (dyn_buckets-1)) != 0) { /* not a power of 2 */
1319 dyn_buckets = curr_dyn_buckets; /* reset */
1322 curr_dyn_buckets = dyn_buckets;
1323 if (ipfw_dyn_v != NULL)
1324 free(ipfw_dyn_v, M_IPFW);
1326 ipfw_dyn_v = malloc(curr_dyn_buckets * sizeof(ipfw_dyn_rule *),
1327 M_IPFW, M_NOWAIT | M_ZERO);
1328 if (ipfw_dyn_v != NULL || curr_dyn_buckets <= 2)
1330 curr_dyn_buckets /= 2;
1335 * Install state of type 'type' for a dynamic session.
1336 * The hash table contains two type of rules:
1337 * - regular rules (O_KEEP_STATE)
1338 * - rules for sessions with limited number of sess per user
1339 * (O_LIMIT). When they are created, the parent is
1340 * increased by 1, and decreased on delete. In this case,
1341 * the third parameter is the parent rule and not the chain.
1342 * - "parent" rules for the above (O_LIMIT_PARENT).
1344 static ipfw_dyn_rule *
1345 add_dyn_rule(struct ipfw_flow_id *id, u_int8_t dyn_type, struct ip_fw *rule)
1350 IPFW_DYN_LOCK_ASSERT();
1352 if (ipfw_dyn_v == NULL ||
1353 (dyn_count == 0 && dyn_buckets != curr_dyn_buckets)) {
1354 realloc_dynamic_table();
1355 if (ipfw_dyn_v == NULL)
1356 return NULL; /* failed ! */
1358 i = hash_packet(id);
1360 r = uma_zalloc(ipfw_dyn_rule_zone, M_NOWAIT | M_ZERO);
1362 printf ("ipfw: sorry cannot allocate state\n");
1366 /* increase refcount on parent, and set pointer */
1367 if (dyn_type == O_LIMIT) {
1368 ipfw_dyn_rule *parent = (ipfw_dyn_rule *)rule;
1369 if ( parent->dyn_type != O_LIMIT_PARENT)
1370 panic("invalid parent");
1373 rule = parent->rule;
1377 r->expire = time_uptime + dyn_syn_lifetime;
1379 r->dyn_type = dyn_type;
1380 r->pcnt = r->bcnt = 0;
1384 r->next = ipfw_dyn_v[i];
1387 DEB(printf("ipfw: add dyn entry ty %d 0x%08x %d -> 0x%08x %d, total %d\n",
1389 (r->id.src_ip), (r->id.src_port),
1390 (r->id.dst_ip), (r->id.dst_port),
1396 * lookup dynamic parent rule using pkt and rule as search keys.
1397 * If the lookup fails, then install one.
1399 static ipfw_dyn_rule *
1400 lookup_dyn_parent(struct ipfw_flow_id *pkt, struct ip_fw *rule)
1405 IPFW_DYN_LOCK_ASSERT();
1408 int is_v6 = IS_IP6_FLOW_ID(pkt);
1409 i = hash_packet( pkt );
1410 for (q = ipfw_dyn_v[i] ; q != NULL ; q=q->next)
1411 if (q->dyn_type == O_LIMIT_PARENT &&
1413 pkt->proto == q->id.proto &&
1414 pkt->src_port == q->id.src_port &&
1415 pkt->dst_port == q->id.dst_port &&
1418 IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
1419 &(q->id.src_ip6)) &&
1420 IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
1421 &(q->id.dst_ip6))) ||
1423 pkt->src_ip == q->id.src_ip &&
1424 pkt->dst_ip == q->id.dst_ip)
1427 q->expire = time_uptime + dyn_short_lifetime;
1428 DEB(printf("ipfw: lookup_dyn_parent found 0x%p\n",q);)
1432 return add_dyn_rule(pkt, O_LIMIT_PARENT, rule);
1436 * Install dynamic state for rule type cmd->o.opcode
1438 * Returns 1 (failure) if state is not installed because of errors or because
1439 * session limitations are enforced.
1442 install_state(struct ip_fw *rule, ipfw_insn_limit *cmd,
1443 struct ip_fw_args *args)
1445 static int last_log;
1449 DEB(printf("ipfw: install state type %d 0x%08x %u -> 0x%08x %u\n",
1451 (args->f_id.src_ip), (args->f_id.src_port),
1452 (args->f_id.dst_ip), (args->f_id.dst_port) );)
1456 q = lookup_dyn_rule_locked(&args->f_id, NULL, NULL);
1458 if (q != NULL) { /* should never occur */
1459 if (last_log != time_uptime) {
1460 last_log = time_uptime;
1461 printf("ipfw: install_state: entry already present, done\n");
1467 if (dyn_count >= dyn_max)
1469 * Run out of slots, try to remove any expired rule.
1471 remove_dyn_rule(NULL, (ipfw_dyn_rule *)1);
1473 if (dyn_count >= dyn_max) {
1474 if (last_log != time_uptime) {
1475 last_log = time_uptime;
1476 printf("ipfw: install_state: Too many dynamic rules\n");
1479 return 1; /* cannot install, notify caller */
1482 switch (cmd->o.opcode) {
1483 case O_KEEP_STATE: /* bidir rule */
1484 add_dyn_rule(&args->f_id, O_KEEP_STATE, rule);
1487 case O_LIMIT: /* limit number of sessions */
1489 u_int16_t limit_mask = cmd->limit_mask;
1490 struct ipfw_flow_id id;
1491 ipfw_dyn_rule *parent;
1493 DEB(printf("ipfw: installing dyn-limit rule %d\n",
1496 id.dst_ip = id.src_ip = 0;
1497 id.dst_port = id.src_port = 0;
1498 id.proto = args->f_id.proto;
1500 if (IS_IP6_FLOW_ID (&(args->f_id))) {
1501 if (limit_mask & DYN_SRC_ADDR)
1502 id.src_ip6 = args->f_id.src_ip6;
1503 if (limit_mask & DYN_DST_ADDR)
1504 id.dst_ip6 = args->f_id.dst_ip6;
1506 if (limit_mask & DYN_SRC_ADDR)
1507 id.src_ip = args->f_id.src_ip;
1508 if (limit_mask & DYN_DST_ADDR)
1509 id.dst_ip = args->f_id.dst_ip;
1511 if (limit_mask & DYN_SRC_PORT)
1512 id.src_port = args->f_id.src_port;
1513 if (limit_mask & DYN_DST_PORT)
1514 id.dst_port = args->f_id.dst_port;
1515 parent = lookup_dyn_parent(&id, rule);
1516 if (parent == NULL) {
1517 printf("ipfw: add parent failed\n");
1521 if (parent->count >= cmd->conn_limit) {
1523 * See if we can remove some expired rule.
1525 remove_dyn_rule(rule, parent);
1526 if (parent->count >= cmd->conn_limit) {
1527 if (fw_verbose && last_log != time_uptime) {
1528 last_log = time_uptime;
1529 log(LOG_SECURITY | LOG_DEBUG,
1530 "drop session, too many entries\n");
1536 add_dyn_rule(&args->f_id, O_LIMIT, (struct ip_fw *)parent);
1540 printf("ipfw: unknown dynamic rule type %u\n", cmd->o.opcode);
1544 lookup_dyn_rule_locked(&args->f_id, NULL, NULL); /* XXX just set lifetime */
1550 * Generate a TCP packet, containing either a RST or a keepalive.
1551 * When flags & TH_RST, we are sending a RST packet, because of a
1552 * "reset" action matched the packet.
1553 * Otherwise we are sending a keepalive, and flags & TH_
1555 static struct mbuf *
1556 send_pkt(struct ipfw_flow_id *id, u_int32_t seq, u_int32_t ack, int flags)
1562 MGETHDR(m, M_DONTWAIT, MT_HEADER);
1565 m->m_pkthdr.rcvif = (struct ifnet *)0;
1566 m->m_pkthdr.len = m->m_len = sizeof(struct ip) + sizeof(struct tcphdr);
1567 m->m_data += max_linkhdr;
1569 ip = mtod(m, struct ip *);
1570 bzero(ip, m->m_len);
1571 tcp = (struct tcphdr *)(ip + 1); /* no IP options */
1572 ip->ip_p = IPPROTO_TCP;
1575 * Assume we are sending a RST (or a keepalive in the reverse
1576 * direction), swap src and destination addresses and ports.
1578 ip->ip_src.s_addr = htonl(id->dst_ip);
1579 ip->ip_dst.s_addr = htonl(id->src_ip);
1580 tcp->th_sport = htons(id->dst_port);
1581 tcp->th_dport = htons(id->src_port);
1582 if (flags & TH_RST) { /* we are sending a RST */
1583 if (flags & TH_ACK) {
1584 tcp->th_seq = htonl(ack);
1585 tcp->th_ack = htonl(0);
1586 tcp->th_flags = TH_RST;
1590 tcp->th_seq = htonl(0);
1591 tcp->th_ack = htonl(seq);
1592 tcp->th_flags = TH_RST | TH_ACK;
1596 * We are sending a keepalive. flags & TH_SYN determines
1597 * the direction, forward if set, reverse if clear.
1598 * NOTE: seq and ack are always assumed to be correct
1599 * as set by the caller. This may be confusing...
1601 if (flags & TH_SYN) {
1603 * we have to rewrite the correct addresses!
1605 ip->ip_dst.s_addr = htonl(id->dst_ip);
1606 ip->ip_src.s_addr = htonl(id->src_ip);
1607 tcp->th_dport = htons(id->dst_port);
1608 tcp->th_sport = htons(id->src_port);
1610 tcp->th_seq = htonl(seq);
1611 tcp->th_ack = htonl(ack);
1612 tcp->th_flags = TH_ACK;
1615 * set ip_len to the payload size so we can compute
1616 * the tcp checksum on the pseudoheader
1617 * XXX check this, could save a couple of words ?
1619 ip->ip_len = htons(sizeof(struct tcphdr));
1620 tcp->th_sum = in_cksum(m, m->m_pkthdr.len);
1622 * now fill fields left out earlier
1624 ip->ip_ttl = ip_defttl;
1625 ip->ip_len = m->m_pkthdr.len;
1626 m->m_flags |= M_SKIP_FIREWALL;
1631 * sends a reject message, consuming the mbuf passed as an argument.
1634 send_reject(struct ip_fw_args *args, int code, u_short offset, int ip_len)
1637 if (code != ICMP_REJECT_RST) { /* Send an ICMP unreach */
1638 /* We need the IP header in host order for icmp_error(). */
1639 if (args->eh != NULL) {
1640 struct ip *ip = mtod(args->m, struct ip *);
1641 ip->ip_len = ntohs(ip->ip_len);
1642 ip->ip_off = ntohs(ip->ip_off);
1644 icmp_error(args->m, ICMP_UNREACH, code, 0L, 0);
1645 } else if (offset == 0 && args->f_id.proto == IPPROTO_TCP) {
1646 struct tcphdr *const tcp =
1647 L3HDR(struct tcphdr, mtod(args->m, struct ip *));
1648 if ( (tcp->th_flags & TH_RST) == 0) {
1650 m = send_pkt(&(args->f_id), ntohl(tcp->th_seq),
1652 tcp->th_flags | TH_RST);
1654 ip_output(m, NULL, NULL, 0, NULL, NULL);
1664 * Given an ip_fw *, lookup_next_rule will return a pointer
1665 * to the next rule, which can be either the jump
1666 * target (for skipto instructions) or the next one in the list (in
1667 * all other cases including a missing jump target).
1668 * The result is also written in the "next_rule" field of the rule.
1669 * Backward jumps are not allowed, so start looking from the next
1672 * This never returns NULL -- in case we do not have an exact match,
1673 * the next rule is returned. When the ruleset is changed,
1674 * pointers are flushed so we are always correct.
1677 static struct ip_fw *
1678 lookup_next_rule(struct ip_fw *me)
1680 struct ip_fw *rule = NULL;
1683 /* look for action, in case it is a skipto */
1684 cmd = ACTION_PTR(me);
1685 if (cmd->opcode == O_LOG)
1687 if (cmd->opcode == O_ALTQ)
1689 if ( cmd->opcode == O_SKIPTO )
1690 for (rule = me->next; rule ; rule = rule->next)
1691 if (rule->rulenum >= cmd->arg1)
1693 if (rule == NULL) /* failure or not a skipto */
1695 me->next_rule = rule;
1704 for (i = 0; i < IPFW_TABLES_MAX; i++) {
1705 rn_inithead((void **)&ipfw_tables[i].rnh, 32);
1706 ipfw_tables[i].modified = 1;
1711 add_table_entry(u_int16_t tbl, in_addr_t addr, u_int8_t mlen, u_int32_t value)
1713 struct radix_node_head *rnh;
1714 struct table_entry *ent;
1716 if (tbl >= IPFW_TABLES_MAX)
1718 rnh = ipfw_tables[tbl].rnh;
1719 ent = malloc(sizeof(*ent), M_IPFW_TBL, M_NOWAIT | M_ZERO);
1723 ent->addr.sin_len = ent->mask.sin_len = 8;
1724 ent->mask.sin_addr.s_addr = htonl(mlen ? ~((1 << (32 - mlen)) - 1) : 0);
1725 ent->addr.sin_addr.s_addr = addr & ent->mask.sin_addr.s_addr;
1726 RADIX_NODE_HEAD_LOCK(rnh);
1727 if (rnh->rnh_addaddr(&ent->addr, &ent->mask, rnh, (void *)ent) ==
1729 RADIX_NODE_HEAD_UNLOCK(rnh);
1730 free(ent, M_IPFW_TBL);
1733 ipfw_tables[tbl].modified = 1;
1734 RADIX_NODE_HEAD_UNLOCK(rnh);
1739 del_table_entry(u_int16_t tbl, in_addr_t addr, u_int8_t mlen)
1741 struct radix_node_head *rnh;
1742 struct table_entry *ent;
1743 struct sockaddr_in sa, mask;
1745 if (tbl >= IPFW_TABLES_MAX)
1747 rnh = ipfw_tables[tbl].rnh;
1748 sa.sin_len = mask.sin_len = 8;
1749 mask.sin_addr.s_addr = htonl(mlen ? ~((1 << (32 - mlen)) - 1) : 0);
1750 sa.sin_addr.s_addr = addr & mask.sin_addr.s_addr;
1751 RADIX_NODE_HEAD_LOCK(rnh);
1752 ent = (struct table_entry *)rnh->rnh_deladdr(&sa, &mask, rnh);
1754 RADIX_NODE_HEAD_UNLOCK(rnh);
1757 ipfw_tables[tbl].modified = 1;
1758 RADIX_NODE_HEAD_UNLOCK(rnh);
1759 free(ent, M_IPFW_TBL);
1764 flush_table_entry(struct radix_node *rn, void *arg)
1766 struct radix_node_head * const rnh = arg;
1767 struct table_entry *ent;
1769 ent = (struct table_entry *)
1770 rnh->rnh_deladdr(rn->rn_key, rn->rn_mask, rnh);
1772 free(ent, M_IPFW_TBL);
1777 flush_table(u_int16_t tbl)
1779 struct radix_node_head *rnh;
1781 if (tbl >= IPFW_TABLES_MAX)
1783 rnh = ipfw_tables[tbl].rnh;
1784 RADIX_NODE_HEAD_LOCK(rnh);
1785 rnh->rnh_walktree(rnh, flush_table_entry, rnh);
1786 ipfw_tables[tbl].modified = 1;
1787 RADIX_NODE_HEAD_UNLOCK(rnh);
1796 for (tbl = 0; tbl < IPFW_TABLES_MAX; tbl++)
1801 lookup_table(u_int16_t tbl, in_addr_t addr, u_int32_t *val)
1803 struct radix_node_head *rnh;
1804 struct ip_fw_table *table;
1805 struct table_entry *ent;
1806 struct sockaddr_in sa;
1809 if (tbl >= IPFW_TABLES_MAX)
1811 table = &ipfw_tables[tbl];
1813 RADIX_NODE_HEAD_LOCK(rnh);
1814 if (addr == table->last_addr && !table->modified) {
1815 last_match = table->last_match;
1817 *val = table->last_value;
1818 RADIX_NODE_HEAD_UNLOCK(rnh);
1819 return (last_match);
1821 table->modified = 0;
1823 sa.sin_addr.s_addr = addr;
1824 ent = (struct table_entry *)(rnh->rnh_lookup(&sa, NULL, rnh));
1825 table->last_addr = addr;
1827 table->last_value = *val = ent->value;
1828 table->last_match = 1;
1829 RADIX_NODE_HEAD_UNLOCK(rnh);
1832 table->last_match = 0;
1833 RADIX_NODE_HEAD_UNLOCK(rnh);
1838 count_table_entry(struct radix_node *rn, void *arg)
1840 u_int32_t * const cnt = arg;
1847 count_table(u_int32_t tbl, u_int32_t *cnt)
1849 struct radix_node_head *rnh;
1851 if (tbl >= IPFW_TABLES_MAX)
1853 rnh = ipfw_tables[tbl].rnh;
1855 RADIX_NODE_HEAD_LOCK(rnh);
1856 rnh->rnh_walktree(rnh, count_table_entry, cnt);
1857 RADIX_NODE_HEAD_UNLOCK(rnh);
1862 dump_table_entry(struct radix_node *rn, void *arg)
1864 struct table_entry * const n = (struct table_entry *)rn;
1865 ipfw_table * const tbl = arg;
1866 ipfw_table_entry *ent;
1868 if (tbl->cnt == tbl->size)
1870 ent = &tbl->ent[tbl->cnt];
1871 ent->tbl = tbl->tbl;
1872 if (in_nullhost(n->mask.sin_addr))
1875 ent->masklen = 33 - ffs(ntohl(n->mask.sin_addr.s_addr));
1876 ent->addr = n->addr.sin_addr.s_addr;
1877 ent->value = n->value;
1883 dump_table(ipfw_table *tbl)
1885 struct radix_node_head *rnh;
1887 if (tbl->tbl >= IPFW_TABLES_MAX)
1889 rnh = ipfw_tables[tbl->tbl].rnh;
1891 RADIX_NODE_HEAD_LOCK(rnh);
1892 rnh->rnh_walktree(rnh, dump_table_entry, tbl);
1893 RADIX_NODE_HEAD_UNLOCK(rnh);
1898 fill_ugid_cache(struct inpcb *inp, struct ip_fw_ugid *ugp)
1902 if (inp->inp_socket != NULL) {
1903 cr = inp->inp_socket->so_cred;
1904 ugp->fw_prid = jailed(cr) ?
1905 cr->cr_prison->pr_id : -1;
1906 ugp->fw_uid = cr->cr_uid;
1907 ugp->fw_ngroups = cr->cr_ngroups;
1908 bcopy(cr->cr_groups, ugp->fw_groups,
1909 sizeof(ugp->fw_groups));
1914 check_uidgid(ipfw_insn_u32 *insn,
1915 int proto, struct ifnet *oif,
1916 struct in_addr dst_ip, u_int16_t dst_port,
1917 struct in_addr src_ip, u_int16_t src_port,
1918 struct ip_fw_ugid *ugp, int *lookup, struct inpcb *inp)
1920 struct inpcbinfo *pi;
1927 * Check to see if the UDP or TCP stack supplied us with
1928 * the PCB. If so, rather then holding a lock and looking
1929 * up the PCB, we can use the one that was supplied.
1931 if (inp && *lookup == 0) {
1932 INP_LOCK_ASSERT(inp);
1933 if (inp->inp_socket != NULL) {
1934 fill_ugid_cache(inp, ugp);
1939 * If we have already been here and the packet has no
1940 * PCB entry associated with it, then we can safely
1941 * assume that this is a no match.
1945 if (proto == IPPROTO_TCP) {
1948 } else if (proto == IPPROTO_UDP) {
1957 in_pcblookup_hash(pi,
1958 dst_ip, htons(dst_port),
1959 src_ip, htons(src_port),
1961 in_pcblookup_hash(pi,
1962 src_ip, htons(src_port),
1963 dst_ip, htons(dst_port),
1967 if (pcb->inp_socket != NULL) {
1968 fill_ugid_cache(pcb, ugp);
1973 INP_INFO_RUNLOCK(pi);
1976 * If the lookup did not yield any results, there
1977 * is no sense in coming back and trying again. So
1978 * we can set lookup to -1 and ensure that we wont
1979 * bother the pcb system again.
1985 if (insn->o.opcode == O_UID)
1986 match = (ugp->fw_uid == (uid_t)insn->d[0]);
1987 else if (insn->o.opcode == O_GID) {
1988 for (gp = ugp->fw_groups;
1989 gp < &ugp->fw_groups[ugp->fw_ngroups]; gp++)
1990 if (*gp == (gid_t)insn->d[0]) {
1994 } else if (insn->o.opcode == O_JAIL)
1995 match = (ugp->fw_prid == (int)insn->d[0]);
2000 * The main check routine for the firewall.
2002 * All arguments are in args so we can modify them and return them
2003 * back to the caller.
2007 * args->m (in/out) The packet; we set to NULL when/if we nuke it.
2008 * Starts with the IP header.
2009 * args->eh (in) Mac header if present, or NULL for layer3 packet.
2010 * args->oif Outgoing interface, or NULL if packet is incoming.
2011 * The incoming interface is in the mbuf. (in)
2012 * args->divert_rule (in/out)
2013 * Skip up to the first rule past this rule number;
2014 * upon return, non-zero port number for divert or tee.
2016 * args->rule Pointer to the last matching rule (in/out)
2017 * args->next_hop Socket we are forwarding to (out).
2018 * args->f_id Addresses grabbed from the packet (out)
2019 * args->cookie a cookie depending on rule action
2023 * IP_FW_PASS the packet must be accepted
2024 * IP_FW_DENY the packet must be dropped
2025 * IP_FW_DIVERT divert packet, port in m_tag
2026 * IP_FW_TEE tee packet, port in m_tag
2027 * IP_FW_DUMMYNET to dummynet, pipe in args->cookie
2028 * IP_FW_NETGRAPH into netgraph, cookie args->cookie
2033 ipfw_chk(struct ip_fw_args *args)
2036 * Local variables hold state during the processing of a packet.
2038 * IMPORTANT NOTE: to speed up the processing of rules, there
2039 * are some assumption on the values of the variables, which
2040 * are documented here. Should you change them, please check
2041 * the implementation of the various instructions to make sure
2042 * that they still work.
2044 * args->eh The MAC header. It is non-null for a layer2
2045 * packet, it is NULL for a layer-3 packet.
2047 * m | args->m Pointer to the mbuf, as received from the caller.
2048 * It may change if ipfw_chk() does an m_pullup, or if it
2049 * consumes the packet because it calls send_reject().
2050 * XXX This has to change, so that ipfw_chk() never modifies
2051 * or consumes the buffer.
2052 * ip is simply an alias of the value of m, and it is kept
2053 * in sync with it (the packet is supposed to start with
2056 struct mbuf *m = args->m;
2057 struct ip *ip = mtod(m, struct ip *);
2060 * For rules which contain uid/gid or jail constraints, cache
2061 * a copy of the users credentials after the pcb lookup has been
2062 * executed. This will speed up the processing of rules with
2063 * these types of constraints, as well as decrease contention
2064 * on pcb related locks.
2066 struct ip_fw_ugid fw_ugid_cache;
2067 int ugid_lookup = 0;
2070 * divinput_flags If non-zero, set to the IP_FW_DIVERT_*_FLAG
2071 * associated with a packet input on a divert socket. This
2072 * will allow to distinguish traffic and its direction when
2073 * it originates from a divert socket.
2075 u_int divinput_flags = 0;
2078 * oif | args->oif If NULL, ipfw_chk has been called on the
2079 * inbound path (ether_input, ip_input).
2080 * If non-NULL, ipfw_chk has been called on the outbound path
2081 * (ether_output, ip_output).
2083 struct ifnet *oif = args->oif;
2085 struct ip_fw *f = NULL; /* matching rule */
2089 * hlen The length of the IP header.
2091 u_int hlen = 0; /* hlen >0 means we have an IP pkt */
2094 * offset The offset of a fragment. offset != 0 means that
2095 * we have a fragment at this offset of an IPv4 packet.
2096 * offset == 0 means that (if this is an IPv4 packet)
2097 * this is the first or only fragment.
2098 * For IPv6 offset == 0 means there is no Fragment Header.
2099 * If offset != 0 for IPv6 always use correct mask to
2100 * get the correct offset because we add IP6F_MORE_FRAG
2101 * to be able to dectect the first fragment which would
2102 * otherwise have offset = 0.
2107 * Local copies of addresses. They are only valid if we have
2110 * proto The protocol. Set to 0 for non-ip packets,
2111 * or to the protocol read from the packet otherwise.
2112 * proto != 0 means that we have an IPv4 packet.
2114 * src_port, dst_port port numbers, in HOST format. Only
2115 * valid for TCP and UDP packets.
2117 * src_ip, dst_ip ip addresses, in NETWORK format.
2118 * Only valid for IPv4 packets.
2121 u_int16_t src_port = 0, dst_port = 0; /* NOTE: host format */
2122 struct in_addr src_ip, dst_ip; /* NOTE: network format */
2127 * dyn_dir = MATCH_UNKNOWN when rules unchecked,
2128 * MATCH_NONE when checked and not matched (q = NULL),
2129 * MATCH_FORWARD or MATCH_REVERSE otherwise (q != NULL)
2131 int dyn_dir = MATCH_UNKNOWN;
2132 ipfw_dyn_rule *q = NULL;
2133 struct ip_fw_chain *chain = &layer3_chain;
2137 * We store in ulp a pointer to the upper layer protocol header.
2138 * In the ipv4 case this is easy to determine from the header,
2139 * but for ipv6 we might have some additional headers in the middle.
2140 * ulp is NULL if not found.
2142 void *ulp = NULL; /* upper layer protocol pointer. */
2143 /* XXX ipv6 variables */
2145 u_int16_t ext_hd = 0; /* bits vector for extension header filtering */
2146 /* end of ipv6 variables */
2149 if (m->m_flags & M_SKIP_FIREWALL)
2150 return (IP_FW_PASS); /* accept */
2152 pktlen = m->m_pkthdr.len;
2153 proto = args->f_id.proto = 0; /* mark f_id invalid */
2154 /* XXX 0 is a valid proto: IP/IPv6 Hop-by-Hop Option */
2157 * PULLUP_TO(len, p, T) makes sure that len + sizeof(T) is contiguous,
2158 * then it sets p to point at the offset "len" in the mbuf. WARNING: the
2159 * pointer might become stale after other pullups (but we never use it
2162 #define PULLUP_TO(len, p, T) \
2164 int x = (len) + sizeof(T); \
2165 if ((m)->m_len < x) { \
2166 args->m = m = m_pullup(m, x); \
2168 goto pullup_failed; \
2170 p = (mtod(m, char *) + (len)); \
2173 /* Identify IP packets and fill up variables. */
2174 if (pktlen >= sizeof(struct ip6_hdr) &&
2175 (args->eh == NULL || ntohs(args->eh->ether_type)==ETHERTYPE_IPV6) &&
2176 mtod(m, struct ip *)->ip_v == 6) {
2178 args->f_id.addr_type = 6;
2179 hlen = sizeof(struct ip6_hdr);
2180 proto = mtod(m, struct ip6_hdr *)->ip6_nxt;
2182 /* Search extension headers to find upper layer protocols */
2183 while (ulp == NULL) {
2185 case IPPROTO_ICMPV6:
2186 PULLUP_TO(hlen, ulp, struct icmp6_hdr);
2187 args->f_id.flags = ICMP6(ulp)->icmp6_type;
2191 PULLUP_TO(hlen, ulp, struct tcphdr);
2192 dst_port = TCP(ulp)->th_dport;
2193 src_port = TCP(ulp)->th_sport;
2194 args->f_id.flags = TCP(ulp)->th_flags;
2198 PULLUP_TO(hlen, ulp, struct udphdr);
2199 dst_port = UDP(ulp)->uh_dport;
2200 src_port = UDP(ulp)->uh_sport;
2203 case IPPROTO_HOPOPTS: /* RFC 2460 */
2204 PULLUP_TO(hlen, ulp, struct ip6_hbh);
2205 ext_hd |= EXT_HOPOPTS;
2206 hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3;
2207 proto = ((struct ip6_hbh *)ulp)->ip6h_nxt;
2211 case IPPROTO_ROUTING: /* RFC 2460 */
2212 PULLUP_TO(hlen, ulp, struct ip6_rthdr);
2213 if (((struct ip6_rthdr *)ulp)->ip6r_type != 0) {
2214 printf("IPFW2: IPV6 - Unknown Routing "
2215 "Header type(%d)\n",
2216 ((struct ip6_rthdr *)ulp)->ip6r_type);
2217 if (fw_deny_unknown_exthdrs)
2218 return (IP_FW_DENY);
2221 ext_hd |= EXT_ROUTING;
2222 hlen += (((struct ip6_rthdr *)ulp)->ip6r_len + 1) << 3;
2223 proto = ((struct ip6_rthdr *)ulp)->ip6r_nxt;
2227 case IPPROTO_FRAGMENT: /* RFC 2460 */
2228 PULLUP_TO(hlen, ulp, struct ip6_frag);
2229 ext_hd |= EXT_FRAGMENT;
2230 hlen += sizeof (struct ip6_frag);
2231 proto = ((struct ip6_frag *)ulp)->ip6f_nxt;
2232 offset = ((struct ip6_frag *)ulp)->ip6f_offlg &
2234 /* Add IP6F_MORE_FRAG for offset of first
2235 * fragment to be != 0. */
2236 offset |= ((struct ip6_frag *)ulp)->ip6f_offlg &
2239 printf("IPFW2: IPV6 - Invalid Fragment "
2241 if (fw_deny_unknown_exthdrs)
2242 return (IP_FW_DENY);
2245 args->f_id.frag_id6 =
2246 ntohl(((struct ip6_frag *)ulp)->ip6f_ident);
2250 case IPPROTO_DSTOPTS: /* RFC 2460 */
2251 PULLUP_TO(hlen, ulp, struct ip6_hbh);
2252 ext_hd |= EXT_DSTOPTS;
2253 hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3;
2254 proto = ((struct ip6_hbh *)ulp)->ip6h_nxt;
2258 case IPPROTO_AH: /* RFC 2402 */
2259 PULLUP_TO(hlen, ulp, struct ip6_ext);
2261 hlen += (((struct ip6_ext *)ulp)->ip6e_len + 2) << 2;
2262 proto = ((struct ip6_ext *)ulp)->ip6e_nxt;
2266 case IPPROTO_ESP: /* RFC 2406 */
2267 PULLUP_TO(hlen, ulp, uint32_t); /* SPI, Seq# */
2268 /* Anything past Seq# is variable length and
2269 * data past this ext. header is encrypted. */
2273 case IPPROTO_NONE: /* RFC 2460 */
2274 PULLUP_TO(hlen, ulp, struct ip6_ext);
2275 /* Packet ends here. if ip6e_len!=0 octets
2276 * must be ignored. */
2279 case IPPROTO_OSPFIGP:
2280 /* XXX OSPF header check? */
2281 PULLUP_TO(hlen, ulp, struct ip6_ext);
2285 printf("IPFW2: IPV6 - Unknown Extension "
2286 "Header(%d), ext_hd=%x\n", proto, ext_hd);
2287 if (fw_deny_unknown_exthdrs)
2288 return (IP_FW_DENY);
2292 args->f_id.src_ip6 = mtod(m,struct ip6_hdr *)->ip6_src;
2293 args->f_id.dst_ip6 = mtod(m,struct ip6_hdr *)->ip6_dst;
2294 args->f_id.src_ip = 0;
2295 args->f_id.dst_ip = 0;
2296 args->f_id.flow_id6 = ntohl(mtod(m, struct ip6_hdr *)->ip6_flow);
2297 } else if (pktlen >= sizeof(struct ip) &&
2298 (args->eh == NULL || ntohs(args->eh->ether_type) == ETHERTYPE_IP) &&
2299 mtod(m, struct ip *)->ip_v == 4) {
2301 ip = mtod(m, struct ip *);
2302 hlen = ip->ip_hl << 2;
2303 args->f_id.addr_type = 4;
2306 * Collect parameters into local variables for faster matching.
2309 src_ip = ip->ip_src;
2310 dst_ip = ip->ip_dst;
2311 if (args->eh != NULL) { /* layer 2 packets are as on the wire */
2312 offset = ntohs(ip->ip_off) & IP_OFFMASK;
2313 ip_len = ntohs(ip->ip_len);
2315 offset = ip->ip_off & IP_OFFMASK;
2316 ip_len = ip->ip_len;
2318 pktlen = ip_len < pktlen ? ip_len : pktlen;
2323 PULLUP_TO(hlen, ulp, struct tcphdr);
2324 dst_port = TCP(ulp)->th_dport;
2325 src_port = TCP(ulp)->th_sport;
2326 args->f_id.flags = TCP(ulp)->th_flags;
2330 PULLUP_TO(hlen, ulp, struct udphdr);
2331 dst_port = UDP(ulp)->uh_dport;
2332 src_port = UDP(ulp)->uh_sport;
2336 PULLUP_TO(hlen, ulp, struct icmphdr);
2337 args->f_id.flags = ICMP(ulp)->icmp_type;
2345 args->f_id.src_ip = ntohl(src_ip.s_addr);
2346 args->f_id.dst_ip = ntohl(dst_ip.s_addr);
2349 if (proto) { /* we may have port numbers, store them */
2350 args->f_id.proto = proto;
2351 args->f_id.src_port = src_port = ntohs(src_port);
2352 args->f_id.dst_port = dst_port = ntohs(dst_port);
2356 mtag = m_tag_find(m, PACKET_TAG_DIVERT, NULL);
2359 * Packet has already been tagged. Look for the next rule
2360 * to restart processing.
2362 * If fw_one_pass != 0 then just accept it.
2363 * XXX should not happen here, but optimized out in
2367 IPFW_RUNLOCK(chain);
2368 return (IP_FW_PASS);
2371 f = args->rule->next_rule;
2373 f = lookup_next_rule(args->rule);
2376 * Find the starting rule. It can be either the first
2377 * one, or the one after divert_rule if asked so.
2379 int skipto = mtag ? divert_cookie(mtag) : 0;
2382 if (args->eh == NULL && skipto != 0) {
2383 if (skipto >= IPFW_DEFAULT_RULE) {
2384 IPFW_RUNLOCK(chain);
2385 return (IP_FW_DENY); /* invalid */
2387 while (f && f->rulenum <= skipto)
2389 if (f == NULL) { /* drop packet */
2390 IPFW_RUNLOCK(chain);
2391 return (IP_FW_DENY);
2395 /* reset divert rule to avoid confusion later */
2397 divinput_flags = divert_info(mtag) &
2398 (IP_FW_DIVERT_OUTPUT_FLAG | IP_FW_DIVERT_LOOPBACK_FLAG);
2399 m_tag_delete(m, mtag);
2403 * Now scan the rules, and parse microinstructions for each rule.
2405 for (; f; f = f->next) {
2408 int skip_or; /* skip rest of OR block */
2411 if (set_disable & (1 << f->set) )
2415 for (l = f->cmd_len, cmd = f->cmd ; l > 0 ;
2416 l -= cmdlen, cmd += cmdlen) {
2420 * check_body is a jump target used when we find a
2421 * CHECK_STATE, and need to jump to the body of
2426 cmdlen = F_LEN(cmd);
2428 * An OR block (insn_1 || .. || insn_n) has the
2429 * F_OR bit set in all but the last instruction.
2430 * The first match will set "skip_or", and cause
2431 * the following instructions to be skipped until
2432 * past the one with the F_OR bit clear.
2434 if (skip_or) { /* skip this instruction */
2435 if ((cmd->len & F_OR) == 0)
2436 skip_or = 0; /* next one is good */
2439 match = 0; /* set to 1 if we succeed */
2441 switch (cmd->opcode) {
2443 * The first set of opcodes compares the packet's
2444 * fields with some pattern, setting 'match' if a
2445 * match is found. At the end of the loop there is
2446 * logic to deal with F_NOT and F_OR flags associated
2454 printf("ipfw: opcode %d unimplemented\n",
2462 * We only check offset == 0 && proto != 0,
2463 * as this ensures that we have a
2464 * packet with the ports info.
2468 if (is_ipv6) /* XXX to be fixed later */
2470 if (proto == IPPROTO_TCP ||
2471 proto == IPPROTO_UDP)
2472 match = check_uidgid(
2473 (ipfw_insn_u32 *)cmd,
2476 src_ip, src_port, &fw_ugid_cache,
2477 &ugid_lookup, args->inp);
2481 match = iface_match(m->m_pkthdr.rcvif,
2482 (ipfw_insn_if *)cmd);
2486 match = iface_match(oif, (ipfw_insn_if *)cmd);
2490 match = iface_match(oif ? oif :
2491 m->m_pkthdr.rcvif, (ipfw_insn_if *)cmd);
2495 if (args->eh != NULL) { /* have MAC header */
2496 u_int32_t *want = (u_int32_t *)
2497 ((ipfw_insn_mac *)cmd)->addr;
2498 u_int32_t *mask = (u_int32_t *)
2499 ((ipfw_insn_mac *)cmd)->mask;
2500 u_int32_t *hdr = (u_int32_t *)args->eh;
2503 ( want[0] == (hdr[0] & mask[0]) &&
2504 want[1] == (hdr[1] & mask[1]) &&
2505 want[2] == (hdr[2] & mask[2]) );
2510 if (args->eh != NULL) {
2512 ntohs(args->eh->ether_type);
2514 ((ipfw_insn_u16 *)cmd)->ports;
2517 for (i = cmdlen - 1; !match && i>0;
2519 match = (t>=p[0] && t<=p[1]);
2524 match = (offset != 0);
2527 case O_IN: /* "out" is "not in" */
2528 match = (oif == NULL);
2532 match = (args->eh != NULL);
2536 match = (cmd->arg1 & 1 && divinput_flags &
2537 IP_FW_DIVERT_LOOPBACK_FLAG) ||
2538 (cmd->arg1 & 2 && divinput_flags &
2539 IP_FW_DIVERT_OUTPUT_FLAG);
2544 * We do not allow an arg of 0 so the
2545 * check of "proto" only suffices.
2547 match = (proto == cmd->arg1);
2552 (((ipfw_insn_ip *)cmd)->addr.s_addr ==
2556 case O_IP_SRC_LOOKUP:
2557 case O_IP_DST_LOOKUP:
2560 (cmd->opcode == O_IP_DST_LOOKUP) ?
2561 dst_ip.s_addr : src_ip.s_addr;
2564 match = lookup_table(cmd->arg1, a, &v);
2567 if (cmdlen == F_INSN_SIZE(ipfw_insn_u32))
2569 ((ipfw_insn_u32 *)cmd)->d[0] == v;
2577 (cmd->opcode == O_IP_DST_MASK) ?
2578 dst_ip.s_addr : src_ip.s_addr;
2579 uint32_t *p = ((ipfw_insn_u32 *)cmd)->d;
2582 for (; !match && i>0; i-= 2, p+= 2)
2583 match = (p[0] == (a & p[1]));
2591 INADDR_TO_IFP(src_ip, tif);
2592 match = (tif != NULL);
2599 u_int32_t *d = (u_int32_t *)(cmd+1);
2601 cmd->opcode == O_IP_DST_SET ?
2607 addr -= d[0]; /* subtract base */
2608 match = (addr < cmd->arg1) &&
2609 ( d[ 1 + (addr>>5)] &
2610 (1<<(addr & 0x1f)) );
2616 (((ipfw_insn_ip *)cmd)->addr.s_addr ==
2624 INADDR_TO_IFP(dst_ip, tif);
2625 match = (tif != NULL);
2632 * offset == 0 && proto != 0 is enough
2633 * to guarantee that we have a
2634 * packet with port info.
2636 if ((proto==IPPROTO_UDP || proto==IPPROTO_TCP)
2639 (cmd->opcode == O_IP_SRCPORT) ?
2640 src_port : dst_port ;
2642 ((ipfw_insn_u16 *)cmd)->ports;
2645 for (i = cmdlen - 1; !match && i>0;
2647 match = (x>=p[0] && x<=p[1]);
2652 match = (offset == 0 && proto==IPPROTO_ICMP &&
2653 icmptype_match(ICMP(ulp), (ipfw_insn_u32 *)cmd) );
2658 match = is_ipv6 && offset == 0 &&
2659 proto==IPPROTO_ICMPV6 &&
2661 ICMP6(ulp)->icmp6_type,
2662 (ipfw_insn_u32 *)cmd);
2668 ipopts_match(mtod(m, struct ip *), cmd) );
2673 cmd->arg1 == mtod(m, struct ip *)->ip_v);
2679 if (is_ipv4) { /* only for IP packets */
2684 if (cmd->opcode == O_IPLEN)
2686 else if (cmd->opcode == O_IPTTL)
2687 x = mtod(m, struct ip *)->ip_ttl;
2688 else /* must be IPID */
2689 x = ntohs(mtod(m, struct ip *)->ip_id);
2691 match = (cmd->arg1 == x);
2694 /* otherwise we have ranges */
2695 p = ((ipfw_insn_u16 *)cmd)->ports;
2697 for (; !match && i>0; i--, p += 2)
2698 match = (x >= p[0] && x <= p[1]);
2702 case O_IPPRECEDENCE:
2704 (cmd->arg1 == (mtod(m, struct ip *)->ip_tos & 0xe0)) );
2709 flags_match(cmd, mtod(m, struct ip *)->ip_tos));
2713 if (proto == IPPROTO_TCP && offset == 0) {
2721 ((ip->ip_hl + tcp->th_off) << 2);
2723 match = (cmd->arg1 == x);
2726 /* otherwise we have ranges */
2727 p = ((ipfw_insn_u16 *)cmd)->ports;
2729 for (; !match && i>0; i--, p += 2)
2730 match = (x >= p[0] && x <= p[1]);
2735 match = (proto == IPPROTO_TCP && offset == 0 &&
2736 flags_match(cmd, TCP(ulp)->th_flags));
2740 match = (proto == IPPROTO_TCP && offset == 0 &&
2741 tcpopts_match(TCP(ulp), cmd));
2745 match = (proto == IPPROTO_TCP && offset == 0 &&
2746 ((ipfw_insn_u32 *)cmd)->d[0] ==
2751 match = (proto == IPPROTO_TCP && offset == 0 &&
2752 ((ipfw_insn_u32 *)cmd)->d[0] ==
2757 match = (proto == IPPROTO_TCP && offset == 0 &&
2758 cmd->arg1 == TCP(ulp)->th_win);
2762 /* reject packets which have SYN only */
2763 /* XXX should i also check for TH_ACK ? */
2764 match = (proto == IPPROTO_TCP && offset == 0 &&
2765 (TCP(ulp)->th_flags &
2766 (TH_RST | TH_ACK | TH_SYN)) != TH_SYN);
2770 struct altq_tag *at;
2771 ipfw_insn_altq *altq = (ipfw_insn_altq *)cmd;
2774 mtag = m_tag_find(m, PACKET_TAG_PF_QID, NULL);
2777 mtag = m_tag_get(PACKET_TAG_PF_QID,
2778 sizeof(struct altq_tag),
2782 * Let the packet fall back to the
2787 at = (struct altq_tag *)(mtag+1);
2788 at->qid = altq->qid;
2794 m_tag_prepend(m, mtag);
2800 ipfw_log(f, hlen, args, m, oif, offset);
2805 match = (random()<((ipfw_insn_u32 *)cmd)->d[0]);
2809 /* Outgoing packets automatically pass/match */
2810 match = ((oif != NULL) ||
2811 (m->m_pkthdr.rcvif == NULL) ||
2815 verify_path6(&(args->f_id.src_ip6),
2816 m->m_pkthdr.rcvif) :
2818 verify_path(src_ip, m->m_pkthdr.rcvif)));
2822 /* Outgoing packets automatically pass/match */
2823 match = (hlen > 0 && ((oif != NULL) ||
2826 verify_path6(&(args->f_id.src_ip6),
2829 verify_path(src_ip, NULL)));
2833 /* Outgoing packets automatically pass/match */
2834 if (oif == NULL && hlen > 0 &&
2835 ( (is_ipv4 && in_localaddr(src_ip))
2838 in6_localaddr(&(args->f_id.src_ip6)))
2843 is_ipv6 ? verify_path6(
2844 &(args->f_id.src_ip6),
2845 m->m_pkthdr.rcvif) :
2855 match = (m_tag_find(m,
2856 PACKET_TAG_IPSEC_IN_DONE, NULL) != NULL);
2859 match = (ipsec_getnhist(m) != 0);
2861 /* otherwise no match */
2867 IN6_ARE_ADDR_EQUAL(&args->f_id.src_ip6,
2868 &((ipfw_insn_ip6 *)cmd)->addr6);
2873 IN6_ARE_ADDR_EQUAL(&args->f_id.dst_ip6,
2874 &((ipfw_insn_ip6 *)cmd)->addr6);
2876 case O_IP6_SRC_MASK:
2878 ipfw_insn_ip6 *te = (ipfw_insn_ip6 *)cmd;
2879 struct in6_addr p = args->f_id.src_ip6;
2881 APPLY_MASK(&p, &te->mask6);
2882 match = IN6_ARE_ADDR_EQUAL(&te->addr6, &p);
2886 case O_IP6_DST_MASK:
2888 ipfw_insn_ip6 *te = (ipfw_insn_ip6 *)cmd;
2889 struct in6_addr p = args->f_id.dst_ip6;
2891 APPLY_MASK(&p, &te->mask6);
2892 match = IN6_ARE_ADDR_EQUAL(&te->addr6, &p);
2897 match= is_ipv6 && search_ip6_addr_net(&args->f_id.src_ip6);
2901 match= is_ipv6 && search_ip6_addr_net(&args->f_id.dst_ip6);
2906 flow6id_match(args->f_id.flow_id6,
2907 (ipfw_insn_u32 *) cmd);
2912 (ext_hd & ((ipfw_insn *) cmd)->arg1);
2925 * The second set of opcodes represents 'actions',
2926 * i.e. the terminal part of a rule once the packet
2927 * matches all previous patterns.
2928 * Typically there is only one action for each rule,
2929 * and the opcode is stored at the end of the rule
2930 * (but there are exceptions -- see below).
2932 * In general, here we set retval and terminate the
2933 * outer loop (would be a 'break 3' in some language,
2934 * but we need to do a 'goto done').
2937 * O_COUNT and O_SKIPTO actions:
2938 * instead of terminating, we jump to the next rule
2939 * ('goto next_rule', equivalent to a 'break 2'),
2940 * or to the SKIPTO target ('goto again' after
2941 * having set f, cmd and l), respectively.
2943 * O_LOG and O_ALTQ action parameters:
2944 * perform some action and set match = 1;
2946 * O_LIMIT and O_KEEP_STATE: these opcodes are
2947 * not real 'actions', and are stored right
2948 * before the 'action' part of the rule.
2949 * These opcodes try to install an entry in the
2950 * state tables; if successful, we continue with
2951 * the next opcode (match=1; break;), otherwise
2952 * the packet * must be dropped
2953 * ('goto done' after setting retval);
2955 * O_PROBE_STATE and O_CHECK_STATE: these opcodes
2956 * cause a lookup of the state table, and a jump
2957 * to the 'action' part of the parent rule
2958 * ('goto check_body') if an entry is found, or
2959 * (CHECK_STATE only) a jump to the next rule if
2960 * the entry is not found ('goto next_rule').
2961 * The result of the lookup is cached to make
2962 * further instances of these opcodes are
2967 if (install_state(f,
2968 (ipfw_insn_limit *)cmd, args)) {
2969 retval = IP_FW_DENY;
2970 goto done; /* error/limit violation */
2978 * dynamic rules are checked at the first
2979 * keep-state or check-state occurrence,
2980 * with the result being stored in dyn_dir.
2981 * The compiler introduces a PROBE_STATE
2982 * instruction for us when we have a
2983 * KEEP_STATE (because PROBE_STATE needs
2986 if (dyn_dir == MATCH_UNKNOWN &&
2987 (q = lookup_dyn_rule(&args->f_id,
2988 &dyn_dir, proto == IPPROTO_TCP ?
2992 * Found dynamic entry, update stats
2993 * and jump to the 'action' part of
2999 cmd = ACTION_PTR(f);
3000 l = f->cmd_len - f->act_ofs;
3005 * Dynamic entry not found. If CHECK_STATE,
3006 * skip to next rule, if PROBE_STATE just
3007 * ignore and continue with next opcode.
3009 if (cmd->opcode == O_CHECK_STATE)
3015 retval = 0; /* accept */
3020 args->rule = f; /* report matching rule */
3021 args->cookie = cmd->arg1;
3022 retval = IP_FW_DUMMYNET;
3027 struct divert_tag *dt;
3029 if (args->eh) /* not on layer 2 */
3031 mtag = m_tag_get(PACKET_TAG_DIVERT,
3032 sizeof(struct divert_tag),
3037 IPFW_RUNLOCK(chain);
3038 return (IP_FW_DENY);
3040 dt = (struct divert_tag *)(mtag+1);
3041 dt->cookie = f->rulenum;
3042 dt->info = cmd->arg1;
3043 m_tag_prepend(m, mtag);
3044 retval = (cmd->opcode == O_DIVERT) ?
3045 IP_FW_DIVERT : IP_FW_TEE;
3051 f->pcnt++; /* update stats */
3053 f->timestamp = time_uptime;
3054 if (cmd->opcode == O_COUNT)
3057 if (f->next_rule == NULL)
3058 lookup_next_rule(f);
3064 * Drop the packet and send a reject notice
3065 * if the packet is not ICMP (or is an ICMP
3066 * query), and it is not multicast/broadcast.
3068 if (hlen > 0 && is_ipv4 &&
3069 (proto != IPPROTO_ICMP ||
3070 is_icmp_query(ICMP(ulp))) &&
3071 !(m->m_flags & (M_BCAST|M_MCAST)) &&
3072 !IN_MULTICAST(ntohl(dst_ip.s_addr))) {
3073 send_reject(args, cmd->arg1,
3080 if (hlen > 0 && is_ipv6 &&
3081 (proto != IPPROTO_ICMPV6 ||
3082 (is_icmp6_query(args->f_id.flags) == 1)) &&
3083 !(m->m_flags & (M_BCAST|M_MCAST)) &&
3084 !IN6_IS_ADDR_MULTICAST(&args->f_id.dst_ip6)) {
3085 send_reject6(args, cmd->arg1,
3092 retval = IP_FW_DENY;
3096 if (args->eh) /* not valid on layer2 pkts */
3098 if (!q || dyn_dir == MATCH_FORWARD)
3100 &((ipfw_insn_sa *)cmd)->sa;
3101 retval = IP_FW_PASS;
3106 args->rule = f; /* report matching rule */
3107 args->cookie = cmd->arg1;
3108 retval = (cmd->opcode == O_NETGRAPH) ?
3109 IP_FW_NETGRAPH : IP_FW_NGTEE;
3113 panic("-- unknown opcode %d\n", cmd->opcode);
3114 } /* end of switch() on opcodes */
3116 if (cmd->len & F_NOT)
3120 if (cmd->len & F_OR)
3123 if (!(cmd->len & F_OR)) /* not an OR block, */
3124 break; /* try next rule */
3127 } /* end of inner for, scan opcodes */
3129 next_rule:; /* try next rule */
3131 } /* end of outer for, scan rules */
3132 printf("ipfw: ouch!, skip past end of rules, denying packet\n");
3133 IPFW_RUNLOCK(chain);
3134 return (IP_FW_DENY);
3137 /* Update statistics */
3140 f->timestamp = time_uptime;
3141 IPFW_RUNLOCK(chain);
3146 printf("ipfw: pullup failed\n");
3147 return (IP_FW_DENY);
3151 * When a rule is added/deleted, clear the next_rule pointers in all rules.
3152 * These will be reconstructed on the fly as packets are matched.
3155 flush_rule_ptrs(struct ip_fw_chain *chain)
3159 IPFW_WLOCK_ASSERT(chain);
3161 for (rule = chain->rules; rule; rule = rule->next)
3162 rule->next_rule = NULL;
3166 * When pipes/queues are deleted, clear the "pipe_ptr" pointer to a given
3167 * pipe/queue, or to all of them (match == NULL).
3170 flush_pipe_ptrs(struct dn_flow_set *match)
3174 IPFW_WLOCK(&layer3_chain);
3175 for (rule = layer3_chain.rules; rule; rule = rule->next) {
3176 ipfw_insn_pipe *cmd = (ipfw_insn_pipe *)ACTION_PTR(rule);
3178 if (cmd->o.opcode != O_PIPE && cmd->o.opcode != O_QUEUE)
3181 * XXX Use bcmp/bzero to handle pipe_ptr to overcome
3182 * possible alignment problems on 64-bit architectures.
3183 * This code is seldom used so we do not worry too
3184 * much about efficiency.
3186 if (match == NULL ||
3187 !bcmp(&cmd->pipe_ptr, &match, sizeof(match)) )
3188 bzero(&cmd->pipe_ptr, sizeof(cmd->pipe_ptr));
3190 IPFW_WUNLOCK(&layer3_chain);
3194 * Add a new rule to the list. Copy the rule into a malloc'ed area, then
3195 * possibly create a rule number and add the rule to the list.
3196 * Update the rule_number in the input struct so the caller knows it as well.
3199 add_rule(struct ip_fw_chain *chain, struct ip_fw *input_rule)
3201 struct ip_fw *rule, *f, *prev;
3202 int l = RULESIZE(input_rule);
3204 if (chain->rules == NULL && input_rule->rulenum != IPFW_DEFAULT_RULE)
3207 rule = malloc(l, M_IPFW, M_NOWAIT | M_ZERO);
3211 bcopy(input_rule, rule, l);
3214 rule->next_rule = NULL;
3218 rule->timestamp = 0;
3222 if (chain->rules == NULL) { /* default rule */
3223 chain->rules = rule;
3228 * If rulenum is 0, find highest numbered rule before the
3229 * default rule, and add autoinc_step
3231 if (autoinc_step < 1)
3233 else if (autoinc_step > 1000)
3234 autoinc_step = 1000;
3235 if (rule->rulenum == 0) {
3237 * locate the highest numbered rule before default
3239 for (f = chain->rules; f; f = f->next) {
3240 if (f->rulenum == IPFW_DEFAULT_RULE)
3242 rule->rulenum = f->rulenum;
3244 if (rule->rulenum < IPFW_DEFAULT_RULE - autoinc_step)
3245 rule->rulenum += autoinc_step;
3246 input_rule->rulenum = rule->rulenum;
3250 * Now insert the new rule in the right place in the sorted list.
3252 for (prev = NULL, f = chain->rules; f; prev = f, f = f->next) {
3253 if (f->rulenum > rule->rulenum) { /* found the location */
3257 } else { /* head insert */
3258 rule->next = chain->rules;
3259 chain->rules = rule;
3264 flush_rule_ptrs(chain);
3268 IPFW_WUNLOCK(chain);
3269 DEB(printf("ipfw: installed rule %d, static count now %d\n",
3270 rule->rulenum, static_count);)
3275 * Remove a static rule (including derived * dynamic rules)
3276 * and place it on the ``reap list'' for later reclamation.
3277 * The caller is in charge of clearing rule pointers to avoid
3278 * dangling pointers.
3279 * @return a pointer to the next entry.
3280 * Arguments are not checked, so they better be correct.
3282 static struct ip_fw *
3283 remove_rule(struct ip_fw_chain *chain, struct ip_fw *rule, struct ip_fw *prev)
3286 int l = RULESIZE(rule);
3288 IPFW_WLOCK_ASSERT(chain);
3292 remove_dyn_rule(rule, NULL /* force removal */);
3301 rule->next = chain->reap;
3308 * Reclaim storage associated with a list of rules. This is
3309 * typically the list created using remove_rule.
3312 reap_rules(struct ip_fw *head)
3316 while ((rule = head) != NULL) {
3318 if (DUMMYNET_LOADED)
3319 ip_dn_ruledel_ptr(rule);
3325 * Remove all rules from a chain (except rules in set RESVD_SET
3326 * unless kill_default = 1). The caller is responsible for
3327 * reclaiming storage for the rules left in chain->reap.
3330 free_chain(struct ip_fw_chain *chain, int kill_default)
3332 struct ip_fw *prev, *rule;
3334 IPFW_WLOCK_ASSERT(chain);
3336 flush_rule_ptrs(chain); /* more efficient to do outside the loop */
3337 for (prev = NULL, rule = chain->rules; rule ; )
3338 if (kill_default || rule->set != RESVD_SET)
3339 rule = remove_rule(chain, rule, prev);
3347 * Remove all rules with given number, and also do set manipulation.
3348 * Assumes chain != NULL && *chain != NULL.
3350 * The argument is an u_int32_t. The low 16 bit are the rule or set number,
3351 * the next 8 bits are the new set, the top 8 bits are the command:
3353 * 0 delete rules with given number
3354 * 1 delete rules with given set number
3355 * 2 move rules with given number to new set
3356 * 3 move rules with given set number to new set
3357 * 4 swap sets with given numbers
3360 del_entry(struct ip_fw_chain *chain, u_int32_t arg)
3362 struct ip_fw *prev = NULL, *rule;
3363 u_int16_t rulenum; /* rule or old_set */
3364 u_int8_t cmd, new_set;
3366 rulenum = arg & 0xffff;
3367 cmd = (arg >> 24) & 0xff;
3368 new_set = (arg >> 16) & 0xff;
3372 if (new_set > RESVD_SET)
3374 if (cmd == 0 || cmd == 2) {
3375 if (rulenum >= IPFW_DEFAULT_RULE)
3378 if (rulenum > RESVD_SET) /* old_set */
3383 rule = chain->rules;
3386 case 0: /* delete rules with given number */
3388 * locate first rule to delete
3390 for (; rule->rulenum < rulenum; prev = rule, rule = rule->next)
3392 if (rule->rulenum != rulenum) {
3393 IPFW_WUNLOCK(chain);
3398 * flush pointers outside the loop, then delete all matching
3399 * rules. prev remains the same throughout the cycle.
3401 flush_rule_ptrs(chain);
3402 while (rule->rulenum == rulenum)
3403 rule = remove_rule(chain, rule, prev);
3406 case 1: /* delete all rules with given set number */
3407 flush_rule_ptrs(chain);
3408 rule = chain->rules;
3409 while (rule->rulenum < IPFW_DEFAULT_RULE)
3410 if (rule->set == rulenum)
3411 rule = remove_rule(chain, rule, prev);
3418 case 2: /* move rules with given number to new set */
3419 rule = chain->rules;
3420 for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
3421 if (rule->rulenum == rulenum)
3422 rule->set = new_set;
3425 case 3: /* move rules with given set number to new set */
3426 for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
3427 if (rule->set == rulenum)
3428 rule->set = new_set;
3431 case 4: /* swap two sets */
3432 for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
3433 if (rule->set == rulenum)
3434 rule->set = new_set;
3435 else if (rule->set == new_set)
3436 rule->set = rulenum;
3440 * Look for rules to reclaim. We grab the list before
3441 * releasing the lock then reclaim them w/o the lock to
3442 * avoid a LOR with dummynet.
3446 IPFW_WUNLOCK(chain);
3453 * Clear counters for a specific rule.
3454 * The enclosing "table" is assumed locked.
3457 clear_counters(struct ip_fw *rule, int log_only)
3459 ipfw_insn_log *l = (ipfw_insn_log *)ACTION_PTR(rule);
3461 if (log_only == 0) {
3462 rule->bcnt = rule->pcnt = 0;
3463 rule->timestamp = 0;
3465 if (l->o.opcode == O_LOG)
3466 l->log_left = l->max_log;
3470 * Reset some or all counters on firewall rules.
3471 * @arg frwl is null to clear all entries, or contains a specific
3473 * @arg log_only is 1 if we only want to reset logs, zero otherwise.
3476 zero_entry(struct ip_fw_chain *chain, int rulenum, int log_only)
3484 for (rule = chain->rules; rule; rule = rule->next)
3485 clear_counters(rule, log_only);
3486 msg = log_only ? "ipfw: All logging counts reset.\n" :
3487 "ipfw: Accounting cleared.\n";
3491 * We can have multiple rules with the same number, so we
3492 * need to clear them all.
3494 for (rule = chain->rules; rule; rule = rule->next)
3495 if (rule->rulenum == rulenum) {
3496 while (rule && rule->rulenum == rulenum) {
3497 clear_counters(rule, log_only);
3503 if (!cleared) { /* we did not find any matching rules */
3504 IPFW_WUNLOCK(chain);
3507 msg = log_only ? "ipfw: Entry %d logging count reset.\n" :
3508 "ipfw: Entry %d cleared.\n";
3510 IPFW_WUNLOCK(chain);
3513 log(LOG_SECURITY | LOG_NOTICE, msg, rulenum);
3518 * Check validity of the structure before insert.
3519 * Fortunately rules are simple, so this mostly need to check rule sizes.
3522 check_ipfw_struct(struct ip_fw *rule, int size)
3528 if (size < sizeof(*rule)) {
3529 printf("ipfw: rule too short\n");
3532 /* first, check for valid size */
3535 printf("ipfw: size mismatch (have %d want %d)\n", size, l);
3538 if (rule->act_ofs >= rule->cmd_len) {
3539 printf("ipfw: bogus action offset (%u > %u)\n",
3540 rule->act_ofs, rule->cmd_len - 1);
3544 * Now go for the individual checks. Very simple ones, basically only
3545 * instruction sizes.
3547 for (l = rule->cmd_len, cmd = rule->cmd ;
3548 l > 0 ; l -= cmdlen, cmd += cmdlen) {
3549 cmdlen = F_LEN(cmd);
3551 printf("ipfw: opcode %d size truncated\n",
3555 DEB(printf("ipfw: opcode %d\n", cmd->opcode);)
3556 switch (cmd->opcode) {
3568 case O_IPPRECEDENCE:
3585 if (cmdlen != F_INSN_SIZE(ipfw_insn))
3598 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32))
3603 if (cmdlen != F_INSN_SIZE(ipfw_insn_limit))
3608 if (cmdlen != F_INSN_SIZE(ipfw_insn_log))
3611 ((ipfw_insn_log *)cmd)->log_left =
3612 ((ipfw_insn_log *)cmd)->max_log;
3618 /* only odd command lengths */
3619 if ( !(cmdlen & 1) || cmdlen > 31)
3625 if (cmd->arg1 == 0 || cmd->arg1 > 256) {
3626 printf("ipfw: invalid set size %d\n",
3630 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
3635 case O_IP_SRC_LOOKUP:
3636 case O_IP_DST_LOOKUP:
3637 if (cmd->arg1 >= IPFW_TABLES_MAX) {
3638 printf("ipfw: invalid table number %d\n",
3642 if (cmdlen != F_INSN_SIZE(ipfw_insn) &&
3643 cmdlen != F_INSN_SIZE(ipfw_insn_u32))
3648 if (cmdlen != F_INSN_SIZE(ipfw_insn_mac))
3657 if (cmdlen < 1 || cmdlen > 31)
3663 case O_IP_DSTPORT: /* XXX artificial limit, 30 port pairs */
3664 if (cmdlen < 2 || cmdlen > 31)
3671 if (cmdlen != F_INSN_SIZE(ipfw_insn_if))
3676 if (cmdlen != F_INSN_SIZE(ipfw_insn_altq))
3682 if (cmdlen != F_INSN_SIZE(ipfw_insn_pipe))
3687 #ifdef IPFIREWALL_FORWARD
3688 if (cmdlen != F_INSN_SIZE(ipfw_insn_sa))
3697 if (ip_divert_ptr == NULL)
3703 if (!NG_IPFW_LOADED)
3707 case O_FORWARD_MAC: /* XXX not implemented yet */
3718 if (cmdlen != F_INSN_SIZE(ipfw_insn))
3722 printf("ipfw: opcode %d, multiple actions"
3729 printf("ipfw: opcode %d, action must be"
3738 if (cmdlen != F_INSN_SIZE(struct in6_addr) +
3739 F_INSN_SIZE(ipfw_insn))
3744 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
3745 ((ipfw_insn_u32 *)cmd)->o.arg1)
3749 case O_IP6_SRC_MASK:
3750 case O_IP6_DST_MASK:
3751 if ( !(cmdlen & 1) || cmdlen > 127)
3755 if( cmdlen != F_INSN_SIZE( ipfw_insn_icmp6 ) )
3761 switch (cmd->opcode) {
3771 case O_IP6_SRC_MASK:
3772 case O_IP6_DST_MASK:
3774 printf("ipfw: no IPv6 support in kernel\n");
3775 return EPROTONOSUPPORT;
3778 printf("ipfw: opcode %d, unknown opcode\n",
3784 if (have_action == 0) {
3785 printf("ipfw: missing action\n");
3791 printf("ipfw: opcode %d size %d wrong\n",
3792 cmd->opcode, cmdlen);
3797 * Copy the static and dynamic rules to the supplied buffer
3798 * and return the amount of space actually used.
3801 ipfw_getrules(struct ip_fw_chain *chain, void *buf, size_t space)
3804 char *ep = bp + space;
3808 /* XXX this can take a long time and locking will block packet flow */
3810 for (rule = chain->rules; rule ; rule = rule->next) {
3812 * Verify the entry fits in the buffer in case the
3813 * rules changed between calculating buffer space and
3814 * now. This would be better done using a generation
3815 * number but should suffice for now.
3820 bcopy(&set_disable, &(((struct ip_fw *)bp)->next_rule),
3821 sizeof(set_disable));
3825 IPFW_RUNLOCK(chain);
3827 ipfw_dyn_rule *p, *last = NULL;
3830 for (i = 0 ; i < curr_dyn_buckets; i++)
3831 for (p = ipfw_dyn_v[i] ; p != NULL; p = p->next) {
3832 if (bp + sizeof *p <= ep) {
3833 ipfw_dyn_rule *dst =
3834 (ipfw_dyn_rule *)bp;
3835 bcopy(p, dst, sizeof *p);
3836 bcopy(&(p->rule->rulenum), &(dst->rule),
3837 sizeof(p->rule->rulenum));
3839 * store a non-null value in "next".
3840 * The userland code will interpret a
3841 * NULL here as a marker
3842 * for the last dynamic rule.
3844 bcopy(&dst, &dst->next, sizeof(dst));
3847 TIME_LEQ(dst->expire, time_uptime) ?
3848 0 : dst->expire - time_uptime ;
3849 bp += sizeof(ipfw_dyn_rule);
3853 if (last != NULL) /* mark last dynamic rule */
3854 bzero(&last->next, sizeof(last));
3856 return (bp - (char *)buf);
3861 * {set|get}sockopt parser.
3864 ipfw_ctl(struct sockopt *sopt)
3866 #define RULE_MAXSIZE (256*sizeof(u_int32_t))
3867 int error, rule_num;
3869 struct ip_fw *buf, *rule;
3870 u_int32_t rulenum[2];
3872 error = suser(sopt->sopt_td);
3877 * Disallow modifications in really-really secure mode, but still allow
3878 * the logging counters to be reset.
3880 if (sopt->sopt_name == IP_FW_ADD ||
3881 (sopt->sopt_dir == SOPT_SET && sopt->sopt_name != IP_FW_RESETLOG)) {
3882 #if __FreeBSD_version >= 500034
3883 error = securelevel_ge(sopt->sopt_td->td_ucred, 3);
3886 #else /* FreeBSD 4.x */
3887 if (securelevel >= 3)
3894 switch (sopt->sopt_name) {
3897 * pass up a copy of the current rules. Static rules
3898 * come first (the last of which has number IPFW_DEFAULT_RULE),
3899 * followed by a possibly empty list of dynamic rule.
3900 * The last dynamic rule has NULL in the "next" field.
3902 * Note that the calculated size is used to bound the
3903 * amount of data returned to the user. The rule set may
3904 * change between calculating the size and returning the
3905 * data in which case we'll just return what fits.
3907 size = static_len; /* size of static rules */
3908 if (ipfw_dyn_v) /* add size of dyn.rules */
3909 size += (dyn_count * sizeof(ipfw_dyn_rule));
3912 * XXX todo: if the user passes a short length just to know
3913 * how much room is needed, do not bother filling up the
3914 * buffer, just jump to the sooptcopyout.
3916 buf = malloc(size, M_TEMP, M_WAITOK);
3917 error = sooptcopyout(sopt, buf,
3918 ipfw_getrules(&layer3_chain, buf, size));
3924 * Normally we cannot release the lock on each iteration.
3925 * We could do it here only because we start from the head all
3926 * the times so there is no risk of missing some entries.
3927 * On the other hand, the risk is that we end up with
3928 * a very inconsistent ruleset, so better keep the lock
3929 * around the whole cycle.
3931 * XXX this code can be improved by resetting the head of
3932 * the list to point to the default rule, and then freeing
3933 * the old list without the need for a lock.
3936 IPFW_WLOCK(&layer3_chain);
3937 layer3_chain.reap = NULL;
3938 free_chain(&layer3_chain, 0 /* keep default rule */);
3939 rule = layer3_chain.reap, layer3_chain.reap = NULL;
3940 IPFW_WUNLOCK(&layer3_chain);
3941 if (layer3_chain.reap != NULL)
3946 rule = malloc(RULE_MAXSIZE, M_TEMP, M_WAITOK);
3947 error = sooptcopyin(sopt, rule, RULE_MAXSIZE,
3948 sizeof(struct ip_fw) );
3950 error = check_ipfw_struct(rule, sopt->sopt_valsize);
3952 error = add_rule(&layer3_chain, rule);
3953 size = RULESIZE(rule);
3954 if (!error && sopt->sopt_dir == SOPT_GET)
3955 error = sooptcopyout(sopt, rule, size);
3962 * IP_FW_DEL is used for deleting single rules or sets,
3963 * and (ab)used to atomically manipulate sets. Argument size
3964 * is used to distinguish between the two:
3966 * delete single rule or set of rules,
3967 * or reassign rules (or sets) to a different set.
3968 * 2*sizeof(u_int32_t)
3969 * atomic disable/enable sets.
3970 * first u_int32_t contains sets to be disabled,
3971 * second u_int32_t contains sets to be enabled.
3973 error = sooptcopyin(sopt, rulenum,
3974 2*sizeof(u_int32_t), sizeof(u_int32_t));
3977 size = sopt->sopt_valsize;
3978 if (size == sizeof(u_int32_t)) /* delete or reassign */
3979 error = del_entry(&layer3_chain, rulenum[0]);
3980 else if (size == 2*sizeof(u_int32_t)) /* set enable/disable */
3982 (set_disable | rulenum[0]) & ~rulenum[1] &
3983 ~(1<<RESVD_SET); /* set RESVD_SET always enabled */
3989 case IP_FW_RESETLOG: /* argument is an int, the rule number */
3991 if (sopt->sopt_val != 0) {
3992 error = sooptcopyin(sopt, &rule_num,
3993 sizeof(int), sizeof(int));
3997 error = zero_entry(&layer3_chain, rule_num,
3998 sopt->sopt_name == IP_FW_RESETLOG);
4001 case IP_FW_TABLE_ADD:
4003 ipfw_table_entry ent;
4005 error = sooptcopyin(sopt, &ent,
4006 sizeof(ent), sizeof(ent));
4009 error = add_table_entry(ent.tbl, ent.addr,
4010 ent.masklen, ent.value);
4014 case IP_FW_TABLE_DEL:
4016 ipfw_table_entry ent;
4018 error = sooptcopyin(sopt, &ent,
4019 sizeof(ent), sizeof(ent));
4022 error = del_table_entry(ent.tbl, ent.addr, ent.masklen);
4026 case IP_FW_TABLE_FLUSH:
4030 error = sooptcopyin(sopt, &tbl,
4031 sizeof(tbl), sizeof(tbl));
4034 error = flush_table(tbl);
4038 case IP_FW_TABLE_GETSIZE:
4042 if ((error = sooptcopyin(sopt, &tbl, sizeof(tbl),
4045 if ((error = count_table(tbl, &cnt)))
4047 error = sooptcopyout(sopt, &cnt, sizeof(cnt));
4051 case IP_FW_TABLE_LIST:
4055 if (sopt->sopt_valsize < sizeof(*tbl)) {
4059 size = sopt->sopt_valsize;
4060 tbl = malloc(size, M_TEMP, M_WAITOK);
4065 error = sooptcopyin(sopt, tbl, size, sizeof(*tbl));
4070 tbl->size = (size - sizeof(*tbl)) /
4071 sizeof(ipfw_table_entry);
4072 error = dump_table(tbl);
4077 error = sooptcopyout(sopt, tbl, size);
4083 printf("ipfw: ipfw_ctl invalid option %d\n", sopt->sopt_name);
4092 * dummynet needs a reference to the default rule, because rules can be
4093 * deleted while packets hold a reference to them. When this happens,
4094 * dummynet changes the reference to the default rule (it could well be a
4095 * NULL pointer, but this way we do not need to check for the special
4096 * case, plus here he have info on the default behaviour).
4098 struct ip_fw *ip_fw_default_rule;
4101 * This procedure is only used to handle keepalives. It is invoked
4102 * every dyn_keepalive_period
4105 ipfw_tick(void * __unused unused)
4107 struct mbuf *m0, *m, *mnext, **mtailp;
4111 if (dyn_keepalive == 0 || ipfw_dyn_v == NULL || dyn_count == 0)
4115 * We make a chain of packets to go out here -- not deferring
4116 * until after we drop the IPFW dynamic rule lock would result
4117 * in a lock order reversal with the normal packet input -> ipfw
4123 for (i = 0 ; i < curr_dyn_buckets ; i++) {
4124 for (q = ipfw_dyn_v[i] ; q ; q = q->next ) {
4125 if (q->dyn_type == O_LIMIT_PARENT)
4127 if (q->id.proto != IPPROTO_TCP)
4129 if ( (q->state & BOTH_SYN) != BOTH_SYN)
4131 if (TIME_LEQ( time_uptime+dyn_keepalive_interval,
4133 continue; /* too early */
4134 if (TIME_LEQ(q->expire, time_uptime))
4135 continue; /* too late, rule expired */
4137 *mtailp = send_pkt(&(q->id), q->ack_rev - 1,
4138 q->ack_fwd, TH_SYN);
4139 if (*mtailp != NULL)
4140 mtailp = &(*mtailp)->m_nextpkt;
4141 *mtailp = send_pkt(&(q->id), q->ack_fwd - 1,
4143 if (*mtailp != NULL)
4144 mtailp = &(*mtailp)->m_nextpkt;
4148 for (m = mnext = m0; m != NULL; m = mnext) {
4149 mnext = m->m_nextpkt;
4150 m->m_nextpkt = NULL;
4151 ip_output(m, NULL, NULL, 0, NULL, NULL);
4154 callout_reset(&ipfw_timeout, dyn_keepalive_period*hz, ipfw_tick, NULL);
4160 struct ip_fw default_rule;
4164 /* Setup IPv6 fw sysctl tree. */
4165 sysctl_ctx_init(&ip6_fw_sysctl_ctx);
4166 ip6_fw_sysctl_tree = SYSCTL_ADD_NODE(&ip6_fw_sysctl_ctx,
4167 SYSCTL_STATIC_CHILDREN(_net_inet6_ip6), OID_AUTO, "fw",
4168 CTLFLAG_RW | CTLFLAG_SECURE, 0, "Firewall");
4169 SYSCTL_ADD_INT(&ip6_fw_sysctl_ctx, SYSCTL_CHILDREN(ip6_fw_sysctl_tree),
4170 OID_AUTO, "deny_unknown_exthdrs", CTLFLAG_RW | CTLFLAG_SECURE,
4171 &fw_deny_unknown_exthdrs, 0,
4172 "Deny packets with unknown IPv6 Extension Headers");
4175 layer3_chain.rules = NULL;
4176 layer3_chain.want_write = 0;
4177 layer3_chain.busy_count = 0;
4178 cv_init(&layer3_chain.cv, "Condition variable for IPFW rw locks");
4179 IPFW_LOCK_INIT(&layer3_chain);
4180 ipfw_dyn_rule_zone = uma_zcreate("IPFW dynamic rule zone",
4181 sizeof(ipfw_dyn_rule), NULL, NULL, NULL, NULL,
4183 IPFW_DYN_LOCK_INIT();
4184 callout_init(&ipfw_timeout, NET_CALLOUT_MPSAFE);
4186 bzero(&default_rule, sizeof default_rule);
4188 default_rule.act_ofs = 0;
4189 default_rule.rulenum = IPFW_DEFAULT_RULE;
4190 default_rule.cmd_len = 1;
4191 default_rule.set = RESVD_SET;
4193 default_rule.cmd[0].len = 1;
4194 default_rule.cmd[0].opcode =
4195 #ifdef IPFIREWALL_DEFAULT_TO_ACCEPT
4200 error = add_rule(&layer3_chain, &default_rule);
4202 printf("ipfw2: error %u initializing default rule "
4203 "(support disabled)\n", error);
4204 IPFW_DYN_LOCK_DESTROY();
4205 IPFW_LOCK_DESTROY(&layer3_chain);
4209 ip_fw_default_rule = layer3_chain.rules;
4210 printf("ipfw2 (+ipv6) initialized, divert %s, "
4211 "rule-based forwarding "
4212 #ifdef IPFIREWALL_FORWARD
4217 "default to %s, logging ",
4223 default_rule.cmd[0].opcode == O_ACCEPT ? "accept" : "deny");
4225 #ifdef IPFIREWALL_VERBOSE
4228 #ifdef IPFIREWALL_VERBOSE_LIMIT
4229 verbose_limit = IPFIREWALL_VERBOSE_LIMIT;
4231 if (fw_verbose == 0)
4232 printf("disabled\n");
4233 else if (verbose_limit == 0)
4234 printf("unlimited\n");
4236 printf("limited to %d packets/entry by default\n",
4240 ip_fw_ctl_ptr = ipfw_ctl;
4241 ip_fw_chk_ptr = ipfw_chk;
4242 callout_reset(&ipfw_timeout, hz, ipfw_tick, NULL);
4252 ip_fw_chk_ptr = NULL;
4253 ip_fw_ctl_ptr = NULL;
4254 callout_drain(&ipfw_timeout);
4255 IPFW_WLOCK(&layer3_chain);
4256 layer3_chain.reap = NULL;
4257 free_chain(&layer3_chain, 1 /* kill default rule */);
4258 reap = layer3_chain.reap, layer3_chain.reap = NULL;
4259 IPFW_WUNLOCK(&layer3_chain);
4263 IPFW_DYN_LOCK_DESTROY();
4264 uma_zdestroy(ipfw_dyn_rule_zone);
4265 IPFW_LOCK_DESTROY(&layer3_chain);
4268 /* Free IPv6 fw sysctl tree. */
4269 sysctl_ctx_free(&ip6_fw_sysctl_ctx);
4272 printf("IP firewall unloaded\n");