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.78 2008/08/27 14:00:45 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>
62 #include <net/route.h>
63 #include <net/netmsg2.h>
65 #include <netinet/in.h>
66 #include <netinet/in_systm.h>
67 #include <netinet/in_var.h>
68 #include <netinet/in_pcb.h>
69 #include <netinet/ip.h>
70 #include <netinet/ip_var.h>
71 #include <netinet/ip_icmp.h>
73 #include <net/dummynet/ip_dummynet.h>
74 #include <netinet/tcp.h>
75 #include <netinet/tcp_timer.h>
76 #include <netinet/tcp_var.h>
77 #include <netinet/tcpip.h>
78 #include <netinet/udp.h>
79 #include <netinet/udp_var.h>
80 #include <netinet/ip_divert.h>
82 #include <netinet/if_ether.h> /* XXX for ETHERTYPE_IP */
85 * Description about per-CPU rule duplication:
87 * Module loading/unloading and all ioctl operations are serialized
88 * by netisr0, so we don't have any ordering or locking problems.
90 * Following graph shows how operation on per-CPU rule list is
91 * performed [2 CPU case]:
95 * netisr0 <------------------------------------+
106 * forwardmsg---------->ifnet1 |
111 * replymsg--------------+
116 * Rules which will not create states (dyn rules) [2 CPU case]
119 * layer3_chain layer3_chain
122 * +-------+ sibling +-------+ sibling
123 * | rule1 |--------->| rule1 |--------->NULL
124 * +-------+ +-------+
128 * +-------+ sibling +-------+ sibling
129 * | rule2 |--------->| rule2 |--------->NULL
130 * +-------+ +-------+
133 * 1) Ease statistics calculation during IP_FW_GET. We only need to
134 * iterate layer3_chain on CPU0; the current rule's duplication on
135 * the other CPUs could safely be read-only accessed by using
137 * 2) Accelerate rule insertion and deletion, e.g. rule insertion:
138 * a) In netisr0 (on CPU0) rule3 is determined to be inserted between
139 * rule1 and rule2. To make this decision we need to iterate the
140 * layer3_chain on CPU0. The netmsg, which is used to insert the
141 * rule, will contain rule1 on CPU0 as prev_rule and rule2 on CPU0
143 * b) After the insertion on CPU0 is done, we will move on to CPU1.
144 * But instead of relocating the rule3's position on CPU1 by
145 * iterating the layer3_chain on CPU1, we set the netmsg's prev_rule
146 * to rule1->sibling and next_rule to rule2->sibling before the
147 * netmsg is forwarded to CPU1 from CPU0
151 * Rules which will create states (dyn rules) [2 CPU case]
152 * (unnecessary parts are omitted; they are same as in the previous figure)
156 * +-------+ +-------+
157 * | rule1 | | rule1 |
158 * +-------+ +-------+
165 * | +--------------------+ |
167 * | | (read-only shared) | |
169 * | | back pointer array | |
170 * | | (indexed by cpuid) | |
172 * +----|---------[0] | |
173 * | [1]--------|----+
175 * +--------------------+
178 * ........|............|............
182 * : +---------+ +---------+ :
183 * : | state1a | | state1b | .... :
184 * : +---------+ +---------+ :
188 * : (protected by dyn_lock) :
189 * ..................................
191 * [state1a and state1b are states created by rule1]
194 * This structure is introduced so that shared (locked) state table could
195 * work with per-CPU (duplicated) static rules. It mainly bridges states
196 * and static rules and serves as static rule's place holder (a read-only
197 * shared part of duplicated rules) from states point of view.
199 * IPFW_RULE_F_STATE (only for rules which create states):
200 * o During rule installation, this flag is turned on after rule's
201 * duplications reach all CPUs, to avoid at least following race:
202 * 1) rule1 is duplicated on CPU0 and is not duplicated on CPU1 yet
203 * 2) rule1 creates state1
204 * 3) state1 is located on CPU1 by check-state
205 * But rule1 is not duplicated on CPU1 yet
206 * o During rule deletion, this flag is turned off before deleting states
207 * created by the rule and before deleting the rule itself, so no
208 * more states will be created by the to-be-deleted rule even when its
209 * duplication on certain CPUs are not eliminated yet.
212 #define IPFW_AUTOINC_STEP_MIN 1
213 #define IPFW_AUTOINC_STEP_MAX 1000
214 #define IPFW_AUTOINC_STEP_DEF 100
216 #define IPFW_DEFAULT_RULE 65535 /* rulenum for the default rule */
217 #define IPFW_DEFAULT_SET 31 /* set number for the default rule */
221 const struct ipfw_ioc_rule *ioc_rule;
222 struct ip_fw *next_rule;
223 struct ip_fw *prev_rule;
224 struct ip_fw *sibling;
225 struct ip_fw_stub *stub;
230 struct ip_fw *start_rule;
231 struct ip_fw *prev_rule;
239 struct ip_fw *start_rule;
244 struct ipfw_context {
245 struct ip_fw *ipfw_layer3_chain; /* list of rules for layer3 */
246 struct ip_fw *ipfw_default_rule; /* default rule */
247 uint64_t ipfw_norule_counter; /* counter for ipfw_log(NULL) */
250 * ipfw_set_disable contains one bit per set value (0..31).
251 * If the bit is set, all rules with the corresponding set
252 * are disabled. Set IPDW_DEFAULT_SET is reserved for the
253 * default rule and CANNOT be disabled.
255 uint32_t ipfw_set_disable;
256 uint32_t ipfw_gen; /* generation of rule list */
259 static struct ipfw_context *ipfw_ctx[MAXCPU];
263 * Module can not be unloaded, if there are references to
264 * certains rules of ipfw(4), e.g. dummynet(4)
266 static int ipfw_refcnt;
269 MALLOC_DEFINE(M_IPFW, "IpFw/IpAcct", "IpFw/IpAcct chain's");
272 * Following two global variables are accessed and
273 * updated only on CPU0
275 static uint32_t static_count; /* # of static rules */
276 static uint32_t static_ioc_len; /* bytes of static rules */
279 * If 1, then ipfw static rules are being flushed,
280 * ipfw_chk() will skip to the default rule.
282 static int ipfw_flushing;
284 static int fw_verbose;
285 static int verbose_limit;
287 static int fw_debug = 1;
288 static int autoinc_step = IPFW_AUTOINC_STEP_DEF;
290 static int ipfw_sysctl_autoinc_step(SYSCTL_HANDLER_ARGS);
291 static int ipfw_sysctl_dyn_buckets(SYSCTL_HANDLER_ARGS);
292 static int ipfw_sysctl_dyn_fin(SYSCTL_HANDLER_ARGS);
293 static int ipfw_sysctl_dyn_rst(SYSCTL_HANDLER_ARGS);
296 SYSCTL_NODE(_net_inet_ip, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall");
297 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, enable, CTLFLAG_RW,
298 &fw_enable, 0, "Enable ipfw");
299 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, autoinc_step, CTLTYPE_INT | CTLFLAG_RW,
300 &autoinc_step, 0, ipfw_sysctl_autoinc_step, "I",
301 "Rule number autincrement step");
302 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO,one_pass,CTLFLAG_RW,
304 "Only do a single pass through ipfw when using dummynet(4)");
305 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, debug, CTLFLAG_RW,
306 &fw_debug, 0, "Enable printing of debug ip_fw statements");
307 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose, CTLFLAG_RW,
308 &fw_verbose, 0, "Log matches to ipfw rules");
309 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose_limit, CTLFLAG_RW,
310 &verbose_limit, 0, "Set upper limit of matches of ipfw rules logged");
313 * Description of dynamic rules.
315 * Dynamic rules are stored in lists accessed through a hash table
316 * (ipfw_dyn_v) whose size is curr_dyn_buckets. This value can
317 * be modified through the sysctl variable dyn_buckets which is
318 * updated when the table becomes empty.
320 * XXX currently there is only one list, ipfw_dyn.
322 * When a packet is received, its address fields are first masked
323 * with the mask defined for the rule, then hashed, then matched
324 * against the entries in the corresponding list.
325 * Dynamic rules can be used for different purposes:
327 * + enforcing limits on the number of sessions;
328 * + in-kernel NAT (not implemented yet)
330 * The lifetime of dynamic rules is regulated by dyn_*_lifetime,
331 * measured in seconds and depending on the flags.
333 * The total number of dynamic rules is stored in dyn_count.
334 * The max number of dynamic rules is dyn_max. When we reach
335 * the maximum number of rules we do not create anymore. This is
336 * done to avoid consuming too much memory, but also too much
337 * time when searching on each packet (ideally, we should try instead
338 * to put a limit on the length of the list on each bucket...).
340 * Each dynamic rule holds a pointer to the parent ipfw rule so
341 * we know what action to perform. Dynamic rules are removed when
342 * the parent rule is deleted. XXX we should make them survive.
344 * There are some limitations with dynamic rules -- we do not
345 * obey the 'randomized match', and we do not do multiple
346 * passes through the firewall. XXX check the latter!!!
348 * NOTE about the SHARED LOCKMGR LOCK during dynamic rule looking up:
349 * Only TCP state transition will change dynamic rule's state and ack
350 * sequences, while all packets of one TCP connection only goes through
351 * one TCP thread, so it is safe to use shared lockmgr lock during dynamic
352 * rule looking up. The keep alive callout uses exclusive lockmgr lock
353 * when it tries to find suitable dynamic rules to send keep alive, so
354 * it will not see half updated state and ack sequences. Though the expire
355 * field updating looks racy for other protocols, the resolution (second)
356 * of expire field makes this kind of race harmless.
357 * XXX statistics' updating is _not_ MPsafe!!!
358 * XXX once UDP output path is fixed, we could use lockless dynamic rule
361 static ipfw_dyn_rule **ipfw_dyn_v = NULL;
362 static uint32_t dyn_buckets = 256; /* must be power of 2 */
363 static uint32_t curr_dyn_buckets = 256; /* must be power of 2 */
364 static uint32_t dyn_buckets_gen; /* generation of dyn buckets array */
365 static struct lock dyn_lock; /* dynamic rules' hash table lock */
366 static struct callout ipfw_timeout_h;
369 * Timeouts for various events in handing dynamic rules.
371 static uint32_t dyn_ack_lifetime = 300;
372 static uint32_t dyn_syn_lifetime = 20;
373 static uint32_t dyn_fin_lifetime = 1;
374 static uint32_t dyn_rst_lifetime = 1;
375 static uint32_t dyn_udp_lifetime = 10;
376 static uint32_t dyn_short_lifetime = 5;
379 * Keepalives are sent if dyn_keepalive is set. They are sent every
380 * dyn_keepalive_period seconds, in the last dyn_keepalive_interval
381 * seconds of lifetime of a rule.
382 * dyn_rst_lifetime and dyn_fin_lifetime should be strictly lower
383 * than dyn_keepalive_period.
386 static uint32_t dyn_keepalive_interval = 20;
387 static uint32_t dyn_keepalive_period = 5;
388 static uint32_t dyn_keepalive = 1; /* do send keepalives */
390 static uint32_t dyn_count; /* # of dynamic rules */
391 static uint32_t dyn_max = 4096; /* max # of dynamic rules */
393 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, dyn_buckets, CTLTYPE_INT | CTLFLAG_RW,
394 &dyn_buckets, 0, ipfw_sysctl_dyn_buckets, "I", "Number of dyn. buckets");
395 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, curr_dyn_buckets, CTLFLAG_RD,
396 &curr_dyn_buckets, 0, "Current Number of dyn. buckets");
397 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_count, CTLFLAG_RD,
398 &dyn_count, 0, "Number of dyn. rules");
399 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_max, CTLFLAG_RW,
400 &dyn_max, 0, "Max number of dyn. rules");
401 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, static_count, CTLFLAG_RD,
402 &static_count, 0, "Number of static rules");
403 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_ack_lifetime, CTLFLAG_RW,
404 &dyn_ack_lifetime, 0, "Lifetime of dyn. rules for acks");
405 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_syn_lifetime, CTLFLAG_RW,
406 &dyn_syn_lifetime, 0, "Lifetime of dyn. rules for syn");
407 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, dyn_fin_lifetime,
408 CTLTYPE_INT | CTLFLAG_RW, &dyn_fin_lifetime, 0, ipfw_sysctl_dyn_fin, "I",
409 "Lifetime of dyn. rules for fin");
410 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, dyn_rst_lifetime,
411 CTLTYPE_INT | CTLFLAG_RW, &dyn_rst_lifetime, 0, ipfw_sysctl_dyn_rst, "I",
412 "Lifetime of dyn. rules for rst");
413 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_udp_lifetime, CTLFLAG_RW,
414 &dyn_udp_lifetime, 0, "Lifetime of dyn. rules for UDP");
415 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_short_lifetime, CTLFLAG_RW,
416 &dyn_short_lifetime, 0, "Lifetime of dyn. rules for other situations");
417 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_keepalive, CTLFLAG_RW,
418 &dyn_keepalive, 0, "Enable keepalives for dyn. rules");
420 #endif /* SYSCTL_NODE */
422 static ip_fw_chk_t ipfw_chk;
425 ipfw_free_rule(struct ip_fw *rule)
427 KASSERT(rule->cpuid == mycpuid, ("rule freed on cpu%d\n", mycpuid));
428 KASSERT(rule->refcnt > 0, ("invalid refcnt %u\n", rule->refcnt));
430 if (rule->refcnt == 0) {
438 ipfw_unref_rule(void *priv)
440 ipfw_free_rule(priv);
442 atomic_subtract_int(&ipfw_refcnt, 1);
447 ipfw_ref_rule(struct ip_fw *rule)
449 KASSERT(rule->cpuid == mycpuid, ("rule used on cpu%d\n", mycpuid));
451 atomic_add_int(&ipfw_refcnt, 1);
457 * This macro maps an ip pointer into a layer3 header pointer of type T
459 #define L3HDR(T, ip) ((T *)((uint32_t *)(ip) + (ip)->ip_hl))
462 icmptype_match(struct ip *ip, ipfw_insn_u32 *cmd)
464 int type = L3HDR(struct icmp,ip)->icmp_type;
466 return (type <= ICMP_MAXTYPE && (cmd->d[0] & (1 << type)));
469 #define TT ((1 << ICMP_ECHO) | \
470 (1 << ICMP_ROUTERSOLICIT) | \
471 (1 << ICMP_TSTAMP) | \
476 is_icmp_query(struct ip *ip)
478 int type = L3HDR(struct icmp, ip)->icmp_type;
480 return (type <= ICMP_MAXTYPE && (TT & (1 << type)));
486 * The following checks use two arrays of 8 or 16 bits to store the
487 * bits that we want set or clear, respectively. They are in the
488 * low and high half of cmd->arg1 or cmd->d[0].
490 * We scan options and store the bits we find set. We succeed if
492 * (want_set & ~bits) == 0 && (want_clear & ~bits) == want_clear
494 * The code is sometimes optimized not to store additional variables.
498 flags_match(ipfw_insn *cmd, uint8_t bits)
503 if (((cmd->arg1 & 0xff) & bits) != 0)
504 return 0; /* some bits we want set were clear */
506 want_clear = (cmd->arg1 >> 8) & 0xff;
507 if ((want_clear & bits) != want_clear)
508 return 0; /* some bits we want clear were set */
513 ipopts_match(struct ip *ip, ipfw_insn *cmd)
515 int optlen, bits = 0;
516 u_char *cp = (u_char *)(ip + 1);
517 int x = (ip->ip_hl << 2) - sizeof(struct ip);
519 for (; x > 0; x -= optlen, cp += optlen) {
520 int opt = cp[IPOPT_OPTVAL];
522 if (opt == IPOPT_EOL)
525 if (opt == IPOPT_NOP) {
528 optlen = cp[IPOPT_OLEN];
529 if (optlen <= 0 || optlen > x)
530 return 0; /* invalid or truncated */
535 bits |= IP_FW_IPOPT_LSRR;
539 bits |= IP_FW_IPOPT_SSRR;
543 bits |= IP_FW_IPOPT_RR;
547 bits |= IP_FW_IPOPT_TS;
554 return (flags_match(cmd, bits));
558 tcpopts_match(struct ip *ip, ipfw_insn *cmd)
560 int optlen, bits = 0;
561 struct tcphdr *tcp = L3HDR(struct tcphdr,ip);
562 u_char *cp = (u_char *)(tcp + 1);
563 int x = (tcp->th_off << 2) - sizeof(struct tcphdr);
565 for (; x > 0; x -= optlen, cp += optlen) {
568 if (opt == TCPOPT_EOL)
571 if (opt == TCPOPT_NOP) {
581 bits |= IP_FW_TCPOPT_MSS;
585 bits |= IP_FW_TCPOPT_WINDOW;
588 case TCPOPT_SACK_PERMITTED:
590 bits |= IP_FW_TCPOPT_SACK;
593 case TCPOPT_TIMESTAMP:
594 bits |= IP_FW_TCPOPT_TS;
600 bits |= IP_FW_TCPOPT_CC;
607 return (flags_match(cmd, bits));
611 iface_match(struct ifnet *ifp, ipfw_insn_if *cmd)
613 if (ifp == NULL) /* no iface with this packet, match fails */
616 /* Check by name or by IP address */
617 if (cmd->name[0] != '\0') { /* match by name */
620 if (kfnmatch(cmd->name, ifp->if_xname, 0) == 0)
623 if (strncmp(ifp->if_xname, cmd->name, IFNAMSIZ) == 0)
627 struct ifaddr_container *ifac;
629 TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
630 struct ifaddr *ia = ifac->ifa;
632 if (ia->ifa_addr == NULL)
634 if (ia->ifa_addr->sa_family != AF_INET)
636 if (cmd->p.ip.s_addr == ((struct sockaddr_in *)
637 (ia->ifa_addr))->sin_addr.s_addr)
638 return(1); /* match */
641 return(0); /* no match, fail ... */
644 #define SNPARGS(buf, len) buf + len, sizeof(buf) > len ? sizeof(buf) - len : 0
647 * We enter here when we have a rule with O_LOG.
648 * XXX this function alone takes about 2Kbytes of code!
651 ipfw_log(struct ip_fw *f, u_int hlen, struct ether_header *eh,
652 struct mbuf *m, struct ifnet *oif)
655 int limit_reached = 0;
656 char action2[40], proto[48], fragment[28];
661 if (f == NULL) { /* bogus pkt */
662 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
664 if (verbose_limit != 0 &&
665 ctx->ipfw_norule_counter >= verbose_limit)
667 ctx->ipfw_norule_counter++;
668 if (ctx->ipfw_norule_counter == verbose_limit)
669 limit_reached = verbose_limit;
671 } else { /* O_LOG is the first action, find the real one */
672 ipfw_insn *cmd = ACTION_PTR(f);
673 ipfw_insn_log *l = (ipfw_insn_log *)cmd;
675 if (l->max_log != 0 && l->log_left == 0)
678 if (l->log_left == 0)
679 limit_reached = l->max_log;
680 cmd += F_LEN(cmd); /* point to first action */
681 if (cmd->opcode == O_PROB)
685 switch (cmd->opcode) {
691 if (cmd->arg1==ICMP_REJECT_RST) {
693 } else if (cmd->arg1==ICMP_UNREACH_HOST) {
696 ksnprintf(SNPARGS(action2, 0), "Unreach %d",
710 ksnprintf(SNPARGS(action2, 0), "Divert %d", cmd->arg1);
714 ksnprintf(SNPARGS(action2, 0), "Tee %d", cmd->arg1);
718 ksnprintf(SNPARGS(action2, 0), "SkipTo %d", cmd->arg1);
722 ksnprintf(SNPARGS(action2, 0), "Pipe %d", cmd->arg1);
726 ksnprintf(SNPARGS(action2, 0), "Queue %d", cmd->arg1);
731 ipfw_insn_sa *sa = (ipfw_insn_sa *)cmd;
734 len = ksnprintf(SNPARGS(action2, 0),
736 inet_ntoa(sa->sa.sin_addr));
737 if (sa->sa.sin_port) {
738 ksnprintf(SNPARGS(action2, len), ":%d",
750 if (hlen == 0) { /* non-ip */
751 ksnprintf(SNPARGS(proto, 0), "MAC");
753 struct ip *ip = mtod(m, struct ip *);
754 /* these three are all aliases to the same thing */
755 struct icmp *const icmp = L3HDR(struct icmp, ip);
756 struct tcphdr *const tcp = (struct tcphdr *)icmp;
757 struct udphdr *const udp = (struct udphdr *)icmp;
759 int ip_off, offset, ip_len;
762 if (eh != NULL) { /* layer 2 packets are as on the wire */
763 ip_off = ntohs(ip->ip_off);
764 ip_len = ntohs(ip->ip_len);
769 offset = ip_off & IP_OFFMASK;
772 len = ksnprintf(SNPARGS(proto, 0), "TCP %s",
773 inet_ntoa(ip->ip_src));
775 ksnprintf(SNPARGS(proto, len), ":%d %s:%d",
776 ntohs(tcp->th_sport),
777 inet_ntoa(ip->ip_dst),
778 ntohs(tcp->th_dport));
780 ksnprintf(SNPARGS(proto, len), " %s",
781 inet_ntoa(ip->ip_dst));
786 len = ksnprintf(SNPARGS(proto, 0), "UDP %s",
787 inet_ntoa(ip->ip_src));
789 ksnprintf(SNPARGS(proto, len), ":%d %s:%d",
790 ntohs(udp->uh_sport),
791 inet_ntoa(ip->ip_dst),
792 ntohs(udp->uh_dport));
794 ksnprintf(SNPARGS(proto, len), " %s",
795 inet_ntoa(ip->ip_dst));
801 len = ksnprintf(SNPARGS(proto, 0),
806 len = ksnprintf(SNPARGS(proto, 0), "ICMP ");
808 len += ksnprintf(SNPARGS(proto, len), "%s",
809 inet_ntoa(ip->ip_src));
810 ksnprintf(SNPARGS(proto, len), " %s",
811 inet_ntoa(ip->ip_dst));
815 len = ksnprintf(SNPARGS(proto, 0), "P:%d %s", ip->ip_p,
816 inet_ntoa(ip->ip_src));
817 ksnprintf(SNPARGS(proto, len), " %s",
818 inet_ntoa(ip->ip_dst));
822 if (ip_off & (IP_MF | IP_OFFMASK)) {
823 ksnprintf(SNPARGS(fragment, 0), " (frag %d:%d@%d%s)",
824 ntohs(ip->ip_id), ip_len - (ip->ip_hl << 2),
825 offset << 3, (ip_off & IP_MF) ? "+" : "");
829 if (oif || m->m_pkthdr.rcvif) {
830 log(LOG_SECURITY | LOG_INFO,
831 "ipfw: %d %s %s %s via %s%s\n",
833 action, proto, oif ? "out" : "in",
834 oif ? oif->if_xname : m->m_pkthdr.rcvif->if_xname,
837 log(LOG_SECURITY | LOG_INFO,
838 "ipfw: %d %s %s [no if info]%s\n",
840 action, proto, fragment);
844 log(LOG_SECURITY | LOG_NOTICE,
845 "ipfw: limit %d reached on entry %d\n",
846 limit_reached, f ? f->rulenum : -1);
853 * IMPORTANT: the hash function for dynamic rules must be commutative
854 * in source and destination (ip,port), because rules are bidirectional
855 * and we want to find both in the same bucket.
858 hash_packet(struct ipfw_flow_id *id)
862 i = (id->dst_ip) ^ (id->src_ip) ^ (id->dst_port) ^ (id->src_port);
863 i &= (curr_dyn_buckets - 1);
868 * unlink a dynamic rule from a chain. prev is a pointer to
869 * the previous one, q is a pointer to the rule to delete,
870 * head is a pointer to the head of the queue.
871 * Modifies q and potentially also head.
873 #define UNLINK_DYN_RULE(prev, head, q) \
875 ipfw_dyn_rule *old_q = q; \
877 /* remove a refcount to the parent */ \
878 if (q->dyn_type == O_LIMIT) \
879 q->parent->count--; \
880 DEB(kprintf("-- unlink entry 0x%08x %d -> 0x%08x %d, %d left\n", \
881 (q->id.src_ip), (q->id.src_port), \
882 (q->id.dst_ip), (q->id.dst_port), dyn_count-1 ); ) \
884 prev->next = q = q->next; \
886 head = q = q->next; \
887 KASSERT(dyn_count > 0, ("invalid dyn count %u\n", dyn_count)); \
889 kfree(old_q, M_IPFW); \
892 #define TIME_LEQ(a, b) ((int)((a) - (b)) <= 0)
895 * Remove dynamic rules pointing to "rule", or all of them if rule == NULL.
897 * If keep_me == NULL, rules are deleted even if not expired,
898 * otherwise only expired rules are removed.
900 * The value of the second parameter is also used to point to identify
901 * a rule we absolutely do not want to remove (e.g. because we are
902 * holding a reference to it -- this is the case with O_LIMIT_PARENT
903 * rules). The pointer is only used for comparison, so any non-null
907 remove_dyn_rule_locked(struct ip_fw *rule, ipfw_dyn_rule *keep_me)
909 static uint32_t last_remove = 0; /* XXX */
911 #define FORCE (keep_me == NULL)
913 ipfw_dyn_rule *prev, *q;
914 int i, pass = 0, max_pass = 0, unlinked = 0;
916 if (ipfw_dyn_v == NULL || dyn_count == 0)
918 /* do not expire more than once per second, it is useless */
919 if (!FORCE && last_remove == time_second)
921 last_remove = time_second;
924 * because O_LIMIT refer to parent rules, during the first pass only
925 * remove child and mark any pending LIMIT_PARENT, and remove
926 * them in a second pass.
929 for (i = 0; i < curr_dyn_buckets; i++) {
930 for (prev = NULL, q = ipfw_dyn_v[i]; q;) {
932 * Logic can become complex here, so we split tests.
936 if (rule != NULL && rule->stub != q->stub)
937 goto next; /* not the one we are looking for */
938 if (q->dyn_type == O_LIMIT_PARENT) {
940 * handle parent in the second pass,
941 * record we need one.
946 if (FORCE && q->count != 0) {
947 /* XXX should not happen! */
948 kprintf("OUCH! cannot remove rule, "
949 "count %d\n", q->count);
952 if (!FORCE && !TIME_LEQ(q->expire, time_second))
956 UNLINK_DYN_RULE(prev, ipfw_dyn_v[i], q);
963 if (pass++ < max_pass)
973 * lookup a dynamic rule.
975 static ipfw_dyn_rule *
976 lookup_dyn_rule(struct ipfw_flow_id *pkt, int *match_direction,
980 * stateful ipfw extensions.
981 * Lookup into dynamic session queue
983 #define MATCH_REVERSE 0
984 #define MATCH_FORWARD 1
986 #define MATCH_UNKNOWN 3
987 int i, dir = MATCH_NONE;
988 ipfw_dyn_rule *prev, *q=NULL;
990 if (ipfw_dyn_v == NULL)
991 goto done; /* not found */
993 i = hash_packet(pkt);
994 for (prev = NULL, q = ipfw_dyn_v[i]; q != NULL;) {
995 if (q->dyn_type == O_LIMIT_PARENT)
998 if (TIME_LEQ(q->expire, time_second)) {
1000 * Entry expired; skip.
1001 * Let ipfw_tick() take care of it
1006 if (pkt->proto == q->id.proto) {
1007 if (pkt->src_ip == q->id.src_ip &&
1008 pkt->dst_ip == q->id.dst_ip &&
1009 pkt->src_port == q->id.src_port &&
1010 pkt->dst_port == q->id.dst_port) {
1011 dir = MATCH_FORWARD;
1014 if (pkt->src_ip == q->id.dst_ip &&
1015 pkt->dst_ip == q->id.src_ip &&
1016 pkt->src_port == q->id.dst_port &&
1017 pkt->dst_port == q->id.src_port) {
1018 dir = MATCH_REVERSE;
1027 goto done; /* q = NULL, not found */
1029 if (pkt->proto == IPPROTO_TCP) { /* update state according to flags */
1030 u_char flags = pkt->flags & (TH_FIN|TH_SYN|TH_RST);
1032 #define BOTH_SYN (TH_SYN | (TH_SYN << 8))
1033 #define BOTH_FIN (TH_FIN | (TH_FIN << 8))
1035 q->state |= (dir == MATCH_FORWARD ) ? flags : (flags << 8);
1037 case TH_SYN: /* opening */
1038 q->expire = time_second + dyn_syn_lifetime;
1041 case BOTH_SYN: /* move to established */
1042 case BOTH_SYN | TH_FIN : /* one side tries to close */
1043 case BOTH_SYN | (TH_FIN << 8) :
1045 uint32_t ack = ntohl(tcp->th_ack);
1047 #define _SEQ_GE(a, b) ((int)(a) - (int)(b) >= 0)
1049 if (dir == MATCH_FORWARD) {
1050 if (q->ack_fwd == 0 ||
1051 _SEQ_GE(ack, q->ack_fwd))
1053 else /* ignore out-of-sequence */
1056 if (q->ack_rev == 0 ||
1057 _SEQ_GE(ack, q->ack_rev))
1059 else /* ignore out-of-sequence */
1064 q->expire = time_second + dyn_ack_lifetime;
1067 case BOTH_SYN | BOTH_FIN: /* both sides closed */
1068 KKASSERT(dyn_fin_lifetime < dyn_keepalive_period);
1069 q->expire = time_second + dyn_fin_lifetime;
1075 * reset or some invalid combination, but can also
1076 * occur if we use keep-state the wrong way.
1078 if ((q->state & ((TH_RST << 8) | TH_RST)) == 0)
1079 kprintf("invalid state: 0x%x\n", q->state);
1081 KKASSERT(dyn_rst_lifetime < dyn_keepalive_period);
1082 q->expire = time_second + dyn_rst_lifetime;
1085 } else if (pkt->proto == IPPROTO_UDP) {
1086 q->expire = time_second + dyn_udp_lifetime;
1088 /* other protocols */
1089 q->expire = time_second + dyn_short_lifetime;
1092 if (match_direction)
1093 *match_direction = dir;
1097 static struct ip_fw *
1098 lookup_rule(struct ipfw_flow_id *pkt, int *match_direction, struct tcphdr *tcp,
1099 uint16_t len, int *deny)
1101 struct ip_fw *rule = NULL;
1103 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
1107 gen = ctx->ipfw_gen;
1109 lockmgr(&dyn_lock, LK_SHARED);
1111 if (ctx->ipfw_gen != gen) {
1113 * Static rules had been change when we were waiting
1114 * for the dynamic hash table lock; deny this packet,
1115 * since it is _not_ known whether it is safe to keep
1116 * iterating the static rules.
1122 q = lookup_dyn_rule(pkt, match_direction, tcp);
1126 rule = q->stub->rule[mycpuid];
1127 KKASSERT(rule->stub == q->stub && rule->cpuid == mycpuid);
1134 lockmgr(&dyn_lock, LK_RELEASE);
1139 realloc_dynamic_table(void)
1141 ipfw_dyn_rule **old_dyn_v;
1142 uint32_t old_curr_dyn_buckets;
1144 KASSERT(dyn_buckets <= 65536 && (dyn_buckets & (dyn_buckets - 1)) == 0,
1145 ("invalid dyn_buckets %d\n", dyn_buckets));
1147 /* Save the current buckets array for later error recovery */
1148 old_dyn_v = ipfw_dyn_v;
1149 old_curr_dyn_buckets = curr_dyn_buckets;
1151 curr_dyn_buckets = dyn_buckets;
1153 ipfw_dyn_v = kmalloc(curr_dyn_buckets * sizeof(ipfw_dyn_rule *),
1154 M_IPFW, M_NOWAIT | M_ZERO);
1155 if (ipfw_dyn_v != NULL || curr_dyn_buckets <= 2)
1158 curr_dyn_buckets /= 2;
1159 if (curr_dyn_buckets <= old_curr_dyn_buckets &&
1160 old_dyn_v != NULL) {
1162 * Don't try allocating smaller buckets array, reuse
1163 * the old one, which alreay contains enough buckets
1169 if (ipfw_dyn_v != NULL) {
1170 if (old_dyn_v != NULL)
1171 kfree(old_dyn_v, M_IPFW);
1173 /* Allocation failed, restore old buckets array */
1174 ipfw_dyn_v = old_dyn_v;
1175 curr_dyn_buckets = old_curr_dyn_buckets;
1178 if (ipfw_dyn_v != NULL)
1183 * Install state of type 'type' for a dynamic session.
1184 * The hash table contains two type of rules:
1185 * - regular rules (O_KEEP_STATE)
1186 * - rules for sessions with limited number of sess per user
1187 * (O_LIMIT). When they are created, the parent is
1188 * increased by 1, and decreased on delete. In this case,
1189 * the third parameter is the parent rule and not the chain.
1190 * - "parent" rules for the above (O_LIMIT_PARENT).
1192 static ipfw_dyn_rule *
1193 add_dyn_rule(struct ipfw_flow_id *id, uint8_t dyn_type, struct ip_fw *rule)
1198 if (ipfw_dyn_v == NULL ||
1199 (dyn_count == 0 && dyn_buckets != curr_dyn_buckets)) {
1200 realloc_dynamic_table();
1201 if (ipfw_dyn_v == NULL)
1202 return NULL; /* failed ! */
1204 i = hash_packet(id);
1206 r = kmalloc(sizeof(*r), M_IPFW, M_NOWAIT | M_ZERO);
1208 kprintf ("sorry cannot allocate state\n");
1212 /* increase refcount on parent, and set pointer */
1213 if (dyn_type == O_LIMIT) {
1214 ipfw_dyn_rule *parent = (ipfw_dyn_rule *)rule;
1216 if (parent->dyn_type != O_LIMIT_PARENT)
1217 panic("invalid parent");
1220 rule = parent->stub->rule[mycpuid];
1221 KKASSERT(rule->stub == parent->stub);
1223 KKASSERT(rule->cpuid == mycpuid && rule->stub != NULL);
1226 r->expire = time_second + dyn_syn_lifetime;
1227 r->stub = rule->stub;
1228 r->dyn_type = dyn_type;
1229 r->pcnt = r->bcnt = 0;
1233 r->next = ipfw_dyn_v[i];
1237 DEB(kprintf("-- add dyn entry ty %d 0x%08x %d -> 0x%08x %d, total %d\n",
1239 (r->id.src_ip), (r->id.src_port),
1240 (r->id.dst_ip), (r->id.dst_port),
1246 * lookup dynamic parent rule using pkt and rule as search keys.
1247 * If the lookup fails, then install one.
1249 static ipfw_dyn_rule *
1250 lookup_dyn_parent(struct ipfw_flow_id *pkt, struct ip_fw *rule)
1256 i = hash_packet(pkt);
1257 for (q = ipfw_dyn_v[i]; q != NULL; q = q->next) {
1258 if (q->dyn_type == O_LIMIT_PARENT &&
1259 rule->stub == q->stub &&
1260 pkt->proto == q->id.proto &&
1261 pkt->src_ip == q->id.src_ip &&
1262 pkt->dst_ip == q->id.dst_ip &&
1263 pkt->src_port == q->id.src_port &&
1264 pkt->dst_port == q->id.dst_port) {
1265 q->expire = time_second + dyn_short_lifetime;
1266 DEB(kprintf("lookup_dyn_parent found 0x%p\n",q);)
1271 return add_dyn_rule(pkt, O_LIMIT_PARENT, rule);
1275 * Install dynamic state for rule type cmd->o.opcode
1277 * Returns 1 (failure) if state is not installed because of errors or because
1278 * session limitations are enforced.
1281 install_state_locked(struct ip_fw *rule, ipfw_insn_limit *cmd,
1282 struct ip_fw_args *args)
1284 static int last_log; /* XXX */
1288 DEB(kprintf("-- install state type %d 0x%08x %u -> 0x%08x %u\n",
1290 (args->f_id.src_ip), (args->f_id.src_port),
1291 (args->f_id.dst_ip), (args->f_id.dst_port) );)
1293 q = lookup_dyn_rule(&args->f_id, NULL, NULL);
1294 if (q != NULL) { /* should never occur */
1295 if (last_log != time_second) {
1296 last_log = time_second;
1297 kprintf(" install_state: entry already present, done\n");
1302 if (dyn_count >= dyn_max) {
1304 * Run out of slots, try to remove any expired rule.
1306 remove_dyn_rule_locked(NULL, (ipfw_dyn_rule *)1);
1307 if (dyn_count >= dyn_max) {
1308 if (last_log != time_second) {
1309 last_log = time_second;
1310 kprintf("install_state: "
1311 "Too many dynamic rules\n");
1313 return 1; /* cannot install, notify caller */
1317 switch (cmd->o.opcode) {
1318 case O_KEEP_STATE: /* bidir rule */
1319 if (add_dyn_rule(&args->f_id, O_KEEP_STATE, rule) == NULL)
1323 case O_LIMIT: /* limit number of sessions */
1325 uint16_t limit_mask = cmd->limit_mask;
1326 struct ipfw_flow_id id;
1327 ipfw_dyn_rule *parent;
1329 DEB(kprintf("installing dyn-limit rule %d\n",
1332 id.dst_ip = id.src_ip = 0;
1333 id.dst_port = id.src_port = 0;
1334 id.proto = args->f_id.proto;
1336 if (limit_mask & DYN_SRC_ADDR)
1337 id.src_ip = args->f_id.src_ip;
1338 if (limit_mask & DYN_DST_ADDR)
1339 id.dst_ip = args->f_id.dst_ip;
1340 if (limit_mask & DYN_SRC_PORT)
1341 id.src_port = args->f_id.src_port;
1342 if (limit_mask & DYN_DST_PORT)
1343 id.dst_port = args->f_id.dst_port;
1345 parent = lookup_dyn_parent(&id, rule);
1346 if (parent == NULL) {
1347 kprintf("add parent failed\n");
1351 if (parent->count >= cmd->conn_limit) {
1353 * See if we can remove some expired rule.
1355 remove_dyn_rule_locked(rule, parent);
1356 if (parent->count >= cmd->conn_limit) {
1358 last_log != time_second) {
1359 last_log = time_second;
1360 log(LOG_SECURITY | LOG_DEBUG,
1362 "too many entries\n");
1367 if (add_dyn_rule(&args->f_id, O_LIMIT,
1368 (struct ip_fw *)parent) == NULL)
1373 kprintf("unknown dynamic rule type %u\n", cmd->o.opcode);
1376 lookup_dyn_rule(&args->f_id, NULL, NULL); /* XXX just set lifetime */
1381 install_state(struct ip_fw *rule, ipfw_insn_limit *cmd,
1382 struct ip_fw_args *args, int *deny)
1384 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
1389 gen = ctx->ipfw_gen;
1391 lockmgr(&dyn_lock, LK_EXCLUSIVE);
1392 if (ctx->ipfw_gen != gen) {
1393 /* See the comment in lookup_rule() */
1396 ret = install_state_locked(rule, cmd, args);
1398 lockmgr(&dyn_lock, LK_RELEASE);
1404 * Transmit a TCP packet, containing either a RST or a keepalive.
1405 * When flags & TH_RST, we are sending a RST packet, because of a
1406 * "reset" action matched the packet.
1407 * Otherwise we are sending a keepalive, and flags & TH_
1410 send_pkt(struct ipfw_flow_id *id, uint32_t seq, uint32_t ack, int flags)
1415 struct route sro; /* fake route */
1417 MGETHDR(m, MB_DONTWAIT, MT_HEADER);
1420 m->m_pkthdr.rcvif = NULL;
1421 m->m_pkthdr.len = m->m_len = sizeof(struct ip) + sizeof(struct tcphdr);
1422 m->m_data += max_linkhdr;
1424 ip = mtod(m, struct ip *);
1425 bzero(ip, m->m_len);
1426 tcp = (struct tcphdr *)(ip + 1); /* no IP options */
1427 ip->ip_p = IPPROTO_TCP;
1431 * Assume we are sending a RST (or a keepalive in the reverse
1432 * direction), swap src and destination addresses and ports.
1434 ip->ip_src.s_addr = htonl(id->dst_ip);
1435 ip->ip_dst.s_addr = htonl(id->src_ip);
1436 tcp->th_sport = htons(id->dst_port);
1437 tcp->th_dport = htons(id->src_port);
1438 if (flags & TH_RST) { /* we are sending a RST */
1439 if (flags & TH_ACK) {
1440 tcp->th_seq = htonl(ack);
1441 tcp->th_ack = htonl(0);
1442 tcp->th_flags = TH_RST;
1446 tcp->th_seq = htonl(0);
1447 tcp->th_ack = htonl(seq);
1448 tcp->th_flags = TH_RST | TH_ACK;
1452 * We are sending a keepalive. flags & TH_SYN determines
1453 * the direction, forward if set, reverse if clear.
1454 * NOTE: seq and ack are always assumed to be correct
1455 * as set by the caller. This may be confusing...
1457 if (flags & TH_SYN) {
1459 * we have to rewrite the correct addresses!
1461 ip->ip_dst.s_addr = htonl(id->dst_ip);
1462 ip->ip_src.s_addr = htonl(id->src_ip);
1463 tcp->th_dport = htons(id->dst_port);
1464 tcp->th_sport = htons(id->src_port);
1466 tcp->th_seq = htonl(seq);
1467 tcp->th_ack = htonl(ack);
1468 tcp->th_flags = TH_ACK;
1472 * set ip_len to the payload size so we can compute
1473 * the tcp checksum on the pseudoheader
1474 * XXX check this, could save a couple of words ?
1476 ip->ip_len = htons(sizeof(struct tcphdr));
1477 tcp->th_sum = in_cksum(m, m->m_pkthdr.len);
1480 * now fill fields left out earlier
1482 ip->ip_ttl = ip_defttl;
1483 ip->ip_len = m->m_pkthdr.len;
1485 bzero(&sro, sizeof(sro));
1486 ip_rtaddr(ip->ip_dst, &sro);
1488 m->m_pkthdr.fw_flags |= IPFW_MBUF_GENERATED;
1489 ip_output(m, NULL, &sro, 0, NULL, NULL);
1495 * sends a reject message, consuming the mbuf passed as an argument.
1498 send_reject(struct ip_fw_args *args, int code, int offset, int ip_len)
1500 if (code != ICMP_REJECT_RST) { /* Send an ICMP unreach */
1501 /* We need the IP header in host order for icmp_error(). */
1502 if (args->eh != NULL) {
1503 struct ip *ip = mtod(args->m, struct ip *);
1505 ip->ip_len = ntohs(ip->ip_len);
1506 ip->ip_off = ntohs(ip->ip_off);
1508 icmp_error(args->m, ICMP_UNREACH, code, 0L, 0);
1509 } else if (offset == 0 && args->f_id.proto == IPPROTO_TCP) {
1510 struct tcphdr *const tcp =
1511 L3HDR(struct tcphdr, mtod(args->m, struct ip *));
1513 if ((tcp->th_flags & TH_RST) == 0) {
1514 send_pkt(&args->f_id, ntohl(tcp->th_seq),
1515 ntohl(tcp->th_ack), tcp->th_flags | TH_RST);
1526 * Given an ip_fw *, lookup_next_rule will return a pointer
1527 * to the next rule, which can be either the jump
1528 * target (for skipto instructions) or the next one in the list (in
1529 * all other cases including a missing jump target).
1530 * The result is also written in the "next_rule" field of the rule.
1531 * Backward jumps are not allowed, so start looking from the next
1534 * This never returns NULL -- in case we do not have an exact match,
1535 * the next rule is returned. When the ruleset is changed,
1536 * pointers are flushed so we are always correct.
1539 static struct ip_fw *
1540 lookup_next_rule(struct ip_fw *me)
1542 struct ip_fw *rule = NULL;
1545 /* look for action, in case it is a skipto */
1546 cmd = ACTION_PTR(me);
1547 if (cmd->opcode == O_LOG)
1549 if (cmd->opcode == O_SKIPTO) {
1550 for (rule = me->next; rule; rule = rule->next) {
1551 if (rule->rulenum >= cmd->arg1)
1555 if (rule == NULL) /* failure or not a skipto */
1557 me->next_rule = rule;
1562 * The main check routine for the firewall.
1564 * All arguments are in args so we can modify them and return them
1565 * back to the caller.
1569 * args->m (in/out) The packet; we set to NULL when/if we nuke it.
1570 * Starts with the IP header.
1571 * args->eh (in) Mac header if present, or NULL for layer3 packet.
1572 * args->oif Outgoing interface, or NULL if packet is incoming.
1573 * The incoming interface is in the mbuf. (in)
1575 * args->rule Pointer to the last matching rule (in/out)
1576 * args->f_id Addresses grabbed from the packet (out)
1580 * IP_FW_PORT_DENY_FLAG the packet must be dropped.
1581 * 0 The packet is to be accepted and routed normally OR
1582 * the packet was denied/rejected and has been dropped;
1583 * in the latter case, *m is equal to NULL upon return.
1584 * port Divert the packet to port, with these caveats:
1586 * - If IP_FW_PORT_TEE_FLAG is set, tee the packet instead
1587 * of diverting it (ie, 'ipfw tee').
1589 * - If IP_FW_PORT_DYNT_FLAG is set, interpret the lower
1590 * 16 bits as a dummynet pipe number instead of diverting
1594 ipfw_chk(struct ip_fw_args *args)
1597 * Local variables hold state during the processing of a packet.
1599 * IMPORTANT NOTE: to speed up the processing of rules, there
1600 * are some assumption on the values of the variables, which
1601 * are documented here. Should you change them, please check
1602 * the implementation of the various instructions to make sure
1603 * that they still work.
1605 * args->eh The MAC header. It is non-null for a layer2
1606 * packet, it is NULL for a layer-3 packet.
1608 * m | args->m Pointer to the mbuf, as received from the caller.
1609 * It may change if ipfw_chk() does an m_pullup, or if it
1610 * consumes the packet because it calls send_reject().
1611 * XXX This has to change, so that ipfw_chk() never modifies
1612 * or consumes the buffer.
1613 * ip is simply an alias of the value of m, and it is kept
1614 * in sync with it (the packet is supposed to start with
1617 struct mbuf *m = args->m;
1618 struct ip *ip = mtod(m, struct ip *);
1621 * oif | args->oif If NULL, ipfw_chk has been called on the
1622 * inbound path (ether_input, ip_input).
1623 * If non-NULL, ipfw_chk has been called on the outbound path
1624 * (ether_output, ip_output).
1626 struct ifnet *oif = args->oif;
1628 struct ip_fw *f = NULL; /* matching rule */
1631 struct divert_info *divinfo;
1634 * hlen The length of the IPv4 header.
1635 * hlen >0 means we have an IPv4 packet.
1637 u_int hlen = 0; /* hlen >0 means we have an IP pkt */
1640 * offset The offset of a fragment. offset != 0 means that
1641 * we have a fragment at this offset of an IPv4 packet.
1642 * offset == 0 means that (if this is an IPv4 packet)
1643 * this is the first or only fragment.
1648 * Local copies of addresses. They are only valid if we have
1651 * proto The protocol. Set to 0 for non-ip packets,
1652 * or to the protocol read from the packet otherwise.
1653 * proto != 0 means that we have an IPv4 packet.
1655 * src_port, dst_port port numbers, in HOST format. Only
1656 * valid for TCP and UDP packets.
1658 * src_ip, dst_ip ip addresses, in NETWORK format.
1659 * Only valid for IPv4 packets.
1662 uint16_t src_port = 0, dst_port = 0; /* NOTE: host format */
1663 struct in_addr src_ip, dst_ip; /* NOTE: network format */
1664 uint16_t ip_len = 0;
1667 * dyn_dir = MATCH_UNKNOWN when rules unchecked,
1668 * MATCH_NONE when checked and not matched (dyn_f = NULL),
1669 * MATCH_FORWARD or MATCH_REVERSE otherwise (dyn_f != NULL)
1671 int dyn_dir = MATCH_UNKNOWN;
1672 struct ip_fw *dyn_f = NULL;
1673 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
1675 if (m->m_pkthdr.fw_flags & IPFW_MBUF_GENERATED)
1676 return 0; /* accept */
1678 if (args->eh == NULL || /* layer 3 packet */
1679 (m->m_pkthdr.len >= sizeof(struct ip) &&
1680 ntohs(args->eh->ether_type) == ETHERTYPE_IP))
1681 hlen = ip->ip_hl << 2;
1684 * Collect parameters into local variables for faster matching.
1686 if (hlen == 0) { /* do not grab addresses for non-ip pkts */
1687 proto = args->f_id.proto = 0; /* mark f_id invalid */
1688 goto after_ip_checks;
1691 proto = args->f_id.proto = ip->ip_p;
1692 src_ip = ip->ip_src;
1693 dst_ip = ip->ip_dst;
1694 if (args->eh != NULL) { /* layer 2 packets are as on the wire */
1695 offset = ntohs(ip->ip_off) & IP_OFFMASK;
1696 ip_len = ntohs(ip->ip_len);
1698 offset = ip->ip_off & IP_OFFMASK;
1699 ip_len = ip->ip_len;
1702 #define PULLUP_TO(len) \
1704 if (m->m_len < (len)) { \
1705 args->m = m = m_pullup(m, (len));\
1707 goto pullup_failed; \
1708 ip = mtod(m, struct ip *); \
1718 PULLUP_TO(hlen + sizeof(struct tcphdr));
1719 tcp = L3HDR(struct tcphdr, ip);
1720 dst_port = tcp->th_dport;
1721 src_port = tcp->th_sport;
1722 args->f_id.flags = tcp->th_flags;
1730 PULLUP_TO(hlen + sizeof(struct udphdr));
1731 udp = L3HDR(struct udphdr, ip);
1732 dst_port = udp->uh_dport;
1733 src_port = udp->uh_sport;
1738 PULLUP_TO(hlen + 4); /* type, code and checksum. */
1739 args->f_id.flags = L3HDR(struct icmp, ip)->icmp_type;
1749 args->f_id.src_ip = ntohl(src_ip.s_addr);
1750 args->f_id.dst_ip = ntohl(dst_ip.s_addr);
1751 args->f_id.src_port = src_port = ntohs(src_port);
1752 args->f_id.dst_port = dst_port = ntohs(dst_port);
1757 * Packet has already been tagged. Look for the next rule
1758 * to restart processing.
1760 * If fw_one_pass != 0 then just accept it.
1761 * XXX should not happen here, but optimized out in
1767 /* This rule is being/has been flushed */
1769 return IP_FW_PORT_DENY_FLAG;
1771 KASSERT(args->rule->cpuid == mycpuid,
1772 ("rule used on cpu%d\n", mycpuid));
1774 /* This rule was deleted */
1775 if (args->rule->rule_flags & IPFW_RULE_F_INVALID)
1776 return IP_FW_PORT_DENY_FLAG;
1778 f = args->rule->next_rule;
1780 f = lookup_next_rule(args->rule);
1783 * Find the starting rule. It can be either the first
1784 * one, or the one after divert_rule if asked so.
1788 mtag = m_tag_find(m, PACKET_TAG_IPFW_DIVERT, NULL);
1790 divinfo = m_tag_data(mtag);
1791 skipto = divinfo->skipto;
1796 f = ctx->ipfw_layer3_chain;
1797 if (args->eh == NULL && skipto != 0) {
1798 /* No skipto during rule flushing */
1800 return IP_FW_PORT_DENY_FLAG;
1802 if (skipto >= IPFW_DEFAULT_RULE)
1803 return(IP_FW_PORT_DENY_FLAG); /* invalid */
1805 while (f && f->rulenum <= skipto)
1807 if (f == NULL) /* drop packet */
1808 return(IP_FW_PORT_DENY_FLAG);
1809 } else if (ipfw_flushing) {
1810 /* Rules are being flushed; skip to default rule */
1811 f = ctx->ipfw_default_rule;
1814 if ((mtag = m_tag_find(m, PACKET_TAG_IPFW_DIVERT, NULL)) != NULL)
1815 m_tag_delete(m, mtag);
1818 * Now scan the rules, and parse microinstructions for each rule.
1820 for (; f; f = f->next) {
1823 int skip_or; /* skip rest of OR block */
1826 if (ctx->ipfw_set_disable & (1 << f->set))
1830 for (l = f->cmd_len, cmd = f->cmd; l > 0;
1831 l -= cmdlen, cmd += cmdlen) {
1835 * check_body is a jump target used when we find a
1836 * CHECK_STATE, and need to jump to the body of
1841 cmdlen = F_LEN(cmd);
1843 * An OR block (insn_1 || .. || insn_n) has the
1844 * F_OR bit set in all but the last instruction.
1845 * The first match will set "skip_or", and cause
1846 * the following instructions to be skipped until
1847 * past the one with the F_OR bit clear.
1849 if (skip_or) { /* skip this instruction */
1850 if ((cmd->len & F_OR) == 0)
1851 skip_or = 0; /* next one is good */
1854 match = 0; /* set to 1 if we succeed */
1856 switch (cmd->opcode) {
1858 * The first set of opcodes compares the packet's
1859 * fields with some pattern, setting 'match' if a
1860 * match is found. At the end of the loop there is
1861 * logic to deal with F_NOT and F_OR flags associated
1869 kprintf("ipfw: opcode %d unimplemented\n",
1876 * We only check offset == 0 && proto != 0,
1877 * as this ensures that we have an IPv4
1878 * packet with the ports info.
1883 struct inpcbinfo *pi;
1887 if (proto == IPPROTO_TCP) {
1889 pi = &tcbinfo[mycpu->gd_cpuid];
1890 } else if (proto == IPPROTO_UDP) {
1897 in_pcblookup_hash(pi,
1898 dst_ip, htons(dst_port),
1899 src_ip, htons(src_port),
1901 in_pcblookup_hash(pi,
1902 src_ip, htons(src_port),
1903 dst_ip, htons(dst_port),
1906 if (pcb == NULL || pcb->inp_socket == NULL)
1909 if (cmd->opcode == O_UID) {
1910 #define socheckuid(a,b) ((a)->so_cred->cr_uid != (b))
1912 !socheckuid(pcb->inp_socket,
1913 (uid_t)((ipfw_insn_u32 *)cmd)->d[0]);
1916 match = groupmember(
1917 (uid_t)((ipfw_insn_u32 *)cmd)->d[0],
1918 pcb->inp_socket->so_cred);
1924 match = iface_match(m->m_pkthdr.rcvif,
1925 (ipfw_insn_if *)cmd);
1929 match = iface_match(oif, (ipfw_insn_if *)cmd);
1933 match = iface_match(oif ? oif :
1934 m->m_pkthdr.rcvif, (ipfw_insn_if *)cmd);
1938 if (args->eh != NULL) { /* have MAC header */
1939 uint32_t *want = (uint32_t *)
1940 ((ipfw_insn_mac *)cmd)->addr;
1941 uint32_t *mask = (uint32_t *)
1942 ((ipfw_insn_mac *)cmd)->mask;
1943 uint32_t *hdr = (uint32_t *)args->eh;
1946 (want[0] == (hdr[0] & mask[0]) &&
1947 want[1] == (hdr[1] & mask[1]) &&
1948 want[2] == (hdr[2] & mask[2]));
1953 if (args->eh != NULL) {
1955 ntohs(args->eh->ether_type);
1957 ((ipfw_insn_u16 *)cmd)->ports;
1960 /* Special vlan handling */
1961 if (m->m_flags & M_VLANTAG)
1964 for (i = cmdlen - 1; !match && i > 0;
1967 (t >= p[0] && t <= p[1]);
1973 match = (hlen > 0 && offset != 0);
1976 case O_IN: /* "out" is "not in" */
1977 match = (oif == NULL);
1981 match = (args->eh != NULL);
1986 * We do not allow an arg of 0 so the
1987 * check of "proto" only suffices.
1989 match = (proto == cmd->arg1);
1993 match = (hlen > 0 &&
1994 ((ipfw_insn_ip *)cmd)->addr.s_addr ==
1999 match = (hlen > 0 &&
2000 ((ipfw_insn_ip *)cmd)->addr.s_addr ==
2002 ((ipfw_insn_ip *)cmd)->mask.s_addr));
2009 tif = INADDR_TO_IFP(&src_ip);
2010 match = (tif != NULL);
2017 uint32_t *d = (uint32_t *)(cmd + 1);
2019 cmd->opcode == O_IP_DST_SET ?
2025 addr -= d[0]; /* subtract base */
2027 (addr < cmd->arg1) &&
2028 (d[1 + (addr >> 5)] &
2029 (1 << (addr & 0x1f)));
2034 match = (hlen > 0 &&
2035 ((ipfw_insn_ip *)cmd)->addr.s_addr ==
2040 match = (hlen > 0) &&
2041 (((ipfw_insn_ip *)cmd)->addr.s_addr ==
2043 ((ipfw_insn_ip *)cmd)->mask.s_addr));
2050 tif = INADDR_TO_IFP(&dst_ip);
2051 match = (tif != NULL);
2058 * offset == 0 && proto != 0 is enough
2059 * to guarantee that we have an IPv4
2060 * packet with port info.
2062 if ((proto==IPPROTO_UDP || proto==IPPROTO_TCP)
2065 (cmd->opcode == O_IP_SRCPORT) ?
2066 src_port : dst_port ;
2068 ((ipfw_insn_u16 *)cmd)->ports;
2071 for (i = cmdlen - 1; !match && i > 0;
2074 (x >= p[0] && x <= p[1]);
2080 match = (offset == 0 && proto==IPPROTO_ICMP &&
2081 icmptype_match(ip, (ipfw_insn_u32 *)cmd));
2085 match = (hlen > 0 && ipopts_match(ip, cmd));
2089 match = (hlen > 0 && cmd->arg1 == ip->ip_v);
2093 match = (hlen > 0 && cmd->arg1 == ip->ip_ttl);
2097 match = (hlen > 0 &&
2098 cmd->arg1 == ntohs(ip->ip_id));
2102 match = (hlen > 0 && cmd->arg1 == ip_len);
2105 case O_IPPRECEDENCE:
2106 match = (hlen > 0 &&
2107 (cmd->arg1 == (ip->ip_tos & 0xe0)));
2111 match = (hlen > 0 &&
2112 flags_match(cmd, ip->ip_tos));
2116 match = (proto == IPPROTO_TCP && offset == 0 &&
2118 L3HDR(struct tcphdr,ip)->th_flags));
2122 match = (proto == IPPROTO_TCP && offset == 0 &&
2123 tcpopts_match(ip, cmd));
2127 match = (proto == IPPROTO_TCP && offset == 0 &&
2128 ((ipfw_insn_u32 *)cmd)->d[0] ==
2129 L3HDR(struct tcphdr,ip)->th_seq);
2133 match = (proto == IPPROTO_TCP && offset == 0 &&
2134 ((ipfw_insn_u32 *)cmd)->d[0] ==
2135 L3HDR(struct tcphdr,ip)->th_ack);
2139 match = (proto == IPPROTO_TCP && offset == 0 &&
2141 L3HDR(struct tcphdr,ip)->th_win);
2145 /* reject packets which have SYN only */
2146 /* XXX should i also check for TH_ACK ? */
2147 match = (proto == IPPROTO_TCP && offset == 0 &&
2148 (L3HDR(struct tcphdr,ip)->th_flags &
2149 (TH_RST | TH_ACK | TH_SYN)) != TH_SYN);
2154 ipfw_log(f, hlen, args->eh, m, oif);
2159 match = (krandom() <
2160 ((ipfw_insn_u32 *)cmd)->d[0]);
2164 * The second set of opcodes represents 'actions',
2165 * i.e. the terminal part of a rule once the packet
2166 * matches all previous patterns.
2167 * Typically there is only one action for each rule,
2168 * and the opcode is stored at the end of the rule
2169 * (but there are exceptions -- see below).
2171 * In general, here we set retval and terminate the
2172 * outer loop (would be a 'break 3' in some language,
2173 * but we need to do a 'goto done').
2176 * O_COUNT and O_SKIPTO actions:
2177 * instead of terminating, we jump to the next rule
2178 * ('goto next_rule', equivalent to a 'break 2'),
2179 * or to the SKIPTO target ('goto again' after
2180 * having set f, cmd and l), respectively.
2182 * O_LIMIT and O_KEEP_STATE: these opcodes are
2183 * not real 'actions', and are stored right
2184 * before the 'action' part of the rule.
2185 * These opcodes try to install an entry in the
2186 * state tables; if successful, we continue with
2187 * the next opcode (match=1; break;), otherwise
2188 * the packet must be dropped ('goto done' after
2189 * setting retval). If static rules are changed
2190 * during the state installation, the packet will
2191 * be dropped ('return IP_FW_PORT_DENY_FLAG').
2193 * O_PROBE_STATE and O_CHECK_STATE: these opcodes
2194 * cause a lookup of the state table, and a jump
2195 * to the 'action' part of the parent rule
2196 * ('goto check_body') if an entry is found, or
2197 * (CHECK_STATE only) a jump to the next rule if
2198 * the entry is not found ('goto next_rule').
2199 * The result of the lookup is cached to make
2200 * further instances of these opcodes are
2201 * effectively NOPs. If static rules are changed
2202 * during the state looking up, the packet will
2203 * be dropped ('return IP_FW_PORT_DENY_FLAG').
2207 if (!(f->rule_flags & IPFW_RULE_F_STATE)) {
2208 kprintf("%s rule (%d) is not ready "
2210 cmd->opcode == O_LIMIT ?
2211 "limit" : "keep state",
2212 f->rulenum, f->cpuid);
2215 if (install_state(f,
2216 (ipfw_insn_limit *)cmd, args, &deny)) {
2218 return IP_FW_PORT_DENY_FLAG;
2220 retval = IP_FW_PORT_DENY_FLAG;
2221 goto done; /* error/limit violation */
2224 return IP_FW_PORT_DENY_FLAG;
2231 * dynamic rules are checked at the first
2232 * keep-state or check-state occurrence,
2233 * with the result being stored in dyn_dir.
2234 * The compiler introduces a PROBE_STATE
2235 * instruction for us when we have a
2236 * KEEP_STATE (because PROBE_STATE needs
2239 if (dyn_dir == MATCH_UNKNOWN) {
2240 dyn_f = lookup_rule(&args->f_id,
2242 proto == IPPROTO_TCP ?
2243 L3HDR(struct tcphdr, ip) : NULL,
2246 return IP_FW_PORT_DENY_FLAG;
2247 if (dyn_f != NULL) {
2249 * Found a rule from a dynamic
2250 * entry; jump to the 'action'
2254 cmd = ACTION_PTR(f);
2255 l = f->cmd_len - f->act_ofs;
2260 * Dynamic entry not found. If CHECK_STATE,
2261 * skip to next rule, if PROBE_STATE just
2262 * ignore and continue with next opcode.
2264 if (cmd->opcode == O_CHECK_STATE)
2266 else if (!(f->rule_flags & IPFW_RULE_F_STATE))
2267 goto next_rule; /* not ready yet */
2272 retval = 0; /* accept */
2277 args->rule = f; /* report matching rule */
2278 retval = cmd->arg1 | IP_FW_PORT_DYNT_FLAG;
2283 if (args->eh) /* not on layer 2 */
2286 mtag = m_tag_get(PACKET_TAG_IPFW_DIVERT,
2287 sizeof(*divinfo), MB_DONTWAIT);
2289 retval = IP_FW_PORT_DENY_FLAG;
2292 divinfo = m_tag_data(mtag);
2294 divinfo->skipto = f->rulenum;
2295 divinfo->port = cmd->arg1;
2296 divinfo->tee = (cmd->opcode == O_TEE);
2297 m_tag_prepend(m, mtag);
2299 retval = (cmd->opcode == O_DIVERT) ?
2301 cmd->arg1 | IP_FW_PORT_TEE_FLAG;
2306 f->pcnt++; /* update stats */
2308 f->timestamp = time_second;
2309 if (cmd->opcode == O_COUNT)
2312 if (f->next_rule == NULL)
2313 lookup_next_rule(f);
2319 * Drop the packet and send a reject notice
2320 * if the packet is not ICMP (or is an ICMP
2321 * query), and it is not multicast/broadcast.
2324 (proto != IPPROTO_ICMP ||
2325 is_icmp_query(ip)) &&
2326 !(m->m_flags & (M_BCAST|M_MCAST)) &&
2327 !IN_MULTICAST(ntohl(dst_ip.s_addr))) {
2329 * Update statistics before the possible
2330 * blocking 'send_reject'
2334 f->timestamp = time_second;
2336 send_reject(args, cmd->arg1,
2341 * Return directly here, rule stats
2342 * have been updated above.
2344 return IP_FW_PORT_DENY_FLAG;
2348 retval = IP_FW_PORT_DENY_FLAG;
2352 if (args->eh) /* not valid on layer2 pkts */
2354 if (!dyn_f || dyn_dir == MATCH_FORWARD) {
2355 struct sockaddr_in *sin;
2357 mtag = m_tag_get(PACKET_TAG_IPFORWARD,
2358 sizeof(*sin), MB_DONTWAIT);
2360 retval = IP_FW_PORT_DENY_FLAG;
2363 sin = m_tag_data(mtag);
2365 /* Structure copy */
2366 *sin = ((ipfw_insn_sa *)cmd)->sa;
2368 m_tag_prepend(m, mtag);
2369 m->m_pkthdr.fw_flags |=
2370 IPFORWARD_MBUF_TAGGED;
2376 panic("-- unknown opcode %d\n", cmd->opcode);
2377 } /* end of switch() on opcodes */
2379 if (cmd->len & F_NOT)
2383 if (cmd->len & F_OR)
2386 if (!(cmd->len & F_OR)) /* not an OR block, */
2387 break; /* try next rule */
2390 } /* end of inner for, scan opcodes */
2392 next_rule:; /* try next rule */
2394 } /* end of outer for, scan rules */
2395 kprintf("+++ ipfw: ouch!, skip past end of rules, denying packet\n");
2396 return(IP_FW_PORT_DENY_FLAG);
2399 /* Update statistics */
2402 f->timestamp = time_second;
2407 kprintf("pullup failed\n");
2408 return(IP_FW_PORT_DENY_FLAG);
2412 ipfw_dummynet_io(struct mbuf *m, int pipe_nr, int dir, struct ip_fw_args *fwa)
2417 const struct ipfw_flow_id *id;
2418 struct dn_flow_id *fid;
2422 mtag = m_tag_get(PACKET_TAG_DUMMYNET, sizeof(*pkt), MB_DONTWAIT);
2427 m_tag_prepend(m, mtag);
2429 pkt = m_tag_data(mtag);
2430 bzero(pkt, sizeof(*pkt));
2432 cmd = fwa->rule->cmd + fwa->rule->act_ofs;
2433 if (cmd->opcode == O_LOG)
2435 KASSERT(cmd->opcode == O_PIPE || cmd->opcode == O_QUEUE,
2436 ("Rule is not PIPE or QUEUE, opcode %d\n", cmd->opcode));
2439 pkt->dn_flags = (dir & DN_FLAGS_DIR_MASK);
2440 pkt->ifp = fwa->oif;
2441 pkt->cpuid = mycpu->gd_cpuid;
2442 pkt->pipe_nr = pipe_nr;
2446 fid->fid_dst_ip = id->dst_ip;
2447 fid->fid_src_ip = id->src_ip;
2448 fid->fid_dst_port = id->dst_port;
2449 fid->fid_src_port = id->src_port;
2450 fid->fid_proto = id->proto;
2451 fid->fid_flags = id->flags;
2453 ipfw_ref_rule(fwa->rule);
2454 pkt->dn_priv = fwa->rule;
2455 pkt->dn_unref_priv = ipfw_unref_rule;
2457 if (cmd->opcode == O_PIPE)
2458 pkt->dn_flags |= DN_FLAGS_IS_PIPE;
2460 if (dir == DN_TO_IP_OUT) {
2462 * We need to copy *ro because for ICMP pkts (and maybe
2463 * others) the caller passed a pointer into the stack;
2464 * dst might also be a pointer into *ro so it needs to
2467 pkt->ro = *(fwa->ro);
2469 fwa->ro->ro_rt->rt_refcnt++;
2470 if (fwa->dst == (struct sockaddr_in *)&fwa->ro->ro_dst) {
2471 /* 'dst' points into 'ro' */
2472 fwa->dst = (struct sockaddr_in *)&(pkt->ro.ro_dst);
2474 pkt->dn_dst = fwa->dst;
2475 pkt->flags = fwa->flags;
2478 m->m_pkthdr.fw_flags |= DUMMYNET_MBUF_TAGGED;
2483 * When a rule is added/deleted, clear the next_rule pointers in all rules.
2484 * These will be reconstructed on the fly as packets are matched.
2485 * Must be called at splimp().
2488 ipfw_flush_rule_ptrs(struct ipfw_context *ctx)
2492 for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next)
2493 rule->next_rule = NULL;
2496 static __inline void
2497 ipfw_inc_static_count(struct ip_fw *rule)
2499 KKASSERT(mycpuid == 0);
2502 static_ioc_len += IOC_RULESIZE(rule);
2505 static __inline void
2506 ipfw_dec_static_count(struct ip_fw *rule)
2508 int l = IOC_RULESIZE(rule);
2510 KKASSERT(mycpuid == 0);
2512 KASSERT(static_count > 0, ("invalid static count %u\n", static_count));
2515 KASSERT(static_ioc_len >= l,
2516 ("invalid static len %u\n", static_ioc_len));
2517 static_ioc_len -= l;
2521 ipfw_link_sibling(struct netmsg_ipfw *fwmsg, struct ip_fw *rule)
2523 if (fwmsg->sibling != NULL) {
2524 KKASSERT(mycpuid > 0 && fwmsg->sibling->cpuid == mycpuid - 1);
2525 fwmsg->sibling->sibling = rule;
2527 fwmsg->sibling = rule;
2530 static struct ip_fw *
2531 ipfw_create_rule(const struct ipfw_ioc_rule *ioc_rule, struct ip_fw_stub *stub)
2535 rule = kmalloc(RULESIZE(ioc_rule), M_IPFW, M_WAITOK | M_ZERO);
2537 rule->act_ofs = ioc_rule->act_ofs;
2538 rule->cmd_len = ioc_rule->cmd_len;
2539 rule->rulenum = ioc_rule->rulenum;
2540 rule->set = ioc_rule->set;
2541 rule->usr_flags = ioc_rule->usr_flags;
2543 bcopy(ioc_rule->cmd, rule->cmd, rule->cmd_len * 4 /* XXX */);
2546 rule->cpuid = mycpuid;
2550 stub->rule[mycpuid] = rule;
2556 ipfw_add_rule_dispatch(struct netmsg *nmsg)
2558 struct netmsg_ipfw *fwmsg = (struct netmsg_ipfw *)nmsg;
2559 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2562 rule = ipfw_create_rule(fwmsg->ioc_rule, fwmsg->stub);
2565 * Bump generation after ipfw_create_rule(),
2566 * since this function is blocking
2571 * Insert rule into the pre-determined position
2573 if (fwmsg->prev_rule != NULL) {
2574 struct ip_fw *prev, *next;
2576 prev = fwmsg->prev_rule;
2577 KKASSERT(prev->cpuid == mycpuid);
2579 next = fwmsg->next_rule;
2580 KKASSERT(next->cpuid == mycpuid);
2586 * Move to the position on the next CPU
2587 * before the msg is forwarded.
2589 fwmsg->prev_rule = prev->sibling;
2590 fwmsg->next_rule = next->sibling;
2592 KKASSERT(fwmsg->next_rule == NULL);
2593 rule->next = ctx->ipfw_layer3_chain;
2594 ctx->ipfw_layer3_chain = rule;
2597 /* Link rule CPU sibling */
2598 ipfw_link_sibling(fwmsg, rule);
2600 ipfw_flush_rule_ptrs(ctx);
2603 /* Statistics only need to be updated once */
2604 ipfw_inc_static_count(rule);
2606 /* Return the rule on CPU0 */
2607 nmsg->nm_lmsg.u.ms_resultp = rule;
2610 ifnet_forwardmsg(&nmsg->nm_lmsg, mycpuid + 1);
2614 ipfw_enable_state_dispatch(struct netmsg *nmsg)
2616 struct lwkt_msg *lmsg = &nmsg->nm_lmsg;
2617 struct ip_fw *rule = lmsg->u.ms_resultp;
2619 KKASSERT(rule->cpuid == mycpuid);
2620 KKASSERT(rule->stub != NULL && rule->stub->rule[mycpuid] == rule);
2621 KKASSERT(!(rule->rule_flags & IPFW_RULE_F_STATE));
2622 rule->rule_flags |= IPFW_RULE_F_STATE;
2623 lmsg->u.ms_resultp = rule->sibling;
2625 ifnet_forwardmsg(lmsg, mycpuid + 1);
2629 * Add a new rule to the list. Copy the rule into a malloc'ed area,
2630 * then possibly create a rule number and add the rule to the list.
2631 * Update the rule_number in the input struct so the caller knows
2635 ipfw_add_rule(struct ipfw_ioc_rule *ioc_rule, uint32_t rule_flags)
2637 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2638 struct netmsg_ipfw fwmsg;
2639 struct netmsg *nmsg;
2640 struct ip_fw *f, *prev, *rule;
2641 struct ip_fw_stub *stub;
2643 IPFW_ASSERT_CFGPORT(&curthread->td_msgport);
2648 * If rulenum is 0, find highest numbered rule before the
2649 * default rule, and add rule number incremental step.
2651 if (ioc_rule->rulenum == 0) {
2652 int step = autoinc_step;
2654 KKASSERT(step >= IPFW_AUTOINC_STEP_MIN &&
2655 step <= IPFW_AUTOINC_STEP_MAX);
2658 * Locate the highest numbered rule before default
2660 for (f = ctx->ipfw_layer3_chain; f; f = f->next) {
2661 if (f->rulenum == IPFW_DEFAULT_RULE)
2663 ioc_rule->rulenum = f->rulenum;
2665 if (ioc_rule->rulenum < IPFW_DEFAULT_RULE - step)
2666 ioc_rule->rulenum += step;
2668 KASSERT(ioc_rule->rulenum != IPFW_DEFAULT_RULE &&
2669 ioc_rule->rulenum != 0,
2670 ("invalid rule num %d\n", ioc_rule->rulenum));
2673 * Now find the right place for the new rule in the sorted list.
2675 for (prev = NULL, f = ctx->ipfw_layer3_chain; f;
2676 prev = f, f = f->next) {
2677 if (f->rulenum > ioc_rule->rulenum) {
2678 /* Found the location */
2682 KASSERT(f != NULL, ("no default rule?!\n"));
2684 if (rule_flags & IPFW_RULE_F_STATE) {
2688 * If the new rule will create states, then allocate
2689 * a rule stub, which will be referenced by states
2692 size = sizeof(*stub) + ((ncpus - 1) * sizeof(struct ip_fw *));
2693 stub = kmalloc(size, M_IPFW, M_WAITOK | M_ZERO);
2699 * Duplicate the rule onto each CPU.
2700 * The rule duplicated on CPU0 will be returned.
2702 bzero(&fwmsg, sizeof(fwmsg));
2704 netmsg_init(nmsg, &curthread->td_msgport, 0, ipfw_add_rule_dispatch);
2705 fwmsg.ioc_rule = ioc_rule;
2706 fwmsg.prev_rule = prev;
2707 fwmsg.next_rule = prev == NULL ? NULL : f;
2710 ifnet_domsg(&nmsg->nm_lmsg, 0);
2711 KKASSERT(fwmsg.prev_rule == NULL && fwmsg.next_rule == NULL);
2713 rule = nmsg->nm_lmsg.u.ms_resultp;
2714 KKASSERT(rule != NULL && rule->cpuid == mycpuid);
2716 if (rule_flags & IPFW_RULE_F_STATE) {
2718 * Turn on state flag, _after_ everything on all
2719 * CPUs have been setup.
2721 bzero(nmsg, sizeof(*nmsg));
2722 netmsg_init(nmsg, &curthread->td_msgport, 0,
2723 ipfw_enable_state_dispatch);
2724 nmsg->nm_lmsg.u.ms_resultp = rule;
2726 ifnet_domsg(&nmsg->nm_lmsg, 0);
2727 KKASSERT(nmsg->nm_lmsg.u.ms_resultp == NULL);
2732 DEB(kprintf("++ installed rule %d, static count now %d\n",
2733 rule->rulenum, static_count);)
2737 * Free storage associated with a static rule (including derived
2739 * The caller is in charge of clearing rule pointers to avoid
2740 * dangling pointers.
2741 * @return a pointer to the next entry.
2742 * Arguments are not checked, so they better be correct.
2743 * Must be called at splimp().
2745 static struct ip_fw *
2746 ipfw_delete_rule(struct ipfw_context *ctx,
2747 struct ip_fw *prev, struct ip_fw *rule)
2750 struct ip_fw_stub *stub;
2754 /* STATE flag should have been cleared before we reach here */
2755 KKASSERT((rule->rule_flags & IPFW_RULE_F_STATE) == 0);
2760 ctx->ipfw_layer3_chain = n;
2764 /* Mark the rule as invalid */
2765 rule->rule_flags |= IPFW_RULE_F_INVALID;
2766 rule->next_rule = NULL;
2767 rule->sibling = NULL;
2770 /* Don't reset cpuid here; keep various assertion working */
2774 /* Statistics only need to be updated once */
2776 ipfw_dec_static_count(rule);
2778 /* Free 'stub' on the last CPU */
2779 if (stub != NULL && mycpuid == ncpus - 1)
2780 kfree(stub, M_IPFW);
2782 /* Try to free this rule */
2783 ipfw_free_rule(rule);
2785 /* Return the next rule */
2790 ipfw_flush_dispatch(struct netmsg *nmsg)
2792 struct lwkt_msg *lmsg = &nmsg->nm_lmsg;
2793 int kill_default = lmsg->u.ms_result;
2794 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2797 ipfw_flush_rule_ptrs(ctx); /* more efficient to do outside the loop */
2799 while ((rule = ctx->ipfw_layer3_chain) != NULL &&
2800 (kill_default || rule->rulenum != IPFW_DEFAULT_RULE))
2801 ipfw_delete_rule(ctx, NULL, rule);
2803 ifnet_forwardmsg(lmsg, mycpuid + 1);
2807 ipfw_disable_rule_state_dispatch(struct netmsg *nmsg)
2809 struct netmsg_del *dmsg = (struct netmsg_del *)nmsg;
2812 rule = dmsg->start_rule;
2814 KKASSERT(rule->cpuid == mycpuid);
2817 * Move to the position on the next CPU
2818 * before the msg is forwarded.
2820 dmsg->start_rule = rule->sibling;
2822 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2824 KKASSERT(dmsg->rulenum == 0);
2825 rule = ctx->ipfw_layer3_chain;
2828 while (rule != NULL) {
2829 if (dmsg->rulenum && rule->rulenum != dmsg->rulenum)
2831 rule->rule_flags &= ~IPFW_RULE_F_STATE;
2835 ifnet_forwardmsg(&nmsg->nm_lmsg, mycpuid + 1);
2839 * Deletes all rules from a chain (including the default rule
2840 * if the second argument is set).
2841 * Must be called at splimp().
2844 ipfw_flush(int kill_default)
2846 struct netmsg_del dmsg;
2848 struct lwkt_msg *lmsg;
2850 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2852 IPFW_ASSERT_CFGPORT(&curthread->td_msgport);
2855 * If 'kill_default' then caller has done the necessary
2856 * msgport syncing; unnecessary to do it again.
2858 if (!kill_default) {
2860 * Let ipfw_chk() know the rules are going to
2861 * be flushed, so it could jump directly to
2865 netmsg_service_sync();
2869 * Clear STATE flag on rules, so no more states (dyn rules)
2872 bzero(&dmsg, sizeof(dmsg));
2873 netmsg_init(&dmsg.nmsg, &curthread->td_msgport, 0,
2874 ipfw_disable_rule_state_dispatch);
2875 ifnet_domsg(&dmsg.nmsg.nm_lmsg, 0);
2878 * This actually nukes all states (dyn rules)
2880 lockmgr(&dyn_lock, LK_EXCLUSIVE);
2881 for (rule = ctx->ipfw_layer3_chain; rule != NULL; rule = rule->next) {
2883 * Can't check IPFW_RULE_F_STATE here,
2884 * since it has been cleared previously.
2885 * Check 'stub' instead.
2887 if (rule->stub != NULL) {
2889 remove_dyn_rule_locked(rule, NULL);
2892 lockmgr(&dyn_lock, LK_RELEASE);
2895 * Press the 'flush' button
2897 bzero(&nmsg, sizeof(nmsg));
2898 netmsg_init(&nmsg, &curthread->td_msgport, 0, ipfw_flush_dispatch);
2899 lmsg = &nmsg.nm_lmsg;
2900 lmsg->u.ms_result = kill_default;
2901 ifnet_domsg(lmsg, 0);
2903 KASSERT(dyn_count == 0, ("%u dyn rule remains\n", dyn_count));
2906 if (ipfw_dyn_v != NULL) {
2908 * Free dynamic rules(state) hash table
2910 kfree(ipfw_dyn_v, M_IPFW);
2914 KASSERT(static_count == 0,
2915 ("%u static rules remains\n", static_count));
2916 KASSERT(static_ioc_len == 0,
2917 ("%u bytes of static rules remains\n", static_ioc_len));
2919 KASSERT(static_count == 1,
2920 ("%u static rules remains\n", static_count));
2921 KASSERT(static_ioc_len == IOC_RULESIZE(ctx->ipfw_default_rule),
2922 ("%u bytes of static rules remains, should be %u\n",
2923 static_ioc_len, IOC_RULESIZE(ctx->ipfw_default_rule)));
2931 ipfw_alt_delete_rule_dispatch(struct netmsg *nmsg)
2933 struct netmsg_del *dmsg = (struct netmsg_del *)nmsg;
2934 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2935 struct ip_fw *rule, *prev;
2937 rule = dmsg->start_rule;
2938 KKASSERT(rule->cpuid == mycpuid);
2939 dmsg->start_rule = rule->sibling;
2941 prev = dmsg->prev_rule;
2943 KKASSERT(prev->cpuid == mycpuid);
2946 * Move to the position on the next CPU
2947 * before the msg is forwarded.
2949 dmsg->prev_rule = prev->sibling;
2953 * flush pointers outside the loop, then delete all matching
2954 * rules. 'prev' remains the same throughout the cycle.
2956 ipfw_flush_rule_ptrs(ctx);
2957 while (rule && rule->rulenum == dmsg->rulenum)
2958 rule = ipfw_delete_rule(ctx, prev, rule);
2960 ifnet_forwardmsg(&nmsg->nm_lmsg, mycpuid + 1);
2964 ipfw_alt_delete_rule(uint16_t rulenum)
2966 struct ip_fw *prev, *rule, *f;
2967 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2968 struct netmsg_del dmsg;
2969 struct netmsg *nmsg;
2973 * Locate first rule to delete
2975 for (prev = NULL, rule = ctx->ipfw_layer3_chain;
2976 rule && rule->rulenum < rulenum;
2977 prev = rule, rule = rule->next)
2979 if (rule->rulenum != rulenum)
2983 * Check whether any rules with the given number will
2987 for (f = rule; f && f->rulenum == rulenum; f = f->next) {
2988 if (f->rule_flags & IPFW_RULE_F_STATE) {
2996 * Clear the STATE flag, so no more states will be
2997 * created based the rules numbered 'rulenum'.
2999 bzero(&dmsg, sizeof(dmsg));
3001 netmsg_init(nmsg, &curthread->td_msgport, 0,
3002 ipfw_disable_rule_state_dispatch);
3003 dmsg.start_rule = rule;
3004 dmsg.rulenum = rulenum;
3006 ifnet_domsg(&nmsg->nm_lmsg, 0);
3007 KKASSERT(dmsg.start_rule == NULL);
3010 * Nuke all related states
3012 lockmgr(&dyn_lock, LK_EXCLUSIVE);
3013 for (f = rule; f && f->rulenum == rulenum; f = f->next) {
3015 * Can't check IPFW_RULE_F_STATE here,
3016 * since it has been cleared previously.
3017 * Check 'stub' instead.
3019 if (f->stub != NULL) {
3021 remove_dyn_rule_locked(f, NULL);
3024 lockmgr(&dyn_lock, LK_RELEASE);
3028 * Get rid of the rule duplications on all CPUs
3030 bzero(&dmsg, sizeof(dmsg));
3032 netmsg_init(nmsg, &curthread->td_msgport, 0,
3033 ipfw_alt_delete_rule_dispatch);
3034 dmsg.prev_rule = prev;
3035 dmsg.start_rule = rule;
3036 dmsg.rulenum = rulenum;
3038 ifnet_domsg(&nmsg->nm_lmsg, 0);
3039 KKASSERT(dmsg.prev_rule == NULL && dmsg.start_rule == NULL);
3044 ipfw_alt_delete_ruleset_dispatch(struct netmsg *nmsg)
3046 struct netmsg_del *dmsg = (struct netmsg_del *)nmsg;
3047 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3048 struct ip_fw *prev, *rule;
3053 ipfw_flush_rule_ptrs(ctx);
3056 rule = ctx->ipfw_layer3_chain;
3057 while (rule != NULL) {
3058 if (rule->set == dmsg->from_set) {
3059 rule = ipfw_delete_rule(ctx, prev, rule);
3068 KASSERT(del, ("no match set?!\n"));
3070 ifnet_forwardmsg(&nmsg->nm_lmsg, mycpuid + 1);
3074 ipfw_disable_ruleset_state_dispatch(struct netmsg *nmsg)
3076 struct netmsg_del *dmsg = (struct netmsg_del *)nmsg;
3077 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3083 for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next) {
3084 if (rule->set == dmsg->from_set) {
3088 rule->rule_flags &= ~IPFW_RULE_F_STATE;
3091 KASSERT(cleared, ("no match set?!\n"));
3093 ifnet_forwardmsg(&nmsg->nm_lmsg, mycpuid + 1);
3097 ipfw_alt_delete_ruleset(uint8_t set)
3099 struct netmsg_del dmsg;
3100 struct netmsg *nmsg;
3103 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3106 * Check whether the 'set' exists. If it exists,
3107 * then check whether any rules within the set will
3108 * try to create states.
3112 for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next) {
3113 if (rule->set == set) {
3115 if (rule->rule_flags & IPFW_RULE_F_STATE) {
3122 return 0; /* XXX EINVAL? */
3126 * Clear the STATE flag, so no more states will be
3127 * created based the rules in this set.
3129 bzero(&dmsg, sizeof(dmsg));
3131 netmsg_init(nmsg, &curthread->td_msgport, 0,
3132 ipfw_disable_ruleset_state_dispatch);
3133 dmsg.from_set = set;
3135 ifnet_domsg(&nmsg->nm_lmsg, 0);
3138 * Nuke all related states
3140 lockmgr(&dyn_lock, LK_EXCLUSIVE);
3141 for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next) {
3142 if (rule->set != set)
3146 * Can't check IPFW_RULE_F_STATE here,
3147 * since it has been cleared previously.
3148 * Check 'stub' instead.
3150 if (rule->stub != NULL) {
3152 remove_dyn_rule_locked(rule, NULL);
3155 lockmgr(&dyn_lock, LK_RELEASE);
3161 bzero(&dmsg, sizeof(dmsg));
3163 netmsg_init(nmsg, &curthread->td_msgport, 0,
3164 ipfw_alt_delete_ruleset_dispatch);
3165 dmsg.from_set = set;
3167 ifnet_domsg(&nmsg->nm_lmsg, 0);
3172 ipfw_alt_move_rule_dispatch(struct netmsg *nmsg)
3174 struct netmsg_del *dmsg = (struct netmsg_del *)nmsg;
3177 rule = dmsg->start_rule;
3178 KKASSERT(rule->cpuid == mycpuid);
3181 * Move to the position on the next CPU
3182 * before the msg is forwarded.
3184 dmsg->start_rule = rule->sibling;
3186 while (rule && rule->rulenum <= dmsg->rulenum) {
3187 if (rule->rulenum == dmsg->rulenum)
3188 rule->set = dmsg->to_set;
3191 ifnet_forwardmsg(&nmsg->nm_lmsg, mycpuid + 1);
3195 ipfw_alt_move_rule(uint16_t rulenum, uint8_t set)
3197 struct netmsg_del dmsg;
3198 struct netmsg *nmsg;
3200 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3203 * Locate first rule to move
3205 for (rule = ctx->ipfw_layer3_chain; rule && rule->rulenum <= rulenum;
3206 rule = rule->next) {
3207 if (rule->rulenum == rulenum && rule->set != set)
3210 if (rule == NULL || rule->rulenum > rulenum)
3211 return 0; /* XXX error? */
3213 bzero(&dmsg, sizeof(dmsg));
3215 netmsg_init(nmsg, &curthread->td_msgport, 0,
3216 ipfw_alt_move_rule_dispatch);
3217 dmsg.start_rule = rule;
3218 dmsg.rulenum = rulenum;
3221 ifnet_domsg(&nmsg->nm_lmsg, 0);
3222 KKASSERT(dmsg.start_rule == NULL);
3227 ipfw_alt_move_ruleset_dispatch(struct netmsg *nmsg)
3229 struct netmsg_del *dmsg = (struct netmsg_del *)nmsg;
3230 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3233 for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next) {
3234 if (rule->set == dmsg->from_set)
3235 rule->set = dmsg->to_set;
3237 ifnet_forwardmsg(&nmsg->nm_lmsg, mycpuid + 1);
3241 ipfw_alt_move_ruleset(uint8_t from_set, uint8_t to_set)
3243 struct netmsg_del dmsg;
3244 struct netmsg *nmsg;
3246 bzero(&dmsg, sizeof(dmsg));
3248 netmsg_init(nmsg, &curthread->td_msgport, 0,
3249 ipfw_alt_move_ruleset_dispatch);
3250 dmsg.from_set = from_set;
3251 dmsg.to_set = to_set;
3253 ifnet_domsg(&nmsg->nm_lmsg, 0);
3258 ipfw_alt_swap_ruleset_dispatch(struct netmsg *nmsg)
3260 struct netmsg_del *dmsg = (struct netmsg_del *)nmsg;
3261 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3264 for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next) {
3265 if (rule->set == dmsg->from_set)
3266 rule->set = dmsg->to_set;
3267 else if (rule->set == dmsg->to_set)
3268 rule->set = dmsg->from_set;
3270 ifnet_forwardmsg(&nmsg->nm_lmsg, mycpuid + 1);
3274 ipfw_alt_swap_ruleset(uint8_t set1, uint8_t set2)
3276 struct netmsg_del dmsg;
3277 struct netmsg *nmsg;
3279 bzero(&dmsg, sizeof(dmsg));
3281 netmsg_init(nmsg, &curthread->td_msgport, 0,
3282 ipfw_alt_swap_ruleset_dispatch);
3283 dmsg.from_set = set1;
3286 ifnet_domsg(&nmsg->nm_lmsg, 0);
3291 * Remove all rules with given number, and also do set manipulation.
3293 * The argument is an uint32_t. The low 16 bit are the rule or set number,
3294 * the next 8 bits are the new set, the top 8 bits are the command:
3296 * 0 delete rules with given number
3297 * 1 delete rules with given set number
3298 * 2 move rules with given number to new set
3299 * 3 move rules with given set number to new set
3300 * 4 swap sets with given numbers
3303 ipfw_ctl_alter(uint32_t arg)
3306 uint8_t cmd, new_set;
3309 rulenum = arg & 0xffff;
3310 cmd = (arg >> 24) & 0xff;
3311 new_set = (arg >> 16) & 0xff;
3315 if (new_set >= IPFW_DEFAULT_SET)
3317 if (cmd == 0 || cmd == 2) {
3318 if (rulenum == IPFW_DEFAULT_RULE)
3321 if (rulenum >= IPFW_DEFAULT_SET)
3326 case 0: /* delete rules with given number */
3327 error = ipfw_alt_delete_rule(rulenum);
3330 case 1: /* delete all rules with given set number */
3331 error = ipfw_alt_delete_ruleset(rulenum);
3334 case 2: /* move rules with given number to new set */
3335 error = ipfw_alt_move_rule(rulenum, new_set);
3338 case 3: /* move rules with given set number to new set */
3339 error = ipfw_alt_move_ruleset(rulenum, new_set);
3342 case 4: /* swap two sets */
3343 error = ipfw_alt_swap_ruleset(rulenum, new_set);
3350 * Clear counters for a specific rule.
3353 clear_counters(struct ip_fw *rule, int log_only)
3355 ipfw_insn_log *l = (ipfw_insn_log *)ACTION_PTR(rule);
3357 if (log_only == 0) {
3358 rule->bcnt = rule->pcnt = 0;
3359 rule->timestamp = 0;
3361 if (l->o.opcode == O_LOG)
3362 l->log_left = l->max_log;
3366 ipfw_zero_entry_dispatch(struct netmsg *nmsg)
3368 struct netmsg_zent *zmsg = (struct netmsg_zent *)nmsg;
3369 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3372 if (zmsg->rulenum == 0) {
3373 KKASSERT(zmsg->start_rule == NULL);
3375 ctx->ipfw_norule_counter = 0;
3376 for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next)
3377 clear_counters(rule, zmsg->log_only);
3379 struct ip_fw *start = zmsg->start_rule;
3381 KKASSERT(start->cpuid == mycpuid);
3382 KKASSERT(start->rulenum == zmsg->rulenum);
3385 * We can have multiple rules with the same number, so we
3386 * need to clear them all.
3388 for (rule = start; rule && rule->rulenum == zmsg->rulenum;
3390 clear_counters(rule, zmsg->log_only);
3393 * Move to the position on the next CPU
3394 * before the msg is forwarded.
3396 zmsg->start_rule = start->sibling;
3398 ifnet_forwardmsg(&nmsg->nm_lmsg, mycpuid + 1);
3402 * Reset some or all counters on firewall rules.
3403 * @arg frwl is null to clear all entries, or contains a specific
3405 * @arg log_only is 1 if we only want to reset logs, zero otherwise.
3408 ipfw_ctl_zero_entry(int rulenum, int log_only)
3410 struct netmsg_zent zmsg;
3411 struct netmsg *nmsg;
3413 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3415 bzero(&zmsg, sizeof(zmsg));
3417 netmsg_init(nmsg, &curthread->td_msgport, 0, ipfw_zero_entry_dispatch);
3418 zmsg.log_only = log_only;
3421 msg = log_only ? "ipfw: All logging counts reset.\n"
3422 : "ipfw: Accounting cleared.\n";
3427 * Locate the first rule with 'rulenum'
3429 for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next) {
3430 if (rule->rulenum == rulenum)
3433 if (rule == NULL) /* we did not find any matching rules */
3435 zmsg.start_rule = rule;
3436 zmsg.rulenum = rulenum;
3438 msg = log_only ? "ipfw: Entry %d logging count reset.\n"
3439 : "ipfw: Entry %d cleared.\n";
3441 ifnet_domsg(&nmsg->nm_lmsg, 0);
3442 KKASSERT(zmsg.start_rule == NULL);
3445 log(LOG_SECURITY | LOG_NOTICE, msg, rulenum);
3450 * Check validity of the structure before insert.
3451 * Fortunately rules are simple, so this mostly need to check rule sizes.
3454 ipfw_check_ioc_rule(struct ipfw_ioc_rule *rule, int size, uint32_t *rule_flags)
3457 int have_action = 0;
3462 /* Check for valid size */
3463 if (size < sizeof(*rule)) {
3464 kprintf("ipfw: rule too short\n");
3467 l = IOC_RULESIZE(rule);
3469 kprintf("ipfw: size mismatch (have %d want %d)\n", size, l);
3473 /* Check rule number */
3474 if (rule->rulenum == IPFW_DEFAULT_RULE) {
3475 kprintf("ipfw: invalid rule number\n");
3480 * Now go for the individual checks. Very simple ones, basically only
3481 * instruction sizes.
3483 for (l = rule->cmd_len, cmd = rule->cmd; l > 0;
3484 l -= cmdlen, cmd += cmdlen) {
3485 cmdlen = F_LEN(cmd);
3487 kprintf("ipfw: opcode %d size truncated\n",
3492 DEB(kprintf("ipfw: opcode %d\n", cmd->opcode);)
3494 if (cmd->opcode == O_KEEP_STATE || cmd->opcode == O_LIMIT) {
3495 /* This rule will create states */
3496 *rule_flags |= IPFW_RULE_F_STATE;
3499 switch (cmd->opcode) {
3513 case O_IPPRECEDENCE:
3520 if (cmdlen != F_INSN_SIZE(ipfw_insn))
3532 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32))
3537 if (cmdlen != F_INSN_SIZE(ipfw_insn_limit))
3542 if (cmdlen != F_INSN_SIZE(ipfw_insn_log))
3545 ((ipfw_insn_log *)cmd)->log_left =
3546 ((ipfw_insn_log *)cmd)->max_log;
3552 if (cmdlen != F_INSN_SIZE(ipfw_insn_ip))
3554 if (((ipfw_insn_ip *)cmd)->mask.s_addr == 0) {
3555 kprintf("ipfw: opcode %d, useless rule\n",
3563 if (cmd->arg1 == 0 || cmd->arg1 > 256) {
3564 kprintf("ipfw: invalid set size %d\n",
3568 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
3574 if (cmdlen != F_INSN_SIZE(ipfw_insn_mac))
3580 case O_IP_DSTPORT: /* XXX artificial limit, 30 port pairs */
3581 if (cmdlen < 2 || cmdlen > 31)
3588 if (cmdlen != F_INSN_SIZE(ipfw_insn_if))
3594 if (cmdlen != F_INSN_SIZE(ipfw_insn_pipe))
3599 if (cmdlen != F_INSN_SIZE(ipfw_insn_sa)) {
3604 fwd_addr = ((ipfw_insn_sa *)cmd)->
3606 if (IN_MULTICAST(ntohl(fwd_addr))) {
3607 kprintf("ipfw: try forwarding to "
3608 "multicast address\n");
3614 case O_FORWARD_MAC: /* XXX not implemented yet */
3623 if (cmdlen != F_INSN_SIZE(ipfw_insn))
3627 kprintf("ipfw: opcode %d, multiple actions"
3634 kprintf("ipfw: opcode %d, action must be"
3641 kprintf("ipfw: opcode %d, unknown opcode\n",
3646 if (have_action == 0) {
3647 kprintf("ipfw: missing action\n");
3653 kprintf("ipfw: opcode %d size %d wrong\n",
3654 cmd->opcode, cmdlen);
3659 ipfw_ctl_add_rule(struct sockopt *sopt)
3661 struct ipfw_ioc_rule *ioc_rule;
3663 uint32_t rule_flags;
3666 size = sopt->sopt_valsize;
3667 if (size > (sizeof(uint32_t) * IPFW_RULE_SIZE_MAX) ||
3668 size < sizeof(*ioc_rule)) {
3671 if (size != (sizeof(uint32_t) * IPFW_RULE_SIZE_MAX)) {
3672 sopt->sopt_val = krealloc(sopt->sopt_val, sizeof(uint32_t) *
3673 IPFW_RULE_SIZE_MAX, M_TEMP, M_WAITOK);
3675 ioc_rule = sopt->sopt_val;
3677 error = ipfw_check_ioc_rule(ioc_rule, size, &rule_flags);
3681 ipfw_add_rule(ioc_rule, rule_flags);
3683 if (sopt->sopt_dir == SOPT_GET)
3684 sopt->sopt_valsize = IOC_RULESIZE(ioc_rule);
3689 ipfw_copy_rule(const struct ip_fw *rule, struct ipfw_ioc_rule *ioc_rule)
3691 const struct ip_fw *sibling;
3696 KKASSERT(rule->cpuid == 0);
3698 ioc_rule->act_ofs = rule->act_ofs;
3699 ioc_rule->cmd_len = rule->cmd_len;
3700 ioc_rule->rulenum = rule->rulenum;
3701 ioc_rule->set = rule->set;
3702 ioc_rule->usr_flags = rule->usr_flags;
3704 ioc_rule->set_disable = ipfw_ctx[mycpuid]->ipfw_set_disable;
3705 ioc_rule->static_count = static_count;
3706 ioc_rule->static_len = static_ioc_len;
3709 * Visit (read-only) all of the rule's duplications to get
3710 * the necessary statistics
3717 ioc_rule->timestamp = 0;
3718 for (sibling = rule; sibling != NULL; sibling = sibling->sibling) {
3719 ioc_rule->pcnt += sibling->pcnt;
3720 ioc_rule->bcnt += sibling->bcnt;
3721 if (sibling->timestamp > ioc_rule->timestamp)
3722 ioc_rule->timestamp = sibling->timestamp;
3727 KASSERT(i == ncpus, ("static rule is not duplicated on every cpu\n"));
3729 bcopy(rule->cmd, ioc_rule->cmd, ioc_rule->cmd_len * 4 /* XXX */);
3731 return ((uint8_t *)ioc_rule + IOC_RULESIZE(ioc_rule));
3735 ipfw_copy_state(const ipfw_dyn_rule *dyn_rule,
3736 struct ipfw_ioc_state *ioc_state)
3738 const struct ipfw_flow_id *id;
3739 struct ipfw_ioc_flowid *ioc_id;
3741 ioc_state->expire = TIME_LEQ(dyn_rule->expire, time_second) ?
3742 0 : dyn_rule->expire - time_second;
3743 ioc_state->pcnt = dyn_rule->pcnt;
3744 ioc_state->bcnt = dyn_rule->bcnt;
3746 ioc_state->dyn_type = dyn_rule->dyn_type;
3747 ioc_state->count = dyn_rule->count;
3749 ioc_state->rulenum = dyn_rule->stub->rule[mycpuid]->rulenum;
3752 ioc_id = &ioc_state->id;
3754 ioc_id->type = ETHERTYPE_IP;
3755 ioc_id->u.ip.dst_ip = id->dst_ip;
3756 ioc_id->u.ip.src_ip = id->src_ip;
3757 ioc_id->u.ip.dst_port = id->dst_port;
3758 ioc_id->u.ip.src_port = id->src_port;
3759 ioc_id->u.ip.proto = id->proto;
3763 ipfw_ctl_get_rules(struct sockopt *sopt)
3765 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3769 uint32_t dcount = 0;
3772 * pass up a copy of the current rules. Static rules
3773 * come first (the last of which has number IPFW_DEFAULT_RULE),
3774 * followed by a possibly empty list of dynamic rule.
3778 size = static_ioc_len; /* size of static rules */
3779 if (ipfw_dyn_v) { /* add size of dyn.rules */
3781 size += dcount * sizeof(struct ipfw_ioc_state);
3784 if (sopt->sopt_valsize < size) {
3785 /* short length, no need to return incomplete rules */
3786 /* XXX: if superuser, no need to zero buffer */
3787 bzero(sopt->sopt_val, sopt->sopt_valsize);
3790 bp = sopt->sopt_val;
3792 for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next)
3793 bp = ipfw_copy_rule(rule, bp);
3795 if (ipfw_dyn_v && dcount != 0) {
3796 struct ipfw_ioc_state *ioc_state = bp;
3797 uint32_t dcount2 = 0;
3799 size_t old_size = size;
3803 lockmgr(&dyn_lock, LK_SHARED);
3805 /* Check 'ipfw_dyn_v' again with lock held */
3806 if (ipfw_dyn_v == NULL)
3809 for (i = 0; i < curr_dyn_buckets; i++) {
3813 * The # of dynamic rules may have grown after the
3814 * snapshot of 'dyn_count' was taken, so we will have
3815 * to check 'dcount' (snapshot of dyn_count) here to
3816 * make sure that we don't overflow the pre-allocated
3819 for (p = ipfw_dyn_v[i]; p != NULL && dcount != 0;
3820 p = p->next, ioc_state++, dcount--, dcount2++)
3821 ipfw_copy_state(p, ioc_state);
3824 lockmgr(&dyn_lock, LK_RELEASE);
3827 * The # of dynamic rules may be shrinked after the
3828 * snapshot of 'dyn_count' was taken. To give user a
3829 * correct dynamic rule count, we use the 'dcount2'
3830 * calculated above (with shared lockmgr lock held).
3832 size = static_ioc_len +
3833 (dcount2 * sizeof(struct ipfw_ioc_state));
3834 KKASSERT(size <= old_size);
3839 sopt->sopt_valsize = size;
3844 ipfw_set_disable_dispatch(struct netmsg *nmsg)
3846 struct lwkt_msg *lmsg = &nmsg->nm_lmsg;
3847 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3850 ctx->ipfw_set_disable = lmsg->u.ms_result32;
3852 ifnet_forwardmsg(lmsg, mycpuid + 1);
3856 ipfw_ctl_set_disable(uint32_t disable, uint32_t enable)
3859 struct lwkt_msg *lmsg;
3860 uint32_t set_disable;
3862 /* IPFW_DEFAULT_SET is always enabled */
3863 enable |= (1 << IPFW_DEFAULT_SET);
3864 set_disable = (ipfw_ctx[mycpuid]->ipfw_set_disable | disable) & ~enable;
3866 bzero(&nmsg, sizeof(nmsg));
3867 netmsg_init(&nmsg, &curthread->td_msgport, 0, ipfw_set_disable_dispatch);
3868 lmsg = &nmsg.nm_lmsg;
3869 lmsg->u.ms_result32 = set_disable;
3871 ifnet_domsg(lmsg, 0);
3875 * {set|get}sockopt parser.
3878 ipfw_ctl(struct sockopt *sopt)
3886 switch (sopt->sopt_name) {
3888 error = ipfw_ctl_get_rules(sopt);
3893 * Normally we cannot release the lock on each iteration.
3894 * We could do it here only because we start from the head all
3895 * the times so there is no risk of missing some entries.
3896 * On the other hand, the risk is that we end up with
3897 * a very inconsistent ruleset, so better keep the lock
3898 * around the whole cycle.
3900 * XXX this code can be improved by resetting the head of
3901 * the list to point to the default rule, and then freeing
3902 * the old list without the need for a lock.
3906 ipfw_flush(0 /* keep default rule */);
3911 error = ipfw_ctl_add_rule(sopt);
3916 * IP_FW_DEL is used for deleting single rules or sets,
3917 * and (ab)used to atomically manipulate sets.
3918 * Argument size is used to distinguish between the two:
3920 * delete single rule or set of rules,
3921 * or reassign rules (or sets) to a different set.
3922 * 2 * sizeof(uint32_t)
3923 * atomic disable/enable sets.
3924 * first uint32_t contains sets to be disabled,
3925 * second uint32_t contains sets to be enabled.
3927 masks = sopt->sopt_val;
3928 size = sopt->sopt_valsize;
3929 if (size == sizeof(*masks)) {
3931 * Delete or reassign static rule
3933 error = ipfw_ctl_alter(masks[0]);
3934 } else if (size == (2 * sizeof(*masks))) {
3936 * Set enable/disable
3938 ipfw_ctl_set_disable(masks[0], masks[1]);
3945 case IP_FW_RESETLOG: /* argument is an int, the rule number */
3948 if (sopt->sopt_val != 0) {
3949 error = soopt_to_kbuf(sopt, &rulenum,
3950 sizeof(int), sizeof(int));
3954 error = ipfw_ctl_zero_entry(rulenum,
3955 sopt->sopt_name == IP_FW_RESETLOG);
3959 kprintf("ipfw_ctl invalid option %d\n", sopt->sopt_name);
3966 * This procedure is only used to handle keepalives. It is invoked
3967 * every dyn_keepalive_period
3970 ipfw_tick(void *dummy __unused)
3976 if (ipfw_dyn_v == NULL || dyn_count == 0)
3979 keep_alive = time_second;
3981 lockmgr(&dyn_lock, LK_EXCLUSIVE);
3983 if (ipfw_dyn_v == NULL || dyn_count == 0) {
3984 lockmgr(&dyn_lock, LK_RELEASE);
3987 gen = dyn_buckets_gen;
3989 for (i = 0; i < curr_dyn_buckets; i++) {
3990 ipfw_dyn_rule *q, *prev;
3992 for (prev = NULL, q = ipfw_dyn_v[i]; q != NULL;) {
3993 uint32_t ack_rev, ack_fwd;
3994 struct ipfw_flow_id id;
3996 if (q->dyn_type == O_LIMIT_PARENT)
3999 if (TIME_LEQ(q->expire, time_second)) {
4001 UNLINK_DYN_RULE(prev, ipfw_dyn_v[i], q);
4006 * Keep alive processing
4011 if (q->id.proto != IPPROTO_TCP)
4013 if ((q->state & BOTH_SYN) != BOTH_SYN)
4015 if (TIME_LEQ(time_second + dyn_keepalive_interval,
4017 goto next; /* too early */
4018 if (q->keep_alive == keep_alive)
4019 goto next; /* alreay done */
4022 * Save necessary information, so that they could
4023 * survive after possible blocking in send_pkt()
4026 ack_rev = q->ack_rev;
4027 ack_fwd = q->ack_fwd;
4029 /* Sending has been started */
4030 q->keep_alive = keep_alive;
4032 /* Release lock to avoid possible dead lock */
4033 lockmgr(&dyn_lock, LK_RELEASE);
4034 send_pkt(&id, ack_rev - 1, ack_fwd, TH_SYN);
4035 send_pkt(&id, ack_fwd - 1, ack_rev, 0);
4036 lockmgr(&dyn_lock, LK_EXCLUSIVE);
4038 if (gen != dyn_buckets_gen) {
4040 * Dyn bucket array has been changed during
4041 * the above two sending; reiterate.
4050 lockmgr(&dyn_lock, LK_RELEASE);
4052 callout_reset(&ipfw_timeout_h, dyn_keepalive_period * hz,
4057 ipfw_sysctl_autoinc_step(SYSCTL_HANDLER_ARGS)
4059 return sysctl_int_range(oidp, arg1, arg2, req,
4060 IPFW_AUTOINC_STEP_MIN, IPFW_AUTOINC_STEP_MAX);
4064 ipfw_sysctl_dyn_buckets(SYSCTL_HANDLER_ARGS)
4068 lockmgr(&dyn_lock, LK_EXCLUSIVE);
4070 value = dyn_buckets;
4071 error = sysctl_handle_int(oidp, &value, 0, req);
4072 if (error || !req->newptr)
4076 * Make sure we have a power of 2 and
4077 * do not allow more than 64k entries.
4080 if (value <= 1 || value > 65536)
4082 if ((value & (value - 1)) != 0)
4086 dyn_buckets = value;
4088 lockmgr(&dyn_lock, LK_RELEASE);
4093 ipfw_sysctl_dyn_fin(SYSCTL_HANDLER_ARGS)
4095 return sysctl_int_range(oidp, arg1, arg2, req,
4096 1, dyn_keepalive_period - 1);
4100 ipfw_sysctl_dyn_rst(SYSCTL_HANDLER_ARGS)
4102 return sysctl_int_range(oidp, arg1, arg2, req,
4103 1, dyn_keepalive_period - 1);
4107 ipfw_ctx_init_dispatch(struct netmsg *nmsg)
4109 struct netmsg_ipfw *fwmsg = (struct netmsg_ipfw *)nmsg;
4110 struct ipfw_context *ctx;
4111 struct ip_fw *def_rule;
4113 ctx = kmalloc(sizeof(*ctx), M_IPFW, M_WAITOK | M_ZERO);
4114 ipfw_ctx[mycpuid] = ctx;
4116 def_rule = kmalloc(sizeof(*def_rule), M_IPFW, M_WAITOK | M_ZERO);
4118 def_rule->act_ofs = 0;
4119 def_rule->rulenum = IPFW_DEFAULT_RULE;
4120 def_rule->cmd_len = 1;
4121 def_rule->set = IPFW_DEFAULT_SET;
4123 def_rule->cmd[0].len = 1;
4124 #ifdef IPFIREWALL_DEFAULT_TO_ACCEPT
4125 def_rule->cmd[0].opcode = O_ACCEPT;
4127 def_rule->cmd[0].opcode = O_DENY;
4130 def_rule->refcnt = 1;
4131 def_rule->cpuid = mycpuid;
4133 /* Install the default rule */
4134 ctx->ipfw_default_rule = def_rule;
4135 ctx->ipfw_layer3_chain = def_rule;
4137 /* Link rule CPU sibling */
4138 ipfw_link_sibling(fwmsg, def_rule);
4140 /* Statistics only need to be updated once */
4142 ipfw_inc_static_count(def_rule);
4144 ifnet_forwardmsg(&nmsg->nm_lmsg, mycpuid + 1);
4148 ipfw_init_dispatch(struct netmsg *nmsg)
4150 struct netmsg_ipfw fwmsg;
4156 kprintf("IP firewall already loaded\n");
4161 bzero(&fwmsg, sizeof(fwmsg));
4162 netmsg_init(&fwmsg.nmsg, &curthread->td_msgport, 0,
4163 ipfw_ctx_init_dispatch);
4164 ifnet_domsg(&fwmsg.nmsg.nm_lmsg, 0);
4166 ip_fw_chk_ptr = ipfw_chk;
4167 ip_fw_ctl_ptr = ipfw_ctl;
4168 ip_fw_dn_io_ptr = ipfw_dummynet_io;
4170 kprintf("ipfw2 initialized, divert %s, "
4171 "rule-based forwarding enabled, default to %s, logging ",
4177 ipfw_ctx[mycpuid]->ipfw_default_rule->cmd[0].opcode ==
4178 O_ACCEPT ? "accept" : "deny");
4180 #ifdef IPFIREWALL_VERBOSE
4183 #ifdef IPFIREWALL_VERBOSE_LIMIT
4184 verbose_limit = IPFIREWALL_VERBOSE_LIMIT;
4186 if (fw_verbose == 0) {
4187 kprintf("disabled\n");
4188 } else if (verbose_limit == 0) {
4189 kprintf("unlimited\n");
4191 kprintf("limited to %d packets/entry by default\n",
4195 callout_init(&ipfw_timeout_h);
4196 lockinit(&dyn_lock, "ipfw_dyn", 0, 0);
4199 callout_reset(&ipfw_timeout_h, hz, ipfw_tick, NULL);
4202 lwkt_replymsg(&nmsg->nm_lmsg, error);
4210 netmsg_init(&smsg, &curthread->td_msgport, 0, ipfw_init_dispatch);
4211 return lwkt_domsg(IPFW_CFGPORT, &smsg.nm_lmsg, 0);
4217 ipfw_fini_dispatch(struct netmsg *nmsg)
4223 if (ipfw_refcnt != 0) {
4228 callout_stop(&ipfw_timeout_h);
4231 netmsg_service_sync();
4233 ip_fw_chk_ptr = NULL;
4234 ip_fw_ctl_ptr = NULL;
4235 ip_fw_dn_io_ptr = NULL;
4236 ipfw_flush(1 /* kill default rule */);
4238 /* Free pre-cpu context */
4239 for (cpu = 0; cpu < ncpus; ++cpu)
4240 kfree(ipfw_ctx[cpu], M_IPFW);
4242 kprintf("IP firewall unloaded\n");
4245 lwkt_replymsg(&nmsg->nm_lmsg, error);
4253 netmsg_init(&smsg, &curthread->td_msgport, 0, ipfw_fini_dispatch);
4254 return lwkt_domsg(IPFW_CFGPORT, &smsg.nm_lmsg, 0);
4257 #endif /* KLD_MODULE */
4260 ipfw_modevent(module_t mod, int type, void *unused)
4271 kprintf("ipfw statically compiled, cannot unload\n");
4283 static moduledata_t ipfwmod = {
4288 DECLARE_MODULE(ipfw, ipfwmod, SI_SUB_PROTO_END, SI_ORDER_ANY);
4289 MODULE_VERSION(ipfw, 1);