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
25 * $FreeBSD: src/sys/netinet/ip_fw2.c,v 1.6.2.12 2003/04/08 10:42:32 maxim Exp $
26 * $DragonFly: src/sys/net/ipfw/ip_fw2.c,v 1.57 2008/07/31 12:35:15 sephe Exp $
33 * Implement IP packet firewall (new version)
39 #include "opt_ipdivert.h"
42 #error IPFIREWALL requires INET.
46 #include <sys/param.h>
47 #include <sys/systm.h>
48 #include <sys/malloc.h>
50 #include <sys/kernel.h>
52 #include <sys/socket.h>
53 #include <sys/socketvar.h>
54 #include <sys/sysctl.h>
55 #include <sys/syslog.h>
56 #include <sys/thread2.h>
57 #include <sys/ucred.h>
58 #include <sys/in_cksum.h>
61 #include <net/route.h>
62 #include <net/netmsg2.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>
72 #include <net/dummynet/ip_dummynet.h>
73 #include <netinet/tcp.h>
74 #include <netinet/tcp_timer.h>
75 #include <netinet/tcp_var.h>
76 #include <netinet/tcpip.h>
77 #include <netinet/udp.h>
78 #include <netinet/udp_var.h>
80 #include <netinet/if_ether.h> /* XXX for ETHERTYPE_IP */
83 * set_disable contains one bit per set value (0..31).
84 * If the bit is set, all rules with the corresponding set
85 * are disabled. Set 31 is reserved for the default rule
86 * and CANNOT be disabled.
88 static uint32_t set_disable;
90 static int fw_verbose;
91 static int verbose_limit;
94 static int ipfw_refcnt;
97 static struct callout ipfw_timeout_h;
98 #define IPFW_DEFAULT_RULE 65535
101 * list of rules for layer 3
103 static struct ip_fw *layer3_chain;
105 MALLOC_DEFINE(M_IPFW, "IpFw/IpAcct", "IpFw/IpAcct chain's");
107 static int fw_debug = 1;
108 static int autoinc_step = 100; /* bounded to 1..1000 in ipfw_add_rule() */
111 SYSCTL_NODE(_net_inet_ip, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall");
112 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, enable, CTLFLAG_RW,
113 &fw_enable, 0, "Enable ipfw");
114 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, autoinc_step, CTLFLAG_RW,
115 &autoinc_step, 0, "Rule number autincrement step");
116 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO,one_pass,CTLFLAG_RW,
118 "Only do a single pass through ipfw when using dummynet(4)");
119 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, debug, CTLFLAG_RW,
120 &fw_debug, 0, "Enable printing of debug ip_fw statements");
121 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose, CTLFLAG_RW,
122 &fw_verbose, 0, "Log matches to ipfw rules");
123 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose_limit, CTLFLAG_RW,
124 &verbose_limit, 0, "Set upper limit of matches of ipfw rules logged");
127 * Description of dynamic rules.
129 * Dynamic rules are stored in lists accessed through a hash table
130 * (ipfw_dyn_v) whose size is curr_dyn_buckets. This value can
131 * be modified through the sysctl variable dyn_buckets which is
132 * updated when the table becomes empty.
134 * XXX currently there is only one list, ipfw_dyn.
136 * When a packet is received, its address fields are first masked
137 * with the mask defined for the rule, then hashed, then matched
138 * against the entries in the corresponding list.
139 * Dynamic rules can be used for different purposes:
141 * + enforcing limits on the number of sessions;
142 * + in-kernel NAT (not implemented yet)
144 * The lifetime of dynamic rules is regulated by dyn_*_lifetime,
145 * measured in seconds and depending on the flags.
147 * The total number of dynamic rules is stored in dyn_count.
148 * The max number of dynamic rules is dyn_max. When we reach
149 * the maximum number of rules we do not create anymore. This is
150 * done to avoid consuming too much memory, but also too much
151 * time when searching on each packet (ideally, we should try instead
152 * to put a limit on the length of the list on each bucket...).
154 * Each dynamic rule holds a pointer to the parent ipfw rule so
155 * we know what action to perform. Dynamic rules are removed when
156 * the parent rule is deleted. XXX we should make them survive.
158 * There are some limitations with dynamic rules -- we do not
159 * obey the 'randomized match', and we do not do multiple
160 * passes through the firewall. XXX check the latter!!!
162 static ipfw_dyn_rule **ipfw_dyn_v = NULL;
163 static uint32_t dyn_buckets = 256; /* must be power of 2 */
164 static uint32_t curr_dyn_buckets = 256; /* must be power of 2 */
167 * Timeouts for various events in handing dynamic rules.
169 static uint32_t dyn_ack_lifetime = 300;
170 static uint32_t dyn_syn_lifetime = 20;
171 static uint32_t dyn_fin_lifetime = 1;
172 static uint32_t dyn_rst_lifetime = 1;
173 static uint32_t dyn_udp_lifetime = 10;
174 static uint32_t dyn_short_lifetime = 5;
177 * Keepalives are sent if dyn_keepalive is set. They are sent every
178 * dyn_keepalive_period seconds, in the last dyn_keepalive_interval
179 * seconds of lifetime of a rule.
180 * dyn_rst_lifetime and dyn_fin_lifetime should be strictly lower
181 * than dyn_keepalive_period.
184 static uint32_t dyn_keepalive_interval = 20;
185 static uint32_t dyn_keepalive_period = 5;
186 static uint32_t dyn_keepalive = 1; /* do send keepalives */
188 static uint32_t static_count; /* # of static rules */
189 static uint32_t static_ioc_len; /* bytes of static rules */
190 static uint32_t dyn_count; /* # of dynamic rules */
191 static uint32_t dyn_max = 4096; /* max # of dynamic rules */
193 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_buckets, CTLFLAG_RW,
194 &dyn_buckets, 0, "Number of dyn. buckets");
195 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, curr_dyn_buckets, CTLFLAG_RD,
196 &curr_dyn_buckets, 0, "Current Number of dyn. buckets");
197 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_count, CTLFLAG_RD,
198 &dyn_count, 0, "Number of dyn. rules");
199 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_max, CTLFLAG_RW,
200 &dyn_max, 0, "Max number of dyn. rules");
201 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, static_count, CTLFLAG_RD,
202 &static_count, 0, "Number of static rules");
203 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_ack_lifetime, CTLFLAG_RW,
204 &dyn_ack_lifetime, 0, "Lifetime of dyn. rules for acks");
205 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_syn_lifetime, CTLFLAG_RW,
206 &dyn_syn_lifetime, 0, "Lifetime of dyn. rules for syn");
207 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_fin_lifetime, CTLFLAG_RW,
208 &dyn_fin_lifetime, 0, "Lifetime of dyn. rules for fin");
209 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_rst_lifetime, CTLFLAG_RW,
210 &dyn_rst_lifetime, 0, "Lifetime of dyn. rules for rst");
211 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_udp_lifetime, CTLFLAG_RW,
212 &dyn_udp_lifetime, 0, "Lifetime of dyn. rules for UDP");
213 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_short_lifetime, CTLFLAG_RW,
214 &dyn_short_lifetime, 0, "Lifetime of dyn. rules for other situations");
215 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_keepalive, CTLFLAG_RW,
216 &dyn_keepalive, 0, "Enable keepalives for dyn. rules");
218 #endif /* SYSCTL_NODE */
220 static struct ip_fw *ip_fw_default_rule;
222 static ip_fw_chk_t ipfw_chk;
225 ipfw_free_rule(struct ip_fw *rule)
227 KASSERT(rule->refcnt > 0, ("invalid refcnt %u\n", rule->refcnt));
228 atomic_subtract_int(&rule->refcnt, 1);
229 if (atomic_cmpset_int(&rule->refcnt, 0, 1)) {
237 ipfw_unref_rule(void *priv)
239 ipfw_free_rule(priv);
241 atomic_subtract_int(&ipfw_refcnt, 1);
246 ipfw_ref_rule(struct ip_fw *rule)
249 atomic_add_int(&ipfw_refcnt, 1);
251 atomic_add_int(&rule->refcnt, 1);
255 * This macro maps an ip pointer into a layer3 header pointer of type T
257 #define L3HDR(T, ip) ((T *)((uint32_t *)(ip) + (ip)->ip_hl))
260 icmptype_match(struct ip *ip, ipfw_insn_u32 *cmd)
262 int type = L3HDR(struct icmp,ip)->icmp_type;
264 return (type <= ICMP_MAXTYPE && (cmd->d[0] & (1 << type)));
267 #define TT ((1 << ICMP_ECHO) | \
268 (1 << ICMP_ROUTERSOLICIT) | \
269 (1 << ICMP_TSTAMP) | \
274 is_icmp_query(struct ip *ip)
276 int type = L3HDR(struct icmp, ip)->icmp_type;
278 return (type <= ICMP_MAXTYPE && (TT & (1 << type)));
284 * The following checks use two arrays of 8 or 16 bits to store the
285 * bits that we want set or clear, respectively. They are in the
286 * low and high half of cmd->arg1 or cmd->d[0].
288 * We scan options and store the bits we find set. We succeed if
290 * (want_set & ~bits) == 0 && (want_clear & ~bits) == want_clear
292 * The code is sometimes optimized not to store additional variables.
296 flags_match(ipfw_insn *cmd, uint8_t bits)
301 if (((cmd->arg1 & 0xff) & bits) != 0)
302 return 0; /* some bits we want set were clear */
304 want_clear = (cmd->arg1 >> 8) & 0xff;
305 if ((want_clear & bits) != want_clear)
306 return 0; /* some bits we want clear were set */
311 ipopts_match(struct ip *ip, ipfw_insn *cmd)
313 int optlen, bits = 0;
314 u_char *cp = (u_char *)(ip + 1);
315 int x = (ip->ip_hl << 2) - sizeof(struct ip);
317 for (; x > 0; x -= optlen, cp += optlen) {
318 int opt = cp[IPOPT_OPTVAL];
320 if (opt == IPOPT_EOL)
323 if (opt == IPOPT_NOP) {
326 optlen = cp[IPOPT_OLEN];
327 if (optlen <= 0 || optlen > x)
328 return 0; /* invalid or truncated */
333 bits |= IP_FW_IPOPT_LSRR;
337 bits |= IP_FW_IPOPT_SSRR;
341 bits |= IP_FW_IPOPT_RR;
345 bits |= IP_FW_IPOPT_TS;
352 return (flags_match(cmd, bits));
356 tcpopts_match(struct ip *ip, ipfw_insn *cmd)
358 int optlen, bits = 0;
359 struct tcphdr *tcp = L3HDR(struct tcphdr,ip);
360 u_char *cp = (u_char *)(tcp + 1);
361 int x = (tcp->th_off << 2) - sizeof(struct tcphdr);
363 for (; x > 0; x -= optlen, cp += optlen) {
366 if (opt == TCPOPT_EOL)
369 if (opt == TCPOPT_NOP) {
379 bits |= IP_FW_TCPOPT_MSS;
383 bits |= IP_FW_TCPOPT_WINDOW;
386 case TCPOPT_SACK_PERMITTED:
388 bits |= IP_FW_TCPOPT_SACK;
391 case TCPOPT_TIMESTAMP:
392 bits |= IP_FW_TCPOPT_TS;
398 bits |= IP_FW_TCPOPT_CC;
405 return (flags_match(cmd, bits));
409 iface_match(struct ifnet *ifp, ipfw_insn_if *cmd)
411 if (ifp == NULL) /* no iface with this packet, match fails */
414 /* Check by name or by IP address */
415 if (cmd->name[0] != '\0') { /* match by name */
418 if (kfnmatch(cmd->name, ifp->if_xname, 0) == 0)
421 if (strncmp(ifp->if_xname, cmd->name, IFNAMSIZ) == 0)
425 struct ifaddr_container *ifac;
427 TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
428 struct ifaddr *ia = ifac->ifa;
430 if (ia->ifa_addr == NULL)
432 if (ia->ifa_addr->sa_family != AF_INET)
434 if (cmd->p.ip.s_addr == ((struct sockaddr_in *)
435 (ia->ifa_addr))->sin_addr.s_addr)
436 return(1); /* match */
439 return(0); /* no match, fail ... */
442 static uint64_t norule_counter; /* counter for ipfw_log(NULL...) */
444 #define SNPARGS(buf, len) buf + len, sizeof(buf) > len ? sizeof(buf) - len : 0
447 * We enter here when we have a rule with O_LOG.
448 * XXX this function alone takes about 2Kbytes of code!
451 ipfw_log(struct ip_fw *f, u_int hlen, struct ether_header *eh,
452 struct mbuf *m, struct ifnet *oif)
455 int limit_reached = 0;
456 char action2[40], proto[48], fragment[28];
461 if (f == NULL) { /* bogus pkt */
462 if (verbose_limit != 0 && norule_counter >= verbose_limit)
465 if (norule_counter == verbose_limit)
466 limit_reached = verbose_limit;
468 } else { /* O_LOG is the first action, find the real one */
469 ipfw_insn *cmd = ACTION_PTR(f);
470 ipfw_insn_log *l = (ipfw_insn_log *)cmd;
472 if (l->max_log != 0 && l->log_left == 0)
475 if (l->log_left == 0)
476 limit_reached = l->max_log;
477 cmd += F_LEN(cmd); /* point to first action */
478 if (cmd->opcode == O_PROB)
482 switch (cmd->opcode) {
488 if (cmd->arg1==ICMP_REJECT_RST) {
490 } else if (cmd->arg1==ICMP_UNREACH_HOST) {
493 ksnprintf(SNPARGS(action2, 0), "Unreach %d",
507 ksnprintf(SNPARGS(action2, 0), "Divert %d", cmd->arg1);
511 ksnprintf(SNPARGS(action2, 0), "Tee %d", cmd->arg1);
515 ksnprintf(SNPARGS(action2, 0), "SkipTo %d", cmd->arg1);
519 ksnprintf(SNPARGS(action2, 0), "Pipe %d", cmd->arg1);
523 ksnprintf(SNPARGS(action2, 0), "Queue %d", cmd->arg1);
528 ipfw_insn_sa *sa = (ipfw_insn_sa *)cmd;
531 len = ksnprintf(SNPARGS(action2, 0),
533 inet_ntoa(sa->sa.sin_addr));
534 if (sa->sa.sin_port) {
535 ksnprintf(SNPARGS(action2, len), ":%d",
547 if (hlen == 0) { /* non-ip */
548 ksnprintf(SNPARGS(proto, 0), "MAC");
550 struct ip *ip = mtod(m, struct ip *);
551 /* these three are all aliases to the same thing */
552 struct icmp *const icmp = L3HDR(struct icmp, ip);
553 struct tcphdr *const tcp = (struct tcphdr *)icmp;
554 struct udphdr *const udp = (struct udphdr *)icmp;
556 int ip_off, offset, ip_len;
559 if (eh != NULL) { /* layer 2 packets are as on the wire */
560 ip_off = ntohs(ip->ip_off);
561 ip_len = ntohs(ip->ip_len);
566 offset = ip_off & IP_OFFMASK;
569 len = ksnprintf(SNPARGS(proto, 0), "TCP %s",
570 inet_ntoa(ip->ip_src));
572 ksnprintf(SNPARGS(proto, len), ":%d %s:%d",
573 ntohs(tcp->th_sport),
574 inet_ntoa(ip->ip_dst),
575 ntohs(tcp->th_dport));
577 ksnprintf(SNPARGS(proto, len), " %s",
578 inet_ntoa(ip->ip_dst));
583 len = ksnprintf(SNPARGS(proto, 0), "UDP %s",
584 inet_ntoa(ip->ip_src));
586 ksnprintf(SNPARGS(proto, len), ":%d %s:%d",
587 ntohs(udp->uh_sport),
588 inet_ntoa(ip->ip_dst),
589 ntohs(udp->uh_dport));
591 ksnprintf(SNPARGS(proto, len), " %s",
592 inet_ntoa(ip->ip_dst));
598 len = ksnprintf(SNPARGS(proto, 0),
603 len = ksnprintf(SNPARGS(proto, 0), "ICMP ");
605 len += ksnprintf(SNPARGS(proto, len), "%s",
606 inet_ntoa(ip->ip_src));
607 ksnprintf(SNPARGS(proto, len), " %s",
608 inet_ntoa(ip->ip_dst));
612 len = ksnprintf(SNPARGS(proto, 0), "P:%d %s", ip->ip_p,
613 inet_ntoa(ip->ip_src));
614 ksnprintf(SNPARGS(proto, len), " %s",
615 inet_ntoa(ip->ip_dst));
619 if (ip_off & (IP_MF | IP_OFFMASK)) {
620 ksnprintf(SNPARGS(fragment, 0), " (frag %d:%d@%d%s)",
621 ntohs(ip->ip_id), ip_len - (ip->ip_hl << 2),
622 offset << 3, (ip_off & IP_MF) ? "+" : "");
626 if (oif || m->m_pkthdr.rcvif) {
627 log(LOG_SECURITY | LOG_INFO,
628 "ipfw: %d %s %s %s via %s%s\n",
630 action, proto, oif ? "out" : "in",
631 oif ? oif->if_xname : m->m_pkthdr.rcvif->if_xname,
634 log(LOG_SECURITY | LOG_INFO,
635 "ipfw: %d %s %s [no if info]%s\n",
637 action, proto, fragment);
641 log(LOG_SECURITY | LOG_NOTICE,
642 "ipfw: limit %d reached on entry %d\n",
643 limit_reached, f ? f->rulenum : -1);
650 * IMPORTANT: the hash function for dynamic rules must be commutative
651 * in source and destination (ip,port), because rules are bidirectional
652 * and we want to find both in the same bucket.
655 hash_packet(struct ipfw_flow_id *id)
659 i = (id->dst_ip) ^ (id->src_ip) ^ (id->dst_port) ^ (id->src_port);
660 i &= (curr_dyn_buckets - 1);
665 * unlink a dynamic rule from a chain. prev is a pointer to
666 * the previous one, q is a pointer to the rule to delete,
667 * head is a pointer to the head of the queue.
668 * Modifies q and potentially also head.
670 #define UNLINK_DYN_RULE(prev, head, q) \
672 ipfw_dyn_rule *old_q = q; \
674 /* remove a refcount to the parent */ \
675 if (q->dyn_type == O_LIMIT) \
676 q->parent->count--; \
677 DEB(kprintf("-- unlink entry 0x%08x %d -> 0x%08x %d, %d left\n", \
678 (q->id.src_ip), (q->id.src_port), \
679 (q->id.dst_ip), (q->id.dst_port), dyn_count-1 ); ) \
681 prev->next = q = q->next; \
683 head = q = q->next; \
684 KASSERT(dyn_count > 0, ("invalid dyn count %u\n", dyn_count)); \
686 kfree(old_q, M_IPFW); \
689 #define TIME_LEQ(a, b) ((int)((a) - (b)) <= 0)
692 * Remove dynamic rules pointing to "rule", or all of them if rule == NULL.
694 * If keep_me == NULL, rules are deleted even if not expired,
695 * otherwise only expired rules are removed.
697 * The value of the second parameter is also used to point to identify
698 * a rule we absolutely do not want to remove (e.g. because we are
699 * holding a reference to it -- this is the case with O_LIMIT_PARENT
700 * rules). The pointer is only used for comparison, so any non-null
704 remove_dyn_rule(struct ip_fw *rule, ipfw_dyn_rule *keep_me)
706 static uint32_t last_remove = 0;
708 #define FORCE (keep_me == NULL)
710 ipfw_dyn_rule *prev, *q;
711 int i, pass = 0, max_pass = 0;
713 if (ipfw_dyn_v == NULL || dyn_count == 0)
715 /* do not expire more than once per second, it is useless */
716 if (!FORCE && last_remove == time_second)
718 last_remove = time_second;
721 * because O_LIMIT refer to parent rules, during the first pass only
722 * remove child and mark any pending LIMIT_PARENT, and remove
723 * them in a second pass.
726 for (i = 0; i < curr_dyn_buckets; i++) {
727 for (prev = NULL, q = ipfw_dyn_v[i]; q;) {
729 * Logic can become complex here, so we split tests.
733 if (rule != NULL && rule != q->rule)
734 goto next; /* not the one we are looking for */
735 if (q->dyn_type == O_LIMIT_PARENT) {
737 * handle parent in the second pass,
738 * record we need one.
743 if (FORCE && q->count != 0) {
744 /* XXX should not happen! */
745 kprintf("OUCH! cannot remove rule, "
746 "count %d\n", q->count);
749 if (!FORCE && !TIME_LEQ(q->expire, time_second))
752 UNLINK_DYN_RULE(prev, ipfw_dyn_v[i], q);
759 if (pass++ < max_pass)
767 * lookup a dynamic rule.
769 static ipfw_dyn_rule *
770 lookup_dyn_rule(struct ipfw_flow_id *pkt, int *match_direction,
774 * stateful ipfw extensions.
775 * Lookup into dynamic session queue
777 #define MATCH_REVERSE 0
778 #define MATCH_FORWARD 1
780 #define MATCH_UNKNOWN 3
781 int i, dir = MATCH_NONE;
782 ipfw_dyn_rule *prev, *q=NULL;
784 if (ipfw_dyn_v == NULL)
785 goto done; /* not found */
787 i = hash_packet(pkt);
788 for (prev = NULL, q = ipfw_dyn_v[i]; q != NULL;) {
789 if (q->dyn_type == O_LIMIT_PARENT)
792 if (TIME_LEQ( q->expire, time_second)) { /* expire entry */
793 UNLINK_DYN_RULE(prev, ipfw_dyn_v[i], q);
796 if (pkt->proto == q->id.proto) {
797 if (pkt->src_ip == q->id.src_ip &&
798 pkt->dst_ip == q->id.dst_ip &&
799 pkt->src_port == q->id.src_port &&
800 pkt->dst_port == q->id.dst_port) {
804 if (pkt->src_ip == q->id.dst_ip &&
805 pkt->dst_ip == q->id.src_ip &&
806 pkt->src_port == q->id.dst_port &&
807 pkt->dst_port == q->id.src_port) {
817 goto done; /* q = NULL, not found */
819 if (prev != NULL) { /* found and not in front */
820 prev->next = q->next;
821 q->next = ipfw_dyn_v[i];
825 if (pkt->proto == IPPROTO_TCP) { /* update state according to flags */
826 u_char flags = pkt->flags & (TH_FIN|TH_SYN|TH_RST);
828 #define BOTH_SYN (TH_SYN | (TH_SYN << 8))
829 #define BOTH_FIN (TH_FIN | (TH_FIN << 8))
831 q->state |= (dir == MATCH_FORWARD ) ? flags : (flags << 8);
833 case TH_SYN: /* opening */
834 q->expire = time_second + dyn_syn_lifetime;
837 case BOTH_SYN: /* move to established */
838 case BOTH_SYN | TH_FIN : /* one side tries to close */
839 case BOTH_SYN | (TH_FIN << 8) :
841 uint32_t ack = ntohl(tcp->th_ack);
843 #define _SEQ_GE(a, b) ((int)(a) - (int)(b) >= 0)
845 if (dir == MATCH_FORWARD) {
846 if (q->ack_fwd == 0 ||
847 _SEQ_GE(ack, q->ack_fwd))
849 else /* ignore out-of-sequence */
852 if (q->ack_rev == 0 ||
853 _SEQ_GE(ack, q->ack_rev))
855 else /* ignore out-of-sequence */
860 q->expire = time_second + dyn_ack_lifetime;
863 case BOTH_SYN | BOTH_FIN: /* both sides closed */
864 if (dyn_fin_lifetime >= dyn_keepalive_period)
865 dyn_fin_lifetime = dyn_keepalive_period - 1;
866 q->expire = time_second + dyn_fin_lifetime;
872 * reset or some invalid combination, but can also
873 * occur if we use keep-state the wrong way.
875 if ((q->state & ((TH_RST << 8) | TH_RST)) == 0)
876 kprintf("invalid state: 0x%x\n", q->state);
878 if (dyn_rst_lifetime >= dyn_keepalive_period)
879 dyn_rst_lifetime = dyn_keepalive_period - 1;
880 q->expire = time_second + dyn_rst_lifetime;
883 } else if (pkt->proto == IPPROTO_UDP) {
884 q->expire = time_second + dyn_udp_lifetime;
886 /* other protocols */
887 q->expire = time_second + dyn_short_lifetime;
891 *match_direction = dir;
896 realloc_dynamic_table(void)
899 * Try reallocation, make sure we have a power of 2 and do
900 * not allow more than 64k entries. In case of overflow,
904 if (dyn_buckets > 65536)
906 if ((dyn_buckets & (dyn_buckets-1)) != 0) { /* not a power of 2 */
907 dyn_buckets = curr_dyn_buckets; /* reset */
910 curr_dyn_buckets = dyn_buckets;
912 if (ipfw_dyn_v != NULL)
913 kfree(ipfw_dyn_v, M_IPFW);
916 ipfw_dyn_v = kmalloc(curr_dyn_buckets * sizeof(ipfw_dyn_rule *),
917 M_IPFW, M_INTWAIT | M_NULLOK | M_ZERO);
918 if (ipfw_dyn_v != NULL || curr_dyn_buckets <= 2)
920 curr_dyn_buckets /= 2;
925 * Install state of type 'type' for a dynamic session.
926 * The hash table contains two type of rules:
927 * - regular rules (O_KEEP_STATE)
928 * - rules for sessions with limited number of sess per user
929 * (O_LIMIT). When they are created, the parent is
930 * increased by 1, and decreased on delete. In this case,
931 * the third parameter is the parent rule and not the chain.
932 * - "parent" rules for the above (O_LIMIT_PARENT).
934 static ipfw_dyn_rule *
935 add_dyn_rule(struct ipfw_flow_id *id, uint8_t dyn_type, struct ip_fw *rule)
940 if (ipfw_dyn_v == NULL ||
941 (dyn_count == 0 && dyn_buckets != curr_dyn_buckets)) {
942 realloc_dynamic_table();
943 if (ipfw_dyn_v == NULL)
944 return NULL; /* failed ! */
948 r = kmalloc(sizeof(*r), M_IPFW, M_INTWAIT | M_NULLOK | M_ZERO);
950 kprintf ("sorry cannot allocate state\n");
954 /* increase refcount on parent, and set pointer */
955 if (dyn_type == O_LIMIT) {
956 ipfw_dyn_rule *parent = (ipfw_dyn_rule *)rule;
958 if (parent->dyn_type != O_LIMIT_PARENT)
959 panic("invalid parent");
966 r->expire = time_second + dyn_syn_lifetime;
968 r->dyn_type = dyn_type;
969 r->pcnt = r->bcnt = 0;
973 r->next = ipfw_dyn_v[i];
976 DEB(kprintf("-- add dyn entry ty %d 0x%08x %d -> 0x%08x %d, total %d\n",
978 (r->id.src_ip), (r->id.src_port),
979 (r->id.dst_ip), (r->id.dst_port),
985 * lookup dynamic parent rule using pkt and rule as search keys.
986 * If the lookup fails, then install one.
988 static ipfw_dyn_rule *
989 lookup_dyn_parent(struct ipfw_flow_id *pkt, struct ip_fw *rule)
995 i = hash_packet(pkt);
996 for (q = ipfw_dyn_v[i]; q != NULL; q = q->next) {
997 if (q->dyn_type == O_LIMIT_PARENT &&
999 pkt->proto == q->id.proto &&
1000 pkt->src_ip == q->id.src_ip &&
1001 pkt->dst_ip == q->id.dst_ip &&
1002 pkt->src_port == q->id.src_port &&
1003 pkt->dst_port == q->id.dst_port) {
1004 q->expire = time_second + dyn_short_lifetime;
1005 DEB(kprintf("lookup_dyn_parent found 0x%p\n",q);)
1010 return add_dyn_rule(pkt, O_LIMIT_PARENT, rule);
1014 * Install dynamic state for rule type cmd->o.opcode
1016 * Returns 1 (failure) if state is not installed because of errors or because
1017 * session limitations are enforced.
1020 install_state(struct ip_fw *rule, ipfw_insn_limit *cmd,
1021 struct ip_fw_args *args)
1023 static int last_log;
1027 DEB(kprintf("-- install state type %d 0x%08x %u -> 0x%08x %u\n",
1029 (args->f_id.src_ip), (args->f_id.src_port),
1030 (args->f_id.dst_ip), (args->f_id.dst_port) );)
1032 q = lookup_dyn_rule(&args->f_id, NULL, NULL);
1033 if (q != NULL) { /* should never occur */
1034 if (last_log != time_second) {
1035 last_log = time_second;
1036 kprintf(" install_state: entry already present, done\n");
1041 if (dyn_count >= dyn_max) {
1043 * Run out of slots, try to remove any expired rule.
1045 remove_dyn_rule(NULL, (ipfw_dyn_rule *)1);
1048 if (dyn_count >= dyn_max) {
1049 if (last_log != time_second) {
1050 last_log = time_second;
1051 kprintf("install_state: Too many dynamic rules\n");
1053 return 1; /* cannot install, notify caller */
1056 switch (cmd->o.opcode) {
1057 case O_KEEP_STATE: /* bidir rule */
1058 add_dyn_rule(&args->f_id, O_KEEP_STATE, rule);
1061 case O_LIMIT: /* limit number of sessions */
1063 uint16_t limit_mask = cmd->limit_mask;
1064 struct ipfw_flow_id id;
1065 ipfw_dyn_rule *parent;
1067 DEB(kprintf("installing dyn-limit rule %d\n",
1070 id.dst_ip = id.src_ip = 0;
1071 id.dst_port = id.src_port = 0;
1072 id.proto = args->f_id.proto;
1074 if (limit_mask & DYN_SRC_ADDR)
1075 id.src_ip = args->f_id.src_ip;
1076 if (limit_mask & DYN_DST_ADDR)
1077 id.dst_ip = args->f_id.dst_ip;
1078 if (limit_mask & DYN_SRC_PORT)
1079 id.src_port = args->f_id.src_port;
1080 if (limit_mask & DYN_DST_PORT)
1081 id.dst_port = args->f_id.dst_port;
1083 parent = lookup_dyn_parent(&id, rule);
1084 if (parent == NULL) {
1085 kprintf("add parent failed\n");
1089 if (parent->count >= cmd->conn_limit) {
1091 * See if we can remove some expired rule.
1093 remove_dyn_rule(rule, parent);
1094 if (parent->count >= cmd->conn_limit) {
1096 last_log != time_second) {
1097 last_log = time_second;
1098 log(LOG_SECURITY | LOG_DEBUG,
1100 "too many entries\n");
1105 add_dyn_rule(&args->f_id, O_LIMIT,
1106 (struct ip_fw *)parent);
1110 kprintf("unknown dynamic rule type %u\n", cmd->o.opcode);
1113 lookup_dyn_rule(&args->f_id, NULL, NULL); /* XXX just set lifetime */
1118 * Transmit a TCP packet, containing either a RST or a keepalive.
1119 * When flags & TH_RST, we are sending a RST packet, because of a
1120 * "reset" action matched the packet.
1121 * Otherwise we are sending a keepalive, and flags & TH_
1124 send_pkt(struct ipfw_flow_id *id, uint32_t seq, uint32_t ack, int flags)
1129 struct route sro; /* fake route */
1131 MGETHDR(m, MB_DONTWAIT, MT_HEADER);
1134 m->m_pkthdr.rcvif = NULL;
1135 m->m_pkthdr.len = m->m_len = sizeof(struct ip) + sizeof(struct tcphdr);
1136 m->m_data += max_linkhdr;
1138 ip = mtod(m, struct ip *);
1139 bzero(ip, m->m_len);
1140 tcp = (struct tcphdr *)(ip + 1); /* no IP options */
1141 ip->ip_p = IPPROTO_TCP;
1145 * Assume we are sending a RST (or a keepalive in the reverse
1146 * direction), swap src and destination addresses and ports.
1148 ip->ip_src.s_addr = htonl(id->dst_ip);
1149 ip->ip_dst.s_addr = htonl(id->src_ip);
1150 tcp->th_sport = htons(id->dst_port);
1151 tcp->th_dport = htons(id->src_port);
1152 if (flags & TH_RST) { /* we are sending a RST */
1153 if (flags & TH_ACK) {
1154 tcp->th_seq = htonl(ack);
1155 tcp->th_ack = htonl(0);
1156 tcp->th_flags = TH_RST;
1160 tcp->th_seq = htonl(0);
1161 tcp->th_ack = htonl(seq);
1162 tcp->th_flags = TH_RST | TH_ACK;
1166 * We are sending a keepalive. flags & TH_SYN determines
1167 * the direction, forward if set, reverse if clear.
1168 * NOTE: seq and ack are always assumed to be correct
1169 * as set by the caller. This may be confusing...
1171 if (flags & TH_SYN) {
1173 * we have to rewrite the correct addresses!
1175 ip->ip_dst.s_addr = htonl(id->dst_ip);
1176 ip->ip_src.s_addr = htonl(id->src_ip);
1177 tcp->th_dport = htons(id->dst_port);
1178 tcp->th_sport = htons(id->src_port);
1180 tcp->th_seq = htonl(seq);
1181 tcp->th_ack = htonl(ack);
1182 tcp->th_flags = TH_ACK;
1186 * set ip_len to the payload size so we can compute
1187 * the tcp checksum on the pseudoheader
1188 * XXX check this, could save a couple of words ?
1190 ip->ip_len = htons(sizeof(struct tcphdr));
1191 tcp->th_sum = in_cksum(m, m->m_pkthdr.len);
1194 * now fill fields left out earlier
1196 ip->ip_ttl = ip_defttl;
1197 ip->ip_len = m->m_pkthdr.len;
1199 bzero(&sro, sizeof(sro));
1200 ip_rtaddr(ip->ip_dst, &sro);
1202 m->m_pkthdr.fw_flags |= IPFW_MBUF_GENERATED;
1203 ip_output(m, NULL, &sro, 0, NULL, NULL);
1209 * sends a reject message, consuming the mbuf passed as an argument.
1212 send_reject(struct ip_fw_args *args, int code, int offset, int ip_len)
1215 if (code != ICMP_REJECT_RST) { /* Send an ICMP unreach */
1216 /* We need the IP header in host order for icmp_error(). */
1217 if (args->eh != NULL) {
1218 struct ip *ip = mtod(args->m, struct ip *);
1219 ip->ip_len = ntohs(ip->ip_len);
1220 ip->ip_off = ntohs(ip->ip_off);
1222 icmp_error(args->m, ICMP_UNREACH, code, 0L, 0);
1223 } else if (offset == 0 && args->f_id.proto == IPPROTO_TCP) {
1224 struct tcphdr *const tcp =
1225 L3HDR(struct tcphdr, mtod(args->m, struct ip *));
1226 if ( (tcp->th_flags & TH_RST) == 0)
1227 send_pkt(&(args->f_id), ntohl(tcp->th_seq),
1229 tcp->th_flags | TH_RST);
1238 * Given an ip_fw *, lookup_next_rule will return a pointer
1239 * to the next rule, which can be either the jump
1240 * target (for skipto instructions) or the next one in the list (in
1241 * all other cases including a missing jump target).
1242 * The result is also written in the "next_rule" field of the rule.
1243 * Backward jumps are not allowed, so start looking from the next
1246 * This never returns NULL -- in case we do not have an exact match,
1247 * the next rule is returned. When the ruleset is changed,
1248 * pointers are flushed so we are always correct.
1251 static struct ip_fw *
1252 lookup_next_rule(struct ip_fw *me)
1254 struct ip_fw *rule = NULL;
1257 /* look for action, in case it is a skipto */
1258 cmd = ACTION_PTR(me);
1259 if (cmd->opcode == O_LOG)
1261 if ( cmd->opcode == O_SKIPTO )
1262 for (rule = me->next; rule ; rule = rule->next)
1263 if (rule->rulenum >= cmd->arg1)
1265 if (rule == NULL) /* failure or not a skipto */
1267 me->next_rule = rule;
1272 * The main check routine for the firewall.
1274 * All arguments are in args so we can modify them and return them
1275 * back to the caller.
1279 * args->m (in/out) The packet; we set to NULL when/if we nuke it.
1280 * Starts with the IP header.
1281 * args->eh (in) Mac header if present, or NULL for layer3 packet.
1282 * args->oif Outgoing interface, or NULL if packet is incoming.
1283 * The incoming interface is in the mbuf. (in)
1285 * args->rule Pointer to the last matching rule (in/out)
1286 * args->next_hop Socket we are forwarding to (out).
1287 * args->f_id Addresses grabbed from the packet (out)
1291 * IP_FW_PORT_DENY_FLAG the packet must be dropped.
1292 * 0 The packet is to be accepted and routed normally OR
1293 * the packet was denied/rejected and has been dropped;
1294 * in the latter case, *m is equal to NULL upon return.
1295 * port Divert the packet to port, with these caveats:
1297 * - If IP_FW_PORT_TEE_FLAG is set, tee the packet instead
1298 * of diverting it (ie, 'ipfw tee').
1300 * - If IP_FW_PORT_DYNT_FLAG is set, interpret the lower
1301 * 16 bits as a dummynet pipe number instead of diverting
1305 ipfw_chk(struct ip_fw_args *args)
1308 * Local variables hold state during the processing of a packet.
1310 * IMPORTANT NOTE: to speed up the processing of rules, there
1311 * are some assumption on the values of the variables, which
1312 * are documented here. Should you change them, please check
1313 * the implementation of the various instructions to make sure
1314 * that they still work.
1316 * args->eh The MAC header. It is non-null for a layer2
1317 * packet, it is NULL for a layer-3 packet.
1319 * m | args->m Pointer to the mbuf, as received from the caller.
1320 * It may change if ipfw_chk() does an m_pullup, or if it
1321 * consumes the packet because it calls send_reject().
1322 * XXX This has to change, so that ipfw_chk() never modifies
1323 * or consumes the buffer.
1324 * ip is simply an alias of the value of m, and it is kept
1325 * in sync with it (the packet is supposed to start with
1328 struct mbuf *m = args->m;
1329 struct ip *ip = mtod(m, struct ip *);
1332 * oif | args->oif If NULL, ipfw_chk has been called on the
1333 * inbound path (ether_input, ip_input).
1334 * If non-NULL, ipfw_chk has been called on the outbound path
1335 * (ether_output, ip_output).
1337 struct ifnet *oif = args->oif;
1339 struct ip_fw *f = NULL; /* matching rule */
1344 * hlen The length of the IPv4 header.
1345 * hlen >0 means we have an IPv4 packet.
1347 u_int hlen = 0; /* hlen >0 means we have an IP pkt */
1350 * offset The offset of a fragment. offset != 0 means that
1351 * we have a fragment at this offset of an IPv4 packet.
1352 * offset == 0 means that (if this is an IPv4 packet)
1353 * this is the first or only fragment.
1358 * Local copies of addresses. They are only valid if we have
1361 * proto The protocol. Set to 0 for non-ip packets,
1362 * or to the protocol read from the packet otherwise.
1363 * proto != 0 means that we have an IPv4 packet.
1365 * src_port, dst_port port numbers, in HOST format. Only
1366 * valid for TCP and UDP packets.
1368 * src_ip, dst_ip ip addresses, in NETWORK format.
1369 * Only valid for IPv4 packets.
1372 uint16_t src_port = 0, dst_port = 0; /* NOTE: host format */
1373 struct in_addr src_ip, dst_ip; /* NOTE: network format */
1374 uint16_t ip_len = 0;
1375 int dyn_dir = MATCH_UNKNOWN;
1376 ipfw_dyn_rule *q = NULL;
1378 if (m->m_pkthdr.fw_flags & IPFW_MBUF_GENERATED)
1379 return 0; /* accept */
1381 * dyn_dir = MATCH_UNKNOWN when rules unchecked,
1382 * MATCH_NONE when checked and not matched (q = NULL),
1383 * MATCH_FORWARD or MATCH_REVERSE otherwise (q != NULL)
1386 if (args->eh == NULL || /* layer 3 packet */
1387 (m->m_pkthdr.len >= sizeof(struct ip) &&
1388 ntohs(args->eh->ether_type) == ETHERTYPE_IP))
1389 hlen = ip->ip_hl << 2;
1392 * Collect parameters into local variables for faster matching.
1394 if (hlen == 0) { /* do not grab addresses for non-ip pkts */
1395 proto = args->f_id.proto = 0; /* mark f_id invalid */
1396 goto after_ip_checks;
1399 proto = args->f_id.proto = ip->ip_p;
1400 src_ip = ip->ip_src;
1401 dst_ip = ip->ip_dst;
1402 if (args->eh != NULL) { /* layer 2 packets are as on the wire */
1403 offset = ntohs(ip->ip_off) & IP_OFFMASK;
1404 ip_len = ntohs(ip->ip_len);
1406 offset = ip->ip_off & IP_OFFMASK;
1407 ip_len = ip->ip_len;
1410 #define PULLUP_TO(len) \
1412 if (m->m_len < (len)) { \
1413 args->m = m = m_pullup(m, (len));\
1415 goto pullup_failed; \
1416 ip = mtod(m, struct ip *); \
1426 PULLUP_TO(hlen + sizeof(struct tcphdr));
1427 tcp = L3HDR(struct tcphdr, ip);
1428 dst_port = tcp->th_dport;
1429 src_port = tcp->th_sport;
1430 args->f_id.flags = tcp->th_flags;
1438 PULLUP_TO(hlen + sizeof(struct udphdr));
1439 udp = L3HDR(struct udphdr, ip);
1440 dst_port = udp->uh_dport;
1441 src_port = udp->uh_sport;
1446 PULLUP_TO(hlen + 4); /* type, code and checksum. */
1447 args->f_id.flags = L3HDR(struct icmp, ip)->icmp_type;
1457 args->f_id.src_ip = ntohl(src_ip.s_addr);
1458 args->f_id.dst_ip = ntohl(dst_ip.s_addr);
1459 args->f_id.src_port = src_port = ntohs(src_port);
1460 args->f_id.dst_port = dst_port = ntohs(dst_port);
1465 * Packet has already been tagged. Look for the next rule
1466 * to restart processing.
1468 * If fw_one_pass != 0 then just accept it.
1469 * XXX should not happen here, but optimized out in
1475 /* This rule was deleted */
1476 if (args->rule->rule_flags & IPFW_RULE_F_INVALID)
1477 return IP_FW_PORT_DENY_FLAG;
1479 f = args->rule->next_rule;
1481 f = lookup_next_rule(args->rule);
1484 * Find the starting rule. It can be either the first
1485 * one, or the one after divert_rule if asked so.
1489 mtag = m_tag_find(m, PACKET_TAG_IPFW_DIVERT, NULL);
1491 skipto = *(uint16_t *)m_tag_data(mtag);
1496 if (args->eh == NULL && skipto != 0) {
1497 if (skipto >= IPFW_DEFAULT_RULE)
1498 return(IP_FW_PORT_DENY_FLAG); /* invalid */
1499 while (f && f->rulenum <= skipto)
1501 if (f == NULL) /* drop packet */
1502 return(IP_FW_PORT_DENY_FLAG);
1505 if ((mtag = m_tag_find(m, PACKET_TAG_IPFW_DIVERT, NULL)) != NULL)
1506 m_tag_delete(m, mtag);
1509 * Now scan the rules, and parse microinstructions for each rule.
1511 for (; f; f = f->next) {
1514 int skip_or; /* skip rest of OR block */
1517 if (set_disable & (1 << f->set))
1521 for (l = f->cmd_len, cmd = f->cmd; l > 0;
1522 l -= cmdlen, cmd += cmdlen) {
1526 * check_body is a jump target used when we find a
1527 * CHECK_STATE, and need to jump to the body of
1532 cmdlen = F_LEN(cmd);
1534 * An OR block (insn_1 || .. || insn_n) has the
1535 * F_OR bit set in all but the last instruction.
1536 * The first match will set "skip_or", and cause
1537 * the following instructions to be skipped until
1538 * past the one with the F_OR bit clear.
1540 if (skip_or) { /* skip this instruction */
1541 if ((cmd->len & F_OR) == 0)
1542 skip_or = 0; /* next one is good */
1545 match = 0; /* set to 1 if we succeed */
1547 switch (cmd->opcode) {
1549 * The first set of opcodes compares the packet's
1550 * fields with some pattern, setting 'match' if a
1551 * match is found. At the end of the loop there is
1552 * logic to deal with F_NOT and F_OR flags associated
1560 kprintf("ipfw: opcode %d unimplemented\n",
1567 * We only check offset == 0 && proto != 0,
1568 * as this ensures that we have an IPv4
1569 * packet with the ports info.
1574 struct inpcbinfo *pi;
1578 if (proto == IPPROTO_TCP) {
1580 pi = &tcbinfo[mycpu->gd_cpuid];
1581 } else if (proto == IPPROTO_UDP) {
1588 in_pcblookup_hash(pi,
1589 dst_ip, htons(dst_port),
1590 src_ip, htons(src_port),
1592 in_pcblookup_hash(pi,
1593 src_ip, htons(src_port),
1594 dst_ip, htons(dst_port),
1597 if (pcb == NULL || pcb->inp_socket == NULL)
1600 if (cmd->opcode == O_UID) {
1601 #define socheckuid(a,b) ((a)->so_cred->cr_uid != (b))
1603 !socheckuid(pcb->inp_socket,
1604 (uid_t)((ipfw_insn_u32 *)cmd)->d[0]);
1607 match = groupmember(
1608 (uid_t)((ipfw_insn_u32 *)cmd)->d[0],
1609 pcb->inp_socket->so_cred);
1615 match = iface_match(m->m_pkthdr.rcvif,
1616 (ipfw_insn_if *)cmd);
1620 match = iface_match(oif, (ipfw_insn_if *)cmd);
1624 match = iface_match(oif ? oif :
1625 m->m_pkthdr.rcvif, (ipfw_insn_if *)cmd);
1629 if (args->eh != NULL) { /* have MAC header */
1630 uint32_t *want = (uint32_t *)
1631 ((ipfw_insn_mac *)cmd)->addr;
1632 uint32_t *mask = (uint32_t *)
1633 ((ipfw_insn_mac *)cmd)->mask;
1634 uint32_t *hdr = (uint32_t *)args->eh;
1637 (want[0] == (hdr[0] & mask[0]) &&
1638 want[1] == (hdr[1] & mask[1]) &&
1639 want[2] == (hdr[2] & mask[2]));
1644 if (args->eh != NULL) {
1646 ntohs(args->eh->ether_type);
1648 ((ipfw_insn_u16 *)cmd)->ports;
1651 /* Special vlan handling */
1652 if (m->m_flags & M_VLANTAG)
1655 for (i = cmdlen - 1; !match && i > 0;
1658 (t >= p[0] && t <= p[1]);
1664 match = (hlen > 0 && offset != 0);
1667 case O_IN: /* "out" is "not in" */
1668 match = (oif == NULL);
1672 match = (args->eh != NULL);
1677 * We do not allow an arg of 0 so the
1678 * check of "proto" only suffices.
1680 match = (proto == cmd->arg1);
1684 match = (hlen > 0 &&
1685 ((ipfw_insn_ip *)cmd)->addr.s_addr ==
1690 match = (hlen > 0 &&
1691 ((ipfw_insn_ip *)cmd)->addr.s_addr ==
1693 ((ipfw_insn_ip *)cmd)->mask.s_addr));
1700 tif = INADDR_TO_IFP(&src_ip);
1701 match = (tif != NULL);
1708 uint32_t *d = (uint32_t *)(cmd+1);
1710 cmd->opcode == O_IP_DST_SET ?
1716 addr -= d[0]; /* subtract base */
1718 (addr < cmd->arg1) &&
1719 (d[1 + (addr >> 5)] &
1720 (1 << (addr & 0x1f)));
1725 match = (hlen > 0 &&
1726 ((ipfw_insn_ip *)cmd)->addr.s_addr ==
1731 match = (hlen > 0) &&
1732 (((ipfw_insn_ip *)cmd)->addr.s_addr ==
1734 ((ipfw_insn_ip *)cmd)->mask.s_addr));
1741 tif = INADDR_TO_IFP(&dst_ip);
1742 match = (tif != NULL);
1749 * offset == 0 && proto != 0 is enough
1750 * to guarantee that we have an IPv4
1751 * packet with port info.
1753 if ((proto==IPPROTO_UDP || proto==IPPROTO_TCP)
1756 (cmd->opcode == O_IP_SRCPORT) ?
1757 src_port : dst_port ;
1759 ((ipfw_insn_u16 *)cmd)->ports;
1762 for (i = cmdlen - 1; !match && i > 0;
1765 (x >= p[0] && x <= p[1]);
1771 match = (offset == 0 && proto==IPPROTO_ICMP &&
1772 icmptype_match(ip, (ipfw_insn_u32 *)cmd));
1776 match = (hlen > 0 && ipopts_match(ip, cmd));
1780 match = (hlen > 0 && cmd->arg1 == ip->ip_v);
1784 match = (hlen > 0 && cmd->arg1 == ip->ip_ttl);
1788 match = (hlen > 0 &&
1789 cmd->arg1 == ntohs(ip->ip_id));
1793 match = (hlen > 0 && cmd->arg1 == ip_len);
1796 case O_IPPRECEDENCE:
1797 match = (hlen > 0 &&
1798 (cmd->arg1 == (ip->ip_tos & 0xe0)));
1802 match = (hlen > 0 &&
1803 flags_match(cmd, ip->ip_tos));
1807 match = (proto == IPPROTO_TCP && offset == 0 &&
1809 L3HDR(struct tcphdr,ip)->th_flags));
1813 match = (proto == IPPROTO_TCP && offset == 0 &&
1814 tcpopts_match(ip, cmd));
1818 match = (proto == IPPROTO_TCP && offset == 0 &&
1819 ((ipfw_insn_u32 *)cmd)->d[0] ==
1820 L3HDR(struct tcphdr,ip)->th_seq);
1824 match = (proto == IPPROTO_TCP && offset == 0 &&
1825 ((ipfw_insn_u32 *)cmd)->d[0] ==
1826 L3HDR(struct tcphdr,ip)->th_ack);
1830 match = (proto == IPPROTO_TCP && offset == 0 &&
1832 L3HDR(struct tcphdr,ip)->th_win);
1836 /* reject packets which have SYN only */
1837 /* XXX should i also check for TH_ACK ? */
1838 match = (proto == IPPROTO_TCP && offset == 0 &&
1839 (L3HDR(struct tcphdr,ip)->th_flags &
1840 (TH_RST | TH_ACK | TH_SYN)) != TH_SYN);
1845 ipfw_log(f, hlen, args->eh, m, oif);
1850 match = (krandom() <
1851 ((ipfw_insn_u32 *)cmd)->d[0]);
1855 * The second set of opcodes represents 'actions',
1856 * i.e. the terminal part of a rule once the packet
1857 * matches all previous patterns.
1858 * Typically there is only one action for each rule,
1859 * and the opcode is stored at the end of the rule
1860 * (but there are exceptions -- see below).
1862 * In general, here we set retval and terminate the
1863 * outer loop (would be a 'break 3' in some language,
1864 * but we need to do a 'goto done').
1867 * O_COUNT and O_SKIPTO actions:
1868 * instead of terminating, we jump to the next rule
1869 * ('goto next_rule', equivalent to a 'break 2'),
1870 * or to the SKIPTO target ('goto again' after
1871 * having set f, cmd and l), respectively.
1873 * O_LIMIT and O_KEEP_STATE: these opcodes are
1874 * not real 'actions', and are stored right
1875 * before the 'action' part of the rule.
1876 * These opcodes try to install an entry in the
1877 * state tables; if successful, we continue with
1878 * the next opcode (match=1; break;), otherwise
1879 * the packet * must be dropped
1880 * ('goto done' after setting retval);
1882 * O_PROBE_STATE and O_CHECK_STATE: these opcodes
1883 * cause a lookup of the state table, and a jump
1884 * to the 'action' part of the parent rule
1885 * ('goto check_body') if an entry is found, or
1886 * (CHECK_STATE only) a jump to the next rule if
1887 * the entry is not found ('goto next_rule').
1888 * The result of the lookup is cached to make
1889 * further instances of these opcodes are
1894 if (install_state(f,
1895 (ipfw_insn_limit *)cmd, args)) {
1896 retval = IP_FW_PORT_DENY_FLAG;
1897 goto done; /* error/limit violation */
1905 * dynamic rules are checked at the first
1906 * keep-state or check-state occurrence,
1907 * with the result being stored in dyn_dir.
1908 * The compiler introduces a PROBE_STATE
1909 * instruction for us when we have a
1910 * KEEP_STATE (because PROBE_STATE needs
1913 if (dyn_dir == MATCH_UNKNOWN &&
1914 (q = lookup_dyn_rule(&args->f_id,
1915 &dyn_dir, proto == IPPROTO_TCP ?
1916 L3HDR(struct tcphdr, ip) : NULL))
1919 * Found dynamic entry, update stats
1920 * and jump to the 'action' part of
1926 cmd = ACTION_PTR(f);
1927 l = f->cmd_len - f->act_ofs;
1931 * Dynamic entry not found. If CHECK_STATE,
1932 * skip to next rule, if PROBE_STATE just
1933 * ignore and continue with next opcode.
1935 if (cmd->opcode == O_CHECK_STATE)
1941 retval = 0; /* accept */
1946 args->rule = f; /* report matching rule */
1947 retval = cmd->arg1 | IP_FW_PORT_DYNT_FLAG;
1952 if (args->eh) /* not on layer 2 */
1955 mtag = m_tag_get(PACKET_TAG_IPFW_DIVERT,
1956 sizeof(uint16_t), MB_DONTWAIT);
1958 retval = IP_FW_PORT_DENY_FLAG;
1961 *(uint16_t *)m_tag_data(mtag) = f->rulenum;
1962 m_tag_prepend(m, mtag);
1963 retval = (cmd->opcode == O_DIVERT) ?
1965 cmd->arg1 | IP_FW_PORT_TEE_FLAG;
1970 f->pcnt++; /* update stats */
1972 f->timestamp = time_second;
1973 if (cmd->opcode == O_COUNT)
1976 if (f->next_rule == NULL)
1977 lookup_next_rule(f);
1983 * Drop the packet and send a reject notice
1984 * if the packet is not ICMP (or is an ICMP
1985 * query), and it is not multicast/broadcast.
1988 (proto != IPPROTO_ICMP ||
1989 is_icmp_query(ip)) &&
1990 !(m->m_flags & (M_BCAST|M_MCAST)) &&
1991 !IN_MULTICAST(ntohl(dst_ip.s_addr))) {
1992 send_reject(args, cmd->arg1,
1998 retval = IP_FW_PORT_DENY_FLAG;
2002 if (args->eh) /* not valid on layer2 pkts */
2004 if (!q || dyn_dir == MATCH_FORWARD) {
2006 &((ipfw_insn_sa *)cmd)->sa;
2012 panic("-- unknown opcode %d\n", cmd->opcode);
2013 } /* end of switch() on opcodes */
2015 if (cmd->len & F_NOT)
2019 if (cmd->len & F_OR)
2022 if (!(cmd->len & F_OR)) /* not an OR block, */
2023 break; /* try next rule */
2026 } /* end of inner for, scan opcodes */
2028 next_rule:; /* try next rule */
2030 } /* end of outer for, scan rules */
2031 kprintf("+++ ipfw: ouch!, skip past end of rules, denying packet\n");
2032 return(IP_FW_PORT_DENY_FLAG);
2035 /* Update statistics */
2038 f->timestamp = time_second;
2043 kprintf("pullup failed\n");
2044 return(IP_FW_PORT_DENY_FLAG);
2048 ipfw_dummynet_io(struct mbuf *m, int pipe_nr, int dir, struct ip_fw_args *fwa)
2053 const struct ipfw_flow_id *id;
2054 struct dn_flow_id *fid;
2058 mtag = m_tag_get(PACKET_TAG_DUMMYNET, sizeof(*pkt), MB_DONTWAIT);
2063 m_tag_prepend(m, mtag);
2065 pkt = m_tag_data(mtag);
2066 bzero(pkt, sizeof(*pkt));
2068 cmd = fwa->rule->cmd + fwa->rule->act_ofs;
2069 if (cmd->opcode == O_LOG)
2071 KASSERT(cmd->opcode == O_PIPE || cmd->opcode == O_QUEUE,
2072 ("Rule is not PIPE or QUEUE, opcode %d\n", cmd->opcode));
2075 pkt->dn_flags = (dir & DN_FLAGS_DIR_MASK);
2076 pkt->ifp = fwa->oif;
2077 pkt->cpuid = mycpu->gd_cpuid;
2078 pkt->pipe_nr = pipe_nr;
2082 fid->fid_dst_ip = id->dst_ip;
2083 fid->fid_src_ip = id->src_ip;
2084 fid->fid_dst_port = id->dst_port;
2085 fid->fid_src_port = id->src_port;
2086 fid->fid_proto = id->proto;
2087 fid->fid_flags = id->flags;
2089 ipfw_ref_rule(fwa->rule);
2090 pkt->dn_priv = fwa->rule;
2091 pkt->dn_unref_priv = ipfw_unref_rule;
2093 if (cmd->opcode == O_PIPE)
2094 pkt->dn_flags |= DN_FLAGS_IS_PIPE;
2096 if (dir == DN_TO_IP_OUT) {
2098 * We need to copy *ro because for ICMP pkts (and maybe
2099 * others) the caller passed a pointer into the stack;
2100 * dst might also be a pointer into *ro so it needs to
2103 pkt->ro = *(fwa->ro);
2105 fwa->ro->ro_rt->rt_refcnt++;
2106 if (fwa->dst == (struct sockaddr_in *)&fwa->ro->ro_dst) {
2107 /* 'dst' points into 'ro' */
2108 fwa->dst = (struct sockaddr_in *)&(pkt->ro.ro_dst);
2110 pkt->dn_dst = fwa->dst;
2111 pkt->flags = fwa->flags;
2114 m->m_pkthdr.fw_flags |= DUMMYNET_MBUF_TAGGED;
2119 * When a rule is added/deleted, clear the next_rule pointers in all rules.
2120 * These will be reconstructed on the fly as packets are matched.
2121 * Must be called at splimp().
2124 flush_rule_ptrs(void)
2128 for (rule = layer3_chain; rule; rule = rule->next)
2129 rule->next_rule = NULL;
2132 static __inline void
2133 ipfw_inc_static_count(struct ip_fw *rule)
2136 static_ioc_len += IOC_RULESIZE(rule);
2139 static __inline void
2140 ipfw_dec_static_count(struct ip_fw *rule)
2142 int l = IOC_RULESIZE(rule);
2144 KASSERT(static_count > 0, ("invalid static count %u\n", static_count));
2147 KASSERT(static_ioc_len >= l,
2148 ("invalid static len %u\n", static_ioc_len));
2149 static_ioc_len -= l;
2152 static struct ip_fw *
2153 ipfw_create_rule(const struct ipfw_ioc_rule *ioc_rule)
2157 rule = kmalloc(RULESIZE(ioc_rule), M_IPFW, M_WAITOK | M_ZERO);
2159 rule->act_ofs = ioc_rule->act_ofs;
2160 rule->cmd_len = ioc_rule->cmd_len;
2161 rule->rulenum = ioc_rule->rulenum;
2162 rule->set = ioc_rule->set;
2163 rule->usr_flags = ioc_rule->usr_flags;
2165 bcopy(ioc_rule->cmd, rule->cmd, rule->cmd_len * 4 /* XXX */);
2173 * Add a new rule to the list. Copy the rule into a malloc'ed area, then
2174 * possibly create a rule number and add the rule to the list.
2175 * Update the rule_number in the input struct so the caller knows it as well.
2178 ipfw_add_rule(struct ip_fw **head, struct ipfw_ioc_rule *ioc_rule)
2180 struct ip_fw *rule, *f, *prev;
2182 KKASSERT(*head != NULL);
2184 rule = ipfw_create_rule(ioc_rule);
2189 * If rulenum is 0, find highest numbered rule before the
2190 * default rule, and add autoinc_step
2192 if (autoinc_step < 1)
2194 else if (autoinc_step > 1000)
2195 autoinc_step = 1000;
2196 if (rule->rulenum == 0) {
2198 * locate the highest numbered rule before default
2200 for (f = *head; f; f = f->next) {
2201 if (f->rulenum == IPFW_DEFAULT_RULE)
2203 rule->rulenum = f->rulenum;
2205 if (rule->rulenum < IPFW_DEFAULT_RULE - autoinc_step)
2206 rule->rulenum += autoinc_step;
2207 ioc_rule->rulenum = rule->rulenum;
2211 * Now insert the new rule in the right place in the sorted list.
2213 for (prev = NULL, f = *head; f; prev = f, f = f->next) {
2214 if (f->rulenum > rule->rulenum) { /* found the location */
2218 } else { /* head insert */
2227 ipfw_inc_static_count(rule);
2231 DEB(kprintf("++ installed rule %d, static count now %d\n",
2232 rule->rulenum, static_count);)
2237 * Free storage associated with a static rule (including derived
2239 * The caller is in charge of clearing rule pointers to avoid
2240 * dangling pointers.
2241 * @return a pointer to the next entry.
2242 * Arguments are not checked, so they better be correct.
2243 * Must be called at splimp().
2245 static struct ip_fw *
2246 delete_rule(struct ip_fw **head, struct ip_fw *prev, struct ip_fw *rule)
2251 remove_dyn_rule(rule, NULL /* force removal */);
2256 ipfw_dec_static_count(rule);
2258 /* Mark the rule as invalid */
2259 rule->rule_flags |= IPFW_RULE_F_INVALID;
2260 rule->next_rule = NULL;
2262 /* Try to free this rule */
2263 ipfw_free_rule(rule);
2269 * Deletes all rules from a chain (including the default rule
2270 * if the second argument is set).
2271 * Must be called at splimp().
2274 free_chain(struct ip_fw **chain, int kill_default)
2278 flush_rule_ptrs(); /* more efficient to do outside the loop */
2280 while ((rule = *chain) != NULL &&
2281 (kill_default || rule->rulenum != IPFW_DEFAULT_RULE))
2282 delete_rule(chain, NULL, rule);
2284 KASSERT(dyn_count == 0, ("%u dyn rule remains\n", dyn_count));
2287 ip_fw_default_rule = NULL; /* Reset default rule */
2289 if (ipfw_dyn_v != NULL) {
2291 * Free dynamic rules(state) hash table
2293 kfree(ipfw_dyn_v, M_IPFW);
2297 KASSERT(static_count == 0,
2298 ("%u static rules remains\n", static_count));
2299 KASSERT(static_ioc_len == 0,
2300 ("%u bytes of static rules remains\n", static_ioc_len));
2302 KASSERT(static_count == 1,
2303 ("%u static rules remains\n", static_count));
2304 KASSERT(static_ioc_len == IOC_RULESIZE(ip_fw_default_rule),
2305 ("%u bytes of static rules remains, should be %u\n",
2306 static_ioc_len, IOC_RULESIZE(ip_fw_default_rule)));
2311 * Remove all rules with given number, and also do set manipulation.
2313 * The argument is an uint32_t. The low 16 bit are the rule or set number,
2314 * the next 8 bits are the new set, the top 8 bits are the command:
2316 * 0 delete rules with given number
2317 * 1 delete rules with given set number
2318 * 2 move rules with given number to new set
2319 * 3 move rules with given set number to new set
2320 * 4 swap sets with given numbers
2323 del_entry(struct ip_fw **chain, uint32_t arg)
2325 struct ip_fw *prev, *rule;
2327 uint8_t cmd, new_set;
2329 rulenum = arg & 0xffff;
2330 cmd = (arg >> 24) & 0xff;
2331 new_set = (arg >> 16) & 0xff;
2337 if (cmd == 0 || cmd == 2) {
2338 if (rulenum == IPFW_DEFAULT_RULE)
2346 case 0: /* delete rules with given number */
2348 * locate first rule to delete
2350 for (prev = NULL, rule = *chain;
2351 rule && rule->rulenum < rulenum;
2352 prev = rule, rule = rule->next)
2354 if (rule->rulenum != rulenum)
2357 crit_enter(); /* no access to rules while removing */
2359 * flush pointers outside the loop, then delete all matching
2360 * rules. prev remains the same throughout the cycle.
2363 while (rule && rule->rulenum == rulenum)
2364 rule = delete_rule(chain, prev, rule);
2368 case 1: /* delete all rules with given set number */
2371 for (prev = NULL, rule = *chain; rule;) {
2372 if (rule->set == rulenum) {
2373 rule = delete_rule(chain, prev, rule);
2382 case 2: /* move rules with given number to new set */
2384 for (rule = *chain; rule; rule = rule->next) {
2385 if (rule->rulenum == rulenum)
2386 rule->set = new_set;
2391 case 3: /* move rules with given set number to new set */
2393 for (rule = *chain; rule; rule = rule->next) {
2394 if (rule->set == rulenum)
2395 rule->set = new_set;
2400 case 4: /* swap two sets */
2402 for (rule = *chain; rule; rule = rule->next) {
2403 if (rule->set == rulenum)
2404 rule->set = new_set;
2405 else if (rule->set == new_set)
2406 rule->set = rulenum;
2415 * Clear counters for a specific rule.
2418 clear_counters(struct ip_fw *rule, int log_only)
2420 ipfw_insn_log *l = (ipfw_insn_log *)ACTION_PTR(rule);
2422 if (log_only == 0) {
2423 rule->bcnt = rule->pcnt = 0;
2424 rule->timestamp = 0;
2426 if (l->o.opcode == O_LOG)
2427 l->log_left = l->max_log;
2431 * Reset some or all counters on firewall rules.
2432 * @arg frwl is null to clear all entries, or contains a specific
2434 * @arg log_only is 1 if we only want to reset logs, zero otherwise.
2437 zero_entry(int rulenum, int log_only)
2445 for (rule = layer3_chain; rule; rule = rule->next)
2446 clear_counters(rule, log_only);
2448 msg = log_only ? "ipfw: All logging counts reset.\n"
2449 : "ipfw: Accounting cleared.\n";
2454 * We can have multiple rules with the same number, so we
2455 * need to clear them all.
2457 for (rule = layer3_chain; rule; rule = rule->next) {
2458 if (rule->rulenum == rulenum) {
2460 while (rule && rule->rulenum == rulenum) {
2461 clear_counters(rule, log_only);
2469 if (!cleared) /* we did not find any matching rules */
2471 msg = log_only ? "ipfw: Entry %d logging count reset.\n"
2472 : "ipfw: Entry %d cleared.\n";
2475 log(LOG_SECURITY | LOG_NOTICE, msg, rulenum);
2480 * Check validity of the structure before insert.
2481 * Fortunately rules are simple, so this mostly need to check rule sizes.
2484 ipfw_ctl_check_rule(struct ipfw_ioc_rule *rule, int size)
2487 int have_action = 0;
2490 /* Check for valid size */
2491 if (size < sizeof(*rule)) {
2492 kprintf("ipfw: rule too short\n");
2495 l = IOC_RULESIZE(rule);
2497 kprintf("ipfw: size mismatch (have %d want %d)\n", size, l);
2502 * Now go for the individual checks. Very simple ones, basically only
2503 * instruction sizes.
2505 for (l = rule->cmd_len, cmd = rule->cmd; l > 0;
2506 l -= cmdlen, cmd += cmdlen) {
2507 cmdlen = F_LEN(cmd);
2509 kprintf("ipfw: opcode %d size truncated\n",
2513 DEB(kprintf("ipfw: opcode %d\n", cmd->opcode);)
2514 switch (cmd->opcode) {
2528 case O_IPPRECEDENCE:
2535 if (cmdlen != F_INSN_SIZE(ipfw_insn))
2547 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32))
2552 if (cmdlen != F_INSN_SIZE(ipfw_insn_limit))
2557 if (cmdlen != F_INSN_SIZE(ipfw_insn_log))
2560 ((ipfw_insn_log *)cmd)->log_left =
2561 ((ipfw_insn_log *)cmd)->max_log;
2567 if (cmdlen != F_INSN_SIZE(ipfw_insn_ip))
2569 if (((ipfw_insn_ip *)cmd)->mask.s_addr == 0) {
2570 kprintf("ipfw: opcode %d, useless rule\n",
2578 if (cmd->arg1 == 0 || cmd->arg1 > 256) {
2579 kprintf("ipfw: invalid set size %d\n",
2583 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
2589 if (cmdlen != F_INSN_SIZE(ipfw_insn_mac))
2595 case O_IP_DSTPORT: /* XXX artificial limit, 30 port pairs */
2596 if (cmdlen < 2 || cmdlen > 31)
2603 if (cmdlen != F_INSN_SIZE(ipfw_insn_if))
2609 if (cmdlen != F_INSN_SIZE(ipfw_insn_pipe))
2614 if (cmdlen != F_INSN_SIZE(ipfw_insn_sa))
2618 case O_FORWARD_MAC: /* XXX not implemented yet */
2627 if (cmdlen != F_INSN_SIZE(ipfw_insn))
2631 kprintf("ipfw: opcode %d, multiple actions"
2638 kprintf("ipfw: opcode %d, action must be"
2645 kprintf("ipfw: opcode %d, unknown opcode\n",
2650 if (have_action == 0) {
2651 kprintf("ipfw: missing action\n");
2657 kprintf("ipfw: opcode %d size %d wrong\n",
2658 cmd->opcode, cmdlen);
2663 ipfw_ctl_add_rule(struct sockopt *sopt)
2665 struct ipfw_ioc_rule *ioc_rule;
2669 size = sopt->sopt_valsize;
2670 if (size > (sizeof(uint32_t) * IPFW_RULE_SIZE_MAX) ||
2671 size < sizeof(*ioc_rule)) {
2674 if (size != (sizeof(uint32_t) * IPFW_RULE_SIZE_MAX)) {
2675 sopt->sopt_val = krealloc(sopt->sopt_val, sizeof(uint32_t) *
2676 IPFW_RULE_SIZE_MAX, M_TEMP, M_WAITOK);
2678 ioc_rule = sopt->sopt_val;
2680 error = ipfw_ctl_check_rule(ioc_rule, size);
2684 error = ipfw_add_rule(&layer3_chain, ioc_rule);
2688 if (sopt->sopt_dir == SOPT_GET)
2689 sopt->sopt_valsize = IOC_RULESIZE(ioc_rule);
2694 ipfw_copy_rule(const struct ip_fw *rule, struct ipfw_ioc_rule *ioc_rule)
2696 ioc_rule->act_ofs = rule->act_ofs;
2697 ioc_rule->cmd_len = rule->cmd_len;
2698 ioc_rule->rulenum = rule->rulenum;
2699 ioc_rule->set = rule->set;
2700 ioc_rule->usr_flags = rule->usr_flags;
2702 ioc_rule->set_disable = set_disable;
2703 ioc_rule->static_count = static_count;
2704 ioc_rule->static_len = static_ioc_len;
2706 ioc_rule->pcnt = rule->pcnt;
2707 ioc_rule->bcnt = rule->bcnt;
2708 ioc_rule->timestamp = rule->timestamp;
2710 bcopy(rule->cmd, ioc_rule->cmd, ioc_rule->cmd_len * 4 /* XXX */);
2712 return ((uint8_t *)ioc_rule + IOC_RULESIZE(ioc_rule));
2716 ipfw_copy_state(const ipfw_dyn_rule *dyn_rule,
2717 struct ipfw_ioc_state *ioc_state)
2719 const struct ipfw_flow_id *id;
2720 struct ipfw_ioc_flowid *ioc_id;
2722 ioc_state->expire = TIME_LEQ(dyn_rule->expire, time_second) ?
2723 0 : dyn_rule->expire - time_second;
2724 ioc_state->pcnt = dyn_rule->pcnt;
2725 ioc_state->bcnt = dyn_rule->bcnt;
2727 ioc_state->dyn_type = dyn_rule->dyn_type;
2728 ioc_state->count = dyn_rule->count;
2730 ioc_state->rulenum = dyn_rule->rule->rulenum;
2733 ioc_id = &ioc_state->id;
2735 ioc_id->type = ETHERTYPE_IP;
2736 ioc_id->u.ip.dst_ip = id->dst_ip;
2737 ioc_id->u.ip.src_ip = id->src_ip;
2738 ioc_id->u.ip.dst_port = id->dst_port;
2739 ioc_id->u.ip.src_port = id->src_port;
2740 ioc_id->u.ip.proto = id->proto;
2744 ipfw_ctl_get_rules(struct sockopt *sopt)
2751 * pass up a copy of the current rules. Static rules
2752 * come first (the last of which has number IPFW_DEFAULT_RULE),
2753 * followed by a possibly empty list of dynamic rule.
2757 size = static_ioc_len; /* size of static rules */
2758 if (ipfw_dyn_v) /* add size of dyn.rules */
2759 size += (dyn_count * sizeof(struct ipfw_ioc_state));
2761 if (sopt->sopt_valsize < size) {
2762 /* short length, no need to return incomplete rules */
2763 /* XXX: if superuser, no need to zero buffer */
2764 bzero(sopt->sopt_val, sopt->sopt_valsize);
2767 bp = sopt->sopt_val;
2769 for (rule = layer3_chain; rule; rule = rule->next)
2770 bp = ipfw_copy_rule(rule, bp);
2773 struct ipfw_ioc_state *ioc_state;
2777 for (i = 0; i < curr_dyn_buckets; i++) {
2780 for (p = ipfw_dyn_v[i]; p != NULL;
2781 p = p->next, ioc_state++)
2782 ipfw_copy_state(p, ioc_state);
2788 sopt->sopt_valsize = size;
2793 * {set|get}sockopt parser.
2796 ipfw_ctl(struct sockopt *sopt)
2804 switch (sopt->sopt_name) {
2806 error = ipfw_ctl_get_rules(sopt);
2811 * Normally we cannot release the lock on each iteration.
2812 * We could do it here only because we start from the head all
2813 * the times so there is no risk of missing some entries.
2814 * On the other hand, the risk is that we end up with
2815 * a very inconsistent ruleset, so better keep the lock
2816 * around the whole cycle.
2818 * XXX this code can be improved by resetting the head of
2819 * the list to point to the default rule, and then freeing
2820 * the old list without the need for a lock.
2824 free_chain(&layer3_chain, 0 /* keep default rule */);
2829 error = ipfw_ctl_add_rule(sopt);
2834 * IP_FW_DEL is used for deleting single rules or sets,
2835 * and (ab)used to atomically manipulate sets. Argument size
2836 * is used to distinguish between the two:
2838 * delete single rule or set of rules,
2839 * or reassign rules (or sets) to a different set.
2840 * 2*sizeof(uint32_t)
2841 * atomic disable/enable sets.
2842 * first uint32_t contains sets to be disabled,
2843 * second uint32_t contains sets to be enabled.
2845 masks = sopt->sopt_val;
2846 size = sopt->sopt_valsize;
2847 if (size == sizeof(*masks)) {
2849 * Delete or reassign static rule
2851 error = del_entry(&layer3_chain, masks[0]);
2852 } else if (size == (2 * sizeof(*masks))) {
2854 * Set enable/disable
2859 (set_disable | masks[0]) & ~masks[1] &
2860 ~(1 << 31); /* set 31 always enabled */
2869 case IP_FW_RESETLOG: /* argument is an int, the rule number */
2872 if (sopt->sopt_val != 0) {
2873 error = soopt_to_kbuf(sopt, &rulenum,
2874 sizeof(int), sizeof(int));
2878 error = zero_entry(rulenum, sopt->sopt_name == IP_FW_RESETLOG);
2882 kprintf("ipfw_ctl invalid option %d\n", sopt->sopt_name);
2889 * This procedure is only used to handle keepalives. It is invoked
2890 * every dyn_keepalive_period
2893 ipfw_tick(void *unused __unused)
2898 if (dyn_keepalive == 0 || ipfw_dyn_v == NULL || dyn_count == 0)
2902 for (i = 0; i < curr_dyn_buckets; i++) {
2903 for (q = ipfw_dyn_v[i]; q; q = q->next) {
2904 if (q->dyn_type == O_LIMIT_PARENT)
2906 if (q->id.proto != IPPROTO_TCP)
2908 if ((q->state & BOTH_SYN) != BOTH_SYN)
2910 if (TIME_LEQ(time_second + dyn_keepalive_interval,
2912 continue; /* too early */
2913 if (TIME_LEQ(q->expire, time_second))
2914 continue; /* too late, rule expired */
2916 send_pkt(&q->id, q->ack_rev - 1, q->ack_fwd, TH_SYN);
2917 send_pkt(&q->id, q->ack_fwd - 1, q->ack_rev, 0);
2922 callout_reset(&ipfw_timeout_h, dyn_keepalive_period * hz,
2927 ipfw_init_default_rule(struct ip_fw **head)
2929 struct ip_fw *def_rule;
2931 KKASSERT(*head == NULL);
2933 def_rule = kmalloc(sizeof(*def_rule), M_IPFW, M_WAITOK | M_ZERO);
2935 def_rule->act_ofs = 0;
2936 def_rule->rulenum = IPFW_DEFAULT_RULE;
2937 def_rule->cmd_len = 1;
2940 def_rule->cmd[0].len = 1;
2941 #ifdef IPFIREWALL_DEFAULT_TO_ACCEPT
2942 def_rule->cmd[0].opcode = O_ACCEPT;
2944 def_rule->cmd[0].opcode = O_DENY;
2947 def_rule->refcnt = 1;
2950 ipfw_inc_static_count(def_rule);
2952 /* Install the default rule */
2953 ip_fw_default_rule = def_rule;
2957 ipfw_init_dispatch(struct netmsg *nmsg)
2964 kprintf("IP firewall already loaded\n");
2969 ip_fw_chk_ptr = ipfw_chk;
2970 ip_fw_ctl_ptr = ipfw_ctl;
2971 ip_fw_dn_io_ptr = ipfw_dummynet_io;
2973 layer3_chain = NULL;
2974 ipfw_init_default_rule(&layer3_chain);
2976 kprintf("ipfw2 initialized, divert %s, "
2977 "rule-based forwarding enabled, default to %s, logging ",
2983 ip_fw_default_rule->cmd[0].opcode == O_ACCEPT ?
2986 #ifdef IPFIREWALL_VERBOSE
2989 #ifdef IPFIREWALL_VERBOSE_LIMIT
2990 verbose_limit = IPFIREWALL_VERBOSE_LIMIT;
2992 if (fw_verbose == 0) {
2993 kprintf("disabled\n");
2994 } else if (verbose_limit == 0) {
2995 kprintf("unlimited\n");
2997 kprintf("limited to %d packets/entry by default\n",
3000 callout_init(&ipfw_timeout_h);
3003 callout_reset(&ipfw_timeout_h, hz, ipfw_tick, NULL);
3006 lwkt_replymsg(&nmsg->nm_lmsg, error);
3014 netmsg_init(&smsg, &curthread->td_msgport, 0, ipfw_init_dispatch);
3015 return lwkt_domsg(cpu_portfn(0), &smsg.nm_lmsg, 0);
3021 ipfw_fini_dispatch(struct netmsg *nmsg)
3027 if (ipfw_refcnt != 0) {
3032 callout_stop(&ipfw_timeout_h);
3035 netmsg_service_sync();
3037 ip_fw_chk_ptr = NULL;
3038 ip_fw_ctl_ptr = NULL;
3039 ip_fw_dn_io_ptr = NULL;
3040 free_chain(&layer3_chain, 1 /* kill default rule */);
3042 kprintf("IP firewall unloaded\n");
3045 lwkt_replymsg(&nmsg->nm_lmsg, error);
3053 netmsg_init(&smsg, &curthread->td_msgport, 0, ipfw_fini_dispatch);
3054 return lwkt_domsg(cpu_portfn(0), &smsg.nm_lmsg, 0);
3057 #endif /* KLD_MODULE */
3060 ipfw_modevent(module_t mod, int type, void *unused)
3071 kprintf("ipfw statically compiled, cannot unload\n");
3083 static moduledata_t ipfwmod = {
3088 DECLARE_MODULE(ipfw, ipfwmod, SI_SUB_PROTO_END, SI_ORDER_ANY);
3089 MODULE_VERSION(ipfw, 1);