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.94 2008/09/19 12:23:56 sephe Exp $
30 * Implement IP packet firewall (new version)
36 #error IPFIREWALL requires INET.
39 #include <sys/param.h>
40 #include <sys/systm.h>
41 #include <sys/malloc.h>
43 #include <sys/kernel.h>
45 #include <sys/socket.h>
46 #include <sys/socketvar.h>
47 #include <sys/sysctl.h>
48 #include <sys/syslog.h>
49 #include <sys/thread2.h>
50 #include <sys/ucred.h>
51 #include <sys/in_cksum.h>
55 #include <net/route.h>
56 #include <net/netmsg2.h>
58 #include <net/dummynet/ip_dummynet.h>
60 #include <netinet/in.h>
61 #include <netinet/in_systm.h>
62 #include <netinet/in_var.h>
63 #include <netinet/in_pcb.h>
64 #include <netinet/ip.h>
65 #include <netinet/ip_var.h>
66 #include <netinet/ip_icmp.h>
67 #include <netinet/tcp.h>
68 #include <netinet/tcp_timer.h>
69 #include <netinet/tcp_var.h>
70 #include <netinet/tcpip.h>
71 #include <netinet/udp.h>
72 #include <netinet/udp_var.h>
73 #include <netinet/ip_divert.h>
74 #include <netinet/if_ether.h> /* XXX for ETHERTYPE_IP */
76 #include <net/ipfw/ip_fw2.h>
78 #ifdef IPFIREWALL_DEBUG
79 #define DPRINTF(fmt, ...) \
82 kprintf(fmt, __VA_ARGS__); \
85 #define DPRINTF(fmt, ...) ((void)0)
89 * Description about per-CPU rule duplication:
91 * Module loading/unloading and all ioctl operations are serialized
92 * by netisr0, so we don't have any ordering or locking problems.
94 * Following graph shows how operation on per-CPU rule list is
95 * performed [2 CPU case]:
99 * netisr0 <------------------------------------+
110 * forwardmsg---------->ifnet1 |
115 * replymsg--------------+
120 * Rules which will not create states (dyn rules) [2 CPU case]
123 * layer3_chain layer3_chain
126 * +-------+ sibling +-------+ sibling
127 * | rule1 |--------->| rule1 |--------->NULL
128 * +-------+ +-------+
132 * +-------+ sibling +-------+ sibling
133 * | rule2 |--------->| rule2 |--------->NULL
134 * +-------+ +-------+
137 * 1) Ease statistics calculation during IP_FW_GET. We only need to
138 * iterate layer3_chain on CPU0; the current rule's duplication on
139 * the other CPUs could safely be read-only accessed by using
141 * 2) Accelerate rule insertion and deletion, e.g. rule insertion:
142 * a) In netisr0 (on CPU0) rule3 is determined to be inserted between
143 * rule1 and rule2. To make this decision we need to iterate the
144 * layer3_chain on CPU0. The netmsg, which is used to insert the
145 * rule, will contain rule1 on CPU0 as prev_rule and rule2 on CPU0
147 * b) After the insertion on CPU0 is done, we will move on to CPU1.
148 * But instead of relocating the rule3's position on CPU1 by
149 * iterating the layer3_chain on CPU1, we set the netmsg's prev_rule
150 * to rule1->sibling and next_rule to rule2->sibling before the
151 * netmsg is forwarded to CPU1 from CPU0
155 * Rules which will create states (dyn rules) [2 CPU case]
156 * (unnecessary parts are omitted; they are same as in the previous figure)
160 * +-------+ +-------+
161 * | rule1 | | rule1 |
162 * +-------+ +-------+
169 * | +--------------------+ |
171 * | | (read-only shared) | |
173 * | | back pointer array | |
174 * | | (indexed by cpuid) | |
176 * +----|---------[0] | |
177 * | [1]--------|----+
179 * +--------------------+
182 * ........|............|............
186 * : +---------+ +---------+ :
187 * : | state1a | | state1b | .... :
188 * : +---------+ +---------+ :
192 * : (protected by dyn_lock) :
193 * ..................................
195 * [state1a and state1b are states created by rule1]
198 * This structure is introduced so that shared (locked) state table could
199 * work with per-CPU (duplicated) static rules. It mainly bridges states
200 * and static rules and serves as static rule's place holder (a read-only
201 * shared part of duplicated rules) from states point of view.
203 * IPFW_RULE_F_STATE (only for rules which create states):
204 * o During rule installation, this flag is turned on after rule's
205 * duplications reach all CPUs, to avoid at least following race:
206 * 1) rule1 is duplicated on CPU0 and is not duplicated on CPU1 yet
207 * 2) rule1 creates state1
208 * 3) state1 is located on CPU1 by check-state
209 * But rule1 is not duplicated on CPU1 yet
210 * o During rule deletion, this flag is turned off before deleting states
211 * created by the rule and before deleting the rule itself, so no
212 * more states will be created by the to-be-deleted rule even when its
213 * duplication on certain CPUs are not eliminated yet.
216 #define IPFW_AUTOINC_STEP_MIN 1
217 #define IPFW_AUTOINC_STEP_MAX 1000
218 #define IPFW_AUTOINC_STEP_DEF 100
220 #define IPFW_DEFAULT_RULE 65535 /* rulenum for the default rule */
221 #define IPFW_DEFAULT_SET 31 /* set number for the default rule */
225 const struct ipfw_ioc_rule *ioc_rule;
226 struct ip_fw *next_rule;
227 struct ip_fw *prev_rule;
228 struct ip_fw *sibling;
229 struct ip_fw_stub *stub;
234 struct ip_fw *start_rule;
235 struct ip_fw *prev_rule;
243 struct ip_fw *start_rule;
248 struct ipfw_context {
249 struct ip_fw *ipfw_layer3_chain; /* list of rules for layer3 */
250 struct ip_fw *ipfw_default_rule; /* default rule */
251 uint64_t ipfw_norule_counter; /* counter for ipfw_log(NULL) */
254 * ipfw_set_disable contains one bit per set value (0..31).
255 * If the bit is set, all rules with the corresponding set
256 * are disabled. Set IPDW_DEFAULT_SET is reserved for the
257 * default rule and CANNOT be disabled.
259 uint32_t ipfw_set_disable;
260 uint32_t ipfw_gen; /* generation of rule list */
263 static struct ipfw_context *ipfw_ctx[MAXCPU];
267 * Module can not be unloaded, if there are references to
268 * certains rules of ipfw(4), e.g. dummynet(4)
270 static int ipfw_refcnt;
273 MALLOC_DEFINE(M_IPFW, "IpFw/IpAcct", "IpFw/IpAcct chain's");
276 * Following two global variables are accessed and
277 * updated only on CPU0
279 static uint32_t static_count; /* # of static rules */
280 static uint32_t static_ioc_len; /* bytes of static rules */
283 * If 1, then ipfw static rules are being flushed,
284 * ipfw_chk() will skip to the default rule.
286 static int ipfw_flushing;
288 static int fw_verbose;
289 static int verbose_limit;
292 static int autoinc_step = IPFW_AUTOINC_STEP_DEF;
294 static int ipfw_sysctl_enable(SYSCTL_HANDLER_ARGS);
295 static int ipfw_sysctl_autoinc_step(SYSCTL_HANDLER_ARGS);
296 static int ipfw_sysctl_dyn_buckets(SYSCTL_HANDLER_ARGS);
297 static int ipfw_sysctl_dyn_fin(SYSCTL_HANDLER_ARGS);
298 static int ipfw_sysctl_dyn_rst(SYSCTL_HANDLER_ARGS);
300 SYSCTL_NODE(_net_inet_ip, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall");
301 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, enable, CTLTYPE_INT | CTLFLAG_RW,
302 &fw_enable, 0, ipfw_sysctl_enable, "I", "Enable ipfw");
303 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, autoinc_step, CTLTYPE_INT | CTLFLAG_RW,
304 &autoinc_step, 0, ipfw_sysctl_autoinc_step, "I",
305 "Rule number autincrement step");
306 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO,one_pass,CTLFLAG_RW,
308 "Only do a single pass through ipfw when using dummynet(4)");
309 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, debug, CTLFLAG_RW,
310 &fw_debug, 0, "Enable printing of debug ip_fw statements");
311 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose, CTLFLAG_RW,
312 &fw_verbose, 0, "Log matches to ipfw rules");
313 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose_limit, CTLFLAG_RW,
314 &verbose_limit, 0, "Set upper limit of matches of ipfw rules logged");
317 * Description of dynamic rules.
319 * Dynamic rules are stored in lists accessed through a hash table
320 * (ipfw_dyn_v) whose size is curr_dyn_buckets. This value can
321 * be modified through the sysctl variable dyn_buckets which is
322 * updated when the table becomes empty.
324 * XXX currently there is only one list, ipfw_dyn.
326 * When a packet is received, its address fields are first masked
327 * with the mask defined for the rule, then hashed, then matched
328 * against the entries in the corresponding list.
329 * Dynamic rules can be used for different purposes:
331 * + enforcing limits on the number of sessions;
332 * + in-kernel NAT (not implemented yet)
334 * The lifetime of dynamic rules is regulated by dyn_*_lifetime,
335 * measured in seconds and depending on the flags.
337 * The total number of dynamic rules is stored in dyn_count.
338 * The max number of dynamic rules is dyn_max. When we reach
339 * the maximum number of rules we do not create anymore. This is
340 * done to avoid consuming too much memory, but also too much
341 * time when searching on each packet (ideally, we should try instead
342 * to put a limit on the length of the list on each bucket...).
344 * Each dynamic rule holds a pointer to the parent ipfw rule so
345 * we know what action to perform. Dynamic rules are removed when
346 * the parent rule is deleted. XXX we should make them survive.
348 * There are some limitations with dynamic rules -- we do not
349 * obey the 'randomized match', and we do not do multiple
350 * passes through the firewall. XXX check the latter!!!
352 * NOTE about the SHARED LOCKMGR LOCK during dynamic rule looking up:
353 * Only TCP state transition will change dynamic rule's state and ack
354 * sequences, while all packets of one TCP connection only goes through
355 * one TCP thread, so it is safe to use shared lockmgr lock during dynamic
356 * rule looking up. The keep alive callout uses exclusive lockmgr lock
357 * when it tries to find suitable dynamic rules to send keep alive, so
358 * it will not see half updated state and ack sequences. Though the expire
359 * field updating looks racy for other protocols, the resolution (second)
360 * of expire field makes this kind of race harmless.
361 * XXX statistics' updating is _not_ MPsafe!!!
362 * XXX once UDP output path is fixed, we could use lockless dynamic rule
365 static ipfw_dyn_rule **ipfw_dyn_v = NULL;
366 static uint32_t dyn_buckets = 256; /* must be power of 2 */
367 static uint32_t curr_dyn_buckets = 256; /* must be power of 2 */
368 static uint32_t dyn_buckets_gen; /* generation of dyn buckets array */
369 static struct lock dyn_lock; /* dynamic rules' hash table lock */
370 static struct callout ipfw_timeout_h;
373 * Timeouts for various events in handing dynamic rules.
375 static uint32_t dyn_ack_lifetime = 300;
376 static uint32_t dyn_syn_lifetime = 20;
377 static uint32_t dyn_fin_lifetime = 1;
378 static uint32_t dyn_rst_lifetime = 1;
379 static uint32_t dyn_udp_lifetime = 10;
380 static uint32_t dyn_short_lifetime = 5;
383 * Keepalives are sent if dyn_keepalive is set. They are sent every
384 * dyn_keepalive_period seconds, in the last dyn_keepalive_interval
385 * seconds of lifetime of a rule.
386 * dyn_rst_lifetime and dyn_fin_lifetime should be strictly lower
387 * than dyn_keepalive_period.
390 static uint32_t dyn_keepalive_interval = 20;
391 static uint32_t dyn_keepalive_period = 5;
392 static uint32_t dyn_keepalive = 1; /* do send keepalives */
394 static uint32_t dyn_count; /* # of dynamic rules */
395 static uint32_t dyn_max = 4096; /* max # of dynamic rules */
397 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, dyn_buckets, CTLTYPE_INT | CTLFLAG_RW,
398 &dyn_buckets, 0, ipfw_sysctl_dyn_buckets, "I", "Number of dyn. buckets");
399 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, curr_dyn_buckets, CTLFLAG_RD,
400 &curr_dyn_buckets, 0, "Current Number of dyn. buckets");
401 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_count, CTLFLAG_RD,
402 &dyn_count, 0, "Number of dyn. rules");
403 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_max, CTLFLAG_RW,
404 &dyn_max, 0, "Max number of dyn. rules");
405 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, static_count, CTLFLAG_RD,
406 &static_count, 0, "Number of static rules");
407 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_ack_lifetime, CTLFLAG_RW,
408 &dyn_ack_lifetime, 0, "Lifetime of dyn. rules for acks");
409 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_syn_lifetime, CTLFLAG_RW,
410 &dyn_syn_lifetime, 0, "Lifetime of dyn. rules for syn");
411 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, dyn_fin_lifetime,
412 CTLTYPE_INT | CTLFLAG_RW, &dyn_fin_lifetime, 0, ipfw_sysctl_dyn_fin, "I",
413 "Lifetime of dyn. rules for fin");
414 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, dyn_rst_lifetime,
415 CTLTYPE_INT | CTLFLAG_RW, &dyn_rst_lifetime, 0, ipfw_sysctl_dyn_rst, "I",
416 "Lifetime of dyn. rules for rst");
417 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_udp_lifetime, CTLFLAG_RW,
418 &dyn_udp_lifetime, 0, "Lifetime of dyn. rules for UDP");
419 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_short_lifetime, CTLFLAG_RW,
420 &dyn_short_lifetime, 0, "Lifetime of dyn. rules for other situations");
421 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_keepalive, CTLFLAG_RW,
422 &dyn_keepalive, 0, "Enable keepalives for dyn. rules");
424 static ip_fw_chk_t ipfw_chk;
427 ipfw_free_rule(struct ip_fw *rule)
429 KASSERT(rule->cpuid == mycpuid, ("rule freed on cpu%d\n", mycpuid));
430 KASSERT(rule->refcnt > 0, ("invalid refcnt %u\n", rule->refcnt));
432 if (rule->refcnt == 0) {
440 ipfw_unref_rule(void *priv)
442 ipfw_free_rule(priv);
444 atomic_subtract_int(&ipfw_refcnt, 1);
449 ipfw_ref_rule(struct ip_fw *rule)
451 KASSERT(rule->cpuid == mycpuid, ("rule used on cpu%d\n", mycpuid));
453 atomic_add_int(&ipfw_refcnt, 1);
459 * This macro maps an ip pointer into a layer3 header pointer of type T
461 #define L3HDR(T, ip) ((T *)((uint32_t *)(ip) + (ip)->ip_hl))
464 icmptype_match(struct ip *ip, ipfw_insn_u32 *cmd)
466 int type = L3HDR(struct icmp,ip)->icmp_type;
468 return (type <= ICMP_MAXTYPE && (cmd->d[0] & (1 << type)));
471 #define TT ((1 << ICMP_ECHO) | \
472 (1 << ICMP_ROUTERSOLICIT) | \
473 (1 << ICMP_TSTAMP) | \
478 is_icmp_query(struct ip *ip)
480 int type = L3HDR(struct icmp, ip)->icmp_type;
482 return (type <= ICMP_MAXTYPE && (TT & (1 << type)));
488 * The following checks use two arrays of 8 or 16 bits to store the
489 * bits that we want set or clear, respectively. They are in the
490 * low and high half of cmd->arg1 or cmd->d[0].
492 * We scan options and store the bits we find set. We succeed if
494 * (want_set & ~bits) == 0 && (want_clear & ~bits) == want_clear
496 * The code is sometimes optimized not to store additional variables.
500 flags_match(ipfw_insn *cmd, uint8_t bits)
505 if (((cmd->arg1 & 0xff) & bits) != 0)
506 return 0; /* some bits we want set were clear */
508 want_clear = (cmd->arg1 >> 8) & 0xff;
509 if ((want_clear & bits) != want_clear)
510 return 0; /* some bits we want clear were set */
515 ipopts_match(struct ip *ip, ipfw_insn *cmd)
517 int optlen, bits = 0;
518 u_char *cp = (u_char *)(ip + 1);
519 int x = (ip->ip_hl << 2) - sizeof(struct ip);
521 for (; x > 0; x -= optlen, cp += optlen) {
522 int opt = cp[IPOPT_OPTVAL];
524 if (opt == IPOPT_EOL)
527 if (opt == IPOPT_NOP) {
530 optlen = cp[IPOPT_OLEN];
531 if (optlen <= 0 || optlen > x)
532 return 0; /* invalid or truncated */
537 bits |= IP_FW_IPOPT_LSRR;
541 bits |= IP_FW_IPOPT_SSRR;
545 bits |= IP_FW_IPOPT_RR;
549 bits |= IP_FW_IPOPT_TS;
556 return (flags_match(cmd, bits));
560 tcpopts_match(struct ip *ip, ipfw_insn *cmd)
562 int optlen, bits = 0;
563 struct tcphdr *tcp = L3HDR(struct tcphdr,ip);
564 u_char *cp = (u_char *)(tcp + 1);
565 int x = (tcp->th_off << 2) - sizeof(struct tcphdr);
567 for (; x > 0; x -= optlen, cp += optlen) {
570 if (opt == TCPOPT_EOL)
573 if (opt == TCPOPT_NOP) {
583 bits |= IP_FW_TCPOPT_MSS;
587 bits |= IP_FW_TCPOPT_WINDOW;
590 case TCPOPT_SACK_PERMITTED:
592 bits |= IP_FW_TCPOPT_SACK;
595 case TCPOPT_TIMESTAMP:
596 bits |= IP_FW_TCPOPT_TS;
602 bits |= IP_FW_TCPOPT_CC;
609 return (flags_match(cmd, bits));
613 iface_match(struct ifnet *ifp, ipfw_insn_if *cmd)
615 if (ifp == NULL) /* no iface with this packet, match fails */
618 /* Check by name or by IP address */
619 if (cmd->name[0] != '\0') { /* match by name */
622 if (kfnmatch(cmd->name, ifp->if_xname, 0) == 0)
625 if (strncmp(ifp->if_xname, cmd->name, IFNAMSIZ) == 0)
629 struct ifaddr_container *ifac;
631 TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
632 struct ifaddr *ia = ifac->ifa;
634 if (ia->ifa_addr == NULL)
636 if (ia->ifa_addr->sa_family != AF_INET)
638 if (cmd->p.ip.s_addr == ((struct sockaddr_in *)
639 (ia->ifa_addr))->sin_addr.s_addr)
640 return(1); /* match */
643 return(0); /* no match, fail ... */
646 #define SNPARGS(buf, len) buf + len, sizeof(buf) > len ? sizeof(buf) - len : 0
649 * We enter here when we have a rule with O_LOG.
650 * XXX this function alone takes about 2Kbytes of code!
653 ipfw_log(struct ip_fw *f, u_int hlen, struct ether_header *eh,
654 struct mbuf *m, struct ifnet *oif)
657 int limit_reached = 0;
658 char action2[40], proto[48], fragment[28];
663 if (f == NULL) { /* bogus pkt */
664 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
666 if (verbose_limit != 0 &&
667 ctx->ipfw_norule_counter >= verbose_limit)
669 ctx->ipfw_norule_counter++;
670 if (ctx->ipfw_norule_counter == verbose_limit)
671 limit_reached = verbose_limit;
673 } else { /* O_LOG is the first action, find the real one */
674 ipfw_insn *cmd = ACTION_PTR(f);
675 ipfw_insn_log *l = (ipfw_insn_log *)cmd;
677 if (l->max_log != 0 && l->log_left == 0)
680 if (l->log_left == 0)
681 limit_reached = l->max_log;
682 cmd += F_LEN(cmd); /* point to first action */
683 if (cmd->opcode == O_PROB)
687 switch (cmd->opcode) {
693 if (cmd->arg1==ICMP_REJECT_RST) {
695 } else if (cmd->arg1==ICMP_UNREACH_HOST) {
698 ksnprintf(SNPARGS(action2, 0), "Unreach %d",
712 ksnprintf(SNPARGS(action2, 0), "Divert %d", cmd->arg1);
716 ksnprintf(SNPARGS(action2, 0), "Tee %d", cmd->arg1);
720 ksnprintf(SNPARGS(action2, 0), "SkipTo %d", cmd->arg1);
724 ksnprintf(SNPARGS(action2, 0), "Pipe %d", cmd->arg1);
728 ksnprintf(SNPARGS(action2, 0), "Queue %d", cmd->arg1);
733 ipfw_insn_sa *sa = (ipfw_insn_sa *)cmd;
736 len = ksnprintf(SNPARGS(action2, 0),
738 inet_ntoa(sa->sa.sin_addr));
739 if (sa->sa.sin_port) {
740 ksnprintf(SNPARGS(action2, len), ":%d",
752 if (hlen == 0) { /* non-ip */
753 ksnprintf(SNPARGS(proto, 0), "MAC");
755 struct ip *ip = mtod(m, struct ip *);
756 /* these three are all aliases to the same thing */
757 struct icmp *const icmp = L3HDR(struct icmp, ip);
758 struct tcphdr *const tcp = (struct tcphdr *)icmp;
759 struct udphdr *const udp = (struct udphdr *)icmp;
761 int ip_off, offset, ip_len;
764 if (eh != NULL) { /* layer 2 packets are as on the wire */
765 ip_off = ntohs(ip->ip_off);
766 ip_len = ntohs(ip->ip_len);
771 offset = ip_off & IP_OFFMASK;
774 len = ksnprintf(SNPARGS(proto, 0), "TCP %s",
775 inet_ntoa(ip->ip_src));
777 ksnprintf(SNPARGS(proto, len), ":%d %s:%d",
778 ntohs(tcp->th_sport),
779 inet_ntoa(ip->ip_dst),
780 ntohs(tcp->th_dport));
782 ksnprintf(SNPARGS(proto, len), " %s",
783 inet_ntoa(ip->ip_dst));
788 len = ksnprintf(SNPARGS(proto, 0), "UDP %s",
789 inet_ntoa(ip->ip_src));
791 ksnprintf(SNPARGS(proto, len), ":%d %s:%d",
792 ntohs(udp->uh_sport),
793 inet_ntoa(ip->ip_dst),
794 ntohs(udp->uh_dport));
796 ksnprintf(SNPARGS(proto, len), " %s",
797 inet_ntoa(ip->ip_dst));
803 len = ksnprintf(SNPARGS(proto, 0),
808 len = ksnprintf(SNPARGS(proto, 0), "ICMP ");
810 len += ksnprintf(SNPARGS(proto, len), "%s",
811 inet_ntoa(ip->ip_src));
812 ksnprintf(SNPARGS(proto, len), " %s",
813 inet_ntoa(ip->ip_dst));
817 len = ksnprintf(SNPARGS(proto, 0), "P:%d %s", ip->ip_p,
818 inet_ntoa(ip->ip_src));
819 ksnprintf(SNPARGS(proto, len), " %s",
820 inet_ntoa(ip->ip_dst));
824 if (ip_off & (IP_MF | IP_OFFMASK)) {
825 ksnprintf(SNPARGS(fragment, 0), " (frag %d:%d@%d%s)",
826 ntohs(ip->ip_id), ip_len - (ip->ip_hl << 2),
827 offset << 3, (ip_off & IP_MF) ? "+" : "");
831 if (oif || m->m_pkthdr.rcvif) {
832 log(LOG_SECURITY | LOG_INFO,
833 "ipfw: %d %s %s %s via %s%s\n",
835 action, proto, oif ? "out" : "in",
836 oif ? oif->if_xname : m->m_pkthdr.rcvif->if_xname,
839 log(LOG_SECURITY | LOG_INFO,
840 "ipfw: %d %s %s [no if info]%s\n",
842 action, proto, fragment);
846 log(LOG_SECURITY | LOG_NOTICE,
847 "ipfw: limit %d reached on entry %d\n",
848 limit_reached, f ? f->rulenum : -1);
855 * IMPORTANT: the hash function for dynamic rules must be commutative
856 * in source and destination (ip,port), because rules are bidirectional
857 * and we want to find both in the same bucket.
860 hash_packet(struct ipfw_flow_id *id)
864 i = (id->dst_ip) ^ (id->src_ip) ^ (id->dst_port) ^ (id->src_port);
865 i &= (curr_dyn_buckets - 1);
870 * unlink a dynamic rule from a chain. prev is a pointer to
871 * the previous one, q is a pointer to the rule to delete,
872 * head is a pointer to the head of the queue.
873 * Modifies q and potentially also head.
875 #define UNLINK_DYN_RULE(prev, head, q) \
877 ipfw_dyn_rule *old_q = q; \
879 /* remove a refcount to the parent */ \
880 if (q->dyn_type == O_LIMIT) \
881 q->parent->count--; \
882 DPRINTF("-- unlink entry 0x%08x %d -> 0x%08x %d, %d left\n", \
883 q->id.src_ip, q->id.src_port, \
884 q->id.dst_ip, q->id.dst_port, dyn_count - 1); \
886 prev->next = q = q->next; \
888 head = q = q->next; \
889 KASSERT(dyn_count > 0, ("invalid dyn count %u\n", dyn_count)); \
891 kfree(old_q, M_IPFW); \
894 #define TIME_LEQ(a, b) ((int)((a) - (b)) <= 0)
897 * Remove dynamic rules pointing to "rule", or all of them if rule == NULL.
899 * If keep_me == NULL, rules are deleted even if not expired,
900 * otherwise only expired rules are removed.
902 * The value of the second parameter is also used to point to identify
903 * a rule we absolutely do not want to remove (e.g. because we are
904 * holding a reference to it -- this is the case with O_LIMIT_PARENT
905 * rules). The pointer is only used for comparison, so any non-null
909 remove_dyn_rule_locked(struct ip_fw *rule, ipfw_dyn_rule *keep_me)
911 static uint32_t last_remove = 0; /* XXX */
913 #define FORCE (keep_me == NULL)
915 ipfw_dyn_rule *prev, *q;
916 int i, pass = 0, max_pass = 0, unlinked = 0;
918 if (ipfw_dyn_v == NULL || dyn_count == 0)
920 /* do not expire more than once per second, it is useless */
921 if (!FORCE && last_remove == time_second)
923 last_remove = time_second;
926 * because O_LIMIT refer to parent rules, during the first pass only
927 * remove child and mark any pending LIMIT_PARENT, and remove
928 * them in a second pass.
931 for (i = 0; i < curr_dyn_buckets; i++) {
932 for (prev = NULL, q = ipfw_dyn_v[i]; q;) {
934 * Logic can become complex here, so we split tests.
938 if (rule != NULL && rule->stub != q->stub)
939 goto next; /* not the one we are looking for */
940 if (q->dyn_type == O_LIMIT_PARENT) {
942 * handle parent in the second pass,
943 * record we need one.
948 if (FORCE && q->count != 0) {
949 /* XXX should not happen! */
950 kprintf("OUCH! cannot remove rule, "
951 "count %d\n", q->count);
954 if (!FORCE && !TIME_LEQ(q->expire, time_second))
958 UNLINK_DYN_RULE(prev, ipfw_dyn_v[i], q);
965 if (pass++ < max_pass)
975 * lookup a dynamic rule.
977 static ipfw_dyn_rule *
978 lookup_dyn_rule(struct ipfw_flow_id *pkt, int *match_direction,
982 * stateful ipfw extensions.
983 * Lookup into dynamic session queue
985 #define MATCH_REVERSE 0
986 #define MATCH_FORWARD 1
988 #define MATCH_UNKNOWN 3
989 int i, dir = MATCH_NONE;
990 ipfw_dyn_rule *prev, *q=NULL;
992 if (ipfw_dyn_v == NULL)
993 goto done; /* not found */
995 i = hash_packet(pkt);
996 for (prev = NULL, q = ipfw_dyn_v[i]; q != NULL;) {
997 if (q->dyn_type == O_LIMIT_PARENT)
1000 if (TIME_LEQ(q->expire, time_second)) {
1002 * Entry expired; skip.
1003 * Let ipfw_tick() take care of it
1008 if (pkt->proto == q->id.proto) {
1009 if (pkt->src_ip == q->id.src_ip &&
1010 pkt->dst_ip == q->id.dst_ip &&
1011 pkt->src_port == q->id.src_port &&
1012 pkt->dst_port == q->id.dst_port) {
1013 dir = MATCH_FORWARD;
1016 if (pkt->src_ip == q->id.dst_ip &&
1017 pkt->dst_ip == q->id.src_ip &&
1018 pkt->src_port == q->id.dst_port &&
1019 pkt->dst_port == q->id.src_port) {
1020 dir = MATCH_REVERSE;
1029 goto done; /* q = NULL, not found */
1031 if (pkt->proto == IPPROTO_TCP) { /* update state according to flags */
1032 u_char flags = pkt->flags & (TH_FIN|TH_SYN|TH_RST);
1034 #define BOTH_SYN (TH_SYN | (TH_SYN << 8))
1035 #define BOTH_FIN (TH_FIN | (TH_FIN << 8))
1037 q->state |= (dir == MATCH_FORWARD ) ? flags : (flags << 8);
1039 case TH_SYN: /* opening */
1040 q->expire = time_second + dyn_syn_lifetime;
1043 case BOTH_SYN: /* move to established */
1044 case BOTH_SYN | TH_FIN : /* one side tries to close */
1045 case BOTH_SYN | (TH_FIN << 8) :
1047 uint32_t ack = ntohl(tcp->th_ack);
1049 #define _SEQ_GE(a, b) ((int)(a) - (int)(b) >= 0)
1051 if (dir == MATCH_FORWARD) {
1052 if (q->ack_fwd == 0 ||
1053 _SEQ_GE(ack, q->ack_fwd))
1055 else /* ignore out-of-sequence */
1058 if (q->ack_rev == 0 ||
1059 _SEQ_GE(ack, q->ack_rev))
1061 else /* ignore out-of-sequence */
1066 q->expire = time_second + dyn_ack_lifetime;
1069 case BOTH_SYN | BOTH_FIN: /* both sides closed */
1070 KKASSERT(dyn_fin_lifetime < dyn_keepalive_period);
1071 q->expire = time_second + dyn_fin_lifetime;
1077 * reset or some invalid combination, but can also
1078 * occur if we use keep-state the wrong way.
1080 if ((q->state & ((TH_RST << 8) | TH_RST)) == 0)
1081 kprintf("invalid state: 0x%x\n", q->state);
1083 KKASSERT(dyn_rst_lifetime < dyn_keepalive_period);
1084 q->expire = time_second + dyn_rst_lifetime;
1087 } else if (pkt->proto == IPPROTO_UDP) {
1088 q->expire = time_second + dyn_udp_lifetime;
1090 /* other protocols */
1091 q->expire = time_second + dyn_short_lifetime;
1094 if (match_direction)
1095 *match_direction = dir;
1099 static struct ip_fw *
1100 lookup_rule(struct ipfw_flow_id *pkt, int *match_direction, struct tcphdr *tcp,
1101 uint16_t len, int *deny)
1103 struct ip_fw *rule = NULL;
1105 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
1109 gen = ctx->ipfw_gen;
1111 lockmgr(&dyn_lock, LK_SHARED);
1113 if (ctx->ipfw_gen != gen) {
1115 * Static rules had been change when we were waiting
1116 * for the dynamic hash table lock; deny this packet,
1117 * since it is _not_ known whether it is safe to keep
1118 * iterating the static rules.
1124 q = lookup_dyn_rule(pkt, match_direction, tcp);
1128 rule = q->stub->rule[mycpuid];
1129 KKASSERT(rule->stub == q->stub && rule->cpuid == mycpuid);
1136 lockmgr(&dyn_lock, LK_RELEASE);
1141 realloc_dynamic_table(void)
1143 ipfw_dyn_rule **old_dyn_v;
1144 uint32_t old_curr_dyn_buckets;
1146 KASSERT(dyn_buckets <= 65536 && (dyn_buckets & (dyn_buckets - 1)) == 0,
1147 ("invalid dyn_buckets %d\n", dyn_buckets));
1149 /* Save the current buckets array for later error recovery */
1150 old_dyn_v = ipfw_dyn_v;
1151 old_curr_dyn_buckets = curr_dyn_buckets;
1153 curr_dyn_buckets = dyn_buckets;
1155 ipfw_dyn_v = kmalloc(curr_dyn_buckets * sizeof(ipfw_dyn_rule *),
1156 M_IPFW, M_NOWAIT | M_ZERO);
1157 if (ipfw_dyn_v != NULL || curr_dyn_buckets <= 2)
1160 curr_dyn_buckets /= 2;
1161 if (curr_dyn_buckets <= old_curr_dyn_buckets &&
1162 old_dyn_v != NULL) {
1164 * Don't try allocating smaller buckets array, reuse
1165 * the old one, which alreay contains enough buckets
1171 if (ipfw_dyn_v != NULL) {
1172 if (old_dyn_v != NULL)
1173 kfree(old_dyn_v, M_IPFW);
1175 /* Allocation failed, restore old buckets array */
1176 ipfw_dyn_v = old_dyn_v;
1177 curr_dyn_buckets = old_curr_dyn_buckets;
1180 if (ipfw_dyn_v != NULL)
1185 * Install state of type 'type' for a dynamic session.
1186 * The hash table contains two type of rules:
1187 * - regular rules (O_KEEP_STATE)
1188 * - rules for sessions with limited number of sess per user
1189 * (O_LIMIT). When they are created, the parent is
1190 * increased by 1, and decreased on delete. In this case,
1191 * the third parameter is the parent rule and not the chain.
1192 * - "parent" rules for the above (O_LIMIT_PARENT).
1194 static ipfw_dyn_rule *
1195 add_dyn_rule(struct ipfw_flow_id *id, uint8_t dyn_type, struct ip_fw *rule)
1200 if (ipfw_dyn_v == NULL ||
1201 (dyn_count == 0 && dyn_buckets != curr_dyn_buckets)) {
1202 realloc_dynamic_table();
1203 if (ipfw_dyn_v == NULL)
1204 return NULL; /* failed ! */
1206 i = hash_packet(id);
1208 r = kmalloc(sizeof(*r), M_IPFW, M_NOWAIT | M_ZERO);
1210 kprintf ("sorry cannot allocate state\n");
1214 /* increase refcount on parent, and set pointer */
1215 if (dyn_type == O_LIMIT) {
1216 ipfw_dyn_rule *parent = (ipfw_dyn_rule *)rule;
1218 if (parent->dyn_type != O_LIMIT_PARENT)
1219 panic("invalid parent");
1222 rule = parent->stub->rule[mycpuid];
1223 KKASSERT(rule->stub == parent->stub);
1225 KKASSERT(rule->cpuid == mycpuid && rule->stub != NULL);
1228 r->expire = time_second + dyn_syn_lifetime;
1229 r->stub = rule->stub;
1230 r->dyn_type = dyn_type;
1231 r->pcnt = r->bcnt = 0;
1235 r->next = ipfw_dyn_v[i];
1239 DPRINTF("-- add dyn entry ty %d 0x%08x %d -> 0x%08x %d, total %d\n",
1241 r->id.src_ip, r->id.src_port,
1242 r->id.dst_ip, r->id.dst_port, dyn_count);
1247 * lookup dynamic parent rule using pkt and rule as search keys.
1248 * If the lookup fails, then install one.
1250 static ipfw_dyn_rule *
1251 lookup_dyn_parent(struct ipfw_flow_id *pkt, struct ip_fw *rule)
1257 i = hash_packet(pkt);
1258 for (q = ipfw_dyn_v[i]; q != NULL; q = q->next) {
1259 if (q->dyn_type == O_LIMIT_PARENT &&
1260 rule->stub == q->stub &&
1261 pkt->proto == q->id.proto &&
1262 pkt->src_ip == q->id.src_ip &&
1263 pkt->dst_ip == q->id.dst_ip &&
1264 pkt->src_port == q->id.src_port &&
1265 pkt->dst_port == q->id.dst_port) {
1266 q->expire = time_second + dyn_short_lifetime;
1267 DPRINTF("lookup_dyn_parent found 0x%p\n", q);
1272 return add_dyn_rule(pkt, O_LIMIT_PARENT, rule);
1276 * Install dynamic state for rule type cmd->o.opcode
1278 * Returns 1 (failure) if state is not installed because of errors or because
1279 * session limitations are enforced.
1282 install_state_locked(struct ip_fw *rule, ipfw_insn_limit *cmd,
1283 struct ip_fw_args *args)
1285 static int last_log; /* XXX */
1289 DPRINTF("-- install state type %d 0x%08x %u -> 0x%08x %u\n",
1291 args->f_id.src_ip, args->f_id.src_port,
1292 args->f_id.dst_ip, args->f_id.dst_port);
1294 q = lookup_dyn_rule(&args->f_id, NULL, NULL);
1295 if (q != NULL) { /* should never occur */
1296 if (last_log != time_second) {
1297 last_log = time_second;
1298 kprintf(" install_state: entry already present, done\n");
1303 if (dyn_count >= dyn_max) {
1305 * Run out of slots, try to remove any expired rule.
1307 remove_dyn_rule_locked(NULL, (ipfw_dyn_rule *)1);
1308 if (dyn_count >= dyn_max) {
1309 if (last_log != time_second) {
1310 last_log = time_second;
1311 kprintf("install_state: "
1312 "Too many dynamic rules\n");
1314 return 1; /* cannot install, notify caller */
1318 switch (cmd->o.opcode) {
1319 case O_KEEP_STATE: /* bidir rule */
1320 if (add_dyn_rule(&args->f_id, O_KEEP_STATE, rule) == NULL)
1324 case O_LIMIT: /* limit number of sessions */
1326 uint16_t limit_mask = cmd->limit_mask;
1327 struct ipfw_flow_id id;
1328 ipfw_dyn_rule *parent;
1330 DPRINTF("installing dyn-limit rule %d\n",
1333 id.dst_ip = id.src_ip = 0;
1334 id.dst_port = id.src_port = 0;
1335 id.proto = args->f_id.proto;
1337 if (limit_mask & DYN_SRC_ADDR)
1338 id.src_ip = args->f_id.src_ip;
1339 if (limit_mask & DYN_DST_ADDR)
1340 id.dst_ip = args->f_id.dst_ip;
1341 if (limit_mask & DYN_SRC_PORT)
1342 id.src_port = args->f_id.src_port;
1343 if (limit_mask & DYN_DST_PORT)
1344 id.dst_port = args->f_id.dst_port;
1346 parent = lookup_dyn_parent(&id, rule);
1347 if (parent == NULL) {
1348 kprintf("add parent failed\n");
1352 if (parent->count >= cmd->conn_limit) {
1354 * See if we can remove some expired rule.
1356 remove_dyn_rule_locked(rule, parent);
1357 if (parent->count >= cmd->conn_limit) {
1359 last_log != time_second) {
1360 last_log = time_second;
1361 log(LOG_SECURITY | LOG_DEBUG,
1363 "too many entries\n");
1368 if (add_dyn_rule(&args->f_id, O_LIMIT,
1369 (struct ip_fw *)parent) == NULL)
1374 kprintf("unknown dynamic rule type %u\n", cmd->o.opcode);
1377 lookup_dyn_rule(&args->f_id, NULL, NULL); /* XXX just set lifetime */
1382 install_state(struct ip_fw *rule, ipfw_insn_limit *cmd,
1383 struct ip_fw_args *args, int *deny)
1385 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
1390 gen = ctx->ipfw_gen;
1392 lockmgr(&dyn_lock, LK_EXCLUSIVE);
1393 if (ctx->ipfw_gen != gen) {
1394 /* See the comment in lookup_rule() */
1397 ret = install_state_locked(rule, cmd, args);
1399 lockmgr(&dyn_lock, LK_RELEASE);
1405 * Transmit a TCP packet, containing either a RST or a keepalive.
1406 * When flags & TH_RST, we are sending a RST packet, because of a
1407 * "reset" action matched the packet.
1408 * Otherwise we are sending a keepalive, and flags & TH_
1411 send_pkt(struct ipfw_flow_id *id, uint32_t seq, uint32_t ack, int flags)
1416 struct route sro; /* fake route */
1418 MGETHDR(m, MB_DONTWAIT, MT_HEADER);
1421 m->m_pkthdr.rcvif = NULL;
1422 m->m_pkthdr.len = m->m_len = sizeof(struct ip) + sizeof(struct tcphdr);
1423 m->m_data += max_linkhdr;
1425 ip = mtod(m, struct ip *);
1426 bzero(ip, m->m_len);
1427 tcp = (struct tcphdr *)(ip + 1); /* no IP options */
1428 ip->ip_p = IPPROTO_TCP;
1432 * Assume we are sending a RST (or a keepalive in the reverse
1433 * direction), swap src and destination addresses and ports.
1435 ip->ip_src.s_addr = htonl(id->dst_ip);
1436 ip->ip_dst.s_addr = htonl(id->src_ip);
1437 tcp->th_sport = htons(id->dst_port);
1438 tcp->th_dport = htons(id->src_port);
1439 if (flags & TH_RST) { /* we are sending a RST */
1440 if (flags & TH_ACK) {
1441 tcp->th_seq = htonl(ack);
1442 tcp->th_ack = htonl(0);
1443 tcp->th_flags = TH_RST;
1447 tcp->th_seq = htonl(0);
1448 tcp->th_ack = htonl(seq);
1449 tcp->th_flags = TH_RST | TH_ACK;
1453 * We are sending a keepalive. flags & TH_SYN determines
1454 * the direction, forward if set, reverse if clear.
1455 * NOTE: seq and ack are always assumed to be correct
1456 * as set by the caller. This may be confusing...
1458 if (flags & TH_SYN) {
1460 * we have to rewrite the correct addresses!
1462 ip->ip_dst.s_addr = htonl(id->dst_ip);
1463 ip->ip_src.s_addr = htonl(id->src_ip);
1464 tcp->th_dport = htons(id->dst_port);
1465 tcp->th_sport = htons(id->src_port);
1467 tcp->th_seq = htonl(seq);
1468 tcp->th_ack = htonl(ack);
1469 tcp->th_flags = TH_ACK;
1473 * set ip_len to the payload size so we can compute
1474 * the tcp checksum on the pseudoheader
1475 * XXX check this, could save a couple of words ?
1477 ip->ip_len = htons(sizeof(struct tcphdr));
1478 tcp->th_sum = in_cksum(m, m->m_pkthdr.len);
1481 * now fill fields left out earlier
1483 ip->ip_ttl = ip_defttl;
1484 ip->ip_len = m->m_pkthdr.len;
1486 bzero(&sro, sizeof(sro));
1487 ip_rtaddr(ip->ip_dst, &sro);
1489 m->m_pkthdr.fw_flags |= IPFW_MBUF_GENERATED;
1490 ip_output(m, NULL, &sro, 0, NULL, NULL);
1496 * sends a reject message, consuming the mbuf passed as an argument.
1499 send_reject(struct ip_fw_args *args, int code, int offset, int ip_len)
1501 if (code != ICMP_REJECT_RST) { /* Send an ICMP unreach */
1502 /* We need the IP header in host order for icmp_error(). */
1503 if (args->eh != NULL) {
1504 struct ip *ip = mtod(args->m, struct ip *);
1506 ip->ip_len = ntohs(ip->ip_len);
1507 ip->ip_off = ntohs(ip->ip_off);
1509 icmp_error(args->m, ICMP_UNREACH, code, 0L, 0);
1510 } else if (offset == 0 && args->f_id.proto == IPPROTO_TCP) {
1511 struct tcphdr *const tcp =
1512 L3HDR(struct tcphdr, mtod(args->m, struct ip *));
1514 if ((tcp->th_flags & TH_RST) == 0) {
1515 send_pkt(&args->f_id, ntohl(tcp->th_seq),
1516 ntohl(tcp->th_ack), tcp->th_flags | TH_RST);
1527 * Given an ip_fw *, lookup_next_rule will return a pointer
1528 * to the next rule, which can be either the jump
1529 * target (for skipto instructions) or the next one in the list (in
1530 * all other cases including a missing jump target).
1531 * The result is also written in the "next_rule" field of the rule.
1532 * Backward jumps are not allowed, so start looking from the next
1535 * This never returns NULL -- in case we do not have an exact match,
1536 * the next rule is returned. When the ruleset is changed,
1537 * pointers are flushed so we are always correct.
1540 static struct ip_fw *
1541 lookup_next_rule(struct ip_fw *me)
1543 struct ip_fw *rule = NULL;
1546 /* look for action, in case it is a skipto */
1547 cmd = ACTION_PTR(me);
1548 if (cmd->opcode == O_LOG)
1550 if (cmd->opcode == O_SKIPTO) {
1551 for (rule = me->next; rule; rule = rule->next) {
1552 if (rule->rulenum >= cmd->arg1)
1556 if (rule == NULL) /* failure or not a skipto */
1558 me->next_rule = rule;
1563 _ipfw_match_uid(const struct ipfw_flow_id *fid, struct ifnet *oif,
1564 enum ipfw_opcodes opcode, uid_t uid)
1566 struct in_addr src_ip, dst_ip;
1567 struct inpcbinfo *pi;
1571 if (fid->proto == IPPROTO_TCP) {
1573 pi = &tcbinfo[mycpuid];
1574 } else if (fid->proto == IPPROTO_UDP) {
1582 * Values in 'fid' are in host byte order
1584 dst_ip.s_addr = htonl(fid->dst_ip);
1585 src_ip.s_addr = htonl(fid->src_ip);
1587 pcb = in_pcblookup_hash(pi,
1588 dst_ip, htons(fid->dst_port),
1589 src_ip, htons(fid->src_port),
1592 pcb = in_pcblookup_hash(pi,
1593 src_ip, htons(fid->src_port),
1594 dst_ip, htons(fid->dst_port),
1597 if (pcb == NULL || pcb->inp_socket == NULL)
1600 if (opcode == O_UID) {
1601 #define socheckuid(a,b) ((a)->so_cred->cr_uid != (b))
1602 return !socheckuid(pcb->inp_socket, uid);
1605 return groupmember(uid, pcb->inp_socket->so_cred);
1610 ipfw_match_uid(const struct ipfw_flow_id *fid, struct ifnet *oif,
1611 enum ipfw_opcodes opcode, uid_t uid, int *deny)
1613 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
1618 gen = ctx->ipfw_gen;
1621 if (gen != ctx->ipfw_gen) {
1622 /* See the comment in lookup_rule() */
1625 match = _ipfw_match_uid(fid, oif, opcode, uid);
1632 * The main check routine for the firewall.
1634 * All arguments are in args so we can modify them and return them
1635 * back to the caller.
1639 * args->m (in/out) The packet; we set to NULL when/if we nuke it.
1640 * Starts with the IP header.
1641 * args->eh (in) Mac header if present, or NULL for layer3 packet.
1642 * args->oif Outgoing interface, or NULL if packet is incoming.
1643 * The incoming interface is in the mbuf. (in)
1645 * args->rule Pointer to the last matching rule (in/out)
1646 * args->f_id Addresses grabbed from the packet (out)
1650 * If the packet was denied/rejected and has been dropped, *m is equal
1651 * to NULL upon return.
1653 * IP_FW_DENY the packet must be dropped.
1654 * IP_FW_PASS The packet is to be accepted and routed normally.
1655 * IP_FW_DIVERT Divert the packet to port (args->cookie)
1656 * IP_FW_TEE Tee the packet to port (args->cookie)
1657 * IP_FW_DUMMYNET Send the packet to pipe/queue (args->cookie)
1661 ipfw_chk(struct ip_fw_args *args)
1664 * Local variables hold state during the processing of a packet.
1666 * IMPORTANT NOTE: to speed up the processing of rules, there
1667 * are some assumption on the values of the variables, which
1668 * are documented here. Should you change them, please check
1669 * the implementation of the various instructions to make sure
1670 * that they still work.
1672 * args->eh The MAC header. It is non-null for a layer2
1673 * packet, it is NULL for a layer-3 packet.
1675 * m | args->m Pointer to the mbuf, as received from the caller.
1676 * It may change if ipfw_chk() does an m_pullup, or if it
1677 * consumes the packet because it calls send_reject().
1678 * XXX This has to change, so that ipfw_chk() never modifies
1679 * or consumes the buffer.
1680 * ip is simply an alias of the value of m, and it is kept
1681 * in sync with it (the packet is supposed to start with
1684 struct mbuf *m = args->m;
1685 struct ip *ip = mtod(m, struct ip *);
1688 * oif | args->oif If NULL, ipfw_chk has been called on the
1689 * inbound path (ether_input, ip_input).
1690 * If non-NULL, ipfw_chk has been called on the outbound path
1691 * (ether_output, ip_output).
1693 struct ifnet *oif = args->oif;
1695 struct ip_fw *f = NULL; /* matching rule */
1696 int retval = IP_FW_PASS;
1698 struct divert_info *divinfo;
1701 * hlen The length of the IPv4 header.
1702 * hlen >0 means we have an IPv4 packet.
1704 u_int hlen = 0; /* hlen >0 means we have an IP pkt */
1707 * offset The offset of a fragment. offset != 0 means that
1708 * we have a fragment at this offset of an IPv4 packet.
1709 * offset == 0 means that (if this is an IPv4 packet)
1710 * this is the first or only fragment.
1715 * Local copies of addresses. They are only valid if we have
1718 * proto The protocol. Set to 0 for non-ip packets,
1719 * or to the protocol read from the packet otherwise.
1720 * proto != 0 means that we have an IPv4 packet.
1722 * src_port, dst_port port numbers, in HOST format. Only
1723 * valid for TCP and UDP packets.
1725 * src_ip, dst_ip ip addresses, in NETWORK format.
1726 * Only valid for IPv4 packets.
1729 uint16_t src_port = 0, dst_port = 0; /* NOTE: host format */
1730 struct in_addr src_ip, dst_ip; /* NOTE: network format */
1731 uint16_t ip_len = 0;
1734 * dyn_dir = MATCH_UNKNOWN when rules unchecked,
1735 * MATCH_NONE when checked and not matched (dyn_f = NULL),
1736 * MATCH_FORWARD or MATCH_REVERSE otherwise (dyn_f != NULL)
1738 int dyn_dir = MATCH_UNKNOWN;
1739 struct ip_fw *dyn_f = NULL;
1740 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
1742 if (m->m_pkthdr.fw_flags & IPFW_MBUF_GENERATED)
1743 return IP_FW_PASS; /* accept */
1745 if (args->eh == NULL || /* layer 3 packet */
1746 (m->m_pkthdr.len >= sizeof(struct ip) &&
1747 ntohs(args->eh->ether_type) == ETHERTYPE_IP))
1748 hlen = ip->ip_hl << 2;
1751 * Collect parameters into local variables for faster matching.
1753 if (hlen == 0) { /* do not grab addresses for non-ip pkts */
1754 proto = args->f_id.proto = 0; /* mark f_id invalid */
1755 goto after_ip_checks;
1758 proto = args->f_id.proto = ip->ip_p;
1759 src_ip = ip->ip_src;
1760 dst_ip = ip->ip_dst;
1761 if (args->eh != NULL) { /* layer 2 packets are as on the wire */
1762 offset = ntohs(ip->ip_off) & IP_OFFMASK;
1763 ip_len = ntohs(ip->ip_len);
1765 offset = ip->ip_off & IP_OFFMASK;
1766 ip_len = ip->ip_len;
1769 #define PULLUP_TO(len) \
1771 if (m->m_len < (len)) { \
1772 args->m = m = m_pullup(m, (len));\
1774 goto pullup_failed; \
1775 ip = mtod(m, struct ip *); \
1785 PULLUP_TO(hlen + sizeof(struct tcphdr));
1786 tcp = L3HDR(struct tcphdr, ip);
1787 dst_port = tcp->th_dport;
1788 src_port = tcp->th_sport;
1789 args->f_id.flags = tcp->th_flags;
1797 PULLUP_TO(hlen + sizeof(struct udphdr));
1798 udp = L3HDR(struct udphdr, ip);
1799 dst_port = udp->uh_dport;
1800 src_port = udp->uh_sport;
1805 PULLUP_TO(hlen + 4); /* type, code and checksum. */
1806 args->f_id.flags = L3HDR(struct icmp, ip)->icmp_type;
1816 args->f_id.src_ip = ntohl(src_ip.s_addr);
1817 args->f_id.dst_ip = ntohl(dst_ip.s_addr);
1818 args->f_id.src_port = src_port = ntohs(src_port);
1819 args->f_id.dst_port = dst_port = ntohs(dst_port);
1824 * Packet has already been tagged. Look for the next rule
1825 * to restart processing.
1827 * If fw_one_pass != 0 then just accept it.
1828 * XXX should not happen here, but optimized out in
1834 /* This rule is being/has been flushed */
1838 KASSERT(args->rule->cpuid == mycpuid,
1839 ("rule used on cpu%d\n", mycpuid));
1841 /* This rule was deleted */
1842 if (args->rule->rule_flags & IPFW_RULE_F_INVALID)
1845 f = args->rule->next_rule;
1847 f = lookup_next_rule(args->rule);
1850 * Find the starting rule. It can be either the first
1851 * one, or the one after divert_rule if asked so.
1855 mtag = m_tag_find(m, PACKET_TAG_IPFW_DIVERT, NULL);
1857 divinfo = m_tag_data(mtag);
1858 skipto = divinfo->skipto;
1863 f = ctx->ipfw_layer3_chain;
1864 if (args->eh == NULL && skipto != 0) {
1865 /* No skipto during rule flushing */
1869 if (skipto >= IPFW_DEFAULT_RULE)
1870 return IP_FW_DENY; /* invalid */
1872 while (f && f->rulenum <= skipto)
1874 if (f == NULL) /* drop packet */
1876 } else if (ipfw_flushing) {
1877 /* Rules are being flushed; skip to default rule */
1878 f = ctx->ipfw_default_rule;
1881 if ((mtag = m_tag_find(m, PACKET_TAG_IPFW_DIVERT, NULL)) != NULL)
1882 m_tag_delete(m, mtag);
1885 * Now scan the rules, and parse microinstructions for each rule.
1887 for (; f; f = f->next) {
1890 int skip_or; /* skip rest of OR block */
1893 if (ctx->ipfw_set_disable & (1 << f->set))
1897 for (l = f->cmd_len, cmd = f->cmd; l > 0;
1898 l -= cmdlen, cmd += cmdlen) {
1902 * check_body is a jump target used when we find a
1903 * CHECK_STATE, and need to jump to the body of
1908 cmdlen = F_LEN(cmd);
1910 * An OR block (insn_1 || .. || insn_n) has the
1911 * F_OR bit set in all but the last instruction.
1912 * The first match will set "skip_or", and cause
1913 * the following instructions to be skipped until
1914 * past the one with the F_OR bit clear.
1916 if (skip_or) { /* skip this instruction */
1917 if ((cmd->len & F_OR) == 0)
1918 skip_or = 0; /* next one is good */
1921 match = 0; /* set to 1 if we succeed */
1923 switch (cmd->opcode) {
1925 * The first set of opcodes compares the packet's
1926 * fields with some pattern, setting 'match' if a
1927 * match is found. At the end of the loop there is
1928 * logic to deal with F_NOT and F_OR flags associated
1936 kprintf("ipfw: opcode %d unimplemented\n",
1943 * We only check offset == 0 && proto != 0,
1944 * as this ensures that we have an IPv4
1945 * packet with the ports info.
1950 match = ipfw_match_uid(&args->f_id, oif,
1952 (uid_t)((ipfw_insn_u32 *)cmd)->d[0],
1959 match = iface_match(m->m_pkthdr.rcvif,
1960 (ipfw_insn_if *)cmd);
1964 match = iface_match(oif, (ipfw_insn_if *)cmd);
1968 match = iface_match(oif ? oif :
1969 m->m_pkthdr.rcvif, (ipfw_insn_if *)cmd);
1973 if (args->eh != NULL) { /* have MAC header */
1974 uint32_t *want = (uint32_t *)
1975 ((ipfw_insn_mac *)cmd)->addr;
1976 uint32_t *mask = (uint32_t *)
1977 ((ipfw_insn_mac *)cmd)->mask;
1978 uint32_t *hdr = (uint32_t *)args->eh;
1981 (want[0] == (hdr[0] & mask[0]) &&
1982 want[1] == (hdr[1] & mask[1]) &&
1983 want[2] == (hdr[2] & mask[2]));
1988 if (args->eh != NULL) {
1990 ntohs(args->eh->ether_type);
1992 ((ipfw_insn_u16 *)cmd)->ports;
1995 /* Special vlan handling */
1996 if (m->m_flags & M_VLANTAG)
1999 for (i = cmdlen - 1; !match && i > 0;
2002 (t >= p[0] && t <= p[1]);
2008 match = (hlen > 0 && offset != 0);
2011 case O_IN: /* "out" is "not in" */
2012 match = (oif == NULL);
2016 match = (args->eh != NULL);
2021 * We do not allow an arg of 0 so the
2022 * check of "proto" only suffices.
2024 match = (proto == cmd->arg1);
2028 match = (hlen > 0 &&
2029 ((ipfw_insn_ip *)cmd)->addr.s_addr ==
2034 match = (hlen > 0 &&
2035 ((ipfw_insn_ip *)cmd)->addr.s_addr ==
2037 ((ipfw_insn_ip *)cmd)->mask.s_addr));
2044 tif = INADDR_TO_IFP(&src_ip);
2045 match = (tif != NULL);
2052 uint32_t *d = (uint32_t *)(cmd + 1);
2054 cmd->opcode == O_IP_DST_SET ?
2060 addr -= d[0]; /* subtract base */
2062 (addr < cmd->arg1) &&
2063 (d[1 + (addr >> 5)] &
2064 (1 << (addr & 0x1f)));
2069 match = (hlen > 0 &&
2070 ((ipfw_insn_ip *)cmd)->addr.s_addr ==
2075 match = (hlen > 0) &&
2076 (((ipfw_insn_ip *)cmd)->addr.s_addr ==
2078 ((ipfw_insn_ip *)cmd)->mask.s_addr));
2085 tif = INADDR_TO_IFP(&dst_ip);
2086 match = (tif != NULL);
2093 * offset == 0 && proto != 0 is enough
2094 * to guarantee that we have an IPv4
2095 * packet with port info.
2097 if ((proto==IPPROTO_UDP || proto==IPPROTO_TCP)
2100 (cmd->opcode == O_IP_SRCPORT) ?
2101 src_port : dst_port ;
2103 ((ipfw_insn_u16 *)cmd)->ports;
2106 for (i = cmdlen - 1; !match && i > 0;
2109 (x >= p[0] && x <= p[1]);
2115 match = (offset == 0 && proto==IPPROTO_ICMP &&
2116 icmptype_match(ip, (ipfw_insn_u32 *)cmd));
2120 match = (hlen > 0 && ipopts_match(ip, cmd));
2124 match = (hlen > 0 && cmd->arg1 == ip->ip_v);
2128 match = (hlen > 0 && cmd->arg1 == ip->ip_ttl);
2132 match = (hlen > 0 &&
2133 cmd->arg1 == ntohs(ip->ip_id));
2137 match = (hlen > 0 && cmd->arg1 == ip_len);
2140 case O_IPPRECEDENCE:
2141 match = (hlen > 0 &&
2142 (cmd->arg1 == (ip->ip_tos & 0xe0)));
2146 match = (hlen > 0 &&
2147 flags_match(cmd, ip->ip_tos));
2151 match = (proto == IPPROTO_TCP && offset == 0 &&
2153 L3HDR(struct tcphdr,ip)->th_flags));
2157 match = (proto == IPPROTO_TCP && offset == 0 &&
2158 tcpopts_match(ip, cmd));
2162 match = (proto == IPPROTO_TCP && offset == 0 &&
2163 ((ipfw_insn_u32 *)cmd)->d[0] ==
2164 L3HDR(struct tcphdr,ip)->th_seq);
2168 match = (proto == IPPROTO_TCP && offset == 0 &&
2169 ((ipfw_insn_u32 *)cmd)->d[0] ==
2170 L3HDR(struct tcphdr,ip)->th_ack);
2174 match = (proto == IPPROTO_TCP && offset == 0 &&
2176 L3HDR(struct tcphdr,ip)->th_win);
2180 /* reject packets which have SYN only */
2181 /* XXX should i also check for TH_ACK ? */
2182 match = (proto == IPPROTO_TCP && offset == 0 &&
2183 (L3HDR(struct tcphdr,ip)->th_flags &
2184 (TH_RST | TH_ACK | TH_SYN)) != TH_SYN);
2189 ipfw_log(f, hlen, args->eh, m, oif);
2194 match = (krandom() <
2195 ((ipfw_insn_u32 *)cmd)->d[0]);
2199 * The second set of opcodes represents 'actions',
2200 * i.e. the terminal part of a rule once the packet
2201 * matches all previous patterns.
2202 * Typically there is only one action for each rule,
2203 * and the opcode is stored at the end of the rule
2204 * (but there are exceptions -- see below).
2206 * In general, here we set retval and terminate the
2207 * outer loop (would be a 'break 3' in some language,
2208 * but we need to do a 'goto done').
2211 * O_COUNT and O_SKIPTO actions:
2212 * instead of terminating, we jump to the next rule
2213 * ('goto next_rule', equivalent to a 'break 2'),
2214 * or to the SKIPTO target ('goto again' after
2215 * having set f, cmd and l), respectively.
2217 * O_LIMIT and O_KEEP_STATE: these opcodes are
2218 * not real 'actions', and are stored right
2219 * before the 'action' part of the rule.
2220 * These opcodes try to install an entry in the
2221 * state tables; if successful, we continue with
2222 * the next opcode (match=1; break;), otherwise
2223 * the packet must be dropped ('goto done' after
2224 * setting retval). If static rules are changed
2225 * during the state installation, the packet will
2226 * be dropped and rule's stats will not beupdated
2227 * ('return IP_FW_DENY').
2229 * O_PROBE_STATE and O_CHECK_STATE: these opcodes
2230 * cause a lookup of the state table, and a jump
2231 * to the 'action' part of the parent rule
2232 * ('goto check_body') if an entry is found, or
2233 * (CHECK_STATE only) a jump to the next rule if
2234 * the entry is not found ('goto next_rule').
2235 * The result of the lookup is cached to make
2236 * further instances of these opcodes are
2237 * effectively NOPs. If static rules are changed
2238 * during the state looking up, the packet will
2239 * be dropped and rule's stats will not be updated
2240 * ('return IP_FW_DENY').
2244 if (!(f->rule_flags & IPFW_RULE_F_STATE)) {
2245 kprintf("%s rule (%d) is not ready "
2247 cmd->opcode == O_LIMIT ?
2248 "limit" : "keep state",
2249 f->rulenum, f->cpuid);
2252 if (install_state(f,
2253 (ipfw_insn_limit *)cmd, args, &deny)) {
2257 retval = IP_FW_DENY;
2258 goto done; /* error/limit violation */
2268 * dynamic rules are checked at the first
2269 * keep-state or check-state occurrence,
2270 * with the result being stored in dyn_dir.
2271 * The compiler introduces a PROBE_STATE
2272 * instruction for us when we have a
2273 * KEEP_STATE (because PROBE_STATE needs
2276 if (dyn_dir == MATCH_UNKNOWN) {
2277 dyn_f = lookup_rule(&args->f_id,
2279 proto == IPPROTO_TCP ?
2280 L3HDR(struct tcphdr, ip) : NULL,
2284 if (dyn_f != NULL) {
2286 * Found a rule from a dynamic
2287 * entry; jump to the 'action'
2291 cmd = ACTION_PTR(f);
2292 l = f->cmd_len - f->act_ofs;
2297 * Dynamic entry not found. If CHECK_STATE,
2298 * skip to next rule, if PROBE_STATE just
2299 * ignore and continue with next opcode.
2301 if (cmd->opcode == O_CHECK_STATE)
2303 else if (!(f->rule_flags & IPFW_RULE_F_STATE))
2304 goto next_rule; /* not ready yet */
2309 retval = IP_FW_PASS; /* accept */
2314 args->rule = f; /* report matching rule */
2315 args->cookie = cmd->arg1;
2316 retval = IP_FW_DUMMYNET;
2321 if (args->eh) /* not on layer 2 */
2324 mtag = m_tag_get(PACKET_TAG_IPFW_DIVERT,
2325 sizeof(*divinfo), MB_DONTWAIT);
2327 retval = IP_FW_DENY;
2330 divinfo = m_tag_data(mtag);
2332 divinfo->skipto = f->rulenum;
2333 divinfo->port = cmd->arg1;
2334 divinfo->tee = (cmd->opcode == O_TEE);
2335 m_tag_prepend(m, mtag);
2337 args->cookie = cmd->arg1;
2338 retval = (cmd->opcode == O_DIVERT) ?
2339 IP_FW_DIVERT : IP_FW_TEE;
2344 f->pcnt++; /* update stats */
2346 f->timestamp = time_second;
2347 if (cmd->opcode == O_COUNT)
2350 if (f->next_rule == NULL)
2351 lookup_next_rule(f);
2357 * Drop the packet and send a reject notice
2358 * if the packet is not ICMP (or is an ICMP
2359 * query), and it is not multicast/broadcast.
2362 (proto != IPPROTO_ICMP ||
2363 is_icmp_query(ip)) &&
2364 !(m->m_flags & (M_BCAST|M_MCAST)) &&
2365 !IN_MULTICAST(ntohl(dst_ip.s_addr))) {
2367 * Update statistics before the possible
2368 * blocking 'send_reject'
2372 f->timestamp = time_second;
2374 send_reject(args, cmd->arg1,
2379 * Return directly here, rule stats
2380 * have been updated above.
2386 retval = IP_FW_DENY;
2390 if (args->eh) /* not valid on layer2 pkts */
2392 if (!dyn_f || dyn_dir == MATCH_FORWARD) {
2393 struct sockaddr_in *sin;
2395 mtag = m_tag_get(PACKET_TAG_IPFORWARD,
2396 sizeof(*sin), MB_DONTWAIT);
2398 retval = IP_FW_DENY;
2401 sin = m_tag_data(mtag);
2403 /* Structure copy */
2404 *sin = ((ipfw_insn_sa *)cmd)->sa;
2406 m_tag_prepend(m, mtag);
2407 m->m_pkthdr.fw_flags |=
2408 IPFORWARD_MBUF_TAGGED;
2410 retval = IP_FW_PASS;
2414 panic("-- unknown opcode %d\n", cmd->opcode);
2415 } /* end of switch() on opcodes */
2417 if (cmd->len & F_NOT)
2421 if (cmd->len & F_OR)
2424 if (!(cmd->len & F_OR)) /* not an OR block, */
2425 break; /* try next rule */
2428 } /* end of inner for, scan opcodes */
2430 next_rule:; /* try next rule */
2432 } /* end of outer for, scan rules */
2433 kprintf("+++ ipfw: ouch!, skip past end of rules, denying packet\n");
2437 /* Update statistics */
2440 f->timestamp = time_second;
2445 kprintf("pullup failed\n");
2450 ipfw_dummynet_io(struct mbuf *m, int pipe_nr, int dir, struct ip_fw_args *fwa)
2455 const struct ipfw_flow_id *id;
2456 struct dn_flow_id *fid;
2460 mtag = m_tag_get(PACKET_TAG_DUMMYNET, sizeof(*pkt), MB_DONTWAIT);
2465 m_tag_prepend(m, mtag);
2467 pkt = m_tag_data(mtag);
2468 bzero(pkt, sizeof(*pkt));
2470 cmd = fwa->rule->cmd + fwa->rule->act_ofs;
2471 if (cmd->opcode == O_LOG)
2473 KASSERT(cmd->opcode == O_PIPE || cmd->opcode == O_QUEUE,
2474 ("Rule is not PIPE or QUEUE, opcode %d\n", cmd->opcode));
2477 pkt->dn_flags = (dir & DN_FLAGS_DIR_MASK);
2478 pkt->ifp = fwa->oif;
2479 pkt->cpuid = mycpuid;
2480 pkt->pipe_nr = pipe_nr;
2484 fid->fid_dst_ip = id->dst_ip;
2485 fid->fid_src_ip = id->src_ip;
2486 fid->fid_dst_port = id->dst_port;
2487 fid->fid_src_port = id->src_port;
2488 fid->fid_proto = id->proto;
2489 fid->fid_flags = id->flags;
2491 ipfw_ref_rule(fwa->rule);
2492 pkt->dn_priv = fwa->rule;
2493 pkt->dn_unref_priv = ipfw_unref_rule;
2495 if (cmd->opcode == O_PIPE)
2496 pkt->dn_flags |= DN_FLAGS_IS_PIPE;
2498 m->m_pkthdr.fw_flags |= DUMMYNET_MBUF_TAGGED;
2502 * When a rule is added/deleted, clear the next_rule pointers in all rules.
2503 * These will be reconstructed on the fly as packets are matched.
2504 * Must be called at splimp().
2507 ipfw_flush_rule_ptrs(struct ipfw_context *ctx)
2511 for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next)
2512 rule->next_rule = NULL;
2515 static __inline void
2516 ipfw_inc_static_count(struct ip_fw *rule)
2518 KKASSERT(mycpuid == 0);
2521 static_ioc_len += IOC_RULESIZE(rule);
2524 static __inline void
2525 ipfw_dec_static_count(struct ip_fw *rule)
2527 int l = IOC_RULESIZE(rule);
2529 KKASSERT(mycpuid == 0);
2531 KASSERT(static_count > 0, ("invalid static count %u\n", static_count));
2534 KASSERT(static_ioc_len >= l,
2535 ("invalid static len %u\n", static_ioc_len));
2536 static_ioc_len -= l;
2540 ipfw_link_sibling(struct netmsg_ipfw *fwmsg, struct ip_fw *rule)
2542 if (fwmsg->sibling != NULL) {
2543 KKASSERT(mycpuid > 0 && fwmsg->sibling->cpuid == mycpuid - 1);
2544 fwmsg->sibling->sibling = rule;
2546 fwmsg->sibling = rule;
2549 static struct ip_fw *
2550 ipfw_create_rule(const struct ipfw_ioc_rule *ioc_rule, struct ip_fw_stub *stub)
2554 rule = kmalloc(RULESIZE(ioc_rule), M_IPFW, M_WAITOK | M_ZERO);
2556 rule->act_ofs = ioc_rule->act_ofs;
2557 rule->cmd_len = ioc_rule->cmd_len;
2558 rule->rulenum = ioc_rule->rulenum;
2559 rule->set = ioc_rule->set;
2560 rule->usr_flags = ioc_rule->usr_flags;
2562 bcopy(ioc_rule->cmd, rule->cmd, rule->cmd_len * 4 /* XXX */);
2565 rule->cpuid = mycpuid;
2569 stub->rule[mycpuid] = rule;
2575 ipfw_add_rule_dispatch(struct netmsg *nmsg)
2577 struct netmsg_ipfw *fwmsg = (struct netmsg_ipfw *)nmsg;
2578 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2581 rule = ipfw_create_rule(fwmsg->ioc_rule, fwmsg->stub);
2584 * Bump generation after ipfw_create_rule(),
2585 * since this function is blocking
2590 * Insert rule into the pre-determined position
2592 if (fwmsg->prev_rule != NULL) {
2593 struct ip_fw *prev, *next;
2595 prev = fwmsg->prev_rule;
2596 KKASSERT(prev->cpuid == mycpuid);
2598 next = fwmsg->next_rule;
2599 KKASSERT(next->cpuid == mycpuid);
2605 * Move to the position on the next CPU
2606 * before the msg is forwarded.
2608 fwmsg->prev_rule = prev->sibling;
2609 fwmsg->next_rule = next->sibling;
2611 KKASSERT(fwmsg->next_rule == NULL);
2612 rule->next = ctx->ipfw_layer3_chain;
2613 ctx->ipfw_layer3_chain = rule;
2616 /* Link rule CPU sibling */
2617 ipfw_link_sibling(fwmsg, rule);
2619 ipfw_flush_rule_ptrs(ctx);
2622 /* Statistics only need to be updated once */
2623 ipfw_inc_static_count(rule);
2625 /* Return the rule on CPU0 */
2626 nmsg->nm_lmsg.u.ms_resultp = rule;
2629 ifnet_forwardmsg(&nmsg->nm_lmsg, mycpuid + 1);
2633 ipfw_enable_state_dispatch(struct netmsg *nmsg)
2635 struct lwkt_msg *lmsg = &nmsg->nm_lmsg;
2636 struct ip_fw *rule = lmsg->u.ms_resultp;
2637 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2641 KKASSERT(rule->cpuid == mycpuid);
2642 KKASSERT(rule->stub != NULL && rule->stub->rule[mycpuid] == rule);
2643 KKASSERT(!(rule->rule_flags & IPFW_RULE_F_STATE));
2644 rule->rule_flags |= IPFW_RULE_F_STATE;
2645 lmsg->u.ms_resultp = rule->sibling;
2647 ifnet_forwardmsg(lmsg, mycpuid + 1);
2651 * Add a new rule to the list. Copy the rule into a malloc'ed area,
2652 * then possibly create a rule number and add the rule to the list.
2653 * Update the rule_number in the input struct so the caller knows
2657 ipfw_add_rule(struct ipfw_ioc_rule *ioc_rule, uint32_t rule_flags)
2659 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2660 struct netmsg_ipfw fwmsg;
2661 struct netmsg *nmsg;
2662 struct ip_fw *f, *prev, *rule;
2663 struct ip_fw_stub *stub;
2665 IPFW_ASSERT_CFGPORT(&curthread->td_msgport);
2668 * If rulenum is 0, find highest numbered rule before the
2669 * default rule, and add rule number incremental step.
2671 if (ioc_rule->rulenum == 0) {
2672 int step = autoinc_step;
2674 KKASSERT(step >= IPFW_AUTOINC_STEP_MIN &&
2675 step <= IPFW_AUTOINC_STEP_MAX);
2678 * Locate the highest numbered rule before default
2680 for (f = ctx->ipfw_layer3_chain; f; f = f->next) {
2681 if (f->rulenum == IPFW_DEFAULT_RULE)
2683 ioc_rule->rulenum = f->rulenum;
2685 if (ioc_rule->rulenum < IPFW_DEFAULT_RULE - step)
2686 ioc_rule->rulenum += step;
2688 KASSERT(ioc_rule->rulenum != IPFW_DEFAULT_RULE &&
2689 ioc_rule->rulenum != 0,
2690 ("invalid rule num %d\n", ioc_rule->rulenum));
2693 * Now find the right place for the new rule in the sorted list.
2695 for (prev = NULL, f = ctx->ipfw_layer3_chain; f;
2696 prev = f, f = f->next) {
2697 if (f->rulenum > ioc_rule->rulenum) {
2698 /* Found the location */
2702 KASSERT(f != NULL, ("no default rule?!\n"));
2704 if (rule_flags & IPFW_RULE_F_STATE) {
2708 * If the new rule will create states, then allocate
2709 * a rule stub, which will be referenced by states
2712 size = sizeof(*stub) + ((ncpus - 1) * sizeof(struct ip_fw *));
2713 stub = kmalloc(size, M_IPFW, M_WAITOK | M_ZERO);
2719 * Duplicate the rule onto each CPU.
2720 * The rule duplicated on CPU0 will be returned.
2722 bzero(&fwmsg, sizeof(fwmsg));
2724 netmsg_init(nmsg, &curthread->td_msgport, 0, ipfw_add_rule_dispatch);
2725 fwmsg.ioc_rule = ioc_rule;
2726 fwmsg.prev_rule = prev;
2727 fwmsg.next_rule = prev == NULL ? NULL : f;
2730 ifnet_domsg(&nmsg->nm_lmsg, 0);
2731 KKASSERT(fwmsg.prev_rule == NULL && fwmsg.next_rule == NULL);
2733 rule = nmsg->nm_lmsg.u.ms_resultp;
2734 KKASSERT(rule != NULL && rule->cpuid == mycpuid);
2736 if (rule_flags & IPFW_RULE_F_STATE) {
2738 * Turn on state flag, _after_ everything on all
2739 * CPUs have been setup.
2741 bzero(nmsg, sizeof(*nmsg));
2742 netmsg_init(nmsg, &curthread->td_msgport, 0,
2743 ipfw_enable_state_dispatch);
2744 nmsg->nm_lmsg.u.ms_resultp = rule;
2746 ifnet_domsg(&nmsg->nm_lmsg, 0);
2747 KKASSERT(nmsg->nm_lmsg.u.ms_resultp == NULL);
2750 DPRINTF("++ installed rule %d, static count now %d\n",
2751 rule->rulenum, static_count);
2755 * Free storage associated with a static rule (including derived
2757 * The caller is in charge of clearing rule pointers to avoid
2758 * dangling pointers.
2759 * @return a pointer to the next entry.
2760 * Arguments are not checked, so they better be correct.
2761 * Must be called at splimp().
2763 static struct ip_fw *
2764 ipfw_delete_rule(struct ipfw_context *ctx,
2765 struct ip_fw *prev, struct ip_fw *rule)
2768 struct ip_fw_stub *stub;
2772 /* STATE flag should have been cleared before we reach here */
2773 KKASSERT((rule->rule_flags & IPFW_RULE_F_STATE) == 0);
2778 ctx->ipfw_layer3_chain = n;
2782 /* Mark the rule as invalid */
2783 rule->rule_flags |= IPFW_RULE_F_INVALID;
2784 rule->next_rule = NULL;
2785 rule->sibling = NULL;
2788 /* Don't reset cpuid here; keep various assertion working */
2792 /* Statistics only need to be updated once */
2794 ipfw_dec_static_count(rule);
2796 /* Free 'stub' on the last CPU */
2797 if (stub != NULL && mycpuid == ncpus - 1)
2798 kfree(stub, M_IPFW);
2800 /* Try to free this rule */
2801 ipfw_free_rule(rule);
2803 /* Return the next rule */
2808 ipfw_flush_dispatch(struct netmsg *nmsg)
2810 struct lwkt_msg *lmsg = &nmsg->nm_lmsg;
2811 int kill_default = lmsg->u.ms_result;
2812 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2815 ipfw_flush_rule_ptrs(ctx); /* more efficient to do outside the loop */
2817 while ((rule = ctx->ipfw_layer3_chain) != NULL &&
2818 (kill_default || rule->rulenum != IPFW_DEFAULT_RULE))
2819 ipfw_delete_rule(ctx, NULL, rule);
2821 ifnet_forwardmsg(lmsg, mycpuid + 1);
2825 ipfw_disable_rule_state_dispatch(struct netmsg *nmsg)
2827 struct netmsg_del *dmsg = (struct netmsg_del *)nmsg;
2828 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2833 rule = dmsg->start_rule;
2835 KKASSERT(rule->cpuid == mycpuid);
2838 * Move to the position on the next CPU
2839 * before the msg is forwarded.
2841 dmsg->start_rule = rule->sibling;
2843 KKASSERT(dmsg->rulenum == 0);
2844 rule = ctx->ipfw_layer3_chain;
2847 while (rule != NULL) {
2848 if (dmsg->rulenum && rule->rulenum != dmsg->rulenum)
2850 rule->rule_flags &= ~IPFW_RULE_F_STATE;
2854 ifnet_forwardmsg(&nmsg->nm_lmsg, mycpuid + 1);
2858 * Deletes all rules from a chain (including the default rule
2859 * if the second argument is set).
2860 * Must be called at splimp().
2863 ipfw_flush(int kill_default)
2865 struct netmsg_del dmsg;
2867 struct lwkt_msg *lmsg;
2869 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2871 IPFW_ASSERT_CFGPORT(&curthread->td_msgport);
2874 * If 'kill_default' then caller has done the necessary
2875 * msgport syncing; unnecessary to do it again.
2877 if (!kill_default) {
2879 * Let ipfw_chk() know the rules are going to
2880 * be flushed, so it could jump directly to
2884 netmsg_service_sync();
2888 * Clear STATE flag on rules, so no more states (dyn rules)
2891 bzero(&dmsg, sizeof(dmsg));
2892 netmsg_init(&dmsg.nmsg, &curthread->td_msgport, 0,
2893 ipfw_disable_rule_state_dispatch);
2894 ifnet_domsg(&dmsg.nmsg.nm_lmsg, 0);
2897 * This actually nukes all states (dyn rules)
2899 lockmgr(&dyn_lock, LK_EXCLUSIVE);
2900 for (rule = ctx->ipfw_layer3_chain; rule != NULL; rule = rule->next) {
2902 * Can't check IPFW_RULE_F_STATE here,
2903 * since it has been cleared previously.
2904 * Check 'stub' instead.
2906 if (rule->stub != NULL) {
2908 remove_dyn_rule_locked(rule, NULL);
2911 lockmgr(&dyn_lock, LK_RELEASE);
2914 * Press the 'flush' button
2916 bzero(&nmsg, sizeof(nmsg));
2917 netmsg_init(&nmsg, &curthread->td_msgport, 0, ipfw_flush_dispatch);
2918 lmsg = &nmsg.nm_lmsg;
2919 lmsg->u.ms_result = kill_default;
2920 ifnet_domsg(lmsg, 0);
2922 KASSERT(dyn_count == 0, ("%u dyn rule remains\n", dyn_count));
2925 if (ipfw_dyn_v != NULL) {
2927 * Free dynamic rules(state) hash table
2929 kfree(ipfw_dyn_v, M_IPFW);
2933 KASSERT(static_count == 0,
2934 ("%u static rules remains\n", static_count));
2935 KASSERT(static_ioc_len == 0,
2936 ("%u bytes of static rules remains\n", static_ioc_len));
2938 KASSERT(static_count == 1,
2939 ("%u static rules remains\n", static_count));
2940 KASSERT(static_ioc_len == IOC_RULESIZE(ctx->ipfw_default_rule),
2941 ("%u bytes of static rules remains, should be %u\n",
2942 static_ioc_len, IOC_RULESIZE(ctx->ipfw_default_rule)));
2950 ipfw_alt_delete_rule_dispatch(struct netmsg *nmsg)
2952 struct netmsg_del *dmsg = (struct netmsg_del *)nmsg;
2953 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2954 struct ip_fw *rule, *prev;
2956 rule = dmsg->start_rule;
2957 KKASSERT(rule->cpuid == mycpuid);
2958 dmsg->start_rule = rule->sibling;
2960 prev = dmsg->prev_rule;
2962 KKASSERT(prev->cpuid == mycpuid);
2965 * Move to the position on the next CPU
2966 * before the msg is forwarded.
2968 dmsg->prev_rule = prev->sibling;
2972 * flush pointers outside the loop, then delete all matching
2973 * rules. 'prev' remains the same throughout the cycle.
2975 ipfw_flush_rule_ptrs(ctx);
2976 while (rule && rule->rulenum == dmsg->rulenum)
2977 rule = ipfw_delete_rule(ctx, prev, rule);
2979 ifnet_forwardmsg(&nmsg->nm_lmsg, mycpuid + 1);
2983 ipfw_alt_delete_rule(uint16_t rulenum)
2985 struct ip_fw *prev, *rule, *f;
2986 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2987 struct netmsg_del dmsg;
2988 struct netmsg *nmsg;
2992 * Locate first rule to delete
2994 for (prev = NULL, rule = ctx->ipfw_layer3_chain;
2995 rule && rule->rulenum < rulenum;
2996 prev = rule, rule = rule->next)
2998 if (rule->rulenum != rulenum)
3002 * Check whether any rules with the given number will
3006 for (f = rule; f && f->rulenum == rulenum; f = f->next) {
3007 if (f->rule_flags & IPFW_RULE_F_STATE) {
3015 * Clear the STATE flag, so no more states will be
3016 * created based the rules numbered 'rulenum'.
3018 bzero(&dmsg, sizeof(dmsg));
3020 netmsg_init(nmsg, &curthread->td_msgport, 0,
3021 ipfw_disable_rule_state_dispatch);
3022 dmsg.start_rule = rule;
3023 dmsg.rulenum = rulenum;
3025 ifnet_domsg(&nmsg->nm_lmsg, 0);
3026 KKASSERT(dmsg.start_rule == NULL);
3029 * Nuke all related states
3031 lockmgr(&dyn_lock, LK_EXCLUSIVE);
3032 for (f = rule; f && f->rulenum == rulenum; f = f->next) {
3034 * Can't check IPFW_RULE_F_STATE here,
3035 * since it has been cleared previously.
3036 * Check 'stub' instead.
3038 if (f->stub != NULL) {
3040 remove_dyn_rule_locked(f, NULL);
3043 lockmgr(&dyn_lock, LK_RELEASE);
3047 * Get rid of the rule duplications on all CPUs
3049 bzero(&dmsg, sizeof(dmsg));
3051 netmsg_init(nmsg, &curthread->td_msgport, 0,
3052 ipfw_alt_delete_rule_dispatch);
3053 dmsg.prev_rule = prev;
3054 dmsg.start_rule = rule;
3055 dmsg.rulenum = rulenum;
3057 ifnet_domsg(&nmsg->nm_lmsg, 0);
3058 KKASSERT(dmsg.prev_rule == NULL && dmsg.start_rule == NULL);
3063 ipfw_alt_delete_ruleset_dispatch(struct netmsg *nmsg)
3065 struct netmsg_del *dmsg = (struct netmsg_del *)nmsg;
3066 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3067 struct ip_fw *prev, *rule;
3072 ipfw_flush_rule_ptrs(ctx);
3075 rule = ctx->ipfw_layer3_chain;
3076 while (rule != NULL) {
3077 if (rule->set == dmsg->from_set) {
3078 rule = ipfw_delete_rule(ctx, prev, rule);
3087 KASSERT(del, ("no match set?!\n"));
3089 ifnet_forwardmsg(&nmsg->nm_lmsg, mycpuid + 1);
3093 ipfw_disable_ruleset_state_dispatch(struct netmsg *nmsg)
3095 struct netmsg_del *dmsg = (struct netmsg_del *)nmsg;
3096 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3104 for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next) {
3105 if (rule->set == dmsg->from_set) {
3109 rule->rule_flags &= ~IPFW_RULE_F_STATE;
3112 KASSERT(cleared, ("no match set?!\n"));
3114 ifnet_forwardmsg(&nmsg->nm_lmsg, mycpuid + 1);
3118 ipfw_alt_delete_ruleset(uint8_t set)
3120 struct netmsg_del dmsg;
3121 struct netmsg *nmsg;
3124 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3127 * Check whether the 'set' exists. If it exists,
3128 * then check whether any rules within the set will
3129 * try to create states.
3133 for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next) {
3134 if (rule->set == set) {
3136 if (rule->rule_flags & IPFW_RULE_F_STATE) {
3143 return 0; /* XXX EINVAL? */
3147 * Clear the STATE flag, so no more states will be
3148 * created based the rules in this set.
3150 bzero(&dmsg, sizeof(dmsg));
3152 netmsg_init(nmsg, &curthread->td_msgport, 0,
3153 ipfw_disable_ruleset_state_dispatch);
3154 dmsg.from_set = set;
3156 ifnet_domsg(&nmsg->nm_lmsg, 0);
3159 * Nuke all related states
3161 lockmgr(&dyn_lock, LK_EXCLUSIVE);
3162 for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next) {
3163 if (rule->set != set)
3167 * Can't check IPFW_RULE_F_STATE here,
3168 * since it has been cleared previously.
3169 * Check 'stub' instead.
3171 if (rule->stub != NULL) {
3173 remove_dyn_rule_locked(rule, NULL);
3176 lockmgr(&dyn_lock, LK_RELEASE);
3182 bzero(&dmsg, sizeof(dmsg));
3184 netmsg_init(nmsg, &curthread->td_msgport, 0,
3185 ipfw_alt_delete_ruleset_dispatch);
3186 dmsg.from_set = set;
3188 ifnet_domsg(&nmsg->nm_lmsg, 0);
3193 ipfw_alt_move_rule_dispatch(struct netmsg *nmsg)
3195 struct netmsg_del *dmsg = (struct netmsg_del *)nmsg;
3198 rule = dmsg->start_rule;
3199 KKASSERT(rule->cpuid == mycpuid);
3202 * Move to the position on the next CPU
3203 * before the msg is forwarded.
3205 dmsg->start_rule = rule->sibling;
3207 while (rule && rule->rulenum <= dmsg->rulenum) {
3208 if (rule->rulenum == dmsg->rulenum)
3209 rule->set = dmsg->to_set;
3212 ifnet_forwardmsg(&nmsg->nm_lmsg, mycpuid + 1);
3216 ipfw_alt_move_rule(uint16_t rulenum, uint8_t set)
3218 struct netmsg_del dmsg;
3219 struct netmsg *nmsg;
3221 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3224 * Locate first rule to move
3226 for (rule = ctx->ipfw_layer3_chain; rule && rule->rulenum <= rulenum;
3227 rule = rule->next) {
3228 if (rule->rulenum == rulenum && rule->set != set)
3231 if (rule == NULL || rule->rulenum > rulenum)
3232 return 0; /* XXX error? */
3234 bzero(&dmsg, sizeof(dmsg));
3236 netmsg_init(nmsg, &curthread->td_msgport, 0,
3237 ipfw_alt_move_rule_dispatch);
3238 dmsg.start_rule = rule;
3239 dmsg.rulenum = rulenum;
3242 ifnet_domsg(&nmsg->nm_lmsg, 0);
3243 KKASSERT(dmsg.start_rule == NULL);
3248 ipfw_alt_move_ruleset_dispatch(struct netmsg *nmsg)
3250 struct netmsg_del *dmsg = (struct netmsg_del *)nmsg;
3251 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3254 for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next) {
3255 if (rule->set == dmsg->from_set)
3256 rule->set = dmsg->to_set;
3258 ifnet_forwardmsg(&nmsg->nm_lmsg, mycpuid + 1);
3262 ipfw_alt_move_ruleset(uint8_t from_set, uint8_t to_set)
3264 struct netmsg_del dmsg;
3265 struct netmsg *nmsg;
3267 bzero(&dmsg, sizeof(dmsg));
3269 netmsg_init(nmsg, &curthread->td_msgport, 0,
3270 ipfw_alt_move_ruleset_dispatch);
3271 dmsg.from_set = from_set;
3272 dmsg.to_set = to_set;
3274 ifnet_domsg(&nmsg->nm_lmsg, 0);
3279 ipfw_alt_swap_ruleset_dispatch(struct netmsg *nmsg)
3281 struct netmsg_del *dmsg = (struct netmsg_del *)nmsg;
3282 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3285 for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next) {
3286 if (rule->set == dmsg->from_set)
3287 rule->set = dmsg->to_set;
3288 else if (rule->set == dmsg->to_set)
3289 rule->set = dmsg->from_set;
3291 ifnet_forwardmsg(&nmsg->nm_lmsg, mycpuid + 1);
3295 ipfw_alt_swap_ruleset(uint8_t set1, uint8_t set2)
3297 struct netmsg_del dmsg;
3298 struct netmsg *nmsg;
3300 bzero(&dmsg, sizeof(dmsg));
3302 netmsg_init(nmsg, &curthread->td_msgport, 0,
3303 ipfw_alt_swap_ruleset_dispatch);
3304 dmsg.from_set = set1;
3307 ifnet_domsg(&nmsg->nm_lmsg, 0);
3312 * Remove all rules with given number, and also do set manipulation.
3314 * The argument is an uint32_t. The low 16 bit are the rule or set number,
3315 * the next 8 bits are the new set, the top 8 bits are the command:
3317 * 0 delete rules with given number
3318 * 1 delete rules with given set number
3319 * 2 move rules with given number to new set
3320 * 3 move rules with given set number to new set
3321 * 4 swap sets with given numbers
3324 ipfw_ctl_alter(uint32_t arg)
3327 uint8_t cmd, new_set;
3330 rulenum = arg & 0xffff;
3331 cmd = (arg >> 24) & 0xff;
3332 new_set = (arg >> 16) & 0xff;
3336 if (new_set >= IPFW_DEFAULT_SET)
3338 if (cmd == 0 || cmd == 2) {
3339 if (rulenum == IPFW_DEFAULT_RULE)
3342 if (rulenum >= IPFW_DEFAULT_SET)
3347 case 0: /* delete rules with given number */
3348 error = ipfw_alt_delete_rule(rulenum);
3351 case 1: /* delete all rules with given set number */
3352 error = ipfw_alt_delete_ruleset(rulenum);
3355 case 2: /* move rules with given number to new set */
3356 error = ipfw_alt_move_rule(rulenum, new_set);
3359 case 3: /* move rules with given set number to new set */
3360 error = ipfw_alt_move_ruleset(rulenum, new_set);
3363 case 4: /* swap two sets */
3364 error = ipfw_alt_swap_ruleset(rulenum, new_set);
3371 * Clear counters for a specific rule.
3374 clear_counters(struct ip_fw *rule, int log_only)
3376 ipfw_insn_log *l = (ipfw_insn_log *)ACTION_PTR(rule);
3378 if (log_only == 0) {
3379 rule->bcnt = rule->pcnt = 0;
3380 rule->timestamp = 0;
3382 if (l->o.opcode == O_LOG)
3383 l->log_left = l->max_log;
3387 ipfw_zero_entry_dispatch(struct netmsg *nmsg)
3389 struct netmsg_zent *zmsg = (struct netmsg_zent *)nmsg;
3390 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3393 if (zmsg->rulenum == 0) {
3394 KKASSERT(zmsg->start_rule == NULL);
3396 ctx->ipfw_norule_counter = 0;
3397 for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next)
3398 clear_counters(rule, zmsg->log_only);
3400 struct ip_fw *start = zmsg->start_rule;
3402 KKASSERT(start->cpuid == mycpuid);
3403 KKASSERT(start->rulenum == zmsg->rulenum);
3406 * We can have multiple rules with the same number, so we
3407 * need to clear them all.
3409 for (rule = start; rule && rule->rulenum == zmsg->rulenum;
3411 clear_counters(rule, zmsg->log_only);
3414 * Move to the position on the next CPU
3415 * before the msg is forwarded.
3417 zmsg->start_rule = start->sibling;
3419 ifnet_forwardmsg(&nmsg->nm_lmsg, mycpuid + 1);
3423 * Reset some or all counters on firewall rules.
3424 * @arg frwl is null to clear all entries, or contains a specific
3426 * @arg log_only is 1 if we only want to reset logs, zero otherwise.
3429 ipfw_ctl_zero_entry(int rulenum, int log_only)
3431 struct netmsg_zent zmsg;
3432 struct netmsg *nmsg;
3434 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3436 bzero(&zmsg, sizeof(zmsg));
3438 netmsg_init(nmsg, &curthread->td_msgport, 0, ipfw_zero_entry_dispatch);
3439 zmsg.log_only = log_only;
3442 msg = log_only ? "ipfw: All logging counts reset.\n"
3443 : "ipfw: Accounting cleared.\n";
3448 * Locate the first rule with 'rulenum'
3450 for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next) {
3451 if (rule->rulenum == rulenum)
3454 if (rule == NULL) /* we did not find any matching rules */
3456 zmsg.start_rule = rule;
3457 zmsg.rulenum = rulenum;
3459 msg = log_only ? "ipfw: Entry %d logging count reset.\n"
3460 : "ipfw: Entry %d cleared.\n";
3462 ifnet_domsg(&nmsg->nm_lmsg, 0);
3463 KKASSERT(zmsg.start_rule == NULL);
3466 log(LOG_SECURITY | LOG_NOTICE, msg, rulenum);
3471 * Check validity of the structure before insert.
3472 * Fortunately rules are simple, so this mostly need to check rule sizes.
3475 ipfw_check_ioc_rule(struct ipfw_ioc_rule *rule, int size, uint32_t *rule_flags)
3478 int have_action = 0;
3483 /* Check for valid size */
3484 if (size < sizeof(*rule)) {
3485 kprintf("ipfw: rule too short\n");
3488 l = IOC_RULESIZE(rule);
3490 kprintf("ipfw: size mismatch (have %d want %d)\n", size, l);
3494 /* Check rule number */
3495 if (rule->rulenum == IPFW_DEFAULT_RULE) {
3496 kprintf("ipfw: invalid rule number\n");
3501 * Now go for the individual checks. Very simple ones, basically only
3502 * instruction sizes.
3504 for (l = rule->cmd_len, cmd = rule->cmd; l > 0;
3505 l -= cmdlen, cmd += cmdlen) {
3506 cmdlen = F_LEN(cmd);
3508 kprintf("ipfw: opcode %d size truncated\n",
3513 DPRINTF("ipfw: opcode %d\n", cmd->opcode);
3515 if (cmd->opcode == O_KEEP_STATE || cmd->opcode == O_LIMIT) {
3516 /* This rule will create states */
3517 *rule_flags |= IPFW_RULE_F_STATE;
3520 switch (cmd->opcode) {
3534 case O_IPPRECEDENCE:
3541 if (cmdlen != F_INSN_SIZE(ipfw_insn))
3553 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32))
3558 if (cmdlen != F_INSN_SIZE(ipfw_insn_limit))
3563 if (cmdlen != F_INSN_SIZE(ipfw_insn_log))
3566 ((ipfw_insn_log *)cmd)->log_left =
3567 ((ipfw_insn_log *)cmd)->max_log;
3573 if (cmdlen != F_INSN_SIZE(ipfw_insn_ip))
3575 if (((ipfw_insn_ip *)cmd)->mask.s_addr == 0) {
3576 kprintf("ipfw: opcode %d, useless rule\n",
3584 if (cmd->arg1 == 0 || cmd->arg1 > 256) {
3585 kprintf("ipfw: invalid set size %d\n",
3589 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
3595 if (cmdlen != F_INSN_SIZE(ipfw_insn_mac))
3601 case O_IP_DSTPORT: /* XXX artificial limit, 30 port pairs */
3602 if (cmdlen < 2 || cmdlen > 31)
3609 if (cmdlen != F_INSN_SIZE(ipfw_insn_if))
3615 if (cmdlen != F_INSN_SIZE(ipfw_insn_pipe))
3620 if (cmdlen != F_INSN_SIZE(ipfw_insn_sa)) {
3625 fwd_addr = ((ipfw_insn_sa *)cmd)->
3627 if (IN_MULTICAST(ntohl(fwd_addr))) {
3628 kprintf("ipfw: try forwarding to "
3629 "multicast address\n");
3635 case O_FORWARD_MAC: /* XXX not implemented yet */
3644 if (cmdlen != F_INSN_SIZE(ipfw_insn))
3648 kprintf("ipfw: opcode %d, multiple actions"
3655 kprintf("ipfw: opcode %d, action must be"
3662 kprintf("ipfw: opcode %d, unknown opcode\n",
3667 if (have_action == 0) {
3668 kprintf("ipfw: missing action\n");
3674 kprintf("ipfw: opcode %d size %d wrong\n",
3675 cmd->opcode, cmdlen);
3680 ipfw_ctl_add_rule(struct sockopt *sopt)
3682 struct ipfw_ioc_rule *ioc_rule;
3684 uint32_t rule_flags;
3687 size = sopt->sopt_valsize;
3688 if (size > (sizeof(uint32_t) * IPFW_RULE_SIZE_MAX) ||
3689 size < sizeof(*ioc_rule)) {
3692 if (size != (sizeof(uint32_t) * IPFW_RULE_SIZE_MAX)) {
3693 sopt->sopt_val = krealloc(sopt->sopt_val, sizeof(uint32_t) *
3694 IPFW_RULE_SIZE_MAX, M_TEMP, M_WAITOK);
3696 ioc_rule = sopt->sopt_val;
3698 error = ipfw_check_ioc_rule(ioc_rule, size, &rule_flags);
3702 ipfw_add_rule(ioc_rule, rule_flags);
3704 if (sopt->sopt_dir == SOPT_GET)
3705 sopt->sopt_valsize = IOC_RULESIZE(ioc_rule);
3710 ipfw_copy_rule(const struct ip_fw *rule, struct ipfw_ioc_rule *ioc_rule)
3712 const struct ip_fw *sibling;
3717 KKASSERT(rule->cpuid == 0);
3719 ioc_rule->act_ofs = rule->act_ofs;
3720 ioc_rule->cmd_len = rule->cmd_len;
3721 ioc_rule->rulenum = rule->rulenum;
3722 ioc_rule->set = rule->set;
3723 ioc_rule->usr_flags = rule->usr_flags;
3725 ioc_rule->set_disable = ipfw_ctx[mycpuid]->ipfw_set_disable;
3726 ioc_rule->static_count = static_count;
3727 ioc_rule->static_len = static_ioc_len;
3730 * Visit (read-only) all of the rule's duplications to get
3731 * the necessary statistics
3738 ioc_rule->timestamp = 0;
3739 for (sibling = rule; sibling != NULL; sibling = sibling->sibling) {
3740 ioc_rule->pcnt += sibling->pcnt;
3741 ioc_rule->bcnt += sibling->bcnt;
3742 if (sibling->timestamp > ioc_rule->timestamp)
3743 ioc_rule->timestamp = sibling->timestamp;
3748 KASSERT(i == ncpus, ("static rule is not duplicated on every cpu\n"));
3750 bcopy(rule->cmd, ioc_rule->cmd, ioc_rule->cmd_len * 4 /* XXX */);
3752 return ((uint8_t *)ioc_rule + IOC_RULESIZE(ioc_rule));
3756 ipfw_copy_state(const ipfw_dyn_rule *dyn_rule,
3757 struct ipfw_ioc_state *ioc_state)
3759 const struct ipfw_flow_id *id;
3760 struct ipfw_ioc_flowid *ioc_id;
3762 ioc_state->expire = TIME_LEQ(dyn_rule->expire, time_second) ?
3763 0 : dyn_rule->expire - time_second;
3764 ioc_state->pcnt = dyn_rule->pcnt;
3765 ioc_state->bcnt = dyn_rule->bcnt;
3767 ioc_state->dyn_type = dyn_rule->dyn_type;
3768 ioc_state->count = dyn_rule->count;
3770 ioc_state->rulenum = dyn_rule->stub->rule[mycpuid]->rulenum;
3773 ioc_id = &ioc_state->id;
3775 ioc_id->type = ETHERTYPE_IP;
3776 ioc_id->u.ip.dst_ip = id->dst_ip;
3777 ioc_id->u.ip.src_ip = id->src_ip;
3778 ioc_id->u.ip.dst_port = id->dst_port;
3779 ioc_id->u.ip.src_port = id->src_port;
3780 ioc_id->u.ip.proto = id->proto;
3784 ipfw_ctl_get_rules(struct sockopt *sopt)
3786 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3790 uint32_t dcount = 0;
3793 * pass up a copy of the current rules. Static rules
3794 * come first (the last of which has number IPFW_DEFAULT_RULE),
3795 * followed by a possibly empty list of dynamic rule.
3798 size = static_ioc_len; /* size of static rules */
3799 if (ipfw_dyn_v) { /* add size of dyn.rules */
3801 size += dcount * sizeof(struct ipfw_ioc_state);
3804 if (sopt->sopt_valsize < size) {
3805 /* short length, no need to return incomplete rules */
3806 /* XXX: if superuser, no need to zero buffer */
3807 bzero(sopt->sopt_val, sopt->sopt_valsize);
3810 bp = sopt->sopt_val;
3812 for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next)
3813 bp = ipfw_copy_rule(rule, bp);
3815 if (ipfw_dyn_v && dcount != 0) {
3816 struct ipfw_ioc_state *ioc_state = bp;
3817 uint32_t dcount2 = 0;
3819 size_t old_size = size;
3823 lockmgr(&dyn_lock, LK_SHARED);
3825 /* Check 'ipfw_dyn_v' again with lock held */
3826 if (ipfw_dyn_v == NULL)
3829 for (i = 0; i < curr_dyn_buckets; i++) {
3833 * The # of dynamic rules may have grown after the
3834 * snapshot of 'dyn_count' was taken, so we will have
3835 * to check 'dcount' (snapshot of dyn_count) here to
3836 * make sure that we don't overflow the pre-allocated
3839 for (p = ipfw_dyn_v[i]; p != NULL && dcount != 0;
3840 p = p->next, ioc_state++, dcount--, dcount2++)
3841 ipfw_copy_state(p, ioc_state);
3844 lockmgr(&dyn_lock, LK_RELEASE);
3847 * The # of dynamic rules may be shrinked after the
3848 * snapshot of 'dyn_count' was taken. To give user a
3849 * correct dynamic rule count, we use the 'dcount2'
3850 * calculated above (with shared lockmgr lock held).
3852 size = static_ioc_len +
3853 (dcount2 * sizeof(struct ipfw_ioc_state));
3854 KKASSERT(size <= old_size);
3857 sopt->sopt_valsize = size;
3862 ipfw_set_disable_dispatch(struct netmsg *nmsg)
3864 struct lwkt_msg *lmsg = &nmsg->nm_lmsg;
3865 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3868 ctx->ipfw_set_disable = lmsg->u.ms_result32;
3870 ifnet_forwardmsg(lmsg, mycpuid + 1);
3874 ipfw_ctl_set_disable(uint32_t disable, uint32_t enable)
3877 struct lwkt_msg *lmsg;
3878 uint32_t set_disable;
3880 /* IPFW_DEFAULT_SET is always enabled */
3881 enable |= (1 << IPFW_DEFAULT_SET);
3882 set_disable = (ipfw_ctx[mycpuid]->ipfw_set_disable | disable) & ~enable;
3884 bzero(&nmsg, sizeof(nmsg));
3885 netmsg_init(&nmsg, &curthread->td_msgport, 0, ipfw_set_disable_dispatch);
3886 lmsg = &nmsg.nm_lmsg;
3887 lmsg->u.ms_result32 = set_disable;
3889 ifnet_domsg(lmsg, 0);
3893 * {set|get}sockopt parser.
3896 ipfw_ctl(struct sockopt *sopt)
3904 switch (sopt->sopt_name) {
3906 error = ipfw_ctl_get_rules(sopt);
3910 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_check_in(void *arg, struct mbuf **m0, struct ifnet *ifp, int dir)
4062 struct ip_fw_args args;
4063 struct mbuf *m = *m0;
4065 int tee = 0, error = 0, ret;
4067 if (m->m_pkthdr.fw_flags & DUMMYNET_MBUF_TAGGED) {
4068 /* Extract info from dummynet tag */
4069 mtag = m_tag_find(m, PACKET_TAG_DUMMYNET, NULL);
4070 KKASSERT(mtag != NULL);
4071 args.rule = ((struct dn_pkt *)m_tag_data(mtag))->dn_priv;
4072 KKASSERT(args.rule != NULL);
4074 m_tag_delete(m, mtag);
4075 m->m_pkthdr.fw_flags &= ~DUMMYNET_MBUF_TAGGED;
4083 ret = ipfw_chk(&args);
4101 case IP_FW_DUMMYNET:
4102 /* Send packet to the appropriate pipe */
4103 ipfw_dummynet_io(m, args.cookie, DN_TO_IP_IN, &args);
4111 if (ip_divert_p != NULL) {
4112 m = ip_divert_p(m, tee, 1);
4116 /* not sure this is the right error msg */
4122 panic("unknown ipfw return value: %d\n", ret);
4130 ipfw_check_out(void *arg, struct mbuf **m0, struct ifnet *ifp, int dir)
4132 struct ip_fw_args args;
4133 struct mbuf *m = *m0;
4135 int tee = 0, error = 0, ret;
4137 if (m->m_pkthdr.fw_flags & DUMMYNET_MBUF_TAGGED) {
4138 /* Extract info from dummynet tag */
4139 mtag = m_tag_find(m, PACKET_TAG_DUMMYNET, NULL);
4140 KKASSERT(mtag != NULL);
4141 args.rule = ((struct dn_pkt *)m_tag_data(mtag))->dn_priv;
4142 KKASSERT(args.rule != NULL);
4144 m_tag_delete(m, mtag);
4145 m->m_pkthdr.fw_flags &= ~DUMMYNET_MBUF_TAGGED;
4153 ret = ipfw_chk(&args);
4171 case IP_FW_DUMMYNET:
4172 ipfw_dummynet_io(m, args.cookie, DN_TO_IP_OUT, &args);
4180 if (ip_divert_p != NULL) {
4181 m = ip_divert_p(m, tee, 0);
4185 /* not sure this is the right error msg */
4191 panic("unknown ipfw return value: %d\n", ret);
4201 struct pfil_head *pfh;
4203 IPFW_ASSERT_CFGPORT(&curthread->td_msgport);
4205 pfh = pfil_head_get(PFIL_TYPE_AF, AF_INET);
4209 pfil_add_hook(ipfw_check_in, NULL, PFIL_IN, pfh);
4210 pfil_add_hook(ipfw_check_out, NULL, PFIL_OUT, pfh);
4216 struct pfil_head *pfh;
4218 IPFW_ASSERT_CFGPORT(&curthread->td_msgport);
4220 pfh = pfil_head_get(PFIL_TYPE_AF, AF_INET);
4224 pfil_remove_hook(ipfw_check_in, NULL, PFIL_IN, pfh);
4225 pfil_remove_hook(ipfw_check_out, NULL, PFIL_OUT, pfh);
4229 ipfw_sysctl_enable_dispatch(struct netmsg *nmsg)
4231 struct lwkt_msg *lmsg = &nmsg->nm_lmsg;
4232 int enable = lmsg->u.ms_result;
4234 if (fw_enable == enable)
4243 lwkt_replymsg(lmsg, 0);
4247 ipfw_sysctl_enable(SYSCTL_HANDLER_ARGS)
4250 struct lwkt_msg *lmsg;
4254 error = sysctl_handle_int(oidp, &enable, 0, req);
4255 if (error || req->newptr == NULL)
4258 netmsg_init(&nmsg, &curthread->td_msgport, 0,
4259 ipfw_sysctl_enable_dispatch);
4260 lmsg = &nmsg.nm_lmsg;
4261 lmsg->u.ms_result = enable;
4263 return lwkt_domsg(IPFW_CFGPORT, lmsg, 0);
4267 ipfw_sysctl_autoinc_step(SYSCTL_HANDLER_ARGS)
4269 return sysctl_int_range(oidp, arg1, arg2, req,
4270 IPFW_AUTOINC_STEP_MIN, IPFW_AUTOINC_STEP_MAX);
4274 ipfw_sysctl_dyn_buckets(SYSCTL_HANDLER_ARGS)
4278 lockmgr(&dyn_lock, LK_EXCLUSIVE);
4280 value = dyn_buckets;
4281 error = sysctl_handle_int(oidp, &value, 0, req);
4282 if (error || !req->newptr)
4286 * Make sure we have a power of 2 and
4287 * do not allow more than 64k entries.
4290 if (value <= 1 || value > 65536)
4292 if ((value & (value - 1)) != 0)
4296 dyn_buckets = value;
4298 lockmgr(&dyn_lock, LK_RELEASE);
4303 ipfw_sysctl_dyn_fin(SYSCTL_HANDLER_ARGS)
4305 return sysctl_int_range(oidp, arg1, arg2, req,
4306 1, dyn_keepalive_period - 1);
4310 ipfw_sysctl_dyn_rst(SYSCTL_HANDLER_ARGS)
4312 return sysctl_int_range(oidp, arg1, arg2, req,
4313 1, dyn_keepalive_period - 1);
4317 ipfw_ctx_init_dispatch(struct netmsg *nmsg)
4319 struct netmsg_ipfw *fwmsg = (struct netmsg_ipfw *)nmsg;
4320 struct ipfw_context *ctx;
4321 struct ip_fw *def_rule;
4323 ctx = kmalloc(sizeof(*ctx), M_IPFW, M_WAITOK | M_ZERO);
4324 ipfw_ctx[mycpuid] = ctx;
4326 def_rule = kmalloc(sizeof(*def_rule), M_IPFW, M_WAITOK | M_ZERO);
4328 def_rule->act_ofs = 0;
4329 def_rule->rulenum = IPFW_DEFAULT_RULE;
4330 def_rule->cmd_len = 1;
4331 def_rule->set = IPFW_DEFAULT_SET;
4333 def_rule->cmd[0].len = 1;
4334 #ifdef IPFIREWALL_DEFAULT_TO_ACCEPT
4335 def_rule->cmd[0].opcode = O_ACCEPT;
4337 def_rule->cmd[0].opcode = O_DENY;
4340 def_rule->refcnt = 1;
4341 def_rule->cpuid = mycpuid;
4343 /* Install the default rule */
4344 ctx->ipfw_default_rule = def_rule;
4345 ctx->ipfw_layer3_chain = def_rule;
4347 /* Link rule CPU sibling */
4348 ipfw_link_sibling(fwmsg, def_rule);
4350 /* Statistics only need to be updated once */
4352 ipfw_inc_static_count(def_rule);
4354 ifnet_forwardmsg(&nmsg->nm_lmsg, mycpuid + 1);
4358 ipfw_init_dispatch(struct netmsg *nmsg)
4360 struct netmsg_ipfw fwmsg;
4364 kprintf("IP firewall already loaded\n");
4369 bzero(&fwmsg, sizeof(fwmsg));
4370 netmsg_init(&fwmsg.nmsg, &curthread->td_msgport, 0,
4371 ipfw_ctx_init_dispatch);
4372 ifnet_domsg(&fwmsg.nmsg.nm_lmsg, 0);
4374 ip_fw_chk_ptr = ipfw_chk;
4375 ip_fw_ctl_ptr = ipfw_ctl;
4376 ip_fw_dn_io_ptr = ipfw_dummynet_io;
4378 kprintf("ipfw2 initialized, default to %s, logging ",
4379 ipfw_ctx[mycpuid]->ipfw_default_rule->cmd[0].opcode ==
4380 O_ACCEPT ? "accept" : "deny");
4382 #ifdef IPFIREWALL_VERBOSE
4385 #ifdef IPFIREWALL_VERBOSE_LIMIT
4386 verbose_limit = IPFIREWALL_VERBOSE_LIMIT;
4388 if (fw_verbose == 0) {
4389 kprintf("disabled\n");
4390 } else if (verbose_limit == 0) {
4391 kprintf("unlimited\n");
4393 kprintf("limited to %d packets/entry by default\n",
4397 callout_init(&ipfw_timeout_h);
4398 lockinit(&dyn_lock, "ipfw_dyn", 0, 0);
4401 callout_reset(&ipfw_timeout_h, hz, ipfw_tick, NULL);
4406 lwkt_replymsg(&nmsg->nm_lmsg, error);
4414 netmsg_init(&smsg, &curthread->td_msgport, 0, ipfw_init_dispatch);
4415 return lwkt_domsg(IPFW_CFGPORT, &smsg.nm_lmsg, 0);
4421 ipfw_fini_dispatch(struct netmsg *nmsg)
4425 if (ipfw_refcnt != 0) {
4432 callout_stop(&ipfw_timeout_h);
4435 netmsg_service_sync();
4437 ip_fw_chk_ptr = NULL;
4438 ip_fw_ctl_ptr = NULL;
4439 ip_fw_dn_io_ptr = NULL;
4440 ipfw_flush(1 /* kill default rule */);
4442 /* Free pre-cpu context */
4443 for (cpu = 0; cpu < ncpus; ++cpu)
4444 kfree(ipfw_ctx[cpu], M_IPFW);
4446 kprintf("IP firewall unloaded\n");
4448 lwkt_replymsg(&nmsg->nm_lmsg, error);
4456 netmsg_init(&smsg, &curthread->td_msgport, 0, ipfw_fini_dispatch);
4457 return lwkt_domsg(IPFW_CFGPORT, &smsg.nm_lmsg, 0);
4460 #endif /* KLD_MODULE */
4463 ipfw_modevent(module_t mod, int type, void *unused)
4474 kprintf("ipfw statically compiled, cannot unload\n");
4486 static moduledata_t ipfwmod = {
4491 DECLARE_MODULE(ipfw, ipfwmod, SI_SUB_PROTO_END, SI_ORDER_ANY);
4492 MODULE_VERSION(ipfw, 1);