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.77 2008/08/26 11:42:40 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>
81 #include <netinet/if_ether.h> /* XXX for ETHERTYPE_IP */
84 * Description about per-CPU rule duplication:
86 * Module loading/unloading and all ioctl operations are serialized
87 * by netisr0, so we don't have any ordering or locking problems.
89 * Following graph shows how operation on per-CPU rule list is
90 * performed [2 CPU case]:
94 * netisr0 <------------------------------------+
105 * forwardmsg---------->ifnet1 |
110 * replymsg--------------+
115 * Rules which will not create states (dyn rules) [2 CPU case]
118 * layer3_chain layer3_chain
121 * +-------+ sibling +-------+ sibling
122 * | rule1 |--------->| rule1 |--------->NULL
123 * +-------+ +-------+
127 * +-------+ sibling +-------+ sibling
128 * | rule2 |--------->| rule2 |--------->NULL
129 * +-------+ +-------+
132 * 1) Ease statistics calculation during IP_FW_GET. We only need to
133 * iterate layer3_chain on CPU0; the current rule's duplication on
134 * the other CPUs could safely be read-only accessed by using
136 * 2) Accelerate rule insertion and deletion, e.g. rule insertion:
137 * a) In netisr0 (on CPU0) rule3 is determined to be inserted between
138 * rule1 and rule2. To make this decision we need to iterate the
139 * layer3_chain on CPU0. The netmsg, which is used to insert the
140 * rule, will contain rule1 on CPU0 as prev_rule and rule2 on CPU0
142 * b) After the insertion on CPU0 is done, we will move on to CPU1.
143 * But instead of relocating the rule3's position on CPU1 by
144 * iterating the layer3_chain on CPU1, we set the netmsg's prev_rule
145 * to rule1->sibling and next_rule to rule2->sibling before the
146 * netmsg is forwarded to CPU1 from CPU0
150 * Rules which will create states (dyn rules) [2 CPU case]
151 * (unnecessary parts are omitted; they are same as in the previous figure)
155 * +-------+ +-------+
156 * | rule1 | | rule1 |
157 * +-------+ +-------+
164 * | +--------------------+ |
166 * | | (read-only shared) | |
168 * | | back pointer array | |
169 * | | (indexed by cpuid) | |
171 * +----|---------[0] | |
172 * | [1]--------|----+
174 * +--------------------+
177 * ........|............|............
181 * : +---------+ +---------+ :
182 * : | state1a | | state1b | .... :
183 * : +---------+ +---------+ :
187 * : (protected by dyn_lock) :
188 * ..................................
190 * [state1a and state1b are states created by rule1]
193 * This structure is introduced so that shared (locked) state table could
194 * work with per-CPU (duplicated) static rules. It mainly bridges states
195 * and static rules and serves as static rule's place holder (a read-only
196 * shared part of duplicated rules) from states point of view.
198 * IPFW_RULE_F_STATE (only for rules which create states):
199 * o During rule installation, this flag is turned on after rule's
200 * duplications reach all CPUs, to avoid at least following race:
201 * 1) rule1 is duplicated on CPU0 and is not duplicated on CPU1 yet
202 * 2) rule1 creates state1
203 * 3) state1 is located on CPU1 by check-state
204 * But rule1 is not duplicated on CPU1 yet
205 * o During rule deletion, this flag is turned off before deleting states
206 * created by the rule and before deleting the rule itself, so no
207 * more states will be created by the to-be-deleted rule even when its
208 * duplication on certain CPUs are not eliminated yet.
211 #define IPFW_AUTOINC_STEP_MIN 1
212 #define IPFW_AUTOINC_STEP_MAX 1000
213 #define IPFW_AUTOINC_STEP_DEF 100
215 #define IPFW_DEFAULT_RULE 65535 /* rulenum for the default rule */
216 #define IPFW_DEFAULT_SET 31 /* set number for the default rule */
220 const struct ipfw_ioc_rule *ioc_rule;
221 struct ip_fw *next_rule;
222 struct ip_fw *prev_rule;
223 struct ip_fw *sibling;
224 struct ip_fw_stub *stub;
229 struct ip_fw *start_rule;
230 struct ip_fw *prev_rule;
238 struct ip_fw *start_rule;
243 struct ipfw_context {
244 struct ip_fw *ipfw_layer3_chain; /* list of rules for layer3 */
245 struct ip_fw *ipfw_default_rule; /* default rule */
246 uint64_t ipfw_norule_counter; /* counter for ipfw_log(NULL) */
249 * ipfw_set_disable contains one bit per set value (0..31).
250 * If the bit is set, all rules with the corresponding set
251 * are disabled. Set IPDW_DEFAULT_SET is reserved for the
252 * default rule and CANNOT be disabled.
254 uint32_t ipfw_set_disable;
255 uint32_t ipfw_gen; /* generation of rule list */
258 static struct ipfw_context *ipfw_ctx[MAXCPU];
262 * Module can not be unloaded, if there are references to
263 * certains rules of ipfw(4), e.g. dummynet(4)
265 static int ipfw_refcnt;
268 MALLOC_DEFINE(M_IPFW, "IpFw/IpAcct", "IpFw/IpAcct chain's");
271 * Following two global variables are accessed and
272 * updated only on CPU0
274 static uint32_t static_count; /* # of static rules */
275 static uint32_t static_ioc_len; /* bytes of static rules */
278 * If 1, then ipfw static rules are being flushed,
279 * ipfw_chk() will skip to the default rule.
281 static int ipfw_flushing;
283 static int fw_verbose;
284 static int verbose_limit;
286 static int fw_debug = 1;
287 static int autoinc_step = IPFW_AUTOINC_STEP_DEF;
289 static int ipfw_sysctl_autoinc_step(SYSCTL_HANDLER_ARGS);
290 static int ipfw_sysctl_dyn_buckets(SYSCTL_HANDLER_ARGS);
291 static int ipfw_sysctl_dyn_fin(SYSCTL_HANDLER_ARGS);
292 static int ipfw_sysctl_dyn_rst(SYSCTL_HANDLER_ARGS);
295 SYSCTL_NODE(_net_inet_ip, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall");
296 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, enable, CTLFLAG_RW,
297 &fw_enable, 0, "Enable ipfw");
298 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, autoinc_step, CTLTYPE_INT | CTLFLAG_RW,
299 &autoinc_step, 0, ipfw_sysctl_autoinc_step, "I",
300 "Rule number autincrement step");
301 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO,one_pass,CTLFLAG_RW,
303 "Only do a single pass through ipfw when using dummynet(4)");
304 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, debug, CTLFLAG_RW,
305 &fw_debug, 0, "Enable printing of debug ip_fw statements");
306 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose, CTLFLAG_RW,
307 &fw_verbose, 0, "Log matches to ipfw rules");
308 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose_limit, CTLFLAG_RW,
309 &verbose_limit, 0, "Set upper limit of matches of ipfw rules logged");
312 * Description of dynamic rules.
314 * Dynamic rules are stored in lists accessed through a hash table
315 * (ipfw_dyn_v) whose size is curr_dyn_buckets. This value can
316 * be modified through the sysctl variable dyn_buckets which is
317 * updated when the table becomes empty.
319 * XXX currently there is only one list, ipfw_dyn.
321 * When a packet is received, its address fields are first masked
322 * with the mask defined for the rule, then hashed, then matched
323 * against the entries in the corresponding list.
324 * Dynamic rules can be used for different purposes:
326 * + enforcing limits on the number of sessions;
327 * + in-kernel NAT (not implemented yet)
329 * The lifetime of dynamic rules is regulated by dyn_*_lifetime,
330 * measured in seconds and depending on the flags.
332 * The total number of dynamic rules is stored in dyn_count.
333 * The max number of dynamic rules is dyn_max. When we reach
334 * the maximum number of rules we do not create anymore. This is
335 * done to avoid consuming too much memory, but also too much
336 * time when searching on each packet (ideally, we should try instead
337 * to put a limit on the length of the list on each bucket...).
339 * Each dynamic rule holds a pointer to the parent ipfw rule so
340 * we know what action to perform. Dynamic rules are removed when
341 * the parent rule is deleted. XXX we should make them survive.
343 * There are some limitations with dynamic rules -- we do not
344 * obey the 'randomized match', and we do not do multiple
345 * passes through the firewall. XXX check the latter!!!
347 * NOTE about the SHARED LOCKMGR LOCK during dynamic rule looking up:
348 * Only TCP state transition will change dynamic rule's state and ack
349 * sequences, while all packets of one TCP connection only goes through
350 * one TCP thread, so it is safe to use shared lockmgr lock during dynamic
351 * rule looking up. The keep alive callout uses exclusive lockmgr lock
352 * when it tries to find suitable dynamic rules to send keep alive, so
353 * it will not see half updated state and ack sequences. Though the expire
354 * field updating looks racy for other protocols, the resolution (second)
355 * of expire field makes this kind of race harmless.
356 * XXX statistics' updating is _not_ MPsafe!!!
357 * XXX once UDP output path is fixed, we could use lockless dynamic rule
360 static ipfw_dyn_rule **ipfw_dyn_v = NULL;
361 static uint32_t dyn_buckets = 256; /* must be power of 2 */
362 static uint32_t curr_dyn_buckets = 256; /* must be power of 2 */
363 static uint32_t dyn_buckets_gen; /* generation of dyn buckets array */
364 static struct lock dyn_lock; /* dynamic rules' hash table lock */
365 static struct callout ipfw_timeout_h;
368 * Timeouts for various events in handing dynamic rules.
370 static uint32_t dyn_ack_lifetime = 300;
371 static uint32_t dyn_syn_lifetime = 20;
372 static uint32_t dyn_fin_lifetime = 1;
373 static uint32_t dyn_rst_lifetime = 1;
374 static uint32_t dyn_udp_lifetime = 10;
375 static uint32_t dyn_short_lifetime = 5;
378 * Keepalives are sent if dyn_keepalive is set. They are sent every
379 * dyn_keepalive_period seconds, in the last dyn_keepalive_interval
380 * seconds of lifetime of a rule.
381 * dyn_rst_lifetime and dyn_fin_lifetime should be strictly lower
382 * than dyn_keepalive_period.
385 static uint32_t dyn_keepalive_interval = 20;
386 static uint32_t dyn_keepalive_period = 5;
387 static uint32_t dyn_keepalive = 1; /* do send keepalives */
389 static uint32_t dyn_count; /* # of dynamic rules */
390 static uint32_t dyn_max = 4096; /* max # of dynamic rules */
392 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, dyn_buckets, CTLTYPE_INT | CTLFLAG_RW,
393 &dyn_buckets, 0, ipfw_sysctl_dyn_buckets, "I", "Number of dyn. buckets");
394 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, curr_dyn_buckets, CTLFLAG_RD,
395 &curr_dyn_buckets, 0, "Current Number of dyn. buckets");
396 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_count, CTLFLAG_RD,
397 &dyn_count, 0, "Number of dyn. rules");
398 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_max, CTLFLAG_RW,
399 &dyn_max, 0, "Max number of dyn. rules");
400 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, static_count, CTLFLAG_RD,
401 &static_count, 0, "Number of static rules");
402 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_ack_lifetime, CTLFLAG_RW,
403 &dyn_ack_lifetime, 0, "Lifetime of dyn. rules for acks");
404 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_syn_lifetime, CTLFLAG_RW,
405 &dyn_syn_lifetime, 0, "Lifetime of dyn. rules for syn");
406 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, dyn_fin_lifetime,
407 CTLTYPE_INT | CTLFLAG_RW, &dyn_fin_lifetime, 0, ipfw_sysctl_dyn_fin, "I",
408 "Lifetime of dyn. rules for fin");
409 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, dyn_rst_lifetime,
410 CTLTYPE_INT | CTLFLAG_RW, &dyn_rst_lifetime, 0, ipfw_sysctl_dyn_rst, "I",
411 "Lifetime of dyn. rules for rst");
412 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_udp_lifetime, CTLFLAG_RW,
413 &dyn_udp_lifetime, 0, "Lifetime of dyn. rules for UDP");
414 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_short_lifetime, CTLFLAG_RW,
415 &dyn_short_lifetime, 0, "Lifetime of dyn. rules for other situations");
416 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_keepalive, CTLFLAG_RW,
417 &dyn_keepalive, 0, "Enable keepalives for dyn. rules");
419 #endif /* SYSCTL_NODE */
421 static ip_fw_chk_t ipfw_chk;
424 ipfw_free_rule(struct ip_fw *rule)
426 KASSERT(rule->cpuid == mycpuid, ("rule freed on cpu%d\n", mycpuid));
427 KASSERT(rule->refcnt > 0, ("invalid refcnt %u\n", rule->refcnt));
429 if (rule->refcnt == 0) {
437 ipfw_unref_rule(void *priv)
439 ipfw_free_rule(priv);
441 atomic_subtract_int(&ipfw_refcnt, 1);
446 ipfw_ref_rule(struct ip_fw *rule)
448 KASSERT(rule->cpuid == mycpuid, ("rule used on cpu%d\n", mycpuid));
450 atomic_add_int(&ipfw_refcnt, 1);
456 * This macro maps an ip pointer into a layer3 header pointer of type T
458 #define L3HDR(T, ip) ((T *)((uint32_t *)(ip) + (ip)->ip_hl))
461 icmptype_match(struct ip *ip, ipfw_insn_u32 *cmd)
463 int type = L3HDR(struct icmp,ip)->icmp_type;
465 return (type <= ICMP_MAXTYPE && (cmd->d[0] & (1 << type)));
468 #define TT ((1 << ICMP_ECHO) | \
469 (1 << ICMP_ROUTERSOLICIT) | \
470 (1 << ICMP_TSTAMP) | \
475 is_icmp_query(struct ip *ip)
477 int type = L3HDR(struct icmp, ip)->icmp_type;
479 return (type <= ICMP_MAXTYPE && (TT & (1 << type)));
485 * The following checks use two arrays of 8 or 16 bits to store the
486 * bits that we want set or clear, respectively. They are in the
487 * low and high half of cmd->arg1 or cmd->d[0].
489 * We scan options and store the bits we find set. We succeed if
491 * (want_set & ~bits) == 0 && (want_clear & ~bits) == want_clear
493 * The code is sometimes optimized not to store additional variables.
497 flags_match(ipfw_insn *cmd, uint8_t bits)
502 if (((cmd->arg1 & 0xff) & bits) != 0)
503 return 0; /* some bits we want set were clear */
505 want_clear = (cmd->arg1 >> 8) & 0xff;
506 if ((want_clear & bits) != want_clear)
507 return 0; /* some bits we want clear were set */
512 ipopts_match(struct ip *ip, ipfw_insn *cmd)
514 int optlen, bits = 0;
515 u_char *cp = (u_char *)(ip + 1);
516 int x = (ip->ip_hl << 2) - sizeof(struct ip);
518 for (; x > 0; x -= optlen, cp += optlen) {
519 int opt = cp[IPOPT_OPTVAL];
521 if (opt == IPOPT_EOL)
524 if (opt == IPOPT_NOP) {
527 optlen = cp[IPOPT_OLEN];
528 if (optlen <= 0 || optlen > x)
529 return 0; /* invalid or truncated */
534 bits |= IP_FW_IPOPT_LSRR;
538 bits |= IP_FW_IPOPT_SSRR;
542 bits |= IP_FW_IPOPT_RR;
546 bits |= IP_FW_IPOPT_TS;
553 return (flags_match(cmd, bits));
557 tcpopts_match(struct ip *ip, ipfw_insn *cmd)
559 int optlen, bits = 0;
560 struct tcphdr *tcp = L3HDR(struct tcphdr,ip);
561 u_char *cp = (u_char *)(tcp + 1);
562 int x = (tcp->th_off << 2) - sizeof(struct tcphdr);
564 for (; x > 0; x -= optlen, cp += optlen) {
567 if (opt == TCPOPT_EOL)
570 if (opt == TCPOPT_NOP) {
580 bits |= IP_FW_TCPOPT_MSS;
584 bits |= IP_FW_TCPOPT_WINDOW;
587 case TCPOPT_SACK_PERMITTED:
589 bits |= IP_FW_TCPOPT_SACK;
592 case TCPOPT_TIMESTAMP:
593 bits |= IP_FW_TCPOPT_TS;
599 bits |= IP_FW_TCPOPT_CC;
606 return (flags_match(cmd, bits));
610 iface_match(struct ifnet *ifp, ipfw_insn_if *cmd)
612 if (ifp == NULL) /* no iface with this packet, match fails */
615 /* Check by name or by IP address */
616 if (cmd->name[0] != '\0') { /* match by name */
619 if (kfnmatch(cmd->name, ifp->if_xname, 0) == 0)
622 if (strncmp(ifp->if_xname, cmd->name, IFNAMSIZ) == 0)
626 struct ifaddr_container *ifac;
628 TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
629 struct ifaddr *ia = ifac->ifa;
631 if (ia->ifa_addr == NULL)
633 if (ia->ifa_addr->sa_family != AF_INET)
635 if (cmd->p.ip.s_addr == ((struct sockaddr_in *)
636 (ia->ifa_addr))->sin_addr.s_addr)
637 return(1); /* match */
640 return(0); /* no match, fail ... */
643 #define SNPARGS(buf, len) buf + len, sizeof(buf) > len ? sizeof(buf) - len : 0
646 * We enter here when we have a rule with O_LOG.
647 * XXX this function alone takes about 2Kbytes of code!
650 ipfw_log(struct ip_fw *f, u_int hlen, struct ether_header *eh,
651 struct mbuf *m, struct ifnet *oif)
654 int limit_reached = 0;
655 char action2[40], proto[48], fragment[28];
660 if (f == NULL) { /* bogus pkt */
661 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
663 if (verbose_limit != 0 &&
664 ctx->ipfw_norule_counter >= verbose_limit)
666 ctx->ipfw_norule_counter++;
667 if (ctx->ipfw_norule_counter == verbose_limit)
668 limit_reached = verbose_limit;
670 } else { /* O_LOG is the first action, find the real one */
671 ipfw_insn *cmd = ACTION_PTR(f);
672 ipfw_insn_log *l = (ipfw_insn_log *)cmd;
674 if (l->max_log != 0 && l->log_left == 0)
677 if (l->log_left == 0)
678 limit_reached = l->max_log;
679 cmd += F_LEN(cmd); /* point to first action */
680 if (cmd->opcode == O_PROB)
684 switch (cmd->opcode) {
690 if (cmd->arg1==ICMP_REJECT_RST) {
692 } else if (cmd->arg1==ICMP_UNREACH_HOST) {
695 ksnprintf(SNPARGS(action2, 0), "Unreach %d",
709 ksnprintf(SNPARGS(action2, 0), "Divert %d", cmd->arg1);
713 ksnprintf(SNPARGS(action2, 0), "Tee %d", cmd->arg1);
717 ksnprintf(SNPARGS(action2, 0), "SkipTo %d", cmd->arg1);
721 ksnprintf(SNPARGS(action2, 0), "Pipe %d", cmd->arg1);
725 ksnprintf(SNPARGS(action2, 0), "Queue %d", cmd->arg1);
730 ipfw_insn_sa *sa = (ipfw_insn_sa *)cmd;
733 len = ksnprintf(SNPARGS(action2, 0),
735 inet_ntoa(sa->sa.sin_addr));
736 if (sa->sa.sin_port) {
737 ksnprintf(SNPARGS(action2, len), ":%d",
749 if (hlen == 0) { /* non-ip */
750 ksnprintf(SNPARGS(proto, 0), "MAC");
752 struct ip *ip = mtod(m, struct ip *);
753 /* these three are all aliases to the same thing */
754 struct icmp *const icmp = L3HDR(struct icmp, ip);
755 struct tcphdr *const tcp = (struct tcphdr *)icmp;
756 struct udphdr *const udp = (struct udphdr *)icmp;
758 int ip_off, offset, ip_len;
761 if (eh != NULL) { /* layer 2 packets are as on the wire */
762 ip_off = ntohs(ip->ip_off);
763 ip_len = ntohs(ip->ip_len);
768 offset = ip_off & IP_OFFMASK;
771 len = ksnprintf(SNPARGS(proto, 0), "TCP %s",
772 inet_ntoa(ip->ip_src));
774 ksnprintf(SNPARGS(proto, len), ":%d %s:%d",
775 ntohs(tcp->th_sport),
776 inet_ntoa(ip->ip_dst),
777 ntohs(tcp->th_dport));
779 ksnprintf(SNPARGS(proto, len), " %s",
780 inet_ntoa(ip->ip_dst));
785 len = ksnprintf(SNPARGS(proto, 0), "UDP %s",
786 inet_ntoa(ip->ip_src));
788 ksnprintf(SNPARGS(proto, len), ":%d %s:%d",
789 ntohs(udp->uh_sport),
790 inet_ntoa(ip->ip_dst),
791 ntohs(udp->uh_dport));
793 ksnprintf(SNPARGS(proto, len), " %s",
794 inet_ntoa(ip->ip_dst));
800 len = ksnprintf(SNPARGS(proto, 0),
805 len = ksnprintf(SNPARGS(proto, 0), "ICMP ");
807 len += ksnprintf(SNPARGS(proto, len), "%s",
808 inet_ntoa(ip->ip_src));
809 ksnprintf(SNPARGS(proto, len), " %s",
810 inet_ntoa(ip->ip_dst));
814 len = ksnprintf(SNPARGS(proto, 0), "P:%d %s", ip->ip_p,
815 inet_ntoa(ip->ip_src));
816 ksnprintf(SNPARGS(proto, len), " %s",
817 inet_ntoa(ip->ip_dst));
821 if (ip_off & (IP_MF | IP_OFFMASK)) {
822 ksnprintf(SNPARGS(fragment, 0), " (frag %d:%d@%d%s)",
823 ntohs(ip->ip_id), ip_len - (ip->ip_hl << 2),
824 offset << 3, (ip_off & IP_MF) ? "+" : "");
828 if (oif || m->m_pkthdr.rcvif) {
829 log(LOG_SECURITY | LOG_INFO,
830 "ipfw: %d %s %s %s via %s%s\n",
832 action, proto, oif ? "out" : "in",
833 oif ? oif->if_xname : m->m_pkthdr.rcvif->if_xname,
836 log(LOG_SECURITY | LOG_INFO,
837 "ipfw: %d %s %s [no if info]%s\n",
839 action, proto, fragment);
843 log(LOG_SECURITY | LOG_NOTICE,
844 "ipfw: limit %d reached on entry %d\n",
845 limit_reached, f ? f->rulenum : -1);
852 * IMPORTANT: the hash function for dynamic rules must be commutative
853 * in source and destination (ip,port), because rules are bidirectional
854 * and we want to find both in the same bucket.
857 hash_packet(struct ipfw_flow_id *id)
861 i = (id->dst_ip) ^ (id->src_ip) ^ (id->dst_port) ^ (id->src_port);
862 i &= (curr_dyn_buckets - 1);
867 * unlink a dynamic rule from a chain. prev is a pointer to
868 * the previous one, q is a pointer to the rule to delete,
869 * head is a pointer to the head of the queue.
870 * Modifies q and potentially also head.
872 #define UNLINK_DYN_RULE(prev, head, q) \
874 ipfw_dyn_rule *old_q = q; \
876 /* remove a refcount to the parent */ \
877 if (q->dyn_type == O_LIMIT) \
878 q->parent->count--; \
879 DEB(kprintf("-- unlink entry 0x%08x %d -> 0x%08x %d, %d left\n", \
880 (q->id.src_ip), (q->id.src_port), \
881 (q->id.dst_ip), (q->id.dst_port), dyn_count-1 ); ) \
883 prev->next = q = q->next; \
885 head = q = q->next; \
886 KASSERT(dyn_count > 0, ("invalid dyn count %u\n", dyn_count)); \
888 kfree(old_q, M_IPFW); \
891 #define TIME_LEQ(a, b) ((int)((a) - (b)) <= 0)
894 * Remove dynamic rules pointing to "rule", or all of them if rule == NULL.
896 * If keep_me == NULL, rules are deleted even if not expired,
897 * otherwise only expired rules are removed.
899 * The value of the second parameter is also used to point to identify
900 * a rule we absolutely do not want to remove (e.g. because we are
901 * holding a reference to it -- this is the case with O_LIMIT_PARENT
902 * rules). The pointer is only used for comparison, so any non-null
906 remove_dyn_rule_locked(struct ip_fw *rule, ipfw_dyn_rule *keep_me)
908 static uint32_t last_remove = 0; /* XXX */
910 #define FORCE (keep_me == NULL)
912 ipfw_dyn_rule *prev, *q;
913 int i, pass = 0, max_pass = 0, unlinked = 0;
915 if (ipfw_dyn_v == NULL || dyn_count == 0)
917 /* do not expire more than once per second, it is useless */
918 if (!FORCE && last_remove == time_second)
920 last_remove = time_second;
923 * because O_LIMIT refer to parent rules, during the first pass only
924 * remove child and mark any pending LIMIT_PARENT, and remove
925 * them in a second pass.
928 for (i = 0; i < curr_dyn_buckets; i++) {
929 for (prev = NULL, q = ipfw_dyn_v[i]; q;) {
931 * Logic can become complex here, so we split tests.
935 if (rule != NULL && rule->stub != q->stub)
936 goto next; /* not the one we are looking for */
937 if (q->dyn_type == O_LIMIT_PARENT) {
939 * handle parent in the second pass,
940 * record we need one.
945 if (FORCE && q->count != 0) {
946 /* XXX should not happen! */
947 kprintf("OUCH! cannot remove rule, "
948 "count %d\n", q->count);
951 if (!FORCE && !TIME_LEQ(q->expire, time_second))
955 UNLINK_DYN_RULE(prev, ipfw_dyn_v[i], q);
962 if (pass++ < max_pass)
972 * lookup a dynamic rule.
974 static ipfw_dyn_rule *
975 lookup_dyn_rule(struct ipfw_flow_id *pkt, int *match_direction,
979 * stateful ipfw extensions.
980 * Lookup into dynamic session queue
982 #define MATCH_REVERSE 0
983 #define MATCH_FORWARD 1
985 #define MATCH_UNKNOWN 3
986 int i, dir = MATCH_NONE;
987 ipfw_dyn_rule *prev, *q=NULL;
989 if (ipfw_dyn_v == NULL)
990 goto done; /* not found */
992 i = hash_packet(pkt);
993 for (prev = NULL, q = ipfw_dyn_v[i]; q != NULL;) {
994 if (q->dyn_type == O_LIMIT_PARENT)
997 if (TIME_LEQ(q->expire, time_second)) {
999 * Entry expired; skip.
1000 * Let ipfw_tick() take care of it
1005 if (pkt->proto == q->id.proto) {
1006 if (pkt->src_ip == q->id.src_ip &&
1007 pkt->dst_ip == q->id.dst_ip &&
1008 pkt->src_port == q->id.src_port &&
1009 pkt->dst_port == q->id.dst_port) {
1010 dir = MATCH_FORWARD;
1013 if (pkt->src_ip == q->id.dst_ip &&
1014 pkt->dst_ip == q->id.src_ip &&
1015 pkt->src_port == q->id.dst_port &&
1016 pkt->dst_port == q->id.src_port) {
1017 dir = MATCH_REVERSE;
1026 goto done; /* q = NULL, not found */
1028 if (pkt->proto == IPPROTO_TCP) { /* update state according to flags */
1029 u_char flags = pkt->flags & (TH_FIN|TH_SYN|TH_RST);
1031 #define BOTH_SYN (TH_SYN | (TH_SYN << 8))
1032 #define BOTH_FIN (TH_FIN | (TH_FIN << 8))
1034 q->state |= (dir == MATCH_FORWARD ) ? flags : (flags << 8);
1036 case TH_SYN: /* opening */
1037 q->expire = time_second + dyn_syn_lifetime;
1040 case BOTH_SYN: /* move to established */
1041 case BOTH_SYN | TH_FIN : /* one side tries to close */
1042 case BOTH_SYN | (TH_FIN << 8) :
1044 uint32_t ack = ntohl(tcp->th_ack);
1046 #define _SEQ_GE(a, b) ((int)(a) - (int)(b) >= 0)
1048 if (dir == MATCH_FORWARD) {
1049 if (q->ack_fwd == 0 ||
1050 _SEQ_GE(ack, q->ack_fwd))
1052 else /* ignore out-of-sequence */
1055 if (q->ack_rev == 0 ||
1056 _SEQ_GE(ack, q->ack_rev))
1058 else /* ignore out-of-sequence */
1063 q->expire = time_second + dyn_ack_lifetime;
1066 case BOTH_SYN | BOTH_FIN: /* both sides closed */
1067 KKASSERT(dyn_fin_lifetime < dyn_keepalive_period);
1068 q->expire = time_second + dyn_fin_lifetime;
1074 * reset or some invalid combination, but can also
1075 * occur if we use keep-state the wrong way.
1077 if ((q->state & ((TH_RST << 8) | TH_RST)) == 0)
1078 kprintf("invalid state: 0x%x\n", q->state);
1080 KKASSERT(dyn_rst_lifetime < dyn_keepalive_period);
1081 q->expire = time_second + dyn_rst_lifetime;
1084 } else if (pkt->proto == IPPROTO_UDP) {
1085 q->expire = time_second + dyn_udp_lifetime;
1087 /* other protocols */
1088 q->expire = time_second + dyn_short_lifetime;
1091 if (match_direction)
1092 *match_direction = dir;
1096 static struct ip_fw *
1097 lookup_rule(struct ipfw_flow_id *pkt, int *match_direction, struct tcphdr *tcp,
1098 uint16_t len, int *deny)
1100 struct ip_fw *rule = NULL;
1102 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
1106 gen = ctx->ipfw_gen;
1108 lockmgr(&dyn_lock, LK_SHARED);
1110 if (ctx->ipfw_gen != gen) {
1112 * Static rules had been change when we were waiting
1113 * for the dynamic hash table lock; deny this packet,
1114 * since it is _not_ known whether it is safe to keep
1115 * iterating the static rules.
1121 q = lookup_dyn_rule(pkt, match_direction, tcp);
1125 rule = q->stub->rule[mycpuid];
1126 KKASSERT(rule->stub == q->stub && rule->cpuid == mycpuid);
1133 lockmgr(&dyn_lock, LK_RELEASE);
1138 realloc_dynamic_table(void)
1140 ipfw_dyn_rule **old_dyn_v;
1141 uint32_t old_curr_dyn_buckets;
1143 KASSERT(dyn_buckets <= 65536 && (dyn_buckets & (dyn_buckets - 1)) == 0,
1144 ("invalid dyn_buckets %d\n", dyn_buckets));
1146 /* Save the current buckets array for later error recovery */
1147 old_dyn_v = ipfw_dyn_v;
1148 old_curr_dyn_buckets = curr_dyn_buckets;
1150 curr_dyn_buckets = dyn_buckets;
1152 ipfw_dyn_v = kmalloc(curr_dyn_buckets * sizeof(ipfw_dyn_rule *),
1153 M_IPFW, M_NOWAIT | M_ZERO);
1154 if (ipfw_dyn_v != NULL || curr_dyn_buckets <= 2)
1157 curr_dyn_buckets /= 2;
1158 if (curr_dyn_buckets <= old_curr_dyn_buckets &&
1159 old_dyn_v != NULL) {
1161 * Don't try allocating smaller buckets array, reuse
1162 * the old one, which alreay contains enough buckets
1168 if (ipfw_dyn_v != NULL) {
1169 if (old_dyn_v != NULL)
1170 kfree(old_dyn_v, M_IPFW);
1172 /* Allocation failed, restore old buckets array */
1173 ipfw_dyn_v = old_dyn_v;
1174 curr_dyn_buckets = old_curr_dyn_buckets;
1177 if (ipfw_dyn_v != NULL)
1182 * Install state of type 'type' for a dynamic session.
1183 * The hash table contains two type of rules:
1184 * - regular rules (O_KEEP_STATE)
1185 * - rules for sessions with limited number of sess per user
1186 * (O_LIMIT). When they are created, the parent is
1187 * increased by 1, and decreased on delete. In this case,
1188 * the third parameter is the parent rule and not the chain.
1189 * - "parent" rules for the above (O_LIMIT_PARENT).
1191 static ipfw_dyn_rule *
1192 add_dyn_rule(struct ipfw_flow_id *id, uint8_t dyn_type, struct ip_fw *rule)
1197 if (ipfw_dyn_v == NULL ||
1198 (dyn_count == 0 && dyn_buckets != curr_dyn_buckets)) {
1199 realloc_dynamic_table();
1200 if (ipfw_dyn_v == NULL)
1201 return NULL; /* failed ! */
1203 i = hash_packet(id);
1205 r = kmalloc(sizeof(*r), M_IPFW, M_NOWAIT | M_ZERO);
1207 kprintf ("sorry cannot allocate state\n");
1211 /* increase refcount on parent, and set pointer */
1212 if (dyn_type == O_LIMIT) {
1213 ipfw_dyn_rule *parent = (ipfw_dyn_rule *)rule;
1215 if (parent->dyn_type != O_LIMIT_PARENT)
1216 panic("invalid parent");
1219 rule = parent->stub->rule[mycpuid];
1220 KKASSERT(rule->stub == parent->stub);
1222 KKASSERT(rule->cpuid == mycpuid && rule->stub != NULL);
1225 r->expire = time_second + dyn_syn_lifetime;
1226 r->stub = rule->stub;
1227 r->dyn_type = dyn_type;
1228 r->pcnt = r->bcnt = 0;
1232 r->next = ipfw_dyn_v[i];
1236 DEB(kprintf("-- add dyn entry ty %d 0x%08x %d -> 0x%08x %d, total %d\n",
1238 (r->id.src_ip), (r->id.src_port),
1239 (r->id.dst_ip), (r->id.dst_port),
1245 * lookup dynamic parent rule using pkt and rule as search keys.
1246 * If the lookup fails, then install one.
1248 static ipfw_dyn_rule *
1249 lookup_dyn_parent(struct ipfw_flow_id *pkt, struct ip_fw *rule)
1255 i = hash_packet(pkt);
1256 for (q = ipfw_dyn_v[i]; q != NULL; q = q->next) {
1257 if (q->dyn_type == O_LIMIT_PARENT &&
1258 rule->stub == q->stub &&
1259 pkt->proto == q->id.proto &&
1260 pkt->src_ip == q->id.src_ip &&
1261 pkt->dst_ip == q->id.dst_ip &&
1262 pkt->src_port == q->id.src_port &&
1263 pkt->dst_port == q->id.dst_port) {
1264 q->expire = time_second + dyn_short_lifetime;
1265 DEB(kprintf("lookup_dyn_parent found 0x%p\n",q);)
1270 return add_dyn_rule(pkt, O_LIMIT_PARENT, rule);
1274 * Install dynamic state for rule type cmd->o.opcode
1276 * Returns 1 (failure) if state is not installed because of errors or because
1277 * session limitations are enforced.
1280 install_state_locked(struct ip_fw *rule, ipfw_insn_limit *cmd,
1281 struct ip_fw_args *args)
1283 static int last_log; /* XXX */
1287 DEB(kprintf("-- install state type %d 0x%08x %u -> 0x%08x %u\n",
1289 (args->f_id.src_ip), (args->f_id.src_port),
1290 (args->f_id.dst_ip), (args->f_id.dst_port) );)
1292 q = lookup_dyn_rule(&args->f_id, NULL, NULL);
1293 if (q != NULL) { /* should never occur */
1294 if (last_log != time_second) {
1295 last_log = time_second;
1296 kprintf(" install_state: entry already present, done\n");
1301 if (dyn_count >= dyn_max) {
1303 * Run out of slots, try to remove any expired rule.
1305 remove_dyn_rule_locked(NULL, (ipfw_dyn_rule *)1);
1306 if (dyn_count >= dyn_max) {
1307 if (last_log != time_second) {
1308 last_log = time_second;
1309 kprintf("install_state: "
1310 "Too many dynamic rules\n");
1312 return 1; /* cannot install, notify caller */
1316 switch (cmd->o.opcode) {
1317 case O_KEEP_STATE: /* bidir rule */
1318 if (add_dyn_rule(&args->f_id, O_KEEP_STATE, rule) == NULL)
1322 case O_LIMIT: /* limit number of sessions */
1324 uint16_t limit_mask = cmd->limit_mask;
1325 struct ipfw_flow_id id;
1326 ipfw_dyn_rule *parent;
1328 DEB(kprintf("installing dyn-limit rule %d\n",
1331 id.dst_ip = id.src_ip = 0;
1332 id.dst_port = id.src_port = 0;
1333 id.proto = args->f_id.proto;
1335 if (limit_mask & DYN_SRC_ADDR)
1336 id.src_ip = args->f_id.src_ip;
1337 if (limit_mask & DYN_DST_ADDR)
1338 id.dst_ip = args->f_id.dst_ip;
1339 if (limit_mask & DYN_SRC_PORT)
1340 id.src_port = args->f_id.src_port;
1341 if (limit_mask & DYN_DST_PORT)
1342 id.dst_port = args->f_id.dst_port;
1344 parent = lookup_dyn_parent(&id, rule);
1345 if (parent == NULL) {
1346 kprintf("add parent failed\n");
1350 if (parent->count >= cmd->conn_limit) {
1352 * See if we can remove some expired rule.
1354 remove_dyn_rule_locked(rule, parent);
1355 if (parent->count >= cmd->conn_limit) {
1357 last_log != time_second) {
1358 last_log = time_second;
1359 log(LOG_SECURITY | LOG_DEBUG,
1361 "too many entries\n");
1366 if (add_dyn_rule(&args->f_id, O_LIMIT,
1367 (struct ip_fw *)parent) == NULL)
1372 kprintf("unknown dynamic rule type %u\n", cmd->o.opcode);
1375 lookup_dyn_rule(&args->f_id, NULL, NULL); /* XXX just set lifetime */
1380 install_state(struct ip_fw *rule, ipfw_insn_limit *cmd,
1381 struct ip_fw_args *args, int *deny)
1383 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
1388 gen = ctx->ipfw_gen;
1390 lockmgr(&dyn_lock, LK_EXCLUSIVE);
1391 if (ctx->ipfw_gen != gen) {
1392 /* See the comment in lookup_rule() */
1395 ret = install_state_locked(rule, cmd, args);
1397 lockmgr(&dyn_lock, LK_RELEASE);
1403 * Transmit a TCP packet, containing either a RST or a keepalive.
1404 * When flags & TH_RST, we are sending a RST packet, because of a
1405 * "reset" action matched the packet.
1406 * Otherwise we are sending a keepalive, and flags & TH_
1409 send_pkt(struct ipfw_flow_id *id, uint32_t seq, uint32_t ack, int flags)
1414 struct route sro; /* fake route */
1416 MGETHDR(m, MB_DONTWAIT, MT_HEADER);
1419 m->m_pkthdr.rcvif = NULL;
1420 m->m_pkthdr.len = m->m_len = sizeof(struct ip) + sizeof(struct tcphdr);
1421 m->m_data += max_linkhdr;
1423 ip = mtod(m, struct ip *);
1424 bzero(ip, m->m_len);
1425 tcp = (struct tcphdr *)(ip + 1); /* no IP options */
1426 ip->ip_p = IPPROTO_TCP;
1430 * Assume we are sending a RST (or a keepalive in the reverse
1431 * direction), swap src and destination addresses and ports.
1433 ip->ip_src.s_addr = htonl(id->dst_ip);
1434 ip->ip_dst.s_addr = htonl(id->src_ip);
1435 tcp->th_sport = htons(id->dst_port);
1436 tcp->th_dport = htons(id->src_port);
1437 if (flags & TH_RST) { /* we are sending a RST */
1438 if (flags & TH_ACK) {
1439 tcp->th_seq = htonl(ack);
1440 tcp->th_ack = htonl(0);
1441 tcp->th_flags = TH_RST;
1445 tcp->th_seq = htonl(0);
1446 tcp->th_ack = htonl(seq);
1447 tcp->th_flags = TH_RST | TH_ACK;
1451 * We are sending a keepalive. flags & TH_SYN determines
1452 * the direction, forward if set, reverse if clear.
1453 * NOTE: seq and ack are always assumed to be correct
1454 * as set by the caller. This may be confusing...
1456 if (flags & TH_SYN) {
1458 * we have to rewrite the correct addresses!
1460 ip->ip_dst.s_addr = htonl(id->dst_ip);
1461 ip->ip_src.s_addr = htonl(id->src_ip);
1462 tcp->th_dport = htons(id->dst_port);
1463 tcp->th_sport = htons(id->src_port);
1465 tcp->th_seq = htonl(seq);
1466 tcp->th_ack = htonl(ack);
1467 tcp->th_flags = TH_ACK;
1471 * set ip_len to the payload size so we can compute
1472 * the tcp checksum on the pseudoheader
1473 * XXX check this, could save a couple of words ?
1475 ip->ip_len = htons(sizeof(struct tcphdr));
1476 tcp->th_sum = in_cksum(m, m->m_pkthdr.len);
1479 * now fill fields left out earlier
1481 ip->ip_ttl = ip_defttl;
1482 ip->ip_len = m->m_pkthdr.len;
1484 bzero(&sro, sizeof(sro));
1485 ip_rtaddr(ip->ip_dst, &sro);
1487 m->m_pkthdr.fw_flags |= IPFW_MBUF_GENERATED;
1488 ip_output(m, NULL, &sro, 0, NULL, NULL);
1494 * sends a reject message, consuming the mbuf passed as an argument.
1497 send_reject(struct ip_fw_args *args, int code, int offset, int ip_len)
1499 if (code != ICMP_REJECT_RST) { /* Send an ICMP unreach */
1500 /* We need the IP header in host order for icmp_error(). */
1501 if (args->eh != NULL) {
1502 struct ip *ip = mtod(args->m, struct ip *);
1504 ip->ip_len = ntohs(ip->ip_len);
1505 ip->ip_off = ntohs(ip->ip_off);
1507 icmp_error(args->m, ICMP_UNREACH, code, 0L, 0);
1508 } else if (offset == 0 && args->f_id.proto == IPPROTO_TCP) {
1509 struct tcphdr *const tcp =
1510 L3HDR(struct tcphdr, mtod(args->m, struct ip *));
1512 if ((tcp->th_flags & TH_RST) == 0) {
1513 send_pkt(&args->f_id, ntohl(tcp->th_seq),
1514 ntohl(tcp->th_ack), tcp->th_flags | TH_RST);
1525 * Given an ip_fw *, lookup_next_rule will return a pointer
1526 * to the next rule, which can be either the jump
1527 * target (for skipto instructions) or the next one in the list (in
1528 * all other cases including a missing jump target).
1529 * The result is also written in the "next_rule" field of the rule.
1530 * Backward jumps are not allowed, so start looking from the next
1533 * This never returns NULL -- in case we do not have an exact match,
1534 * the next rule is returned. When the ruleset is changed,
1535 * pointers are flushed so we are always correct.
1538 static struct ip_fw *
1539 lookup_next_rule(struct ip_fw *me)
1541 struct ip_fw *rule = NULL;
1544 /* look for action, in case it is a skipto */
1545 cmd = ACTION_PTR(me);
1546 if (cmd->opcode == O_LOG)
1548 if (cmd->opcode == O_SKIPTO) {
1549 for (rule = me->next; rule; rule = rule->next) {
1550 if (rule->rulenum >= cmd->arg1)
1554 if (rule == NULL) /* failure or not a skipto */
1556 me->next_rule = rule;
1561 * The main check routine for the firewall.
1563 * All arguments are in args so we can modify them and return them
1564 * back to the caller.
1568 * args->m (in/out) The packet; we set to NULL when/if we nuke it.
1569 * Starts with the IP header.
1570 * args->eh (in) Mac header if present, or NULL for layer3 packet.
1571 * args->oif Outgoing interface, or NULL if packet is incoming.
1572 * The incoming interface is in the mbuf. (in)
1574 * args->rule Pointer to the last matching rule (in/out)
1575 * args->f_id Addresses grabbed from the packet (out)
1579 * IP_FW_PORT_DENY_FLAG the packet must be dropped.
1580 * 0 The packet is to be accepted and routed normally OR
1581 * the packet was denied/rejected and has been dropped;
1582 * in the latter case, *m is equal to NULL upon return.
1583 * port Divert the packet to port, with these caveats:
1585 * - If IP_FW_PORT_TEE_FLAG is set, tee the packet instead
1586 * of diverting it (ie, 'ipfw tee').
1588 * - If IP_FW_PORT_DYNT_FLAG is set, interpret the lower
1589 * 16 bits as a dummynet pipe number instead of diverting
1593 ipfw_chk(struct ip_fw_args *args)
1596 * Local variables hold state during the processing of a packet.
1598 * IMPORTANT NOTE: to speed up the processing of rules, there
1599 * are some assumption on the values of the variables, which
1600 * are documented here. Should you change them, please check
1601 * the implementation of the various instructions to make sure
1602 * that they still work.
1604 * args->eh The MAC header. It is non-null for a layer2
1605 * packet, it is NULL for a layer-3 packet.
1607 * m | args->m Pointer to the mbuf, as received from the caller.
1608 * It may change if ipfw_chk() does an m_pullup, or if it
1609 * consumes the packet because it calls send_reject().
1610 * XXX This has to change, so that ipfw_chk() never modifies
1611 * or consumes the buffer.
1612 * ip is simply an alias of the value of m, and it is kept
1613 * in sync with it (the packet is supposed to start with
1616 struct mbuf *m = args->m;
1617 struct ip *ip = mtod(m, struct ip *);
1620 * oif | args->oif If NULL, ipfw_chk has been called on the
1621 * inbound path (ether_input, ip_input).
1622 * If non-NULL, ipfw_chk has been called on the outbound path
1623 * (ether_output, ip_output).
1625 struct ifnet *oif = args->oif;
1627 struct ip_fw *f = NULL; /* matching rule */
1632 * hlen The length of the IPv4 header.
1633 * hlen >0 means we have an IPv4 packet.
1635 u_int hlen = 0; /* hlen >0 means we have an IP pkt */
1638 * offset The offset of a fragment. offset != 0 means that
1639 * we have a fragment at this offset of an IPv4 packet.
1640 * offset == 0 means that (if this is an IPv4 packet)
1641 * this is the first or only fragment.
1646 * Local copies of addresses. They are only valid if we have
1649 * proto The protocol. Set to 0 for non-ip packets,
1650 * or to the protocol read from the packet otherwise.
1651 * proto != 0 means that we have an IPv4 packet.
1653 * src_port, dst_port port numbers, in HOST format. Only
1654 * valid for TCP and UDP packets.
1656 * src_ip, dst_ip ip addresses, in NETWORK format.
1657 * Only valid for IPv4 packets.
1660 uint16_t src_port = 0, dst_port = 0; /* NOTE: host format */
1661 struct in_addr src_ip, dst_ip; /* NOTE: network format */
1662 uint16_t ip_len = 0;
1665 * dyn_dir = MATCH_UNKNOWN when rules unchecked,
1666 * MATCH_NONE when checked and not matched (dyn_f = NULL),
1667 * MATCH_FORWARD or MATCH_REVERSE otherwise (dyn_f != NULL)
1669 int dyn_dir = MATCH_UNKNOWN;
1670 struct ip_fw *dyn_f = NULL;
1671 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
1673 if (m->m_pkthdr.fw_flags & IPFW_MBUF_GENERATED)
1674 return 0; /* accept */
1676 if (args->eh == NULL || /* layer 3 packet */
1677 (m->m_pkthdr.len >= sizeof(struct ip) &&
1678 ntohs(args->eh->ether_type) == ETHERTYPE_IP))
1679 hlen = ip->ip_hl << 2;
1682 * Collect parameters into local variables for faster matching.
1684 if (hlen == 0) { /* do not grab addresses for non-ip pkts */
1685 proto = args->f_id.proto = 0; /* mark f_id invalid */
1686 goto after_ip_checks;
1689 proto = args->f_id.proto = ip->ip_p;
1690 src_ip = ip->ip_src;
1691 dst_ip = ip->ip_dst;
1692 if (args->eh != NULL) { /* layer 2 packets are as on the wire */
1693 offset = ntohs(ip->ip_off) & IP_OFFMASK;
1694 ip_len = ntohs(ip->ip_len);
1696 offset = ip->ip_off & IP_OFFMASK;
1697 ip_len = ip->ip_len;
1700 #define PULLUP_TO(len) \
1702 if (m->m_len < (len)) { \
1703 args->m = m = m_pullup(m, (len));\
1705 goto pullup_failed; \
1706 ip = mtod(m, struct ip *); \
1716 PULLUP_TO(hlen + sizeof(struct tcphdr));
1717 tcp = L3HDR(struct tcphdr, ip);
1718 dst_port = tcp->th_dport;
1719 src_port = tcp->th_sport;
1720 args->f_id.flags = tcp->th_flags;
1728 PULLUP_TO(hlen + sizeof(struct udphdr));
1729 udp = L3HDR(struct udphdr, ip);
1730 dst_port = udp->uh_dport;
1731 src_port = udp->uh_sport;
1736 PULLUP_TO(hlen + 4); /* type, code and checksum. */
1737 args->f_id.flags = L3HDR(struct icmp, ip)->icmp_type;
1747 args->f_id.src_ip = ntohl(src_ip.s_addr);
1748 args->f_id.dst_ip = ntohl(dst_ip.s_addr);
1749 args->f_id.src_port = src_port = ntohs(src_port);
1750 args->f_id.dst_port = dst_port = ntohs(dst_port);
1755 * Packet has already been tagged. Look for the next rule
1756 * to restart processing.
1758 * If fw_one_pass != 0 then just accept it.
1759 * XXX should not happen here, but optimized out in
1765 /* This rule is being/has been flushed */
1767 return IP_FW_PORT_DENY_FLAG;
1769 KASSERT(args->rule->cpuid == mycpuid,
1770 ("rule used on cpu%d\n", mycpuid));
1772 /* This rule was deleted */
1773 if (args->rule->rule_flags & IPFW_RULE_F_INVALID)
1774 return IP_FW_PORT_DENY_FLAG;
1776 f = args->rule->next_rule;
1778 f = lookup_next_rule(args->rule);
1781 * Find the starting rule. It can be either the first
1782 * one, or the one after divert_rule if asked so.
1786 mtag = m_tag_find(m, PACKET_TAG_IPFW_DIVERT, NULL);
1788 skipto = *(uint16_t *)m_tag_data(mtag);
1792 f = ctx->ipfw_layer3_chain;
1793 if (args->eh == NULL && skipto != 0) {
1794 /* No skipto during rule flushing */
1796 return IP_FW_PORT_DENY_FLAG;
1798 if (skipto >= IPFW_DEFAULT_RULE)
1799 return(IP_FW_PORT_DENY_FLAG); /* invalid */
1801 while (f && f->rulenum <= skipto)
1803 if (f == NULL) /* drop packet */
1804 return(IP_FW_PORT_DENY_FLAG);
1805 } else if (ipfw_flushing) {
1806 /* Rules are being flushed; skip to default rule */
1807 f = ctx->ipfw_default_rule;
1810 if ((mtag = m_tag_find(m, PACKET_TAG_IPFW_DIVERT, NULL)) != NULL)
1811 m_tag_delete(m, mtag);
1814 * Now scan the rules, and parse microinstructions for each rule.
1816 for (; f; f = f->next) {
1819 int skip_or; /* skip rest of OR block */
1822 if (ctx->ipfw_set_disable & (1 << f->set))
1826 for (l = f->cmd_len, cmd = f->cmd; l > 0;
1827 l -= cmdlen, cmd += cmdlen) {
1831 * check_body is a jump target used when we find a
1832 * CHECK_STATE, and need to jump to the body of
1837 cmdlen = F_LEN(cmd);
1839 * An OR block (insn_1 || .. || insn_n) has the
1840 * F_OR bit set in all but the last instruction.
1841 * The first match will set "skip_or", and cause
1842 * the following instructions to be skipped until
1843 * past the one with the F_OR bit clear.
1845 if (skip_or) { /* skip this instruction */
1846 if ((cmd->len & F_OR) == 0)
1847 skip_or = 0; /* next one is good */
1850 match = 0; /* set to 1 if we succeed */
1852 switch (cmd->opcode) {
1854 * The first set of opcodes compares the packet's
1855 * fields with some pattern, setting 'match' if a
1856 * match is found. At the end of the loop there is
1857 * logic to deal with F_NOT and F_OR flags associated
1865 kprintf("ipfw: opcode %d unimplemented\n",
1872 * We only check offset == 0 && proto != 0,
1873 * as this ensures that we have an IPv4
1874 * packet with the ports info.
1879 struct inpcbinfo *pi;
1883 if (proto == IPPROTO_TCP) {
1885 pi = &tcbinfo[mycpu->gd_cpuid];
1886 } else if (proto == IPPROTO_UDP) {
1893 in_pcblookup_hash(pi,
1894 dst_ip, htons(dst_port),
1895 src_ip, htons(src_port),
1897 in_pcblookup_hash(pi,
1898 src_ip, htons(src_port),
1899 dst_ip, htons(dst_port),
1902 if (pcb == NULL || pcb->inp_socket == NULL)
1905 if (cmd->opcode == O_UID) {
1906 #define socheckuid(a,b) ((a)->so_cred->cr_uid != (b))
1908 !socheckuid(pcb->inp_socket,
1909 (uid_t)((ipfw_insn_u32 *)cmd)->d[0]);
1912 match = groupmember(
1913 (uid_t)((ipfw_insn_u32 *)cmd)->d[0],
1914 pcb->inp_socket->so_cred);
1920 match = iface_match(m->m_pkthdr.rcvif,
1921 (ipfw_insn_if *)cmd);
1925 match = iface_match(oif, (ipfw_insn_if *)cmd);
1929 match = iface_match(oif ? oif :
1930 m->m_pkthdr.rcvif, (ipfw_insn_if *)cmd);
1934 if (args->eh != NULL) { /* have MAC header */
1935 uint32_t *want = (uint32_t *)
1936 ((ipfw_insn_mac *)cmd)->addr;
1937 uint32_t *mask = (uint32_t *)
1938 ((ipfw_insn_mac *)cmd)->mask;
1939 uint32_t *hdr = (uint32_t *)args->eh;
1942 (want[0] == (hdr[0] & mask[0]) &&
1943 want[1] == (hdr[1] & mask[1]) &&
1944 want[2] == (hdr[2] & mask[2]));
1949 if (args->eh != NULL) {
1951 ntohs(args->eh->ether_type);
1953 ((ipfw_insn_u16 *)cmd)->ports;
1956 /* Special vlan handling */
1957 if (m->m_flags & M_VLANTAG)
1960 for (i = cmdlen - 1; !match && i > 0;
1963 (t >= p[0] && t <= p[1]);
1969 match = (hlen > 0 && offset != 0);
1972 case O_IN: /* "out" is "not in" */
1973 match = (oif == NULL);
1977 match = (args->eh != NULL);
1982 * We do not allow an arg of 0 so the
1983 * check of "proto" only suffices.
1985 match = (proto == cmd->arg1);
1989 match = (hlen > 0 &&
1990 ((ipfw_insn_ip *)cmd)->addr.s_addr ==
1995 match = (hlen > 0 &&
1996 ((ipfw_insn_ip *)cmd)->addr.s_addr ==
1998 ((ipfw_insn_ip *)cmd)->mask.s_addr));
2005 tif = INADDR_TO_IFP(&src_ip);
2006 match = (tif != NULL);
2013 uint32_t *d = (uint32_t *)(cmd + 1);
2015 cmd->opcode == O_IP_DST_SET ?
2021 addr -= d[0]; /* subtract base */
2023 (addr < cmd->arg1) &&
2024 (d[1 + (addr >> 5)] &
2025 (1 << (addr & 0x1f)));
2030 match = (hlen > 0 &&
2031 ((ipfw_insn_ip *)cmd)->addr.s_addr ==
2036 match = (hlen > 0) &&
2037 (((ipfw_insn_ip *)cmd)->addr.s_addr ==
2039 ((ipfw_insn_ip *)cmd)->mask.s_addr));
2046 tif = INADDR_TO_IFP(&dst_ip);
2047 match = (tif != NULL);
2054 * offset == 0 && proto != 0 is enough
2055 * to guarantee that we have an IPv4
2056 * packet with port info.
2058 if ((proto==IPPROTO_UDP || proto==IPPROTO_TCP)
2061 (cmd->opcode == O_IP_SRCPORT) ?
2062 src_port : dst_port ;
2064 ((ipfw_insn_u16 *)cmd)->ports;
2067 for (i = cmdlen - 1; !match && i > 0;
2070 (x >= p[0] && x <= p[1]);
2076 match = (offset == 0 && proto==IPPROTO_ICMP &&
2077 icmptype_match(ip, (ipfw_insn_u32 *)cmd));
2081 match = (hlen > 0 && ipopts_match(ip, cmd));
2085 match = (hlen > 0 && cmd->arg1 == ip->ip_v);
2089 match = (hlen > 0 && cmd->arg1 == ip->ip_ttl);
2093 match = (hlen > 0 &&
2094 cmd->arg1 == ntohs(ip->ip_id));
2098 match = (hlen > 0 && cmd->arg1 == ip_len);
2101 case O_IPPRECEDENCE:
2102 match = (hlen > 0 &&
2103 (cmd->arg1 == (ip->ip_tos & 0xe0)));
2107 match = (hlen > 0 &&
2108 flags_match(cmd, ip->ip_tos));
2112 match = (proto == IPPROTO_TCP && offset == 0 &&
2114 L3HDR(struct tcphdr,ip)->th_flags));
2118 match = (proto == IPPROTO_TCP && offset == 0 &&
2119 tcpopts_match(ip, cmd));
2123 match = (proto == IPPROTO_TCP && offset == 0 &&
2124 ((ipfw_insn_u32 *)cmd)->d[0] ==
2125 L3HDR(struct tcphdr,ip)->th_seq);
2129 match = (proto == IPPROTO_TCP && offset == 0 &&
2130 ((ipfw_insn_u32 *)cmd)->d[0] ==
2131 L3HDR(struct tcphdr,ip)->th_ack);
2135 match = (proto == IPPROTO_TCP && offset == 0 &&
2137 L3HDR(struct tcphdr,ip)->th_win);
2141 /* reject packets which have SYN only */
2142 /* XXX should i also check for TH_ACK ? */
2143 match = (proto == IPPROTO_TCP && offset == 0 &&
2144 (L3HDR(struct tcphdr,ip)->th_flags &
2145 (TH_RST | TH_ACK | TH_SYN)) != TH_SYN);
2150 ipfw_log(f, hlen, args->eh, m, oif);
2155 match = (krandom() <
2156 ((ipfw_insn_u32 *)cmd)->d[0]);
2160 * The second set of opcodes represents 'actions',
2161 * i.e. the terminal part of a rule once the packet
2162 * matches all previous patterns.
2163 * Typically there is only one action for each rule,
2164 * and the opcode is stored at the end of the rule
2165 * (but there are exceptions -- see below).
2167 * In general, here we set retval and terminate the
2168 * outer loop (would be a 'break 3' in some language,
2169 * but we need to do a 'goto done').
2172 * O_COUNT and O_SKIPTO actions:
2173 * instead of terminating, we jump to the next rule
2174 * ('goto next_rule', equivalent to a 'break 2'),
2175 * or to the SKIPTO target ('goto again' after
2176 * having set f, cmd and l), respectively.
2178 * O_LIMIT and O_KEEP_STATE: these opcodes are
2179 * not real 'actions', and are stored right
2180 * before the 'action' part of the rule.
2181 * These opcodes try to install an entry in the
2182 * state tables; if successful, we continue with
2183 * the next opcode (match=1; break;), otherwise
2184 * the packet must be dropped ('goto done' after
2185 * setting retval). If static rules are changed
2186 * during the state installation, the packet will
2187 * be dropped ('return IP_FW_PORT_DENY_FLAG').
2189 * O_PROBE_STATE and O_CHECK_STATE: these opcodes
2190 * cause a lookup of the state table, and a jump
2191 * to the 'action' part of the parent rule
2192 * ('goto check_body') if an entry is found, or
2193 * (CHECK_STATE only) a jump to the next rule if
2194 * the entry is not found ('goto next_rule').
2195 * The result of the lookup is cached to make
2196 * further instances of these opcodes are
2197 * effectively NOPs. If static rules are changed
2198 * during the state looking up, the packet will
2199 * be dropped ('return IP_FW_PORT_DENY_FLAG').
2203 if (!(f->rule_flags & IPFW_RULE_F_STATE)) {
2204 kprintf("%s rule (%d) is not ready "
2206 cmd->opcode == O_LIMIT ?
2207 "limit" : "keep state",
2208 f->rulenum, f->cpuid);
2211 if (install_state(f,
2212 (ipfw_insn_limit *)cmd, args, &deny)) {
2214 return IP_FW_PORT_DENY_FLAG;
2216 retval = IP_FW_PORT_DENY_FLAG;
2217 goto done; /* error/limit violation */
2220 return IP_FW_PORT_DENY_FLAG;
2227 * dynamic rules are checked at the first
2228 * keep-state or check-state occurrence,
2229 * with the result being stored in dyn_dir.
2230 * The compiler introduces a PROBE_STATE
2231 * instruction for us when we have a
2232 * KEEP_STATE (because PROBE_STATE needs
2235 if (dyn_dir == MATCH_UNKNOWN) {
2236 dyn_f = lookup_rule(&args->f_id,
2238 proto == IPPROTO_TCP ?
2239 L3HDR(struct tcphdr, ip) : NULL,
2242 return IP_FW_PORT_DENY_FLAG;
2243 if (dyn_f != NULL) {
2245 * Found a rule from a dynamic
2246 * entry; jump to the 'action'
2250 cmd = ACTION_PTR(f);
2251 l = f->cmd_len - f->act_ofs;
2256 * Dynamic entry not found. If CHECK_STATE,
2257 * skip to next rule, if PROBE_STATE just
2258 * ignore and continue with next opcode.
2260 if (cmd->opcode == O_CHECK_STATE)
2262 else if (!(f->rule_flags & IPFW_RULE_F_STATE))
2263 goto next_rule; /* not ready yet */
2268 retval = 0; /* accept */
2273 args->rule = f; /* report matching rule */
2274 retval = cmd->arg1 | IP_FW_PORT_DYNT_FLAG;
2279 if (args->eh) /* not on layer 2 */
2282 mtag = m_tag_get(PACKET_TAG_IPFW_DIVERT,
2283 sizeof(uint16_t), MB_DONTWAIT);
2285 retval = IP_FW_PORT_DENY_FLAG;
2288 *(uint16_t *)m_tag_data(mtag) = f->rulenum;
2289 m_tag_prepend(m, mtag);
2290 retval = (cmd->opcode == O_DIVERT) ?
2292 cmd->arg1 | IP_FW_PORT_TEE_FLAG;
2297 f->pcnt++; /* update stats */
2299 f->timestamp = time_second;
2300 if (cmd->opcode == O_COUNT)
2303 if (f->next_rule == NULL)
2304 lookup_next_rule(f);
2310 * Drop the packet and send a reject notice
2311 * if the packet is not ICMP (or is an ICMP
2312 * query), and it is not multicast/broadcast.
2315 (proto != IPPROTO_ICMP ||
2316 is_icmp_query(ip)) &&
2317 !(m->m_flags & (M_BCAST|M_MCAST)) &&
2318 !IN_MULTICAST(ntohl(dst_ip.s_addr))) {
2320 * Update statistics before the possible
2321 * blocking 'send_reject'
2325 f->timestamp = time_second;
2327 send_reject(args, cmd->arg1,
2332 * Return directly here, rule stats
2333 * have been updated above.
2335 return IP_FW_PORT_DENY_FLAG;
2339 retval = IP_FW_PORT_DENY_FLAG;
2343 if (args->eh) /* not valid on layer2 pkts */
2345 if (!dyn_f || dyn_dir == MATCH_FORWARD) {
2346 struct sockaddr_in *sin;
2348 mtag = m_tag_get(PACKET_TAG_IPFORWARD,
2349 sizeof(*sin), MB_DONTWAIT);
2351 retval = IP_FW_PORT_DENY_FLAG;
2354 sin = m_tag_data(mtag);
2356 /* Structure copy */
2357 *sin = ((ipfw_insn_sa *)cmd)->sa;
2359 m_tag_prepend(m, mtag);
2360 m->m_pkthdr.fw_flags |=
2361 IPFORWARD_MBUF_TAGGED;
2367 panic("-- unknown opcode %d\n", cmd->opcode);
2368 } /* end of switch() on opcodes */
2370 if (cmd->len & F_NOT)
2374 if (cmd->len & F_OR)
2377 if (!(cmd->len & F_OR)) /* not an OR block, */
2378 break; /* try next rule */
2381 } /* end of inner for, scan opcodes */
2383 next_rule:; /* try next rule */
2385 } /* end of outer for, scan rules */
2386 kprintf("+++ ipfw: ouch!, skip past end of rules, denying packet\n");
2387 return(IP_FW_PORT_DENY_FLAG);
2390 /* Update statistics */
2393 f->timestamp = time_second;
2398 kprintf("pullup failed\n");
2399 return(IP_FW_PORT_DENY_FLAG);
2403 ipfw_dummynet_io(struct mbuf *m, int pipe_nr, int dir, struct ip_fw_args *fwa)
2408 const struct ipfw_flow_id *id;
2409 struct dn_flow_id *fid;
2413 mtag = m_tag_get(PACKET_TAG_DUMMYNET, sizeof(*pkt), MB_DONTWAIT);
2418 m_tag_prepend(m, mtag);
2420 pkt = m_tag_data(mtag);
2421 bzero(pkt, sizeof(*pkt));
2423 cmd = fwa->rule->cmd + fwa->rule->act_ofs;
2424 if (cmd->opcode == O_LOG)
2426 KASSERT(cmd->opcode == O_PIPE || cmd->opcode == O_QUEUE,
2427 ("Rule is not PIPE or QUEUE, opcode %d\n", cmd->opcode));
2430 pkt->dn_flags = (dir & DN_FLAGS_DIR_MASK);
2431 pkt->ifp = fwa->oif;
2432 pkt->cpuid = mycpu->gd_cpuid;
2433 pkt->pipe_nr = pipe_nr;
2437 fid->fid_dst_ip = id->dst_ip;
2438 fid->fid_src_ip = id->src_ip;
2439 fid->fid_dst_port = id->dst_port;
2440 fid->fid_src_port = id->src_port;
2441 fid->fid_proto = id->proto;
2442 fid->fid_flags = id->flags;
2444 ipfw_ref_rule(fwa->rule);
2445 pkt->dn_priv = fwa->rule;
2446 pkt->dn_unref_priv = ipfw_unref_rule;
2448 if (cmd->opcode == O_PIPE)
2449 pkt->dn_flags |= DN_FLAGS_IS_PIPE;
2451 if (dir == DN_TO_IP_OUT) {
2453 * We need to copy *ro because for ICMP pkts (and maybe
2454 * others) the caller passed a pointer into the stack;
2455 * dst might also be a pointer into *ro so it needs to
2458 pkt->ro = *(fwa->ro);
2460 fwa->ro->ro_rt->rt_refcnt++;
2461 if (fwa->dst == (struct sockaddr_in *)&fwa->ro->ro_dst) {
2462 /* 'dst' points into 'ro' */
2463 fwa->dst = (struct sockaddr_in *)&(pkt->ro.ro_dst);
2465 pkt->dn_dst = fwa->dst;
2466 pkt->flags = fwa->flags;
2469 m->m_pkthdr.fw_flags |= DUMMYNET_MBUF_TAGGED;
2474 * When a rule is added/deleted, clear the next_rule pointers in all rules.
2475 * These will be reconstructed on the fly as packets are matched.
2476 * Must be called at splimp().
2479 ipfw_flush_rule_ptrs(struct ipfw_context *ctx)
2483 for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next)
2484 rule->next_rule = NULL;
2487 static __inline void
2488 ipfw_inc_static_count(struct ip_fw *rule)
2490 KKASSERT(mycpuid == 0);
2493 static_ioc_len += IOC_RULESIZE(rule);
2496 static __inline void
2497 ipfw_dec_static_count(struct ip_fw *rule)
2499 int l = IOC_RULESIZE(rule);
2501 KKASSERT(mycpuid == 0);
2503 KASSERT(static_count > 0, ("invalid static count %u\n", static_count));
2506 KASSERT(static_ioc_len >= l,
2507 ("invalid static len %u\n", static_ioc_len));
2508 static_ioc_len -= l;
2512 ipfw_link_sibling(struct netmsg_ipfw *fwmsg, struct ip_fw *rule)
2514 if (fwmsg->sibling != NULL) {
2515 KKASSERT(mycpuid > 0 && fwmsg->sibling->cpuid == mycpuid - 1);
2516 fwmsg->sibling->sibling = rule;
2518 fwmsg->sibling = rule;
2521 static struct ip_fw *
2522 ipfw_create_rule(const struct ipfw_ioc_rule *ioc_rule, struct ip_fw_stub *stub)
2526 rule = kmalloc(RULESIZE(ioc_rule), M_IPFW, M_WAITOK | M_ZERO);
2528 rule->act_ofs = ioc_rule->act_ofs;
2529 rule->cmd_len = ioc_rule->cmd_len;
2530 rule->rulenum = ioc_rule->rulenum;
2531 rule->set = ioc_rule->set;
2532 rule->usr_flags = ioc_rule->usr_flags;
2534 bcopy(ioc_rule->cmd, rule->cmd, rule->cmd_len * 4 /* XXX */);
2537 rule->cpuid = mycpuid;
2541 stub->rule[mycpuid] = rule;
2547 ipfw_add_rule_dispatch(struct netmsg *nmsg)
2549 struct netmsg_ipfw *fwmsg = (struct netmsg_ipfw *)nmsg;
2550 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2553 rule = ipfw_create_rule(fwmsg->ioc_rule, fwmsg->stub);
2556 * Bump generation after ipfw_create_rule(),
2557 * since this function is blocking
2562 * Insert rule into the pre-determined position
2564 if (fwmsg->prev_rule != NULL) {
2565 struct ip_fw *prev, *next;
2567 prev = fwmsg->prev_rule;
2568 KKASSERT(prev->cpuid == mycpuid);
2570 next = fwmsg->next_rule;
2571 KKASSERT(next->cpuid == mycpuid);
2577 * Move to the position on the next CPU
2578 * before the msg is forwarded.
2580 fwmsg->prev_rule = prev->sibling;
2581 fwmsg->next_rule = next->sibling;
2583 KKASSERT(fwmsg->next_rule == NULL);
2584 rule->next = ctx->ipfw_layer3_chain;
2585 ctx->ipfw_layer3_chain = rule;
2588 /* Link rule CPU sibling */
2589 ipfw_link_sibling(fwmsg, rule);
2591 ipfw_flush_rule_ptrs(ctx);
2594 /* Statistics only need to be updated once */
2595 ipfw_inc_static_count(rule);
2597 /* Return the rule on CPU0 */
2598 nmsg->nm_lmsg.u.ms_resultp = rule;
2601 ifnet_forwardmsg(&nmsg->nm_lmsg, mycpuid + 1);
2605 ipfw_enable_state_dispatch(struct netmsg *nmsg)
2607 struct lwkt_msg *lmsg = &nmsg->nm_lmsg;
2608 struct ip_fw *rule = lmsg->u.ms_resultp;
2610 KKASSERT(rule->cpuid == mycpuid);
2611 KKASSERT(rule->stub != NULL && rule->stub->rule[mycpuid] == rule);
2612 KKASSERT(!(rule->rule_flags & IPFW_RULE_F_STATE));
2613 rule->rule_flags |= IPFW_RULE_F_STATE;
2614 lmsg->u.ms_resultp = rule->sibling;
2616 ifnet_forwardmsg(lmsg, mycpuid + 1);
2620 * Add a new rule to the list. Copy the rule into a malloc'ed area,
2621 * then possibly create a rule number and add the rule to the list.
2622 * Update the rule_number in the input struct so the caller knows
2626 ipfw_add_rule(struct ipfw_ioc_rule *ioc_rule, uint32_t rule_flags)
2628 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2629 struct netmsg_ipfw fwmsg;
2630 struct netmsg *nmsg;
2631 struct ip_fw *f, *prev, *rule;
2632 struct ip_fw_stub *stub;
2634 IPFW_ASSERT_CFGPORT(&curthread->td_msgport);
2639 * If rulenum is 0, find highest numbered rule before the
2640 * default rule, and add rule number incremental step.
2642 if (ioc_rule->rulenum == 0) {
2643 int step = autoinc_step;
2645 KKASSERT(step >= IPFW_AUTOINC_STEP_MIN &&
2646 step <= IPFW_AUTOINC_STEP_MAX);
2649 * Locate the highest numbered rule before default
2651 for (f = ctx->ipfw_layer3_chain; f; f = f->next) {
2652 if (f->rulenum == IPFW_DEFAULT_RULE)
2654 ioc_rule->rulenum = f->rulenum;
2656 if (ioc_rule->rulenum < IPFW_DEFAULT_RULE - step)
2657 ioc_rule->rulenum += step;
2659 KASSERT(ioc_rule->rulenum != IPFW_DEFAULT_RULE &&
2660 ioc_rule->rulenum != 0,
2661 ("invalid rule num %d\n", ioc_rule->rulenum));
2664 * Now find the right place for the new rule in the sorted list.
2666 for (prev = NULL, f = ctx->ipfw_layer3_chain; f;
2667 prev = f, f = f->next) {
2668 if (f->rulenum > ioc_rule->rulenum) {
2669 /* Found the location */
2673 KASSERT(f != NULL, ("no default rule?!\n"));
2675 if (rule_flags & IPFW_RULE_F_STATE) {
2679 * If the new rule will create states, then allocate
2680 * a rule stub, which will be referenced by states
2683 size = sizeof(*stub) + ((ncpus - 1) * sizeof(struct ip_fw *));
2684 stub = kmalloc(size, M_IPFW, M_WAITOK | M_ZERO);
2690 * Duplicate the rule onto each CPU.
2691 * The rule duplicated on CPU0 will be returned.
2693 bzero(&fwmsg, sizeof(fwmsg));
2695 netmsg_init(nmsg, &curthread->td_msgport, 0, ipfw_add_rule_dispatch);
2696 fwmsg.ioc_rule = ioc_rule;
2697 fwmsg.prev_rule = prev;
2698 fwmsg.next_rule = prev == NULL ? NULL : f;
2701 ifnet_domsg(&nmsg->nm_lmsg, 0);
2702 KKASSERT(fwmsg.prev_rule == NULL && fwmsg.next_rule == NULL);
2704 rule = nmsg->nm_lmsg.u.ms_resultp;
2705 KKASSERT(rule != NULL && rule->cpuid == mycpuid);
2707 if (rule_flags & IPFW_RULE_F_STATE) {
2709 * Turn on state flag, _after_ everything on all
2710 * CPUs have been setup.
2712 bzero(nmsg, sizeof(*nmsg));
2713 netmsg_init(nmsg, &curthread->td_msgport, 0,
2714 ipfw_enable_state_dispatch);
2715 nmsg->nm_lmsg.u.ms_resultp = rule;
2717 ifnet_domsg(&nmsg->nm_lmsg, 0);
2718 KKASSERT(nmsg->nm_lmsg.u.ms_resultp == NULL);
2723 DEB(kprintf("++ installed rule %d, static count now %d\n",
2724 rule->rulenum, static_count);)
2728 * Free storage associated with a static rule (including derived
2730 * The caller is in charge of clearing rule pointers to avoid
2731 * dangling pointers.
2732 * @return a pointer to the next entry.
2733 * Arguments are not checked, so they better be correct.
2734 * Must be called at splimp().
2736 static struct ip_fw *
2737 ipfw_delete_rule(struct ipfw_context *ctx,
2738 struct ip_fw *prev, struct ip_fw *rule)
2741 struct ip_fw_stub *stub;
2745 /* STATE flag should have been cleared before we reach here */
2746 KKASSERT((rule->rule_flags & IPFW_RULE_F_STATE) == 0);
2751 ctx->ipfw_layer3_chain = n;
2755 /* Mark the rule as invalid */
2756 rule->rule_flags |= IPFW_RULE_F_INVALID;
2757 rule->next_rule = NULL;
2758 rule->sibling = NULL;
2761 /* Don't reset cpuid here; keep various assertion working */
2765 /* Statistics only need to be updated once */
2767 ipfw_dec_static_count(rule);
2769 /* Free 'stub' on the last CPU */
2770 if (stub != NULL && mycpuid == ncpus - 1)
2771 kfree(stub, M_IPFW);
2773 /* Try to free this rule */
2774 ipfw_free_rule(rule);
2776 /* Return the next rule */
2781 ipfw_flush_dispatch(struct netmsg *nmsg)
2783 struct lwkt_msg *lmsg = &nmsg->nm_lmsg;
2784 int kill_default = lmsg->u.ms_result;
2785 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2788 ipfw_flush_rule_ptrs(ctx); /* more efficient to do outside the loop */
2790 while ((rule = ctx->ipfw_layer3_chain) != NULL &&
2791 (kill_default || rule->rulenum != IPFW_DEFAULT_RULE))
2792 ipfw_delete_rule(ctx, NULL, rule);
2794 ifnet_forwardmsg(lmsg, mycpuid + 1);
2798 ipfw_disable_rule_state_dispatch(struct netmsg *nmsg)
2800 struct netmsg_del *dmsg = (struct netmsg_del *)nmsg;
2803 rule = dmsg->start_rule;
2805 KKASSERT(rule->cpuid == mycpuid);
2808 * Move to the position on the next CPU
2809 * before the msg is forwarded.
2811 dmsg->start_rule = rule->sibling;
2813 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2815 KKASSERT(dmsg->rulenum == 0);
2816 rule = ctx->ipfw_layer3_chain;
2819 while (rule != NULL) {
2820 if (dmsg->rulenum && rule->rulenum != dmsg->rulenum)
2822 rule->rule_flags &= ~IPFW_RULE_F_STATE;
2826 ifnet_forwardmsg(&nmsg->nm_lmsg, mycpuid + 1);
2830 * Deletes all rules from a chain (including the default rule
2831 * if the second argument is set).
2832 * Must be called at splimp().
2835 ipfw_flush(int kill_default)
2837 struct netmsg_del dmsg;
2839 struct lwkt_msg *lmsg;
2841 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2843 IPFW_ASSERT_CFGPORT(&curthread->td_msgport);
2846 * If 'kill_default' then caller has done the necessary
2847 * msgport syncing; unnecessary to do it again.
2849 if (!kill_default) {
2851 * Let ipfw_chk() know the rules are going to
2852 * be flushed, so it could jump directly to
2856 netmsg_service_sync();
2860 * Clear STATE flag on rules, so no more states (dyn rules)
2863 bzero(&dmsg, sizeof(dmsg));
2864 netmsg_init(&dmsg.nmsg, &curthread->td_msgport, 0,
2865 ipfw_disable_rule_state_dispatch);
2866 ifnet_domsg(&dmsg.nmsg.nm_lmsg, 0);
2869 * This actually nukes all states (dyn rules)
2871 lockmgr(&dyn_lock, LK_EXCLUSIVE);
2872 for (rule = ctx->ipfw_layer3_chain; rule != NULL; rule = rule->next) {
2874 * Can't check IPFW_RULE_F_STATE here,
2875 * since it has been cleared previously.
2876 * Check 'stub' instead.
2878 if (rule->stub != NULL) {
2880 remove_dyn_rule_locked(rule, NULL);
2883 lockmgr(&dyn_lock, LK_RELEASE);
2886 * Press the 'flush' button
2888 bzero(&nmsg, sizeof(nmsg));
2889 netmsg_init(&nmsg, &curthread->td_msgport, 0, ipfw_flush_dispatch);
2890 lmsg = &nmsg.nm_lmsg;
2891 lmsg->u.ms_result = kill_default;
2892 ifnet_domsg(lmsg, 0);
2894 KASSERT(dyn_count == 0, ("%u dyn rule remains\n", dyn_count));
2897 if (ipfw_dyn_v != NULL) {
2899 * Free dynamic rules(state) hash table
2901 kfree(ipfw_dyn_v, M_IPFW);
2905 KASSERT(static_count == 0,
2906 ("%u static rules remains\n", static_count));
2907 KASSERT(static_ioc_len == 0,
2908 ("%u bytes of static rules remains\n", static_ioc_len));
2910 KASSERT(static_count == 1,
2911 ("%u static rules remains\n", static_count));
2912 KASSERT(static_ioc_len == IOC_RULESIZE(ctx->ipfw_default_rule),
2913 ("%u bytes of static rules remains, should be %u\n",
2914 static_ioc_len, IOC_RULESIZE(ctx->ipfw_default_rule)));
2922 ipfw_alt_delete_rule_dispatch(struct netmsg *nmsg)
2924 struct netmsg_del *dmsg = (struct netmsg_del *)nmsg;
2925 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2926 struct ip_fw *rule, *prev;
2928 rule = dmsg->start_rule;
2929 KKASSERT(rule->cpuid == mycpuid);
2930 dmsg->start_rule = rule->sibling;
2932 prev = dmsg->prev_rule;
2934 KKASSERT(prev->cpuid == mycpuid);
2937 * Move to the position on the next CPU
2938 * before the msg is forwarded.
2940 dmsg->prev_rule = prev->sibling;
2944 * flush pointers outside the loop, then delete all matching
2945 * rules. 'prev' remains the same throughout the cycle.
2947 ipfw_flush_rule_ptrs(ctx);
2948 while (rule && rule->rulenum == dmsg->rulenum)
2949 rule = ipfw_delete_rule(ctx, prev, rule);
2951 ifnet_forwardmsg(&nmsg->nm_lmsg, mycpuid + 1);
2955 ipfw_alt_delete_rule(uint16_t rulenum)
2957 struct ip_fw *prev, *rule, *f;
2958 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2959 struct netmsg_del dmsg;
2960 struct netmsg *nmsg;
2964 * Locate first rule to delete
2966 for (prev = NULL, rule = ctx->ipfw_layer3_chain;
2967 rule && rule->rulenum < rulenum;
2968 prev = rule, rule = rule->next)
2970 if (rule->rulenum != rulenum)
2974 * Check whether any rules with the given number will
2978 for (f = rule; f && f->rulenum == rulenum; f = f->next) {
2979 if (f->rule_flags & IPFW_RULE_F_STATE) {
2987 * Clear the STATE flag, so no more states will be
2988 * created based the rules numbered 'rulenum'.
2990 bzero(&dmsg, sizeof(dmsg));
2992 netmsg_init(nmsg, &curthread->td_msgport, 0,
2993 ipfw_disable_rule_state_dispatch);
2994 dmsg.start_rule = rule;
2995 dmsg.rulenum = rulenum;
2997 ifnet_domsg(&nmsg->nm_lmsg, 0);
2998 KKASSERT(dmsg.start_rule == NULL);
3001 * Nuke all related states
3003 lockmgr(&dyn_lock, LK_EXCLUSIVE);
3004 for (f = rule; f && f->rulenum == rulenum; f = f->next) {
3006 * Can't check IPFW_RULE_F_STATE here,
3007 * since it has been cleared previously.
3008 * Check 'stub' instead.
3010 if (f->stub != NULL) {
3012 remove_dyn_rule_locked(f, NULL);
3015 lockmgr(&dyn_lock, LK_RELEASE);
3019 * Get rid of the rule duplications on all CPUs
3021 bzero(&dmsg, sizeof(dmsg));
3023 netmsg_init(nmsg, &curthread->td_msgport, 0,
3024 ipfw_alt_delete_rule_dispatch);
3025 dmsg.prev_rule = prev;
3026 dmsg.start_rule = rule;
3027 dmsg.rulenum = rulenum;
3029 ifnet_domsg(&nmsg->nm_lmsg, 0);
3030 KKASSERT(dmsg.prev_rule == NULL && dmsg.start_rule == NULL);
3035 ipfw_alt_delete_ruleset_dispatch(struct netmsg *nmsg)
3037 struct netmsg_del *dmsg = (struct netmsg_del *)nmsg;
3038 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3039 struct ip_fw *prev, *rule;
3044 ipfw_flush_rule_ptrs(ctx);
3047 rule = ctx->ipfw_layer3_chain;
3048 while (rule != NULL) {
3049 if (rule->set == dmsg->from_set) {
3050 rule = ipfw_delete_rule(ctx, prev, rule);
3059 KASSERT(del, ("no match set?!\n"));
3061 ifnet_forwardmsg(&nmsg->nm_lmsg, mycpuid + 1);
3065 ipfw_disable_ruleset_state_dispatch(struct netmsg *nmsg)
3067 struct netmsg_del *dmsg = (struct netmsg_del *)nmsg;
3068 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3074 for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next) {
3075 if (rule->set == dmsg->from_set) {
3079 rule->rule_flags &= ~IPFW_RULE_F_STATE;
3082 KASSERT(cleared, ("no match set?!\n"));
3084 ifnet_forwardmsg(&nmsg->nm_lmsg, mycpuid + 1);
3088 ipfw_alt_delete_ruleset(uint8_t set)
3090 struct netmsg_del dmsg;
3091 struct netmsg *nmsg;
3094 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3097 * Check whether the 'set' exists. If it exists,
3098 * then check whether any rules within the set will
3099 * try to create states.
3103 for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next) {
3104 if (rule->set == set) {
3106 if (rule->rule_flags & IPFW_RULE_F_STATE) {
3113 return 0; /* XXX EINVAL? */
3117 * Clear the STATE flag, so no more states will be
3118 * created based the rules in this set.
3120 bzero(&dmsg, sizeof(dmsg));
3122 netmsg_init(nmsg, &curthread->td_msgport, 0,
3123 ipfw_disable_ruleset_state_dispatch);
3124 dmsg.from_set = set;
3126 ifnet_domsg(&nmsg->nm_lmsg, 0);
3129 * Nuke all related states
3131 lockmgr(&dyn_lock, LK_EXCLUSIVE);
3132 for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next) {
3133 if (rule->set != set)
3137 * Can't check IPFW_RULE_F_STATE here,
3138 * since it has been cleared previously.
3139 * Check 'stub' instead.
3141 if (rule->stub != NULL) {
3143 remove_dyn_rule_locked(rule, NULL);
3146 lockmgr(&dyn_lock, LK_RELEASE);
3152 bzero(&dmsg, sizeof(dmsg));
3154 netmsg_init(nmsg, &curthread->td_msgport, 0,
3155 ipfw_alt_delete_ruleset_dispatch);
3156 dmsg.from_set = set;
3158 ifnet_domsg(&nmsg->nm_lmsg, 0);
3163 ipfw_alt_move_rule_dispatch(struct netmsg *nmsg)
3165 struct netmsg_del *dmsg = (struct netmsg_del *)nmsg;
3168 rule = dmsg->start_rule;
3169 KKASSERT(rule->cpuid == mycpuid);
3172 * Move to the position on the next CPU
3173 * before the msg is forwarded.
3175 dmsg->start_rule = rule->sibling;
3177 while (rule && rule->rulenum <= dmsg->rulenum) {
3178 if (rule->rulenum == dmsg->rulenum)
3179 rule->set = dmsg->to_set;
3182 ifnet_forwardmsg(&nmsg->nm_lmsg, mycpuid + 1);
3186 ipfw_alt_move_rule(uint16_t rulenum, uint8_t set)
3188 struct netmsg_del dmsg;
3189 struct netmsg *nmsg;
3191 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3194 * Locate first rule to move
3196 for (rule = ctx->ipfw_layer3_chain; rule && rule->rulenum <= rulenum;
3197 rule = rule->next) {
3198 if (rule->rulenum == rulenum && rule->set != set)
3201 if (rule == NULL || rule->rulenum > rulenum)
3202 return 0; /* XXX error? */
3204 bzero(&dmsg, sizeof(dmsg));
3206 netmsg_init(nmsg, &curthread->td_msgport, 0,
3207 ipfw_alt_move_rule_dispatch);
3208 dmsg.start_rule = rule;
3209 dmsg.rulenum = rulenum;
3212 ifnet_domsg(&nmsg->nm_lmsg, 0);
3213 KKASSERT(dmsg.start_rule == NULL);
3218 ipfw_alt_move_ruleset_dispatch(struct netmsg *nmsg)
3220 struct netmsg_del *dmsg = (struct netmsg_del *)nmsg;
3221 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3224 for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next) {
3225 if (rule->set == dmsg->from_set)
3226 rule->set = dmsg->to_set;
3228 ifnet_forwardmsg(&nmsg->nm_lmsg, mycpuid + 1);
3232 ipfw_alt_move_ruleset(uint8_t from_set, uint8_t to_set)
3234 struct netmsg_del dmsg;
3235 struct netmsg *nmsg;
3237 bzero(&dmsg, sizeof(dmsg));
3239 netmsg_init(nmsg, &curthread->td_msgport, 0,
3240 ipfw_alt_move_ruleset_dispatch);
3241 dmsg.from_set = from_set;
3242 dmsg.to_set = to_set;
3244 ifnet_domsg(&nmsg->nm_lmsg, 0);
3249 ipfw_alt_swap_ruleset_dispatch(struct netmsg *nmsg)
3251 struct netmsg_del *dmsg = (struct netmsg_del *)nmsg;
3252 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3255 for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next) {
3256 if (rule->set == dmsg->from_set)
3257 rule->set = dmsg->to_set;
3258 else if (rule->set == dmsg->to_set)
3259 rule->set = dmsg->from_set;
3261 ifnet_forwardmsg(&nmsg->nm_lmsg, mycpuid + 1);
3265 ipfw_alt_swap_ruleset(uint8_t set1, uint8_t set2)
3267 struct netmsg_del dmsg;
3268 struct netmsg *nmsg;
3270 bzero(&dmsg, sizeof(dmsg));
3272 netmsg_init(nmsg, &curthread->td_msgport, 0,
3273 ipfw_alt_swap_ruleset_dispatch);
3274 dmsg.from_set = set1;
3277 ifnet_domsg(&nmsg->nm_lmsg, 0);
3282 * Remove all rules with given number, and also do set manipulation.
3284 * The argument is an uint32_t. The low 16 bit are the rule or set number,
3285 * the next 8 bits are the new set, the top 8 bits are the command:
3287 * 0 delete rules with given number
3288 * 1 delete rules with given set number
3289 * 2 move rules with given number to new set
3290 * 3 move rules with given set number to new set
3291 * 4 swap sets with given numbers
3294 ipfw_ctl_alter(uint32_t arg)
3297 uint8_t cmd, new_set;
3300 rulenum = arg & 0xffff;
3301 cmd = (arg >> 24) & 0xff;
3302 new_set = (arg >> 16) & 0xff;
3306 if (new_set >= IPFW_DEFAULT_SET)
3308 if (cmd == 0 || cmd == 2) {
3309 if (rulenum == IPFW_DEFAULT_RULE)
3312 if (rulenum >= IPFW_DEFAULT_SET)
3317 case 0: /* delete rules with given number */
3318 error = ipfw_alt_delete_rule(rulenum);
3321 case 1: /* delete all rules with given set number */
3322 error = ipfw_alt_delete_ruleset(rulenum);
3325 case 2: /* move rules with given number to new set */
3326 error = ipfw_alt_move_rule(rulenum, new_set);
3329 case 3: /* move rules with given set number to new set */
3330 error = ipfw_alt_move_ruleset(rulenum, new_set);
3333 case 4: /* swap two sets */
3334 error = ipfw_alt_swap_ruleset(rulenum, new_set);
3341 * Clear counters for a specific rule.
3344 clear_counters(struct ip_fw *rule, int log_only)
3346 ipfw_insn_log *l = (ipfw_insn_log *)ACTION_PTR(rule);
3348 if (log_only == 0) {
3349 rule->bcnt = rule->pcnt = 0;
3350 rule->timestamp = 0;
3352 if (l->o.opcode == O_LOG)
3353 l->log_left = l->max_log;
3357 ipfw_zero_entry_dispatch(struct netmsg *nmsg)
3359 struct netmsg_zent *zmsg = (struct netmsg_zent *)nmsg;
3360 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3363 if (zmsg->rulenum == 0) {
3364 KKASSERT(zmsg->start_rule == NULL);
3366 ctx->ipfw_norule_counter = 0;
3367 for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next)
3368 clear_counters(rule, zmsg->log_only);
3370 struct ip_fw *start = zmsg->start_rule;
3372 KKASSERT(start->cpuid == mycpuid);
3373 KKASSERT(start->rulenum == zmsg->rulenum);
3376 * We can have multiple rules with the same number, so we
3377 * need to clear them all.
3379 for (rule = start; rule && rule->rulenum == zmsg->rulenum;
3381 clear_counters(rule, zmsg->log_only);
3384 * Move to the position on the next CPU
3385 * before the msg is forwarded.
3387 zmsg->start_rule = start->sibling;
3389 ifnet_forwardmsg(&nmsg->nm_lmsg, mycpuid + 1);
3393 * Reset some or all counters on firewall rules.
3394 * @arg frwl is null to clear all entries, or contains a specific
3396 * @arg log_only is 1 if we only want to reset logs, zero otherwise.
3399 ipfw_ctl_zero_entry(int rulenum, int log_only)
3401 struct netmsg_zent zmsg;
3402 struct netmsg *nmsg;
3404 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3406 bzero(&zmsg, sizeof(zmsg));
3408 netmsg_init(nmsg, &curthread->td_msgport, 0, ipfw_zero_entry_dispatch);
3409 zmsg.log_only = log_only;
3412 msg = log_only ? "ipfw: All logging counts reset.\n"
3413 : "ipfw: Accounting cleared.\n";
3418 * Locate the first rule with 'rulenum'
3420 for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next) {
3421 if (rule->rulenum == rulenum)
3424 if (rule == NULL) /* we did not find any matching rules */
3426 zmsg.start_rule = rule;
3427 zmsg.rulenum = rulenum;
3429 msg = log_only ? "ipfw: Entry %d logging count reset.\n"
3430 : "ipfw: Entry %d cleared.\n";
3432 ifnet_domsg(&nmsg->nm_lmsg, 0);
3433 KKASSERT(zmsg.start_rule == NULL);
3436 log(LOG_SECURITY | LOG_NOTICE, msg, rulenum);
3441 * Check validity of the structure before insert.
3442 * Fortunately rules are simple, so this mostly need to check rule sizes.
3445 ipfw_check_ioc_rule(struct ipfw_ioc_rule *rule, int size, uint32_t *rule_flags)
3448 int have_action = 0;
3453 /* Check for valid size */
3454 if (size < sizeof(*rule)) {
3455 kprintf("ipfw: rule too short\n");
3458 l = IOC_RULESIZE(rule);
3460 kprintf("ipfw: size mismatch (have %d want %d)\n", size, l);
3464 /* Check rule number */
3465 if (rule->rulenum == IPFW_DEFAULT_RULE) {
3466 kprintf("ipfw: invalid rule number\n");
3471 * Now go for the individual checks. Very simple ones, basically only
3472 * instruction sizes.
3474 for (l = rule->cmd_len, cmd = rule->cmd; l > 0;
3475 l -= cmdlen, cmd += cmdlen) {
3476 cmdlen = F_LEN(cmd);
3478 kprintf("ipfw: opcode %d size truncated\n",
3483 DEB(kprintf("ipfw: opcode %d\n", cmd->opcode);)
3485 if (cmd->opcode == O_KEEP_STATE || cmd->opcode == O_LIMIT) {
3486 /* This rule will create states */
3487 *rule_flags |= IPFW_RULE_F_STATE;
3490 switch (cmd->opcode) {
3504 case O_IPPRECEDENCE:
3511 if (cmdlen != F_INSN_SIZE(ipfw_insn))
3523 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32))
3528 if (cmdlen != F_INSN_SIZE(ipfw_insn_limit))
3533 if (cmdlen != F_INSN_SIZE(ipfw_insn_log))
3536 ((ipfw_insn_log *)cmd)->log_left =
3537 ((ipfw_insn_log *)cmd)->max_log;
3543 if (cmdlen != F_INSN_SIZE(ipfw_insn_ip))
3545 if (((ipfw_insn_ip *)cmd)->mask.s_addr == 0) {
3546 kprintf("ipfw: opcode %d, useless rule\n",
3554 if (cmd->arg1 == 0 || cmd->arg1 > 256) {
3555 kprintf("ipfw: invalid set size %d\n",
3559 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
3565 if (cmdlen != F_INSN_SIZE(ipfw_insn_mac))
3571 case O_IP_DSTPORT: /* XXX artificial limit, 30 port pairs */
3572 if (cmdlen < 2 || cmdlen > 31)
3579 if (cmdlen != F_INSN_SIZE(ipfw_insn_if))
3585 if (cmdlen != F_INSN_SIZE(ipfw_insn_pipe))
3590 if (cmdlen != F_INSN_SIZE(ipfw_insn_sa)) {
3595 fwd_addr = ((ipfw_insn_sa *)cmd)->
3597 if (IN_MULTICAST(ntohl(fwd_addr))) {
3598 kprintf("ipfw: try forwarding to "
3599 "multicast address\n");
3605 case O_FORWARD_MAC: /* XXX not implemented yet */
3614 if (cmdlen != F_INSN_SIZE(ipfw_insn))
3618 kprintf("ipfw: opcode %d, multiple actions"
3625 kprintf("ipfw: opcode %d, action must be"
3632 kprintf("ipfw: opcode %d, unknown opcode\n",
3637 if (have_action == 0) {
3638 kprintf("ipfw: missing action\n");
3644 kprintf("ipfw: opcode %d size %d wrong\n",
3645 cmd->opcode, cmdlen);
3650 ipfw_ctl_add_rule(struct sockopt *sopt)
3652 struct ipfw_ioc_rule *ioc_rule;
3654 uint32_t rule_flags;
3657 size = sopt->sopt_valsize;
3658 if (size > (sizeof(uint32_t) * IPFW_RULE_SIZE_MAX) ||
3659 size < sizeof(*ioc_rule)) {
3662 if (size != (sizeof(uint32_t) * IPFW_RULE_SIZE_MAX)) {
3663 sopt->sopt_val = krealloc(sopt->sopt_val, sizeof(uint32_t) *
3664 IPFW_RULE_SIZE_MAX, M_TEMP, M_WAITOK);
3666 ioc_rule = sopt->sopt_val;
3668 error = ipfw_check_ioc_rule(ioc_rule, size, &rule_flags);
3672 ipfw_add_rule(ioc_rule, rule_flags);
3674 if (sopt->sopt_dir == SOPT_GET)
3675 sopt->sopt_valsize = IOC_RULESIZE(ioc_rule);
3680 ipfw_copy_rule(const struct ip_fw *rule, struct ipfw_ioc_rule *ioc_rule)
3682 const struct ip_fw *sibling;
3687 KKASSERT(rule->cpuid == 0);
3689 ioc_rule->act_ofs = rule->act_ofs;
3690 ioc_rule->cmd_len = rule->cmd_len;
3691 ioc_rule->rulenum = rule->rulenum;
3692 ioc_rule->set = rule->set;
3693 ioc_rule->usr_flags = rule->usr_flags;
3695 ioc_rule->set_disable = ipfw_ctx[mycpuid]->ipfw_set_disable;
3696 ioc_rule->static_count = static_count;
3697 ioc_rule->static_len = static_ioc_len;
3700 * Visit (read-only) all of the rule's duplications to get
3701 * the necessary statistics
3708 ioc_rule->timestamp = 0;
3709 for (sibling = rule; sibling != NULL; sibling = sibling->sibling) {
3710 ioc_rule->pcnt += sibling->pcnt;
3711 ioc_rule->bcnt += sibling->bcnt;
3712 if (sibling->timestamp > ioc_rule->timestamp)
3713 ioc_rule->timestamp = sibling->timestamp;
3718 KASSERT(i == ncpus, ("static rule is not duplicated on every cpu\n"));
3720 bcopy(rule->cmd, ioc_rule->cmd, ioc_rule->cmd_len * 4 /* XXX */);
3722 return ((uint8_t *)ioc_rule + IOC_RULESIZE(ioc_rule));
3726 ipfw_copy_state(const ipfw_dyn_rule *dyn_rule,
3727 struct ipfw_ioc_state *ioc_state)
3729 const struct ipfw_flow_id *id;
3730 struct ipfw_ioc_flowid *ioc_id;
3732 ioc_state->expire = TIME_LEQ(dyn_rule->expire, time_second) ?
3733 0 : dyn_rule->expire - time_second;
3734 ioc_state->pcnt = dyn_rule->pcnt;
3735 ioc_state->bcnt = dyn_rule->bcnt;
3737 ioc_state->dyn_type = dyn_rule->dyn_type;
3738 ioc_state->count = dyn_rule->count;
3740 ioc_state->rulenum = dyn_rule->stub->rule[mycpuid]->rulenum;
3743 ioc_id = &ioc_state->id;
3745 ioc_id->type = ETHERTYPE_IP;
3746 ioc_id->u.ip.dst_ip = id->dst_ip;
3747 ioc_id->u.ip.src_ip = id->src_ip;
3748 ioc_id->u.ip.dst_port = id->dst_port;
3749 ioc_id->u.ip.src_port = id->src_port;
3750 ioc_id->u.ip.proto = id->proto;
3754 ipfw_ctl_get_rules(struct sockopt *sopt)
3756 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3760 uint32_t dcount = 0;
3763 * pass up a copy of the current rules. Static rules
3764 * come first (the last of which has number IPFW_DEFAULT_RULE),
3765 * followed by a possibly empty list of dynamic rule.
3769 size = static_ioc_len; /* size of static rules */
3770 if (ipfw_dyn_v) { /* add size of dyn.rules */
3772 size += dcount * sizeof(struct ipfw_ioc_state);
3775 if (sopt->sopt_valsize < size) {
3776 /* short length, no need to return incomplete rules */
3777 /* XXX: if superuser, no need to zero buffer */
3778 bzero(sopt->sopt_val, sopt->sopt_valsize);
3781 bp = sopt->sopt_val;
3783 for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next)
3784 bp = ipfw_copy_rule(rule, bp);
3786 if (ipfw_dyn_v && dcount != 0) {
3787 struct ipfw_ioc_state *ioc_state = bp;
3788 uint32_t dcount2 = 0;
3790 size_t old_size = size;
3794 lockmgr(&dyn_lock, LK_SHARED);
3796 /* Check 'ipfw_dyn_v' again with lock held */
3797 if (ipfw_dyn_v == NULL)
3800 for (i = 0; i < curr_dyn_buckets; i++) {
3804 * The # of dynamic rules may have grown after the
3805 * snapshot of 'dyn_count' was taken, so we will have
3806 * to check 'dcount' (snapshot of dyn_count) here to
3807 * make sure that we don't overflow the pre-allocated
3810 for (p = ipfw_dyn_v[i]; p != NULL && dcount != 0;
3811 p = p->next, ioc_state++, dcount--, dcount2++)
3812 ipfw_copy_state(p, ioc_state);
3815 lockmgr(&dyn_lock, LK_RELEASE);
3818 * The # of dynamic rules may be shrinked after the
3819 * snapshot of 'dyn_count' was taken. To give user a
3820 * correct dynamic rule count, we use the 'dcount2'
3821 * calculated above (with shared lockmgr lock held).
3823 size = static_ioc_len +
3824 (dcount2 * sizeof(struct ipfw_ioc_state));
3825 KKASSERT(size <= old_size);
3830 sopt->sopt_valsize = size;
3835 ipfw_set_disable_dispatch(struct netmsg *nmsg)
3837 struct lwkt_msg *lmsg = &nmsg->nm_lmsg;
3838 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3841 ctx->ipfw_set_disable = lmsg->u.ms_result32;
3843 ifnet_forwardmsg(lmsg, mycpuid + 1);
3847 ipfw_ctl_set_disable(uint32_t disable, uint32_t enable)
3850 struct lwkt_msg *lmsg;
3851 uint32_t set_disable;
3853 /* IPFW_DEFAULT_SET is always enabled */
3854 enable |= (1 << IPFW_DEFAULT_SET);
3855 set_disable = (ipfw_ctx[mycpuid]->ipfw_set_disable | disable) & ~enable;
3857 bzero(&nmsg, sizeof(nmsg));
3858 netmsg_init(&nmsg, &curthread->td_msgport, 0, ipfw_set_disable_dispatch);
3859 lmsg = &nmsg.nm_lmsg;
3860 lmsg->u.ms_result32 = set_disable;
3862 ifnet_domsg(lmsg, 0);
3866 * {set|get}sockopt parser.
3869 ipfw_ctl(struct sockopt *sopt)
3877 switch (sopt->sopt_name) {
3879 error = ipfw_ctl_get_rules(sopt);
3884 * Normally we cannot release the lock on each iteration.
3885 * We could do it here only because we start from the head all
3886 * the times so there is no risk of missing some entries.
3887 * On the other hand, the risk is that we end up with
3888 * a very inconsistent ruleset, so better keep the lock
3889 * around the whole cycle.
3891 * XXX this code can be improved by resetting the head of
3892 * the list to point to the default rule, and then freeing
3893 * the old list without the need for a lock.
3897 ipfw_flush(0 /* keep default rule */);
3902 error = ipfw_ctl_add_rule(sopt);
3907 * IP_FW_DEL is used for deleting single rules or sets,
3908 * and (ab)used to atomically manipulate sets.
3909 * Argument size is used to distinguish between the two:
3911 * delete single rule or set of rules,
3912 * or reassign rules (or sets) to a different set.
3913 * 2 * sizeof(uint32_t)
3914 * atomic disable/enable sets.
3915 * first uint32_t contains sets to be disabled,
3916 * second uint32_t contains sets to be enabled.
3918 masks = sopt->sopt_val;
3919 size = sopt->sopt_valsize;
3920 if (size == sizeof(*masks)) {
3922 * Delete or reassign static rule
3924 error = ipfw_ctl_alter(masks[0]);
3925 } else if (size == (2 * sizeof(*masks))) {
3927 * Set enable/disable
3929 ipfw_ctl_set_disable(masks[0], masks[1]);
3936 case IP_FW_RESETLOG: /* argument is an int, the rule number */
3939 if (sopt->sopt_val != 0) {
3940 error = soopt_to_kbuf(sopt, &rulenum,
3941 sizeof(int), sizeof(int));
3945 error = ipfw_ctl_zero_entry(rulenum,
3946 sopt->sopt_name == IP_FW_RESETLOG);
3950 kprintf("ipfw_ctl invalid option %d\n", sopt->sopt_name);
3957 * This procedure is only used to handle keepalives. It is invoked
3958 * every dyn_keepalive_period
3961 ipfw_tick(void *dummy __unused)
3967 if (ipfw_dyn_v == NULL || dyn_count == 0)
3970 keep_alive = time_second;
3972 lockmgr(&dyn_lock, LK_EXCLUSIVE);
3974 if (ipfw_dyn_v == NULL || dyn_count == 0) {
3975 lockmgr(&dyn_lock, LK_RELEASE);
3978 gen = dyn_buckets_gen;
3980 for (i = 0; i < curr_dyn_buckets; i++) {
3981 ipfw_dyn_rule *q, *prev;
3983 for (prev = NULL, q = ipfw_dyn_v[i]; q != NULL;) {
3984 uint32_t ack_rev, ack_fwd;
3985 struct ipfw_flow_id id;
3987 if (q->dyn_type == O_LIMIT_PARENT)
3990 if (TIME_LEQ(q->expire, time_second)) {
3992 UNLINK_DYN_RULE(prev, ipfw_dyn_v[i], q);
3997 * Keep alive processing
4002 if (q->id.proto != IPPROTO_TCP)
4004 if ((q->state & BOTH_SYN) != BOTH_SYN)
4006 if (TIME_LEQ(time_second + dyn_keepalive_interval,
4008 goto next; /* too early */
4009 if (q->keep_alive == keep_alive)
4010 goto next; /* alreay done */
4013 * Save necessary information, so that they could
4014 * survive after possible blocking in send_pkt()
4017 ack_rev = q->ack_rev;
4018 ack_fwd = q->ack_fwd;
4020 /* Sending has been started */
4021 q->keep_alive = keep_alive;
4023 /* Release lock to avoid possible dead lock */
4024 lockmgr(&dyn_lock, LK_RELEASE);
4025 send_pkt(&id, ack_rev - 1, ack_fwd, TH_SYN);
4026 send_pkt(&id, ack_fwd - 1, ack_rev, 0);
4027 lockmgr(&dyn_lock, LK_EXCLUSIVE);
4029 if (gen != dyn_buckets_gen) {
4031 * Dyn bucket array has been changed during
4032 * the above two sending; reiterate.
4041 lockmgr(&dyn_lock, LK_RELEASE);
4043 callout_reset(&ipfw_timeout_h, dyn_keepalive_period * hz,
4048 ipfw_sysctl_autoinc_step(SYSCTL_HANDLER_ARGS)
4050 return sysctl_int_range(oidp, arg1, arg2, req,
4051 IPFW_AUTOINC_STEP_MIN, IPFW_AUTOINC_STEP_MAX);
4055 ipfw_sysctl_dyn_buckets(SYSCTL_HANDLER_ARGS)
4059 lockmgr(&dyn_lock, LK_EXCLUSIVE);
4061 value = dyn_buckets;
4062 error = sysctl_handle_int(oidp, &value, 0, req);
4063 if (error || !req->newptr)
4067 * Make sure we have a power of 2 and
4068 * do not allow more than 64k entries.
4071 if (value <= 1 || value > 65536)
4073 if ((value & (value - 1)) != 0)
4077 dyn_buckets = value;
4079 lockmgr(&dyn_lock, LK_RELEASE);
4084 ipfw_sysctl_dyn_fin(SYSCTL_HANDLER_ARGS)
4086 return sysctl_int_range(oidp, arg1, arg2, req,
4087 1, dyn_keepalive_period - 1);
4091 ipfw_sysctl_dyn_rst(SYSCTL_HANDLER_ARGS)
4093 return sysctl_int_range(oidp, arg1, arg2, req,
4094 1, dyn_keepalive_period - 1);
4098 ipfw_ctx_init_dispatch(struct netmsg *nmsg)
4100 struct netmsg_ipfw *fwmsg = (struct netmsg_ipfw *)nmsg;
4101 struct ipfw_context *ctx;
4102 struct ip_fw *def_rule;
4104 ctx = kmalloc(sizeof(*ctx), M_IPFW, M_WAITOK | M_ZERO);
4105 ipfw_ctx[mycpuid] = ctx;
4107 def_rule = kmalloc(sizeof(*def_rule), M_IPFW, M_WAITOK | M_ZERO);
4109 def_rule->act_ofs = 0;
4110 def_rule->rulenum = IPFW_DEFAULT_RULE;
4111 def_rule->cmd_len = 1;
4112 def_rule->set = IPFW_DEFAULT_SET;
4114 def_rule->cmd[0].len = 1;
4115 #ifdef IPFIREWALL_DEFAULT_TO_ACCEPT
4116 def_rule->cmd[0].opcode = O_ACCEPT;
4118 def_rule->cmd[0].opcode = O_DENY;
4121 def_rule->refcnt = 1;
4122 def_rule->cpuid = mycpuid;
4124 /* Install the default rule */
4125 ctx->ipfw_default_rule = def_rule;
4126 ctx->ipfw_layer3_chain = def_rule;
4128 /* Link rule CPU sibling */
4129 ipfw_link_sibling(fwmsg, def_rule);
4131 /* Statistics only need to be updated once */
4133 ipfw_inc_static_count(def_rule);
4135 ifnet_forwardmsg(&nmsg->nm_lmsg, mycpuid + 1);
4139 ipfw_init_dispatch(struct netmsg *nmsg)
4141 struct netmsg_ipfw fwmsg;
4147 kprintf("IP firewall already loaded\n");
4152 bzero(&fwmsg, sizeof(fwmsg));
4153 netmsg_init(&fwmsg.nmsg, &curthread->td_msgport, 0,
4154 ipfw_ctx_init_dispatch);
4155 ifnet_domsg(&fwmsg.nmsg.nm_lmsg, 0);
4157 ip_fw_chk_ptr = ipfw_chk;
4158 ip_fw_ctl_ptr = ipfw_ctl;
4159 ip_fw_dn_io_ptr = ipfw_dummynet_io;
4161 kprintf("ipfw2 initialized, divert %s, "
4162 "rule-based forwarding enabled, default to %s, logging ",
4168 ipfw_ctx[mycpuid]->ipfw_default_rule->cmd[0].opcode ==
4169 O_ACCEPT ? "accept" : "deny");
4171 #ifdef IPFIREWALL_VERBOSE
4174 #ifdef IPFIREWALL_VERBOSE_LIMIT
4175 verbose_limit = IPFIREWALL_VERBOSE_LIMIT;
4177 if (fw_verbose == 0) {
4178 kprintf("disabled\n");
4179 } else if (verbose_limit == 0) {
4180 kprintf("unlimited\n");
4182 kprintf("limited to %d packets/entry by default\n",
4186 callout_init(&ipfw_timeout_h);
4187 lockinit(&dyn_lock, "ipfw_dyn", 0, 0);
4190 callout_reset(&ipfw_timeout_h, hz, ipfw_tick, NULL);
4193 lwkt_replymsg(&nmsg->nm_lmsg, error);
4201 netmsg_init(&smsg, &curthread->td_msgport, 0, ipfw_init_dispatch);
4202 return lwkt_domsg(IPFW_CFGPORT, &smsg.nm_lmsg, 0);
4208 ipfw_fini_dispatch(struct netmsg *nmsg)
4214 if (ipfw_refcnt != 0) {
4219 callout_stop(&ipfw_timeout_h);
4222 netmsg_service_sync();
4224 ip_fw_chk_ptr = NULL;
4225 ip_fw_ctl_ptr = NULL;
4226 ip_fw_dn_io_ptr = NULL;
4227 ipfw_flush(1 /* kill default rule */);
4229 /* Free pre-cpu context */
4230 for (cpu = 0; cpu < ncpus; ++cpu)
4231 kfree(ipfw_ctx[cpu], M_IPFW);
4233 kprintf("IP firewall unloaded\n");
4236 lwkt_replymsg(&nmsg->nm_lmsg, error);
4244 netmsg_init(&smsg, &curthread->td_msgport, 0, ipfw_fini_dispatch);
4245 return lwkt_domsg(IPFW_CFGPORT, &smsg.nm_lmsg, 0);
4248 #endif /* KLD_MODULE */
4251 ipfw_modevent(module_t mod, int type, void *unused)
4262 kprintf("ipfw statically compiled, cannot unload\n");
4274 static moduledata_t ipfwmod = {
4279 DECLARE_MODULE(ipfw, ipfwmod, SI_SUB_PROTO_END, SI_ORDER_ANY);
4280 MODULE_VERSION(ipfw, 1);