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)
38 #include "opt_ipdivert.h"
41 #error IPFIREWALL requires INET.
47 #include <sys/param.h>
48 #include <sys/systm.h>
49 #include <sys/malloc.h>
51 #include <sys/kernel.h>
53 #include <sys/socket.h>
54 #include <sys/socketvar.h>
55 #include <sys/sysctl.h>
56 #include <sys/syslog.h>
57 #include <sys/ucred.h>
59 #include <net/route.h>
60 #include <netinet/in.h>
61 #include <netinet/in_systm.h>
62 #include <netinet/in_var.h>
63 #include <netinet/in_pcb.h>
64 #include <netinet/ip.h>
65 #include <netinet/ip_var.h>
66 #include <netinet/ip_icmp.h>
67 #include <netinet/ip_fw.h>
68 #include <netinet/ip_dummynet.h>
69 #include <netinet/tcp.h>
70 #include <netinet/tcp_timer.h>
71 #include <netinet/tcp_var.h>
72 #include <netinet/tcpip.h>
73 #include <netinet/udp.h>
74 #include <netinet/udp_var.h>
77 #include <netinet6/ipsec.h>
80 #include <netinet/if_ether.h> /* XXX for ETHERTYPE_IP */
82 #include <machine/in_cksum.h> /* XXX for in_cksum */
85 * XXX This one should go in sys/mbuf.h. It is used to avoid that
86 * a firewall-generated packet loops forever through the firewall.
88 #ifndef M_SKIP_FIREWALL
89 #define M_SKIP_FIREWALL 0x4000
93 * set_disable contains one bit per set value (0..31).
94 * If the bit is set, all rules with the corresponding set
95 * are disabled. Set RESVD_SET(31) is reserved for the default rule
96 * and rules that are not deleted by the flush command,
97 * and CANNOT be disabled.
98 * Rules in set RESVD_SET can only be deleted explicitly.
100 static u_int32_t set_disable;
102 static int fw_verbose;
103 static int verbose_limit;
105 static struct callout ipfw_timeout;
106 #define IPFW_DEFAULT_RULE 65535
109 struct ip_fw *rules; /* list of rules */
110 struct ip_fw *reap; /* list of rules to reap */
111 struct mtx mtx; /* lock guarding rule list */
113 #define IPFW_LOCK_INIT(_chain) \
114 mtx_init(&(_chain)->mtx, "IPFW static rules", NULL, \
115 MTX_DEF | MTX_RECURSE)
116 #define IPFW_LOCK_DESTROY(_chain) mtx_destroy(&(_chain)->mtx)
117 #define IPFW_LOCK(_chain) mtx_lock(&(_chain)->mtx)
118 #define IPFW_UNLOCK(_chain) mtx_unlock(&(_chain)->mtx)
119 #define IPFW_LOCK_ASSERT(_chain) mtx_assert(&(_chain)->mtx, MA_OWNED)
122 * list of rules for layer 3
124 static struct ip_fw_chain layer3_chain;
126 MALLOC_DEFINE(M_IPFW, "IpFw/IpAcct", "IpFw/IpAcct chain's");
128 static int fw_debug = 1;
129 static int autoinc_step = 100; /* bounded to 1..1000 in add_rule() */
132 SYSCTL_NODE(_net_inet_ip, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall");
133 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, enable,
134 CTLFLAG_RW | CTLFLAG_SECURE3,
135 &fw_enable, 0, "Enable ipfw");
136 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, autoinc_step, CTLFLAG_RW,
137 &autoinc_step, 0, "Rule number autincrement step");
138 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, one_pass,
139 CTLFLAG_RW | CTLFLAG_SECURE3,
141 "Only do a single pass through ipfw when using dummynet(4)");
142 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, debug, CTLFLAG_RW,
143 &fw_debug, 0, "Enable printing of debug ip_fw statements");
144 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose,
145 CTLFLAG_RW | CTLFLAG_SECURE3,
146 &fw_verbose, 0, "Log matches to ipfw rules");
147 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose_limit, CTLFLAG_RW,
148 &verbose_limit, 0, "Set upper limit of matches of ipfw rules logged");
151 * Description of dynamic rules.
153 * Dynamic rules are stored in lists accessed through a hash table
154 * (ipfw_dyn_v) whose size is curr_dyn_buckets. This value can
155 * be modified through the sysctl variable dyn_buckets which is
156 * updated when the table becomes empty.
158 * XXX currently there is only one list, ipfw_dyn.
160 * When a packet is received, its address fields are first masked
161 * with the mask defined for the rule, then hashed, then matched
162 * against the entries in the corresponding list.
163 * Dynamic rules can be used for different purposes:
165 * + enforcing limits on the number of sessions;
166 * + in-kernel NAT (not implemented yet)
168 * The lifetime of dynamic rules is regulated by dyn_*_lifetime,
169 * measured in seconds and depending on the flags.
171 * The total number of dynamic rules is stored in dyn_count.
172 * The max number of dynamic rules is dyn_max. When we reach
173 * the maximum number of rules we do not create anymore. This is
174 * done to avoid consuming too much memory, but also too much
175 * time when searching on each packet (ideally, we should try instead
176 * to put a limit on the length of the list on each bucket...).
178 * Each dynamic rule holds a pointer to the parent ipfw rule so
179 * we know what action to perform. Dynamic rules are removed when
180 * the parent rule is deleted. XXX we should make them survive.
182 * There are some limitations with dynamic rules -- we do not
183 * obey the 'randomized match', and we do not do multiple
184 * passes through the firewall. XXX check the latter!!!
186 static ipfw_dyn_rule **ipfw_dyn_v = NULL;
187 static u_int32_t dyn_buckets = 256; /* must be power of 2 */
188 static u_int32_t curr_dyn_buckets = 256; /* must be power of 2 */
190 static struct mtx ipfw_dyn_mtx; /* mutex guarding dynamic rules */
191 #define IPFW_DYN_LOCK_INIT() \
192 mtx_init(&ipfw_dyn_mtx, "IPFW dynamic rules", NULL, MTX_DEF)
193 #define IPFW_DYN_LOCK_DESTROY() mtx_destroy(&ipfw_dyn_mtx)
194 #define IPFW_DYN_LOCK() mtx_lock(&ipfw_dyn_mtx)
195 #define IPFW_DYN_UNLOCK() mtx_unlock(&ipfw_dyn_mtx)
196 #define IPFW_DYN_LOCK_ASSERT() mtx_assert(&ipfw_dyn_mtx, MA_OWNED)
199 * Timeouts for various events in handing dynamic rules.
201 static u_int32_t dyn_ack_lifetime = 300;
202 static u_int32_t dyn_syn_lifetime = 20;
203 static u_int32_t dyn_fin_lifetime = 1;
204 static u_int32_t dyn_rst_lifetime = 1;
205 static u_int32_t dyn_udp_lifetime = 10;
206 static u_int32_t dyn_short_lifetime = 5;
209 * Keepalives are sent if dyn_keepalive is set. They are sent every
210 * dyn_keepalive_period seconds, in the last dyn_keepalive_interval
211 * seconds of lifetime of a rule.
212 * dyn_rst_lifetime and dyn_fin_lifetime should be strictly lower
213 * than dyn_keepalive_period.
216 static u_int32_t dyn_keepalive_interval = 20;
217 static u_int32_t dyn_keepalive_period = 5;
218 static u_int32_t dyn_keepalive = 1; /* do send keepalives */
220 static u_int32_t static_count; /* # of static rules */
221 static u_int32_t static_len; /* size in bytes of static rules */
222 static u_int32_t dyn_count; /* # of dynamic rules */
223 static u_int32_t dyn_max = 4096; /* max # of dynamic rules */
225 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_buckets, CTLFLAG_RW,
226 &dyn_buckets, 0, "Number of dyn. buckets");
227 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, curr_dyn_buckets, CTLFLAG_RD,
228 &curr_dyn_buckets, 0, "Current Number of dyn. buckets");
229 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_count, CTLFLAG_RD,
230 &dyn_count, 0, "Number of dyn. rules");
231 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_max, CTLFLAG_RW,
232 &dyn_max, 0, "Max number of dyn. rules");
233 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, static_count, CTLFLAG_RD,
234 &static_count, 0, "Number of static rules");
235 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_ack_lifetime, CTLFLAG_RW,
236 &dyn_ack_lifetime, 0, "Lifetime of dyn. rules for acks");
237 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_syn_lifetime, CTLFLAG_RW,
238 &dyn_syn_lifetime, 0, "Lifetime of dyn. rules for syn");
239 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_fin_lifetime, CTLFLAG_RW,
240 &dyn_fin_lifetime, 0, "Lifetime of dyn. rules for fin");
241 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_rst_lifetime, CTLFLAG_RW,
242 &dyn_rst_lifetime, 0, "Lifetime of dyn. rules for rst");
243 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_udp_lifetime, CTLFLAG_RW,
244 &dyn_udp_lifetime, 0, "Lifetime of dyn. rules for UDP");
245 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_short_lifetime, CTLFLAG_RW,
246 &dyn_short_lifetime, 0, "Lifetime of dyn. rules for other situations");
247 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_keepalive, CTLFLAG_RW,
248 &dyn_keepalive, 0, "Enable keepalives for dyn. rules");
250 #endif /* SYSCTL_NODE */
253 static ip_fw_chk_t ipfw_chk;
255 ip_dn_ruledel_t *ip_dn_ruledel_ptr = NULL; /* hook into dummynet */
258 * This macro maps an ip pointer into a layer3 header pointer of type T
260 #define L3HDR(T, ip) ((T *)((u_int32_t *)(ip) + (ip)->ip_hl))
263 icmptype_match(struct ip *ip, ipfw_insn_u32 *cmd)
265 int type = L3HDR(struct icmp,ip)->icmp_type;
267 return (type <= ICMP_MAXTYPE && (cmd->d[0] & (1<<type)) );
270 #define TT ( (1 << ICMP_ECHO) | (1 << ICMP_ROUTERSOLICIT) | \
271 (1 << ICMP_TSTAMP) | (1 << ICMP_IREQ) | (1 << ICMP_MASKREQ) )
274 is_icmp_query(struct ip *ip)
276 int type = L3HDR(struct icmp, ip)->icmp_type;
277 return (type <= ICMP_MAXTYPE && (TT & (1<<type)) );
282 * The following checks use two arrays of 8 or 16 bits to store the
283 * bits that we want set or clear, respectively. They are in the
284 * low and high half of cmd->arg1 or cmd->d[0].
286 * We scan options and store the bits we find set. We succeed if
288 * (want_set & ~bits) == 0 && (want_clear & ~bits) == want_clear
290 * The code is sometimes optimized not to store additional variables.
294 flags_match(ipfw_insn *cmd, u_int8_t bits)
299 if ( ((cmd->arg1 & 0xff) & bits) != 0)
300 return 0; /* some bits we want set were clear */
301 want_clear = (cmd->arg1 >> 8) & 0xff;
302 if ( (want_clear & bits) != want_clear)
303 return 0; /* some bits we want clear were set */
308 ipopts_match(struct ip *ip, ipfw_insn *cmd)
310 int optlen, bits = 0;
311 u_char *cp = (u_char *)(ip + 1);
312 int x = (ip->ip_hl << 2) - sizeof (struct ip);
314 for (; x > 0; x -= optlen, cp += optlen) {
315 int opt = cp[IPOPT_OPTVAL];
317 if (opt == IPOPT_EOL)
319 if (opt == IPOPT_NOP)
322 optlen = cp[IPOPT_OLEN];
323 if (optlen <= 0 || optlen > x)
324 return 0; /* invalid or truncated */
332 bits |= IP_FW_IPOPT_LSRR;
336 bits |= IP_FW_IPOPT_SSRR;
340 bits |= IP_FW_IPOPT_RR;
344 bits |= IP_FW_IPOPT_TS;
348 return (flags_match(cmd, bits));
352 tcpopts_match(struct ip *ip, ipfw_insn *cmd)
354 int optlen, bits = 0;
355 struct tcphdr *tcp = L3HDR(struct tcphdr,ip);
356 u_char *cp = (u_char *)(tcp + 1);
357 int x = (tcp->th_off << 2) - sizeof(struct tcphdr);
359 for (; x > 0; x -= optlen, cp += optlen) {
361 if (opt == TCPOPT_EOL)
363 if (opt == TCPOPT_NOP)
377 bits |= IP_FW_TCPOPT_MSS;
381 bits |= IP_FW_TCPOPT_WINDOW;
384 case TCPOPT_SACK_PERMITTED:
386 bits |= IP_FW_TCPOPT_SACK;
389 case TCPOPT_TIMESTAMP:
390 bits |= IP_FW_TCPOPT_TS;
396 bits |= IP_FW_TCPOPT_CC;
400 return (flags_match(cmd, bits));
404 iface_match(struct ifnet *ifp, ipfw_insn_if *cmd)
406 if (ifp == NULL) /* no iface with this packet, match fails */
408 /* Check by name or by IP address */
409 if (cmd->name[0] != '\0') { /* match by name */
410 /* Check unit number (-1 is wildcard) */
411 if (cmd->p.unit != -1 && cmd->p.unit != ifp->if_unit)
414 if (!strncmp(ifp->if_name, cmd->name, IFNAMSIZ))
420 TAILQ_FOREACH(ia, &ifp->if_addrhead, ifa_link) {
421 if (ia->ifa_addr == NULL)
423 if (ia->ifa_addr->sa_family != AF_INET)
425 if (cmd->p.ip.s_addr == ((struct sockaddr_in *)
426 (ia->ifa_addr))->sin_addr.s_addr)
427 return(1); /* match */
430 return(0); /* no match, fail ... */
434 * The 'verrevpath' option checks that the interface that an IP packet
435 * arrives on is the same interface that traffic destined for the
436 * packet's source address would be routed out of. This is a measure
437 * to block forged packets. This is also commonly known as "anti-spoofing"
438 * or Unicast Reverse Path Forwarding (Unicast RFP) in Cisco-ese. The
439 * name of the knob is purposely reminisent of the Cisco IOS command,
441 * ip verify unicast reverse-path
443 * which implements the same functionality. But note that syntax is
444 * misleading. The check may be performed on all IP packets whether unicast,
445 * multicast, or broadcast.
448 verify_rev_path(struct in_addr src, struct ifnet *ifp)
450 static struct route ro;
451 struct sockaddr_in *dst;
453 dst = (struct sockaddr_in *)&(ro.ro_dst);
455 /* Check if we've cached the route from the previous call. */
456 if (src.s_addr != dst->sin_addr.s_addr) {
459 bzero(dst, sizeof(*dst));
460 dst->sin_family = AF_INET;
461 dst->sin_len = sizeof(*dst);
464 rtalloc_ign(&ro, RTF_CLONING|RTF_PRCLONING);
467 if ((ro.ro_rt == NULL) || (ifp == NULL) ||
468 (ro.ro_rt->rt_ifp->if_index != ifp->if_index))
475 static u_int64_t norule_counter; /* counter for ipfw_log(NULL...) */
477 #define SNPARGS(buf, len) buf + len, sizeof(buf) > len ? sizeof(buf) - len : 0
478 #define SNP(buf) buf, sizeof(buf)
481 * We enter here when we have a rule with O_LOG.
482 * XXX this function alone takes about 2Kbytes of code!
485 ipfw_log(struct ip_fw *f, u_int hlen, struct ether_header *eh,
486 struct mbuf *m, struct ifnet *oif)
489 int limit_reached = 0;
490 char action2[40], proto[48], fragment[28];
495 if (f == NULL) { /* bogus pkt */
496 if (verbose_limit != 0 && norule_counter >= verbose_limit)
499 if (norule_counter == verbose_limit)
500 limit_reached = verbose_limit;
502 } else { /* O_LOG is the first action, find the real one */
503 ipfw_insn *cmd = ACTION_PTR(f);
504 ipfw_insn_log *l = (ipfw_insn_log *)cmd;
506 if (l->max_log != 0 && l->log_left == 0)
509 if (l->log_left == 0)
510 limit_reached = l->max_log;
511 cmd += F_LEN(cmd); /* point to first action */
512 if (cmd->opcode == O_PROB)
516 switch (cmd->opcode) {
522 if (cmd->arg1==ICMP_REJECT_RST)
524 else if (cmd->arg1==ICMP_UNREACH_HOST)
527 snprintf(SNPARGS(action2, 0), "Unreach %d",
538 snprintf(SNPARGS(action2, 0), "Divert %d",
542 snprintf(SNPARGS(action2, 0), "Tee %d",
546 snprintf(SNPARGS(action2, 0), "SkipTo %d",
550 snprintf(SNPARGS(action2, 0), "Pipe %d",
554 snprintf(SNPARGS(action2, 0), "Queue %d",
558 ipfw_insn_sa *sa = (ipfw_insn_sa *)cmd;
561 len = snprintf(SNPARGS(action2, 0), "Forward to %s",
562 inet_ntoa(sa->sa.sin_addr));
564 snprintf(SNPARGS(action2, len), ":%d",
574 if (hlen == 0) { /* non-ip */
575 snprintf(SNPARGS(proto, 0), "MAC");
577 struct ip *ip = mtod(m, struct ip *);
578 /* these three are all aliases to the same thing */
579 struct icmp *const icmp = L3HDR(struct icmp, ip);
580 struct tcphdr *const tcp = (struct tcphdr *)icmp;
581 struct udphdr *const udp = (struct udphdr *)icmp;
583 int ip_off, offset, ip_len;
587 if (eh != NULL) { /* layer 2 packets are as on the wire */
588 ip_off = ntohs(ip->ip_off);
589 ip_len = ntohs(ip->ip_len);
594 offset = ip_off & IP_OFFMASK;
597 len = snprintf(SNPARGS(proto, 0), "TCP %s",
598 inet_ntoa(ip->ip_src));
600 snprintf(SNPARGS(proto, len), ":%d %s:%d",
601 ntohs(tcp->th_sport),
602 inet_ntoa(ip->ip_dst),
603 ntohs(tcp->th_dport));
605 snprintf(SNPARGS(proto, len), " %s",
606 inet_ntoa(ip->ip_dst));
610 len = snprintf(SNPARGS(proto, 0), "UDP %s",
611 inet_ntoa(ip->ip_src));
613 snprintf(SNPARGS(proto, len), ":%d %s:%d",
614 ntohs(udp->uh_sport),
615 inet_ntoa(ip->ip_dst),
616 ntohs(udp->uh_dport));
618 snprintf(SNPARGS(proto, len), " %s",
619 inet_ntoa(ip->ip_dst));
624 len = snprintf(SNPARGS(proto, 0),
626 icmp->icmp_type, icmp->icmp_code);
628 len = snprintf(SNPARGS(proto, 0), "ICMP ");
629 len += snprintf(SNPARGS(proto, len), "%s",
630 inet_ntoa(ip->ip_src));
631 snprintf(SNPARGS(proto, len), " %s",
632 inet_ntoa(ip->ip_dst));
636 len = snprintf(SNPARGS(proto, 0), "P:%d %s", ip->ip_p,
637 inet_ntoa(ip->ip_src));
638 snprintf(SNPARGS(proto, len), " %s",
639 inet_ntoa(ip->ip_dst));
643 if (ip_off & (IP_MF | IP_OFFMASK))
644 snprintf(SNPARGS(fragment, 0), " (frag %d:%d@%d%s)",
645 ntohs(ip->ip_id), ip_len - (ip->ip_hl << 2),
647 (ip_off & IP_MF) ? "+" : "");
649 if (oif || m->m_pkthdr.rcvif)
650 log(LOG_SECURITY | LOG_INFO,
651 "ipfw: %d %s %s %s via %s%d%s\n",
653 action, proto, oif ? "out" : "in",
654 oif ? oif->if_name : m->m_pkthdr.rcvif->if_name,
655 oif ? oif->if_unit : m->m_pkthdr.rcvif->if_unit,
658 log(LOG_SECURITY | LOG_INFO,
659 "ipfw: %d %s %s [no if info]%s\n",
661 action, proto, fragment);
663 log(LOG_SECURITY | LOG_NOTICE,
664 "ipfw: limit %d reached on entry %d\n",
665 limit_reached, f ? f->rulenum : -1);
669 * IMPORTANT: the hash function for dynamic rules must be commutative
670 * in source and destination (ip,port), because rules are bidirectional
671 * and we want to find both in the same bucket.
674 hash_packet(struct ipfw_flow_id *id)
678 i = (id->dst_ip) ^ (id->src_ip) ^ (id->dst_port) ^ (id->src_port);
679 i &= (curr_dyn_buckets - 1);
684 * unlink a dynamic rule from a chain. prev is a pointer to
685 * the previous one, q is a pointer to the rule to delete,
686 * head is a pointer to the head of the queue.
687 * Modifies q and potentially also head.
689 #define UNLINK_DYN_RULE(prev, head, q) { \
690 ipfw_dyn_rule *old_q = q; \
692 /* remove a refcount to the parent */ \
693 if (q->dyn_type == O_LIMIT) \
694 q->parent->count--; \
695 DEB(printf("ipfw: unlink entry 0x%08x %d -> 0x%08x %d, %d left\n",\
696 (q->id.src_ip), (q->id.src_port), \
697 (q->id.dst_ip), (q->id.dst_port), dyn_count-1 ); ) \
699 prev->next = q = q->next; \
701 head = q = q->next; \
703 free(old_q, M_IPFW); }
705 #define TIME_LEQ(a,b) ((int)((a)-(b)) <= 0)
708 * Remove dynamic rules pointing to "rule", or all of them if rule == NULL.
710 * If keep_me == NULL, rules are deleted even if not expired,
711 * otherwise only expired rules are removed.
713 * The value of the second parameter is also used to point to identify
714 * a rule we absolutely do not want to remove (e.g. because we are
715 * holding a reference to it -- this is the case with O_LIMIT_PARENT
716 * rules). The pointer is only used for comparison, so any non-null
720 remove_dyn_rule(struct ip_fw *rule, ipfw_dyn_rule *keep_me)
722 static u_int32_t last_remove = 0;
724 #define FORCE (keep_me == NULL)
726 ipfw_dyn_rule *prev, *q;
727 int i, pass = 0, max_pass = 0;
729 IPFW_DYN_LOCK_ASSERT();
731 if (ipfw_dyn_v == NULL || dyn_count == 0)
733 /* do not expire more than once per second, it is useless */
734 if (!FORCE && last_remove == time_second)
736 last_remove = time_second;
739 * because O_LIMIT refer to parent rules, during the first pass only
740 * remove child and mark any pending LIMIT_PARENT, and remove
741 * them in a second pass.
744 for (i = 0 ; i < curr_dyn_buckets ; i++) {
745 for (prev=NULL, q = ipfw_dyn_v[i] ; q ; ) {
747 * Logic can become complex here, so we split tests.
751 if (rule != NULL && rule != q->rule)
752 goto next; /* not the one we are looking for */
753 if (q->dyn_type == O_LIMIT_PARENT) {
755 * handle parent in the second pass,
756 * record we need one.
761 if (FORCE && q->count != 0 ) {
762 /* XXX should not happen! */
763 printf("ipfw: OUCH! cannot remove rule,"
764 " count %d\n", q->count);
768 !TIME_LEQ( q->expire, time_second ))
771 UNLINK_DYN_RULE(prev, ipfw_dyn_v[i], q);
778 if (pass++ < max_pass)
784 * lookup a dynamic rule.
786 static ipfw_dyn_rule *
787 lookup_dyn_rule_locked(struct ipfw_flow_id *pkt, int *match_direction,
791 * stateful ipfw extensions.
792 * Lookup into dynamic session queue
794 #define MATCH_REVERSE 0
795 #define MATCH_FORWARD 1
797 #define MATCH_UNKNOWN 3
798 int i, dir = MATCH_NONE;
799 ipfw_dyn_rule *prev, *q=NULL;
801 IPFW_DYN_LOCK_ASSERT();
803 if (ipfw_dyn_v == NULL)
804 goto done; /* not found */
805 i = hash_packet( pkt );
806 for (prev=NULL, q = ipfw_dyn_v[i] ; q != NULL ; ) {
807 if (q->dyn_type == O_LIMIT_PARENT)
809 if (TIME_LEQ( q->expire, time_second)) { /* expire entry */
810 UNLINK_DYN_RULE(prev, ipfw_dyn_v[i], q);
813 if ( pkt->proto == q->id.proto) {
814 if (pkt->src_ip == q->id.src_ip &&
815 pkt->dst_ip == q->id.dst_ip &&
816 pkt->src_port == q->id.src_port &&
817 pkt->dst_port == q->id.dst_port ) {
821 if (pkt->src_ip == q->id.dst_ip &&
822 pkt->dst_ip == q->id.src_ip &&
823 pkt->src_port == q->id.dst_port &&
824 pkt->dst_port == q->id.src_port ) {
834 goto done; /* q = NULL, not found */
836 if ( prev != NULL) { /* found and not in front */
837 prev->next = q->next;
838 q->next = ipfw_dyn_v[i];
841 if (pkt->proto == IPPROTO_TCP) { /* update state according to flags */
842 u_char flags = pkt->flags & (TH_FIN|TH_SYN|TH_RST);
844 #define BOTH_SYN (TH_SYN | (TH_SYN << 8))
845 #define BOTH_FIN (TH_FIN | (TH_FIN << 8))
846 q->state |= (dir == MATCH_FORWARD ) ? flags : (flags << 8);
848 case TH_SYN: /* opening */
849 q->expire = time_second + dyn_syn_lifetime;
852 case BOTH_SYN: /* move to established */
853 case BOTH_SYN | TH_FIN : /* one side tries to close */
854 case BOTH_SYN | (TH_FIN << 8) :
856 #define _SEQ_GE(a,b) ((int)(a) - (int)(b) >= 0)
857 u_int32_t ack = ntohl(tcp->th_ack);
858 if (dir == MATCH_FORWARD) {
859 if (q->ack_fwd == 0 || _SEQ_GE(ack, q->ack_fwd))
861 else { /* ignore out-of-sequence */
865 if (q->ack_rev == 0 || _SEQ_GE(ack, q->ack_rev))
867 else { /* ignore out-of-sequence */
872 q->expire = time_second + dyn_ack_lifetime;
875 case BOTH_SYN | BOTH_FIN: /* both sides closed */
876 if (dyn_fin_lifetime >= dyn_keepalive_period)
877 dyn_fin_lifetime = dyn_keepalive_period - 1;
878 q->expire = time_second + dyn_fin_lifetime;
884 * reset or some invalid combination, but can also
885 * occur if we use keep-state the wrong way.
887 if ( (q->state & ((TH_RST << 8)|TH_RST)) == 0)
888 printf("invalid state: 0x%x\n", q->state);
890 if (dyn_rst_lifetime >= dyn_keepalive_period)
891 dyn_rst_lifetime = dyn_keepalive_period - 1;
892 q->expire = time_second + dyn_rst_lifetime;
895 } else if (pkt->proto == IPPROTO_UDP) {
896 q->expire = time_second + dyn_udp_lifetime;
898 /* other protocols */
899 q->expire = time_second + dyn_short_lifetime;
903 *match_direction = dir;
907 static ipfw_dyn_rule *
908 lookup_dyn_rule(struct ipfw_flow_id *pkt, int *match_direction,
914 q = lookup_dyn_rule_locked(pkt, match_direction, tcp);
917 /* NB: return table locked when q is not NULL */
922 realloc_dynamic_table(void)
924 IPFW_DYN_LOCK_ASSERT();
927 * Try reallocation, make sure we have a power of 2 and do
928 * not allow more than 64k entries. In case of overflow,
932 if (dyn_buckets > 65536)
934 if ((dyn_buckets & (dyn_buckets-1)) != 0) { /* not a power of 2 */
935 dyn_buckets = curr_dyn_buckets; /* reset */
938 curr_dyn_buckets = dyn_buckets;
939 if (ipfw_dyn_v != NULL)
940 free(ipfw_dyn_v, M_IPFW);
942 ipfw_dyn_v = malloc(curr_dyn_buckets * sizeof(ipfw_dyn_rule *),
943 M_IPFW, M_NOWAIT | M_ZERO);
944 if (ipfw_dyn_v != NULL || curr_dyn_buckets <= 2)
946 curr_dyn_buckets /= 2;
951 * Install state of type 'type' for a dynamic session.
952 * The hash table contains two type of rules:
953 * - regular rules (O_KEEP_STATE)
954 * - rules for sessions with limited number of sess per user
955 * (O_LIMIT). When they are created, the parent is
956 * increased by 1, and decreased on delete. In this case,
957 * the third parameter is the parent rule and not the chain.
958 * - "parent" rules for the above (O_LIMIT_PARENT).
960 static ipfw_dyn_rule *
961 add_dyn_rule(struct ipfw_flow_id *id, u_int8_t dyn_type, struct ip_fw *rule)
966 IPFW_DYN_LOCK_ASSERT();
968 if (ipfw_dyn_v == NULL ||
969 (dyn_count == 0 && dyn_buckets != curr_dyn_buckets)) {
970 realloc_dynamic_table();
971 if (ipfw_dyn_v == NULL)
972 return NULL; /* failed ! */
976 r = malloc(sizeof *r, M_IPFW, M_NOWAIT | M_ZERO);
978 printf ("ipfw: sorry cannot allocate state\n");
982 /* increase refcount on parent, and set pointer */
983 if (dyn_type == O_LIMIT) {
984 ipfw_dyn_rule *parent = (ipfw_dyn_rule *)rule;
985 if ( parent->dyn_type != O_LIMIT_PARENT)
986 panic("invalid parent");
993 r->expire = time_second + dyn_syn_lifetime;
995 r->dyn_type = dyn_type;
996 r->pcnt = r->bcnt = 0;
1000 r->next = ipfw_dyn_v[i];
1003 DEB(printf("ipfw: add dyn entry ty %d 0x%08x %d -> 0x%08x %d, total %d\n",
1005 (r->id.src_ip), (r->id.src_port),
1006 (r->id.dst_ip), (r->id.dst_port),
1012 * lookup dynamic parent rule using pkt and rule as search keys.
1013 * If the lookup fails, then install one.
1015 static ipfw_dyn_rule *
1016 lookup_dyn_parent(struct ipfw_flow_id *pkt, struct ip_fw *rule)
1021 IPFW_DYN_LOCK_ASSERT();
1024 i = hash_packet( pkt );
1025 for (q = ipfw_dyn_v[i] ; q != NULL ; q=q->next)
1026 if (q->dyn_type == O_LIMIT_PARENT &&
1028 pkt->proto == q->id.proto &&
1029 pkt->src_ip == q->id.src_ip &&
1030 pkt->dst_ip == q->id.dst_ip &&
1031 pkt->src_port == q->id.src_port &&
1032 pkt->dst_port == q->id.dst_port) {
1033 q->expire = time_second + dyn_short_lifetime;
1034 DEB(printf("ipfw: lookup_dyn_parent found 0x%p\n",q);)
1038 return add_dyn_rule(pkt, O_LIMIT_PARENT, rule);
1042 * Install dynamic state for rule type cmd->o.opcode
1044 * Returns 1 (failure) if state is not installed because of errors or because
1045 * session limitations are enforced.
1048 install_state(struct ip_fw *rule, ipfw_insn_limit *cmd,
1049 struct ip_fw_args *args)
1051 static int last_log;
1055 DEB(printf("ipfw: install state type %d 0x%08x %u -> 0x%08x %u\n",
1057 (args->f_id.src_ip), (args->f_id.src_port),
1058 (args->f_id.dst_ip), (args->f_id.dst_port) );)
1062 q = lookup_dyn_rule_locked(&args->f_id, NULL, NULL);
1064 if (q != NULL) { /* should never occur */
1065 if (last_log != time_second) {
1066 last_log = time_second;
1067 printf("ipfw: install_state: entry already present, done\n");
1073 if (dyn_count >= dyn_max)
1075 * Run out of slots, try to remove any expired rule.
1077 remove_dyn_rule(NULL, (ipfw_dyn_rule *)1);
1079 if (dyn_count >= dyn_max) {
1080 if (last_log != time_second) {
1081 last_log = time_second;
1082 printf("ipfw: install_state: Too many dynamic rules\n");
1085 return 1; /* cannot install, notify caller */
1088 switch (cmd->o.opcode) {
1089 case O_KEEP_STATE: /* bidir rule */
1090 add_dyn_rule(&args->f_id, O_KEEP_STATE, rule);
1093 case O_LIMIT: /* limit number of sessions */
1095 u_int16_t limit_mask = cmd->limit_mask;
1096 struct ipfw_flow_id id;
1097 ipfw_dyn_rule *parent;
1099 DEB(printf("ipfw: installing dyn-limit rule %d\n",
1102 id.dst_ip = id.src_ip = 0;
1103 id.dst_port = id.src_port = 0;
1104 id.proto = args->f_id.proto;
1106 if (limit_mask & DYN_SRC_ADDR)
1107 id.src_ip = args->f_id.src_ip;
1108 if (limit_mask & DYN_DST_ADDR)
1109 id.dst_ip = args->f_id.dst_ip;
1110 if (limit_mask & DYN_SRC_PORT)
1111 id.src_port = args->f_id.src_port;
1112 if (limit_mask & DYN_DST_PORT)
1113 id.dst_port = args->f_id.dst_port;
1114 parent = lookup_dyn_parent(&id, rule);
1115 if (parent == NULL) {
1116 printf("ipfw: add parent failed\n");
1119 if (parent->count >= cmd->conn_limit) {
1121 * See if we can remove some expired rule.
1123 remove_dyn_rule(rule, parent);
1124 if (parent->count >= cmd->conn_limit) {
1125 if (fw_verbose && last_log != time_second) {
1126 last_log = time_second;
1127 log(LOG_SECURITY | LOG_DEBUG,
1128 "drop session, too many entries\n");
1134 add_dyn_rule(&args->f_id, O_LIMIT, (struct ip_fw *)parent);
1138 printf("ipfw: unknown dynamic rule type %u\n", cmd->o.opcode);
1142 lookup_dyn_rule_locked(&args->f_id, NULL, NULL); /* XXX just set lifetime */
1148 * Transmit a TCP packet, containing either a RST or a keepalive.
1149 * When flags & TH_RST, we are sending a RST packet, because of a
1150 * "reset" action matched the packet.
1151 * Otherwise we are sending a keepalive, and flags & TH_
1154 send_pkt(struct ipfw_flow_id *id, u_int32_t seq, u_int32_t ack, int flags)
1159 struct route sro; /* fake route */
1161 MGETHDR(m, M_DONTWAIT, MT_HEADER);
1164 m->m_pkthdr.rcvif = (struct ifnet *)0;
1165 m->m_pkthdr.len = m->m_len = sizeof(struct ip) + sizeof(struct tcphdr);
1166 m->m_data += max_linkhdr;
1168 ip = mtod(m, struct ip *);
1169 bzero(ip, m->m_len);
1170 tcp = (struct tcphdr *)(ip + 1); /* no IP options */
1171 ip->ip_p = IPPROTO_TCP;
1174 * Assume we are sending a RST (or a keepalive in the reverse
1175 * direction), swap src and destination addresses and ports.
1177 ip->ip_src.s_addr = htonl(id->dst_ip);
1178 ip->ip_dst.s_addr = htonl(id->src_ip);
1179 tcp->th_sport = htons(id->dst_port);
1180 tcp->th_dport = htons(id->src_port);
1181 if (flags & TH_RST) { /* we are sending a RST */
1182 if (flags & TH_ACK) {
1183 tcp->th_seq = htonl(ack);
1184 tcp->th_ack = htonl(0);
1185 tcp->th_flags = TH_RST;
1189 tcp->th_seq = htonl(0);
1190 tcp->th_ack = htonl(seq);
1191 tcp->th_flags = TH_RST | TH_ACK;
1195 * We are sending a keepalive. flags & TH_SYN determines
1196 * the direction, forward if set, reverse if clear.
1197 * NOTE: seq and ack are always assumed to be correct
1198 * as set by the caller. This may be confusing...
1200 if (flags & TH_SYN) {
1202 * we have to rewrite the correct addresses!
1204 ip->ip_dst.s_addr = htonl(id->dst_ip);
1205 ip->ip_src.s_addr = htonl(id->src_ip);
1206 tcp->th_dport = htons(id->dst_port);
1207 tcp->th_sport = htons(id->src_port);
1209 tcp->th_seq = htonl(seq);
1210 tcp->th_ack = htonl(ack);
1211 tcp->th_flags = TH_ACK;
1214 * set ip_len to the payload size so we can compute
1215 * the tcp checksum on the pseudoheader
1216 * XXX check this, could save a couple of words ?
1218 ip->ip_len = htons(sizeof(struct tcphdr));
1219 tcp->th_sum = in_cksum(m, m->m_pkthdr.len);
1221 * now fill fields left out earlier
1223 ip->ip_ttl = ip_defttl;
1224 ip->ip_len = m->m_pkthdr.len;
1225 bzero (&sro, sizeof (sro));
1226 ip_rtaddr(ip->ip_dst, &sro);
1227 m->m_flags |= M_SKIP_FIREWALL;
1228 ip_output(m, NULL, &sro, 0, NULL, NULL);
1234 * sends a reject message, consuming the mbuf passed as an argument.
1237 send_reject(struct ip_fw_args *args, int code, int offset, int ip_len)
1240 if (code != ICMP_REJECT_RST) { /* Send an ICMP unreach */
1241 /* We need the IP header in host order for icmp_error(). */
1242 if (args->eh != NULL) {
1243 struct ip *ip = mtod(args->m, struct ip *);
1244 ip->ip_len = ntohs(ip->ip_len);
1245 ip->ip_off = ntohs(ip->ip_off);
1247 icmp_error(args->m, ICMP_UNREACH, code, 0L, 0);
1248 } else if (offset == 0 && args->f_id.proto == IPPROTO_TCP) {
1249 struct tcphdr *const tcp =
1250 L3HDR(struct tcphdr, mtod(args->m, struct ip *));
1251 if ( (tcp->th_flags & TH_RST) == 0)
1252 send_pkt(&(args->f_id), ntohl(tcp->th_seq),
1254 tcp->th_flags | TH_RST);
1263 * Given an ip_fw *, lookup_next_rule will return a pointer
1264 * to the next rule, which can be either the jump
1265 * target (for skipto instructions) or the next one in the list (in
1266 * all other cases including a missing jump target).
1267 * The result is also written in the "next_rule" field of the rule.
1268 * Backward jumps are not allowed, so start looking from the next
1271 * This never returns NULL -- in case we do not have an exact match,
1272 * the next rule is returned. When the ruleset is changed,
1273 * pointers are flushed so we are always correct.
1276 static struct ip_fw *
1277 lookup_next_rule(struct ip_fw *me)
1279 struct ip_fw *rule = NULL;
1282 /* look for action, in case it is a skipto */
1283 cmd = ACTION_PTR(me);
1284 if (cmd->opcode == O_LOG)
1286 if ( cmd->opcode == O_SKIPTO )
1287 for (rule = me->next; rule ; rule = rule->next)
1288 if (rule->rulenum >= cmd->arg1)
1290 if (rule == NULL) /* failure or not a skipto */
1292 me->next_rule = rule;
1297 * The main check routine for the firewall.
1299 * All arguments are in args so we can modify them and return them
1300 * back to the caller.
1304 * args->m (in/out) The packet; we set to NULL when/if we nuke it.
1305 * Starts with the IP header.
1306 * args->eh (in) Mac header if present, or NULL for layer3 packet.
1307 * args->oif Outgoing interface, or NULL if packet is incoming.
1308 * The incoming interface is in the mbuf. (in)
1309 * args->divert_rule (in/out)
1310 * Skip up to the first rule past this rule number;
1311 * upon return, non-zero port number for divert or tee.
1313 * args->rule Pointer to the last matching rule (in/out)
1314 * args->next_hop Socket we are forwarding to (out).
1315 * args->f_id Addresses grabbed from the packet (out)
1319 * IP_FW_PORT_DENY_FLAG the packet must be dropped.
1320 * 0 The packet is to be accepted and routed normally OR
1321 * the packet was denied/rejected and has been dropped;
1322 * in the latter case, *m is equal to NULL upon return.
1323 * port Divert the packet to port, with these caveats:
1325 * - If IP_FW_PORT_TEE_FLAG is set, tee the packet instead
1326 * of diverting it (ie, 'ipfw tee').
1328 * - If IP_FW_PORT_DYNT_FLAG is set, interpret the lower
1329 * 16 bits as a dummynet pipe number instead of diverting
1333 ipfw_chk(struct ip_fw_args *args)
1336 * Local variables hold state during the processing of a packet.
1338 * IMPORTANT NOTE: to speed up the processing of rules, there
1339 * are some assumption on the values of the variables, which
1340 * are documented here. Should you change them, please check
1341 * the implementation of the various instructions to make sure
1342 * that they still work.
1344 * args->eh The MAC header. It is non-null for a layer2
1345 * packet, it is NULL for a layer-3 packet.
1347 * m | args->m Pointer to the mbuf, as received from the caller.
1348 * It may change if ipfw_chk() does an m_pullup, or if it
1349 * consumes the packet because it calls send_reject().
1350 * XXX This has to change, so that ipfw_chk() never modifies
1351 * or consumes the buffer.
1352 * ip is simply an alias of the value of m, and it is kept
1353 * in sync with it (the packet is supposed to start with
1356 struct mbuf *m = args->m;
1357 struct ip *ip = mtod(m, struct ip *);
1360 * oif | args->oif If NULL, ipfw_chk has been called on the
1361 * inbound path (ether_input, bdg_forward, ip_input).
1362 * If non-NULL, ipfw_chk has been called on the outbound path
1363 * (ether_output, ip_output).
1365 struct ifnet *oif = args->oif;
1367 struct ip_fw *f = NULL; /* matching rule */
1371 * hlen The length of the IPv4 header.
1372 * hlen >0 means we have an IPv4 packet.
1374 u_int hlen = 0; /* hlen >0 means we have an IP pkt */
1377 * offset The offset of a fragment. offset != 0 means that
1378 * we have a fragment at this offset of an IPv4 packet.
1379 * offset == 0 means that (if this is an IPv4 packet)
1380 * this is the first or only fragment.
1385 * Local copies of addresses. They are only valid if we have
1388 * proto The protocol. Set to 0 for non-ip packets,
1389 * or to the protocol read from the packet otherwise.
1390 * proto != 0 means that we have an IPv4 packet.
1392 * src_port, dst_port port numbers, in HOST format. Only
1393 * valid for TCP and UDP packets.
1395 * src_ip, dst_ip ip addresses, in NETWORK format.
1396 * Only valid for IPv4 packets.
1399 u_int16_t src_port = 0, dst_port = 0; /* NOTE: host format */
1400 struct in_addr src_ip, dst_ip; /* NOTE: network format */
1403 int dyn_dir = MATCH_UNKNOWN;
1404 ipfw_dyn_rule *q = NULL;
1405 struct ip_fw_chain *chain = &layer3_chain;
1407 if (m->m_flags & M_SKIP_FIREWALL)
1408 return 0; /* accept */
1410 * dyn_dir = MATCH_UNKNOWN when rules unchecked,
1411 * MATCH_NONE when checked and not matched (q = NULL),
1412 * MATCH_FORWARD or MATCH_REVERSE otherwise (q != NULL)
1415 pktlen = m->m_pkthdr.len;
1416 if (args->eh == NULL || /* layer 3 packet */
1417 ( m->m_pkthdr.len >= sizeof(struct ip) &&
1418 ntohs(args->eh->ether_type) == ETHERTYPE_IP))
1419 hlen = ip->ip_hl << 2;
1422 * Collect parameters into local variables for faster matching.
1424 if (hlen == 0) { /* do not grab addresses for non-ip pkts */
1425 proto = args->f_id.proto = 0; /* mark f_id invalid */
1426 goto after_ip_checks;
1429 proto = args->f_id.proto = ip->ip_p;
1430 src_ip = ip->ip_src;
1431 dst_ip = ip->ip_dst;
1432 if (args->eh != NULL) { /* layer 2 packets are as on the wire */
1433 offset = ntohs(ip->ip_off) & IP_OFFMASK;
1434 ip_len = ntohs(ip->ip_len);
1436 offset = ip->ip_off & IP_OFFMASK;
1437 ip_len = ip->ip_len;
1439 pktlen = ip_len < pktlen ? ip_len : pktlen;
1441 #define PULLUP_TO(len) \
1443 if ((m)->m_len < (len)) { \
1444 args->m = m = m_pullup(m, (len)); \
1446 goto pullup_failed; \
1447 ip = mtod(m, struct ip *); \
1457 PULLUP_TO(hlen + sizeof(struct tcphdr));
1458 tcp = L3HDR(struct tcphdr, ip);
1459 dst_port = tcp->th_dport;
1460 src_port = tcp->th_sport;
1461 args->f_id.flags = tcp->th_flags;
1469 PULLUP_TO(hlen + sizeof(struct udphdr));
1470 udp = L3HDR(struct udphdr, ip);
1471 dst_port = udp->uh_dport;
1472 src_port = udp->uh_sport;
1477 PULLUP_TO(hlen + 4); /* type, code and checksum. */
1478 args->f_id.flags = L3HDR(struct icmp, ip)->icmp_type;
1487 args->f_id.src_ip = ntohl(src_ip.s_addr);
1488 args->f_id.dst_ip = ntohl(dst_ip.s_addr);
1489 args->f_id.src_port = src_port = ntohs(src_port);
1490 args->f_id.dst_port = dst_port = ntohs(dst_port);
1493 IPFW_LOCK(chain); /* XXX expensive? can we run lock free? */
1496 * Packet has already been tagged. Look for the next rule
1497 * to restart processing.
1499 * If fw_one_pass != 0 then just accept it.
1500 * XXX should not happen here, but optimized out in
1504 IPFW_UNLOCK(chain); /* XXX optimize */
1508 f = args->rule->next_rule;
1510 f = lookup_next_rule(args->rule);
1513 * Find the starting rule. It can be either the first
1514 * one, or the one after divert_rule if asked so.
1516 int skipto = args->divert_rule;
1519 if (args->eh == NULL && skipto != 0) {
1520 if (skipto >= IPFW_DEFAULT_RULE) {
1522 return(IP_FW_PORT_DENY_FLAG); /* invalid */
1524 while (f && f->rulenum <= skipto)
1526 if (f == NULL) { /* drop packet */
1528 return(IP_FW_PORT_DENY_FLAG);
1532 args->divert_rule = 0; /* reset to avoid confusion later */
1535 * Now scan the rules, and parse microinstructions for each rule.
1537 for (; f; f = f->next) {
1540 int skip_or; /* skip rest of OR block */
1543 if (set_disable & (1 << f->set) )
1547 for (l = f->cmd_len, cmd = f->cmd ; l > 0 ;
1548 l -= cmdlen, cmd += cmdlen) {
1552 * check_body is a jump target used when we find a
1553 * CHECK_STATE, and need to jump to the body of
1558 cmdlen = F_LEN(cmd);
1560 * An OR block (insn_1 || .. || insn_n) has the
1561 * F_OR bit set in all but the last instruction.
1562 * The first match will set "skip_or", and cause
1563 * the following instructions to be skipped until
1564 * past the one with the F_OR bit clear.
1566 if (skip_or) { /* skip this instruction */
1567 if ((cmd->len & F_OR) == 0)
1568 skip_or = 0; /* next one is good */
1571 match = 0; /* set to 1 if we succeed */
1573 switch (cmd->opcode) {
1575 * The first set of opcodes compares the packet's
1576 * fields with some pattern, setting 'match' if a
1577 * match is found. At the end of the loop there is
1578 * logic to deal with F_NOT and F_OR flags associated
1586 printf("ipfw: opcode %d unimplemented\n",
1593 * We only check offset == 0 && proto != 0,
1594 * as this ensures that we have an IPv4
1595 * packet with the ports info.
1600 struct inpcbinfo *pi;
1604 if (proto == IPPROTO_TCP) {
1607 } else if (proto == IPPROTO_UDP) {
1615 in_pcblookup_hash(pi,
1616 dst_ip, htons(dst_port),
1617 src_ip, htons(src_port),
1619 in_pcblookup_hash(pi,
1620 src_ip, htons(src_port),
1621 dst_ip, htons(dst_port),
1624 if (pcb == NULL || pcb->inp_socket == NULL)
1626 #if __FreeBSD_version < 500034
1627 #define socheckuid(a,b) ((a)->so_cred->cr_uid != (b))
1629 if (cmd->opcode == O_UID) {
1631 !socheckuid(pcb->inp_socket,
1632 (uid_t)((ipfw_insn_u32 *)cmd)->d[0]);
1634 match = groupmember(
1635 (uid_t)((ipfw_insn_u32 *)cmd)->d[0],
1636 pcb->inp_socket->so_cred);
1642 match = iface_match(m->m_pkthdr.rcvif,
1643 (ipfw_insn_if *)cmd);
1647 match = iface_match(oif, (ipfw_insn_if *)cmd);
1651 match = iface_match(oif ? oif :
1652 m->m_pkthdr.rcvif, (ipfw_insn_if *)cmd);
1656 if (args->eh != NULL) { /* have MAC header */
1657 u_int32_t *want = (u_int32_t *)
1658 ((ipfw_insn_mac *)cmd)->addr;
1659 u_int32_t *mask = (u_int32_t *)
1660 ((ipfw_insn_mac *)cmd)->mask;
1661 u_int32_t *hdr = (u_int32_t *)args->eh;
1664 ( want[0] == (hdr[0] & mask[0]) &&
1665 want[1] == (hdr[1] & mask[1]) &&
1666 want[2] == (hdr[2] & mask[2]) );
1671 if (args->eh != NULL) {
1673 ntohs(args->eh->ether_type);
1675 ((ipfw_insn_u16 *)cmd)->ports;
1678 for (i = cmdlen - 1; !match && i>0;
1680 match = (t>=p[0] && t<=p[1]);
1685 match = (hlen > 0 && offset != 0);
1688 case O_IN: /* "out" is "not in" */
1689 match = (oif == NULL);
1693 match = (args->eh != NULL);
1698 * We do not allow an arg of 0 so the
1699 * check of "proto" only suffices.
1701 match = (proto == cmd->arg1);
1705 match = (hlen > 0 &&
1706 ((ipfw_insn_ip *)cmd)->addr.s_addr ==
1714 (cmd->opcode == O_IP_DST_MASK) ?
1715 dst_ip.s_addr : src_ip.s_addr;
1716 uint32_t *p = ((ipfw_insn_u32 *)cmd)->d;
1719 for (; !match && i>0; i-= 2, p+= 2)
1720 match = (p[0] == (a & p[1]));
1728 INADDR_TO_IFP(src_ip, tif);
1729 match = (tif != NULL);
1736 u_int32_t *d = (u_int32_t *)(cmd+1);
1738 cmd->opcode == O_IP_DST_SET ?
1744 addr -= d[0]; /* subtract base */
1745 match = (addr < cmd->arg1) &&
1746 ( d[ 1 + (addr>>5)] &
1747 (1<<(addr & 0x1f)) );
1752 match = (hlen > 0 &&
1753 ((ipfw_insn_ip *)cmd)->addr.s_addr ==
1761 INADDR_TO_IFP(dst_ip, tif);
1762 match = (tif != NULL);
1769 * offset == 0 && proto != 0 is enough
1770 * to guarantee that we have an IPv4
1771 * packet with port info.
1773 if ((proto==IPPROTO_UDP || proto==IPPROTO_TCP)
1776 (cmd->opcode == O_IP_SRCPORT) ?
1777 src_port : dst_port ;
1779 ((ipfw_insn_u16 *)cmd)->ports;
1782 for (i = cmdlen - 1; !match && i>0;
1784 match = (x>=p[0] && x<=p[1]);
1789 match = (offset == 0 && proto==IPPROTO_ICMP &&
1790 icmptype_match(ip, (ipfw_insn_u32 *)cmd) );
1794 match = (hlen > 0 && ipopts_match(ip, cmd) );
1798 match = (hlen > 0 && cmd->arg1 == ip->ip_v);
1804 if (hlen > 0) { /* only for IP packets */
1809 if (cmd->opcode == O_IPLEN)
1811 else if (cmd->opcode == O_IPTTL)
1813 else /* must be IPID */
1814 x = ntohs(ip->ip_id);
1816 match = (cmd->arg1 == x);
1819 /* otherwise we have ranges */
1820 p = ((ipfw_insn_u16 *)cmd)->ports;
1822 for (; !match && i>0; i--, p += 2)
1823 match = (x >= p[0] && x <= p[1]);
1827 case O_IPPRECEDENCE:
1828 match = (hlen > 0 &&
1829 (cmd->arg1 == (ip->ip_tos & 0xe0)) );
1833 match = (hlen > 0 &&
1834 flags_match(cmd, ip->ip_tos));
1838 match = (proto == IPPROTO_TCP && offset == 0 &&
1840 L3HDR(struct tcphdr,ip)->th_flags));
1844 match = (proto == IPPROTO_TCP && offset == 0 &&
1845 tcpopts_match(ip, cmd));
1849 match = (proto == IPPROTO_TCP && offset == 0 &&
1850 ((ipfw_insn_u32 *)cmd)->d[0] ==
1851 L3HDR(struct tcphdr,ip)->th_seq);
1855 match = (proto == IPPROTO_TCP && offset == 0 &&
1856 ((ipfw_insn_u32 *)cmd)->d[0] ==
1857 L3HDR(struct tcphdr,ip)->th_ack);
1861 match = (proto == IPPROTO_TCP && offset == 0 &&
1863 L3HDR(struct tcphdr,ip)->th_win);
1867 /* reject packets which have SYN only */
1868 /* XXX should i also check for TH_ACK ? */
1869 match = (proto == IPPROTO_TCP && offset == 0 &&
1870 (L3HDR(struct tcphdr,ip)->th_flags &
1871 (TH_RST | TH_ACK | TH_SYN)) != TH_SYN);
1876 ipfw_log(f, hlen, args->eh, m, oif);
1881 match = (random()<((ipfw_insn_u32 *)cmd)->d[0]);
1885 /* Outgoing packets automatically pass/match */
1886 match = ((oif != NULL) ||
1887 (m->m_pkthdr.rcvif == NULL) ||
1888 verify_rev_path(src_ip, m->m_pkthdr.rcvif));
1893 match = (m_tag_find(m,
1894 PACKET_TAG_IPSEC_IN_DONE, NULL) != NULL);
1897 match = (ipsec_gethist(m, NULL) != NULL);
1899 /* otherwise no match */
1903 * The second set of opcodes represents 'actions',
1904 * i.e. the terminal part of a rule once the packet
1905 * matches all previous patterns.
1906 * Typically there is only one action for each rule,
1907 * and the opcode is stored at the end of the rule
1908 * (but there are exceptions -- see below).
1910 * In general, here we set retval and terminate the
1911 * outer loop (would be a 'break 3' in some language,
1912 * but we need to do a 'goto done').
1915 * O_COUNT and O_SKIPTO actions:
1916 * instead of terminating, we jump to the next rule
1917 * ('goto next_rule', equivalent to a 'break 2'),
1918 * or to the SKIPTO target ('goto again' after
1919 * having set f, cmd and l), respectively.
1921 * O_LIMIT and O_KEEP_STATE: these opcodes are
1922 * not real 'actions', and are stored right
1923 * before the 'action' part of the rule.
1924 * These opcodes try to install an entry in the
1925 * state tables; if successful, we continue with
1926 * the next opcode (match=1; break;), otherwise
1927 * the packet * must be dropped
1928 * ('goto done' after setting retval);
1930 * O_PROBE_STATE and O_CHECK_STATE: these opcodes
1931 * cause a lookup of the state table, and a jump
1932 * to the 'action' part of the parent rule
1933 * ('goto check_body') if an entry is found, or
1934 * (CHECK_STATE only) a jump to the next rule if
1935 * the entry is not found ('goto next_rule').
1936 * The result of the lookup is cached to make
1937 * further instances of these opcodes are
1942 if (install_state(f,
1943 (ipfw_insn_limit *)cmd, args)) {
1944 retval = IP_FW_PORT_DENY_FLAG;
1945 goto done; /* error/limit violation */
1953 * dynamic rules are checked at the first
1954 * keep-state or check-state occurrence,
1955 * with the result being stored in dyn_dir.
1956 * The compiler introduces a PROBE_STATE
1957 * instruction for us when we have a
1958 * KEEP_STATE (because PROBE_STATE needs
1961 if (dyn_dir == MATCH_UNKNOWN &&
1962 (q = lookup_dyn_rule(&args->f_id,
1963 &dyn_dir, proto == IPPROTO_TCP ?
1964 L3HDR(struct tcphdr, ip) : NULL))
1967 * Found dynamic entry, update stats
1968 * and jump to the 'action' part of
1974 cmd = ACTION_PTR(f);
1975 l = f->cmd_len - f->act_ofs;
1980 * Dynamic entry not found. If CHECK_STATE,
1981 * skip to next rule, if PROBE_STATE just
1982 * ignore and continue with next opcode.
1984 if (cmd->opcode == O_CHECK_STATE)
1990 retval = 0; /* accept */
1995 args->rule = f; /* report matching rule */
1996 retval = cmd->arg1 | IP_FW_PORT_DYNT_FLAG;
2001 if (args->eh) /* not on layer 2 */
2003 args->divert_rule = f->rulenum;
2004 retval = (cmd->opcode == O_DIVERT) ?
2006 cmd->arg1 | IP_FW_PORT_TEE_FLAG;
2011 f->pcnt++; /* update stats */
2013 f->timestamp = time_second;
2014 if (cmd->opcode == O_COUNT)
2017 if (f->next_rule == NULL)
2018 lookup_next_rule(f);
2024 * Drop the packet and send a reject notice
2025 * if the packet is not ICMP (or is an ICMP
2026 * query), and it is not multicast/broadcast.
2029 (proto != IPPROTO_ICMP ||
2030 is_icmp_query(ip)) &&
2031 !(m->m_flags & (M_BCAST|M_MCAST)) &&
2032 !IN_MULTICAST(dst_ip.s_addr)) {
2033 send_reject(args, cmd->arg1,
2039 retval = IP_FW_PORT_DENY_FLAG;
2043 if (args->eh) /* not valid on layer2 pkts */
2045 if (!q || dyn_dir == MATCH_FORWARD)
2047 &((ipfw_insn_sa *)cmd)->sa;
2052 panic("-- unknown opcode %d\n", cmd->opcode);
2053 } /* end of switch() on opcodes */
2055 if (cmd->len & F_NOT)
2059 if (cmd->len & F_OR)
2062 if (!(cmd->len & F_OR)) /* not an OR block, */
2063 break; /* try next rule */
2066 } /* end of inner for, scan opcodes */
2068 next_rule:; /* try next rule */
2070 } /* end of outer for, scan rules */
2071 printf("ipfw: ouch!, skip past end of rules, denying packet\n");
2073 return(IP_FW_PORT_DENY_FLAG);
2076 /* Update statistics */
2079 f->timestamp = time_second;
2085 printf("ipfw: pullup failed\n");
2086 return(IP_FW_PORT_DENY_FLAG);
2090 * When a rule is added/deleted, clear the next_rule pointers in all rules.
2091 * These will be reconstructed on the fly as packets are matched.
2094 flush_rule_ptrs(struct ip_fw_chain *chain)
2098 IPFW_LOCK_ASSERT(chain);
2100 for (rule = chain->rules; rule; rule = rule->next)
2101 rule->next_rule = NULL;
2105 * When pipes/queues are deleted, clear the "pipe_ptr" pointer to a given
2106 * pipe/queue, or to all of them (match == NULL).
2109 flush_pipe_ptrs(struct dn_flow_set *match)
2113 IPFW_LOCK(&layer3_chain);
2114 for (rule = layer3_chain.rules; rule; rule = rule->next) {
2115 ipfw_insn_pipe *cmd = (ipfw_insn_pipe *)ACTION_PTR(rule);
2117 if (cmd->o.opcode != O_PIPE && cmd->o.opcode != O_QUEUE)
2120 * XXX Use bcmp/bzero to handle pipe_ptr to overcome
2121 * possible alignment problems on 64-bit architectures.
2122 * This code is seldom used so we do not worry too
2123 * much about efficiency.
2125 if (match == NULL ||
2126 !bcmp(&cmd->pipe_ptr, &match, sizeof(match)) )
2127 bzero(&cmd->pipe_ptr, sizeof(cmd->pipe_ptr));
2129 IPFW_UNLOCK(&layer3_chain);
2133 * Add a new rule to the list. Copy the rule into a malloc'ed area, then
2134 * possibly create a rule number and add the rule to the list.
2135 * Update the rule_number in the input struct so the caller knows it as well.
2138 add_rule(struct ip_fw_chain *chain, struct ip_fw *input_rule)
2140 struct ip_fw *rule, *f, *prev;
2141 int l = RULESIZE(input_rule);
2143 if (chain->rules == NULL && input_rule->rulenum != IPFW_DEFAULT_RULE)
2146 rule = malloc(l, M_IPFW, M_NOWAIT | M_ZERO);
2150 bcopy(input_rule, rule, l);
2153 rule->next_rule = NULL;
2157 rule->timestamp = 0;
2161 if (chain->rules == NULL) { /* default rule */
2162 chain->rules = rule;
2167 * If rulenum is 0, find highest numbered rule before the
2168 * default rule, and add autoinc_step
2170 if (autoinc_step < 1)
2172 else if (autoinc_step > 1000)
2173 autoinc_step = 1000;
2174 if (rule->rulenum == 0) {
2176 * locate the highest numbered rule before default
2178 for (f = chain->rules; f; f = f->next) {
2179 if (f->rulenum == IPFW_DEFAULT_RULE)
2181 rule->rulenum = f->rulenum;
2183 if (rule->rulenum < IPFW_DEFAULT_RULE - autoinc_step)
2184 rule->rulenum += autoinc_step;
2185 input_rule->rulenum = rule->rulenum;
2189 * Now insert the new rule in the right place in the sorted list.
2191 for (prev = NULL, f = chain->rules; f; prev = f, f = f->next) {
2192 if (f->rulenum > rule->rulenum) { /* found the location */
2196 } else { /* head insert */
2197 rule->next = chain->rules;
2198 chain->rules = rule;
2203 flush_rule_ptrs(chain);
2208 DEB(printf("ipfw: installed rule %d, static count now %d\n",
2209 rule->rulenum, static_count);)
2214 * Remove a static rule (including derived * dynamic rules)
2215 * and place it on the ``reap list'' for later reclamation.
2216 * The caller is in charge of clearing rule pointers to avoid
2217 * dangling pointers.
2218 * @return a pointer to the next entry.
2219 * Arguments are not checked, so they better be correct.
2221 static struct ip_fw *
2222 remove_rule(struct ip_fw_chain *chain, struct ip_fw *rule, struct ip_fw *prev)
2225 int l = RULESIZE(rule);
2227 IPFW_LOCK_ASSERT(chain);
2231 remove_dyn_rule(rule, NULL /* force removal */);
2240 rule->next = chain->reap;
2247 * Reclaim storage associated with a list of rules. This is
2248 * typically the list created using remove_rule.
2251 reap_rules(struct ip_fw *head)
2255 while ((rule = head) != NULL) {
2257 if (DUMMYNET_LOADED)
2258 ip_dn_ruledel_ptr(rule);
2264 * Remove all rules from a chain (except rules in set RESVD_SET
2265 * unless kill_default = 1). The caller is responsible for
2266 * reclaiming storage for the rules left in chain->reap.
2269 free_chain(struct ip_fw_chain *chain, int kill_default)
2271 struct ip_fw *prev, *rule;
2273 IPFW_LOCK_ASSERT(chain);
2275 flush_rule_ptrs(chain); /* more efficient to do outside the loop */
2276 for (prev = NULL, rule = chain->rules; rule ; )
2277 if (kill_default || rule->set != RESVD_SET)
2278 rule = remove_rule(chain, rule, prev);
2286 * Remove all rules with given number, and also do set manipulation.
2287 * Assumes chain != NULL && *chain != NULL.
2289 * The argument is an u_int32_t. The low 16 bit are the rule or set number,
2290 * the next 8 bits are the new set, the top 8 bits are the command:
2292 * 0 delete rules with given number
2293 * 1 delete rules with given set number
2294 * 2 move rules with given number to new set
2295 * 3 move rules with given set number to new set
2296 * 4 swap sets with given numbers
2299 del_entry(struct ip_fw_chain *chain, u_int32_t arg)
2301 struct ip_fw *prev = NULL, *rule;
2302 u_int16_t rulenum; /* rule or old_set */
2303 u_int8_t cmd, new_set;
2305 rulenum = arg & 0xffff;
2306 cmd = (arg >> 24) & 0xff;
2307 new_set = (arg >> 16) & 0xff;
2311 if (new_set > RESVD_SET)
2313 if (cmd == 0 || cmd == 2) {
2314 if (rulenum >= IPFW_DEFAULT_RULE)
2317 if (rulenum > RESVD_SET) /* old_set */
2322 rule = chain->rules;
2325 case 0: /* delete rules with given number */
2327 * locate first rule to delete
2329 for (; rule->rulenum < rulenum; prev = rule, rule = rule->next)
2331 if (rule->rulenum != rulenum) {
2337 * flush pointers outside the loop, then delete all matching
2338 * rules. prev remains the same throughout the cycle.
2340 flush_rule_ptrs(chain);
2341 while (rule->rulenum == rulenum)
2342 rule = remove_rule(chain, rule, prev);
2345 case 1: /* delete all rules with given set number */
2346 flush_rule_ptrs(chain);
2347 rule = chain->rules;
2348 while (rule->rulenum < IPFW_DEFAULT_RULE)
2349 if (rule->set == rulenum)
2350 rule = remove_rule(chain, rule, prev);
2357 case 2: /* move rules with given number to new set */
2358 rule = chain->rules;
2359 for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
2360 if (rule->rulenum == rulenum)
2361 rule->set = new_set;
2364 case 3: /* move rules with given set number to new set */
2365 for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
2366 if (rule->set == rulenum)
2367 rule->set = new_set;
2370 case 4: /* swap two sets */
2371 for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
2372 if (rule->set == rulenum)
2373 rule->set = new_set;
2374 else if (rule->set == new_set)
2375 rule->set = rulenum;
2379 * Look for rules to reclaim. We grab the list before
2380 * releasing the lock then reclaim them w/o the lock to
2381 * avoid a LOR with dummynet.
2392 * Clear counters for a specific rule.
2393 * The enclosing "table" is assumed locked.
2396 clear_counters(struct ip_fw *rule, int log_only)
2398 ipfw_insn_log *l = (ipfw_insn_log *)ACTION_PTR(rule);
2400 if (log_only == 0) {
2401 rule->bcnt = rule->pcnt = 0;
2402 rule->timestamp = 0;
2404 if (l->o.opcode == O_LOG)
2405 l->log_left = l->max_log;
2409 * Reset some or all counters on firewall rules.
2410 * @arg frwl is null to clear all entries, or contains a specific
2412 * @arg log_only is 1 if we only want to reset logs, zero otherwise.
2415 zero_entry(struct ip_fw_chain *chain, int rulenum, int log_only)
2423 for (rule = chain->rules; rule; rule = rule->next)
2424 clear_counters(rule, log_only);
2425 msg = log_only ? "ipfw: All logging counts reset.\n" :
2426 "ipfw: Accounting cleared.\n";
2430 * We can have multiple rules with the same number, so we
2431 * need to clear them all.
2433 for (rule = chain->rules; rule; rule = rule->next)
2434 if (rule->rulenum == rulenum) {
2435 while (rule && rule->rulenum == rulenum) {
2436 clear_counters(rule, log_only);
2442 if (!cleared) { /* we did not find any matching rules */
2446 msg = log_only ? "ipfw: Entry %d logging count reset.\n" :
2447 "ipfw: Entry %d cleared.\n";
2452 log(LOG_SECURITY | LOG_NOTICE, msg, rulenum);
2457 * Check validity of the structure before insert.
2458 * Fortunately rules are simple, so this mostly need to check rule sizes.
2461 check_ipfw_struct(struct ip_fw *rule, int size)
2467 if (size < sizeof(*rule)) {
2468 printf("ipfw: rule too short\n");
2471 /* first, check for valid size */
2474 printf("ipfw: size mismatch (have %d want %d)\n", size, l);
2478 * Now go for the individual checks. Very simple ones, basically only
2479 * instruction sizes.
2481 for (l = rule->cmd_len, cmd = rule->cmd ;
2482 l > 0 ; l -= cmdlen, cmd += cmdlen) {
2483 cmdlen = F_LEN(cmd);
2485 printf("ipfw: opcode %d size truncated\n",
2489 DEB(printf("ipfw: opcode %d\n", cmd->opcode);)
2490 switch (cmd->opcode) {
2501 case O_IPPRECEDENCE:
2509 if (cmdlen != F_INSN_SIZE(ipfw_insn))
2521 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32))
2526 if (cmdlen != F_INSN_SIZE(ipfw_insn_limit))
2531 if (cmdlen != F_INSN_SIZE(ipfw_insn_log))
2534 ((ipfw_insn_log *)cmd)->log_left =
2535 ((ipfw_insn_log *)cmd)->max_log;
2541 /* only odd command lengths */
2542 if ( !(cmdlen & 1) || cmdlen > 31)
2548 if (cmd->arg1 == 0 || cmd->arg1 > 256) {
2549 printf("ipfw: invalid set size %d\n",
2553 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
2559 if (cmdlen != F_INSN_SIZE(ipfw_insn_mac))
2567 if (cmdlen < 1 || cmdlen > 31)
2573 case O_IP_DSTPORT: /* XXX artificial limit, 30 port pairs */
2574 if (cmdlen < 2 || cmdlen > 31)
2581 if (cmdlen != F_INSN_SIZE(ipfw_insn_if))
2587 if (cmdlen != F_INSN_SIZE(ipfw_insn_pipe))
2592 if (cmdlen != F_INSN_SIZE(ipfw_insn_sa))
2596 case O_FORWARD_MAC: /* XXX not implemented yet */
2605 if (cmdlen != F_INSN_SIZE(ipfw_insn))
2609 printf("ipfw: opcode %d, multiple actions"
2616 printf("ipfw: opcode %d, action must be"
2623 printf("ipfw: opcode %d, unknown opcode\n",
2628 if (have_action == 0) {
2629 printf("ipfw: missing action\n");
2635 printf("ipfw: opcode %d size %d wrong\n",
2636 cmd->opcode, cmdlen);
2641 * Copy the static and dynamic rules to the supplied buffer
2642 * and return the amount of space actually used.
2645 ipfw_getrules(struct ip_fw_chain *chain, void *buf, size_t space)
2648 char *ep = bp + space;
2652 /* XXX this can take a long time and locking will block packet flow */
2654 for (rule = chain->rules; rule ; rule = rule->next) {
2656 * Verify the entry fits in the buffer in case the
2657 * rules changed between calculating buffer space and
2658 * now. This would be better done using a generation
2659 * number but should suffice for now.
2664 bcopy(&set_disable, &(((struct ip_fw *)bp)->next_rule),
2665 sizeof(set_disable));
2671 ipfw_dyn_rule *p, *last = NULL;
2674 for (i = 0 ; i < curr_dyn_buckets; i++)
2675 for (p = ipfw_dyn_v[i] ; p != NULL; p = p->next) {
2676 if (bp + sizeof *p <= ep) {
2677 ipfw_dyn_rule *dst =
2678 (ipfw_dyn_rule *)bp;
2679 bcopy(p, dst, sizeof *p);
2680 bcopy(&(p->rule->rulenum), &(dst->rule),
2681 sizeof(p->rule->rulenum));
2683 * store a non-null value in "next".
2684 * The userland code will interpret a
2685 * NULL here as a marker
2686 * for the last dynamic rule.
2688 bcopy(&dst, &dst->next, sizeof(dst));
2691 TIME_LEQ(dst->expire, time_second) ?
2692 0 : dst->expire - time_second ;
2693 bp += sizeof(ipfw_dyn_rule);
2697 if (last != NULL) /* mark last dynamic rule */
2698 bzero(&last->next, sizeof(last));
2700 return (bp - (char *)buf);
2705 * {set|get}sockopt parser.
2708 ipfw_ctl(struct sockopt *sopt)
2710 #define RULE_MAXSIZE (256*sizeof(u_int32_t))
2711 int error, rule_num;
2713 struct ip_fw *buf, *rule;
2714 u_int32_t rulenum[2];
2717 * Disallow modifications in really-really secure mode, but still allow
2718 * the logging counters to be reset.
2720 if (sopt->sopt_name == IP_FW_ADD ||
2721 (sopt->sopt_dir == SOPT_SET && sopt->sopt_name != IP_FW_RESETLOG)) {
2722 #if __FreeBSD_version >= 500034
2723 error = securelevel_ge(sopt->sopt_td->td_ucred, 3);
2726 #else /* FreeBSD 4.x */
2727 if (securelevel >= 3)
2734 switch (sopt->sopt_name) {
2737 * pass up a copy of the current rules. Static rules
2738 * come first (the last of which has number IPFW_DEFAULT_RULE),
2739 * followed by a possibly empty list of dynamic rule.
2740 * The last dynamic rule has NULL in the "next" field.
2742 * Note that the calculated size is used to bound the
2743 * amount of data returned to the user. The rule set may
2744 * change between calculating the size and returning the
2745 * data in which case we'll just return what fits.
2747 size = static_len; /* size of static rules */
2748 if (ipfw_dyn_v) /* add size of dyn.rules */
2749 size += (dyn_count * sizeof(ipfw_dyn_rule));
2752 * XXX todo: if the user passes a short length just to know
2753 * how much room is needed, do not bother filling up the
2754 * buffer, just jump to the sooptcopyout.
2756 buf = malloc(size, M_TEMP, M_WAITOK);
2757 error = sooptcopyout(sopt, buf,
2758 ipfw_getrules(&layer3_chain, buf, size));
2764 * Normally we cannot release the lock on each iteration.
2765 * We could do it here only because we start from the head all
2766 * the times so there is no risk of missing some entries.
2767 * On the other hand, the risk is that we end up with
2768 * a very inconsistent ruleset, so better keep the lock
2769 * around the whole cycle.
2771 * XXX this code can be improved by resetting the head of
2772 * the list to point to the default rule, and then freeing
2773 * the old list without the need for a lock.
2776 IPFW_LOCK(&layer3_chain);
2777 layer3_chain.reap = NULL;
2778 free_chain(&layer3_chain, 0 /* keep default rule */);
2779 rule = layer3_chain.reap, layer3_chain.reap = NULL;
2780 IPFW_UNLOCK(&layer3_chain);
2781 if (layer3_chain.reap != NULL)
2786 rule = malloc(RULE_MAXSIZE, M_TEMP, M_WAITOK);
2787 error = sooptcopyin(sopt, rule, RULE_MAXSIZE,
2788 sizeof(struct ip_fw) );
2790 error = check_ipfw_struct(rule, sopt->sopt_valsize);
2792 error = add_rule(&layer3_chain, rule);
2793 size = RULESIZE(rule);
2794 if (!error && sopt->sopt_dir == SOPT_GET)
2795 error = sooptcopyout(sopt, rule, size);
2802 * IP_FW_DEL is used for deleting single rules or sets,
2803 * and (ab)used to atomically manipulate sets. Argument size
2804 * is used to distinguish between the two:
2806 * delete single rule or set of rules,
2807 * or reassign rules (or sets) to a different set.
2808 * 2*sizeof(u_int32_t)
2809 * atomic disable/enable sets.
2810 * first u_int32_t contains sets to be disabled,
2811 * second u_int32_t contains sets to be enabled.
2813 error = sooptcopyin(sopt, rulenum,
2814 2*sizeof(u_int32_t), sizeof(u_int32_t));
2817 size = sopt->sopt_valsize;
2818 if (size == sizeof(u_int32_t)) /* delete or reassign */
2819 error = del_entry(&layer3_chain, rulenum[0]);
2820 else if (size == 2*sizeof(u_int32_t)) /* set enable/disable */
2822 (set_disable | rulenum[0]) & ~rulenum[1] &
2823 ~(1<<RESVD_SET); /* set RESVD_SET always enabled */
2829 case IP_FW_RESETLOG: /* argument is an int, the rule number */
2831 if (sopt->sopt_val != 0) {
2832 error = sooptcopyin(sopt, &rule_num,
2833 sizeof(int), sizeof(int));
2837 error = zero_entry(&layer3_chain, rule_num,
2838 sopt->sopt_name == IP_FW_RESETLOG);
2842 printf("ipfw: ipfw_ctl invalid option %d\n", sopt->sopt_name);
2851 * dummynet needs a reference to the default rule, because rules can be
2852 * deleted while packets hold a reference to them. When this happens,
2853 * dummynet changes the reference to the default rule (it could well be a
2854 * NULL pointer, but this way we do not need to check for the special
2855 * case, plus here he have info on the default behaviour).
2857 struct ip_fw *ip_fw_default_rule;
2860 * This procedure is only used to handle keepalives. It is invoked
2861 * every dyn_keepalive_period
2864 ipfw_tick(void * __unused unused)
2869 if (dyn_keepalive == 0 || ipfw_dyn_v == NULL || dyn_count == 0)
2873 for (i = 0 ; i < curr_dyn_buckets ; i++) {
2874 for (q = ipfw_dyn_v[i] ; q ; q = q->next ) {
2875 if (q->dyn_type == O_LIMIT_PARENT)
2877 if (q->id.proto != IPPROTO_TCP)
2879 if ( (q->state & BOTH_SYN) != BOTH_SYN)
2881 if (TIME_LEQ( time_second+dyn_keepalive_interval,
2883 continue; /* too early */
2884 if (TIME_LEQ(q->expire, time_second))
2885 continue; /* too late, rule expired */
2887 send_pkt(&(q->id), q->ack_rev - 1, q->ack_fwd, TH_SYN);
2888 send_pkt(&(q->id), q->ack_fwd - 1, q->ack_rev, 0);
2893 callout_reset(&ipfw_timeout, dyn_keepalive_period*hz, ipfw_tick, NULL);
2899 struct ip_fw default_rule;
2902 layer3_chain.rules = NULL;
2903 IPFW_LOCK_INIT(&layer3_chain);
2904 IPFW_DYN_LOCK_INIT();
2905 callout_init(&ipfw_timeout, CALLOUT_MPSAFE);
2907 bzero(&default_rule, sizeof default_rule);
2909 default_rule.act_ofs = 0;
2910 default_rule.rulenum = IPFW_DEFAULT_RULE;
2911 default_rule.cmd_len = 1;
2912 default_rule.set = RESVD_SET;
2914 default_rule.cmd[0].len = 1;
2915 default_rule.cmd[0].opcode =
2916 #ifdef IPFIREWALL_DEFAULT_TO_ACCEPT
2921 error = add_rule(&layer3_chain, &default_rule);
2923 printf("ipfw2: error %u initializing default rule "
2924 "(support disabled)\n", error);
2925 IPFW_DYN_LOCK_DESTROY();
2926 IPFW_LOCK_DESTROY(&layer3_chain);
2930 ip_fw_default_rule = layer3_chain.rules;
2931 printf("ipfw2 initialized, divert %s, "
2932 "rule-based forwarding enabled, default to %s, logging ",
2938 default_rule.cmd[0].opcode == O_ACCEPT ? "accept" : "deny");
2940 #ifdef IPFIREWALL_VERBOSE
2943 #ifdef IPFIREWALL_VERBOSE_LIMIT
2944 verbose_limit = IPFIREWALL_VERBOSE_LIMIT;
2946 if (fw_verbose == 0)
2947 printf("disabled\n");
2948 else if (verbose_limit == 0)
2949 printf("unlimited\n");
2951 printf("limited to %d packets/entry by default\n",
2954 ip_fw_chk_ptr = ipfw_chk;
2955 ip_fw_ctl_ptr = ipfw_ctl;
2956 callout_reset(&ipfw_timeout, hz, ipfw_tick, NULL);
2966 IPFW_LOCK(&layer3_chain);
2967 callout_stop(&ipfw_timeout);
2968 ip_fw_chk_ptr = NULL;
2969 ip_fw_ctl_ptr = NULL;
2970 layer3_chain.reap = NULL;
2971 free_chain(&layer3_chain, 1 /* kill default rule */);
2972 reap = layer3_chain.reap, layer3_chain.reap = NULL;
2973 IPFW_UNLOCK(&layer3_chain);
2977 IPFW_DYN_LOCK_DESTROY();
2978 IPFW_LOCK_DESTROY(&layer3_chain);
2979 printf("IP firewall unloaded\n");
2983 ipfw_modevent(module_t mod, int type, void *unused)
2990 printf("IP firewall already loaded\n");
3007 static moduledata_t ipfwmod = {
3012 DECLARE_MODULE(ipfw, ipfwmod, SI_SUB_PSEUDO, SI_ORDER_ANY);
3013 MODULE_VERSION(ipfw, 1);