kernel: Don't include <sys/mutex.h> in some drivers that don't need it.
[dragonfly.git] / sys / net / ipfw / ip_fw2.c
blob6cf6e3130207fd9dbf459dd11fddbf3abc32a4be
1 /*
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
6 * are met:
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
23 * SUCH DAMAGE.
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)
32 #include "opt_ipfw.h"
33 #include "opt_inet.h"
34 #ifndef INET
35 #error IPFIREWALL requires INET.
36 #endif /* INET */
38 #include <sys/param.h>
39 #include <sys/systm.h>
40 #include <sys/malloc.h>
41 #include <sys/mbuf.h>
42 #include <sys/kernel.h>
43 #include <sys/proc.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>
50 #include <sys/lock.h>
52 #include <net/if.h>
53 #include <net/route.h>
54 #include <net/pfil.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, ...) \
81 do { \
82 if (fw_debug > 0) \
83 kprintf(fmt, __VA_ARGS__); \
84 } while (0)
85 #else
86 #define DPRINTF(fmt, ...) ((void)0)
87 #endif
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]:
98 * CPU0 CPU1
100 * netisr0 <------------------------------------+
101 * domsg |
102 * : |
103 * :(delete/add...) |
104 * : |
105 * : netmsg | netmsg
106 * forwardmsg---------->netisr1 |
107 * : |
108 * :(delete/add...) |
109 * : |
110 * : |
111 * replymsg--------------+
115 * Rules which will not create states (dyn rules) [2 CPU case]
117 * CPU0 CPU1
119 * layer3_chain layer3_chain
120 * | |
121 * V V
122 * +-------+ sibling +-------+ sibling
123 * | rule1 |--------->| rule1 |--------->NULL
124 * +-------+ +-------+
125 * | |
126 * |next |next
127 * V V
128 * +-------+ sibling +-------+ sibling
129 * | rule2 |--------->| rule2 |--------->NULL
130 * +-------+ +-------+
132 * ip_fw.sibling:
133 * 1) Ease statistics calculation during IP_FW_GET. We only need to
134 * iterate layer3_chain in netisr0; the current rule's duplication
135 * to the other CPUs could safely be read-only accessed through
136 * ip_fw.sibling.
137 * 2) Accelerate rule insertion and deletion, e.g. rule insertion:
138 * a) In netisr0 rule3 is determined to be inserted between rule1
139 * and rule2. To make this decision we need to iterate the
140 * layer3_chain in netisr0. The netmsg, which is used to insert
141 * the rule, will contain rule1 in netisr0 as prev_rule and rule2
142 * in netisr0 as next_rule.
143 * b) After the insertion in netisr0 is done, we will move on to
144 * netisr1. But instead of relocating the rule3's position in
145 * netisr1 by iterating the layer3_chain in netisr1, we set the
146 * netmsg's prev_rule to rule1->sibling and next_rule to
147 * rule2->sibling before the netmsg is forwarded to netisr1 from
148 * netisr0.
152 * Rules which will create states (dyn rules) [2 CPU case]
153 * (unnecessary parts are omitted; they are same as in the previous figure)
155 * CPU0 CPU1
157 * +-------+ +-------+
158 * | rule1 | | rule1 |
159 * +-------+ +-------+
160 * ^ | | ^
161 * | |stub stub| |
162 * | | | |
163 * | +----+ +----+ |
164 * | | | |
165 * | V V |
166 * | +--------------------+ |
167 * | | rule_stub | |
168 * | | (read-only shared) | |
169 * | | | |
170 * | | back pointer array | |
171 * | | (indexed by cpuid) | |
172 * | | | |
173 * +----|---------[0] | |
174 * | [1]--------|----+
175 * | |
176 * +--------------------+
177 * ^ ^
178 * | |
179 * ........|............|............
180 * : | | :
181 * : |stub |stub :
182 * : | | :
183 * : +---------+ +---------+ :
184 * : | state1a | | state1b | .... :
185 * : +---------+ +---------+ :
186 * : :
187 * : states table :
188 * : (shared) :
189 * : (protected by dyn_lock) :
190 * ..................................
192 * [state1a and state1b are states created by rule1]
194 * ip_fw_stub:
195 * This structure is introduced so that shared (locked) state table could
196 * work with per-CPU (duplicated) static rules. It mainly bridges states
197 * and static rules and serves as static rule's place holder (a read-only
198 * shared part of duplicated rules) from states point of view.
200 * IPFW_RULE_F_STATE (only for rules which create states):
201 * o During rule installation, this flag is turned on after rule's
202 * duplications reach all CPUs, to avoid at least following race:
203 * 1) rule1 is duplicated on CPU0 and is not duplicated on CPU1 yet
204 * 2) rule1 creates state1
205 * 3) state1 is located on CPU1 by check-state
206 * But rule1 is not duplicated on CPU1 yet
207 * o During rule deletion, this flag is turned off before deleting states
208 * created by the rule and before deleting the rule itself, so no
209 * more states will be created by the to-be-deleted rule even when its
210 * duplication on certain CPUs are not eliminated yet.
213 #define IPFW_AUTOINC_STEP_MIN 1
214 #define IPFW_AUTOINC_STEP_MAX 1000
215 #define IPFW_AUTOINC_STEP_DEF 100
217 #define IPFW_DEFAULT_RULE 65535 /* rulenum for the default rule */
218 #define IPFW_DEFAULT_SET 31 /* set number for the default rule */
220 struct netmsg_ipfw {
221 struct netmsg_base base;
222 const struct ipfw_ioc_rule *ioc_rule;
223 struct ip_fw *next_rule;
224 struct ip_fw *prev_rule;
225 struct ip_fw *sibling;
226 struct ip_fw_stub *stub;
229 struct netmsg_del {
230 struct netmsg_base base;
231 struct ip_fw *start_rule;
232 struct ip_fw *prev_rule;
233 uint16_t rulenum;
234 uint8_t from_set;
235 uint8_t to_set;
238 struct netmsg_zent {
239 struct netmsg_base base;
240 struct ip_fw *start_rule;
241 uint16_t rulenum;
242 uint16_t log_only;
245 struct ipfw_context {
246 struct ip_fw *ipfw_layer3_chain; /* list of rules for layer3 */
247 struct ip_fw *ipfw_default_rule; /* default rule */
248 uint64_t ipfw_norule_counter; /* counter for ipfw_log(NULL) */
251 * ipfw_set_disable contains one bit per set value (0..31).
252 * If the bit is set, all rules with the corresponding set
253 * are disabled. Set IPDW_DEFAULT_SET is reserved for the
254 * default rule and CANNOT be disabled.
256 uint32_t ipfw_set_disable;
257 uint32_t ipfw_gen; /* generation of rule list */
260 static struct ipfw_context *ipfw_ctx[MAXCPU];
262 #ifdef KLD_MODULE
264 * Module can not be unloaded, if there are references to
265 * certains rules of ipfw(4), e.g. dummynet(4)
267 static int ipfw_refcnt;
268 #endif
270 MALLOC_DEFINE(M_IPFW, "IpFw/IpAcct", "IpFw/IpAcct chain's");
273 * Following two global variables are accessed and updated only
274 * in netisr0.
276 static uint32_t static_count; /* # of static rules */
277 static uint32_t static_ioc_len; /* bytes of static rules */
280 * If 1, then ipfw static rules are being flushed,
281 * ipfw_chk() will skip to the default rule.
283 static int ipfw_flushing;
285 static int fw_verbose;
286 static int verbose_limit;
288 static int fw_debug;
289 static int autoinc_step = IPFW_AUTOINC_STEP_DEF;
291 static int ipfw_sysctl_enable(SYSCTL_HANDLER_ARGS);
292 static int ipfw_sysctl_autoinc_step(SYSCTL_HANDLER_ARGS);
293 static int ipfw_sysctl_dyn_buckets(SYSCTL_HANDLER_ARGS);
294 static int ipfw_sysctl_dyn_fin(SYSCTL_HANDLER_ARGS);
295 static int ipfw_sysctl_dyn_rst(SYSCTL_HANDLER_ARGS);
297 SYSCTL_NODE(_net_inet_ip, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall");
298 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, enable, CTLTYPE_INT | CTLFLAG_RW,
299 &fw_enable, 0, ipfw_sysctl_enable, "I", "Enable ipfw");
300 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, autoinc_step, CTLTYPE_INT | CTLFLAG_RW,
301 &autoinc_step, 0, ipfw_sysctl_autoinc_step, "I",
302 "Rule number autincrement step");
303 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO,one_pass,CTLFLAG_RW,
304 &fw_one_pass, 0,
305 "Only do a single pass through ipfw when using dummynet(4)");
306 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, debug, CTLFLAG_RW,
307 &fw_debug, 0, "Enable printing of debug ip_fw statements");
308 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose, CTLFLAG_RW,
309 &fw_verbose, 0, "Log matches to ipfw rules");
310 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose_limit, CTLFLAG_RW,
311 &verbose_limit, 0, "Set upper limit of matches of ipfw rules logged");
314 * Description of dynamic rules.
316 * Dynamic rules are stored in lists accessed through a hash table
317 * (ipfw_dyn_v) whose size is curr_dyn_buckets. This value can
318 * be modified through the sysctl variable dyn_buckets which is
319 * updated when the table becomes empty.
321 * XXX currently there is only one list, ipfw_dyn.
323 * When a packet is received, its address fields are first masked
324 * with the mask defined for the rule, then hashed, then matched
325 * against the entries in the corresponding list.
326 * Dynamic rules can be used for different purposes:
327 * + stateful rules;
328 * + enforcing limits on the number of sessions;
329 * + in-kernel NAT (not implemented yet)
331 * The lifetime of dynamic rules is regulated by dyn_*_lifetime,
332 * measured in seconds and depending on the flags.
334 * The total number of dynamic rules is stored in dyn_count.
335 * The max number of dynamic rules is dyn_max. When we reach
336 * the maximum number of rules we do not create anymore. This is
337 * done to avoid consuming too much memory, but also too much
338 * time when searching on each packet (ideally, we should try instead
339 * to put a limit on the length of the list on each bucket...).
341 * Each dynamic rule holds a pointer to the parent ipfw rule so
342 * we know what action to perform. Dynamic rules are removed when
343 * the parent rule is deleted. XXX we should make them survive.
345 * There are some limitations with dynamic rules -- we do not
346 * obey the 'randomized match', and we do not do multiple
347 * passes through the firewall. XXX check the latter!!!
349 * NOTE about the SHARED LOCKMGR LOCK during dynamic rule looking up:
350 * Only TCP state transition will change dynamic rule's state and ack
351 * sequences, while all packets of one TCP connection only goes through
352 * one TCP thread, so it is safe to use shared lockmgr lock during dynamic
353 * rule looking up. The keep alive callout uses exclusive lockmgr lock
354 * when it tries to find suitable dynamic rules to send keep alive, so
355 * it will not see half updated state and ack sequences. Though the expire
356 * field updating looks racy for other protocols, the resolution (second)
357 * of expire field makes this kind of race harmless.
358 * XXX statistics' updating is _not_ MPsafe!!!
359 * XXX once UDP output path is fixed, we could use lockless dynamic rule
360 * hash table
362 static ipfw_dyn_rule **ipfw_dyn_v = NULL;
363 static uint32_t dyn_buckets = 256; /* must be power of 2 */
364 static uint32_t curr_dyn_buckets = 256; /* must be power of 2 */
365 static uint32_t dyn_buckets_gen; /* generation of dyn buckets array */
366 static struct lock dyn_lock; /* dynamic rules' hash table lock */
368 static struct netmsg_base ipfw_timeout_netmsg; /* schedule ipfw timeout */
369 static struct callout ipfw_timeout_h;
372 * Timeouts for various events in handing dynamic rules.
374 static uint32_t dyn_ack_lifetime = 300;
375 static uint32_t dyn_syn_lifetime = 20;
376 static uint32_t dyn_fin_lifetime = 1;
377 static uint32_t dyn_rst_lifetime = 1;
378 static uint32_t dyn_udp_lifetime = 10;
379 static uint32_t dyn_short_lifetime = 5;
382 * Keepalives are sent if dyn_keepalive is set. They are sent every
383 * dyn_keepalive_period seconds, in the last dyn_keepalive_interval
384 * seconds of lifetime of a rule.
385 * dyn_rst_lifetime and dyn_fin_lifetime should be strictly lower
386 * than dyn_keepalive_period.
389 static uint32_t dyn_keepalive_interval = 20;
390 static uint32_t dyn_keepalive_period = 5;
391 static uint32_t dyn_keepalive = 1; /* do send keepalives */
393 static uint32_t dyn_count; /* # of dynamic rules */
394 static uint32_t dyn_max = 4096; /* max # of dynamic rules */
396 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, dyn_buckets, CTLTYPE_INT | CTLFLAG_RW,
397 &dyn_buckets, 0, ipfw_sysctl_dyn_buckets, "I", "Number of dyn. buckets");
398 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, curr_dyn_buckets, CTLFLAG_RD,
399 &curr_dyn_buckets, 0, "Current Number of dyn. buckets");
400 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_count, CTLFLAG_RD,
401 &dyn_count, 0, "Number of dyn. rules");
402 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_max, CTLFLAG_RW,
403 &dyn_max, 0, "Max number of dyn. rules");
404 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, static_count, CTLFLAG_RD,
405 &static_count, 0, "Number of static rules");
406 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_ack_lifetime, CTLFLAG_RW,
407 &dyn_ack_lifetime, 0, "Lifetime of dyn. rules for acks");
408 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_syn_lifetime, CTLFLAG_RW,
409 &dyn_syn_lifetime, 0, "Lifetime of dyn. rules for syn");
410 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, dyn_fin_lifetime,
411 CTLTYPE_INT | CTLFLAG_RW, &dyn_fin_lifetime, 0, ipfw_sysctl_dyn_fin, "I",
412 "Lifetime of dyn. rules for fin");
413 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, dyn_rst_lifetime,
414 CTLTYPE_INT | CTLFLAG_RW, &dyn_rst_lifetime, 0, ipfw_sysctl_dyn_rst, "I",
415 "Lifetime of dyn. rules for rst");
416 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_udp_lifetime, CTLFLAG_RW,
417 &dyn_udp_lifetime, 0, "Lifetime of dyn. rules for UDP");
418 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_short_lifetime, CTLFLAG_RW,
419 &dyn_short_lifetime, 0, "Lifetime of dyn. rules for other situations");
420 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_keepalive, CTLFLAG_RW,
421 &dyn_keepalive, 0, "Enable keepalives for dyn. rules");
423 static ip_fw_chk_t ipfw_chk;
424 static void ipfw_tick(void *);
426 static __inline int
427 ipfw_free_rule(struct ip_fw *rule)
429 KASSERT(rule->cpuid == mycpuid, ("rule freed on cpu%d", mycpuid));
430 KASSERT(rule->refcnt > 0, ("invalid refcnt %u", rule->refcnt));
431 rule->refcnt--;
432 if (rule->refcnt == 0) {
433 kfree(rule, M_IPFW);
434 return 1;
436 return 0;
439 static void
440 ipfw_unref_rule(void *priv)
442 ipfw_free_rule(priv);
443 #ifdef KLD_MODULE
444 atomic_subtract_int(&ipfw_refcnt, 1);
445 #endif
448 static __inline void
449 ipfw_ref_rule(struct ip_fw *rule)
451 KASSERT(rule->cpuid == mycpuid, ("rule used on cpu%d", mycpuid));
452 #ifdef KLD_MODULE
453 atomic_add_int(&ipfw_refcnt, 1);
454 #endif
455 rule->refcnt++;
459 * This macro maps an ip pointer into a layer3 header pointer of type T
461 #define L3HDR(T, ip) ((T *)((uint32_t *)(ip) + (ip)->ip_hl))
463 static __inline int
464 icmptype_match(struct ip *ip, ipfw_insn_u32 *cmd)
466 int type = L3HDR(struct icmp,ip)->icmp_type;
468 return (type <= ICMP_MAXTYPE && (cmd->d[0] & (1 << type)));
471 #define TT ((1 << ICMP_ECHO) | \
472 (1 << ICMP_ROUTERSOLICIT) | \
473 (1 << ICMP_TSTAMP) | \
474 (1 << ICMP_IREQ) | \
475 (1 << ICMP_MASKREQ))
477 static int
478 is_icmp_query(struct ip *ip)
480 int type = L3HDR(struct icmp, ip)->icmp_type;
482 return (type <= ICMP_MAXTYPE && (TT & (1 << type)));
485 #undef TT
488 * The following checks use two arrays of 8 or 16 bits to store the
489 * bits that we want set or clear, respectively. They are in the
490 * low and high half of cmd->arg1 or cmd->d[0].
492 * We scan options and store the bits we find set. We succeed if
494 * (want_set & ~bits) == 0 && (want_clear & ~bits) == want_clear
496 * The code is sometimes optimized not to store additional variables.
498 static int
499 flags_match(ipfw_insn *cmd, uint8_t bits)
501 u_char want_clear;
502 bits = ~bits;
504 if (((cmd->arg1 & 0xff) & bits) != 0)
505 return 0; /* some bits we want set were clear */
507 want_clear = (cmd->arg1 >> 8) & 0xff;
508 if ((want_clear & bits) != want_clear)
509 return 0; /* some bits we want clear were set */
510 return 1;
513 static int
514 ipopts_match(struct ip *ip, ipfw_insn *cmd)
516 int optlen, bits = 0;
517 u_char *cp = (u_char *)(ip + 1);
518 int x = (ip->ip_hl << 2) - sizeof(struct ip);
520 for (; x > 0; x -= optlen, cp += optlen) {
521 int opt = cp[IPOPT_OPTVAL];
523 if (opt == IPOPT_EOL)
524 break;
526 if (opt == IPOPT_NOP) {
527 optlen = 1;
528 } else {
529 optlen = cp[IPOPT_OLEN];
530 if (optlen <= 0 || optlen > x)
531 return 0; /* invalid or truncated */
534 switch (opt) {
535 case IPOPT_LSRR:
536 bits |= IP_FW_IPOPT_LSRR;
537 break;
539 case IPOPT_SSRR:
540 bits |= IP_FW_IPOPT_SSRR;
541 break;
543 case IPOPT_RR:
544 bits |= IP_FW_IPOPT_RR;
545 break;
547 case IPOPT_TS:
548 bits |= IP_FW_IPOPT_TS;
549 break;
551 default:
552 break;
555 return (flags_match(cmd, bits));
558 static int
559 tcpopts_match(struct ip *ip, ipfw_insn *cmd)
561 int optlen, bits = 0;
562 struct tcphdr *tcp = L3HDR(struct tcphdr,ip);
563 u_char *cp = (u_char *)(tcp + 1);
564 int x = (tcp->th_off << 2) - sizeof(struct tcphdr);
566 for (; x > 0; x -= optlen, cp += optlen) {
567 int opt = cp[0];
569 if (opt == TCPOPT_EOL)
570 break;
572 if (opt == TCPOPT_NOP) {
573 optlen = 1;
574 } else {
575 optlen = cp[1];
576 if (optlen <= 0)
577 break;
580 switch (opt) {
581 case TCPOPT_MAXSEG:
582 bits |= IP_FW_TCPOPT_MSS;
583 break;
585 case TCPOPT_WINDOW:
586 bits |= IP_FW_TCPOPT_WINDOW;
587 break;
589 case TCPOPT_SACK_PERMITTED:
590 case TCPOPT_SACK:
591 bits |= IP_FW_TCPOPT_SACK;
592 break;
594 case TCPOPT_TIMESTAMP:
595 bits |= IP_FW_TCPOPT_TS;
596 break;
598 case TCPOPT_CC:
599 case TCPOPT_CCNEW:
600 case TCPOPT_CCECHO:
601 bits |= IP_FW_TCPOPT_CC;
602 break;
604 default:
605 break;
608 return (flags_match(cmd, bits));
611 static int
612 iface_match(struct ifnet *ifp, ipfw_insn_if *cmd)
614 if (ifp == NULL) /* no iface with this packet, match fails */
615 return 0;
617 /* Check by name or by IP address */
618 if (cmd->name[0] != '\0') { /* match by name */
619 /* Check name */
620 if (cmd->p.glob) {
621 if (kfnmatch(cmd->name, ifp->if_xname, 0) == 0)
622 return(1);
623 } else {
624 if (strncmp(ifp->if_xname, cmd->name, IFNAMSIZ) == 0)
625 return(1);
627 } else {
628 struct ifaddr_container *ifac;
630 TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
631 struct ifaddr *ia = ifac->ifa;
633 if (ia->ifa_addr == NULL)
634 continue;
635 if (ia->ifa_addr->sa_family != AF_INET)
636 continue;
637 if (cmd->p.ip.s_addr == ((struct sockaddr_in *)
638 (ia->ifa_addr))->sin_addr.s_addr)
639 return(1); /* match */
642 return(0); /* no match, fail ... */
645 #define SNPARGS(buf, len) buf + len, sizeof(buf) > len ? sizeof(buf) - len : 0
648 * We enter here when we have a rule with O_LOG.
649 * XXX this function alone takes about 2Kbytes of code!
651 static void
652 ipfw_log(struct ip_fw *f, u_int hlen, struct ether_header *eh,
653 struct mbuf *m, struct ifnet *oif)
655 char *action;
656 int limit_reached = 0;
657 char action2[40], proto[48], fragment[28], abuf[INET_ADDRSTRLEN];
659 fragment[0] = '\0';
660 proto[0] = '\0';
662 if (f == NULL) { /* bogus pkt */
663 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
665 if (verbose_limit != 0 &&
666 ctx->ipfw_norule_counter >= verbose_limit)
667 return;
668 ctx->ipfw_norule_counter++;
669 if (ctx->ipfw_norule_counter == verbose_limit)
670 limit_reached = verbose_limit;
671 action = "Refuse";
672 } else { /* O_LOG is the first action, find the real one */
673 ipfw_insn *cmd = ACTION_PTR(f);
674 ipfw_insn_log *l = (ipfw_insn_log *)cmd;
676 if (l->max_log != 0 && l->log_left == 0)
677 return;
678 l->log_left--;
679 if (l->log_left == 0)
680 limit_reached = l->max_log;
681 cmd += F_LEN(cmd); /* point to first action */
682 if (cmd->opcode == O_PROB)
683 cmd += F_LEN(cmd);
685 action = action2;
686 switch (cmd->opcode) {
687 case O_DENY:
688 action = "Deny";
689 break;
691 case O_REJECT:
692 if (cmd->arg1==ICMP_REJECT_RST) {
693 action = "Reset";
694 } else if (cmd->arg1==ICMP_UNREACH_HOST) {
695 action = "Reject";
696 } else {
697 ksnprintf(SNPARGS(action2, 0), "Unreach %d",
698 cmd->arg1);
700 break;
702 case O_ACCEPT:
703 action = "Accept";
704 break;
706 case O_COUNT:
707 action = "Count";
708 break;
710 case O_DIVERT:
711 ksnprintf(SNPARGS(action2, 0), "Divert %d", cmd->arg1);
712 break;
714 case O_TEE:
715 ksnprintf(SNPARGS(action2, 0), "Tee %d", cmd->arg1);
716 break;
718 case O_SKIPTO:
719 ksnprintf(SNPARGS(action2, 0), "SkipTo %d", cmd->arg1);
720 break;
722 case O_PIPE:
723 ksnprintf(SNPARGS(action2, 0), "Pipe %d", cmd->arg1);
724 break;
726 case O_QUEUE:
727 ksnprintf(SNPARGS(action2, 0), "Queue %d", cmd->arg1);
728 break;
730 case O_FORWARD_IP:
732 ipfw_insn_sa *sa = (ipfw_insn_sa *)cmd;
733 int len;
735 len = ksnprintf(SNPARGS(action2, 0),
736 "Forward to %s",
737 kinet_ntoa(sa->sa.sin_addr, abuf));
738 if (sa->sa.sin_port) {
739 ksnprintf(SNPARGS(action2, len), ":%d",
740 sa->sa.sin_port);
743 break;
745 default:
746 action = "UNKNOWN";
747 break;
751 if (hlen == 0) { /* non-ip */
752 ksnprintf(SNPARGS(proto, 0), "MAC");
753 } else {
754 struct ip *ip = mtod(m, struct ip *);
755 /* these three are all aliases to the same thing */
756 struct icmp *const icmp = L3HDR(struct icmp, ip);
757 struct tcphdr *const tcp = (struct tcphdr *)icmp;
758 struct udphdr *const udp = (struct udphdr *)icmp;
760 int ip_off, offset, ip_len;
761 int len;
763 if (eh != NULL) { /* layer 2 packets are as on the wire */
764 ip_off = ntohs(ip->ip_off);
765 ip_len = ntohs(ip->ip_len);
766 } else {
767 ip_off = ip->ip_off;
768 ip_len = ip->ip_len;
770 offset = ip_off & IP_OFFMASK;
771 switch (ip->ip_p) {
772 case IPPROTO_TCP:
773 len = ksnprintf(SNPARGS(proto, 0), "TCP %s",
774 kinet_ntoa(ip->ip_src, abuf));
775 if (offset == 0) {
776 ksnprintf(SNPARGS(proto, len), ":%d %s:%d",
777 ntohs(tcp->th_sport),
778 kinet_ntoa(ip->ip_dst, abuf),
779 ntohs(tcp->th_dport));
780 } else {
781 ksnprintf(SNPARGS(proto, len), " %s",
782 kinet_ntoa(ip->ip_dst, abuf));
784 break;
786 case IPPROTO_UDP:
787 len = ksnprintf(SNPARGS(proto, 0), "UDP %s",
788 kinet_ntoa(ip->ip_src, abuf));
789 if (offset == 0) {
790 ksnprintf(SNPARGS(proto, len), ":%d %s:%d",
791 ntohs(udp->uh_sport),
792 kinet_ntoa(ip->ip_dst, abuf),
793 ntohs(udp->uh_dport));
794 } else {
795 ksnprintf(SNPARGS(proto, len), " %s",
796 kinet_ntoa(ip->ip_dst, abuf));
798 break;
800 case IPPROTO_ICMP:
801 if (offset == 0) {
802 len = ksnprintf(SNPARGS(proto, 0),
803 "ICMP:%u.%u ",
804 icmp->icmp_type,
805 icmp->icmp_code);
806 } else {
807 len = ksnprintf(SNPARGS(proto, 0), "ICMP ");
809 len += ksnprintf(SNPARGS(proto, len), "%s",
810 kinet_ntoa(ip->ip_src, abuf));
811 ksnprintf(SNPARGS(proto, len), " %s",
812 kinet_ntoa(ip->ip_dst, abuf));
813 break;
815 default:
816 len = ksnprintf(SNPARGS(proto, 0), "P:%d %s", ip->ip_p,
817 kinet_ntoa(ip->ip_src, abuf));
818 ksnprintf(SNPARGS(proto, len), " %s",
819 kinet_ntoa(ip->ip_dst, abuf));
820 break;
823 if (ip_off & (IP_MF | IP_OFFMASK)) {
824 ksnprintf(SNPARGS(fragment, 0), " (frag %d:%d@%d%s)",
825 ntohs(ip->ip_id), ip_len - (ip->ip_hl << 2),
826 offset << 3, (ip_off & IP_MF) ? "+" : "");
830 if (oif || m->m_pkthdr.rcvif) {
831 log(LOG_SECURITY | LOG_INFO,
832 "ipfw: %d %s %s %s via %s%s\n",
833 f ? f->rulenum : -1,
834 action, proto, oif ? "out" : "in",
835 oif ? oif->if_xname : m->m_pkthdr.rcvif->if_xname,
836 fragment);
837 } else {
838 log(LOG_SECURITY | LOG_INFO,
839 "ipfw: %d %s %s [no if info]%s\n",
840 f ? f->rulenum : -1,
841 action, proto, fragment);
844 if (limit_reached) {
845 log(LOG_SECURITY | LOG_NOTICE,
846 "ipfw: limit %d reached on entry %d\n",
847 limit_reached, f ? f->rulenum : -1);
851 #undef SNPARGS
854 * IMPORTANT: the hash function for dynamic rules must be commutative
855 * in source and destination (ip,port), because rules are bidirectional
856 * and we want to find both in the same bucket.
858 static __inline int
859 hash_packet(struct ipfw_flow_id *id)
861 uint32_t i;
863 i = (id->dst_ip) ^ (id->src_ip) ^ (id->dst_port) ^ (id->src_port);
864 i &= (curr_dyn_buckets - 1);
865 return i;
869 * Unlink a dynamic rule from a chain. prev is a pointer to
870 * the previous one, q is a pointer to the rule to delete,
871 * head is a pointer to the head of the queue.
872 * Modifies q and potentially also head.
874 #define UNLINK_DYN_RULE(prev, head, q) \
875 do { \
876 ipfw_dyn_rule *old_q = q; \
878 /* remove a refcount to the parent */ \
879 if (q->dyn_type == O_LIMIT) \
880 q->parent->count--; \
881 DPRINTF("-- unlink entry 0x%08x %d -> 0x%08x %d, %d left\n", \
882 q->id.src_ip, q->id.src_port, \
883 q->id.dst_ip, q->id.dst_port, dyn_count - 1); \
884 if (prev != NULL) \
885 prev->next = q = q->next; \
886 else \
887 head = q = q->next; \
888 KASSERT(dyn_count > 0, ("invalid dyn count %u", dyn_count)); \
889 dyn_count--; \
890 kfree(old_q, M_IPFW); \
891 } while (0)
893 #define TIME_LEQ(a, b) ((int)((a) - (b)) <= 0)
896 * Remove dynamic rules pointing to "rule", or all of them if rule == NULL.
898 * If keep_me == NULL, rules are deleted even if not expired,
899 * otherwise only expired rules are removed.
901 * The value of the second parameter is also used to point to identify
902 * a rule we absolutely do not want to remove (e.g. because we are
903 * holding a reference to it -- this is the case with O_LIMIT_PARENT
904 * rules). The pointer is only used for comparison, so any non-null
905 * value will do.
907 static void
908 remove_dyn_rule_locked(struct ip_fw *rule, ipfw_dyn_rule *keep_me)
910 static time_t last_remove = 0; /* XXX */
912 #define FORCE (keep_me == NULL)
914 ipfw_dyn_rule *prev, *q;
915 int i, pass = 0, max_pass = 0, unlinked = 0;
917 if (ipfw_dyn_v == NULL || dyn_count == 0)
918 return;
919 /* do not expire more than once per second, it is useless */
920 if (!FORCE && last_remove == time_uptime)
921 return;
922 last_remove = time_uptime;
925 * because O_LIMIT refer to parent rules, during the first pass only
926 * remove child and mark any pending LIMIT_PARENT, and remove
927 * them in a second pass.
929 next_pass:
930 for (i = 0; i < curr_dyn_buckets; i++) {
931 for (prev = NULL, q = ipfw_dyn_v[i]; q;) {
933 * Logic can become complex here, so we split tests.
935 if (q == keep_me)
936 goto next;
937 if (rule != NULL && rule->stub != q->stub)
938 goto next; /* not the one we are looking for */
939 if (q->dyn_type == O_LIMIT_PARENT) {
941 * handle parent in the second pass,
942 * record we need one.
944 max_pass = 1;
945 if (pass == 0)
946 goto next;
947 if (FORCE && q->count != 0) {
948 /* XXX should not happen! */
949 kprintf("OUCH! cannot remove rule, "
950 "count %d\n", q->count);
952 } else {
953 if (!FORCE && !TIME_LEQ(q->expire, time_second))
954 goto next;
956 unlinked = 1;
957 UNLINK_DYN_RULE(prev, ipfw_dyn_v[i], q);
958 continue;
959 next:
960 prev = q;
961 q = q->next;
964 if (pass++ < max_pass)
965 goto next_pass;
967 if (unlinked)
968 ++dyn_buckets_gen;
970 #undef FORCE
974 * Lookup a dynamic rule.
976 static ipfw_dyn_rule *
977 lookup_dyn_rule(struct ipfw_flow_id *pkt, int *match_direction,
978 struct tcphdr *tcp)
981 * stateful ipfw extensions.
982 * Lookup into dynamic session queue
984 #define MATCH_REVERSE 0
985 #define MATCH_FORWARD 1
986 #define MATCH_NONE 2
987 #define MATCH_UNKNOWN 3
988 int i, dir = MATCH_NONE;
989 ipfw_dyn_rule *q=NULL;
991 if (ipfw_dyn_v == NULL)
992 goto done; /* not found */
994 i = hash_packet(pkt);
995 for (q = ipfw_dyn_v[i]; q != NULL;) {
996 if (q->dyn_type == O_LIMIT_PARENT)
997 goto next;
999 if (TIME_LEQ(q->expire, time_second)) {
1001 * Entry expired; skip.
1002 * Let ipfw_tick() take care of it
1004 goto next;
1007 if (pkt->proto == q->id.proto) {
1008 if (pkt->src_ip == q->id.src_ip &&
1009 pkt->dst_ip == q->id.dst_ip &&
1010 pkt->src_port == q->id.src_port &&
1011 pkt->dst_port == q->id.dst_port) {
1012 dir = MATCH_FORWARD;
1013 break;
1015 if (pkt->src_ip == q->id.dst_ip &&
1016 pkt->dst_ip == q->id.src_ip &&
1017 pkt->src_port == q->id.dst_port &&
1018 pkt->dst_port == q->id.src_port) {
1019 dir = MATCH_REVERSE;
1020 break;
1023 next:
1024 q = q->next;
1026 if (q == NULL)
1027 goto done; /* q = NULL, not found */
1029 if (pkt->proto == IPPROTO_TCP) { /* update state according to flags */
1030 u_char flags = pkt->flags & (TH_FIN|TH_SYN|TH_RST);
1032 #define BOTH_SYN (TH_SYN | (TH_SYN << 8))
1033 #define BOTH_FIN (TH_FIN | (TH_FIN << 8))
1035 q->state |= (dir == MATCH_FORWARD ) ? flags : (flags << 8);
1036 switch (q->state) {
1037 case TH_SYN: /* opening */
1038 q->expire = time_second + dyn_syn_lifetime;
1039 break;
1041 case BOTH_SYN: /* move to established */
1042 case BOTH_SYN | TH_FIN : /* one side tries to close */
1043 case BOTH_SYN | (TH_FIN << 8) :
1044 if (tcp) {
1045 uint32_t ack = ntohl(tcp->th_ack);
1047 #define _SEQ_GE(a, b) ((int)(a) - (int)(b) >= 0)
1049 if (dir == MATCH_FORWARD) {
1050 if (q->ack_fwd == 0 ||
1051 _SEQ_GE(ack, q->ack_fwd))
1052 q->ack_fwd = ack;
1053 else /* ignore out-of-sequence */
1054 break;
1055 } else {
1056 if (q->ack_rev == 0 ||
1057 _SEQ_GE(ack, q->ack_rev))
1058 q->ack_rev = ack;
1059 else /* ignore out-of-sequence */
1060 break;
1062 #undef _SEQ_GE
1064 q->expire = time_second + dyn_ack_lifetime;
1065 break;
1067 case BOTH_SYN | BOTH_FIN: /* both sides closed */
1068 KKASSERT(dyn_fin_lifetime < dyn_keepalive_period);
1069 q->expire = time_second + dyn_fin_lifetime;
1070 break;
1072 default:
1073 #if 0
1075 * reset or some invalid combination, but can also
1076 * occur if we use keep-state the wrong way.
1078 if ((q->state & ((TH_RST << 8) | TH_RST)) == 0)
1079 kprintf("invalid state: 0x%x\n", q->state);
1080 #endif
1081 KKASSERT(dyn_rst_lifetime < dyn_keepalive_period);
1082 q->expire = time_second + dyn_rst_lifetime;
1083 break;
1085 } else if (pkt->proto == IPPROTO_UDP) {
1086 q->expire = time_second + dyn_udp_lifetime;
1087 } else {
1088 /* other protocols */
1089 q->expire = time_second + dyn_short_lifetime;
1091 done:
1092 if (match_direction)
1093 *match_direction = dir;
1094 return q;
1097 static struct ip_fw *
1098 lookup_rule(struct ipfw_flow_id *pkt, int *match_direction, struct tcphdr *tcp,
1099 uint16_t len, int *deny)
1101 struct ip_fw *rule = NULL;
1102 ipfw_dyn_rule *q;
1103 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
1104 uint32_t gen;
1106 *deny = 0;
1107 gen = ctx->ipfw_gen;
1109 lockmgr(&dyn_lock, LK_SHARED);
1111 if (ctx->ipfw_gen != gen) {
1113 * Static rules had been change when we were waiting
1114 * for the dynamic hash table lock; deny this packet,
1115 * since it is _not_ known whether it is safe to keep
1116 * iterating the static rules.
1118 *deny = 1;
1119 goto back;
1122 q = lookup_dyn_rule(pkt, match_direction, tcp);
1123 if (q == NULL) {
1124 rule = NULL;
1125 } else {
1126 rule = q->stub->rule[mycpuid];
1127 KKASSERT(rule->stub == q->stub && rule->cpuid == mycpuid);
1129 /* XXX */
1130 q->pcnt++;
1131 q->bcnt += len;
1133 back:
1134 lockmgr(&dyn_lock, LK_RELEASE);
1135 return rule;
1138 static void
1139 realloc_dynamic_table(void)
1141 ipfw_dyn_rule **old_dyn_v;
1142 uint32_t old_curr_dyn_buckets;
1144 KASSERT(dyn_buckets <= 65536 && (dyn_buckets & (dyn_buckets - 1)) == 0,
1145 ("invalid dyn_buckets %d", dyn_buckets));
1147 /* Save the current buckets array for later error recovery */
1148 old_dyn_v = ipfw_dyn_v;
1149 old_curr_dyn_buckets = curr_dyn_buckets;
1151 curr_dyn_buckets = dyn_buckets;
1152 for (;;) {
1153 ipfw_dyn_v = kmalloc(curr_dyn_buckets * sizeof(ipfw_dyn_rule *),
1154 M_IPFW, M_NOWAIT | M_ZERO);
1155 if (ipfw_dyn_v != NULL || curr_dyn_buckets <= 2)
1156 break;
1158 curr_dyn_buckets /= 2;
1159 if (curr_dyn_buckets <= old_curr_dyn_buckets &&
1160 old_dyn_v != NULL) {
1162 * Don't try allocating smaller buckets array, reuse
1163 * the old one, which alreay contains enough buckets
1165 break;
1169 if (ipfw_dyn_v != NULL) {
1170 if (old_dyn_v != NULL)
1171 kfree(old_dyn_v, M_IPFW);
1172 } else {
1173 /* Allocation failed, restore old buckets array */
1174 ipfw_dyn_v = old_dyn_v;
1175 curr_dyn_buckets = old_curr_dyn_buckets;
1178 if (ipfw_dyn_v != NULL)
1179 ++dyn_buckets_gen;
1183 * Install state of type 'type' for a dynamic session.
1184 * The hash table contains two type of rules:
1185 * - regular rules (O_KEEP_STATE)
1186 * - rules for sessions with limited number of sess per user
1187 * (O_LIMIT). When they are created, the parent is
1188 * increased by 1, and decreased on delete. In this case,
1189 * the third parameter is the parent rule and not the chain.
1190 * - "parent" rules for the above (O_LIMIT_PARENT).
1192 static ipfw_dyn_rule *
1193 add_dyn_rule(struct ipfw_flow_id *id, uint8_t dyn_type, struct ip_fw *rule)
1195 ipfw_dyn_rule *r;
1196 int i;
1198 if (ipfw_dyn_v == NULL ||
1199 (dyn_count == 0 && dyn_buckets != curr_dyn_buckets)) {
1200 realloc_dynamic_table();
1201 if (ipfw_dyn_v == NULL)
1202 return NULL; /* failed ! */
1204 i = hash_packet(id);
1206 r = kmalloc(sizeof(*r), M_IPFW, M_NOWAIT | M_ZERO);
1207 if (r == NULL)
1208 return NULL;
1210 /* increase refcount on parent, and set pointer */
1211 if (dyn_type == O_LIMIT) {
1212 ipfw_dyn_rule *parent = (ipfw_dyn_rule *)rule;
1214 if (parent->dyn_type != O_LIMIT_PARENT)
1215 panic("invalid parent");
1216 parent->count++;
1217 r->parent = parent;
1218 rule = parent->stub->rule[mycpuid];
1219 KKASSERT(rule->stub == parent->stub);
1221 KKASSERT(rule->cpuid == mycpuid && rule->stub != NULL);
1223 r->id = *id;
1224 r->expire = time_second + dyn_syn_lifetime;
1225 r->stub = rule->stub;
1226 r->dyn_type = dyn_type;
1227 r->pcnt = r->bcnt = 0;
1228 r->count = 0;
1230 r->bucket = i;
1231 r->next = ipfw_dyn_v[i];
1232 ipfw_dyn_v[i] = r;
1233 dyn_count++;
1234 dyn_buckets_gen++;
1235 DPRINTF("-- add dyn entry ty %d 0x%08x %d -> 0x%08x %d, total %d\n",
1236 dyn_type,
1237 r->id.src_ip, r->id.src_port,
1238 r->id.dst_ip, r->id.dst_port, dyn_count);
1239 return r;
1243 * Lookup dynamic parent rule using pkt and rule as search keys.
1244 * If the lookup fails, then install one.
1246 static ipfw_dyn_rule *
1247 lookup_dyn_parent(struct ipfw_flow_id *pkt, struct ip_fw *rule)
1249 ipfw_dyn_rule *q;
1250 int i;
1252 if (ipfw_dyn_v) {
1253 i = hash_packet(pkt);
1254 for (q = ipfw_dyn_v[i]; q != NULL; q = q->next) {
1255 if (q->dyn_type == O_LIMIT_PARENT &&
1256 rule->stub == q->stub &&
1257 pkt->proto == q->id.proto &&
1258 pkt->src_ip == q->id.src_ip &&
1259 pkt->dst_ip == q->id.dst_ip &&
1260 pkt->src_port == q->id.src_port &&
1261 pkt->dst_port == q->id.dst_port) {
1262 q->expire = time_second + dyn_short_lifetime;
1263 DPRINTF("lookup_dyn_parent found 0x%p\n", q);
1264 return q;
1268 return add_dyn_rule(pkt, O_LIMIT_PARENT, rule);
1272 * Install dynamic state for rule type cmd->o.opcode
1274 * Returns 1 (failure) if state is not installed because of errors or because
1275 * session limitations are enforced.
1277 static int
1278 install_state_locked(struct ip_fw *rule, ipfw_insn_limit *cmd,
1279 struct ip_fw_args *args)
1281 static int last_log; /* XXX */
1283 ipfw_dyn_rule *q;
1285 DPRINTF("-- install state type %d 0x%08x %u -> 0x%08x %u\n",
1286 cmd->o.opcode,
1287 args->f_id.src_ip, args->f_id.src_port,
1288 args->f_id.dst_ip, args->f_id.dst_port);
1290 q = lookup_dyn_rule(&args->f_id, NULL, NULL);
1291 if (q != NULL) { /* should never occur */
1292 if (last_log != time_second) {
1293 last_log = time_second;
1294 kprintf(" install_state: entry already present, done\n");
1296 return 0;
1299 if (dyn_count >= dyn_max) {
1301 * Run out of slots, try to remove any expired rule.
1303 remove_dyn_rule_locked(NULL, (ipfw_dyn_rule *)1);
1304 if (dyn_count >= dyn_max) {
1305 if (last_log != time_second) {
1306 last_log = time_second;
1307 kprintf("install_state: "
1308 "Too many dynamic rules\n");
1310 return 1; /* cannot install, notify caller */
1314 switch (cmd->o.opcode) {
1315 case O_KEEP_STATE: /* bidir rule */
1316 if (add_dyn_rule(&args->f_id, O_KEEP_STATE, rule) == NULL)
1317 return 1;
1318 break;
1320 case O_LIMIT: /* limit number of sessions */
1322 uint16_t limit_mask = cmd->limit_mask;
1323 struct ipfw_flow_id id;
1324 ipfw_dyn_rule *parent;
1326 DPRINTF("installing dyn-limit rule %d\n",
1327 cmd->conn_limit);
1329 id.dst_ip = id.src_ip = 0;
1330 id.dst_port = id.src_port = 0;
1331 id.proto = args->f_id.proto;
1333 if (limit_mask & DYN_SRC_ADDR)
1334 id.src_ip = args->f_id.src_ip;
1335 if (limit_mask & DYN_DST_ADDR)
1336 id.dst_ip = args->f_id.dst_ip;
1337 if (limit_mask & DYN_SRC_PORT)
1338 id.src_port = args->f_id.src_port;
1339 if (limit_mask & DYN_DST_PORT)
1340 id.dst_port = args->f_id.dst_port;
1342 parent = lookup_dyn_parent(&id, rule);
1343 if (parent == NULL) {
1344 kprintf("add parent failed\n");
1345 return 1;
1348 if (parent->count >= cmd->conn_limit) {
1350 * See if we can remove some expired rule.
1352 remove_dyn_rule_locked(rule, parent);
1353 if (parent->count >= cmd->conn_limit) {
1354 if (fw_verbose &&
1355 last_log != time_second) {
1356 last_log = time_second;
1357 log(LOG_SECURITY | LOG_DEBUG,
1358 "drop session, "
1359 "too many entries\n");
1361 return 1;
1364 if (add_dyn_rule(&args->f_id, O_LIMIT,
1365 (struct ip_fw *)parent) == NULL)
1366 return 1;
1368 break;
1369 default:
1370 kprintf("unknown dynamic rule type %u\n", cmd->o.opcode);
1371 return 1;
1373 lookup_dyn_rule(&args->f_id, NULL, NULL); /* XXX just set lifetime */
1374 return 0;
1377 static int
1378 install_state(struct ip_fw *rule, ipfw_insn_limit *cmd,
1379 struct ip_fw_args *args, int *deny)
1381 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
1382 uint32_t gen;
1383 int ret = 0;
1385 *deny = 0;
1386 gen = ctx->ipfw_gen;
1388 lockmgr(&dyn_lock, LK_EXCLUSIVE);
1389 if (ctx->ipfw_gen != gen) {
1390 /* See the comment in lookup_rule() */
1391 *deny = 1;
1392 } else {
1393 ret = install_state_locked(rule, cmd, args);
1395 lockmgr(&dyn_lock, LK_RELEASE);
1397 return ret;
1401 * Transmit a TCP packet, containing either a RST or a keepalive.
1402 * When flags & TH_RST, we are sending a RST packet, because of a
1403 * "reset" action matched the packet.
1404 * Otherwise we are sending a keepalive, and flags & TH_
1406 static void
1407 send_pkt(struct ipfw_flow_id *id, uint32_t seq, uint32_t ack, int flags)
1409 struct mbuf *m;
1410 struct ip *ip;
1411 struct tcphdr *tcp;
1412 struct route sro; /* fake route */
1414 MGETHDR(m, M_NOWAIT, MT_HEADER);
1415 if (m == NULL)
1416 return;
1417 m->m_pkthdr.rcvif = NULL;
1418 m->m_pkthdr.len = m->m_len = sizeof(struct ip) + sizeof(struct tcphdr);
1419 m->m_data += max_linkhdr;
1421 ip = mtod(m, struct ip *);
1422 bzero(ip, m->m_len);
1423 tcp = (struct tcphdr *)(ip + 1); /* no IP options */
1424 ip->ip_p = IPPROTO_TCP;
1425 tcp->th_off = 5;
1428 * Assume we are sending a RST (or a keepalive in the reverse
1429 * direction), swap src and destination addresses and ports.
1431 ip->ip_src.s_addr = htonl(id->dst_ip);
1432 ip->ip_dst.s_addr = htonl(id->src_ip);
1433 tcp->th_sport = htons(id->dst_port);
1434 tcp->th_dport = htons(id->src_port);
1435 if (flags & TH_RST) { /* we are sending a RST */
1436 if (flags & TH_ACK) {
1437 tcp->th_seq = htonl(ack);
1438 tcp->th_ack = htonl(0);
1439 tcp->th_flags = TH_RST;
1440 } else {
1441 if (flags & TH_SYN)
1442 seq++;
1443 tcp->th_seq = htonl(0);
1444 tcp->th_ack = htonl(seq);
1445 tcp->th_flags = TH_RST | TH_ACK;
1447 } else {
1449 * We are sending a keepalive. flags & TH_SYN determines
1450 * the direction, forward if set, reverse if clear.
1451 * NOTE: seq and ack are always assumed to be correct
1452 * as set by the caller. This may be confusing...
1454 if (flags & TH_SYN) {
1456 * we have to rewrite the correct addresses!
1458 ip->ip_dst.s_addr = htonl(id->dst_ip);
1459 ip->ip_src.s_addr = htonl(id->src_ip);
1460 tcp->th_dport = htons(id->dst_port);
1461 tcp->th_sport = htons(id->src_port);
1463 tcp->th_seq = htonl(seq);
1464 tcp->th_ack = htonl(ack);
1465 tcp->th_flags = TH_ACK;
1469 * set ip_len to the payload size so we can compute
1470 * the tcp checksum on the pseudoheader
1471 * XXX check this, could save a couple of words ?
1473 ip->ip_len = htons(sizeof(struct tcphdr));
1474 tcp->th_sum = in_cksum(m, m->m_pkthdr.len);
1477 * now fill fields left out earlier
1479 ip->ip_ttl = ip_defttl;
1480 ip->ip_len = m->m_pkthdr.len;
1482 bzero(&sro, sizeof(sro));
1483 ip_rtaddr(ip->ip_dst, &sro);
1485 m->m_pkthdr.fw_flags |= IPFW_MBUF_GENERATED;
1486 ip_output(m, NULL, &sro, 0, NULL, NULL);
1487 if (sro.ro_rt)
1488 RTFREE(sro.ro_rt);
1492 * Send a reject message, consuming the mbuf passed as an argument.
1494 static void
1495 send_reject(struct ip_fw_args *args, int code, int offset, int ip_len)
1497 if (code != ICMP_REJECT_RST) { /* Send an ICMP unreach */
1498 /* We need the IP header in host order for icmp_error(). */
1499 if (args->eh != NULL) {
1500 struct ip *ip = mtod(args->m, struct ip *);
1502 ip->ip_len = ntohs(ip->ip_len);
1503 ip->ip_off = ntohs(ip->ip_off);
1505 icmp_error(args->m, ICMP_UNREACH, code, 0L, 0);
1506 } else if (offset == 0 && args->f_id.proto == IPPROTO_TCP) {
1507 struct tcphdr *const tcp =
1508 L3HDR(struct tcphdr, mtod(args->m, struct ip *));
1510 if ((tcp->th_flags & TH_RST) == 0) {
1511 send_pkt(&args->f_id, ntohl(tcp->th_seq),
1512 ntohl(tcp->th_ack), tcp->th_flags | TH_RST);
1514 m_freem(args->m);
1515 } else {
1516 m_freem(args->m);
1518 args->m = NULL;
1522 * Given an ip_fw *, lookup_next_rule will return a pointer
1523 * to the next rule, which can be either the jump
1524 * target (for skipto instructions) or the next one in the list (in
1525 * all other cases including a missing jump target).
1526 * The result is also written in the "next_rule" field of the rule.
1527 * Backward jumps are not allowed, so start looking from the next
1528 * rule...
1530 * This never returns NULL -- in case we do not have an exact match,
1531 * the next rule is returned. When the ruleset is changed,
1532 * pointers are flushed so we are always correct.
1534 static struct ip_fw *
1535 lookup_next_rule(struct ip_fw *me)
1537 struct ip_fw *rule = NULL;
1538 ipfw_insn *cmd;
1540 /* look for action, in case it is a skipto */
1541 cmd = ACTION_PTR(me);
1542 if (cmd->opcode == O_LOG)
1543 cmd += F_LEN(cmd);
1544 if (cmd->opcode == O_SKIPTO) {
1545 for (rule = me->next; rule; rule = rule->next) {
1546 if (rule->rulenum >= cmd->arg1)
1547 break;
1550 if (rule == NULL) /* failure or not a skipto */
1551 rule = me->next;
1552 me->next_rule = rule;
1553 return rule;
1556 static int
1557 _ipfw_match_uid(const struct ipfw_flow_id *fid, struct ifnet *oif,
1558 enum ipfw_opcodes opcode, uid_t uid)
1560 struct in_addr src_ip, dst_ip;
1561 struct inpcbinfo *pi;
1562 boolean_t wildcard;
1563 struct inpcb *pcb;
1565 if (fid->proto == IPPROTO_TCP) {
1566 wildcard = FALSE;
1567 pi = &tcbinfo[mycpuid];
1568 } else if (fid->proto == IPPROTO_UDP) {
1569 wildcard = TRUE;
1570 pi = &udbinfo[mycpuid];
1571 } else {
1572 return 0;
1576 * Values in 'fid' are in host byte order
1578 dst_ip.s_addr = htonl(fid->dst_ip);
1579 src_ip.s_addr = htonl(fid->src_ip);
1580 if (oif) {
1581 pcb = in_pcblookup_hash(pi,
1582 dst_ip, htons(fid->dst_port),
1583 src_ip, htons(fid->src_port),
1584 wildcard, oif);
1585 } else {
1586 pcb = in_pcblookup_hash(pi,
1587 src_ip, htons(fid->src_port),
1588 dst_ip, htons(fid->dst_port),
1589 wildcard, NULL);
1591 if (pcb == NULL || pcb->inp_socket == NULL)
1592 return 0;
1594 if (opcode == O_UID) {
1595 #define socheckuid(a,b) ((a)->so_cred->cr_uid != (b))
1596 return !socheckuid(pcb->inp_socket, uid);
1597 #undef socheckuid
1598 } else {
1599 return groupmember(uid, pcb->inp_socket->so_cred);
1603 static int
1604 ipfw_match_uid(const struct ipfw_flow_id *fid, struct ifnet *oif,
1605 enum ipfw_opcodes opcode, uid_t uid, int *deny)
1607 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
1608 uint32_t gen;
1609 int match = 0;
1611 *deny = 0;
1612 gen = ctx->ipfw_gen;
1614 if (gen != ctx->ipfw_gen) {
1615 /* See the comment in lookup_rule() */
1616 *deny = 1;
1617 } else {
1618 match = _ipfw_match_uid(fid, oif, opcode, uid);
1620 return match;
1624 * The main check routine for the firewall.
1626 * All arguments are in args so we can modify them and return them
1627 * back to the caller.
1629 * Parameters:
1631 * args->m (in/out) The packet; we set to NULL when/if we nuke it.
1632 * Starts with the IP header.
1633 * args->eh (in) Mac header if present, or NULL for layer3 packet.
1634 * args->oif Outgoing interface, or NULL if packet is incoming.
1635 * The incoming interface is in the mbuf. (in)
1637 * args->rule Pointer to the last matching rule (in/out)
1638 * args->f_id Addresses grabbed from the packet (out)
1640 * Return value:
1642 * If the packet was denied/rejected and has been dropped, *m is equal
1643 * to NULL upon return.
1645 * IP_FW_DENY the packet must be dropped.
1646 * IP_FW_PASS The packet is to be accepted and routed normally.
1647 * IP_FW_DIVERT Divert the packet to port (args->cookie)
1648 * IP_FW_TEE Tee the packet to port (args->cookie)
1649 * IP_FW_DUMMYNET Send the packet to pipe/queue (args->cookie)
1651 static int
1652 ipfw_chk(struct ip_fw_args *args)
1655 * Local variables hold state during the processing of a packet.
1657 * IMPORTANT NOTE: to speed up the processing of rules, there
1658 * are some assumption on the values of the variables, which
1659 * are documented here. Should you change them, please check
1660 * the implementation of the various instructions to make sure
1661 * that they still work.
1663 * args->eh The MAC header. It is non-null for a layer2
1664 * packet, it is NULL for a layer-3 packet.
1666 * m | args->m Pointer to the mbuf, as received from the caller.
1667 * It may change if ipfw_chk() does an m_pullup, or if it
1668 * consumes the packet because it calls send_reject().
1669 * XXX This has to change, so that ipfw_chk() never modifies
1670 * or consumes the buffer.
1671 * ip is simply an alias of the value of m, and it is kept
1672 * in sync with it (the packet is supposed to start with
1673 * the ip header).
1675 struct mbuf *m = args->m;
1676 struct ip *ip = mtod(m, struct ip *);
1679 * oif | args->oif If NULL, ipfw_chk has been called on the
1680 * inbound path (ether_input, ip_input).
1681 * If non-NULL, ipfw_chk has been called on the outbound path
1682 * (ether_output, ip_output).
1684 struct ifnet *oif = args->oif;
1686 struct ip_fw *f = NULL; /* matching rule */
1687 int retval = IP_FW_PASS;
1688 struct m_tag *mtag;
1689 struct divert_info *divinfo;
1692 * hlen The length of the IPv4 header.
1693 * hlen >0 means we have an IPv4 packet.
1695 u_int hlen = 0; /* hlen >0 means we have an IP pkt */
1698 * offset The offset of a fragment. offset != 0 means that
1699 * we have a fragment at this offset of an IPv4 packet.
1700 * offset == 0 means that (if this is an IPv4 packet)
1701 * this is the first or only fragment.
1703 u_short offset = 0;
1706 * Local copies of addresses. They are only valid if we have
1707 * an IP packet.
1709 * proto The protocol. Set to 0 for non-ip packets,
1710 * or to the protocol read from the packet otherwise.
1711 * proto != 0 means that we have an IPv4 packet.
1713 * src_port, dst_port port numbers, in HOST format. Only
1714 * valid for TCP and UDP packets.
1716 * src_ip, dst_ip ip addresses, in NETWORK format.
1717 * Only valid for IPv4 packets.
1719 uint8_t proto;
1720 uint16_t src_port = 0, dst_port = 0; /* NOTE: host format */
1721 struct in_addr src_ip, dst_ip; /* NOTE: network format */
1722 uint16_t ip_len = 0;
1725 * dyn_dir = MATCH_UNKNOWN when rules unchecked,
1726 * MATCH_NONE when checked and not matched (dyn_f = NULL),
1727 * MATCH_FORWARD or MATCH_REVERSE otherwise (dyn_f != NULL)
1729 int dyn_dir = MATCH_UNKNOWN;
1730 struct ip_fw *dyn_f = NULL;
1731 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
1733 if (m->m_pkthdr.fw_flags & IPFW_MBUF_GENERATED)
1734 return IP_FW_PASS; /* accept */
1736 if (args->eh == NULL || /* layer 3 packet */
1737 (m->m_pkthdr.len >= sizeof(struct ip) &&
1738 ntohs(args->eh->ether_type) == ETHERTYPE_IP))
1739 hlen = ip->ip_hl << 2;
1742 * Collect parameters into local variables for faster matching.
1744 if (hlen == 0) { /* do not grab addresses for non-ip pkts */
1745 proto = args->f_id.proto = 0; /* mark f_id invalid */
1746 goto after_ip_checks;
1749 proto = args->f_id.proto = ip->ip_p;
1750 src_ip = ip->ip_src;
1751 dst_ip = ip->ip_dst;
1752 if (args->eh != NULL) { /* layer 2 packets are as on the wire */
1753 offset = ntohs(ip->ip_off) & IP_OFFMASK;
1754 ip_len = ntohs(ip->ip_len);
1755 } else {
1756 offset = ip->ip_off & IP_OFFMASK;
1757 ip_len = ip->ip_len;
1760 #define PULLUP_TO(len) \
1761 do { \
1762 if (m->m_len < (len)) { \
1763 args->m = m = m_pullup(m, (len));\
1764 if (m == NULL) \
1765 goto pullup_failed; \
1766 ip = mtod(m, struct ip *); \
1768 } while (0)
1770 if (offset == 0) {
1771 switch (proto) {
1772 case IPPROTO_TCP:
1774 struct tcphdr *tcp;
1776 PULLUP_TO(hlen + sizeof(struct tcphdr));
1777 tcp = L3HDR(struct tcphdr, ip);
1778 dst_port = tcp->th_dport;
1779 src_port = tcp->th_sport;
1780 args->f_id.flags = tcp->th_flags;
1782 break;
1784 case IPPROTO_UDP:
1786 struct udphdr *udp;
1788 PULLUP_TO(hlen + sizeof(struct udphdr));
1789 udp = L3HDR(struct udphdr, ip);
1790 dst_port = udp->uh_dport;
1791 src_port = udp->uh_sport;
1793 break;
1795 case IPPROTO_ICMP:
1796 PULLUP_TO(hlen + 4); /* type, code and checksum. */
1797 args->f_id.flags = L3HDR(struct icmp, ip)->icmp_type;
1798 break;
1800 default:
1801 break;
1805 #undef PULLUP_TO
1807 args->f_id.src_ip = ntohl(src_ip.s_addr);
1808 args->f_id.dst_ip = ntohl(dst_ip.s_addr);
1809 args->f_id.src_port = src_port = ntohs(src_port);
1810 args->f_id.dst_port = dst_port = ntohs(dst_port);
1812 after_ip_checks:
1813 if (args->rule) {
1815 * Packet has already been tagged. Look for the next rule
1816 * to restart processing.
1818 * If fw_one_pass != 0 then just accept it.
1819 * XXX should not happen here, but optimized out in
1820 * the caller.
1822 if (fw_one_pass)
1823 return IP_FW_PASS;
1825 /* This rule is being/has been flushed */
1826 if (ipfw_flushing)
1827 return IP_FW_DENY;
1829 KASSERT(args->rule->cpuid == mycpuid,
1830 ("rule used on cpu%d", mycpuid));
1832 /* This rule was deleted */
1833 if (args->rule->rule_flags & IPFW_RULE_F_INVALID)
1834 return IP_FW_DENY;
1836 f = args->rule->next_rule;
1837 if (f == NULL)
1838 f = lookup_next_rule(args->rule);
1839 } else {
1841 * Find the starting rule. It can be either the first
1842 * one, or the one after divert_rule if asked so.
1844 int skipto;
1846 mtag = m_tag_find(m, PACKET_TAG_IPFW_DIVERT, NULL);
1847 if (mtag != NULL) {
1848 divinfo = m_tag_data(mtag);
1849 skipto = divinfo->skipto;
1850 } else {
1851 skipto = 0;
1854 f = ctx->ipfw_layer3_chain;
1855 if (args->eh == NULL && skipto != 0) {
1856 /* No skipto during rule flushing */
1857 if (ipfw_flushing)
1858 return IP_FW_DENY;
1860 if (skipto >= IPFW_DEFAULT_RULE)
1861 return IP_FW_DENY; /* invalid */
1863 while (f && f->rulenum <= skipto)
1864 f = f->next;
1865 if (f == NULL) /* drop packet */
1866 return IP_FW_DENY;
1867 } else if (ipfw_flushing) {
1868 /* Rules are being flushed; skip to default rule */
1869 f = ctx->ipfw_default_rule;
1872 if ((mtag = m_tag_find(m, PACKET_TAG_IPFW_DIVERT, NULL)) != NULL)
1873 m_tag_delete(m, mtag);
1876 * Now scan the rules, and parse microinstructions for each rule.
1878 for (; f; f = f->next) {
1879 int l, cmdlen;
1880 ipfw_insn *cmd;
1881 int skip_or; /* skip rest of OR block */
1883 again:
1884 if (ctx->ipfw_set_disable & (1 << f->set))
1885 continue;
1887 skip_or = 0;
1888 for (l = f->cmd_len, cmd = f->cmd; l > 0;
1889 l -= cmdlen, cmd += cmdlen) {
1890 int match, deny;
1893 * check_body is a jump target used when we find a
1894 * CHECK_STATE, and need to jump to the body of
1895 * the target rule.
1898 check_body:
1899 cmdlen = F_LEN(cmd);
1901 * An OR block (insn_1 || .. || insn_n) has the
1902 * F_OR bit set in all but the last instruction.
1903 * The first match will set "skip_or", and cause
1904 * the following instructions to be skipped until
1905 * past the one with the F_OR bit clear.
1907 if (skip_or) { /* skip this instruction */
1908 if ((cmd->len & F_OR) == 0)
1909 skip_or = 0; /* next one is good */
1910 continue;
1912 match = 0; /* set to 1 if we succeed */
1914 switch (cmd->opcode) {
1916 * The first set of opcodes compares the packet's
1917 * fields with some pattern, setting 'match' if a
1918 * match is found. At the end of the loop there is
1919 * logic to deal with F_NOT and F_OR flags associated
1920 * with the opcode.
1922 case O_NOP:
1923 match = 1;
1924 break;
1926 case O_FORWARD_MAC:
1927 kprintf("ipfw: opcode %d unimplemented\n",
1928 cmd->opcode);
1929 break;
1931 case O_GID:
1932 case O_UID:
1934 * We only check offset == 0 && proto != 0,
1935 * as this ensures that we have an IPv4
1936 * packet with the ports info.
1938 if (offset!=0)
1939 break;
1941 match = ipfw_match_uid(&args->f_id, oif,
1942 cmd->opcode,
1943 (uid_t)((ipfw_insn_u32 *)cmd)->d[0],
1944 &deny);
1945 if (deny)
1946 return IP_FW_DENY;
1947 break;
1949 case O_RECV:
1950 match = iface_match(m->m_pkthdr.rcvif,
1951 (ipfw_insn_if *)cmd);
1952 break;
1954 case O_XMIT:
1955 match = iface_match(oif, (ipfw_insn_if *)cmd);
1956 break;
1958 case O_VIA:
1959 match = iface_match(oif ? oif :
1960 m->m_pkthdr.rcvif, (ipfw_insn_if *)cmd);
1961 break;
1963 case O_MACADDR2:
1964 if (args->eh != NULL) { /* have MAC header */
1965 uint32_t *want = (uint32_t *)
1966 ((ipfw_insn_mac *)cmd)->addr;
1967 uint32_t *mask = (uint32_t *)
1968 ((ipfw_insn_mac *)cmd)->mask;
1969 uint32_t *hdr = (uint32_t *)args->eh;
1971 match =
1972 (want[0] == (hdr[0] & mask[0]) &&
1973 want[1] == (hdr[1] & mask[1]) &&
1974 want[2] == (hdr[2] & mask[2]));
1976 break;
1978 case O_MAC_TYPE:
1979 if (args->eh != NULL) {
1980 uint16_t t =
1981 ntohs(args->eh->ether_type);
1982 uint16_t *p =
1983 ((ipfw_insn_u16 *)cmd)->ports;
1984 int i;
1986 /* Special vlan handling */
1987 if (m->m_flags & M_VLANTAG)
1988 t = ETHERTYPE_VLAN;
1990 for (i = cmdlen - 1; !match && i > 0;
1991 i--, p += 2) {
1992 match =
1993 (t >= p[0] && t <= p[1]);
1996 break;
1998 case O_FRAG:
1999 match = (hlen > 0 && offset != 0);
2000 break;
2002 case O_IN: /* "out" is "not in" */
2003 match = (oif == NULL);
2004 break;
2006 case O_LAYER2:
2007 match = (args->eh != NULL);
2008 break;
2010 case O_PROTO:
2012 * We do not allow an arg of 0 so the
2013 * check of "proto" only suffices.
2015 match = (proto == cmd->arg1);
2016 break;
2018 case O_IP_SRC:
2019 match = (hlen > 0 &&
2020 ((ipfw_insn_ip *)cmd)->addr.s_addr ==
2021 src_ip.s_addr);
2022 break;
2024 case O_IP_SRC_MASK:
2025 match = (hlen > 0 &&
2026 ((ipfw_insn_ip *)cmd)->addr.s_addr ==
2027 (src_ip.s_addr &
2028 ((ipfw_insn_ip *)cmd)->mask.s_addr));
2029 break;
2031 case O_IP_SRC_ME:
2032 if (hlen > 0) {
2033 struct ifnet *tif;
2035 tif = INADDR_TO_IFP(&src_ip);
2036 match = (tif != NULL);
2038 break;
2040 case O_IP_DST_SET:
2041 case O_IP_SRC_SET:
2042 if (hlen > 0) {
2043 uint32_t *d = (uint32_t *)(cmd + 1);
2044 uint32_t addr =
2045 cmd->opcode == O_IP_DST_SET ?
2046 args->f_id.dst_ip :
2047 args->f_id.src_ip;
2049 if (addr < d[0])
2050 break;
2051 addr -= d[0]; /* subtract base */
2052 match =
2053 (addr < cmd->arg1) &&
2054 (d[1 + (addr >> 5)] &
2055 (1 << (addr & 0x1f)));
2057 break;
2059 case O_IP_DST:
2060 match = (hlen > 0 &&
2061 ((ipfw_insn_ip *)cmd)->addr.s_addr ==
2062 dst_ip.s_addr);
2063 break;
2065 case O_IP_DST_MASK:
2066 match = (hlen > 0) &&
2067 (((ipfw_insn_ip *)cmd)->addr.s_addr ==
2068 (dst_ip.s_addr &
2069 ((ipfw_insn_ip *)cmd)->mask.s_addr));
2070 break;
2072 case O_IP_DST_ME:
2073 if (hlen > 0) {
2074 struct ifnet *tif;
2076 tif = INADDR_TO_IFP(&dst_ip);
2077 match = (tif != NULL);
2079 break;
2081 case O_IP_SRCPORT:
2082 case O_IP_DSTPORT:
2084 * offset == 0 && proto != 0 is enough
2085 * to guarantee that we have an IPv4
2086 * packet with port info.
2088 if ((proto==IPPROTO_UDP || proto==IPPROTO_TCP)
2089 && offset == 0) {
2090 uint16_t x =
2091 (cmd->opcode == O_IP_SRCPORT) ?
2092 src_port : dst_port ;
2093 uint16_t *p =
2094 ((ipfw_insn_u16 *)cmd)->ports;
2095 int i;
2097 for (i = cmdlen - 1; !match && i > 0;
2098 i--, p += 2) {
2099 match =
2100 (x >= p[0] && x <= p[1]);
2103 break;
2105 case O_ICMPTYPE:
2106 match = (offset == 0 && proto==IPPROTO_ICMP &&
2107 icmptype_match(ip, (ipfw_insn_u32 *)cmd));
2108 break;
2110 case O_IPOPT:
2111 match = (hlen > 0 && ipopts_match(ip, cmd));
2112 break;
2114 case O_IPVER:
2115 match = (hlen > 0 && cmd->arg1 == ip->ip_v);
2116 break;
2118 case O_IPTTL:
2119 match = (hlen > 0 && cmd->arg1 == ip->ip_ttl);
2120 break;
2122 case O_IPID:
2123 match = (hlen > 0 &&
2124 cmd->arg1 == ntohs(ip->ip_id));
2125 break;
2127 case O_IPLEN:
2128 match = (hlen > 0 && cmd->arg1 == ip_len);
2129 break;
2131 case O_IPPRECEDENCE:
2132 match = (hlen > 0 &&
2133 (cmd->arg1 == (ip->ip_tos & 0xe0)));
2134 break;
2136 case O_IPTOS:
2137 match = (hlen > 0 &&
2138 flags_match(cmd, ip->ip_tos));
2139 break;
2141 case O_TCPFLAGS:
2142 match = (proto == IPPROTO_TCP && offset == 0 &&
2143 flags_match(cmd,
2144 L3HDR(struct tcphdr,ip)->th_flags));
2145 break;
2147 case O_TCPOPTS:
2148 match = (proto == IPPROTO_TCP && offset == 0 &&
2149 tcpopts_match(ip, cmd));
2150 break;
2152 case O_TCPSEQ:
2153 match = (proto == IPPROTO_TCP && offset == 0 &&
2154 ((ipfw_insn_u32 *)cmd)->d[0] ==
2155 L3HDR(struct tcphdr,ip)->th_seq);
2156 break;
2158 case O_TCPACK:
2159 match = (proto == IPPROTO_TCP && offset == 0 &&
2160 ((ipfw_insn_u32 *)cmd)->d[0] ==
2161 L3HDR(struct tcphdr,ip)->th_ack);
2162 break;
2164 case O_TCPWIN:
2165 match = (proto == IPPROTO_TCP && offset == 0 &&
2166 cmd->arg1 ==
2167 L3HDR(struct tcphdr,ip)->th_win);
2168 break;
2170 case O_ESTAB:
2171 /* reject packets which have SYN only */
2172 /* XXX should i also check for TH_ACK ? */
2173 match = (proto == IPPROTO_TCP && offset == 0 &&
2174 (L3HDR(struct tcphdr,ip)->th_flags &
2175 (TH_RST | TH_ACK | TH_SYN)) != TH_SYN);
2176 break;
2178 case O_LOG:
2179 if (fw_verbose)
2180 ipfw_log(f, hlen, args->eh, m, oif);
2181 match = 1;
2182 break;
2184 case O_PROB:
2185 match = (krandom() <
2186 ((ipfw_insn_u32 *)cmd)->d[0]);
2187 break;
2190 * The second set of opcodes represents 'actions',
2191 * i.e. the terminal part of a rule once the packet
2192 * matches all previous patterns.
2193 * Typically there is only one action for each rule,
2194 * and the opcode is stored at the end of the rule
2195 * (but there are exceptions -- see below).
2197 * In general, here we set retval and terminate the
2198 * outer loop (would be a 'break 3' in some language,
2199 * but we need to do a 'goto done').
2201 * Exceptions:
2202 * O_COUNT and O_SKIPTO actions:
2203 * instead of terminating, we jump to the next rule
2204 * ('goto next_rule', equivalent to a 'break 2'),
2205 * or to the SKIPTO target ('goto again' after
2206 * having set f, cmd and l), respectively.
2208 * O_LIMIT and O_KEEP_STATE: these opcodes are
2209 * not real 'actions', and are stored right
2210 * before the 'action' part of the rule.
2211 * These opcodes try to install an entry in the
2212 * state tables; if successful, we continue with
2213 * the next opcode (match=1; break;), otherwise
2214 * the packet must be dropped ('goto done' after
2215 * setting retval). If static rules are changed
2216 * during the state installation, the packet will
2217 * be dropped and rule's stats will not beupdated
2218 * ('return IP_FW_DENY').
2220 * O_PROBE_STATE and O_CHECK_STATE: these opcodes
2221 * cause a lookup of the state table, and a jump
2222 * to the 'action' part of the parent rule
2223 * ('goto check_body') if an entry is found, or
2224 * (CHECK_STATE only) a jump to the next rule if
2225 * the entry is not found ('goto next_rule').
2226 * The result of the lookup is cached to make
2227 * further instances of these opcodes are
2228 * effectively NOPs. If static rules are changed
2229 * during the state looking up, the packet will
2230 * be dropped and rule's stats will not be updated
2231 * ('return IP_FW_DENY').
2233 case O_LIMIT:
2234 case O_KEEP_STATE:
2235 if (!(f->rule_flags & IPFW_RULE_F_STATE)) {
2236 kprintf("%s rule (%d) is not ready "
2237 "on cpu%d\n",
2238 cmd->opcode == O_LIMIT ?
2239 "limit" : "keep state",
2240 f->rulenum, f->cpuid);
2241 goto next_rule;
2243 if (install_state(f,
2244 (ipfw_insn_limit *)cmd, args, &deny)) {
2245 if (deny)
2246 return IP_FW_DENY;
2248 retval = IP_FW_DENY;
2249 goto done; /* error/limit violation */
2251 if (deny)
2252 return IP_FW_DENY;
2253 match = 1;
2254 break;
2256 case O_PROBE_STATE:
2257 case O_CHECK_STATE:
2259 * dynamic rules are checked at the first
2260 * keep-state or check-state occurrence,
2261 * with the result being stored in dyn_dir.
2262 * The compiler introduces a PROBE_STATE
2263 * instruction for us when we have a
2264 * KEEP_STATE (because PROBE_STATE needs
2265 * to be run first).
2267 if (dyn_dir == MATCH_UNKNOWN) {
2268 dyn_f = lookup_rule(&args->f_id,
2269 &dyn_dir,
2270 proto == IPPROTO_TCP ?
2271 L3HDR(struct tcphdr, ip) : NULL,
2272 ip_len, &deny);
2273 if (deny)
2274 return IP_FW_DENY;
2275 if (dyn_f != NULL) {
2277 * Found a rule from a dynamic
2278 * entry; jump to the 'action'
2279 * part of the rule.
2281 f = dyn_f;
2282 cmd = ACTION_PTR(f);
2283 l = f->cmd_len - f->act_ofs;
2284 goto check_body;
2288 * Dynamic entry not found. If CHECK_STATE,
2289 * skip to next rule, if PROBE_STATE just
2290 * ignore and continue with next opcode.
2292 if (cmd->opcode == O_CHECK_STATE)
2293 goto next_rule;
2294 else if (!(f->rule_flags & IPFW_RULE_F_STATE))
2295 goto next_rule; /* not ready yet */
2296 match = 1;
2297 break;
2299 case O_ACCEPT:
2300 retval = IP_FW_PASS; /* accept */
2301 goto done;
2303 case O_PIPE:
2304 case O_QUEUE:
2305 args->rule = f; /* report matching rule */
2306 args->cookie = cmd->arg1;
2307 retval = IP_FW_DUMMYNET;
2308 goto done;
2310 case O_DIVERT:
2311 case O_TEE:
2312 if (args->eh) /* not on layer 2 */
2313 break;
2315 mtag = m_tag_get(PACKET_TAG_IPFW_DIVERT,
2316 sizeof(*divinfo), M_NOWAIT);
2317 if (mtag == NULL) {
2318 retval = IP_FW_DENY;
2319 goto done;
2321 divinfo = m_tag_data(mtag);
2323 divinfo->skipto = f->rulenum;
2324 divinfo->port = cmd->arg1;
2325 divinfo->tee = (cmd->opcode == O_TEE);
2326 m_tag_prepend(m, mtag);
2328 args->cookie = cmd->arg1;
2329 retval = (cmd->opcode == O_DIVERT) ?
2330 IP_FW_DIVERT : IP_FW_TEE;
2331 goto done;
2333 case O_COUNT:
2334 case O_SKIPTO:
2335 f->pcnt++; /* update stats */
2336 f->bcnt += ip_len;
2337 f->timestamp = time_second;
2338 if (cmd->opcode == O_COUNT)
2339 goto next_rule;
2340 /* handle skipto */
2341 if (f->next_rule == NULL)
2342 lookup_next_rule(f);
2343 f = f->next_rule;
2344 goto again;
2346 case O_REJECT:
2348 * Drop the packet and send a reject notice
2349 * if the packet is not ICMP (or is an ICMP
2350 * query), and it is not multicast/broadcast.
2352 if (hlen > 0 &&
2353 (proto != IPPROTO_ICMP ||
2354 is_icmp_query(ip)) &&
2355 !(m->m_flags & (M_BCAST|M_MCAST)) &&
2356 !IN_MULTICAST(ntohl(dst_ip.s_addr))) {
2358 * Update statistics before the possible
2359 * blocking 'send_reject'
2361 f->pcnt++;
2362 f->bcnt += ip_len;
2363 f->timestamp = time_second;
2365 send_reject(args, cmd->arg1,
2366 offset,ip_len);
2367 m = args->m;
2370 * Return directly here, rule stats
2371 * have been updated above.
2373 return IP_FW_DENY;
2375 /* FALLTHROUGH */
2376 case O_DENY:
2377 retval = IP_FW_DENY;
2378 goto done;
2380 case O_FORWARD_IP:
2381 if (args->eh) /* not valid on layer2 pkts */
2382 break;
2383 if (!dyn_f || dyn_dir == MATCH_FORWARD) {
2384 struct sockaddr_in *sin;
2386 mtag = m_tag_get(PACKET_TAG_IPFORWARD,
2387 sizeof(*sin), M_NOWAIT);
2388 if (mtag == NULL) {
2389 retval = IP_FW_DENY;
2390 goto done;
2392 sin = m_tag_data(mtag);
2394 /* Structure copy */
2395 *sin = ((ipfw_insn_sa *)cmd)->sa;
2397 m_tag_prepend(m, mtag);
2398 m->m_pkthdr.fw_flags |=
2399 IPFORWARD_MBUF_TAGGED;
2400 m->m_pkthdr.fw_flags &=
2401 ~BRIDGE_MBUF_TAGGED;
2403 retval = IP_FW_PASS;
2404 goto done;
2406 default:
2407 panic("-- unknown opcode %d", cmd->opcode);
2408 } /* end of switch() on opcodes */
2410 if (cmd->len & F_NOT)
2411 match = !match;
2413 if (match) {
2414 if (cmd->len & F_OR)
2415 skip_or = 1;
2416 } else {
2417 if (!(cmd->len & F_OR)) /* not an OR block, */
2418 break; /* try next rule */
2421 } /* end of inner for, scan opcodes */
2423 next_rule:; /* try next rule */
2425 } /* end of outer for, scan rules */
2426 kprintf("+++ ipfw: ouch!, skip past end of rules, denying packet\n");
2427 return IP_FW_DENY;
2429 done:
2430 /* Update statistics */
2431 f->pcnt++;
2432 f->bcnt += ip_len;
2433 f->timestamp = time_second;
2434 return retval;
2436 pullup_failed:
2437 if (fw_verbose)
2438 kprintf("pullup failed\n");
2439 return IP_FW_DENY;
2442 static void
2443 ipfw_dummynet_io(struct mbuf *m, int pipe_nr, int dir, struct ip_fw_args *fwa)
2445 struct m_tag *mtag;
2446 struct dn_pkt *pkt;
2447 ipfw_insn *cmd;
2448 const struct ipfw_flow_id *id;
2449 struct dn_flow_id *fid;
2451 M_ASSERTPKTHDR(m);
2453 mtag = m_tag_get(PACKET_TAG_DUMMYNET, sizeof(*pkt), M_NOWAIT);
2454 if (mtag == NULL) {
2455 m_freem(m);
2456 return;
2458 m_tag_prepend(m, mtag);
2460 pkt = m_tag_data(mtag);
2461 bzero(pkt, sizeof(*pkt));
2463 cmd = fwa->rule->cmd + fwa->rule->act_ofs;
2464 if (cmd->opcode == O_LOG)
2465 cmd += F_LEN(cmd);
2466 KASSERT(cmd->opcode == O_PIPE || cmd->opcode == O_QUEUE,
2467 ("Rule is not PIPE or QUEUE, opcode %d", cmd->opcode));
2469 pkt->dn_m = m;
2470 pkt->dn_flags = (dir & DN_FLAGS_DIR_MASK);
2471 pkt->ifp = fwa->oif;
2472 pkt->pipe_nr = pipe_nr;
2474 pkt->cpuid = mycpuid;
2475 pkt->msgport = netisr_curport();
2477 id = &fwa->f_id;
2478 fid = &pkt->id;
2479 fid->fid_dst_ip = id->dst_ip;
2480 fid->fid_src_ip = id->src_ip;
2481 fid->fid_dst_port = id->dst_port;
2482 fid->fid_src_port = id->src_port;
2483 fid->fid_proto = id->proto;
2484 fid->fid_flags = id->flags;
2486 ipfw_ref_rule(fwa->rule);
2487 pkt->dn_priv = fwa->rule;
2488 pkt->dn_unref_priv = ipfw_unref_rule;
2490 if (cmd->opcode == O_PIPE)
2491 pkt->dn_flags |= DN_FLAGS_IS_PIPE;
2493 m->m_pkthdr.fw_flags |= DUMMYNET_MBUF_TAGGED;
2497 * When a rule is added/deleted, clear the next_rule pointers in all rules.
2498 * These will be reconstructed on the fly as packets are matched.
2500 static void
2501 ipfw_flush_rule_ptrs(struct ipfw_context *ctx)
2503 struct ip_fw *rule;
2505 for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next)
2506 rule->next_rule = NULL;
2509 static __inline void
2510 ipfw_inc_static_count(struct ip_fw *rule)
2512 /* Static rule's counts are updated only on CPU0 */
2513 KKASSERT(mycpuid == 0);
2515 static_count++;
2516 static_ioc_len += IOC_RULESIZE(rule);
2519 static __inline void
2520 ipfw_dec_static_count(struct ip_fw *rule)
2522 int l = IOC_RULESIZE(rule);
2524 /* Static rule's counts are updated only on CPU0 */
2525 KKASSERT(mycpuid == 0);
2527 KASSERT(static_count > 0, ("invalid static count %u", static_count));
2528 static_count--;
2530 KASSERT(static_ioc_len >= l,
2531 ("invalid static len %u", static_ioc_len));
2532 static_ioc_len -= l;
2535 static void
2536 ipfw_link_sibling(struct netmsg_ipfw *fwmsg, struct ip_fw *rule)
2538 if (fwmsg->sibling != NULL) {
2539 KKASSERT(mycpuid > 0 && fwmsg->sibling->cpuid == mycpuid - 1);
2540 fwmsg->sibling->sibling = rule;
2542 fwmsg->sibling = rule;
2545 static struct ip_fw *
2546 ipfw_create_rule(const struct ipfw_ioc_rule *ioc_rule, struct ip_fw_stub *stub)
2548 struct ip_fw *rule;
2550 rule = kmalloc(RULESIZE(ioc_rule), M_IPFW, M_WAITOK | M_ZERO);
2552 rule->act_ofs = ioc_rule->act_ofs;
2553 rule->cmd_len = ioc_rule->cmd_len;
2554 rule->rulenum = ioc_rule->rulenum;
2555 rule->set = ioc_rule->set;
2556 rule->usr_flags = ioc_rule->usr_flags;
2558 bcopy(ioc_rule->cmd, rule->cmd, rule->cmd_len * 4 /* XXX */);
2560 rule->refcnt = 1;
2561 rule->cpuid = mycpuid;
2563 rule->stub = stub;
2564 if (stub != NULL)
2565 stub->rule[mycpuid] = rule;
2567 return rule;
2570 static void
2571 ipfw_add_rule_dispatch(netmsg_t nmsg)
2573 struct netmsg_ipfw *fwmsg = (struct netmsg_ipfw *)nmsg;
2574 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2575 struct ip_fw *rule;
2577 rule = ipfw_create_rule(fwmsg->ioc_rule, fwmsg->stub);
2580 * Bump generation after ipfw_create_rule(),
2581 * since this function is blocking
2583 ctx->ipfw_gen++;
2586 * Insert rule into the pre-determined position
2588 if (fwmsg->prev_rule != NULL) {
2589 struct ip_fw *prev, *next;
2591 prev = fwmsg->prev_rule;
2592 KKASSERT(prev->cpuid == mycpuid);
2594 next = fwmsg->next_rule;
2595 KKASSERT(next->cpuid == mycpuid);
2597 rule->next = next;
2598 prev->next = rule;
2601 * Move to the position on the next CPU
2602 * before the msg is forwarded.
2604 fwmsg->prev_rule = prev->sibling;
2605 fwmsg->next_rule = next->sibling;
2606 } else {
2607 KKASSERT(fwmsg->next_rule == NULL);
2608 rule->next = ctx->ipfw_layer3_chain;
2609 ctx->ipfw_layer3_chain = rule;
2612 /* Link rule CPU sibling */
2613 ipfw_link_sibling(fwmsg, rule);
2615 ipfw_flush_rule_ptrs(ctx);
2617 if (mycpuid == 0) {
2618 /* Statistics only need to be updated once */
2619 ipfw_inc_static_count(rule);
2621 /* Return the rule on CPU0 */
2622 nmsg->lmsg.u.ms_resultp = rule;
2625 netisr_forwardmsg(&nmsg->base, mycpuid + 1);
2628 static void
2629 ipfw_enable_state_dispatch(netmsg_t nmsg)
2631 struct lwkt_msg *lmsg = &nmsg->lmsg;
2632 struct ip_fw *rule = lmsg->u.ms_resultp;
2633 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2635 ctx->ipfw_gen++;
2637 KKASSERT(rule->cpuid == mycpuid);
2638 KKASSERT(rule->stub != NULL && rule->stub->rule[mycpuid] == rule);
2639 KKASSERT(!(rule->rule_flags & IPFW_RULE_F_STATE));
2640 rule->rule_flags |= IPFW_RULE_F_STATE;
2641 lmsg->u.ms_resultp = rule->sibling;
2643 netisr_forwardmsg(&nmsg->base, mycpuid + 1);
2647 * Add a new rule to the list. Copy the rule into a malloc'ed area,
2648 * then possibly create a rule number and add the rule to the list.
2649 * Update the rule_number in the input struct so the caller knows
2650 * it as well.
2652 static void
2653 ipfw_add_rule(struct ipfw_ioc_rule *ioc_rule, uint32_t rule_flags)
2655 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2656 struct netmsg_ipfw fwmsg;
2657 struct netmsg_base *nmsg;
2658 struct ip_fw *f, *prev, *rule;
2659 struct ip_fw_stub *stub;
2661 IPFW_ASSERT_CFGPORT(&curthread->td_msgport);
2664 * If rulenum is 0, find highest numbered rule before the
2665 * default rule, and add rule number incremental step.
2667 if (ioc_rule->rulenum == 0) {
2668 int step = autoinc_step;
2670 KKASSERT(step >= IPFW_AUTOINC_STEP_MIN &&
2671 step <= IPFW_AUTOINC_STEP_MAX);
2674 * Locate the highest numbered rule before default
2676 for (f = ctx->ipfw_layer3_chain; f; f = f->next) {
2677 if (f->rulenum == IPFW_DEFAULT_RULE)
2678 break;
2679 ioc_rule->rulenum = f->rulenum;
2681 if (ioc_rule->rulenum < IPFW_DEFAULT_RULE - step)
2682 ioc_rule->rulenum += step;
2684 KASSERT(ioc_rule->rulenum != IPFW_DEFAULT_RULE &&
2685 ioc_rule->rulenum != 0,
2686 ("invalid rule num %d", ioc_rule->rulenum));
2689 * Now find the right place for the new rule in the sorted list.
2691 for (prev = NULL, f = ctx->ipfw_layer3_chain; f;
2692 prev = f, f = f->next) {
2693 if (f->rulenum > ioc_rule->rulenum) {
2694 /* Found the location */
2695 break;
2698 KASSERT(f != NULL, ("no default rule?!"));
2700 if (rule_flags & IPFW_RULE_F_STATE) {
2701 int size;
2704 * If the new rule will create states, then allocate
2705 * a rule stub, which will be referenced by states
2706 * (dyn rules)
2708 size = sizeof(*stub) + ((ncpus - 1) * sizeof(struct ip_fw *));
2709 stub = kmalloc(size, M_IPFW, M_WAITOK | M_ZERO);
2710 } else {
2711 stub = NULL;
2715 * Duplicate the rule onto each CPU.
2716 * The rule duplicated on CPU0 will be returned.
2718 bzero(&fwmsg, sizeof(fwmsg));
2719 nmsg = &fwmsg.base;
2720 netmsg_init(nmsg, NULL, &curthread->td_msgport,
2721 0, ipfw_add_rule_dispatch);
2722 fwmsg.ioc_rule = ioc_rule;
2723 fwmsg.prev_rule = prev;
2724 fwmsg.next_rule = prev == NULL ? NULL : f;
2725 fwmsg.stub = stub;
2727 netisr_domsg(nmsg, 0);
2728 KKASSERT(fwmsg.prev_rule == NULL && fwmsg.next_rule == NULL);
2730 rule = nmsg->lmsg.u.ms_resultp;
2731 KKASSERT(rule != NULL && rule->cpuid == mycpuid);
2733 if (rule_flags & IPFW_RULE_F_STATE) {
2735 * Turn on state flag, _after_ everything on all
2736 * CPUs have been setup.
2738 bzero(nmsg, sizeof(*nmsg));
2739 netmsg_init(nmsg, NULL, &curthread->td_msgport,
2740 0, ipfw_enable_state_dispatch);
2741 nmsg->lmsg.u.ms_resultp = rule;
2743 netisr_domsg(nmsg, 0);
2744 KKASSERT(nmsg->lmsg.u.ms_resultp == NULL);
2747 DPRINTF("++ installed rule %d, static count now %d\n",
2748 rule->rulenum, static_count);
2752 * Free storage associated with a static rule (including derived
2753 * dynamic rules).
2754 * The caller is in charge of clearing rule pointers to avoid
2755 * dangling pointers.
2756 * @return a pointer to the next entry.
2757 * Arguments are not checked, so they better be correct.
2759 static struct ip_fw *
2760 ipfw_delete_rule(struct ipfw_context *ctx,
2761 struct ip_fw *prev, struct ip_fw *rule)
2763 struct ip_fw *n;
2764 struct ip_fw_stub *stub;
2766 ctx->ipfw_gen++;
2768 /* STATE flag should have been cleared before we reach here */
2769 KKASSERT((rule->rule_flags & IPFW_RULE_F_STATE) == 0);
2771 stub = rule->stub;
2772 n = rule->next;
2773 if (prev == NULL)
2774 ctx->ipfw_layer3_chain = n;
2775 else
2776 prev->next = n;
2778 /* Mark the rule as invalid */
2779 rule->rule_flags |= IPFW_RULE_F_INVALID;
2780 rule->next_rule = NULL;
2781 rule->sibling = NULL;
2782 rule->stub = NULL;
2783 #ifdef foo
2784 /* Don't reset cpuid here; keep various assertion working */
2785 rule->cpuid = -1;
2786 #endif
2788 /* Statistics only need to be updated once */
2789 if (mycpuid == 0)
2790 ipfw_dec_static_count(rule);
2792 /* Free 'stub' on the last CPU */
2793 if (stub != NULL && mycpuid == ncpus - 1)
2794 kfree(stub, M_IPFW);
2796 /* Try to free this rule */
2797 ipfw_free_rule(rule);
2799 /* Return the next rule */
2800 return n;
2803 static void
2804 ipfw_flush_dispatch(netmsg_t nmsg)
2806 struct lwkt_msg *lmsg = &nmsg->lmsg;
2807 int kill_default = lmsg->u.ms_result;
2808 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2809 struct ip_fw *rule;
2811 ipfw_flush_rule_ptrs(ctx); /* more efficient to do outside the loop */
2813 while ((rule = ctx->ipfw_layer3_chain) != NULL &&
2814 (kill_default || rule->rulenum != IPFW_DEFAULT_RULE))
2815 ipfw_delete_rule(ctx, NULL, rule);
2817 netisr_forwardmsg(&nmsg->base, mycpuid + 1);
2820 static void
2821 ipfw_disable_rule_state_dispatch(netmsg_t nmsg)
2823 struct netmsg_del *dmsg = (struct netmsg_del *)nmsg;
2824 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2825 struct ip_fw *rule;
2827 ctx->ipfw_gen++;
2829 rule = dmsg->start_rule;
2830 if (rule != NULL) {
2831 KKASSERT(rule->cpuid == mycpuid);
2834 * Move to the position on the next CPU
2835 * before the msg is forwarded.
2837 dmsg->start_rule = rule->sibling;
2838 } else {
2839 KKASSERT(dmsg->rulenum == 0);
2840 rule = ctx->ipfw_layer3_chain;
2843 while (rule != NULL) {
2844 if (dmsg->rulenum && rule->rulenum != dmsg->rulenum)
2845 break;
2846 rule->rule_flags &= ~IPFW_RULE_F_STATE;
2847 rule = rule->next;
2850 netisr_forwardmsg(&nmsg->base, mycpuid + 1);
2854 * Deletes all rules from a chain (including the default rule
2855 * if the second argument is set).
2857 static void
2858 ipfw_flush(int kill_default)
2860 struct netmsg_del dmsg;
2861 struct netmsg_base nmsg;
2862 struct lwkt_msg *lmsg;
2863 struct ip_fw *rule;
2864 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2866 IPFW_ASSERT_CFGPORT(&curthread->td_msgport);
2869 * If 'kill_default' then caller has done the necessary
2870 * msgport syncing; unnecessary to do it again.
2872 if (!kill_default) {
2874 * Let ipfw_chk() know the rules are going to
2875 * be flushed, so it could jump directly to
2876 * the default rule.
2878 ipfw_flushing = 1;
2879 netmsg_service_sync();
2883 * Clear STATE flag on rules, so no more states (dyn rules)
2884 * will be created.
2886 bzero(&dmsg, sizeof(dmsg));
2887 netmsg_init(&dmsg.base, NULL, &curthread->td_msgport,
2888 0, ipfw_disable_rule_state_dispatch);
2889 netisr_domsg(&dmsg.base, 0);
2892 * This actually nukes all states (dyn rules)
2894 lockmgr(&dyn_lock, LK_EXCLUSIVE);
2895 for (rule = ctx->ipfw_layer3_chain; rule != NULL; rule = rule->next) {
2897 * Can't check IPFW_RULE_F_STATE here,
2898 * since it has been cleared previously.
2899 * Check 'stub' instead.
2901 if (rule->stub != NULL) {
2902 /* Force removal */
2903 remove_dyn_rule_locked(rule, NULL);
2906 lockmgr(&dyn_lock, LK_RELEASE);
2909 * Press the 'flush' button
2911 bzero(&nmsg, sizeof(nmsg));
2912 netmsg_init(&nmsg, NULL, &curthread->td_msgport,
2913 0, ipfw_flush_dispatch);
2914 lmsg = &nmsg.lmsg;
2915 lmsg->u.ms_result = kill_default;
2916 netisr_domsg(&nmsg, 0);
2918 KASSERT(dyn_count == 0, ("%u dyn rule remains", dyn_count));
2920 if (kill_default) {
2921 if (ipfw_dyn_v != NULL) {
2923 * Free dynamic rules(state) hash table
2925 kfree(ipfw_dyn_v, M_IPFW);
2926 ipfw_dyn_v = NULL;
2929 KASSERT(static_count == 0,
2930 ("%u static rules remain", static_count));
2931 KASSERT(static_ioc_len == 0,
2932 ("%u bytes of static rules remain", static_ioc_len));
2933 } else {
2934 KASSERT(static_count == 1,
2935 ("%u static rules remain", static_count));
2936 KASSERT(static_ioc_len == IOC_RULESIZE(ctx->ipfw_default_rule),
2937 ("%u bytes of static rules remain, should be %lu",
2938 static_ioc_len,
2939 (u_long)IOC_RULESIZE(ctx->ipfw_default_rule)));
2942 /* Flush is done */
2943 ipfw_flushing = 0;
2946 static void
2947 ipfw_alt_delete_rule_dispatch(netmsg_t nmsg)
2949 struct netmsg_del *dmsg = (struct netmsg_del *)nmsg;
2950 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2951 struct ip_fw *rule, *prev;
2953 rule = dmsg->start_rule;
2954 KKASSERT(rule->cpuid == mycpuid);
2955 dmsg->start_rule = rule->sibling;
2957 prev = dmsg->prev_rule;
2958 if (prev != NULL) {
2959 KKASSERT(prev->cpuid == mycpuid);
2962 * Move to the position on the next CPU
2963 * before the msg is forwarded.
2965 dmsg->prev_rule = prev->sibling;
2969 * flush pointers outside the loop, then delete all matching
2970 * rules. 'prev' remains the same throughout the cycle.
2972 ipfw_flush_rule_ptrs(ctx);
2973 while (rule && rule->rulenum == dmsg->rulenum)
2974 rule = ipfw_delete_rule(ctx, prev, rule);
2976 netisr_forwardmsg(&nmsg->base, mycpuid + 1);
2979 static int
2980 ipfw_alt_delete_rule(uint16_t rulenum)
2982 struct ip_fw *prev, *rule, *f;
2983 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2984 struct netmsg_del dmsg;
2985 struct netmsg_base *nmsg;
2986 int state;
2989 * Locate first rule to delete
2991 for (prev = NULL, rule = ctx->ipfw_layer3_chain;
2992 rule && rule->rulenum < rulenum;
2993 prev = rule, rule = rule->next)
2994 ; /* EMPTY */
2995 if (rule->rulenum != rulenum)
2996 return EINVAL;
2999 * Check whether any rules with the given number will
3000 * create states.
3002 state = 0;
3003 for (f = rule; f && f->rulenum == rulenum; f = f->next) {
3004 if (f->rule_flags & IPFW_RULE_F_STATE) {
3005 state = 1;
3006 break;
3010 if (state) {
3012 * Clear the STATE flag, so no more states will be
3013 * created based the rules numbered 'rulenum'.
3015 bzero(&dmsg, sizeof(dmsg));
3016 nmsg = &dmsg.base;
3017 netmsg_init(nmsg, NULL, &curthread->td_msgport,
3018 0, ipfw_disable_rule_state_dispatch);
3019 dmsg.start_rule = rule;
3020 dmsg.rulenum = rulenum;
3022 netisr_domsg(nmsg, 0);
3023 KKASSERT(dmsg.start_rule == NULL);
3026 * Nuke all related states
3028 lockmgr(&dyn_lock, LK_EXCLUSIVE);
3029 for (f = rule; f && f->rulenum == rulenum; f = f->next) {
3031 * Can't check IPFW_RULE_F_STATE here,
3032 * since it has been cleared previously.
3033 * Check 'stub' instead.
3035 if (f->stub != NULL) {
3036 /* Force removal */
3037 remove_dyn_rule_locked(f, NULL);
3040 lockmgr(&dyn_lock, LK_RELEASE);
3044 * Get rid of the rule duplications on all CPUs
3046 bzero(&dmsg, sizeof(dmsg));
3047 nmsg = &dmsg.base;
3048 netmsg_init(nmsg, NULL, &curthread->td_msgport,
3049 0, ipfw_alt_delete_rule_dispatch);
3050 dmsg.prev_rule = prev;
3051 dmsg.start_rule = rule;
3052 dmsg.rulenum = rulenum;
3054 netisr_domsg(nmsg, 0);
3055 KKASSERT(dmsg.prev_rule == NULL && dmsg.start_rule == NULL);
3056 return 0;
3059 static void
3060 ipfw_alt_delete_ruleset_dispatch(netmsg_t nmsg)
3062 struct netmsg_del *dmsg = (struct netmsg_del *)nmsg;
3063 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3064 struct ip_fw *prev, *rule;
3065 #ifdef INVARIANTS
3066 int del = 0;
3067 #endif
3069 ipfw_flush_rule_ptrs(ctx);
3071 prev = NULL;
3072 rule = ctx->ipfw_layer3_chain;
3073 while (rule != NULL) {
3074 if (rule->set == dmsg->from_set) {
3075 rule = ipfw_delete_rule(ctx, prev, rule);
3076 #ifdef INVARIANTS
3077 del = 1;
3078 #endif
3079 } else {
3080 prev = rule;
3081 rule = rule->next;
3084 KASSERT(del, ("no match set?!"));
3086 netisr_forwardmsg(&nmsg->base, mycpuid + 1);
3089 static void
3090 ipfw_disable_ruleset_state_dispatch(netmsg_t nmsg)
3092 struct netmsg_del *dmsg = (struct netmsg_del *)nmsg;
3093 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3094 struct ip_fw *rule;
3095 #ifdef INVARIANTS
3096 int cleared = 0;
3097 #endif
3099 ctx->ipfw_gen++;
3101 for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next) {
3102 if (rule->set == dmsg->from_set) {
3103 #ifdef INVARIANTS
3104 cleared = 1;
3105 #endif
3106 rule->rule_flags &= ~IPFW_RULE_F_STATE;
3109 KASSERT(cleared, ("no match set?!"));
3111 netisr_forwardmsg(&nmsg->base, mycpuid + 1);
3114 static int
3115 ipfw_alt_delete_ruleset(uint8_t set)
3117 struct netmsg_del dmsg;
3118 struct netmsg_base *nmsg;
3119 int state, del;
3120 struct ip_fw *rule;
3121 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3124 * Check whether the 'set' exists. If it exists,
3125 * then check whether any rules within the set will
3126 * try to create states.
3128 state = 0;
3129 del = 0;
3130 for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next) {
3131 if (rule->set == set) {
3132 del = 1;
3133 if (rule->rule_flags & IPFW_RULE_F_STATE) {
3134 state = 1;
3135 break;
3139 if (!del)
3140 return 0; /* XXX EINVAL? */
3142 if (state) {
3144 * Clear the STATE flag, so no more states will be
3145 * created based the rules in this set.
3147 bzero(&dmsg, sizeof(dmsg));
3148 nmsg = &dmsg.base;
3149 netmsg_init(nmsg, NULL, &curthread->td_msgport,
3150 0, ipfw_disable_ruleset_state_dispatch);
3151 dmsg.from_set = set;
3153 netisr_domsg(nmsg, 0);
3156 * Nuke all related states
3158 lockmgr(&dyn_lock, LK_EXCLUSIVE);
3159 for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next) {
3160 if (rule->set != set)
3161 continue;
3164 * Can't check IPFW_RULE_F_STATE here,
3165 * since it has been cleared previously.
3166 * Check 'stub' instead.
3168 if (rule->stub != NULL) {
3169 /* Force removal */
3170 remove_dyn_rule_locked(rule, NULL);
3173 lockmgr(&dyn_lock, LK_RELEASE);
3177 * Delete this set
3179 bzero(&dmsg, sizeof(dmsg));
3180 nmsg = &dmsg.base;
3181 netmsg_init(nmsg, NULL, &curthread->td_msgport,
3182 0, ipfw_alt_delete_ruleset_dispatch);
3183 dmsg.from_set = set;
3185 netisr_domsg(nmsg, 0);
3186 return 0;
3189 static void
3190 ipfw_alt_move_rule_dispatch(netmsg_t nmsg)
3192 struct netmsg_del *dmsg = (struct netmsg_del *)nmsg;
3193 struct ip_fw *rule;
3195 rule = dmsg->start_rule;
3196 KKASSERT(rule->cpuid == mycpuid);
3199 * Move to the position on the next CPU
3200 * before the msg is forwarded.
3202 dmsg->start_rule = rule->sibling;
3204 while (rule && rule->rulenum <= dmsg->rulenum) {
3205 if (rule->rulenum == dmsg->rulenum)
3206 rule->set = dmsg->to_set;
3207 rule = rule->next;
3209 netisr_forwardmsg(&nmsg->base, mycpuid + 1);
3212 static int
3213 ipfw_alt_move_rule(uint16_t rulenum, uint8_t set)
3215 struct netmsg_del dmsg;
3216 struct netmsg_base *nmsg;
3217 struct ip_fw *rule;
3218 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3221 * Locate first rule to move
3223 for (rule = ctx->ipfw_layer3_chain; rule && rule->rulenum <= rulenum;
3224 rule = rule->next) {
3225 if (rule->rulenum == rulenum && rule->set != set)
3226 break;
3228 if (rule == NULL || rule->rulenum > rulenum)
3229 return 0; /* XXX error? */
3231 bzero(&dmsg, sizeof(dmsg));
3232 nmsg = &dmsg.base;
3233 netmsg_init(nmsg, NULL, &curthread->td_msgport,
3234 0, ipfw_alt_move_rule_dispatch);
3235 dmsg.start_rule = rule;
3236 dmsg.rulenum = rulenum;
3237 dmsg.to_set = set;
3239 netisr_domsg(nmsg, 0);
3240 KKASSERT(dmsg.start_rule == NULL);
3241 return 0;
3244 static void
3245 ipfw_alt_move_ruleset_dispatch(netmsg_t nmsg)
3247 struct netmsg_del *dmsg = (struct netmsg_del *)nmsg;
3248 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3249 struct ip_fw *rule;
3251 for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next) {
3252 if (rule->set == dmsg->from_set)
3253 rule->set = dmsg->to_set;
3255 netisr_forwardmsg(&nmsg->base, mycpuid + 1);
3258 static int
3259 ipfw_alt_move_ruleset(uint8_t from_set, uint8_t to_set)
3261 struct netmsg_del dmsg;
3262 struct netmsg_base *nmsg;
3264 bzero(&dmsg, sizeof(dmsg));
3265 nmsg = &dmsg.base;
3266 netmsg_init(nmsg, NULL, &curthread->td_msgport,
3267 0, ipfw_alt_move_ruleset_dispatch);
3268 dmsg.from_set = from_set;
3269 dmsg.to_set = to_set;
3271 netisr_domsg(nmsg, 0);
3272 return 0;
3275 static void
3276 ipfw_alt_swap_ruleset_dispatch(netmsg_t nmsg)
3278 struct netmsg_del *dmsg = (struct netmsg_del *)nmsg;
3279 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3280 struct ip_fw *rule;
3282 for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next) {
3283 if (rule->set == dmsg->from_set)
3284 rule->set = dmsg->to_set;
3285 else if (rule->set == dmsg->to_set)
3286 rule->set = dmsg->from_set;
3288 netisr_forwardmsg(&nmsg->base, mycpuid + 1);
3291 static int
3292 ipfw_alt_swap_ruleset(uint8_t set1, uint8_t set2)
3294 struct netmsg_del dmsg;
3295 struct netmsg_base *nmsg;
3297 bzero(&dmsg, sizeof(dmsg));
3298 nmsg = &dmsg.base;
3299 netmsg_init(nmsg, NULL, &curthread->td_msgport,
3300 0, ipfw_alt_swap_ruleset_dispatch);
3301 dmsg.from_set = set1;
3302 dmsg.to_set = set2;
3304 netisr_domsg(nmsg, 0);
3305 return 0;
3309 * Remove all rules with given number, and also do set manipulation.
3311 * The argument is an uint32_t. The low 16 bit are the rule or set number,
3312 * the next 8 bits are the new set, the top 8 bits are the command:
3314 * 0 delete rules with given number
3315 * 1 delete rules with given set number
3316 * 2 move rules with given number to new set
3317 * 3 move rules with given set number to new set
3318 * 4 swap sets with given numbers
3320 static int
3321 ipfw_ctl_alter(uint32_t arg)
3323 uint16_t rulenum;
3324 uint8_t cmd, new_set;
3325 int error = 0;
3327 rulenum = arg & 0xffff;
3328 cmd = (arg >> 24) & 0xff;
3329 new_set = (arg >> 16) & 0xff;
3331 if (cmd > 4)
3332 return EINVAL;
3333 if (new_set >= IPFW_DEFAULT_SET)
3334 return EINVAL;
3335 if (cmd == 0 || cmd == 2) {
3336 if (rulenum == IPFW_DEFAULT_RULE)
3337 return EINVAL;
3338 } else {
3339 if (rulenum >= IPFW_DEFAULT_SET)
3340 return EINVAL;
3343 switch (cmd) {
3344 case 0: /* delete rules with given number */
3345 error = ipfw_alt_delete_rule(rulenum);
3346 break;
3348 case 1: /* delete all rules with given set number */
3349 error = ipfw_alt_delete_ruleset(rulenum);
3350 break;
3352 case 2: /* move rules with given number to new set */
3353 error = ipfw_alt_move_rule(rulenum, new_set);
3354 break;
3356 case 3: /* move rules with given set number to new set */
3357 error = ipfw_alt_move_ruleset(rulenum, new_set);
3358 break;
3360 case 4: /* swap two sets */
3361 error = ipfw_alt_swap_ruleset(rulenum, new_set);
3362 break;
3364 return error;
3368 * Clear counters for a specific rule.
3370 static void
3371 clear_counters(struct ip_fw *rule, int log_only)
3373 ipfw_insn_log *l = (ipfw_insn_log *)ACTION_PTR(rule);
3375 if (log_only == 0) {
3376 rule->bcnt = rule->pcnt = 0;
3377 rule->timestamp = 0;
3379 if (l->o.opcode == O_LOG)
3380 l->log_left = l->max_log;
3383 static void
3384 ipfw_zero_entry_dispatch(netmsg_t nmsg)
3386 struct netmsg_zent *zmsg = (struct netmsg_zent *)nmsg;
3387 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3388 struct ip_fw *rule;
3390 if (zmsg->rulenum == 0) {
3391 KKASSERT(zmsg->start_rule == NULL);
3393 ctx->ipfw_norule_counter = 0;
3394 for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next)
3395 clear_counters(rule, zmsg->log_only);
3396 } else {
3397 struct ip_fw *start = zmsg->start_rule;
3399 KKASSERT(start->cpuid == mycpuid);
3400 KKASSERT(start->rulenum == zmsg->rulenum);
3403 * We can have multiple rules with the same number, so we
3404 * need to clear them all.
3406 for (rule = start; rule && rule->rulenum == zmsg->rulenum;
3407 rule = rule->next)
3408 clear_counters(rule, zmsg->log_only);
3411 * Move to the position on the next CPU
3412 * before the msg is forwarded.
3414 zmsg->start_rule = start->sibling;
3416 netisr_forwardmsg(&nmsg->base, mycpuid + 1);
3420 * Reset some or all counters on firewall rules.
3421 * @arg frwl is null to clear all entries, or contains a specific
3422 * rule number.
3423 * @arg log_only is 1 if we only want to reset logs, zero otherwise.
3425 static int
3426 ipfw_ctl_zero_entry(int rulenum, int log_only)
3428 struct netmsg_zent zmsg;
3429 struct netmsg_base *nmsg;
3430 const char *msg;
3431 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3433 bzero(&zmsg, sizeof(zmsg));
3434 nmsg = &zmsg.base;
3435 netmsg_init(nmsg, NULL, &curthread->td_msgport,
3436 0, ipfw_zero_entry_dispatch);
3437 zmsg.log_only = log_only;
3439 if (rulenum == 0) {
3440 msg = log_only ? "ipfw: All logging counts reset.\n"
3441 : "ipfw: Accounting cleared.\n";
3442 } else {
3443 struct ip_fw *rule;
3446 * Locate the first rule with 'rulenum'
3448 for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next) {
3449 if (rule->rulenum == rulenum)
3450 break;
3452 if (rule == NULL) /* we did not find any matching rules */
3453 return (EINVAL);
3454 zmsg.start_rule = rule;
3455 zmsg.rulenum = rulenum;
3457 msg = log_only ? "ipfw: Entry %d logging count reset.\n"
3458 : "ipfw: Entry %d cleared.\n";
3460 netisr_domsg(nmsg, 0);
3461 KKASSERT(zmsg.start_rule == NULL);
3463 if (fw_verbose)
3464 log(LOG_SECURITY | LOG_NOTICE, msg, rulenum);
3465 return (0);
3469 * Check validity of the structure before insert.
3470 * Fortunately rules are simple, so this mostly need to check rule sizes.
3472 static int
3473 ipfw_check_ioc_rule(struct ipfw_ioc_rule *rule, int size, uint32_t *rule_flags)
3475 int l, cmdlen = 0;
3476 int have_action = 0;
3477 ipfw_insn *cmd;
3479 *rule_flags = 0;
3481 /* Check for valid size */
3482 if (size < sizeof(*rule)) {
3483 kprintf("ipfw: rule too short\n");
3484 return EINVAL;
3486 l = IOC_RULESIZE(rule);
3487 if (l != size) {
3488 kprintf("ipfw: size mismatch (have %d want %d)\n", size, l);
3489 return EINVAL;
3492 /* Check rule number */
3493 if (rule->rulenum == IPFW_DEFAULT_RULE) {
3494 kprintf("ipfw: invalid rule number\n");
3495 return EINVAL;
3499 * Now go for the individual checks. Very simple ones, basically only
3500 * instruction sizes.
3502 for (l = rule->cmd_len, cmd = rule->cmd; l > 0;
3503 l -= cmdlen, cmd += cmdlen) {
3504 cmdlen = F_LEN(cmd);
3505 if (cmdlen > l) {
3506 kprintf("ipfw: opcode %d size truncated\n",
3507 cmd->opcode);
3508 return EINVAL;
3511 DPRINTF("ipfw: opcode %d\n", cmd->opcode);
3513 if (cmd->opcode == O_KEEP_STATE || cmd->opcode == O_LIMIT) {
3514 /* This rule will create states */
3515 *rule_flags |= IPFW_RULE_F_STATE;
3518 switch (cmd->opcode) {
3519 case O_NOP:
3520 case O_PROBE_STATE:
3521 case O_KEEP_STATE:
3522 case O_PROTO:
3523 case O_IP_SRC_ME:
3524 case O_IP_DST_ME:
3525 case O_LAYER2:
3526 case O_IN:
3527 case O_FRAG:
3528 case O_IPOPT:
3529 case O_IPLEN:
3530 case O_IPID:
3531 case O_IPTOS:
3532 case O_IPPRECEDENCE:
3533 case O_IPTTL:
3534 case O_IPVER:
3535 case O_TCPWIN:
3536 case O_TCPFLAGS:
3537 case O_TCPOPTS:
3538 case O_ESTAB:
3539 if (cmdlen != F_INSN_SIZE(ipfw_insn))
3540 goto bad_size;
3541 break;
3543 case O_UID:
3544 case O_GID:
3545 case O_IP_SRC:
3546 case O_IP_DST:
3547 case O_TCPSEQ:
3548 case O_TCPACK:
3549 case O_PROB:
3550 case O_ICMPTYPE:
3551 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32))
3552 goto bad_size;
3553 break;
3555 case O_LIMIT:
3556 if (cmdlen != F_INSN_SIZE(ipfw_insn_limit))
3557 goto bad_size;
3558 break;
3560 case O_LOG:
3561 if (cmdlen != F_INSN_SIZE(ipfw_insn_log))
3562 goto bad_size;
3564 ((ipfw_insn_log *)cmd)->log_left =
3565 ((ipfw_insn_log *)cmd)->max_log;
3567 break;
3569 case O_IP_SRC_MASK:
3570 case O_IP_DST_MASK:
3571 if (cmdlen != F_INSN_SIZE(ipfw_insn_ip))
3572 goto bad_size;
3573 if (((ipfw_insn_ip *)cmd)->mask.s_addr == 0) {
3574 kprintf("ipfw: opcode %d, useless rule\n",
3575 cmd->opcode);
3576 return EINVAL;
3578 break;
3580 case O_IP_SRC_SET:
3581 case O_IP_DST_SET:
3582 if (cmd->arg1 == 0 || cmd->arg1 > 256) {
3583 kprintf("ipfw: invalid set size %d\n",
3584 cmd->arg1);
3585 return EINVAL;
3587 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
3588 (cmd->arg1+31)/32 )
3589 goto bad_size;
3590 break;
3592 case O_MACADDR2:
3593 if (cmdlen != F_INSN_SIZE(ipfw_insn_mac))
3594 goto bad_size;
3595 break;
3597 case O_MAC_TYPE:
3598 case O_IP_SRCPORT:
3599 case O_IP_DSTPORT: /* XXX artificial limit, 30 port pairs */
3600 if (cmdlen < 2 || cmdlen > 31)
3601 goto bad_size;
3602 break;
3604 case O_RECV:
3605 case O_XMIT:
3606 case O_VIA:
3607 if (cmdlen != F_INSN_SIZE(ipfw_insn_if))
3608 goto bad_size;
3609 break;
3611 case O_PIPE:
3612 case O_QUEUE:
3613 if (cmdlen != F_INSN_SIZE(ipfw_insn_pipe))
3614 goto bad_size;
3615 goto check_action;
3617 case O_FORWARD_IP:
3618 if (cmdlen != F_INSN_SIZE(ipfw_insn_sa)) {
3619 goto bad_size;
3620 } else {
3621 in_addr_t fwd_addr;
3623 fwd_addr = ((ipfw_insn_sa *)cmd)->
3624 sa.sin_addr.s_addr;
3625 if (IN_MULTICAST(ntohl(fwd_addr))) {
3626 kprintf("ipfw: try forwarding to "
3627 "multicast address\n");
3628 return EINVAL;
3631 goto check_action;
3633 case O_FORWARD_MAC: /* XXX not implemented yet */
3634 case O_CHECK_STATE:
3635 case O_COUNT:
3636 case O_ACCEPT:
3637 case O_DENY:
3638 case O_REJECT:
3639 case O_SKIPTO:
3640 case O_DIVERT:
3641 case O_TEE:
3642 if (cmdlen != F_INSN_SIZE(ipfw_insn))
3643 goto bad_size;
3644 check_action:
3645 if (have_action) {
3646 kprintf("ipfw: opcode %d, multiple actions"
3647 " not allowed\n",
3648 cmd->opcode);
3649 return EINVAL;
3651 have_action = 1;
3652 if (l != cmdlen) {
3653 kprintf("ipfw: opcode %d, action must be"
3654 " last opcode\n",
3655 cmd->opcode);
3656 return EINVAL;
3658 break;
3659 default:
3660 kprintf("ipfw: opcode %d, unknown opcode\n",
3661 cmd->opcode);
3662 return EINVAL;
3665 if (have_action == 0) {
3666 kprintf("ipfw: missing action\n");
3667 return EINVAL;
3669 return 0;
3671 bad_size:
3672 kprintf("ipfw: opcode %d size %d wrong\n",
3673 cmd->opcode, cmdlen);
3674 return EINVAL;
3677 static int
3678 ipfw_ctl_add_rule(struct sockopt *sopt)
3680 struct ipfw_ioc_rule *ioc_rule;
3681 size_t size;
3682 uint32_t rule_flags;
3683 int error;
3685 size = sopt->sopt_valsize;
3686 if (size > (sizeof(uint32_t) * IPFW_RULE_SIZE_MAX) ||
3687 size < sizeof(*ioc_rule)) {
3688 return EINVAL;
3690 if (size != (sizeof(uint32_t) * IPFW_RULE_SIZE_MAX)) {
3691 sopt->sopt_val = krealloc(sopt->sopt_val, sizeof(uint32_t) *
3692 IPFW_RULE_SIZE_MAX, M_TEMP, M_WAITOK);
3694 ioc_rule = sopt->sopt_val;
3696 error = ipfw_check_ioc_rule(ioc_rule, size, &rule_flags);
3697 if (error)
3698 return error;
3700 ipfw_add_rule(ioc_rule, rule_flags);
3702 if (sopt->sopt_dir == SOPT_GET)
3703 sopt->sopt_valsize = IOC_RULESIZE(ioc_rule);
3704 return 0;
3707 static void *
3708 ipfw_copy_rule(const struct ip_fw *rule, struct ipfw_ioc_rule *ioc_rule)
3710 const struct ip_fw *sibling;
3711 #ifdef INVARIANTS
3712 int i;
3713 #endif
3715 KKASSERT(rule->cpuid == IPFW_CFGCPUID);
3717 ioc_rule->act_ofs = rule->act_ofs;
3718 ioc_rule->cmd_len = rule->cmd_len;
3719 ioc_rule->rulenum = rule->rulenum;
3720 ioc_rule->set = rule->set;
3721 ioc_rule->usr_flags = rule->usr_flags;
3723 ioc_rule->set_disable = ipfw_ctx[mycpuid]->ipfw_set_disable;
3724 ioc_rule->static_count = static_count;
3725 ioc_rule->static_len = static_ioc_len;
3728 * Visit (read-only) all of the rule's duplications to get
3729 * the necessary statistics
3731 #ifdef INVARIANTS
3732 i = 0;
3733 #endif
3734 ioc_rule->pcnt = 0;
3735 ioc_rule->bcnt = 0;
3736 ioc_rule->timestamp = 0;
3737 for (sibling = rule; sibling != NULL; sibling = sibling->sibling) {
3738 ioc_rule->pcnt += sibling->pcnt;
3739 ioc_rule->bcnt += sibling->bcnt;
3740 if (sibling->timestamp > ioc_rule->timestamp)
3741 ioc_rule->timestamp = sibling->timestamp;
3742 #ifdef INVARIANTS
3743 ++i;
3744 #endif
3746 KASSERT(i == ncpus, ("static rule is not duplicated on every cpu"));
3748 bcopy(rule->cmd, ioc_rule->cmd, ioc_rule->cmd_len * 4 /* XXX */);
3750 return ((uint8_t *)ioc_rule + IOC_RULESIZE(ioc_rule));
3753 static void
3754 ipfw_copy_state(const ipfw_dyn_rule *dyn_rule,
3755 struct ipfw_ioc_state *ioc_state)
3757 const struct ipfw_flow_id *id;
3758 struct ipfw_ioc_flowid *ioc_id;
3760 ioc_state->expire = TIME_LEQ(dyn_rule->expire, time_second) ?
3761 0 : dyn_rule->expire - time_second;
3762 ioc_state->pcnt = dyn_rule->pcnt;
3763 ioc_state->bcnt = dyn_rule->bcnt;
3765 ioc_state->dyn_type = dyn_rule->dyn_type;
3766 ioc_state->count = dyn_rule->count;
3768 ioc_state->rulenum = dyn_rule->stub->rule[mycpuid]->rulenum;
3770 id = &dyn_rule->id;
3771 ioc_id = &ioc_state->id;
3773 ioc_id->type = ETHERTYPE_IP;
3774 ioc_id->u.ip.dst_ip = id->dst_ip;
3775 ioc_id->u.ip.src_ip = id->src_ip;
3776 ioc_id->u.ip.dst_port = id->dst_port;
3777 ioc_id->u.ip.src_port = id->src_port;
3778 ioc_id->u.ip.proto = id->proto;
3781 static int
3782 ipfw_ctl_get_rules(struct sockopt *sopt)
3784 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3785 struct ip_fw *rule;
3786 void *bp;
3787 size_t size;
3788 uint32_t dcount = 0;
3791 * pass up a copy of the current rules. Static rules
3792 * come first (the last of which has number IPFW_DEFAULT_RULE),
3793 * followed by a possibly empty list of dynamic rule.
3796 size = static_ioc_len; /* size of static rules */
3797 if (ipfw_dyn_v) { /* add size of dyn.rules */
3798 dcount = dyn_count;
3799 size += dcount * sizeof(struct ipfw_ioc_state);
3802 if (sopt->sopt_valsize < size) {
3803 /* short length, no need to return incomplete rules */
3804 /* XXX: if superuser, no need to zero buffer */
3805 bzero(sopt->sopt_val, sopt->sopt_valsize);
3806 return 0;
3808 bp = sopt->sopt_val;
3810 for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next)
3811 bp = ipfw_copy_rule(rule, bp);
3813 if (ipfw_dyn_v && dcount != 0) {
3814 struct ipfw_ioc_state *ioc_state = bp;
3815 uint32_t dcount2 = 0;
3816 #ifdef INVARIANTS
3817 size_t old_size = size;
3818 #endif
3819 int i;
3821 lockmgr(&dyn_lock, LK_SHARED);
3823 /* Check 'ipfw_dyn_v' again with lock held */
3824 if (ipfw_dyn_v == NULL)
3825 goto skip;
3827 for (i = 0; i < curr_dyn_buckets; i++) {
3828 ipfw_dyn_rule *p;
3831 * The # of dynamic rules may have grown after the
3832 * snapshot of 'dyn_count' was taken, so we will have
3833 * to check 'dcount' (snapshot of dyn_count) here to
3834 * make sure that we don't overflow the pre-allocated
3835 * buffer.
3837 for (p = ipfw_dyn_v[i]; p != NULL && dcount != 0;
3838 p = p->next, ioc_state++, dcount--, dcount2++)
3839 ipfw_copy_state(p, ioc_state);
3841 skip:
3842 lockmgr(&dyn_lock, LK_RELEASE);
3845 * The # of dynamic rules may be shrinked after the
3846 * snapshot of 'dyn_count' was taken. To give user a
3847 * correct dynamic rule count, we use the 'dcount2'
3848 * calculated above (with shared lockmgr lock held).
3850 size = static_ioc_len +
3851 (dcount2 * sizeof(struct ipfw_ioc_state));
3852 KKASSERT(size <= old_size);
3855 sopt->sopt_valsize = size;
3856 return 0;
3859 static void
3860 ipfw_set_disable_dispatch(netmsg_t nmsg)
3862 struct lwkt_msg *lmsg = &nmsg->lmsg;
3863 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3865 ctx->ipfw_gen++;
3866 ctx->ipfw_set_disable = lmsg->u.ms_result32;
3868 netisr_forwardmsg(&nmsg->base, mycpuid + 1);
3871 static void
3872 ipfw_ctl_set_disable(uint32_t disable, uint32_t enable)
3874 struct netmsg_base nmsg;
3875 struct lwkt_msg *lmsg;
3876 uint32_t set_disable;
3878 /* IPFW_DEFAULT_SET is always enabled */
3879 enable |= (1 << IPFW_DEFAULT_SET);
3880 set_disable = (ipfw_ctx[mycpuid]->ipfw_set_disable | disable) & ~enable;
3882 bzero(&nmsg, sizeof(nmsg));
3883 netmsg_init(&nmsg, NULL, &curthread->td_msgport,
3884 0, ipfw_set_disable_dispatch);
3885 lmsg = &nmsg.lmsg;
3886 lmsg->u.ms_result32 = set_disable;
3888 netisr_domsg(&nmsg, 0);
3892 * {set|get}sockopt parser.
3894 static int
3895 ipfw_ctl(struct sockopt *sopt)
3897 int error, rulenum;
3898 uint32_t *masks;
3899 size_t size;
3901 error = 0;
3903 switch (sopt->sopt_name) {
3904 case IP_FW_GET:
3905 error = ipfw_ctl_get_rules(sopt);
3906 break;
3908 case IP_FW_FLUSH:
3909 ipfw_flush(0 /* keep default rule */);
3910 break;
3912 case IP_FW_ADD:
3913 error = ipfw_ctl_add_rule(sopt);
3914 break;
3916 case IP_FW_DEL:
3918 * IP_FW_DEL is used for deleting single rules or sets,
3919 * and (ab)used to atomically manipulate sets.
3920 * Argument size is used to distinguish between the two:
3921 * sizeof(uint32_t)
3922 * delete single rule or set of rules,
3923 * or reassign rules (or sets) to a different set.
3924 * 2 * sizeof(uint32_t)
3925 * atomic disable/enable sets.
3926 * first uint32_t contains sets to be disabled,
3927 * second uint32_t contains sets to be enabled.
3929 masks = sopt->sopt_val;
3930 size = sopt->sopt_valsize;
3931 if (size == sizeof(*masks)) {
3933 * Delete or reassign static rule
3935 error = ipfw_ctl_alter(masks[0]);
3936 } else if (size == (2 * sizeof(*masks))) {
3938 * Set enable/disable
3940 ipfw_ctl_set_disable(masks[0], masks[1]);
3941 } else {
3942 error = EINVAL;
3944 break;
3946 case IP_FW_ZERO:
3947 case IP_FW_RESETLOG: /* argument is an int, the rule number */
3948 rulenum = 0;
3950 if (sopt->sopt_val != 0) {
3951 error = soopt_to_kbuf(sopt, &rulenum,
3952 sizeof(int), sizeof(int));
3953 if (error)
3954 break;
3956 error = ipfw_ctl_zero_entry(rulenum,
3957 sopt->sopt_name == IP_FW_RESETLOG);
3958 break;
3960 default:
3961 kprintf("ipfw_ctl invalid option %d\n", sopt->sopt_name);
3962 error = EINVAL;
3964 return error;
3968 * This procedure is only used to handle keepalives. It is invoked
3969 * every dyn_keepalive_period
3971 static void
3972 ipfw_tick_dispatch(netmsg_t nmsg)
3974 time_t keep_alive;
3975 uint32_t gen;
3976 int i;
3978 IPFW_ASSERT_CFGPORT(&curthread->td_msgport);
3979 KKASSERT(IPFW_LOADED);
3981 /* Reply ASAP */
3982 crit_enter();
3983 lwkt_replymsg(&nmsg->lmsg, 0);
3984 crit_exit();
3986 if (ipfw_dyn_v == NULL || dyn_count == 0)
3987 goto done;
3989 keep_alive = time_second;
3991 lockmgr(&dyn_lock, LK_EXCLUSIVE);
3992 again:
3993 if (ipfw_dyn_v == NULL || dyn_count == 0) {
3994 lockmgr(&dyn_lock, LK_RELEASE);
3995 goto done;
3997 gen = dyn_buckets_gen;
3999 for (i = 0; i < curr_dyn_buckets; i++) {
4000 ipfw_dyn_rule *q, *prev;
4002 for (prev = NULL, q = ipfw_dyn_v[i]; q != NULL;) {
4003 uint32_t ack_rev, ack_fwd;
4004 struct ipfw_flow_id id;
4006 if (q->dyn_type == O_LIMIT_PARENT)
4007 goto next;
4009 if (TIME_LEQ(q->expire, time_second)) {
4010 /* State expired */
4011 UNLINK_DYN_RULE(prev, ipfw_dyn_v[i], q);
4012 continue;
4016 * Keep alive processing
4019 if (!dyn_keepalive)
4020 goto next;
4021 if (q->id.proto != IPPROTO_TCP)
4022 goto next;
4023 if ((q->state & BOTH_SYN) != BOTH_SYN)
4024 goto next;
4025 if (TIME_LEQ(time_second + dyn_keepalive_interval,
4026 q->expire))
4027 goto next; /* too early */
4028 if (q->keep_alive == keep_alive)
4029 goto next; /* alreay done */
4032 * Save necessary information, so that they could
4033 * survive after possible blocking in send_pkt()
4035 id = q->id;
4036 ack_rev = q->ack_rev;
4037 ack_fwd = q->ack_fwd;
4039 /* Sending has been started */
4040 q->keep_alive = keep_alive;
4042 /* Release lock to avoid possible dead lock */
4043 lockmgr(&dyn_lock, LK_RELEASE);
4044 send_pkt(&id, ack_rev - 1, ack_fwd, TH_SYN);
4045 send_pkt(&id, ack_fwd - 1, ack_rev, 0);
4046 lockmgr(&dyn_lock, LK_EXCLUSIVE);
4048 if (gen != dyn_buckets_gen) {
4050 * Dyn bucket array has been changed during
4051 * the above two sending; reiterate.
4053 goto again;
4055 next:
4056 prev = q;
4057 q = q->next;
4060 lockmgr(&dyn_lock, LK_RELEASE);
4061 done:
4062 callout_reset(&ipfw_timeout_h, dyn_keepalive_period * hz,
4063 ipfw_tick, NULL);
4067 * This procedure is only used to handle keepalives. It is invoked
4068 * every dyn_keepalive_period
4070 static void
4071 ipfw_tick(void *dummy __unused)
4073 struct lwkt_msg *lmsg = &ipfw_timeout_netmsg.lmsg;
4075 KKASSERT(mycpuid == IPFW_CFGCPUID);
4077 crit_enter();
4079 KKASSERT(lmsg->ms_flags & MSGF_DONE);
4080 if (IPFW_LOADED) {
4081 lwkt_sendmsg_oncpu(IPFW_CFGPORT, lmsg);
4082 /* ipfw_timeout_netmsg's handler reset this callout */
4085 crit_exit();
4088 static int
4089 ipfw_check_in(void *arg, struct mbuf **m0, struct ifnet *ifp, int dir)
4091 struct ip_fw_args args;
4092 struct mbuf *m = *m0;
4093 struct m_tag *mtag;
4094 int tee = 0, error = 0, ret;
4096 if (m->m_pkthdr.fw_flags & DUMMYNET_MBUF_TAGGED) {
4097 /* Extract info from dummynet tag */
4098 mtag = m_tag_find(m, PACKET_TAG_DUMMYNET, NULL);
4099 KKASSERT(mtag != NULL);
4100 args.rule = ((struct dn_pkt *)m_tag_data(mtag))->dn_priv;
4101 KKASSERT(args.rule != NULL);
4103 m_tag_delete(m, mtag);
4104 m->m_pkthdr.fw_flags &= ~DUMMYNET_MBUF_TAGGED;
4105 } else {
4106 args.rule = NULL;
4109 args.eh = NULL;
4110 args.oif = NULL;
4111 args.m = m;
4112 ret = ipfw_chk(&args);
4113 m = args.m;
4115 if (m == NULL) {
4116 error = EACCES;
4117 goto back;
4120 switch (ret) {
4121 case IP_FW_PASS:
4122 break;
4124 case IP_FW_DENY:
4125 m_freem(m);
4126 m = NULL;
4127 error = EACCES;
4128 break;
4130 case IP_FW_DUMMYNET:
4131 /* Send packet to the appropriate pipe */
4132 ipfw_dummynet_io(m, args.cookie, DN_TO_IP_IN, &args);
4133 break;
4135 case IP_FW_TEE:
4136 tee = 1;
4137 /* FALL THROUGH */
4139 case IP_FW_DIVERT:
4141 * Must clear bridge tag when changing
4143 m->m_pkthdr.fw_flags &= ~BRIDGE_MBUF_TAGGED;
4144 if (ip_divert_p != NULL) {
4145 m = ip_divert_p(m, tee, 1);
4146 } else {
4147 m_freem(m);
4148 m = NULL;
4149 /* not sure this is the right error msg */
4150 error = EACCES;
4152 break;
4154 default:
4155 panic("unknown ipfw return value: %d", ret);
4157 back:
4158 *m0 = m;
4159 return error;
4162 static int
4163 ipfw_check_out(void *arg, struct mbuf **m0, struct ifnet *ifp, int dir)
4165 struct ip_fw_args args;
4166 struct mbuf *m = *m0;
4167 struct m_tag *mtag;
4168 int tee = 0, error = 0, ret;
4170 if (m->m_pkthdr.fw_flags & DUMMYNET_MBUF_TAGGED) {
4171 /* Extract info from dummynet tag */
4172 mtag = m_tag_find(m, PACKET_TAG_DUMMYNET, NULL);
4173 KKASSERT(mtag != NULL);
4174 args.rule = ((struct dn_pkt *)m_tag_data(mtag))->dn_priv;
4175 KKASSERT(args.rule != NULL);
4177 m_tag_delete(m, mtag);
4178 m->m_pkthdr.fw_flags &= ~DUMMYNET_MBUF_TAGGED;
4179 } else {
4180 args.rule = NULL;
4183 args.eh = NULL;
4184 args.m = m;
4185 args.oif = ifp;
4186 ret = ipfw_chk(&args);
4187 m = args.m;
4189 if (m == NULL) {
4190 error = EACCES;
4191 goto back;
4194 switch (ret) {
4195 case IP_FW_PASS:
4196 break;
4198 case IP_FW_DENY:
4199 m_freem(m);
4200 m = NULL;
4201 error = EACCES;
4202 break;
4204 case IP_FW_DUMMYNET:
4205 ipfw_dummynet_io(m, args.cookie, DN_TO_IP_OUT, &args);
4206 break;
4208 case IP_FW_TEE:
4209 tee = 1;
4210 /* FALL THROUGH */
4212 case IP_FW_DIVERT:
4213 if (ip_divert_p != NULL) {
4214 m = ip_divert_p(m, tee, 0);
4215 } else {
4216 m_freem(m);
4217 m = NULL;
4218 /* not sure this is the right error msg */
4219 error = EACCES;
4221 break;
4223 default:
4224 panic("unknown ipfw return value: %d", ret);
4226 back:
4227 *m0 = m;
4228 return error;
4231 static void
4232 ipfw_hook(void)
4234 struct pfil_head *pfh;
4236 IPFW_ASSERT_CFGPORT(&curthread->td_msgport);
4238 pfh = pfil_head_get(PFIL_TYPE_AF, AF_INET);
4239 if (pfh == NULL)
4240 return;
4242 pfil_add_hook(ipfw_check_in, NULL, PFIL_IN, pfh);
4243 pfil_add_hook(ipfw_check_out, NULL, PFIL_OUT, pfh);
4246 static void
4247 ipfw_dehook(void)
4249 struct pfil_head *pfh;
4251 IPFW_ASSERT_CFGPORT(&curthread->td_msgport);
4253 pfh = pfil_head_get(PFIL_TYPE_AF, AF_INET);
4254 if (pfh == NULL)
4255 return;
4257 pfil_remove_hook(ipfw_check_in, NULL, PFIL_IN, pfh);
4258 pfil_remove_hook(ipfw_check_out, NULL, PFIL_OUT, pfh);
4261 static void
4262 ipfw_sysctl_enable_dispatch(netmsg_t nmsg)
4264 struct lwkt_msg *lmsg = &nmsg->lmsg;
4265 int enable = lmsg->u.ms_result;
4267 if (fw_enable == enable)
4268 goto reply;
4270 fw_enable = enable;
4271 if (fw_enable)
4272 ipfw_hook();
4273 else
4274 ipfw_dehook();
4275 reply:
4276 lwkt_replymsg(lmsg, 0);
4279 static int
4280 ipfw_sysctl_enable(SYSCTL_HANDLER_ARGS)
4282 struct netmsg_base nmsg;
4283 struct lwkt_msg *lmsg;
4284 int enable, error;
4286 enable = fw_enable;
4287 error = sysctl_handle_int(oidp, &enable, 0, req);
4288 if (error || req->newptr == NULL)
4289 return error;
4291 netmsg_init(&nmsg, NULL, &curthread->td_msgport,
4292 0, ipfw_sysctl_enable_dispatch);
4293 lmsg = &nmsg.lmsg;
4294 lmsg->u.ms_result = enable;
4296 return lwkt_domsg(IPFW_CFGPORT, lmsg, 0);
4299 static int
4300 ipfw_sysctl_autoinc_step(SYSCTL_HANDLER_ARGS)
4302 return sysctl_int_range(oidp, arg1, arg2, req,
4303 IPFW_AUTOINC_STEP_MIN, IPFW_AUTOINC_STEP_MAX);
4306 static int
4307 ipfw_sysctl_dyn_buckets(SYSCTL_HANDLER_ARGS)
4309 int error, value;
4311 lockmgr(&dyn_lock, LK_EXCLUSIVE);
4313 value = dyn_buckets;
4314 error = sysctl_handle_int(oidp, &value, 0, req);
4315 if (error || !req->newptr)
4316 goto back;
4319 * Make sure we have a power of 2 and
4320 * do not allow more than 64k entries.
4322 error = EINVAL;
4323 if (value <= 1 || value > 65536)
4324 goto back;
4325 if ((value & (value - 1)) != 0)
4326 goto back;
4328 error = 0;
4329 dyn_buckets = value;
4330 back:
4331 lockmgr(&dyn_lock, LK_RELEASE);
4332 return error;
4335 static int
4336 ipfw_sysctl_dyn_fin(SYSCTL_HANDLER_ARGS)
4338 return sysctl_int_range(oidp, arg1, arg2, req,
4339 1, dyn_keepalive_period - 1);
4342 static int
4343 ipfw_sysctl_dyn_rst(SYSCTL_HANDLER_ARGS)
4345 return sysctl_int_range(oidp, arg1, arg2, req,
4346 1, dyn_keepalive_period - 1);
4349 static void
4350 ipfw_ctx_init_dispatch(netmsg_t nmsg)
4352 struct netmsg_ipfw *fwmsg = (struct netmsg_ipfw *)nmsg;
4353 struct ipfw_context *ctx;
4354 struct ip_fw *def_rule;
4356 ctx = kmalloc(sizeof(*ctx), M_IPFW, M_WAITOK | M_ZERO);
4357 ipfw_ctx[mycpuid] = ctx;
4359 def_rule = kmalloc(sizeof(*def_rule), M_IPFW, M_WAITOK | M_ZERO);
4361 def_rule->act_ofs = 0;
4362 def_rule->rulenum = IPFW_DEFAULT_RULE;
4363 def_rule->cmd_len = 1;
4364 def_rule->set = IPFW_DEFAULT_SET;
4366 def_rule->cmd[0].len = 1;
4367 #ifdef IPFIREWALL_DEFAULT_TO_ACCEPT
4368 def_rule->cmd[0].opcode = O_ACCEPT;
4369 #else
4370 if (filters_default_to_accept)
4371 def_rule->cmd[0].opcode = O_ACCEPT;
4372 else
4373 def_rule->cmd[0].opcode = O_DENY;
4374 #endif
4376 def_rule->refcnt = 1;
4377 def_rule->cpuid = mycpuid;
4379 /* Install the default rule */
4380 ctx->ipfw_default_rule = def_rule;
4381 ctx->ipfw_layer3_chain = def_rule;
4383 /* Link rule CPU sibling */
4384 ipfw_link_sibling(fwmsg, def_rule);
4386 /* Statistics only need to be updated once */
4387 if (mycpuid == 0)
4388 ipfw_inc_static_count(def_rule);
4390 netisr_forwardmsg(&nmsg->base, mycpuid + 1);
4393 static void
4394 ipfw_init_dispatch(netmsg_t nmsg)
4396 struct netmsg_ipfw fwmsg;
4397 int error = 0;
4399 if (IPFW_LOADED) {
4400 kprintf("IP firewall already loaded\n");
4401 error = EEXIST;
4402 goto reply;
4405 bzero(&fwmsg, sizeof(fwmsg));
4406 netmsg_init(&fwmsg.base, NULL, &curthread->td_msgport,
4407 0, ipfw_ctx_init_dispatch);
4408 netisr_domsg(&fwmsg.base, 0);
4410 ip_fw_chk_ptr = ipfw_chk;
4411 ip_fw_ctl_ptr = ipfw_ctl;
4412 ip_fw_dn_io_ptr = ipfw_dummynet_io;
4414 kprintf("ipfw2 initialized, default to %s, logging ",
4415 ipfw_ctx[mycpuid]->ipfw_default_rule->cmd[0].opcode ==
4416 O_ACCEPT ? "accept" : "deny");
4418 #ifdef IPFIREWALL_VERBOSE
4419 fw_verbose = 1;
4420 #endif
4421 #ifdef IPFIREWALL_VERBOSE_LIMIT
4422 verbose_limit = IPFIREWALL_VERBOSE_LIMIT;
4423 #endif
4424 if (fw_verbose == 0) {
4425 kprintf("disabled\n");
4426 } else if (verbose_limit == 0) {
4427 kprintf("unlimited\n");
4428 } else {
4429 kprintf("limited to %d packets/entry by default\n",
4430 verbose_limit);
4433 callout_init_mp(&ipfw_timeout_h);
4434 netmsg_init(&ipfw_timeout_netmsg, NULL, &netisr_adone_rport,
4435 MSGF_DROPABLE | MSGF_PRIORITY,
4436 ipfw_tick_dispatch);
4437 lockinit(&dyn_lock, "ipfw_dyn", 0, 0);
4439 ip_fw_loaded = 1;
4440 callout_reset(&ipfw_timeout_h, hz, ipfw_tick, NULL);
4442 if (fw_enable)
4443 ipfw_hook();
4444 reply:
4445 lwkt_replymsg(&nmsg->lmsg, error);
4448 static int
4449 ipfw_init(void)
4451 struct netmsg_base smsg;
4453 netmsg_init(&smsg, NULL, &curthread->td_msgport,
4454 0, ipfw_init_dispatch);
4455 return lwkt_domsg(IPFW_CFGPORT, &smsg.lmsg, 0);
4458 #ifdef KLD_MODULE
4460 static void
4461 ipfw_fini_dispatch(netmsg_t nmsg)
4463 int error = 0, cpu;
4465 if (ipfw_refcnt != 0) {
4466 error = EBUSY;
4467 goto reply;
4470 ip_fw_loaded = 0;
4472 ipfw_dehook();
4473 callout_stop(&ipfw_timeout_h);
4475 netmsg_service_sync();
4477 crit_enter();
4478 lwkt_dropmsg(&ipfw_timeout_netmsg.lmsg);
4479 crit_exit();
4481 ip_fw_chk_ptr = NULL;
4482 ip_fw_ctl_ptr = NULL;
4483 ip_fw_dn_io_ptr = NULL;
4484 ipfw_flush(1 /* kill default rule */);
4486 /* Free pre-cpu context */
4487 for (cpu = 0; cpu < ncpus; ++cpu)
4488 kfree(ipfw_ctx[cpu], M_IPFW);
4490 kprintf("IP firewall unloaded\n");
4491 reply:
4492 lwkt_replymsg(&nmsg->lmsg, error);
4495 static int
4496 ipfw_fini(void)
4498 struct netmsg_base smsg;
4500 netmsg_init(&smsg, NULL, &curthread->td_msgport,
4501 0, ipfw_fini_dispatch);
4502 return lwkt_domsg(IPFW_CFGPORT, &smsg.lmsg, 0);
4505 #endif /* KLD_MODULE */
4507 static int
4508 ipfw_modevent(module_t mod, int type, void *unused)
4510 int err = 0;
4512 switch (type) {
4513 case MOD_LOAD:
4514 err = ipfw_init();
4515 break;
4517 case MOD_UNLOAD:
4518 #ifndef KLD_MODULE
4519 kprintf("ipfw statically compiled, cannot unload\n");
4520 err = EBUSY;
4521 #else
4522 err = ipfw_fini();
4523 #endif
4524 break;
4525 default:
4526 break;
4528 return err;
4531 static moduledata_t ipfwmod = {
4532 "ipfw",
4533 ipfw_modevent,
4536 DECLARE_MODULE(ipfw, ipfwmod, SI_SUB_PROTO_END, SI_ORDER_ANY);
4537 MODULE_VERSION(ipfw, 1);