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 $
29 * Implement IP packet firewall (new version)
35 #error IPFIREWALL requires INET.
38 #include <sys/param.h>
39 #include <sys/systm.h>
40 #include <sys/malloc.h>
42 #include <sys/kernel.h>
44 #include <sys/socket.h>
45 #include <sys/socketvar.h>
46 #include <sys/sysctl.h>
47 #include <sys/syslog.h>
48 #include <sys/ucred.h>
49 #include <sys/in_cksum.h>
53 #include <net/route.h>
55 #include <net/dummynet/ip_dummynet.h>
57 #include <sys/thread2.h>
58 #include <sys/mplock2.h>
59 #include <net/netmsg2.h>
61 #include <netinet/in.h>
62 #include <netinet/in_systm.h>
63 #include <netinet/in_var.h>
64 #include <netinet/in_pcb.h>
65 #include <netinet/ip.h>
66 #include <netinet/ip_var.h>
67 #include <netinet/ip_icmp.h>
68 #include <netinet/tcp.h>
69 #include <netinet/tcp_timer.h>
70 #include <netinet/tcp_var.h>
71 #include <netinet/tcpip.h>
72 #include <netinet/udp.h>
73 #include <netinet/udp_var.h>
74 #include <netinet/ip_divert.h>
75 #include <netinet/if_ether.h> /* XXX for ETHERTYPE_IP */
77 #include <net/ipfw/ip_fw2.h>
79 #ifdef IPFIREWALL_DEBUG
80 #define DPRINTF(fmt, ...) \
83 kprintf(fmt, __VA_ARGS__); \
86 #define DPRINTF(fmt, ...) ((void)0)
90 * Description about per-CPU rule duplication:
92 * Module loading/unloading and all ioctl operations are serialized
93 * by netisr0, so we don't have any ordering or locking problems.
95 * Following graph shows how operation on per-CPU rule list is
96 * performed [2 CPU case]:
100 * netisr0 <------------------------------------+
111 * forwardmsg---------->ifnet1 |
116 * replymsg--------------+
121 * Rules which will not create states (dyn rules) [2 CPU case]
124 * layer3_chain layer3_chain
127 * +-------+ sibling +-------+ sibling
128 * | rule1 |--------->| rule1 |--------->NULL
129 * +-------+ +-------+
133 * +-------+ sibling +-------+ sibling
134 * | rule2 |--------->| rule2 |--------->NULL
135 * +-------+ +-------+
138 * 1) Ease statistics calculation during IP_FW_GET. We only need to
139 * iterate layer3_chain on CPU0; the current rule's duplication on
140 * the other CPUs could safely be read-only accessed by using
142 * 2) Accelerate rule insertion and deletion, e.g. rule insertion:
143 * a) In netisr0 (on CPU0) rule3 is determined to be inserted between
144 * rule1 and rule2. To make this decision we need to iterate the
145 * layer3_chain on CPU0. The netmsg, which is used to insert the
146 * rule, will contain rule1 on CPU0 as prev_rule and rule2 on CPU0
148 * b) After the insertion on CPU0 is done, we will move on to CPU1.
149 * But instead of relocating the rule3's position on CPU1 by
150 * iterating the layer3_chain on CPU1, we set the netmsg's prev_rule
151 * to rule1->sibling and next_rule to rule2->sibling before the
152 * netmsg is forwarded to CPU1 from CPU0
156 * Rules which will create states (dyn rules) [2 CPU case]
157 * (unnecessary parts are omitted; they are same as in the previous figure)
161 * +-------+ +-------+
162 * | rule1 | | rule1 |
163 * +-------+ +-------+
170 * | +--------------------+ |
172 * | | (read-only shared) | |
174 * | | back pointer array | |
175 * | | (indexed by cpuid) | |
177 * +----|---------[0] | |
178 * | [1]--------|----+
180 * +--------------------+
183 * ........|............|............
187 * : +---------+ +---------+ :
188 * : | state1a | | state1b | .... :
189 * : +---------+ +---------+ :
193 * : (protected by dyn_lock) :
194 * ..................................
196 * [state1a and state1b are states created by rule1]
199 * This structure is introduced so that shared (locked) state table could
200 * work with per-CPU (duplicated) static rules. It mainly bridges states
201 * and static rules and serves as static rule's place holder (a read-only
202 * shared part of duplicated rules) from states point of view.
204 * IPFW_RULE_F_STATE (only for rules which create states):
205 * o During rule installation, this flag is turned on after rule's
206 * duplications reach all CPUs, to avoid at least following race:
207 * 1) rule1 is duplicated on CPU0 and is not duplicated on CPU1 yet
208 * 2) rule1 creates state1
209 * 3) state1 is located on CPU1 by check-state
210 * But rule1 is not duplicated on CPU1 yet
211 * o During rule deletion, this flag is turned off before deleting states
212 * created by the rule and before deleting the rule itself, so no
213 * more states will be created by the to-be-deleted rule even when its
214 * duplication on certain CPUs are not eliminated yet.
217 #define IPFW_AUTOINC_STEP_MIN 1
218 #define IPFW_AUTOINC_STEP_MAX 1000
219 #define IPFW_AUTOINC_STEP_DEF 100
221 #define IPFW_DEFAULT_RULE 65535 /* rulenum for the default rule */
222 #define IPFW_DEFAULT_SET 31 /* set number for the default rule */
225 struct netmsg_base base;
226 const struct ipfw_ioc_rule *ioc_rule;
227 struct ip_fw *next_rule;
228 struct ip_fw *prev_rule;
229 struct ip_fw *sibling;
230 struct ip_fw_stub *stub;
234 struct netmsg_base base;
235 struct ip_fw *start_rule;
236 struct ip_fw *prev_rule;
243 struct netmsg_base base;
244 struct ip_fw *start_rule;
249 struct ipfw_context {
250 struct ip_fw *ipfw_layer3_chain; /* list of rules for layer3 */
251 struct ip_fw *ipfw_default_rule; /* default rule */
252 uint64_t ipfw_norule_counter; /* counter for ipfw_log(NULL) */
255 * ipfw_set_disable contains one bit per set value (0..31).
256 * If the bit is set, all rules with the corresponding set
257 * are disabled. Set IPDW_DEFAULT_SET is reserved for the
258 * default rule and CANNOT be disabled.
260 uint32_t ipfw_set_disable;
261 uint32_t ipfw_gen; /* generation of rule list */
264 static struct ipfw_context *ipfw_ctx[MAXCPU];
268 * Module can not be unloaded, if there are references to
269 * certains rules of ipfw(4), e.g. dummynet(4)
271 static int ipfw_refcnt;
274 MALLOC_DEFINE(M_IPFW, "IpFw/IpAcct", "IpFw/IpAcct chain's");
277 * Following two global variables are accessed and
278 * updated only on CPU0
280 static uint32_t static_count; /* # of static rules */
281 static uint32_t static_ioc_len; /* bytes of static rules */
284 * If 1, then ipfw static rules are being flushed,
285 * ipfw_chk() will skip to the default rule.
287 static int ipfw_flushing;
289 static int fw_verbose;
290 static int verbose_limit;
293 static int autoinc_step = IPFW_AUTOINC_STEP_DEF;
295 static int ipfw_sysctl_enable(SYSCTL_HANDLER_ARGS);
296 static int ipfw_sysctl_autoinc_step(SYSCTL_HANDLER_ARGS);
297 static int ipfw_sysctl_dyn_buckets(SYSCTL_HANDLER_ARGS);
298 static int ipfw_sysctl_dyn_fin(SYSCTL_HANDLER_ARGS);
299 static int ipfw_sysctl_dyn_rst(SYSCTL_HANDLER_ARGS);
301 SYSCTL_NODE(_net_inet_ip, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall");
302 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, enable, CTLTYPE_INT | CTLFLAG_RW,
303 &fw_enable, 0, ipfw_sysctl_enable, "I", "Enable ipfw");
304 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, autoinc_step, CTLTYPE_INT | CTLFLAG_RW,
305 &autoinc_step, 0, ipfw_sysctl_autoinc_step, "I",
306 "Rule number autincrement step");
307 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO,one_pass,CTLFLAG_RW,
309 "Only do a single pass through ipfw when using dummynet(4)");
310 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, debug, CTLFLAG_RW,
311 &fw_debug, 0, "Enable printing of debug ip_fw statements");
312 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose, CTLFLAG_RW,
313 &fw_verbose, 0, "Log matches to ipfw rules");
314 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose_limit, CTLFLAG_RW,
315 &verbose_limit, 0, "Set upper limit of matches of ipfw rules logged");
318 * Description of dynamic rules.
320 * Dynamic rules are stored in lists accessed through a hash table
321 * (ipfw_dyn_v) whose size is curr_dyn_buckets. This value can
322 * be modified through the sysctl variable dyn_buckets which is
323 * updated when the table becomes empty.
325 * XXX currently there is only one list, ipfw_dyn.
327 * When a packet is received, its address fields are first masked
328 * with the mask defined for the rule, then hashed, then matched
329 * against the entries in the corresponding list.
330 * Dynamic rules can be used for different purposes:
332 * + enforcing limits on the number of sessions;
333 * + in-kernel NAT (not implemented yet)
335 * The lifetime of dynamic rules is regulated by dyn_*_lifetime,
336 * measured in seconds and depending on the flags.
338 * The total number of dynamic rules is stored in dyn_count.
339 * The max number of dynamic rules is dyn_max. When we reach
340 * the maximum number of rules we do not create anymore. This is
341 * done to avoid consuming too much memory, but also too much
342 * time when searching on each packet (ideally, we should try instead
343 * to put a limit on the length of the list on each bucket...).
345 * Each dynamic rule holds a pointer to the parent ipfw rule so
346 * we know what action to perform. Dynamic rules are removed when
347 * the parent rule is deleted. XXX we should make them survive.
349 * There are some limitations with dynamic rules -- we do not
350 * obey the 'randomized match', and we do not do multiple
351 * passes through the firewall. XXX check the latter!!!
353 * NOTE about the SHARED LOCKMGR LOCK during dynamic rule looking up:
354 * Only TCP state transition will change dynamic rule's state and ack
355 * sequences, while all packets of one TCP connection only goes through
356 * one TCP thread, so it is safe to use shared lockmgr lock during dynamic
357 * rule looking up. The keep alive callout uses exclusive lockmgr lock
358 * when it tries to find suitable dynamic rules to send keep alive, so
359 * it will not see half updated state and ack sequences. Though the expire
360 * field updating looks racy for other protocols, the resolution (second)
361 * of expire field makes this kind of race harmless.
362 * XXX statistics' updating is _not_ MPsafe!!!
363 * XXX once UDP output path is fixed, we could use lockless dynamic rule
366 static ipfw_dyn_rule **ipfw_dyn_v = NULL;
367 static uint32_t dyn_buckets = 256; /* must be power of 2 */
368 static uint32_t curr_dyn_buckets = 256; /* must be power of 2 */
369 static uint32_t dyn_buckets_gen; /* generation of dyn buckets array */
370 static struct lock dyn_lock; /* dynamic rules' hash table lock */
372 static struct netmsg_base ipfw_timeout_netmsg; /* schedule ipfw timeout */
373 static struct callout ipfw_timeout_h;
376 * Timeouts for various events in handing dynamic rules.
378 static uint32_t dyn_ack_lifetime = 300;
379 static uint32_t dyn_syn_lifetime = 20;
380 static uint32_t dyn_fin_lifetime = 1;
381 static uint32_t dyn_rst_lifetime = 1;
382 static uint32_t dyn_udp_lifetime = 10;
383 static uint32_t dyn_short_lifetime = 5;
386 * Keepalives are sent if dyn_keepalive is set. They are sent every
387 * dyn_keepalive_period seconds, in the last dyn_keepalive_interval
388 * seconds of lifetime of a rule.
389 * dyn_rst_lifetime and dyn_fin_lifetime should be strictly lower
390 * than dyn_keepalive_period.
393 static uint32_t dyn_keepalive_interval = 20;
394 static uint32_t dyn_keepalive_period = 5;
395 static uint32_t dyn_keepalive = 1; /* do send keepalives */
397 static uint32_t dyn_count; /* # of dynamic rules */
398 static uint32_t dyn_max = 4096; /* max # of dynamic rules */
400 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, dyn_buckets, CTLTYPE_INT | CTLFLAG_RW,
401 &dyn_buckets, 0, ipfw_sysctl_dyn_buckets, "I", "Number of dyn. buckets");
402 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, curr_dyn_buckets, CTLFLAG_RD,
403 &curr_dyn_buckets, 0, "Current Number of dyn. buckets");
404 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_count, CTLFLAG_RD,
405 &dyn_count, 0, "Number of dyn. rules");
406 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_max, CTLFLAG_RW,
407 &dyn_max, 0, "Max number of dyn. rules");
408 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, static_count, CTLFLAG_RD,
409 &static_count, 0, "Number of static rules");
410 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_ack_lifetime, CTLFLAG_RW,
411 &dyn_ack_lifetime, 0, "Lifetime of dyn. rules for acks");
412 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_syn_lifetime, CTLFLAG_RW,
413 &dyn_syn_lifetime, 0, "Lifetime of dyn. rules for syn");
414 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, dyn_fin_lifetime,
415 CTLTYPE_INT | CTLFLAG_RW, &dyn_fin_lifetime, 0, ipfw_sysctl_dyn_fin, "I",
416 "Lifetime of dyn. rules for fin");
417 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, dyn_rst_lifetime,
418 CTLTYPE_INT | CTLFLAG_RW, &dyn_rst_lifetime, 0, ipfw_sysctl_dyn_rst, "I",
419 "Lifetime of dyn. rules for rst");
420 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_udp_lifetime, CTLFLAG_RW,
421 &dyn_udp_lifetime, 0, "Lifetime of dyn. rules for UDP");
422 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_short_lifetime, CTLFLAG_RW,
423 &dyn_short_lifetime, 0, "Lifetime of dyn. rules for other situations");
424 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_keepalive, CTLFLAG_RW,
425 &dyn_keepalive, 0, "Enable keepalives for dyn. rules");
427 static ip_fw_chk_t ipfw_chk;
428 static void ipfw_tick(void *);
431 ipfw_free_rule(struct ip_fw *rule)
433 KASSERT(rule->cpuid == mycpuid, ("rule freed on cpu%d", mycpuid));
434 KASSERT(rule->refcnt > 0, ("invalid refcnt %u", rule->refcnt));
436 if (rule->refcnt == 0) {
444 ipfw_unref_rule(void *priv)
446 ipfw_free_rule(priv);
448 atomic_subtract_int(&ipfw_refcnt, 1);
453 ipfw_ref_rule(struct ip_fw *rule)
455 KASSERT(rule->cpuid == mycpuid, ("rule used on cpu%d", mycpuid));
457 atomic_add_int(&ipfw_refcnt, 1);
463 * This macro maps an ip pointer into a layer3 header pointer of type T
465 #define L3HDR(T, ip) ((T *)((uint32_t *)(ip) + (ip)->ip_hl))
468 icmptype_match(struct ip *ip, ipfw_insn_u32 *cmd)
470 int type = L3HDR(struct icmp,ip)->icmp_type;
472 return (type <= ICMP_MAXTYPE && (cmd->d[0] & (1 << type)));
475 #define TT ((1 << ICMP_ECHO) | \
476 (1 << ICMP_ROUTERSOLICIT) | \
477 (1 << ICMP_TSTAMP) | \
482 is_icmp_query(struct ip *ip)
484 int type = L3HDR(struct icmp, ip)->icmp_type;
486 return (type <= ICMP_MAXTYPE && (TT & (1 << type)));
492 * The following checks use two arrays of 8 or 16 bits to store the
493 * bits that we want set or clear, respectively. They are in the
494 * low and high half of cmd->arg1 or cmd->d[0].
496 * We scan options and store the bits we find set. We succeed if
498 * (want_set & ~bits) == 0 && (want_clear & ~bits) == want_clear
500 * The code is sometimes optimized not to store additional variables.
504 flags_match(ipfw_insn *cmd, uint8_t bits)
509 if (((cmd->arg1 & 0xff) & bits) != 0)
510 return 0; /* some bits we want set were clear */
512 want_clear = (cmd->arg1 >> 8) & 0xff;
513 if ((want_clear & bits) != want_clear)
514 return 0; /* some bits we want clear were set */
519 ipopts_match(struct ip *ip, ipfw_insn *cmd)
521 int optlen, bits = 0;
522 u_char *cp = (u_char *)(ip + 1);
523 int x = (ip->ip_hl << 2) - sizeof(struct ip);
525 for (; x > 0; x -= optlen, cp += optlen) {
526 int opt = cp[IPOPT_OPTVAL];
528 if (opt == IPOPT_EOL)
531 if (opt == IPOPT_NOP) {
534 optlen = cp[IPOPT_OLEN];
535 if (optlen <= 0 || optlen > x)
536 return 0; /* invalid or truncated */
541 bits |= IP_FW_IPOPT_LSRR;
545 bits |= IP_FW_IPOPT_SSRR;
549 bits |= IP_FW_IPOPT_RR;
553 bits |= IP_FW_IPOPT_TS;
560 return (flags_match(cmd, bits));
564 tcpopts_match(struct ip *ip, ipfw_insn *cmd)
566 int optlen, bits = 0;
567 struct tcphdr *tcp = L3HDR(struct tcphdr,ip);
568 u_char *cp = (u_char *)(tcp + 1);
569 int x = (tcp->th_off << 2) - sizeof(struct tcphdr);
571 for (; x > 0; x -= optlen, cp += optlen) {
574 if (opt == TCPOPT_EOL)
577 if (opt == TCPOPT_NOP) {
587 bits |= IP_FW_TCPOPT_MSS;
591 bits |= IP_FW_TCPOPT_WINDOW;
594 case TCPOPT_SACK_PERMITTED:
596 bits |= IP_FW_TCPOPT_SACK;
599 case TCPOPT_TIMESTAMP:
600 bits |= IP_FW_TCPOPT_TS;
606 bits |= IP_FW_TCPOPT_CC;
613 return (flags_match(cmd, bits));
617 iface_match(struct ifnet *ifp, ipfw_insn_if *cmd)
619 if (ifp == NULL) /* no iface with this packet, match fails */
622 /* Check by name or by IP address */
623 if (cmd->name[0] != '\0') { /* match by name */
626 if (kfnmatch(cmd->name, ifp->if_xname, 0) == 0)
629 if (strncmp(ifp->if_xname, cmd->name, IFNAMSIZ) == 0)
633 struct ifaddr_container *ifac;
635 TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
636 struct ifaddr *ia = ifac->ifa;
638 if (ia->ifa_addr == NULL)
640 if (ia->ifa_addr->sa_family != AF_INET)
642 if (cmd->p.ip.s_addr == ((struct sockaddr_in *)
643 (ia->ifa_addr))->sin_addr.s_addr)
644 return(1); /* match */
647 return(0); /* no match, fail ... */
650 #define SNPARGS(buf, len) buf + len, sizeof(buf) > len ? sizeof(buf) - len : 0
653 * We enter here when we have a rule with O_LOG.
654 * XXX this function alone takes about 2Kbytes of code!
657 ipfw_log(struct ip_fw *f, u_int hlen, struct ether_header *eh,
658 struct mbuf *m, struct ifnet *oif)
661 int limit_reached = 0;
662 char action2[40], proto[48], fragment[28];
667 if (f == NULL) { /* bogus pkt */
668 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
670 if (verbose_limit != 0 &&
671 ctx->ipfw_norule_counter >= verbose_limit)
673 ctx->ipfw_norule_counter++;
674 if (ctx->ipfw_norule_counter == verbose_limit)
675 limit_reached = verbose_limit;
677 } else { /* O_LOG is the first action, find the real one */
678 ipfw_insn *cmd = ACTION_PTR(f);
679 ipfw_insn_log *l = (ipfw_insn_log *)cmd;
681 if (l->max_log != 0 && l->log_left == 0)
684 if (l->log_left == 0)
685 limit_reached = l->max_log;
686 cmd += F_LEN(cmd); /* point to first action */
687 if (cmd->opcode == O_PROB)
691 switch (cmd->opcode) {
697 if (cmd->arg1==ICMP_REJECT_RST) {
699 } else if (cmd->arg1==ICMP_UNREACH_HOST) {
702 ksnprintf(SNPARGS(action2, 0), "Unreach %d",
716 ksnprintf(SNPARGS(action2, 0), "Divert %d", cmd->arg1);
720 ksnprintf(SNPARGS(action2, 0), "Tee %d", cmd->arg1);
724 ksnprintf(SNPARGS(action2, 0), "SkipTo %d", cmd->arg1);
728 ksnprintf(SNPARGS(action2, 0), "Pipe %d", cmd->arg1);
732 ksnprintf(SNPARGS(action2, 0), "Queue %d", cmd->arg1);
737 ipfw_insn_sa *sa = (ipfw_insn_sa *)cmd;
740 len = ksnprintf(SNPARGS(action2, 0),
742 inet_ntoa(sa->sa.sin_addr));
743 if (sa->sa.sin_port) {
744 ksnprintf(SNPARGS(action2, len), ":%d",
756 if (hlen == 0) { /* non-ip */
757 ksnprintf(SNPARGS(proto, 0), "MAC");
759 struct ip *ip = mtod(m, struct ip *);
760 /* these three are all aliases to the same thing */
761 struct icmp *const icmp = L3HDR(struct icmp, ip);
762 struct tcphdr *const tcp = (struct tcphdr *)icmp;
763 struct udphdr *const udp = (struct udphdr *)icmp;
765 int ip_off, offset, ip_len;
768 if (eh != NULL) { /* layer 2 packets are as on the wire */
769 ip_off = ntohs(ip->ip_off);
770 ip_len = ntohs(ip->ip_len);
775 offset = ip_off & IP_OFFMASK;
778 len = ksnprintf(SNPARGS(proto, 0), "TCP %s",
779 inet_ntoa(ip->ip_src));
781 ksnprintf(SNPARGS(proto, len), ":%d %s:%d",
782 ntohs(tcp->th_sport),
783 inet_ntoa(ip->ip_dst),
784 ntohs(tcp->th_dport));
786 ksnprintf(SNPARGS(proto, len), " %s",
787 inet_ntoa(ip->ip_dst));
792 len = ksnprintf(SNPARGS(proto, 0), "UDP %s",
793 inet_ntoa(ip->ip_src));
795 ksnprintf(SNPARGS(proto, len), ":%d %s:%d",
796 ntohs(udp->uh_sport),
797 inet_ntoa(ip->ip_dst),
798 ntohs(udp->uh_dport));
800 ksnprintf(SNPARGS(proto, len), " %s",
801 inet_ntoa(ip->ip_dst));
807 len = ksnprintf(SNPARGS(proto, 0),
812 len = ksnprintf(SNPARGS(proto, 0), "ICMP ");
814 len += ksnprintf(SNPARGS(proto, len), "%s",
815 inet_ntoa(ip->ip_src));
816 ksnprintf(SNPARGS(proto, len), " %s",
817 inet_ntoa(ip->ip_dst));
821 len = ksnprintf(SNPARGS(proto, 0), "P:%d %s", ip->ip_p,
822 inet_ntoa(ip->ip_src));
823 ksnprintf(SNPARGS(proto, len), " %s",
824 inet_ntoa(ip->ip_dst));
828 if (ip_off & (IP_MF | IP_OFFMASK)) {
829 ksnprintf(SNPARGS(fragment, 0), " (frag %d:%d@%d%s)",
830 ntohs(ip->ip_id), ip_len - (ip->ip_hl << 2),
831 offset << 3, (ip_off & IP_MF) ? "+" : "");
835 if (oif || m->m_pkthdr.rcvif) {
836 log(LOG_SECURITY | LOG_INFO,
837 "ipfw: %d %s %s %s via %s%s\n",
839 action, proto, oif ? "out" : "in",
840 oif ? oif->if_xname : m->m_pkthdr.rcvif->if_xname,
843 log(LOG_SECURITY | LOG_INFO,
844 "ipfw: %d %s %s [no if info]%s\n",
846 action, proto, fragment);
850 log(LOG_SECURITY | LOG_NOTICE,
851 "ipfw: limit %d reached on entry %d\n",
852 limit_reached, f ? f->rulenum : -1);
859 * IMPORTANT: the hash function for dynamic rules must be commutative
860 * in source and destination (ip,port), because rules are bidirectional
861 * and we want to find both in the same bucket.
864 hash_packet(struct ipfw_flow_id *id)
868 i = (id->dst_ip) ^ (id->src_ip) ^ (id->dst_port) ^ (id->src_port);
869 i &= (curr_dyn_buckets - 1);
874 * unlink a dynamic rule from a chain. prev is a pointer to
875 * the previous one, q is a pointer to the rule to delete,
876 * head is a pointer to the head of the queue.
877 * Modifies q and potentially also head.
879 #define UNLINK_DYN_RULE(prev, head, q) \
881 ipfw_dyn_rule *old_q = q; \
883 /* remove a refcount to the parent */ \
884 if (q->dyn_type == O_LIMIT) \
885 q->parent->count--; \
886 DPRINTF("-- unlink entry 0x%08x %d -> 0x%08x %d, %d left\n", \
887 q->id.src_ip, q->id.src_port, \
888 q->id.dst_ip, q->id.dst_port, dyn_count - 1); \
890 prev->next = q = q->next; \
892 head = q = q->next; \
893 KASSERT(dyn_count > 0, ("invalid dyn count %u", dyn_count)); \
895 kfree(old_q, M_IPFW); \
898 #define TIME_LEQ(a, b) ((int)((a) - (b)) <= 0)
901 * Remove dynamic rules pointing to "rule", or all of them if rule == NULL.
903 * If keep_me == NULL, rules are deleted even if not expired,
904 * otherwise only expired rules are removed.
906 * The value of the second parameter is also used to point to identify
907 * a rule we absolutely do not want to remove (e.g. because we are
908 * holding a reference to it -- this is the case with O_LIMIT_PARENT
909 * rules). The pointer is only used for comparison, so any non-null
913 remove_dyn_rule_locked(struct ip_fw *rule, ipfw_dyn_rule *keep_me)
915 static uint32_t last_remove = 0; /* XXX */
917 #define FORCE (keep_me == NULL)
919 ipfw_dyn_rule *prev, *q;
920 int i, pass = 0, max_pass = 0, unlinked = 0;
922 if (ipfw_dyn_v == NULL || dyn_count == 0)
924 /* do not expire more than once per second, it is useless */
925 if (!FORCE && last_remove == time_second)
927 last_remove = time_second;
930 * because O_LIMIT refer to parent rules, during the first pass only
931 * remove child and mark any pending LIMIT_PARENT, and remove
932 * them in a second pass.
935 for (i = 0; i < curr_dyn_buckets; i++) {
936 for (prev = NULL, q = ipfw_dyn_v[i]; q;) {
938 * Logic can become complex here, so we split tests.
942 if (rule != NULL && rule->stub != q->stub)
943 goto next; /* not the one we are looking for */
944 if (q->dyn_type == O_LIMIT_PARENT) {
946 * handle parent in the second pass,
947 * record we need one.
952 if (FORCE && q->count != 0) {
953 /* XXX should not happen! */
954 kprintf("OUCH! cannot remove rule, "
955 "count %d\n", q->count);
958 if (!FORCE && !TIME_LEQ(q->expire, time_second))
962 UNLINK_DYN_RULE(prev, ipfw_dyn_v[i], q);
969 if (pass++ < max_pass)
979 * lookup a dynamic rule.
981 static ipfw_dyn_rule *
982 lookup_dyn_rule(struct ipfw_flow_id *pkt, int *match_direction,
986 * stateful ipfw extensions.
987 * Lookup into dynamic session queue
989 #define MATCH_REVERSE 0
990 #define MATCH_FORWARD 1
992 #define MATCH_UNKNOWN 3
993 int i, dir = MATCH_NONE;
994 ipfw_dyn_rule *q=NULL;
996 if (ipfw_dyn_v == NULL)
997 goto done; /* not found */
999 i = hash_packet(pkt);
1000 for (q = ipfw_dyn_v[i]; q != NULL;) {
1001 if (q->dyn_type == O_LIMIT_PARENT)
1004 if (TIME_LEQ(q->expire, time_second)) {
1006 * Entry expired; skip.
1007 * Let ipfw_tick() take care of it
1012 if (pkt->proto == q->id.proto) {
1013 if (pkt->src_ip == q->id.src_ip &&
1014 pkt->dst_ip == q->id.dst_ip &&
1015 pkt->src_port == q->id.src_port &&
1016 pkt->dst_port == q->id.dst_port) {
1017 dir = MATCH_FORWARD;
1020 if (pkt->src_ip == q->id.dst_ip &&
1021 pkt->dst_ip == q->id.src_ip &&
1022 pkt->src_port == q->id.dst_port &&
1023 pkt->dst_port == q->id.src_port) {
1024 dir = MATCH_REVERSE;
1032 goto done; /* q = NULL, not found */
1034 if (pkt->proto == IPPROTO_TCP) { /* update state according to flags */
1035 u_char flags = pkt->flags & (TH_FIN|TH_SYN|TH_RST);
1037 #define BOTH_SYN (TH_SYN | (TH_SYN << 8))
1038 #define BOTH_FIN (TH_FIN | (TH_FIN << 8))
1040 q->state |= (dir == MATCH_FORWARD ) ? flags : (flags << 8);
1042 case TH_SYN: /* opening */
1043 q->expire = time_second + dyn_syn_lifetime;
1046 case BOTH_SYN: /* move to established */
1047 case BOTH_SYN | TH_FIN : /* one side tries to close */
1048 case BOTH_SYN | (TH_FIN << 8) :
1050 uint32_t ack = ntohl(tcp->th_ack);
1052 #define _SEQ_GE(a, b) ((int)(a) - (int)(b) >= 0)
1054 if (dir == MATCH_FORWARD) {
1055 if (q->ack_fwd == 0 ||
1056 _SEQ_GE(ack, q->ack_fwd))
1058 else /* ignore out-of-sequence */
1061 if (q->ack_rev == 0 ||
1062 _SEQ_GE(ack, q->ack_rev))
1064 else /* ignore out-of-sequence */
1069 q->expire = time_second + dyn_ack_lifetime;
1072 case BOTH_SYN | BOTH_FIN: /* both sides closed */
1073 KKASSERT(dyn_fin_lifetime < dyn_keepalive_period);
1074 q->expire = time_second + dyn_fin_lifetime;
1080 * reset or some invalid combination, but can also
1081 * occur if we use keep-state the wrong way.
1083 if ((q->state & ((TH_RST << 8) | TH_RST)) == 0)
1084 kprintf("invalid state: 0x%x\n", q->state);
1086 KKASSERT(dyn_rst_lifetime < dyn_keepalive_period);
1087 q->expire = time_second + dyn_rst_lifetime;
1090 } else if (pkt->proto == IPPROTO_UDP) {
1091 q->expire = time_second + dyn_udp_lifetime;
1093 /* other protocols */
1094 q->expire = time_second + dyn_short_lifetime;
1097 if (match_direction)
1098 *match_direction = dir;
1102 static struct ip_fw *
1103 lookup_rule(struct ipfw_flow_id *pkt, int *match_direction, struct tcphdr *tcp,
1104 uint16_t len, int *deny)
1106 struct ip_fw *rule = NULL;
1108 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
1112 gen = ctx->ipfw_gen;
1114 lockmgr(&dyn_lock, LK_SHARED);
1116 if (ctx->ipfw_gen != gen) {
1118 * Static rules had been change when we were waiting
1119 * for the dynamic hash table lock; deny this packet,
1120 * since it is _not_ known whether it is safe to keep
1121 * iterating the static rules.
1127 q = lookup_dyn_rule(pkt, match_direction, tcp);
1131 rule = q->stub->rule[mycpuid];
1132 KKASSERT(rule->stub == q->stub && rule->cpuid == mycpuid);
1139 lockmgr(&dyn_lock, LK_RELEASE);
1144 realloc_dynamic_table(void)
1146 ipfw_dyn_rule **old_dyn_v;
1147 uint32_t old_curr_dyn_buckets;
1149 KASSERT(dyn_buckets <= 65536 && (dyn_buckets & (dyn_buckets - 1)) == 0,
1150 ("invalid dyn_buckets %d", dyn_buckets));
1152 /* Save the current buckets array for later error recovery */
1153 old_dyn_v = ipfw_dyn_v;
1154 old_curr_dyn_buckets = curr_dyn_buckets;
1156 curr_dyn_buckets = dyn_buckets;
1158 ipfw_dyn_v = kmalloc(curr_dyn_buckets * sizeof(ipfw_dyn_rule *),
1159 M_IPFW, M_NOWAIT | M_ZERO);
1160 if (ipfw_dyn_v != NULL || curr_dyn_buckets <= 2)
1163 curr_dyn_buckets /= 2;
1164 if (curr_dyn_buckets <= old_curr_dyn_buckets &&
1165 old_dyn_v != NULL) {
1167 * Don't try allocating smaller buckets array, reuse
1168 * the old one, which alreay contains enough buckets
1174 if (ipfw_dyn_v != NULL) {
1175 if (old_dyn_v != NULL)
1176 kfree(old_dyn_v, M_IPFW);
1178 /* Allocation failed, restore old buckets array */
1179 ipfw_dyn_v = old_dyn_v;
1180 curr_dyn_buckets = old_curr_dyn_buckets;
1183 if (ipfw_dyn_v != NULL)
1188 * Install state of type 'type' for a dynamic session.
1189 * The hash table contains two type of rules:
1190 * - regular rules (O_KEEP_STATE)
1191 * - rules for sessions with limited number of sess per user
1192 * (O_LIMIT). When they are created, the parent is
1193 * increased by 1, and decreased on delete. In this case,
1194 * the third parameter is the parent rule and not the chain.
1195 * - "parent" rules for the above (O_LIMIT_PARENT).
1197 static ipfw_dyn_rule *
1198 add_dyn_rule(struct ipfw_flow_id *id, uint8_t dyn_type, struct ip_fw *rule)
1203 if (ipfw_dyn_v == NULL ||
1204 (dyn_count == 0 && dyn_buckets != curr_dyn_buckets)) {
1205 realloc_dynamic_table();
1206 if (ipfw_dyn_v == NULL)
1207 return NULL; /* failed ! */
1209 i = hash_packet(id);
1211 r = kmalloc(sizeof(*r), M_IPFW, M_NOWAIT | M_ZERO);
1215 /* increase refcount on parent, and set pointer */
1216 if (dyn_type == O_LIMIT) {
1217 ipfw_dyn_rule *parent = (ipfw_dyn_rule *)rule;
1219 if (parent->dyn_type != O_LIMIT_PARENT)
1220 panic("invalid parent");
1223 rule = parent->stub->rule[mycpuid];
1224 KKASSERT(rule->stub == parent->stub);
1226 KKASSERT(rule->cpuid == mycpuid && rule->stub != NULL);
1229 r->expire = time_second + dyn_syn_lifetime;
1230 r->stub = rule->stub;
1231 r->dyn_type = dyn_type;
1232 r->pcnt = r->bcnt = 0;
1236 r->next = ipfw_dyn_v[i];
1240 DPRINTF("-- add dyn entry ty %d 0x%08x %d -> 0x%08x %d, total %d\n",
1242 r->id.src_ip, r->id.src_port,
1243 r->id.dst_ip, r->id.dst_port, dyn_count);
1248 * lookup dynamic parent rule using pkt and rule as search keys.
1249 * If the lookup fails, then install one.
1251 static ipfw_dyn_rule *
1252 lookup_dyn_parent(struct ipfw_flow_id *pkt, struct ip_fw *rule)
1258 i = hash_packet(pkt);
1259 for (q = ipfw_dyn_v[i]; q != NULL; q = q->next) {
1260 if (q->dyn_type == O_LIMIT_PARENT &&
1261 rule->stub == q->stub &&
1262 pkt->proto == q->id.proto &&
1263 pkt->src_ip == q->id.src_ip &&
1264 pkt->dst_ip == q->id.dst_ip &&
1265 pkt->src_port == q->id.src_port &&
1266 pkt->dst_port == q->id.dst_port) {
1267 q->expire = time_second + dyn_short_lifetime;
1268 DPRINTF("lookup_dyn_parent found 0x%p\n", q);
1273 return add_dyn_rule(pkt, O_LIMIT_PARENT, rule);
1277 * Install dynamic state for rule type cmd->o.opcode
1279 * Returns 1 (failure) if state is not installed because of errors or because
1280 * session limitations are enforced.
1283 install_state_locked(struct ip_fw *rule, ipfw_insn_limit *cmd,
1284 struct ip_fw_args *args)
1286 static int last_log; /* XXX */
1290 DPRINTF("-- install state type %d 0x%08x %u -> 0x%08x %u\n",
1292 args->f_id.src_ip, args->f_id.src_port,
1293 args->f_id.dst_ip, args->f_id.dst_port);
1295 q = lookup_dyn_rule(&args->f_id, NULL, NULL);
1296 if (q != NULL) { /* should never occur */
1297 if (last_log != time_second) {
1298 last_log = time_second;
1299 kprintf(" install_state: entry already present, done\n");
1304 if (dyn_count >= dyn_max) {
1306 * Run out of slots, try to remove any expired rule.
1308 remove_dyn_rule_locked(NULL, (ipfw_dyn_rule *)1);
1309 if (dyn_count >= dyn_max) {
1310 if (last_log != time_second) {
1311 last_log = time_second;
1312 kprintf("install_state: "
1313 "Too many dynamic rules\n");
1315 return 1; /* cannot install, notify caller */
1319 switch (cmd->o.opcode) {
1320 case O_KEEP_STATE: /* bidir rule */
1321 if (add_dyn_rule(&args->f_id, O_KEEP_STATE, rule) == NULL)
1325 case O_LIMIT: /* limit number of sessions */
1327 uint16_t limit_mask = cmd->limit_mask;
1328 struct ipfw_flow_id id;
1329 ipfw_dyn_rule *parent;
1331 DPRINTF("installing dyn-limit rule %d\n",
1334 id.dst_ip = id.src_ip = 0;
1335 id.dst_port = id.src_port = 0;
1336 id.proto = args->f_id.proto;
1338 if (limit_mask & DYN_SRC_ADDR)
1339 id.src_ip = args->f_id.src_ip;
1340 if (limit_mask & DYN_DST_ADDR)
1341 id.dst_ip = args->f_id.dst_ip;
1342 if (limit_mask & DYN_SRC_PORT)
1343 id.src_port = args->f_id.src_port;
1344 if (limit_mask & DYN_DST_PORT)
1345 id.dst_port = args->f_id.dst_port;
1347 parent = lookup_dyn_parent(&id, rule);
1348 if (parent == NULL) {
1349 kprintf("add parent failed\n");
1353 if (parent->count >= cmd->conn_limit) {
1355 * See if we can remove some expired rule.
1357 remove_dyn_rule_locked(rule, parent);
1358 if (parent->count >= cmd->conn_limit) {
1360 last_log != time_second) {
1361 last_log = time_second;
1362 log(LOG_SECURITY | LOG_DEBUG,
1364 "too many entries\n");
1369 if (add_dyn_rule(&args->f_id, O_LIMIT,
1370 (struct ip_fw *)parent) == NULL)
1375 kprintf("unknown dynamic rule type %u\n", cmd->o.opcode);
1378 lookup_dyn_rule(&args->f_id, NULL, NULL); /* XXX just set lifetime */
1383 install_state(struct ip_fw *rule, ipfw_insn_limit *cmd,
1384 struct ip_fw_args *args, int *deny)
1386 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
1391 gen = ctx->ipfw_gen;
1393 lockmgr(&dyn_lock, LK_EXCLUSIVE);
1394 if (ctx->ipfw_gen != gen) {
1395 /* See the comment in lookup_rule() */
1398 ret = install_state_locked(rule, cmd, args);
1400 lockmgr(&dyn_lock, LK_RELEASE);
1406 * Transmit a TCP packet, containing either a RST or a keepalive.
1407 * When flags & TH_RST, we are sending a RST packet, because of a
1408 * "reset" action matched the packet.
1409 * Otherwise we are sending a keepalive, and flags & TH_
1412 send_pkt(struct ipfw_flow_id *id, uint32_t seq, uint32_t ack, int flags)
1417 struct route sro; /* fake route */
1419 MGETHDR(m, MB_DONTWAIT, MT_HEADER);
1422 m->m_pkthdr.rcvif = NULL;
1423 m->m_pkthdr.len = m->m_len = sizeof(struct ip) + sizeof(struct tcphdr);
1424 m->m_data += max_linkhdr;
1426 ip = mtod(m, struct ip *);
1427 bzero(ip, m->m_len);
1428 tcp = (struct tcphdr *)(ip + 1); /* no IP options */
1429 ip->ip_p = IPPROTO_TCP;
1433 * Assume we are sending a RST (or a keepalive in the reverse
1434 * direction), swap src and destination addresses and ports.
1436 ip->ip_src.s_addr = htonl(id->dst_ip);
1437 ip->ip_dst.s_addr = htonl(id->src_ip);
1438 tcp->th_sport = htons(id->dst_port);
1439 tcp->th_dport = htons(id->src_port);
1440 if (flags & TH_RST) { /* we are sending a RST */
1441 if (flags & TH_ACK) {
1442 tcp->th_seq = htonl(ack);
1443 tcp->th_ack = htonl(0);
1444 tcp->th_flags = TH_RST;
1448 tcp->th_seq = htonl(0);
1449 tcp->th_ack = htonl(seq);
1450 tcp->th_flags = TH_RST | TH_ACK;
1454 * We are sending a keepalive. flags & TH_SYN determines
1455 * the direction, forward if set, reverse if clear.
1456 * NOTE: seq and ack are always assumed to be correct
1457 * as set by the caller. This may be confusing...
1459 if (flags & TH_SYN) {
1461 * we have to rewrite the correct addresses!
1463 ip->ip_dst.s_addr = htonl(id->dst_ip);
1464 ip->ip_src.s_addr = htonl(id->src_ip);
1465 tcp->th_dport = htons(id->dst_port);
1466 tcp->th_sport = htons(id->src_port);
1468 tcp->th_seq = htonl(seq);
1469 tcp->th_ack = htonl(ack);
1470 tcp->th_flags = TH_ACK;
1474 * set ip_len to the payload size so we can compute
1475 * the tcp checksum on the pseudoheader
1476 * XXX check this, could save a couple of words ?
1478 ip->ip_len = htons(sizeof(struct tcphdr));
1479 tcp->th_sum = in_cksum(m, m->m_pkthdr.len);
1482 * now fill fields left out earlier
1484 ip->ip_ttl = ip_defttl;
1485 ip->ip_len = m->m_pkthdr.len;
1487 bzero(&sro, sizeof(sro));
1488 ip_rtaddr(ip->ip_dst, &sro);
1490 m->m_pkthdr.fw_flags |= IPFW_MBUF_GENERATED;
1491 ip_output(m, NULL, &sro, 0, NULL, NULL);
1497 * sends a reject message, consuming the mbuf passed as an argument.
1500 send_reject(struct ip_fw_args *args, int code, int offset, int ip_len)
1502 if (code != ICMP_REJECT_RST) { /* Send an ICMP unreach */
1503 /* We need the IP header in host order for icmp_error(). */
1504 if (args->eh != NULL) {
1505 struct ip *ip = mtod(args->m, struct ip *);
1507 ip->ip_len = ntohs(ip->ip_len);
1508 ip->ip_off = ntohs(ip->ip_off);
1510 icmp_error(args->m, ICMP_UNREACH, code, 0L, 0);
1511 } else if (offset == 0 && args->f_id.proto == IPPROTO_TCP) {
1512 struct tcphdr *const tcp =
1513 L3HDR(struct tcphdr, mtod(args->m, struct ip *));
1515 if ((tcp->th_flags & TH_RST) == 0) {
1516 send_pkt(&args->f_id, ntohl(tcp->th_seq),
1517 ntohl(tcp->th_ack), tcp->th_flags | TH_RST);
1528 * Given an ip_fw *, lookup_next_rule will return a pointer
1529 * to the next rule, which can be either the jump
1530 * target (for skipto instructions) or the next one in the list (in
1531 * all other cases including a missing jump target).
1532 * The result is also written in the "next_rule" field of the rule.
1533 * Backward jumps are not allowed, so start looking from the next
1536 * This never returns NULL -- in case we do not have an exact match,
1537 * the next rule is returned. When the ruleset is changed,
1538 * pointers are flushed so we are always correct.
1541 static struct ip_fw *
1542 lookup_next_rule(struct ip_fw *me)
1544 struct ip_fw *rule = NULL;
1547 /* look for action, in case it is a skipto */
1548 cmd = ACTION_PTR(me);
1549 if (cmd->opcode == O_LOG)
1551 if (cmd->opcode == O_SKIPTO) {
1552 for (rule = me->next; rule; rule = rule->next) {
1553 if (rule->rulenum >= cmd->arg1)
1557 if (rule == NULL) /* failure or not a skipto */
1559 me->next_rule = rule;
1564 _ipfw_match_uid(const struct ipfw_flow_id *fid, struct ifnet *oif,
1565 enum ipfw_opcodes opcode, uid_t uid)
1567 struct in_addr src_ip, dst_ip;
1568 struct inpcbinfo *pi;
1572 if (fid->proto == IPPROTO_TCP) {
1574 pi = &tcbinfo[mycpuid];
1575 } else if (fid->proto == IPPROTO_UDP) {
1583 * Values in 'fid' are in host byte order
1585 dst_ip.s_addr = htonl(fid->dst_ip);
1586 src_ip.s_addr = htonl(fid->src_ip);
1588 pcb = in_pcblookup_hash(pi,
1589 dst_ip, htons(fid->dst_port),
1590 src_ip, htons(fid->src_port),
1593 pcb = in_pcblookup_hash(pi,
1594 src_ip, htons(fid->src_port),
1595 dst_ip, htons(fid->dst_port),
1598 if (pcb == NULL || pcb->inp_socket == NULL)
1601 if (opcode == O_UID) {
1602 #define socheckuid(a,b) ((a)->so_cred->cr_uid != (b))
1603 return !socheckuid(pcb->inp_socket, uid);
1606 return groupmember(uid, pcb->inp_socket->so_cred);
1611 ipfw_match_uid(const struct ipfw_flow_id *fid, struct ifnet *oif,
1612 enum ipfw_opcodes opcode, uid_t uid, int *deny)
1614 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
1619 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);
1631 * The main check routine for the firewall.
1633 * All arguments are in args so we can modify them and return them
1634 * back to the caller.
1638 * args->m (in/out) The packet; we set to NULL when/if we nuke it.
1639 * Starts with the IP header.
1640 * args->eh (in) Mac header if present, or NULL for layer3 packet.
1641 * args->oif Outgoing interface, or NULL if packet is incoming.
1642 * The incoming interface is in the mbuf. (in)
1644 * args->rule Pointer to the last matching rule (in/out)
1645 * args->f_id Addresses grabbed from the packet (out)
1649 * If the packet was denied/rejected and has been dropped, *m is equal
1650 * to NULL upon return.
1652 * IP_FW_DENY the packet must be dropped.
1653 * IP_FW_PASS The packet is to be accepted and routed normally.
1654 * IP_FW_DIVERT Divert the packet to port (args->cookie)
1655 * IP_FW_TEE Tee the packet to port (args->cookie)
1656 * IP_FW_DUMMYNET Send the packet to pipe/queue (args->cookie)
1660 ipfw_chk(struct ip_fw_args *args)
1663 * Local variables hold state during the processing of a packet.
1665 * IMPORTANT NOTE: to speed up the processing of rules, there
1666 * are some assumption on the values of the variables, which
1667 * are documented here. Should you change them, please check
1668 * the implementation of the various instructions to make sure
1669 * that they still work.
1671 * args->eh The MAC header. It is non-null for a layer2
1672 * packet, it is NULL for a layer-3 packet.
1674 * m | args->m Pointer to the mbuf, as received from the caller.
1675 * It may change if ipfw_chk() does an m_pullup, or if it
1676 * consumes the packet because it calls send_reject().
1677 * XXX This has to change, so that ipfw_chk() never modifies
1678 * or consumes the buffer.
1679 * ip is simply an alias of the value of m, and it is kept
1680 * in sync with it (the packet is supposed to start with
1683 struct mbuf *m = args->m;
1684 struct ip *ip = mtod(m, struct ip *);
1687 * oif | args->oif If NULL, ipfw_chk has been called on the
1688 * inbound path (ether_input, ip_input).
1689 * If non-NULL, ipfw_chk has been called on the outbound path
1690 * (ether_output, ip_output).
1692 struct ifnet *oif = args->oif;
1694 struct ip_fw *f = NULL; /* matching rule */
1695 int retval = IP_FW_PASS;
1697 struct divert_info *divinfo;
1700 * hlen The length of the IPv4 header.
1701 * hlen >0 means we have an IPv4 packet.
1703 u_int hlen = 0; /* hlen >0 means we have an IP pkt */
1706 * offset The offset of a fragment. offset != 0 means that
1707 * we have a fragment at this offset of an IPv4 packet.
1708 * offset == 0 means that (if this is an IPv4 packet)
1709 * this is the first or only fragment.
1714 * Local copies of addresses. They are only valid if we have
1717 * proto The protocol. Set to 0 for non-ip packets,
1718 * or to the protocol read from the packet otherwise.
1719 * proto != 0 means that we have an IPv4 packet.
1721 * src_port, dst_port port numbers, in HOST format. Only
1722 * valid for TCP and UDP packets.
1724 * src_ip, dst_ip ip addresses, in NETWORK format.
1725 * Only valid for IPv4 packets.
1728 uint16_t src_port = 0, dst_port = 0; /* NOTE: host format */
1729 struct in_addr src_ip, dst_ip; /* NOTE: network format */
1730 uint16_t ip_len = 0;
1733 * dyn_dir = MATCH_UNKNOWN when rules unchecked,
1734 * MATCH_NONE when checked and not matched (dyn_f = NULL),
1735 * MATCH_FORWARD or MATCH_REVERSE otherwise (dyn_f != NULL)
1737 int dyn_dir = MATCH_UNKNOWN;
1738 struct ip_fw *dyn_f = NULL;
1739 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
1741 if (m->m_pkthdr.fw_flags & IPFW_MBUF_GENERATED)
1742 return IP_FW_PASS; /* accept */
1744 if (args->eh == NULL || /* layer 3 packet */
1745 (m->m_pkthdr.len >= sizeof(struct ip) &&
1746 ntohs(args->eh->ether_type) == ETHERTYPE_IP))
1747 hlen = ip->ip_hl << 2;
1750 * Collect parameters into local variables for faster matching.
1752 if (hlen == 0) { /* do not grab addresses for non-ip pkts */
1753 proto = args->f_id.proto = 0; /* mark f_id invalid */
1754 goto after_ip_checks;
1757 proto = args->f_id.proto = ip->ip_p;
1758 src_ip = ip->ip_src;
1759 dst_ip = ip->ip_dst;
1760 if (args->eh != NULL) { /* layer 2 packets are as on the wire */
1761 offset = ntohs(ip->ip_off) & IP_OFFMASK;
1762 ip_len = ntohs(ip->ip_len);
1764 offset = ip->ip_off & IP_OFFMASK;
1765 ip_len = ip->ip_len;
1768 #define PULLUP_TO(len) \
1770 if (m->m_len < (len)) { \
1771 args->m = m = m_pullup(m, (len));\
1773 goto pullup_failed; \
1774 ip = mtod(m, struct ip *); \
1784 PULLUP_TO(hlen + sizeof(struct tcphdr));
1785 tcp = L3HDR(struct tcphdr, ip);
1786 dst_port = tcp->th_dport;
1787 src_port = tcp->th_sport;
1788 args->f_id.flags = tcp->th_flags;
1796 PULLUP_TO(hlen + sizeof(struct udphdr));
1797 udp = L3HDR(struct udphdr, ip);
1798 dst_port = udp->uh_dport;
1799 src_port = udp->uh_sport;
1804 PULLUP_TO(hlen + 4); /* type, code and checksum. */
1805 args->f_id.flags = L3HDR(struct icmp, ip)->icmp_type;
1815 args->f_id.src_ip = ntohl(src_ip.s_addr);
1816 args->f_id.dst_ip = ntohl(dst_ip.s_addr);
1817 args->f_id.src_port = src_port = ntohs(src_port);
1818 args->f_id.dst_port = dst_port = ntohs(dst_port);
1823 * Packet has already been tagged. Look for the next rule
1824 * to restart processing.
1826 * If fw_one_pass != 0 then just accept it.
1827 * XXX should not happen here, but optimized out in
1833 /* This rule is being/has been flushed */
1837 KASSERT(args->rule->cpuid == mycpuid,
1838 ("rule used on cpu%d", mycpuid));
1840 /* This rule was deleted */
1841 if (args->rule->rule_flags & IPFW_RULE_F_INVALID)
1844 f = args->rule->next_rule;
1846 f = lookup_next_rule(args->rule);
1849 * Find the starting rule. It can be either the first
1850 * one, or the one after divert_rule if asked so.
1854 mtag = m_tag_find(m, PACKET_TAG_IPFW_DIVERT, NULL);
1856 divinfo = m_tag_data(mtag);
1857 skipto = divinfo->skipto;
1862 f = ctx->ipfw_layer3_chain;
1863 if (args->eh == NULL && skipto != 0) {
1864 /* No skipto during rule flushing */
1868 if (skipto >= IPFW_DEFAULT_RULE)
1869 return IP_FW_DENY; /* invalid */
1871 while (f && f->rulenum <= skipto)
1873 if (f == NULL) /* drop packet */
1875 } else if (ipfw_flushing) {
1876 /* Rules are being flushed; skip to default rule */
1877 f = ctx->ipfw_default_rule;
1880 if ((mtag = m_tag_find(m, PACKET_TAG_IPFW_DIVERT, NULL)) != NULL)
1881 m_tag_delete(m, mtag);
1884 * Now scan the rules, and parse microinstructions for each rule.
1886 for (; f; f = f->next) {
1889 int skip_or; /* skip rest of OR block */
1892 if (ctx->ipfw_set_disable & (1 << f->set))
1896 for (l = f->cmd_len, cmd = f->cmd; l > 0;
1897 l -= cmdlen, cmd += cmdlen) {
1901 * check_body is a jump target used when we find a
1902 * CHECK_STATE, and need to jump to the body of
1907 cmdlen = F_LEN(cmd);
1909 * An OR block (insn_1 || .. || insn_n) has the
1910 * F_OR bit set in all but the last instruction.
1911 * The first match will set "skip_or", and cause
1912 * the following instructions to be skipped until
1913 * past the one with the F_OR bit clear.
1915 if (skip_or) { /* skip this instruction */
1916 if ((cmd->len & F_OR) == 0)
1917 skip_or = 0; /* next one is good */
1920 match = 0; /* set to 1 if we succeed */
1922 switch (cmd->opcode) {
1924 * The first set of opcodes compares the packet's
1925 * fields with some pattern, setting 'match' if a
1926 * match is found. At the end of the loop there is
1927 * logic to deal with F_NOT and F_OR flags associated
1935 kprintf("ipfw: opcode %d unimplemented\n",
1942 * We only check offset == 0 && proto != 0,
1943 * as this ensures that we have an IPv4
1944 * packet with the ports info.
1949 match = ipfw_match_uid(&args->f_id, oif,
1951 (uid_t)((ipfw_insn_u32 *)cmd)->d[0],
1958 match = iface_match(m->m_pkthdr.rcvif,
1959 (ipfw_insn_if *)cmd);
1963 match = iface_match(oif, (ipfw_insn_if *)cmd);
1967 match = iface_match(oif ? oif :
1968 m->m_pkthdr.rcvif, (ipfw_insn_if *)cmd);
1972 if (args->eh != NULL) { /* have MAC header */
1973 uint32_t *want = (uint32_t *)
1974 ((ipfw_insn_mac *)cmd)->addr;
1975 uint32_t *mask = (uint32_t *)
1976 ((ipfw_insn_mac *)cmd)->mask;
1977 uint32_t *hdr = (uint32_t *)args->eh;
1980 (want[0] == (hdr[0] & mask[0]) &&
1981 want[1] == (hdr[1] & mask[1]) &&
1982 want[2] == (hdr[2] & mask[2]));
1987 if (args->eh != NULL) {
1989 ntohs(args->eh->ether_type);
1991 ((ipfw_insn_u16 *)cmd)->ports;
1994 /* Special vlan handling */
1995 if (m->m_flags & M_VLANTAG)
1998 for (i = cmdlen - 1; !match && i > 0;
2001 (t >= p[0] && t <= p[1]);
2007 match = (hlen > 0 && offset != 0);
2010 case O_IN: /* "out" is "not in" */
2011 match = (oif == NULL);
2015 match = (args->eh != NULL);
2020 * We do not allow an arg of 0 so the
2021 * check of "proto" only suffices.
2023 match = (proto == cmd->arg1);
2027 match = (hlen > 0 &&
2028 ((ipfw_insn_ip *)cmd)->addr.s_addr ==
2033 match = (hlen > 0 &&
2034 ((ipfw_insn_ip *)cmd)->addr.s_addr ==
2036 ((ipfw_insn_ip *)cmd)->mask.s_addr));
2043 tif = INADDR_TO_IFP(&src_ip);
2044 match = (tif != NULL);
2051 uint32_t *d = (uint32_t *)(cmd + 1);
2053 cmd->opcode == O_IP_DST_SET ?
2059 addr -= d[0]; /* subtract base */
2061 (addr < cmd->arg1) &&
2062 (d[1 + (addr >> 5)] &
2063 (1 << (addr & 0x1f)));
2068 match = (hlen > 0 &&
2069 ((ipfw_insn_ip *)cmd)->addr.s_addr ==
2074 match = (hlen > 0) &&
2075 (((ipfw_insn_ip *)cmd)->addr.s_addr ==
2077 ((ipfw_insn_ip *)cmd)->mask.s_addr));
2084 tif = INADDR_TO_IFP(&dst_ip);
2085 match = (tif != NULL);
2092 * offset == 0 && proto != 0 is enough
2093 * to guarantee that we have an IPv4
2094 * packet with port info.
2096 if ((proto==IPPROTO_UDP || proto==IPPROTO_TCP)
2099 (cmd->opcode == O_IP_SRCPORT) ?
2100 src_port : dst_port ;
2102 ((ipfw_insn_u16 *)cmd)->ports;
2105 for (i = cmdlen - 1; !match && i > 0;
2108 (x >= p[0] && x <= p[1]);
2114 match = (offset == 0 && proto==IPPROTO_ICMP &&
2115 icmptype_match(ip, (ipfw_insn_u32 *)cmd));
2119 match = (hlen > 0 && ipopts_match(ip, cmd));
2123 match = (hlen > 0 && cmd->arg1 == ip->ip_v);
2127 match = (hlen > 0 && cmd->arg1 == ip->ip_ttl);
2131 match = (hlen > 0 &&
2132 cmd->arg1 == ntohs(ip->ip_id));
2136 match = (hlen > 0 && cmd->arg1 == ip_len);
2139 case O_IPPRECEDENCE:
2140 match = (hlen > 0 &&
2141 (cmd->arg1 == (ip->ip_tos & 0xe0)));
2145 match = (hlen > 0 &&
2146 flags_match(cmd, ip->ip_tos));
2150 match = (proto == IPPROTO_TCP && offset == 0 &&
2152 L3HDR(struct tcphdr,ip)->th_flags));
2156 match = (proto == IPPROTO_TCP && offset == 0 &&
2157 tcpopts_match(ip, cmd));
2161 match = (proto == IPPROTO_TCP && offset == 0 &&
2162 ((ipfw_insn_u32 *)cmd)->d[0] ==
2163 L3HDR(struct tcphdr,ip)->th_seq);
2167 match = (proto == IPPROTO_TCP && offset == 0 &&
2168 ((ipfw_insn_u32 *)cmd)->d[0] ==
2169 L3HDR(struct tcphdr,ip)->th_ack);
2173 match = (proto == IPPROTO_TCP && offset == 0 &&
2175 L3HDR(struct tcphdr,ip)->th_win);
2179 /* reject packets which have SYN only */
2180 /* XXX should i also check for TH_ACK ? */
2181 match = (proto == IPPROTO_TCP && offset == 0 &&
2182 (L3HDR(struct tcphdr,ip)->th_flags &
2183 (TH_RST | TH_ACK | TH_SYN)) != TH_SYN);
2188 ipfw_log(f, hlen, args->eh, m, oif);
2193 match = (krandom() <
2194 ((ipfw_insn_u32 *)cmd)->d[0]);
2198 * The second set of opcodes represents 'actions',
2199 * i.e. the terminal part of a rule once the packet
2200 * matches all previous patterns.
2201 * Typically there is only one action for each rule,
2202 * and the opcode is stored at the end of the rule
2203 * (but there are exceptions -- see below).
2205 * In general, here we set retval and terminate the
2206 * outer loop (would be a 'break 3' in some language,
2207 * but we need to do a 'goto done').
2210 * O_COUNT and O_SKIPTO actions:
2211 * instead of terminating, we jump to the next rule
2212 * ('goto next_rule', equivalent to a 'break 2'),
2213 * or to the SKIPTO target ('goto again' after
2214 * having set f, cmd and l), respectively.
2216 * O_LIMIT and O_KEEP_STATE: these opcodes are
2217 * not real 'actions', and are stored right
2218 * before the 'action' part of the rule.
2219 * These opcodes try to install an entry in the
2220 * state tables; if successful, we continue with
2221 * the next opcode (match=1; break;), otherwise
2222 * the packet must be dropped ('goto done' after
2223 * setting retval). If static rules are changed
2224 * during the state installation, the packet will
2225 * be dropped and rule's stats will not beupdated
2226 * ('return IP_FW_DENY').
2228 * O_PROBE_STATE and O_CHECK_STATE: these opcodes
2229 * cause a lookup of the state table, and a jump
2230 * to the 'action' part of the parent rule
2231 * ('goto check_body') if an entry is found, or
2232 * (CHECK_STATE only) a jump to the next rule if
2233 * the entry is not found ('goto next_rule').
2234 * The result of the lookup is cached to make
2235 * further instances of these opcodes are
2236 * effectively NOPs. If static rules are changed
2237 * during the state looking up, the packet will
2238 * be dropped and rule's stats will not be updated
2239 * ('return IP_FW_DENY').
2243 if (!(f->rule_flags & IPFW_RULE_F_STATE)) {
2244 kprintf("%s rule (%d) is not ready "
2246 cmd->opcode == O_LIMIT ?
2247 "limit" : "keep state",
2248 f->rulenum, f->cpuid);
2251 if (install_state(f,
2252 (ipfw_insn_limit *)cmd, args, &deny)) {
2256 retval = IP_FW_DENY;
2257 goto done; /* error/limit violation */
2267 * dynamic rules are checked at the first
2268 * keep-state or check-state occurrence,
2269 * with the result being stored in dyn_dir.
2270 * The compiler introduces a PROBE_STATE
2271 * instruction for us when we have a
2272 * KEEP_STATE (because PROBE_STATE needs
2275 if (dyn_dir == MATCH_UNKNOWN) {
2276 dyn_f = lookup_rule(&args->f_id,
2278 proto == IPPROTO_TCP ?
2279 L3HDR(struct tcphdr, ip) : NULL,
2283 if (dyn_f != NULL) {
2285 * Found a rule from a dynamic
2286 * entry; jump to the 'action'
2290 cmd = ACTION_PTR(f);
2291 l = f->cmd_len - f->act_ofs;
2296 * Dynamic entry not found. If CHECK_STATE,
2297 * skip to next rule, if PROBE_STATE just
2298 * ignore and continue with next opcode.
2300 if (cmd->opcode == O_CHECK_STATE)
2302 else if (!(f->rule_flags & IPFW_RULE_F_STATE))
2303 goto next_rule; /* not ready yet */
2308 retval = IP_FW_PASS; /* accept */
2313 args->rule = f; /* report matching rule */
2314 args->cookie = cmd->arg1;
2315 retval = IP_FW_DUMMYNET;
2320 if (args->eh) /* not on layer 2 */
2323 mtag = m_tag_get(PACKET_TAG_IPFW_DIVERT,
2324 sizeof(*divinfo), MB_DONTWAIT);
2326 retval = IP_FW_DENY;
2329 divinfo = m_tag_data(mtag);
2331 divinfo->skipto = f->rulenum;
2332 divinfo->port = cmd->arg1;
2333 divinfo->tee = (cmd->opcode == O_TEE);
2334 m_tag_prepend(m, mtag);
2336 args->cookie = cmd->arg1;
2337 retval = (cmd->opcode == O_DIVERT) ?
2338 IP_FW_DIVERT : IP_FW_TEE;
2343 f->pcnt++; /* update stats */
2345 f->timestamp = time_second;
2346 if (cmd->opcode == O_COUNT)
2349 if (f->next_rule == NULL)
2350 lookup_next_rule(f);
2356 * Drop the packet and send a reject notice
2357 * if the packet is not ICMP (or is an ICMP
2358 * query), and it is not multicast/broadcast.
2361 (proto != IPPROTO_ICMP ||
2362 is_icmp_query(ip)) &&
2363 !(m->m_flags & (M_BCAST|M_MCAST)) &&
2364 !IN_MULTICAST(ntohl(dst_ip.s_addr))) {
2366 * Update statistics before the possible
2367 * blocking 'send_reject'
2371 f->timestamp = time_second;
2373 send_reject(args, cmd->arg1,
2378 * Return directly here, rule stats
2379 * have been updated above.
2385 retval = IP_FW_DENY;
2389 if (args->eh) /* not valid on layer2 pkts */
2391 if (!dyn_f || dyn_dir == MATCH_FORWARD) {
2392 struct sockaddr_in *sin;
2394 mtag = m_tag_get(PACKET_TAG_IPFORWARD,
2395 sizeof(*sin), MB_DONTWAIT);
2397 retval = IP_FW_DENY;
2400 sin = m_tag_data(mtag);
2402 /* Structure copy */
2403 *sin = ((ipfw_insn_sa *)cmd)->sa;
2405 m_tag_prepend(m, mtag);
2406 m->m_pkthdr.fw_flags |=
2407 IPFORWARD_MBUF_TAGGED;
2408 m->m_pkthdr.fw_flags &=
2409 ~BRIDGE_MBUF_TAGGED;
2411 retval = IP_FW_PASS;
2415 panic("-- unknown opcode %d", cmd->opcode);
2416 } /* end of switch() on opcodes */
2418 if (cmd->len & F_NOT)
2422 if (cmd->len & F_OR)
2425 if (!(cmd->len & F_OR)) /* not an OR block, */
2426 break; /* try next rule */
2429 } /* end of inner for, scan opcodes */
2431 next_rule:; /* try next rule */
2433 } /* end of outer for, scan rules */
2434 kprintf("+++ ipfw: ouch!, skip past end of rules, denying packet\n");
2438 /* Update statistics */
2441 f->timestamp = time_second;
2446 kprintf("pullup failed\n");
2451 ipfw_dummynet_io(struct mbuf *m, int pipe_nr, int dir, struct ip_fw_args *fwa)
2456 const struct ipfw_flow_id *id;
2457 struct dn_flow_id *fid;
2461 mtag = m_tag_get(PACKET_TAG_DUMMYNET, sizeof(*pkt), MB_DONTWAIT);
2466 m_tag_prepend(m, mtag);
2468 pkt = m_tag_data(mtag);
2469 bzero(pkt, sizeof(*pkt));
2471 cmd = fwa->rule->cmd + fwa->rule->act_ofs;
2472 if (cmd->opcode == O_LOG)
2474 KASSERT(cmd->opcode == O_PIPE || cmd->opcode == O_QUEUE,
2475 ("Rule is not PIPE or QUEUE, opcode %d", cmd->opcode));
2478 pkt->dn_flags = (dir & DN_FLAGS_DIR_MASK);
2479 pkt->ifp = fwa->oif;
2480 pkt->pipe_nr = pipe_nr;
2482 pkt->cpuid = mycpuid;
2483 pkt->msgport = cur_netport();
2487 fid->fid_dst_ip = id->dst_ip;
2488 fid->fid_src_ip = id->src_ip;
2489 fid->fid_dst_port = id->dst_port;
2490 fid->fid_src_port = id->src_port;
2491 fid->fid_proto = id->proto;
2492 fid->fid_flags = id->flags;
2494 ipfw_ref_rule(fwa->rule);
2495 pkt->dn_priv = fwa->rule;
2496 pkt->dn_unref_priv = ipfw_unref_rule;
2498 if (cmd->opcode == O_PIPE)
2499 pkt->dn_flags |= DN_FLAGS_IS_PIPE;
2501 m->m_pkthdr.fw_flags |= DUMMYNET_MBUF_TAGGED;
2505 * When a rule is added/deleted, clear the next_rule pointers in all rules.
2506 * These will be reconstructed on the fly as packets are matched.
2507 * Must be called at splimp().
2510 ipfw_flush_rule_ptrs(struct ipfw_context *ctx)
2514 for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next)
2515 rule->next_rule = NULL;
2518 static __inline void
2519 ipfw_inc_static_count(struct ip_fw *rule)
2521 /* Static rule's counts are updated only on CPU0 */
2522 KKASSERT(mycpuid == 0);
2525 static_ioc_len += IOC_RULESIZE(rule);
2528 static __inline void
2529 ipfw_dec_static_count(struct ip_fw *rule)
2531 int l = IOC_RULESIZE(rule);
2533 /* Static rule's counts are updated only on CPU0 */
2534 KKASSERT(mycpuid == 0);
2536 KASSERT(static_count > 0, ("invalid static count %u", static_count));
2539 KASSERT(static_ioc_len >= l,
2540 ("invalid static len %u", static_ioc_len));
2541 static_ioc_len -= l;
2545 ipfw_link_sibling(struct netmsg_ipfw *fwmsg, struct ip_fw *rule)
2547 if (fwmsg->sibling != NULL) {
2548 KKASSERT(mycpuid > 0 && fwmsg->sibling->cpuid == mycpuid - 1);
2549 fwmsg->sibling->sibling = rule;
2551 fwmsg->sibling = rule;
2554 static struct ip_fw *
2555 ipfw_create_rule(const struct ipfw_ioc_rule *ioc_rule, struct ip_fw_stub *stub)
2559 rule = kmalloc(RULESIZE(ioc_rule), M_IPFW, M_WAITOK | M_ZERO);
2561 rule->act_ofs = ioc_rule->act_ofs;
2562 rule->cmd_len = ioc_rule->cmd_len;
2563 rule->rulenum = ioc_rule->rulenum;
2564 rule->set = ioc_rule->set;
2565 rule->usr_flags = ioc_rule->usr_flags;
2567 bcopy(ioc_rule->cmd, rule->cmd, rule->cmd_len * 4 /* XXX */);
2570 rule->cpuid = mycpuid;
2574 stub->rule[mycpuid] = rule;
2580 ipfw_add_rule_dispatch(netmsg_t nmsg)
2582 struct netmsg_ipfw *fwmsg = (struct netmsg_ipfw *)nmsg;
2583 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2586 rule = ipfw_create_rule(fwmsg->ioc_rule, fwmsg->stub);
2589 * Bump generation after ipfw_create_rule(),
2590 * since this function is blocking
2595 * Insert rule into the pre-determined position
2597 if (fwmsg->prev_rule != NULL) {
2598 struct ip_fw *prev, *next;
2600 prev = fwmsg->prev_rule;
2601 KKASSERT(prev->cpuid == mycpuid);
2603 next = fwmsg->next_rule;
2604 KKASSERT(next->cpuid == mycpuid);
2610 * Move to the position on the next CPU
2611 * before the msg is forwarded.
2613 fwmsg->prev_rule = prev->sibling;
2614 fwmsg->next_rule = next->sibling;
2616 KKASSERT(fwmsg->next_rule == NULL);
2617 rule->next = ctx->ipfw_layer3_chain;
2618 ctx->ipfw_layer3_chain = rule;
2621 /* Link rule CPU sibling */
2622 ipfw_link_sibling(fwmsg, rule);
2624 ipfw_flush_rule_ptrs(ctx);
2627 /* Statistics only need to be updated once */
2628 ipfw_inc_static_count(rule);
2630 /* Return the rule on CPU0 */
2631 nmsg->lmsg.u.ms_resultp = rule;
2634 ifnet_forwardmsg(&nmsg->lmsg, mycpuid + 1);
2638 ipfw_enable_state_dispatch(netmsg_t nmsg)
2640 struct lwkt_msg *lmsg = &nmsg->lmsg;
2641 struct ip_fw *rule = lmsg->u.ms_resultp;
2642 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2646 KKASSERT(rule->cpuid == mycpuid);
2647 KKASSERT(rule->stub != NULL && rule->stub->rule[mycpuid] == rule);
2648 KKASSERT(!(rule->rule_flags & IPFW_RULE_F_STATE));
2649 rule->rule_flags |= IPFW_RULE_F_STATE;
2650 lmsg->u.ms_resultp = rule->sibling;
2652 ifnet_forwardmsg(lmsg, mycpuid + 1);
2656 * Add a new rule to the list. Copy the rule into a malloc'ed area,
2657 * then possibly create a rule number and add the rule to the list.
2658 * Update the rule_number in the input struct so the caller knows
2662 ipfw_add_rule(struct ipfw_ioc_rule *ioc_rule, uint32_t rule_flags)
2664 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2665 struct netmsg_ipfw fwmsg;
2666 struct netmsg_base *nmsg;
2667 struct ip_fw *f, *prev, *rule;
2668 struct ip_fw_stub *stub;
2670 IPFW_ASSERT_CFGPORT(&curthread->td_msgport);
2673 * If rulenum is 0, find highest numbered rule before the
2674 * default rule, and add rule number incremental step.
2676 if (ioc_rule->rulenum == 0) {
2677 int step = autoinc_step;
2679 KKASSERT(step >= IPFW_AUTOINC_STEP_MIN &&
2680 step <= IPFW_AUTOINC_STEP_MAX);
2683 * Locate the highest numbered rule before default
2685 for (f = ctx->ipfw_layer3_chain; f; f = f->next) {
2686 if (f->rulenum == IPFW_DEFAULT_RULE)
2688 ioc_rule->rulenum = f->rulenum;
2690 if (ioc_rule->rulenum < IPFW_DEFAULT_RULE - step)
2691 ioc_rule->rulenum += step;
2693 KASSERT(ioc_rule->rulenum != IPFW_DEFAULT_RULE &&
2694 ioc_rule->rulenum != 0,
2695 ("invalid rule num %d", ioc_rule->rulenum));
2698 * Now find the right place for the new rule in the sorted list.
2700 for (prev = NULL, f = ctx->ipfw_layer3_chain; f;
2701 prev = f, f = f->next) {
2702 if (f->rulenum > ioc_rule->rulenum) {
2703 /* Found the location */
2707 KASSERT(f != NULL, ("no default rule?!"));
2709 if (rule_flags & IPFW_RULE_F_STATE) {
2713 * If the new rule will create states, then allocate
2714 * a rule stub, which will be referenced by states
2717 size = sizeof(*stub) + ((ncpus - 1) * sizeof(struct ip_fw *));
2718 stub = kmalloc(size, M_IPFW, M_WAITOK | M_ZERO);
2724 * Duplicate the rule onto each CPU.
2725 * The rule duplicated on CPU0 will be returned.
2727 bzero(&fwmsg, sizeof(fwmsg));
2729 netmsg_init(nmsg, NULL, &curthread->td_msgport,
2730 0, ipfw_add_rule_dispatch);
2731 fwmsg.ioc_rule = ioc_rule;
2732 fwmsg.prev_rule = prev;
2733 fwmsg.next_rule = prev == NULL ? NULL : f;
2736 ifnet_domsg(&nmsg->lmsg, 0);
2737 KKASSERT(fwmsg.prev_rule == NULL && fwmsg.next_rule == NULL);
2739 rule = nmsg->lmsg.u.ms_resultp;
2740 KKASSERT(rule != NULL && rule->cpuid == mycpuid);
2742 if (rule_flags & IPFW_RULE_F_STATE) {
2744 * Turn on state flag, _after_ everything on all
2745 * CPUs have been setup.
2747 bzero(nmsg, sizeof(*nmsg));
2748 netmsg_init(nmsg, NULL, &curthread->td_msgport,
2749 0, ipfw_enable_state_dispatch);
2750 nmsg->lmsg.u.ms_resultp = rule;
2752 ifnet_domsg(&nmsg->lmsg, 0);
2753 KKASSERT(nmsg->lmsg.u.ms_resultp == NULL);
2756 DPRINTF("++ installed rule %d, static count now %d\n",
2757 rule->rulenum, static_count);
2761 * Free storage associated with a static rule (including derived
2763 * The caller is in charge of clearing rule pointers to avoid
2764 * dangling pointers.
2765 * @return a pointer to the next entry.
2766 * Arguments are not checked, so they better be correct.
2767 * Must be called at splimp().
2769 static struct ip_fw *
2770 ipfw_delete_rule(struct ipfw_context *ctx,
2771 struct ip_fw *prev, struct ip_fw *rule)
2774 struct ip_fw_stub *stub;
2778 /* STATE flag should have been cleared before we reach here */
2779 KKASSERT((rule->rule_flags & IPFW_RULE_F_STATE) == 0);
2784 ctx->ipfw_layer3_chain = n;
2788 /* Mark the rule as invalid */
2789 rule->rule_flags |= IPFW_RULE_F_INVALID;
2790 rule->next_rule = NULL;
2791 rule->sibling = NULL;
2794 /* Don't reset cpuid here; keep various assertion working */
2798 /* Statistics only need to be updated once */
2800 ipfw_dec_static_count(rule);
2802 /* Free 'stub' on the last CPU */
2803 if (stub != NULL && mycpuid == ncpus - 1)
2804 kfree(stub, M_IPFW);
2806 /* Try to free this rule */
2807 ipfw_free_rule(rule);
2809 /* Return the next rule */
2814 ipfw_flush_dispatch(netmsg_t nmsg)
2816 struct lwkt_msg *lmsg = &nmsg->lmsg;
2817 int kill_default = lmsg->u.ms_result;
2818 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2821 ipfw_flush_rule_ptrs(ctx); /* more efficient to do outside the loop */
2823 while ((rule = ctx->ipfw_layer3_chain) != NULL &&
2824 (kill_default || rule->rulenum != IPFW_DEFAULT_RULE))
2825 ipfw_delete_rule(ctx, NULL, rule);
2827 ifnet_forwardmsg(lmsg, mycpuid + 1);
2831 ipfw_disable_rule_state_dispatch(netmsg_t nmsg)
2833 struct netmsg_del *dmsg = (struct netmsg_del *)nmsg;
2834 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2839 rule = dmsg->start_rule;
2841 KKASSERT(rule->cpuid == mycpuid);
2844 * Move to the position on the next CPU
2845 * before the msg is forwarded.
2847 dmsg->start_rule = rule->sibling;
2849 KKASSERT(dmsg->rulenum == 0);
2850 rule = ctx->ipfw_layer3_chain;
2853 while (rule != NULL) {
2854 if (dmsg->rulenum && rule->rulenum != dmsg->rulenum)
2856 rule->rule_flags &= ~IPFW_RULE_F_STATE;
2860 ifnet_forwardmsg(&nmsg->lmsg, mycpuid + 1);
2864 * Deletes all rules from a chain (including the default rule
2865 * if the second argument is set).
2866 * Must be called at splimp().
2869 ipfw_flush(int kill_default)
2871 struct netmsg_del dmsg;
2872 struct netmsg_base nmsg;
2873 struct lwkt_msg *lmsg;
2875 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2877 IPFW_ASSERT_CFGPORT(&curthread->td_msgport);
2880 * If 'kill_default' then caller has done the necessary
2881 * msgport syncing; unnecessary to do it again.
2883 if (!kill_default) {
2885 * Let ipfw_chk() know the rules are going to
2886 * be flushed, so it could jump directly to
2890 netmsg_service_sync();
2894 * Clear STATE flag on rules, so no more states (dyn rules)
2897 bzero(&dmsg, sizeof(dmsg));
2898 netmsg_init(&dmsg.base, NULL, &curthread->td_msgport,
2899 0, ipfw_disable_rule_state_dispatch);
2900 ifnet_domsg(&dmsg.base.lmsg, 0);
2903 * This actually nukes all states (dyn rules)
2905 lockmgr(&dyn_lock, LK_EXCLUSIVE);
2906 for (rule = ctx->ipfw_layer3_chain; rule != NULL; rule = rule->next) {
2908 * Can't check IPFW_RULE_F_STATE here,
2909 * since it has been cleared previously.
2910 * Check 'stub' instead.
2912 if (rule->stub != NULL) {
2914 remove_dyn_rule_locked(rule, NULL);
2917 lockmgr(&dyn_lock, LK_RELEASE);
2920 * Press the 'flush' button
2922 bzero(&nmsg, sizeof(nmsg));
2923 netmsg_init(&nmsg, NULL, &curthread->td_msgport,
2924 0, ipfw_flush_dispatch);
2926 lmsg->u.ms_result = kill_default;
2927 ifnet_domsg(lmsg, 0);
2929 KASSERT(dyn_count == 0, ("%u dyn rule remains", dyn_count));
2932 if (ipfw_dyn_v != NULL) {
2934 * Free dynamic rules(state) hash table
2936 kfree(ipfw_dyn_v, M_IPFW);
2940 KASSERT(static_count == 0,
2941 ("%u static rules remain", static_count));
2942 KASSERT(static_ioc_len == 0,
2943 ("%u bytes of static rules remain", static_ioc_len));
2945 KASSERT(static_count == 1,
2946 ("%u static rules remain", static_count));
2947 KASSERT(static_ioc_len == IOC_RULESIZE(ctx->ipfw_default_rule),
2948 ("%u bytes of static rules remain, should be %lu",
2950 (u_long)IOC_RULESIZE(ctx->ipfw_default_rule)));
2958 ipfw_alt_delete_rule_dispatch(netmsg_t nmsg)
2960 struct netmsg_del *dmsg = (struct netmsg_del *)nmsg;
2961 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2962 struct ip_fw *rule, *prev;
2964 rule = dmsg->start_rule;
2965 KKASSERT(rule->cpuid == mycpuid);
2966 dmsg->start_rule = rule->sibling;
2968 prev = dmsg->prev_rule;
2970 KKASSERT(prev->cpuid == mycpuid);
2973 * Move to the position on the next CPU
2974 * before the msg is forwarded.
2976 dmsg->prev_rule = prev->sibling;
2980 * flush pointers outside the loop, then delete all matching
2981 * rules. 'prev' remains the same throughout the cycle.
2983 ipfw_flush_rule_ptrs(ctx);
2984 while (rule && rule->rulenum == dmsg->rulenum)
2985 rule = ipfw_delete_rule(ctx, prev, rule);
2987 ifnet_forwardmsg(&nmsg->lmsg, mycpuid + 1);
2991 ipfw_alt_delete_rule(uint16_t rulenum)
2993 struct ip_fw *prev, *rule, *f;
2994 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2995 struct netmsg_del dmsg;
2996 struct netmsg_base *nmsg;
3000 * Locate first rule to delete
3002 for (prev = NULL, rule = ctx->ipfw_layer3_chain;
3003 rule && rule->rulenum < rulenum;
3004 prev = rule, rule = rule->next)
3006 if (rule->rulenum != rulenum)
3010 * Check whether any rules with the given number will
3014 for (f = rule; f && f->rulenum == rulenum; f = f->next) {
3015 if (f->rule_flags & IPFW_RULE_F_STATE) {
3023 * Clear the STATE flag, so no more states will be
3024 * created based the rules numbered 'rulenum'.
3026 bzero(&dmsg, sizeof(dmsg));
3028 netmsg_init(nmsg, NULL, &curthread->td_msgport,
3029 0, ipfw_disable_rule_state_dispatch);
3030 dmsg.start_rule = rule;
3031 dmsg.rulenum = rulenum;
3033 ifnet_domsg(&nmsg->lmsg, 0);
3034 KKASSERT(dmsg.start_rule == NULL);
3037 * Nuke all related states
3039 lockmgr(&dyn_lock, LK_EXCLUSIVE);
3040 for (f = rule; f && f->rulenum == rulenum; f = f->next) {
3042 * Can't check IPFW_RULE_F_STATE here,
3043 * since it has been cleared previously.
3044 * Check 'stub' instead.
3046 if (f->stub != NULL) {
3048 remove_dyn_rule_locked(f, NULL);
3051 lockmgr(&dyn_lock, LK_RELEASE);
3055 * Get rid of the rule duplications on all CPUs
3057 bzero(&dmsg, sizeof(dmsg));
3059 netmsg_init(nmsg, NULL, &curthread->td_msgport,
3060 0, ipfw_alt_delete_rule_dispatch);
3061 dmsg.prev_rule = prev;
3062 dmsg.start_rule = rule;
3063 dmsg.rulenum = rulenum;
3065 ifnet_domsg(&nmsg->lmsg, 0);
3066 KKASSERT(dmsg.prev_rule == NULL && dmsg.start_rule == NULL);
3071 ipfw_alt_delete_ruleset_dispatch(netmsg_t nmsg)
3073 struct netmsg_del *dmsg = (struct netmsg_del *)nmsg;
3074 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3075 struct ip_fw *prev, *rule;
3080 ipfw_flush_rule_ptrs(ctx);
3083 rule = ctx->ipfw_layer3_chain;
3084 while (rule != NULL) {
3085 if (rule->set == dmsg->from_set) {
3086 rule = ipfw_delete_rule(ctx, prev, rule);
3095 KASSERT(del, ("no match set?!"));
3097 ifnet_forwardmsg(&nmsg->lmsg, mycpuid + 1);
3101 ipfw_disable_ruleset_state_dispatch(netmsg_t nmsg)
3103 struct netmsg_del *dmsg = (struct netmsg_del *)nmsg;
3104 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3112 for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next) {
3113 if (rule->set == dmsg->from_set) {
3117 rule->rule_flags &= ~IPFW_RULE_F_STATE;
3120 KASSERT(cleared, ("no match set?!"));
3122 ifnet_forwardmsg(&nmsg->lmsg, mycpuid + 1);
3126 ipfw_alt_delete_ruleset(uint8_t set)
3128 struct netmsg_del dmsg;
3129 struct netmsg_base *nmsg;
3132 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3135 * Check whether the 'set' exists. If it exists,
3136 * then check whether any rules within the set will
3137 * try to create states.
3141 for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next) {
3142 if (rule->set == set) {
3144 if (rule->rule_flags & IPFW_RULE_F_STATE) {
3151 return 0; /* XXX EINVAL? */
3155 * Clear the STATE flag, so no more states will be
3156 * created based the rules in this set.
3158 bzero(&dmsg, sizeof(dmsg));
3160 netmsg_init(nmsg, NULL, &curthread->td_msgport,
3161 0, ipfw_disable_ruleset_state_dispatch);
3162 dmsg.from_set = set;
3164 ifnet_domsg(&nmsg->lmsg, 0);
3167 * Nuke all related states
3169 lockmgr(&dyn_lock, LK_EXCLUSIVE);
3170 for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next) {
3171 if (rule->set != set)
3175 * Can't check IPFW_RULE_F_STATE here,
3176 * since it has been cleared previously.
3177 * Check 'stub' instead.
3179 if (rule->stub != NULL) {
3181 remove_dyn_rule_locked(rule, NULL);
3184 lockmgr(&dyn_lock, LK_RELEASE);
3190 bzero(&dmsg, sizeof(dmsg));
3192 netmsg_init(nmsg, NULL, &curthread->td_msgport,
3193 0, ipfw_alt_delete_ruleset_dispatch);
3194 dmsg.from_set = set;
3196 ifnet_domsg(&nmsg->lmsg, 0);
3201 ipfw_alt_move_rule_dispatch(netmsg_t nmsg)
3203 struct netmsg_del *dmsg = (struct netmsg_del *)nmsg;
3206 rule = dmsg->start_rule;
3207 KKASSERT(rule->cpuid == mycpuid);
3210 * Move to the position on the next CPU
3211 * before the msg is forwarded.
3213 dmsg->start_rule = rule->sibling;
3215 while (rule && rule->rulenum <= dmsg->rulenum) {
3216 if (rule->rulenum == dmsg->rulenum)
3217 rule->set = dmsg->to_set;
3220 ifnet_forwardmsg(&nmsg->lmsg, mycpuid + 1);
3224 ipfw_alt_move_rule(uint16_t rulenum, uint8_t set)
3226 struct netmsg_del dmsg;
3227 struct netmsg_base *nmsg;
3229 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3232 * Locate first rule to move
3234 for (rule = ctx->ipfw_layer3_chain; rule && rule->rulenum <= rulenum;
3235 rule = rule->next) {
3236 if (rule->rulenum == rulenum && rule->set != set)
3239 if (rule == NULL || rule->rulenum > rulenum)
3240 return 0; /* XXX error? */
3242 bzero(&dmsg, sizeof(dmsg));
3244 netmsg_init(nmsg, NULL, &curthread->td_msgport,
3245 0, ipfw_alt_move_rule_dispatch);
3246 dmsg.start_rule = rule;
3247 dmsg.rulenum = rulenum;
3250 ifnet_domsg(&nmsg->lmsg, 0);
3251 KKASSERT(dmsg.start_rule == NULL);
3256 ipfw_alt_move_ruleset_dispatch(netmsg_t nmsg)
3258 struct netmsg_del *dmsg = (struct netmsg_del *)nmsg;
3259 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3262 for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next) {
3263 if (rule->set == dmsg->from_set)
3264 rule->set = dmsg->to_set;
3266 ifnet_forwardmsg(&nmsg->lmsg, mycpuid + 1);
3270 ipfw_alt_move_ruleset(uint8_t from_set, uint8_t to_set)
3272 struct netmsg_del dmsg;
3273 struct netmsg_base *nmsg;
3275 bzero(&dmsg, sizeof(dmsg));
3277 netmsg_init(nmsg, NULL, &curthread->td_msgport,
3278 0, ipfw_alt_move_ruleset_dispatch);
3279 dmsg.from_set = from_set;
3280 dmsg.to_set = to_set;
3282 ifnet_domsg(&nmsg->lmsg, 0);
3287 ipfw_alt_swap_ruleset_dispatch(netmsg_t nmsg)
3289 struct netmsg_del *dmsg = (struct netmsg_del *)nmsg;
3290 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3293 for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next) {
3294 if (rule->set == dmsg->from_set)
3295 rule->set = dmsg->to_set;
3296 else if (rule->set == dmsg->to_set)
3297 rule->set = dmsg->from_set;
3299 ifnet_forwardmsg(&nmsg->lmsg, mycpuid + 1);
3303 ipfw_alt_swap_ruleset(uint8_t set1, uint8_t set2)
3305 struct netmsg_del dmsg;
3306 struct netmsg_base *nmsg;
3308 bzero(&dmsg, sizeof(dmsg));
3310 netmsg_init(nmsg, NULL, &curthread->td_msgport,
3311 0, ipfw_alt_swap_ruleset_dispatch);
3312 dmsg.from_set = set1;
3315 ifnet_domsg(&nmsg->lmsg, 0);
3320 * Remove all rules with given number, and also do set manipulation.
3322 * The argument is an uint32_t. The low 16 bit are the rule or set number,
3323 * the next 8 bits are the new set, the top 8 bits are the command:
3325 * 0 delete rules with given number
3326 * 1 delete rules with given set number
3327 * 2 move rules with given number to new set
3328 * 3 move rules with given set number to new set
3329 * 4 swap sets with given numbers
3332 ipfw_ctl_alter(uint32_t arg)
3335 uint8_t cmd, new_set;
3338 rulenum = arg & 0xffff;
3339 cmd = (arg >> 24) & 0xff;
3340 new_set = (arg >> 16) & 0xff;
3344 if (new_set >= IPFW_DEFAULT_SET)
3346 if (cmd == 0 || cmd == 2) {
3347 if (rulenum == IPFW_DEFAULT_RULE)
3350 if (rulenum >= IPFW_DEFAULT_SET)
3355 case 0: /* delete rules with given number */
3356 error = ipfw_alt_delete_rule(rulenum);
3359 case 1: /* delete all rules with given set number */
3360 error = ipfw_alt_delete_ruleset(rulenum);
3363 case 2: /* move rules with given number to new set */
3364 error = ipfw_alt_move_rule(rulenum, new_set);
3367 case 3: /* move rules with given set number to new set */
3368 error = ipfw_alt_move_ruleset(rulenum, new_set);
3371 case 4: /* swap two sets */
3372 error = ipfw_alt_swap_ruleset(rulenum, new_set);
3379 * Clear counters for a specific rule.
3382 clear_counters(struct ip_fw *rule, int log_only)
3384 ipfw_insn_log *l = (ipfw_insn_log *)ACTION_PTR(rule);
3386 if (log_only == 0) {
3387 rule->bcnt = rule->pcnt = 0;
3388 rule->timestamp = 0;
3390 if (l->o.opcode == O_LOG)
3391 l->log_left = l->max_log;
3395 ipfw_zero_entry_dispatch(netmsg_t nmsg)
3397 struct netmsg_zent *zmsg = (struct netmsg_zent *)nmsg;
3398 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3401 if (zmsg->rulenum == 0) {
3402 KKASSERT(zmsg->start_rule == NULL);
3404 ctx->ipfw_norule_counter = 0;
3405 for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next)
3406 clear_counters(rule, zmsg->log_only);
3408 struct ip_fw *start = zmsg->start_rule;
3410 KKASSERT(start->cpuid == mycpuid);
3411 KKASSERT(start->rulenum == zmsg->rulenum);
3414 * We can have multiple rules with the same number, so we
3415 * need to clear them all.
3417 for (rule = start; rule && rule->rulenum == zmsg->rulenum;
3419 clear_counters(rule, zmsg->log_only);
3422 * Move to the position on the next CPU
3423 * before the msg is forwarded.
3425 zmsg->start_rule = start->sibling;
3427 ifnet_forwardmsg(&nmsg->lmsg, mycpuid + 1);
3431 * Reset some or all counters on firewall rules.
3432 * @arg frwl is null to clear all entries, or contains a specific
3434 * @arg log_only is 1 if we only want to reset logs, zero otherwise.
3437 ipfw_ctl_zero_entry(int rulenum, int log_only)
3439 struct netmsg_zent zmsg;
3440 struct netmsg_base *nmsg;
3442 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3444 bzero(&zmsg, sizeof(zmsg));
3446 netmsg_init(nmsg, NULL, &curthread->td_msgport,
3447 0, ipfw_zero_entry_dispatch);
3448 zmsg.log_only = log_only;
3451 msg = log_only ? "ipfw: All logging counts reset.\n"
3452 : "ipfw: Accounting cleared.\n";
3457 * Locate the first rule with 'rulenum'
3459 for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next) {
3460 if (rule->rulenum == rulenum)
3463 if (rule == NULL) /* we did not find any matching rules */
3465 zmsg.start_rule = rule;
3466 zmsg.rulenum = rulenum;
3468 msg = log_only ? "ipfw: Entry %d logging count reset.\n"
3469 : "ipfw: Entry %d cleared.\n";
3471 ifnet_domsg(&nmsg->lmsg, 0);
3472 KKASSERT(zmsg.start_rule == NULL);
3475 log(LOG_SECURITY | LOG_NOTICE, msg, rulenum);
3480 * Check validity of the structure before insert.
3481 * Fortunately rules are simple, so this mostly need to check rule sizes.
3484 ipfw_check_ioc_rule(struct ipfw_ioc_rule *rule, int size, uint32_t *rule_flags)
3487 int have_action = 0;
3492 /* Check for valid size */
3493 if (size < sizeof(*rule)) {
3494 kprintf("ipfw: rule too short\n");
3497 l = IOC_RULESIZE(rule);
3499 kprintf("ipfw: size mismatch (have %d want %d)\n", size, l);
3503 /* Check rule number */
3504 if (rule->rulenum == IPFW_DEFAULT_RULE) {
3505 kprintf("ipfw: invalid rule number\n");
3510 * Now go for the individual checks. Very simple ones, basically only
3511 * instruction sizes.
3513 for (l = rule->cmd_len, cmd = rule->cmd; l > 0;
3514 l -= cmdlen, cmd += cmdlen) {
3515 cmdlen = F_LEN(cmd);
3517 kprintf("ipfw: opcode %d size truncated\n",
3522 DPRINTF("ipfw: opcode %d\n", cmd->opcode);
3524 if (cmd->opcode == O_KEEP_STATE || cmd->opcode == O_LIMIT) {
3525 /* This rule will create states */
3526 *rule_flags |= IPFW_RULE_F_STATE;
3529 switch (cmd->opcode) {
3543 case O_IPPRECEDENCE:
3550 if (cmdlen != F_INSN_SIZE(ipfw_insn))
3562 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32))
3567 if (cmdlen != F_INSN_SIZE(ipfw_insn_limit))
3572 if (cmdlen != F_INSN_SIZE(ipfw_insn_log))
3575 ((ipfw_insn_log *)cmd)->log_left =
3576 ((ipfw_insn_log *)cmd)->max_log;
3582 if (cmdlen != F_INSN_SIZE(ipfw_insn_ip))
3584 if (((ipfw_insn_ip *)cmd)->mask.s_addr == 0) {
3585 kprintf("ipfw: opcode %d, useless rule\n",
3593 if (cmd->arg1 == 0 || cmd->arg1 > 256) {
3594 kprintf("ipfw: invalid set size %d\n",
3598 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
3604 if (cmdlen != F_INSN_SIZE(ipfw_insn_mac))
3610 case O_IP_DSTPORT: /* XXX artificial limit, 30 port pairs */
3611 if (cmdlen < 2 || cmdlen > 31)
3618 if (cmdlen != F_INSN_SIZE(ipfw_insn_if))
3624 if (cmdlen != F_INSN_SIZE(ipfw_insn_pipe))
3629 if (cmdlen != F_INSN_SIZE(ipfw_insn_sa)) {
3634 fwd_addr = ((ipfw_insn_sa *)cmd)->
3636 if (IN_MULTICAST(ntohl(fwd_addr))) {
3637 kprintf("ipfw: try forwarding to "
3638 "multicast address\n");
3644 case O_FORWARD_MAC: /* XXX not implemented yet */
3653 if (cmdlen != F_INSN_SIZE(ipfw_insn))
3657 kprintf("ipfw: opcode %d, multiple actions"
3664 kprintf("ipfw: opcode %d, action must be"
3671 kprintf("ipfw: opcode %d, unknown opcode\n",
3676 if (have_action == 0) {
3677 kprintf("ipfw: missing action\n");
3683 kprintf("ipfw: opcode %d size %d wrong\n",
3684 cmd->opcode, cmdlen);
3689 ipfw_ctl_add_rule(struct sockopt *sopt)
3691 struct ipfw_ioc_rule *ioc_rule;
3693 uint32_t rule_flags;
3696 size = sopt->sopt_valsize;
3697 if (size > (sizeof(uint32_t) * IPFW_RULE_SIZE_MAX) ||
3698 size < sizeof(*ioc_rule)) {
3701 if (size != (sizeof(uint32_t) * IPFW_RULE_SIZE_MAX)) {
3702 sopt->sopt_val = krealloc(sopt->sopt_val, sizeof(uint32_t) *
3703 IPFW_RULE_SIZE_MAX, M_TEMP, M_WAITOK);
3705 ioc_rule = sopt->sopt_val;
3707 error = ipfw_check_ioc_rule(ioc_rule, size, &rule_flags);
3711 ipfw_add_rule(ioc_rule, rule_flags);
3713 if (sopt->sopt_dir == SOPT_GET)
3714 sopt->sopt_valsize = IOC_RULESIZE(ioc_rule);
3719 ipfw_copy_rule(const struct ip_fw *rule, struct ipfw_ioc_rule *ioc_rule)
3721 const struct ip_fw *sibling;
3726 KKASSERT(rule->cpuid == IPFW_CFGCPUID);
3728 ioc_rule->act_ofs = rule->act_ofs;
3729 ioc_rule->cmd_len = rule->cmd_len;
3730 ioc_rule->rulenum = rule->rulenum;
3731 ioc_rule->set = rule->set;
3732 ioc_rule->usr_flags = rule->usr_flags;
3734 ioc_rule->set_disable = ipfw_ctx[mycpuid]->ipfw_set_disable;
3735 ioc_rule->static_count = static_count;
3736 ioc_rule->static_len = static_ioc_len;
3739 * Visit (read-only) all of the rule's duplications to get
3740 * the necessary statistics
3747 ioc_rule->timestamp = 0;
3748 for (sibling = rule; sibling != NULL; sibling = sibling->sibling) {
3749 ioc_rule->pcnt += sibling->pcnt;
3750 ioc_rule->bcnt += sibling->bcnt;
3751 if (sibling->timestamp > ioc_rule->timestamp)
3752 ioc_rule->timestamp = sibling->timestamp;
3757 KASSERT(i == ncpus, ("static rule is not duplicated on every cpu"));
3759 bcopy(rule->cmd, ioc_rule->cmd, ioc_rule->cmd_len * 4 /* XXX */);
3761 return ((uint8_t *)ioc_rule + IOC_RULESIZE(ioc_rule));
3765 ipfw_copy_state(const ipfw_dyn_rule *dyn_rule,
3766 struct ipfw_ioc_state *ioc_state)
3768 const struct ipfw_flow_id *id;
3769 struct ipfw_ioc_flowid *ioc_id;
3771 ioc_state->expire = TIME_LEQ(dyn_rule->expire, time_second) ?
3772 0 : dyn_rule->expire - time_second;
3773 ioc_state->pcnt = dyn_rule->pcnt;
3774 ioc_state->bcnt = dyn_rule->bcnt;
3776 ioc_state->dyn_type = dyn_rule->dyn_type;
3777 ioc_state->count = dyn_rule->count;
3779 ioc_state->rulenum = dyn_rule->stub->rule[mycpuid]->rulenum;
3782 ioc_id = &ioc_state->id;
3784 ioc_id->type = ETHERTYPE_IP;
3785 ioc_id->u.ip.dst_ip = id->dst_ip;
3786 ioc_id->u.ip.src_ip = id->src_ip;
3787 ioc_id->u.ip.dst_port = id->dst_port;
3788 ioc_id->u.ip.src_port = id->src_port;
3789 ioc_id->u.ip.proto = id->proto;
3793 ipfw_ctl_get_rules(struct sockopt *sopt)
3795 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3799 uint32_t dcount = 0;
3802 * pass up a copy of the current rules. Static rules
3803 * come first (the last of which has number IPFW_DEFAULT_RULE),
3804 * followed by a possibly empty list of dynamic rule.
3807 size = static_ioc_len; /* size of static rules */
3808 if (ipfw_dyn_v) { /* add size of dyn.rules */
3810 size += dcount * sizeof(struct ipfw_ioc_state);
3813 if (sopt->sopt_valsize < size) {
3814 /* short length, no need to return incomplete rules */
3815 /* XXX: if superuser, no need to zero buffer */
3816 bzero(sopt->sopt_val, sopt->sopt_valsize);
3819 bp = sopt->sopt_val;
3821 for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next)
3822 bp = ipfw_copy_rule(rule, bp);
3824 if (ipfw_dyn_v && dcount != 0) {
3825 struct ipfw_ioc_state *ioc_state = bp;
3826 uint32_t dcount2 = 0;
3828 size_t old_size = size;
3832 lockmgr(&dyn_lock, LK_SHARED);
3834 /* Check 'ipfw_dyn_v' again with lock held */
3835 if (ipfw_dyn_v == NULL)
3838 for (i = 0; i < curr_dyn_buckets; i++) {
3842 * The # of dynamic rules may have grown after the
3843 * snapshot of 'dyn_count' was taken, so we will have
3844 * to check 'dcount' (snapshot of dyn_count) here to
3845 * make sure that we don't overflow the pre-allocated
3848 for (p = ipfw_dyn_v[i]; p != NULL && dcount != 0;
3849 p = p->next, ioc_state++, dcount--, dcount2++)
3850 ipfw_copy_state(p, ioc_state);
3853 lockmgr(&dyn_lock, LK_RELEASE);
3856 * The # of dynamic rules may be shrinked after the
3857 * snapshot of 'dyn_count' was taken. To give user a
3858 * correct dynamic rule count, we use the 'dcount2'
3859 * calculated above (with shared lockmgr lock held).
3861 size = static_ioc_len +
3862 (dcount2 * sizeof(struct ipfw_ioc_state));
3863 KKASSERT(size <= old_size);
3866 sopt->sopt_valsize = size;
3871 ipfw_set_disable_dispatch(netmsg_t nmsg)
3873 struct lwkt_msg *lmsg = &nmsg->lmsg;
3874 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3877 ctx->ipfw_set_disable = lmsg->u.ms_result32;
3879 ifnet_forwardmsg(lmsg, mycpuid + 1);
3883 ipfw_ctl_set_disable(uint32_t disable, uint32_t enable)
3885 struct netmsg_base nmsg;
3886 struct lwkt_msg *lmsg;
3887 uint32_t set_disable;
3889 /* IPFW_DEFAULT_SET is always enabled */
3890 enable |= (1 << IPFW_DEFAULT_SET);
3891 set_disable = (ipfw_ctx[mycpuid]->ipfw_set_disable | disable) & ~enable;
3893 bzero(&nmsg, sizeof(nmsg));
3894 netmsg_init(&nmsg, NULL, &curthread->td_msgport,
3895 0, ipfw_set_disable_dispatch);
3897 lmsg->u.ms_result32 = set_disable;
3899 ifnet_domsg(lmsg, 0);
3903 * {set|get}sockopt parser.
3906 ipfw_ctl(struct sockopt *sopt)
3914 switch (sopt->sopt_name) {
3916 error = ipfw_ctl_get_rules(sopt);
3920 ipfw_flush(0 /* keep default rule */);
3924 error = ipfw_ctl_add_rule(sopt);
3929 * IP_FW_DEL is used for deleting single rules or sets,
3930 * and (ab)used to atomically manipulate sets.
3931 * Argument size is used to distinguish between the two:
3933 * delete single rule or set of rules,
3934 * or reassign rules (or sets) to a different set.
3935 * 2 * sizeof(uint32_t)
3936 * atomic disable/enable sets.
3937 * first uint32_t contains sets to be disabled,
3938 * second uint32_t contains sets to be enabled.
3940 masks = sopt->sopt_val;
3941 size = sopt->sopt_valsize;
3942 if (size == sizeof(*masks)) {
3944 * Delete or reassign static rule
3946 error = ipfw_ctl_alter(masks[0]);
3947 } else if (size == (2 * sizeof(*masks))) {
3949 * Set enable/disable
3951 ipfw_ctl_set_disable(masks[0], masks[1]);
3958 case IP_FW_RESETLOG: /* argument is an int, the rule number */
3961 if (sopt->sopt_val != 0) {
3962 error = soopt_to_kbuf(sopt, &rulenum,
3963 sizeof(int), sizeof(int));
3967 error = ipfw_ctl_zero_entry(rulenum,
3968 sopt->sopt_name == IP_FW_RESETLOG);
3972 kprintf("ipfw_ctl invalid option %d\n", sopt->sopt_name);
3979 * This procedure is only used to handle keepalives. It is invoked
3980 * every dyn_keepalive_period
3983 ipfw_tick_dispatch(netmsg_t nmsg)
3989 IPFW_ASSERT_CFGPORT(&curthread->td_msgport);
3990 KKASSERT(IPFW_LOADED);
3994 lwkt_replymsg(&nmsg->lmsg, 0);
3997 if (ipfw_dyn_v == NULL || dyn_count == 0)
4000 keep_alive = time_second;
4002 lockmgr(&dyn_lock, LK_EXCLUSIVE);
4004 if (ipfw_dyn_v == NULL || dyn_count == 0) {
4005 lockmgr(&dyn_lock, LK_RELEASE);
4008 gen = dyn_buckets_gen;
4010 for (i = 0; i < curr_dyn_buckets; i++) {
4011 ipfw_dyn_rule *q, *prev;
4013 for (prev = NULL, q = ipfw_dyn_v[i]; q != NULL;) {
4014 uint32_t ack_rev, ack_fwd;
4015 struct ipfw_flow_id id;
4017 if (q->dyn_type == O_LIMIT_PARENT)
4020 if (TIME_LEQ(q->expire, time_second)) {
4022 UNLINK_DYN_RULE(prev, ipfw_dyn_v[i], q);
4027 * Keep alive processing
4032 if (q->id.proto != IPPROTO_TCP)
4034 if ((q->state & BOTH_SYN) != BOTH_SYN)
4036 if (TIME_LEQ(time_second + dyn_keepalive_interval,
4038 goto next; /* too early */
4039 if (q->keep_alive == keep_alive)
4040 goto next; /* alreay done */
4043 * Save necessary information, so that they could
4044 * survive after possible blocking in send_pkt()
4047 ack_rev = q->ack_rev;
4048 ack_fwd = q->ack_fwd;
4050 /* Sending has been started */
4051 q->keep_alive = keep_alive;
4053 /* Release lock to avoid possible dead lock */
4054 lockmgr(&dyn_lock, LK_RELEASE);
4055 send_pkt(&id, ack_rev - 1, ack_fwd, TH_SYN);
4056 send_pkt(&id, ack_fwd - 1, ack_rev, 0);
4057 lockmgr(&dyn_lock, LK_EXCLUSIVE);
4059 if (gen != dyn_buckets_gen) {
4061 * Dyn bucket array has been changed during
4062 * the above two sending; reiterate.
4071 lockmgr(&dyn_lock, LK_RELEASE);
4073 callout_reset(&ipfw_timeout_h, dyn_keepalive_period * hz,
4078 * This procedure is only used to handle keepalives. It is invoked
4079 * every dyn_keepalive_period
4082 ipfw_tick(void *dummy __unused)
4084 struct lwkt_msg *lmsg = &ipfw_timeout_netmsg.lmsg;
4086 KKASSERT(mycpuid == IPFW_CFGCPUID);
4090 KKASSERT(lmsg->ms_flags & MSGF_DONE);
4092 lwkt_sendmsg(IPFW_CFGPORT, lmsg);
4093 /* ipfw_timeout_netmsg's handler reset this callout */
4100 ipfw_check_in(void *arg, struct mbuf **m0, struct ifnet *ifp, int dir)
4102 struct ip_fw_args args;
4103 struct mbuf *m = *m0;
4105 int tee = 0, error = 0, ret;
4107 if (m->m_pkthdr.fw_flags & DUMMYNET_MBUF_TAGGED) {
4108 /* Extract info from dummynet tag */
4109 mtag = m_tag_find(m, PACKET_TAG_DUMMYNET, NULL);
4110 KKASSERT(mtag != NULL);
4111 args.rule = ((struct dn_pkt *)m_tag_data(mtag))->dn_priv;
4112 KKASSERT(args.rule != NULL);
4114 m_tag_delete(m, mtag);
4115 m->m_pkthdr.fw_flags &= ~DUMMYNET_MBUF_TAGGED;
4123 ret = ipfw_chk(&args);
4141 case IP_FW_DUMMYNET:
4142 /* Send packet to the appropriate pipe */
4143 ipfw_dummynet_io(m, args.cookie, DN_TO_IP_IN, &args);
4152 * Must clear bridge tag when changing
4154 m->m_pkthdr.fw_flags &= ~BRIDGE_MBUF_TAGGED;
4155 if (ip_divert_p != NULL) {
4156 m = ip_divert_p(m, tee, 1);
4160 /* not sure this is the right error msg */
4166 panic("unknown ipfw return value: %d", ret);
4174 ipfw_check_out(void *arg, struct mbuf **m0, struct ifnet *ifp, int dir)
4176 struct ip_fw_args args;
4177 struct mbuf *m = *m0;
4179 int tee = 0, error = 0, ret;
4181 if (m->m_pkthdr.fw_flags & DUMMYNET_MBUF_TAGGED) {
4182 /* Extract info from dummynet tag */
4183 mtag = m_tag_find(m, PACKET_TAG_DUMMYNET, NULL);
4184 KKASSERT(mtag != NULL);
4185 args.rule = ((struct dn_pkt *)m_tag_data(mtag))->dn_priv;
4186 KKASSERT(args.rule != NULL);
4188 m_tag_delete(m, mtag);
4189 m->m_pkthdr.fw_flags &= ~DUMMYNET_MBUF_TAGGED;
4197 ret = ipfw_chk(&args);
4215 case IP_FW_DUMMYNET:
4216 ipfw_dummynet_io(m, args.cookie, DN_TO_IP_OUT, &args);
4224 if (ip_divert_p != NULL) {
4225 m = ip_divert_p(m, tee, 0);
4229 /* not sure this is the right error msg */
4235 panic("unknown ipfw return value: %d", ret);
4245 struct pfil_head *pfh;
4247 IPFW_ASSERT_CFGPORT(&curthread->td_msgport);
4249 pfh = pfil_head_get(PFIL_TYPE_AF, AF_INET);
4253 pfil_add_hook(ipfw_check_in, NULL, PFIL_IN | PFIL_MPSAFE, pfh);
4254 pfil_add_hook(ipfw_check_out, NULL, PFIL_OUT | PFIL_MPSAFE, pfh);
4260 struct pfil_head *pfh;
4262 IPFW_ASSERT_CFGPORT(&curthread->td_msgport);
4264 pfh = pfil_head_get(PFIL_TYPE_AF, AF_INET);
4268 pfil_remove_hook(ipfw_check_in, NULL, PFIL_IN, pfh);
4269 pfil_remove_hook(ipfw_check_out, NULL, PFIL_OUT, pfh);
4273 ipfw_sysctl_enable_dispatch(netmsg_t nmsg)
4275 struct lwkt_msg *lmsg = &nmsg->lmsg;
4276 int enable = lmsg->u.ms_result;
4278 if (fw_enable == enable)
4287 lwkt_replymsg(lmsg, 0);
4291 ipfw_sysctl_enable(SYSCTL_HANDLER_ARGS)
4293 struct netmsg_base nmsg;
4294 struct lwkt_msg *lmsg;
4298 error = sysctl_handle_int(oidp, &enable, 0, req);
4299 if (error || req->newptr == NULL)
4302 netmsg_init(&nmsg, NULL, &curthread->td_msgport,
4303 0, ipfw_sysctl_enable_dispatch);
4305 lmsg->u.ms_result = enable;
4307 return lwkt_domsg(IPFW_CFGPORT, lmsg, 0);
4311 ipfw_sysctl_autoinc_step(SYSCTL_HANDLER_ARGS)
4313 return sysctl_int_range(oidp, arg1, arg2, req,
4314 IPFW_AUTOINC_STEP_MIN, IPFW_AUTOINC_STEP_MAX);
4318 ipfw_sysctl_dyn_buckets(SYSCTL_HANDLER_ARGS)
4322 lockmgr(&dyn_lock, LK_EXCLUSIVE);
4324 value = dyn_buckets;
4325 error = sysctl_handle_int(oidp, &value, 0, req);
4326 if (error || !req->newptr)
4330 * Make sure we have a power of 2 and
4331 * do not allow more than 64k entries.
4334 if (value <= 1 || value > 65536)
4336 if ((value & (value - 1)) != 0)
4340 dyn_buckets = value;
4342 lockmgr(&dyn_lock, LK_RELEASE);
4347 ipfw_sysctl_dyn_fin(SYSCTL_HANDLER_ARGS)
4349 return sysctl_int_range(oidp, arg1, arg2, req,
4350 1, dyn_keepalive_period - 1);
4354 ipfw_sysctl_dyn_rst(SYSCTL_HANDLER_ARGS)
4356 return sysctl_int_range(oidp, arg1, arg2, req,
4357 1, dyn_keepalive_period - 1);
4361 ipfw_ctx_init_dispatch(netmsg_t nmsg)
4363 struct netmsg_ipfw *fwmsg = (struct netmsg_ipfw *)nmsg;
4364 struct ipfw_context *ctx;
4365 struct ip_fw *def_rule;
4367 ctx = kmalloc(sizeof(*ctx), M_IPFW, M_WAITOK | M_ZERO);
4368 ipfw_ctx[mycpuid] = ctx;
4370 def_rule = kmalloc(sizeof(*def_rule), M_IPFW, M_WAITOK | M_ZERO);
4372 def_rule->act_ofs = 0;
4373 def_rule->rulenum = IPFW_DEFAULT_RULE;
4374 def_rule->cmd_len = 1;
4375 def_rule->set = IPFW_DEFAULT_SET;
4377 def_rule->cmd[0].len = 1;
4378 #ifdef IPFIREWALL_DEFAULT_TO_ACCEPT
4379 def_rule->cmd[0].opcode = O_ACCEPT;
4381 def_rule->cmd[0].opcode = O_DENY;
4384 def_rule->refcnt = 1;
4385 def_rule->cpuid = mycpuid;
4387 /* Install the default rule */
4388 ctx->ipfw_default_rule = def_rule;
4389 ctx->ipfw_layer3_chain = def_rule;
4391 /* Link rule CPU sibling */
4392 ipfw_link_sibling(fwmsg, def_rule);
4394 /* Statistics only need to be updated once */
4396 ipfw_inc_static_count(def_rule);
4398 ifnet_forwardmsg(&nmsg->lmsg, mycpuid + 1);
4402 ipfw_init_dispatch(netmsg_t nmsg)
4404 struct netmsg_ipfw fwmsg;
4408 kprintf("IP firewall already loaded\n");
4413 bzero(&fwmsg, sizeof(fwmsg));
4414 netmsg_init(&fwmsg.base, NULL, &curthread->td_msgport,
4415 0, ipfw_ctx_init_dispatch);
4416 ifnet_domsg(&fwmsg.base.lmsg, 0);
4418 ip_fw_chk_ptr = ipfw_chk;
4419 ip_fw_ctl_ptr = ipfw_ctl;
4420 ip_fw_dn_io_ptr = ipfw_dummynet_io;
4422 kprintf("ipfw2 initialized, default to %s, logging ",
4423 ipfw_ctx[mycpuid]->ipfw_default_rule->cmd[0].opcode ==
4424 O_ACCEPT ? "accept" : "deny");
4426 #ifdef IPFIREWALL_VERBOSE
4429 #ifdef IPFIREWALL_VERBOSE_LIMIT
4430 verbose_limit = IPFIREWALL_VERBOSE_LIMIT;
4432 if (fw_verbose == 0) {
4433 kprintf("disabled\n");
4434 } else if (verbose_limit == 0) {
4435 kprintf("unlimited\n");
4437 kprintf("limited to %d packets/entry by default\n",
4441 callout_init_mp(&ipfw_timeout_h);
4442 netmsg_init(&ipfw_timeout_netmsg, NULL, &netisr_adone_rport,
4443 MSGF_DROPABLE | MSGF_PRIORITY,
4444 ipfw_tick_dispatch);
4445 lockinit(&dyn_lock, "ipfw_dyn", 0, 0);
4448 callout_reset(&ipfw_timeout_h, hz, ipfw_tick, NULL);
4453 lwkt_replymsg(&nmsg->lmsg, error);
4459 struct netmsg_base smsg;
4461 netmsg_init(&smsg, NULL, &curthread->td_msgport,
4462 0, ipfw_init_dispatch);
4463 return lwkt_domsg(IPFW_CFGPORT, &smsg.lmsg, 0);
4469 ipfw_fini_dispatch(netmsg_t nmsg)
4473 if (ipfw_refcnt != 0) {
4481 callout_stop(&ipfw_timeout_h);
4483 netmsg_service_sync();
4486 lwkt_dropmsg(&ipfw_timeout_netmsg.lmsg);
4489 ip_fw_chk_ptr = NULL;
4490 ip_fw_ctl_ptr = NULL;
4491 ip_fw_dn_io_ptr = NULL;
4492 ipfw_flush(1 /* kill default rule */);
4494 /* Free pre-cpu context */
4495 for (cpu = 0; cpu < ncpus; ++cpu)
4496 kfree(ipfw_ctx[cpu], M_IPFW);
4498 kprintf("IP firewall unloaded\n");
4500 lwkt_replymsg(&nmsg->lmsg, error);
4506 struct netmsg_base smsg;
4508 netmsg_init(&smsg, NULL, &curthread->td_msgport,
4509 0, ipfw_fini_dispatch);
4510 return lwkt_domsg(IPFW_CFGPORT, &smsg.lmsg, 0);
4513 #endif /* KLD_MODULE */
4516 ipfw_modevent(module_t mod, int type, void *unused)
4527 kprintf("ipfw statically compiled, cannot unload\n");
4539 static moduledata_t ipfwmod = {
4544 DECLARE_MODULE(ipfw, ipfwmod, SI_SUB_PROTO_END, SI_ORDER_ANY);
4545 MODULE_VERSION(ipfw, 1);