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.79 2008/09/07 10:03: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 */
1629 int retval = IP_FW_PASS;
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 IP_FW_PASS; /* 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 */
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)
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 */
1802 if (skipto >= IPFW_DEFAULT_RULE)
1803 return IP_FW_DENY; /* invalid */
1805 while (f && f->rulenum <= skipto)
1807 if (f == NULL) /* drop packet */
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 and rule's stats will not beupdated
2192 * ('return IP_FW_DENY').
2194 * O_PROBE_STATE and O_CHECK_STATE: these opcodes
2195 * cause a lookup of the state table, and a jump
2196 * to the 'action' part of the parent rule
2197 * ('goto check_body') if an entry is found, or
2198 * (CHECK_STATE only) a jump to the next rule if
2199 * the entry is not found ('goto next_rule').
2200 * The result of the lookup is cached to make
2201 * further instances of these opcodes are
2202 * effectively NOPs. If static rules are changed
2203 * during the state looking up, the packet will
2204 * be dropped and rule's stats will not be updated
2205 * ('return IP_FW_DENY').
2209 if (!(f->rule_flags & IPFW_RULE_F_STATE)) {
2210 kprintf("%s rule (%d) is not ready "
2212 cmd->opcode == O_LIMIT ?
2213 "limit" : "keep state",
2214 f->rulenum, f->cpuid);
2217 if (install_state(f,
2218 (ipfw_insn_limit *)cmd, args, &deny)) {
2222 retval = IP_FW_DENY;
2223 goto done; /* error/limit violation */
2233 * dynamic rules are checked at the first
2234 * keep-state or check-state occurrence,
2235 * with the result being stored in dyn_dir.
2236 * The compiler introduces a PROBE_STATE
2237 * instruction for us when we have a
2238 * KEEP_STATE (because PROBE_STATE needs
2241 if (dyn_dir == MATCH_UNKNOWN) {
2242 dyn_f = lookup_rule(&args->f_id,
2244 proto == IPPROTO_TCP ?
2245 L3HDR(struct tcphdr, ip) : NULL,
2249 if (dyn_f != NULL) {
2251 * Found a rule from a dynamic
2252 * entry; jump to the 'action'
2256 cmd = ACTION_PTR(f);
2257 l = f->cmd_len - f->act_ofs;
2262 * Dynamic entry not found. If CHECK_STATE,
2263 * skip to next rule, if PROBE_STATE just
2264 * ignore and continue with next opcode.
2266 if (cmd->opcode == O_CHECK_STATE)
2268 else if (!(f->rule_flags & IPFW_RULE_F_STATE))
2269 goto next_rule; /* not ready yet */
2274 retval = IP_FW_PASS; /* accept */
2279 args->rule = f; /* report matching rule */
2280 args->cookie = cmd->arg1;
2281 retval = IP_FW_DUMMYNET;
2286 if (args->eh) /* not on layer 2 */
2289 mtag = m_tag_get(PACKET_TAG_IPFW_DIVERT,
2290 sizeof(*divinfo), MB_DONTWAIT);
2292 retval = IP_FW_DENY;
2295 divinfo = m_tag_data(mtag);
2297 divinfo->skipto = f->rulenum;
2298 divinfo->port = cmd->arg1;
2299 divinfo->tee = (cmd->opcode == O_TEE);
2300 m_tag_prepend(m, mtag);
2302 args->cookie = cmd->arg1;
2303 retval = (cmd->opcode == O_DIVERT) ?
2304 IP_FW_DIVERT : IP_FW_TEE;
2309 f->pcnt++; /* update stats */
2311 f->timestamp = time_second;
2312 if (cmd->opcode == O_COUNT)
2315 if (f->next_rule == NULL)
2316 lookup_next_rule(f);
2322 * Drop the packet and send a reject notice
2323 * if the packet is not ICMP (or is an ICMP
2324 * query), and it is not multicast/broadcast.
2327 (proto != IPPROTO_ICMP ||
2328 is_icmp_query(ip)) &&
2329 !(m->m_flags & (M_BCAST|M_MCAST)) &&
2330 !IN_MULTICAST(ntohl(dst_ip.s_addr))) {
2332 * Update statistics before the possible
2333 * blocking 'send_reject'
2337 f->timestamp = time_second;
2339 send_reject(args, cmd->arg1,
2344 * Return directly here, rule stats
2345 * have been updated above.
2351 retval = IP_FW_DENY;
2355 if (args->eh) /* not valid on layer2 pkts */
2357 if (!dyn_f || dyn_dir == MATCH_FORWARD) {
2358 struct sockaddr_in *sin;
2360 mtag = m_tag_get(PACKET_TAG_IPFORWARD,
2361 sizeof(*sin), MB_DONTWAIT);
2363 retval = IP_FW_DENY;
2366 sin = m_tag_data(mtag);
2368 /* Structure copy */
2369 *sin = ((ipfw_insn_sa *)cmd)->sa;
2371 m_tag_prepend(m, mtag);
2372 m->m_pkthdr.fw_flags |=
2373 IPFORWARD_MBUF_TAGGED;
2375 retval = IP_FW_PASS;
2379 panic("-- unknown opcode %d\n", cmd->opcode);
2380 } /* end of switch() on opcodes */
2382 if (cmd->len & F_NOT)
2386 if (cmd->len & F_OR)
2389 if (!(cmd->len & F_OR)) /* not an OR block, */
2390 break; /* try next rule */
2393 } /* end of inner for, scan opcodes */
2395 next_rule:; /* try next rule */
2397 } /* end of outer for, scan rules */
2398 kprintf("+++ ipfw: ouch!, skip past end of rules, denying packet\n");
2402 /* Update statistics */
2405 f->timestamp = time_second;
2410 kprintf("pullup failed\n");
2415 ipfw_dummynet_io(struct mbuf *m, int pipe_nr, int dir, struct ip_fw_args *fwa)
2420 const struct ipfw_flow_id *id;
2421 struct dn_flow_id *fid;
2425 mtag = m_tag_get(PACKET_TAG_DUMMYNET, sizeof(*pkt), MB_DONTWAIT);
2430 m_tag_prepend(m, mtag);
2432 pkt = m_tag_data(mtag);
2433 bzero(pkt, sizeof(*pkt));
2435 cmd = fwa->rule->cmd + fwa->rule->act_ofs;
2436 if (cmd->opcode == O_LOG)
2438 KASSERT(cmd->opcode == O_PIPE || cmd->opcode == O_QUEUE,
2439 ("Rule is not PIPE or QUEUE, opcode %d\n", cmd->opcode));
2442 pkt->dn_flags = (dir & DN_FLAGS_DIR_MASK);
2443 pkt->ifp = fwa->oif;
2444 pkt->cpuid = mycpu->gd_cpuid;
2445 pkt->pipe_nr = pipe_nr;
2449 fid->fid_dst_ip = id->dst_ip;
2450 fid->fid_src_ip = id->src_ip;
2451 fid->fid_dst_port = id->dst_port;
2452 fid->fid_src_port = id->src_port;
2453 fid->fid_proto = id->proto;
2454 fid->fid_flags = id->flags;
2456 ipfw_ref_rule(fwa->rule);
2457 pkt->dn_priv = fwa->rule;
2458 pkt->dn_unref_priv = ipfw_unref_rule;
2460 if (cmd->opcode == O_PIPE)
2461 pkt->dn_flags |= DN_FLAGS_IS_PIPE;
2463 if (dir == DN_TO_IP_OUT) {
2465 * We need to copy *ro because for ICMP pkts (and maybe
2466 * others) the caller passed a pointer into the stack;
2467 * dst might also be a pointer into *ro so it needs to
2470 pkt->ro = *(fwa->ro);
2472 fwa->ro->ro_rt->rt_refcnt++;
2473 if (fwa->dst == (struct sockaddr_in *)&fwa->ro->ro_dst) {
2474 /* 'dst' points into 'ro' */
2475 fwa->dst = (struct sockaddr_in *)&(pkt->ro.ro_dst);
2477 pkt->dn_dst = fwa->dst;
2478 pkt->flags = fwa->flags;
2481 m->m_pkthdr.fw_flags |= DUMMYNET_MBUF_TAGGED;
2486 * When a rule is added/deleted, clear the next_rule pointers in all rules.
2487 * These will be reconstructed on the fly as packets are matched.
2488 * Must be called at splimp().
2491 ipfw_flush_rule_ptrs(struct ipfw_context *ctx)
2495 for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next)
2496 rule->next_rule = NULL;
2499 static __inline void
2500 ipfw_inc_static_count(struct ip_fw *rule)
2502 KKASSERT(mycpuid == 0);
2505 static_ioc_len += IOC_RULESIZE(rule);
2508 static __inline void
2509 ipfw_dec_static_count(struct ip_fw *rule)
2511 int l = IOC_RULESIZE(rule);
2513 KKASSERT(mycpuid == 0);
2515 KASSERT(static_count > 0, ("invalid static count %u\n", static_count));
2518 KASSERT(static_ioc_len >= l,
2519 ("invalid static len %u\n", static_ioc_len));
2520 static_ioc_len -= l;
2524 ipfw_link_sibling(struct netmsg_ipfw *fwmsg, struct ip_fw *rule)
2526 if (fwmsg->sibling != NULL) {
2527 KKASSERT(mycpuid > 0 && fwmsg->sibling->cpuid == mycpuid - 1);
2528 fwmsg->sibling->sibling = rule;
2530 fwmsg->sibling = rule;
2533 static struct ip_fw *
2534 ipfw_create_rule(const struct ipfw_ioc_rule *ioc_rule, struct ip_fw_stub *stub)
2538 rule = kmalloc(RULESIZE(ioc_rule), M_IPFW, M_WAITOK | M_ZERO);
2540 rule->act_ofs = ioc_rule->act_ofs;
2541 rule->cmd_len = ioc_rule->cmd_len;
2542 rule->rulenum = ioc_rule->rulenum;
2543 rule->set = ioc_rule->set;
2544 rule->usr_flags = ioc_rule->usr_flags;
2546 bcopy(ioc_rule->cmd, rule->cmd, rule->cmd_len * 4 /* XXX */);
2549 rule->cpuid = mycpuid;
2553 stub->rule[mycpuid] = rule;
2559 ipfw_add_rule_dispatch(struct netmsg *nmsg)
2561 struct netmsg_ipfw *fwmsg = (struct netmsg_ipfw *)nmsg;
2562 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2565 rule = ipfw_create_rule(fwmsg->ioc_rule, fwmsg->stub);
2568 * Bump generation after ipfw_create_rule(),
2569 * since this function is blocking
2574 * Insert rule into the pre-determined position
2576 if (fwmsg->prev_rule != NULL) {
2577 struct ip_fw *prev, *next;
2579 prev = fwmsg->prev_rule;
2580 KKASSERT(prev->cpuid == mycpuid);
2582 next = fwmsg->next_rule;
2583 KKASSERT(next->cpuid == mycpuid);
2589 * Move to the position on the next CPU
2590 * before the msg is forwarded.
2592 fwmsg->prev_rule = prev->sibling;
2593 fwmsg->next_rule = next->sibling;
2595 KKASSERT(fwmsg->next_rule == NULL);
2596 rule->next = ctx->ipfw_layer3_chain;
2597 ctx->ipfw_layer3_chain = rule;
2600 /* Link rule CPU sibling */
2601 ipfw_link_sibling(fwmsg, rule);
2603 ipfw_flush_rule_ptrs(ctx);
2606 /* Statistics only need to be updated once */
2607 ipfw_inc_static_count(rule);
2609 /* Return the rule on CPU0 */
2610 nmsg->nm_lmsg.u.ms_resultp = rule;
2613 ifnet_forwardmsg(&nmsg->nm_lmsg, mycpuid + 1);
2617 ipfw_enable_state_dispatch(struct netmsg *nmsg)
2619 struct lwkt_msg *lmsg = &nmsg->nm_lmsg;
2620 struct ip_fw *rule = lmsg->u.ms_resultp;
2622 KKASSERT(rule->cpuid == mycpuid);
2623 KKASSERT(rule->stub != NULL && rule->stub->rule[mycpuid] == rule);
2624 KKASSERT(!(rule->rule_flags & IPFW_RULE_F_STATE));
2625 rule->rule_flags |= IPFW_RULE_F_STATE;
2626 lmsg->u.ms_resultp = rule->sibling;
2628 ifnet_forwardmsg(lmsg, mycpuid + 1);
2632 * Add a new rule to the list. Copy the rule into a malloc'ed area,
2633 * then possibly create a rule number and add the rule to the list.
2634 * Update the rule_number in the input struct so the caller knows
2638 ipfw_add_rule(struct ipfw_ioc_rule *ioc_rule, uint32_t rule_flags)
2640 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2641 struct netmsg_ipfw fwmsg;
2642 struct netmsg *nmsg;
2643 struct ip_fw *f, *prev, *rule;
2644 struct ip_fw_stub *stub;
2646 IPFW_ASSERT_CFGPORT(&curthread->td_msgport);
2651 * If rulenum is 0, find highest numbered rule before the
2652 * default rule, and add rule number incremental step.
2654 if (ioc_rule->rulenum == 0) {
2655 int step = autoinc_step;
2657 KKASSERT(step >= IPFW_AUTOINC_STEP_MIN &&
2658 step <= IPFW_AUTOINC_STEP_MAX);
2661 * Locate the highest numbered rule before default
2663 for (f = ctx->ipfw_layer3_chain; f; f = f->next) {
2664 if (f->rulenum == IPFW_DEFAULT_RULE)
2666 ioc_rule->rulenum = f->rulenum;
2668 if (ioc_rule->rulenum < IPFW_DEFAULT_RULE - step)
2669 ioc_rule->rulenum += step;
2671 KASSERT(ioc_rule->rulenum != IPFW_DEFAULT_RULE &&
2672 ioc_rule->rulenum != 0,
2673 ("invalid rule num %d\n", ioc_rule->rulenum));
2676 * Now find the right place for the new rule in the sorted list.
2678 for (prev = NULL, f = ctx->ipfw_layer3_chain; f;
2679 prev = f, f = f->next) {
2680 if (f->rulenum > ioc_rule->rulenum) {
2681 /* Found the location */
2685 KASSERT(f != NULL, ("no default rule?!\n"));
2687 if (rule_flags & IPFW_RULE_F_STATE) {
2691 * If the new rule will create states, then allocate
2692 * a rule stub, which will be referenced by states
2695 size = sizeof(*stub) + ((ncpus - 1) * sizeof(struct ip_fw *));
2696 stub = kmalloc(size, M_IPFW, M_WAITOK | M_ZERO);
2702 * Duplicate the rule onto each CPU.
2703 * The rule duplicated on CPU0 will be returned.
2705 bzero(&fwmsg, sizeof(fwmsg));
2707 netmsg_init(nmsg, &curthread->td_msgport, 0, ipfw_add_rule_dispatch);
2708 fwmsg.ioc_rule = ioc_rule;
2709 fwmsg.prev_rule = prev;
2710 fwmsg.next_rule = prev == NULL ? NULL : f;
2713 ifnet_domsg(&nmsg->nm_lmsg, 0);
2714 KKASSERT(fwmsg.prev_rule == NULL && fwmsg.next_rule == NULL);
2716 rule = nmsg->nm_lmsg.u.ms_resultp;
2717 KKASSERT(rule != NULL && rule->cpuid == mycpuid);
2719 if (rule_flags & IPFW_RULE_F_STATE) {
2721 * Turn on state flag, _after_ everything on all
2722 * CPUs have been setup.
2724 bzero(nmsg, sizeof(*nmsg));
2725 netmsg_init(nmsg, &curthread->td_msgport, 0,
2726 ipfw_enable_state_dispatch);
2727 nmsg->nm_lmsg.u.ms_resultp = rule;
2729 ifnet_domsg(&nmsg->nm_lmsg, 0);
2730 KKASSERT(nmsg->nm_lmsg.u.ms_resultp == NULL);
2735 DEB(kprintf("++ installed rule %d, static count now %d\n",
2736 rule->rulenum, static_count);)
2740 * Free storage associated with a static rule (including derived
2742 * The caller is in charge of clearing rule pointers to avoid
2743 * dangling pointers.
2744 * @return a pointer to the next entry.
2745 * Arguments are not checked, so they better be correct.
2746 * Must be called at splimp().
2748 static struct ip_fw *
2749 ipfw_delete_rule(struct ipfw_context *ctx,
2750 struct ip_fw *prev, struct ip_fw *rule)
2753 struct ip_fw_stub *stub;
2757 /* STATE flag should have been cleared before we reach here */
2758 KKASSERT((rule->rule_flags & IPFW_RULE_F_STATE) == 0);
2763 ctx->ipfw_layer3_chain = n;
2767 /* Mark the rule as invalid */
2768 rule->rule_flags |= IPFW_RULE_F_INVALID;
2769 rule->next_rule = NULL;
2770 rule->sibling = NULL;
2773 /* Don't reset cpuid here; keep various assertion working */
2777 /* Statistics only need to be updated once */
2779 ipfw_dec_static_count(rule);
2781 /* Free 'stub' on the last CPU */
2782 if (stub != NULL && mycpuid == ncpus - 1)
2783 kfree(stub, M_IPFW);
2785 /* Try to free this rule */
2786 ipfw_free_rule(rule);
2788 /* Return the next rule */
2793 ipfw_flush_dispatch(struct netmsg *nmsg)
2795 struct lwkt_msg *lmsg = &nmsg->nm_lmsg;
2796 int kill_default = lmsg->u.ms_result;
2797 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2800 ipfw_flush_rule_ptrs(ctx); /* more efficient to do outside the loop */
2802 while ((rule = ctx->ipfw_layer3_chain) != NULL &&
2803 (kill_default || rule->rulenum != IPFW_DEFAULT_RULE))
2804 ipfw_delete_rule(ctx, NULL, rule);
2806 ifnet_forwardmsg(lmsg, mycpuid + 1);
2810 ipfw_disable_rule_state_dispatch(struct netmsg *nmsg)
2812 struct netmsg_del *dmsg = (struct netmsg_del *)nmsg;
2815 rule = dmsg->start_rule;
2817 KKASSERT(rule->cpuid == mycpuid);
2820 * Move to the position on the next CPU
2821 * before the msg is forwarded.
2823 dmsg->start_rule = rule->sibling;
2825 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2827 KKASSERT(dmsg->rulenum == 0);
2828 rule = ctx->ipfw_layer3_chain;
2831 while (rule != NULL) {
2832 if (dmsg->rulenum && rule->rulenum != dmsg->rulenum)
2834 rule->rule_flags &= ~IPFW_RULE_F_STATE;
2838 ifnet_forwardmsg(&nmsg->nm_lmsg, mycpuid + 1);
2842 * Deletes all rules from a chain (including the default rule
2843 * if the second argument is set).
2844 * Must be called at splimp().
2847 ipfw_flush(int kill_default)
2849 struct netmsg_del dmsg;
2851 struct lwkt_msg *lmsg;
2853 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2855 IPFW_ASSERT_CFGPORT(&curthread->td_msgport);
2858 * If 'kill_default' then caller has done the necessary
2859 * msgport syncing; unnecessary to do it again.
2861 if (!kill_default) {
2863 * Let ipfw_chk() know the rules are going to
2864 * be flushed, so it could jump directly to
2868 netmsg_service_sync();
2872 * Clear STATE flag on rules, so no more states (dyn rules)
2875 bzero(&dmsg, sizeof(dmsg));
2876 netmsg_init(&dmsg.nmsg, &curthread->td_msgport, 0,
2877 ipfw_disable_rule_state_dispatch);
2878 ifnet_domsg(&dmsg.nmsg.nm_lmsg, 0);
2881 * This actually nukes all states (dyn rules)
2883 lockmgr(&dyn_lock, LK_EXCLUSIVE);
2884 for (rule = ctx->ipfw_layer3_chain; rule != NULL; rule = rule->next) {
2886 * Can't check IPFW_RULE_F_STATE here,
2887 * since it has been cleared previously.
2888 * Check 'stub' instead.
2890 if (rule->stub != NULL) {
2892 remove_dyn_rule_locked(rule, NULL);
2895 lockmgr(&dyn_lock, LK_RELEASE);
2898 * Press the 'flush' button
2900 bzero(&nmsg, sizeof(nmsg));
2901 netmsg_init(&nmsg, &curthread->td_msgport, 0, ipfw_flush_dispatch);
2902 lmsg = &nmsg.nm_lmsg;
2903 lmsg->u.ms_result = kill_default;
2904 ifnet_domsg(lmsg, 0);
2906 KASSERT(dyn_count == 0, ("%u dyn rule remains\n", dyn_count));
2909 if (ipfw_dyn_v != NULL) {
2911 * Free dynamic rules(state) hash table
2913 kfree(ipfw_dyn_v, M_IPFW);
2917 KASSERT(static_count == 0,
2918 ("%u static rules remains\n", static_count));
2919 KASSERT(static_ioc_len == 0,
2920 ("%u bytes of static rules remains\n", static_ioc_len));
2922 KASSERT(static_count == 1,
2923 ("%u static rules remains\n", static_count));
2924 KASSERT(static_ioc_len == IOC_RULESIZE(ctx->ipfw_default_rule),
2925 ("%u bytes of static rules remains, should be %u\n",
2926 static_ioc_len, IOC_RULESIZE(ctx->ipfw_default_rule)));
2934 ipfw_alt_delete_rule_dispatch(struct netmsg *nmsg)
2936 struct netmsg_del *dmsg = (struct netmsg_del *)nmsg;
2937 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2938 struct ip_fw *rule, *prev;
2940 rule = dmsg->start_rule;
2941 KKASSERT(rule->cpuid == mycpuid);
2942 dmsg->start_rule = rule->sibling;
2944 prev = dmsg->prev_rule;
2946 KKASSERT(prev->cpuid == mycpuid);
2949 * Move to the position on the next CPU
2950 * before the msg is forwarded.
2952 dmsg->prev_rule = prev->sibling;
2956 * flush pointers outside the loop, then delete all matching
2957 * rules. 'prev' remains the same throughout the cycle.
2959 ipfw_flush_rule_ptrs(ctx);
2960 while (rule && rule->rulenum == dmsg->rulenum)
2961 rule = ipfw_delete_rule(ctx, prev, rule);
2963 ifnet_forwardmsg(&nmsg->nm_lmsg, mycpuid + 1);
2967 ipfw_alt_delete_rule(uint16_t rulenum)
2969 struct ip_fw *prev, *rule, *f;
2970 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2971 struct netmsg_del dmsg;
2972 struct netmsg *nmsg;
2976 * Locate first rule to delete
2978 for (prev = NULL, rule = ctx->ipfw_layer3_chain;
2979 rule && rule->rulenum < rulenum;
2980 prev = rule, rule = rule->next)
2982 if (rule->rulenum != rulenum)
2986 * Check whether any rules with the given number will
2990 for (f = rule; f && f->rulenum == rulenum; f = f->next) {
2991 if (f->rule_flags & IPFW_RULE_F_STATE) {
2999 * Clear the STATE flag, so no more states will be
3000 * created based the rules numbered 'rulenum'.
3002 bzero(&dmsg, sizeof(dmsg));
3004 netmsg_init(nmsg, &curthread->td_msgport, 0,
3005 ipfw_disable_rule_state_dispatch);
3006 dmsg.start_rule = rule;
3007 dmsg.rulenum = rulenum;
3009 ifnet_domsg(&nmsg->nm_lmsg, 0);
3010 KKASSERT(dmsg.start_rule == NULL);
3013 * Nuke all related states
3015 lockmgr(&dyn_lock, LK_EXCLUSIVE);
3016 for (f = rule; f && f->rulenum == rulenum; f = f->next) {
3018 * Can't check IPFW_RULE_F_STATE here,
3019 * since it has been cleared previously.
3020 * Check 'stub' instead.
3022 if (f->stub != NULL) {
3024 remove_dyn_rule_locked(f, NULL);
3027 lockmgr(&dyn_lock, LK_RELEASE);
3031 * Get rid of the rule duplications on all CPUs
3033 bzero(&dmsg, sizeof(dmsg));
3035 netmsg_init(nmsg, &curthread->td_msgport, 0,
3036 ipfw_alt_delete_rule_dispatch);
3037 dmsg.prev_rule = prev;
3038 dmsg.start_rule = rule;
3039 dmsg.rulenum = rulenum;
3041 ifnet_domsg(&nmsg->nm_lmsg, 0);
3042 KKASSERT(dmsg.prev_rule == NULL && dmsg.start_rule == NULL);
3047 ipfw_alt_delete_ruleset_dispatch(struct netmsg *nmsg)
3049 struct netmsg_del *dmsg = (struct netmsg_del *)nmsg;
3050 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3051 struct ip_fw *prev, *rule;
3056 ipfw_flush_rule_ptrs(ctx);
3059 rule = ctx->ipfw_layer3_chain;
3060 while (rule != NULL) {
3061 if (rule->set == dmsg->from_set) {
3062 rule = ipfw_delete_rule(ctx, prev, rule);
3071 KASSERT(del, ("no match set?!\n"));
3073 ifnet_forwardmsg(&nmsg->nm_lmsg, mycpuid + 1);
3077 ipfw_disable_ruleset_state_dispatch(struct netmsg *nmsg)
3079 struct netmsg_del *dmsg = (struct netmsg_del *)nmsg;
3080 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3086 for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next) {
3087 if (rule->set == dmsg->from_set) {
3091 rule->rule_flags &= ~IPFW_RULE_F_STATE;
3094 KASSERT(cleared, ("no match set?!\n"));
3096 ifnet_forwardmsg(&nmsg->nm_lmsg, mycpuid + 1);
3100 ipfw_alt_delete_ruleset(uint8_t set)
3102 struct netmsg_del dmsg;
3103 struct netmsg *nmsg;
3106 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3109 * Check whether the 'set' exists. If it exists,
3110 * then check whether any rules within the set will
3111 * try to create states.
3115 for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next) {
3116 if (rule->set == set) {
3118 if (rule->rule_flags & IPFW_RULE_F_STATE) {
3125 return 0; /* XXX EINVAL? */
3129 * Clear the STATE flag, so no more states will be
3130 * created based the rules in this set.
3132 bzero(&dmsg, sizeof(dmsg));
3134 netmsg_init(nmsg, &curthread->td_msgport, 0,
3135 ipfw_disable_ruleset_state_dispatch);
3136 dmsg.from_set = set;
3138 ifnet_domsg(&nmsg->nm_lmsg, 0);
3141 * Nuke all related states
3143 lockmgr(&dyn_lock, LK_EXCLUSIVE);
3144 for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next) {
3145 if (rule->set != set)
3149 * Can't check IPFW_RULE_F_STATE here,
3150 * since it has been cleared previously.
3151 * Check 'stub' instead.
3153 if (rule->stub != NULL) {
3155 remove_dyn_rule_locked(rule, NULL);
3158 lockmgr(&dyn_lock, LK_RELEASE);
3164 bzero(&dmsg, sizeof(dmsg));
3166 netmsg_init(nmsg, &curthread->td_msgport, 0,
3167 ipfw_alt_delete_ruleset_dispatch);
3168 dmsg.from_set = set;
3170 ifnet_domsg(&nmsg->nm_lmsg, 0);
3175 ipfw_alt_move_rule_dispatch(struct netmsg *nmsg)
3177 struct netmsg_del *dmsg = (struct netmsg_del *)nmsg;
3180 rule = dmsg->start_rule;
3181 KKASSERT(rule->cpuid == mycpuid);
3184 * Move to the position on the next CPU
3185 * before the msg is forwarded.
3187 dmsg->start_rule = rule->sibling;
3189 while (rule && rule->rulenum <= dmsg->rulenum) {
3190 if (rule->rulenum == dmsg->rulenum)
3191 rule->set = dmsg->to_set;
3194 ifnet_forwardmsg(&nmsg->nm_lmsg, mycpuid + 1);
3198 ipfw_alt_move_rule(uint16_t rulenum, uint8_t set)
3200 struct netmsg_del dmsg;
3201 struct netmsg *nmsg;
3203 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3206 * Locate first rule to move
3208 for (rule = ctx->ipfw_layer3_chain; rule && rule->rulenum <= rulenum;
3209 rule = rule->next) {
3210 if (rule->rulenum == rulenum && rule->set != set)
3213 if (rule == NULL || rule->rulenum > rulenum)
3214 return 0; /* XXX error? */
3216 bzero(&dmsg, sizeof(dmsg));
3218 netmsg_init(nmsg, &curthread->td_msgport, 0,
3219 ipfw_alt_move_rule_dispatch);
3220 dmsg.start_rule = rule;
3221 dmsg.rulenum = rulenum;
3224 ifnet_domsg(&nmsg->nm_lmsg, 0);
3225 KKASSERT(dmsg.start_rule == NULL);
3230 ipfw_alt_move_ruleset_dispatch(struct netmsg *nmsg)
3232 struct netmsg_del *dmsg = (struct netmsg_del *)nmsg;
3233 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3236 for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next) {
3237 if (rule->set == dmsg->from_set)
3238 rule->set = dmsg->to_set;
3240 ifnet_forwardmsg(&nmsg->nm_lmsg, mycpuid + 1);
3244 ipfw_alt_move_ruleset(uint8_t from_set, uint8_t to_set)
3246 struct netmsg_del dmsg;
3247 struct netmsg *nmsg;
3249 bzero(&dmsg, sizeof(dmsg));
3251 netmsg_init(nmsg, &curthread->td_msgport, 0,
3252 ipfw_alt_move_ruleset_dispatch);
3253 dmsg.from_set = from_set;
3254 dmsg.to_set = to_set;
3256 ifnet_domsg(&nmsg->nm_lmsg, 0);
3261 ipfw_alt_swap_ruleset_dispatch(struct netmsg *nmsg)
3263 struct netmsg_del *dmsg = (struct netmsg_del *)nmsg;
3264 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3267 for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next) {
3268 if (rule->set == dmsg->from_set)
3269 rule->set = dmsg->to_set;
3270 else if (rule->set == dmsg->to_set)
3271 rule->set = dmsg->from_set;
3273 ifnet_forwardmsg(&nmsg->nm_lmsg, mycpuid + 1);
3277 ipfw_alt_swap_ruleset(uint8_t set1, uint8_t set2)
3279 struct netmsg_del dmsg;
3280 struct netmsg *nmsg;
3282 bzero(&dmsg, sizeof(dmsg));
3284 netmsg_init(nmsg, &curthread->td_msgport, 0,
3285 ipfw_alt_swap_ruleset_dispatch);
3286 dmsg.from_set = set1;
3289 ifnet_domsg(&nmsg->nm_lmsg, 0);
3294 * Remove all rules with given number, and also do set manipulation.
3296 * The argument is an uint32_t. The low 16 bit are the rule or set number,
3297 * the next 8 bits are the new set, the top 8 bits are the command:
3299 * 0 delete rules with given number
3300 * 1 delete rules with given set number
3301 * 2 move rules with given number to new set
3302 * 3 move rules with given set number to new set
3303 * 4 swap sets with given numbers
3306 ipfw_ctl_alter(uint32_t arg)
3309 uint8_t cmd, new_set;
3312 rulenum = arg & 0xffff;
3313 cmd = (arg >> 24) & 0xff;
3314 new_set = (arg >> 16) & 0xff;
3318 if (new_set >= IPFW_DEFAULT_SET)
3320 if (cmd == 0 || cmd == 2) {
3321 if (rulenum == IPFW_DEFAULT_RULE)
3324 if (rulenum >= IPFW_DEFAULT_SET)
3329 case 0: /* delete rules with given number */
3330 error = ipfw_alt_delete_rule(rulenum);
3333 case 1: /* delete all rules with given set number */
3334 error = ipfw_alt_delete_ruleset(rulenum);
3337 case 2: /* move rules with given number to new set */
3338 error = ipfw_alt_move_rule(rulenum, new_set);
3341 case 3: /* move rules with given set number to new set */
3342 error = ipfw_alt_move_ruleset(rulenum, new_set);
3345 case 4: /* swap two sets */
3346 error = ipfw_alt_swap_ruleset(rulenum, new_set);
3353 * Clear counters for a specific rule.
3356 clear_counters(struct ip_fw *rule, int log_only)
3358 ipfw_insn_log *l = (ipfw_insn_log *)ACTION_PTR(rule);
3360 if (log_only == 0) {
3361 rule->bcnt = rule->pcnt = 0;
3362 rule->timestamp = 0;
3364 if (l->o.opcode == O_LOG)
3365 l->log_left = l->max_log;
3369 ipfw_zero_entry_dispatch(struct netmsg *nmsg)
3371 struct netmsg_zent *zmsg = (struct netmsg_zent *)nmsg;
3372 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3375 if (zmsg->rulenum == 0) {
3376 KKASSERT(zmsg->start_rule == NULL);
3378 ctx->ipfw_norule_counter = 0;
3379 for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next)
3380 clear_counters(rule, zmsg->log_only);
3382 struct ip_fw *start = zmsg->start_rule;
3384 KKASSERT(start->cpuid == mycpuid);
3385 KKASSERT(start->rulenum == zmsg->rulenum);
3388 * We can have multiple rules with the same number, so we
3389 * need to clear them all.
3391 for (rule = start; rule && rule->rulenum == zmsg->rulenum;
3393 clear_counters(rule, zmsg->log_only);
3396 * Move to the position on the next CPU
3397 * before the msg is forwarded.
3399 zmsg->start_rule = start->sibling;
3401 ifnet_forwardmsg(&nmsg->nm_lmsg, mycpuid + 1);
3405 * Reset some or all counters on firewall rules.
3406 * @arg frwl is null to clear all entries, or contains a specific
3408 * @arg log_only is 1 if we only want to reset logs, zero otherwise.
3411 ipfw_ctl_zero_entry(int rulenum, int log_only)
3413 struct netmsg_zent zmsg;
3414 struct netmsg *nmsg;
3416 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3418 bzero(&zmsg, sizeof(zmsg));
3420 netmsg_init(nmsg, &curthread->td_msgport, 0, ipfw_zero_entry_dispatch);
3421 zmsg.log_only = log_only;
3424 msg = log_only ? "ipfw: All logging counts reset.\n"
3425 : "ipfw: Accounting cleared.\n";
3430 * Locate the first rule with 'rulenum'
3432 for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next) {
3433 if (rule->rulenum == rulenum)
3436 if (rule == NULL) /* we did not find any matching rules */
3438 zmsg.start_rule = rule;
3439 zmsg.rulenum = rulenum;
3441 msg = log_only ? "ipfw: Entry %d logging count reset.\n"
3442 : "ipfw: Entry %d cleared.\n";
3444 ifnet_domsg(&nmsg->nm_lmsg, 0);
3445 KKASSERT(zmsg.start_rule == NULL);
3448 log(LOG_SECURITY | LOG_NOTICE, msg, rulenum);
3453 * Check validity of the structure before insert.
3454 * Fortunately rules are simple, so this mostly need to check rule sizes.
3457 ipfw_check_ioc_rule(struct ipfw_ioc_rule *rule, int size, uint32_t *rule_flags)
3460 int have_action = 0;
3465 /* Check for valid size */
3466 if (size < sizeof(*rule)) {
3467 kprintf("ipfw: rule too short\n");
3470 l = IOC_RULESIZE(rule);
3472 kprintf("ipfw: size mismatch (have %d want %d)\n", size, l);
3476 /* Check rule number */
3477 if (rule->rulenum == IPFW_DEFAULT_RULE) {
3478 kprintf("ipfw: invalid rule number\n");
3483 * Now go for the individual checks. Very simple ones, basically only
3484 * instruction sizes.
3486 for (l = rule->cmd_len, cmd = rule->cmd; l > 0;
3487 l -= cmdlen, cmd += cmdlen) {
3488 cmdlen = F_LEN(cmd);
3490 kprintf("ipfw: opcode %d size truncated\n",
3495 DEB(kprintf("ipfw: opcode %d\n", cmd->opcode);)
3497 if (cmd->opcode == O_KEEP_STATE || cmd->opcode == O_LIMIT) {
3498 /* This rule will create states */
3499 *rule_flags |= IPFW_RULE_F_STATE;
3502 switch (cmd->opcode) {
3516 case O_IPPRECEDENCE:
3523 if (cmdlen != F_INSN_SIZE(ipfw_insn))
3535 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32))
3540 if (cmdlen != F_INSN_SIZE(ipfw_insn_limit))
3545 if (cmdlen != F_INSN_SIZE(ipfw_insn_log))
3548 ((ipfw_insn_log *)cmd)->log_left =
3549 ((ipfw_insn_log *)cmd)->max_log;
3555 if (cmdlen != F_INSN_SIZE(ipfw_insn_ip))
3557 if (((ipfw_insn_ip *)cmd)->mask.s_addr == 0) {
3558 kprintf("ipfw: opcode %d, useless rule\n",
3566 if (cmd->arg1 == 0 || cmd->arg1 > 256) {
3567 kprintf("ipfw: invalid set size %d\n",
3571 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
3577 if (cmdlen != F_INSN_SIZE(ipfw_insn_mac))
3583 case O_IP_DSTPORT: /* XXX artificial limit, 30 port pairs */
3584 if (cmdlen < 2 || cmdlen > 31)
3591 if (cmdlen != F_INSN_SIZE(ipfw_insn_if))
3597 if (cmdlen != F_INSN_SIZE(ipfw_insn_pipe))
3602 if (cmdlen != F_INSN_SIZE(ipfw_insn_sa)) {
3607 fwd_addr = ((ipfw_insn_sa *)cmd)->
3609 if (IN_MULTICAST(ntohl(fwd_addr))) {
3610 kprintf("ipfw: try forwarding to "
3611 "multicast address\n");
3617 case O_FORWARD_MAC: /* XXX not implemented yet */
3626 if (cmdlen != F_INSN_SIZE(ipfw_insn))
3630 kprintf("ipfw: opcode %d, multiple actions"
3637 kprintf("ipfw: opcode %d, action must be"
3644 kprintf("ipfw: opcode %d, unknown opcode\n",
3649 if (have_action == 0) {
3650 kprintf("ipfw: missing action\n");
3656 kprintf("ipfw: opcode %d size %d wrong\n",
3657 cmd->opcode, cmdlen);
3662 ipfw_ctl_add_rule(struct sockopt *sopt)
3664 struct ipfw_ioc_rule *ioc_rule;
3666 uint32_t rule_flags;
3669 size = sopt->sopt_valsize;
3670 if (size > (sizeof(uint32_t) * IPFW_RULE_SIZE_MAX) ||
3671 size < sizeof(*ioc_rule)) {
3674 if (size != (sizeof(uint32_t) * IPFW_RULE_SIZE_MAX)) {
3675 sopt->sopt_val = krealloc(sopt->sopt_val, sizeof(uint32_t) *
3676 IPFW_RULE_SIZE_MAX, M_TEMP, M_WAITOK);
3678 ioc_rule = sopt->sopt_val;
3680 error = ipfw_check_ioc_rule(ioc_rule, size, &rule_flags);
3684 ipfw_add_rule(ioc_rule, rule_flags);
3686 if (sopt->sopt_dir == SOPT_GET)
3687 sopt->sopt_valsize = IOC_RULESIZE(ioc_rule);
3692 ipfw_copy_rule(const struct ip_fw *rule, struct ipfw_ioc_rule *ioc_rule)
3694 const struct ip_fw *sibling;
3699 KKASSERT(rule->cpuid == 0);
3701 ioc_rule->act_ofs = rule->act_ofs;
3702 ioc_rule->cmd_len = rule->cmd_len;
3703 ioc_rule->rulenum = rule->rulenum;
3704 ioc_rule->set = rule->set;
3705 ioc_rule->usr_flags = rule->usr_flags;
3707 ioc_rule->set_disable = ipfw_ctx[mycpuid]->ipfw_set_disable;
3708 ioc_rule->static_count = static_count;
3709 ioc_rule->static_len = static_ioc_len;
3712 * Visit (read-only) all of the rule's duplications to get
3713 * the necessary statistics
3720 ioc_rule->timestamp = 0;
3721 for (sibling = rule; sibling != NULL; sibling = sibling->sibling) {
3722 ioc_rule->pcnt += sibling->pcnt;
3723 ioc_rule->bcnt += sibling->bcnt;
3724 if (sibling->timestamp > ioc_rule->timestamp)
3725 ioc_rule->timestamp = sibling->timestamp;
3730 KASSERT(i == ncpus, ("static rule is not duplicated on every cpu\n"));
3732 bcopy(rule->cmd, ioc_rule->cmd, ioc_rule->cmd_len * 4 /* XXX */);
3734 return ((uint8_t *)ioc_rule + IOC_RULESIZE(ioc_rule));
3738 ipfw_copy_state(const ipfw_dyn_rule *dyn_rule,
3739 struct ipfw_ioc_state *ioc_state)
3741 const struct ipfw_flow_id *id;
3742 struct ipfw_ioc_flowid *ioc_id;
3744 ioc_state->expire = TIME_LEQ(dyn_rule->expire, time_second) ?
3745 0 : dyn_rule->expire - time_second;
3746 ioc_state->pcnt = dyn_rule->pcnt;
3747 ioc_state->bcnt = dyn_rule->bcnt;
3749 ioc_state->dyn_type = dyn_rule->dyn_type;
3750 ioc_state->count = dyn_rule->count;
3752 ioc_state->rulenum = dyn_rule->stub->rule[mycpuid]->rulenum;
3755 ioc_id = &ioc_state->id;
3757 ioc_id->type = ETHERTYPE_IP;
3758 ioc_id->u.ip.dst_ip = id->dst_ip;
3759 ioc_id->u.ip.src_ip = id->src_ip;
3760 ioc_id->u.ip.dst_port = id->dst_port;
3761 ioc_id->u.ip.src_port = id->src_port;
3762 ioc_id->u.ip.proto = id->proto;
3766 ipfw_ctl_get_rules(struct sockopt *sopt)
3768 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3772 uint32_t dcount = 0;
3775 * pass up a copy of the current rules. Static rules
3776 * come first (the last of which has number IPFW_DEFAULT_RULE),
3777 * followed by a possibly empty list of dynamic rule.
3781 size = static_ioc_len; /* size of static rules */
3782 if (ipfw_dyn_v) { /* add size of dyn.rules */
3784 size += dcount * sizeof(struct ipfw_ioc_state);
3787 if (sopt->sopt_valsize < size) {
3788 /* short length, no need to return incomplete rules */
3789 /* XXX: if superuser, no need to zero buffer */
3790 bzero(sopt->sopt_val, sopt->sopt_valsize);
3793 bp = sopt->sopt_val;
3795 for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next)
3796 bp = ipfw_copy_rule(rule, bp);
3798 if (ipfw_dyn_v && dcount != 0) {
3799 struct ipfw_ioc_state *ioc_state = bp;
3800 uint32_t dcount2 = 0;
3802 size_t old_size = size;
3806 lockmgr(&dyn_lock, LK_SHARED);
3808 /* Check 'ipfw_dyn_v' again with lock held */
3809 if (ipfw_dyn_v == NULL)
3812 for (i = 0; i < curr_dyn_buckets; i++) {
3816 * The # of dynamic rules may have grown after the
3817 * snapshot of 'dyn_count' was taken, so we will have
3818 * to check 'dcount' (snapshot of dyn_count) here to
3819 * make sure that we don't overflow the pre-allocated
3822 for (p = ipfw_dyn_v[i]; p != NULL && dcount != 0;
3823 p = p->next, ioc_state++, dcount--, dcount2++)
3824 ipfw_copy_state(p, ioc_state);
3827 lockmgr(&dyn_lock, LK_RELEASE);
3830 * The # of dynamic rules may be shrinked after the
3831 * snapshot of 'dyn_count' was taken. To give user a
3832 * correct dynamic rule count, we use the 'dcount2'
3833 * calculated above (with shared lockmgr lock held).
3835 size = static_ioc_len +
3836 (dcount2 * sizeof(struct ipfw_ioc_state));
3837 KKASSERT(size <= old_size);
3842 sopt->sopt_valsize = size;
3847 ipfw_set_disable_dispatch(struct netmsg *nmsg)
3849 struct lwkt_msg *lmsg = &nmsg->nm_lmsg;
3850 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3853 ctx->ipfw_set_disable = lmsg->u.ms_result32;
3855 ifnet_forwardmsg(lmsg, mycpuid + 1);
3859 ipfw_ctl_set_disable(uint32_t disable, uint32_t enable)
3862 struct lwkt_msg *lmsg;
3863 uint32_t set_disable;
3865 /* IPFW_DEFAULT_SET is always enabled */
3866 enable |= (1 << IPFW_DEFAULT_SET);
3867 set_disable = (ipfw_ctx[mycpuid]->ipfw_set_disable | disable) & ~enable;
3869 bzero(&nmsg, sizeof(nmsg));
3870 netmsg_init(&nmsg, &curthread->td_msgport, 0, ipfw_set_disable_dispatch);
3871 lmsg = &nmsg.nm_lmsg;
3872 lmsg->u.ms_result32 = set_disable;
3874 ifnet_domsg(lmsg, 0);
3878 * {set|get}sockopt parser.
3881 ipfw_ctl(struct sockopt *sopt)
3889 switch (sopt->sopt_name) {
3891 error = ipfw_ctl_get_rules(sopt);
3896 * Normally we cannot release the lock on each iteration.
3897 * We could do it here only because we start from the head all
3898 * the times so there is no risk of missing some entries.
3899 * On the other hand, the risk is that we end up with
3900 * a very inconsistent ruleset, so better keep the lock
3901 * around the whole cycle.
3903 * XXX this code can be improved by resetting the head of
3904 * the list to point to the default rule, and then freeing
3905 * the old list without the need for a lock.
3909 ipfw_flush(0 /* keep default rule */);
3914 error = ipfw_ctl_add_rule(sopt);
3919 * IP_FW_DEL is used for deleting single rules or sets,
3920 * and (ab)used to atomically manipulate sets.
3921 * Argument size is used to distinguish between the two:
3923 * delete single rule or set of rules,
3924 * or reassign rules (or sets) to a different set.
3925 * 2 * sizeof(uint32_t)
3926 * atomic disable/enable sets.
3927 * first uint32_t contains sets to be disabled,
3928 * second uint32_t contains sets to be enabled.
3930 masks = sopt->sopt_val;
3931 size = sopt->sopt_valsize;
3932 if (size == sizeof(*masks)) {
3934 * Delete or reassign static rule
3936 error = ipfw_ctl_alter(masks[0]);
3937 } else if (size == (2 * sizeof(*masks))) {
3939 * Set enable/disable
3941 ipfw_ctl_set_disable(masks[0], masks[1]);
3948 case IP_FW_RESETLOG: /* argument is an int, the rule number */
3951 if (sopt->sopt_val != 0) {
3952 error = soopt_to_kbuf(sopt, &rulenum,
3953 sizeof(int), sizeof(int));
3957 error = ipfw_ctl_zero_entry(rulenum,
3958 sopt->sopt_name == IP_FW_RESETLOG);
3962 kprintf("ipfw_ctl invalid option %d\n", sopt->sopt_name);
3969 * This procedure is only used to handle keepalives. It is invoked
3970 * every dyn_keepalive_period
3973 ipfw_tick(void *dummy __unused)
3979 if (ipfw_dyn_v == NULL || dyn_count == 0)
3982 keep_alive = time_second;
3984 lockmgr(&dyn_lock, LK_EXCLUSIVE);
3986 if (ipfw_dyn_v == NULL || dyn_count == 0) {
3987 lockmgr(&dyn_lock, LK_RELEASE);
3990 gen = dyn_buckets_gen;
3992 for (i = 0; i < curr_dyn_buckets; i++) {
3993 ipfw_dyn_rule *q, *prev;
3995 for (prev = NULL, q = ipfw_dyn_v[i]; q != NULL;) {
3996 uint32_t ack_rev, ack_fwd;
3997 struct ipfw_flow_id id;
3999 if (q->dyn_type == O_LIMIT_PARENT)
4002 if (TIME_LEQ(q->expire, time_second)) {
4004 UNLINK_DYN_RULE(prev, ipfw_dyn_v[i], q);
4009 * Keep alive processing
4014 if (q->id.proto != IPPROTO_TCP)
4016 if ((q->state & BOTH_SYN) != BOTH_SYN)
4018 if (TIME_LEQ(time_second + dyn_keepalive_interval,
4020 goto next; /* too early */
4021 if (q->keep_alive == keep_alive)
4022 goto next; /* alreay done */
4025 * Save necessary information, so that they could
4026 * survive after possible blocking in send_pkt()
4029 ack_rev = q->ack_rev;
4030 ack_fwd = q->ack_fwd;
4032 /* Sending has been started */
4033 q->keep_alive = keep_alive;
4035 /* Release lock to avoid possible dead lock */
4036 lockmgr(&dyn_lock, LK_RELEASE);
4037 send_pkt(&id, ack_rev - 1, ack_fwd, TH_SYN);
4038 send_pkt(&id, ack_fwd - 1, ack_rev, 0);
4039 lockmgr(&dyn_lock, LK_EXCLUSIVE);
4041 if (gen != dyn_buckets_gen) {
4043 * Dyn bucket array has been changed during
4044 * the above two sending; reiterate.
4053 lockmgr(&dyn_lock, LK_RELEASE);
4055 callout_reset(&ipfw_timeout_h, dyn_keepalive_period * hz,
4060 ipfw_sysctl_autoinc_step(SYSCTL_HANDLER_ARGS)
4062 return sysctl_int_range(oidp, arg1, arg2, req,
4063 IPFW_AUTOINC_STEP_MIN, IPFW_AUTOINC_STEP_MAX);
4067 ipfw_sysctl_dyn_buckets(SYSCTL_HANDLER_ARGS)
4071 lockmgr(&dyn_lock, LK_EXCLUSIVE);
4073 value = dyn_buckets;
4074 error = sysctl_handle_int(oidp, &value, 0, req);
4075 if (error || !req->newptr)
4079 * Make sure we have a power of 2 and
4080 * do not allow more than 64k entries.
4083 if (value <= 1 || value > 65536)
4085 if ((value & (value - 1)) != 0)
4089 dyn_buckets = value;
4091 lockmgr(&dyn_lock, LK_RELEASE);
4096 ipfw_sysctl_dyn_fin(SYSCTL_HANDLER_ARGS)
4098 return sysctl_int_range(oidp, arg1, arg2, req,
4099 1, dyn_keepalive_period - 1);
4103 ipfw_sysctl_dyn_rst(SYSCTL_HANDLER_ARGS)
4105 return sysctl_int_range(oidp, arg1, arg2, req,
4106 1, dyn_keepalive_period - 1);
4110 ipfw_ctx_init_dispatch(struct netmsg *nmsg)
4112 struct netmsg_ipfw *fwmsg = (struct netmsg_ipfw *)nmsg;
4113 struct ipfw_context *ctx;
4114 struct ip_fw *def_rule;
4116 ctx = kmalloc(sizeof(*ctx), M_IPFW, M_WAITOK | M_ZERO);
4117 ipfw_ctx[mycpuid] = ctx;
4119 def_rule = kmalloc(sizeof(*def_rule), M_IPFW, M_WAITOK | M_ZERO);
4121 def_rule->act_ofs = 0;
4122 def_rule->rulenum = IPFW_DEFAULT_RULE;
4123 def_rule->cmd_len = 1;
4124 def_rule->set = IPFW_DEFAULT_SET;
4126 def_rule->cmd[0].len = 1;
4127 #ifdef IPFIREWALL_DEFAULT_TO_ACCEPT
4128 def_rule->cmd[0].opcode = O_ACCEPT;
4130 def_rule->cmd[0].opcode = O_DENY;
4133 def_rule->refcnt = 1;
4134 def_rule->cpuid = mycpuid;
4136 /* Install the default rule */
4137 ctx->ipfw_default_rule = def_rule;
4138 ctx->ipfw_layer3_chain = def_rule;
4140 /* Link rule CPU sibling */
4141 ipfw_link_sibling(fwmsg, def_rule);
4143 /* Statistics only need to be updated once */
4145 ipfw_inc_static_count(def_rule);
4147 ifnet_forwardmsg(&nmsg->nm_lmsg, mycpuid + 1);
4151 ipfw_init_dispatch(struct netmsg *nmsg)
4153 struct netmsg_ipfw fwmsg;
4159 kprintf("IP firewall already loaded\n");
4164 bzero(&fwmsg, sizeof(fwmsg));
4165 netmsg_init(&fwmsg.nmsg, &curthread->td_msgport, 0,
4166 ipfw_ctx_init_dispatch);
4167 ifnet_domsg(&fwmsg.nmsg.nm_lmsg, 0);
4169 ip_fw_chk_ptr = ipfw_chk;
4170 ip_fw_ctl_ptr = ipfw_ctl;
4171 ip_fw_dn_io_ptr = ipfw_dummynet_io;
4173 kprintf("ipfw2 initialized, divert %s, "
4174 "rule-based forwarding enabled, default to %s, logging ",
4180 ipfw_ctx[mycpuid]->ipfw_default_rule->cmd[0].opcode ==
4181 O_ACCEPT ? "accept" : "deny");
4183 #ifdef IPFIREWALL_VERBOSE
4186 #ifdef IPFIREWALL_VERBOSE_LIMIT
4187 verbose_limit = IPFIREWALL_VERBOSE_LIMIT;
4189 if (fw_verbose == 0) {
4190 kprintf("disabled\n");
4191 } else if (verbose_limit == 0) {
4192 kprintf("unlimited\n");
4194 kprintf("limited to %d packets/entry by default\n",
4198 callout_init(&ipfw_timeout_h);
4199 lockinit(&dyn_lock, "ipfw_dyn", 0, 0);
4202 callout_reset(&ipfw_timeout_h, hz, ipfw_tick, NULL);
4205 lwkt_replymsg(&nmsg->nm_lmsg, error);
4213 netmsg_init(&smsg, &curthread->td_msgport, 0, ipfw_init_dispatch);
4214 return lwkt_domsg(IPFW_CFGPORT, &smsg.nm_lmsg, 0);
4220 ipfw_fini_dispatch(struct netmsg *nmsg)
4226 if (ipfw_refcnt != 0) {
4231 callout_stop(&ipfw_timeout_h);
4234 netmsg_service_sync();
4236 ip_fw_chk_ptr = NULL;
4237 ip_fw_ctl_ptr = NULL;
4238 ip_fw_dn_io_ptr = NULL;
4239 ipfw_flush(1 /* kill default rule */);
4241 /* Free pre-cpu context */
4242 for (cpu = 0; cpu < ncpus; ++cpu)
4243 kfree(ipfw_ctx[cpu], M_IPFW);
4245 kprintf("IP firewall unloaded\n");
4248 lwkt_replymsg(&nmsg->nm_lmsg, error);
4256 netmsg_init(&smsg, &curthread->td_msgport, 0, ipfw_fini_dispatch);
4257 return lwkt_domsg(IPFW_CFGPORT, &smsg.nm_lmsg, 0);
4260 #endif /* KLD_MODULE */
4263 ipfw_modevent(module_t mod, int type, void *unused)
4274 kprintf("ipfw statically compiled, cannot unload\n");
4286 static moduledata_t ipfwmod = {
4291 DECLARE_MODULE(ipfw, ipfwmod, SI_SUB_PROTO_END, SI_ORDER_ANY);
4292 MODULE_VERSION(ipfw, 1);