Update comment
[dragonfly.git] / sys / net / ipfw / ip_fw2.c
1 /*
2  * Copyright (c) 2002 Luigi Rizzo, Universita` di Pisa
3  *
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.
12  *
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.
24  *
25  * $FreeBSD: src/sys/netinet/ip_fw2.c,v 1.6.2.12 2003/04/08 10:42:32 maxim Exp $
26  * $DragonFly: src/sys/net/ipfw/ip_fw2.c,v 1.94 2008/09/19 12:23:56 sephe Exp $
27  */
28
29 /*
30  * Implement IP packet firewall (new version)
31  */
32
33 #include "opt_ipfw.h"
34 #include "opt_inet.h"
35 #ifndef INET
36 #error IPFIREWALL requires INET.
37 #endif /* INET */
38
39 #include <sys/param.h>
40 #include <sys/systm.h>
41 #include <sys/malloc.h>
42 #include <sys/mbuf.h>
43 #include <sys/kernel.h>
44 #include <sys/proc.h>
45 #include <sys/socket.h>
46 #include <sys/socketvar.h>
47 #include <sys/sysctl.h>
48 #include <sys/syslog.h>
49 #include <sys/thread2.h>
50 #include <sys/ucred.h>
51 #include <sys/in_cksum.h>
52 #include <sys/lock.h>
53
54 #include <net/if.h>
55 #include <net/route.h>
56 #include <net/netmsg2.h>
57 #include <net/pfil.h>
58 #include <net/dummynet/ip_dummynet.h>
59
60 #include <netinet/in.h>
61 #include <netinet/in_systm.h>
62 #include <netinet/in_var.h>
63 #include <netinet/in_pcb.h>
64 #include <netinet/ip.h>
65 #include <netinet/ip_var.h>
66 #include <netinet/ip_icmp.h>
67 #include <netinet/tcp.h>
68 #include <netinet/tcp_timer.h>
69 #include <netinet/tcp_var.h>
70 #include <netinet/tcpip.h>
71 #include <netinet/udp.h>
72 #include <netinet/udp_var.h>
73 #include <netinet/ip_divert.h>
74 #include <netinet/if_ether.h> /* XXX for ETHERTYPE_IP */
75
76 #include <net/ipfw/ip_fw2.h>
77
78 #ifdef IPFIREWALL_DEBUG
79 #define DPRINTF(fmt, ...) \
80 do { \
81         if (fw_debug > 0) \
82                 kprintf(fmt, __VA_ARGS__); \
83 } while (0)
84 #else
85 #define DPRINTF(fmt, ...)       ((void)0)
86 #endif
87
88 /*
89  * Description about per-CPU rule duplication:
90  *
91  * Module loading/unloading and all ioctl operations are serialized
92  * by netisr0, so we don't have any ordering or locking problems.
93  *
94  * Following graph shows how operation on per-CPU rule list is
95  * performed [2 CPU case]:
96  *
97  *   CPU0                 CPU1
98  *
99  * netisr0 <------------------------------------+
100  *  domsg                                       |
101  *    |                                         |
102  *    | netmsg                                  |
103  *    |                                         |
104  *    V                                         |
105  *  ifnet0                                      |
106  *    :                                         | netmsg
107  *    :(delete/add...)                          |
108  *    :                                         |
109  *    :         netmsg                          |
110  *  forwardmsg---------->ifnet1                 |
111  *                          :                   |
112  *                          :(delete/add...)    |
113  *                          :                   |
114  *                          :                   |
115  *                        replymsg--------------+
116  *
117  *
118  *
119  *
120  * Rules which will not create states (dyn rules) [2 CPU case]
121  *
122  *    CPU0               CPU1
123  * layer3_chain       layer3_chain
124  *     |                  |
125  *     V                  V
126  * +-------+ sibling  +-------+ sibling
127  * | rule1 |--------->| rule1 |--------->NULL
128  * +-------+          +-------+
129  *     |                  |
130  *     |next              |next
131  *     V                  V
132  * +-------+ sibling  +-------+ sibling
133  * | rule2 |--------->| rule2 |--------->NULL
134  * +-------+          +-------+
135  *
136  * ip_fw.sibling:
137  * 1) Ease statistics calculation during IP_FW_GET.  We only need to
138  *    iterate layer3_chain on CPU0; the current rule's duplication on
139  *    the other CPUs could safely be read-only accessed by using
140  *    ip_fw.sibling
141  * 2) Accelerate rule insertion and deletion, e.g. rule insertion:
142  *    a) In netisr0 (on CPU0) rule3 is determined to be inserted between
143  *       rule1 and rule2.  To make this decision we need to iterate the
144  *       layer3_chain on CPU0.  The netmsg, which is used to insert the
145  *       rule, will contain rule1 on CPU0 as prev_rule and rule2 on CPU0
146  *       as next_rule
147  *    b) After the insertion on CPU0 is done, we will move on to CPU1.
148  *       But instead of relocating the rule3's position on CPU1 by
149  *       iterating the layer3_chain on CPU1, we set the netmsg's prev_rule
150  *       to rule1->sibling and next_rule to rule2->sibling before the
151  *       netmsg is forwarded to CPU1 from CPU0
152  *       
153  *    
154  *
155  * Rules which will create states (dyn rules) [2 CPU case]
156  * (unnecessary parts are omitted; they are same as in the previous figure)
157  *
158  *   CPU0                       CPU1
159  * 
160  * +-------+                  +-------+
161  * | rule1 |                  | rule1 |
162  * +-------+                  +-------+
163  *   ^   |                      |   ^
164  *   |   |stub              stub|   |
165  *   |   |                      |   |
166  *   |   +----+            +----+   |
167  *   |        |            |        |
168  *   |        V            V        |
169  *   |    +--------------------+    |
170  *   |    |     rule_stub      |    |
171  *   |    | (read-only shared) |    |
172  *   |    |                    |    |
173  *   |    | back pointer array |    |
174  *   |    | (indexed by cpuid) |    |
175  *   |    |                    |    |
176  *   +----|---------[0]        |    |
177  *        |         [1]--------|----+
178  *        |                    |
179  *        +--------------------+
180  *          ^            ^
181  *          |            |
182  *  ........|............|............
183  *  :       |            |           :
184  *  :       |stub        |stub       :
185  *  :       |            |           :
186  *  :  +---------+  +---------+      :
187  *  :  | state1a |  | state1b | .... :
188  *  :  +---------+  +---------+      :
189  *  :                                :
190  *  :           states table         :
191  *  :            (shared)            :
192  *  :      (protected by dyn_lock)   :
193  *  ..................................
194  * 
195  * [state1a and state1b are states created by rule1]
196  *
197  * ip_fw_stub:
198  * This structure is introduced so that shared (locked) state table could
199  * work with per-CPU (duplicated) static rules.  It mainly bridges states
200  * and static rules and serves as static rule's place holder (a read-only
201  * shared part of duplicated rules) from states point of view.
202  *
203  * IPFW_RULE_F_STATE (only for rules which create states):
204  * o  During rule installation, this flag is turned on after rule's
205  *    duplications reach all CPUs, to avoid at least following race:
206  *    1) rule1 is duplicated on CPU0 and is not duplicated on CPU1 yet
207  *    2) rule1 creates state1
208  *    3) state1 is located on CPU1 by check-state
209  *    But rule1 is not duplicated on CPU1 yet
210  * o  During rule deletion, this flag is turned off before deleting states
211  *    created by the rule and before deleting the rule itself, so no
212  *    more states will be created by the to-be-deleted rule even when its
213  *    duplication on certain CPUs are not eliminated yet.
214  */
215
216 #define IPFW_AUTOINC_STEP_MIN   1
217 #define IPFW_AUTOINC_STEP_MAX   1000
218 #define IPFW_AUTOINC_STEP_DEF   100
219
220 #define IPFW_DEFAULT_RULE       65535   /* rulenum for the default rule */
221 #define IPFW_DEFAULT_SET        31      /* set number for the default rule */
222
223 struct netmsg_ipfw {
224         struct netmsg   nmsg;
225         const struct ipfw_ioc_rule *ioc_rule;
226         struct ip_fw    *next_rule;
227         struct ip_fw    *prev_rule;
228         struct ip_fw    *sibling;
229         struct ip_fw_stub *stub;
230 };
231
232 struct netmsg_del {
233         struct netmsg   nmsg;
234         struct ip_fw    *start_rule;
235         struct ip_fw    *prev_rule;
236         uint16_t        rulenum;
237         uint8_t         from_set;
238         uint8_t         to_set;
239 };
240
241 struct netmsg_zent {
242         struct netmsg   nmsg;
243         struct ip_fw    *start_rule;
244         uint16_t        rulenum;
245         uint16_t        log_only;
246 };
247
248 struct ipfw_context {
249         struct ip_fw    *ipfw_layer3_chain;     /* list of rules for layer3 */
250         struct ip_fw    *ipfw_default_rule;     /* default rule */
251         uint64_t        ipfw_norule_counter;    /* counter for ipfw_log(NULL) */
252
253         /*
254          * ipfw_set_disable contains one bit per set value (0..31).
255          * If the bit is set, all rules with the corresponding set
256          * are disabled.  Set IPDW_DEFAULT_SET is reserved for the
257          * default rule and CANNOT be disabled.
258          */
259         uint32_t        ipfw_set_disable;
260         uint32_t        ipfw_gen;               /* generation of rule list */
261 };
262
263 static struct ipfw_context      *ipfw_ctx[MAXCPU];
264
265 #ifdef KLD_MODULE
266 /*
267  * Module can not be unloaded, if there are references to
268  * certains rules of ipfw(4), e.g. dummynet(4)
269  */
270 static int ipfw_refcnt;
271 #endif
272
273 MALLOC_DEFINE(M_IPFW, "IpFw/IpAcct", "IpFw/IpAcct chain's");
274
275 /*
276  * Following two global variables are accessed and
277  * updated only on CPU0
278  */
279 static uint32_t static_count;   /* # of static rules */
280 static uint32_t static_ioc_len; /* bytes of static rules */
281
282 /*
283  * If 1, then ipfw static rules are being flushed,
284  * ipfw_chk() will skip to the default rule.
285  */
286 static int ipfw_flushing;
287
288 static int fw_verbose;
289 static int verbose_limit;
290
291 static int fw_debug;
292 static int autoinc_step = IPFW_AUTOINC_STEP_DEF;
293
294 static int      ipfw_sysctl_enable(SYSCTL_HANDLER_ARGS);
295 static int      ipfw_sysctl_autoinc_step(SYSCTL_HANDLER_ARGS);
296 static int      ipfw_sysctl_dyn_buckets(SYSCTL_HANDLER_ARGS);
297 static int      ipfw_sysctl_dyn_fin(SYSCTL_HANDLER_ARGS);
298 static int      ipfw_sysctl_dyn_rst(SYSCTL_HANDLER_ARGS);
299
300 SYSCTL_NODE(_net_inet_ip, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall");
301 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, enable, CTLTYPE_INT | CTLFLAG_RW,
302     &fw_enable, 0, ipfw_sysctl_enable, "I", "Enable ipfw");
303 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, autoinc_step, CTLTYPE_INT | CTLFLAG_RW,
304     &autoinc_step, 0, ipfw_sysctl_autoinc_step, "I",
305     "Rule number autincrement step");
306 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO,one_pass,CTLFLAG_RW,
307     &fw_one_pass, 0,
308     "Only do a single pass through ipfw when using dummynet(4)");
309 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, debug, CTLFLAG_RW,
310     &fw_debug, 0, "Enable printing of debug ip_fw statements");
311 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose, CTLFLAG_RW,
312     &fw_verbose, 0, "Log matches to ipfw rules");
313 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose_limit, CTLFLAG_RW,
314     &verbose_limit, 0, "Set upper limit of matches of ipfw rules logged");
315
316 /*
317  * Description of dynamic rules.
318  *
319  * Dynamic rules are stored in lists accessed through a hash table
320  * (ipfw_dyn_v) whose size is curr_dyn_buckets. This value can
321  * be modified through the sysctl variable dyn_buckets which is
322  * updated when the table becomes empty.
323  *
324  * XXX currently there is only one list, ipfw_dyn.
325  *
326  * When a packet is received, its address fields are first masked
327  * with the mask defined for the rule, then hashed, then matched
328  * against the entries in the corresponding list.
329  * Dynamic rules can be used for different purposes:
330  *  + stateful rules;
331  *  + enforcing limits on the number of sessions;
332  *  + in-kernel NAT (not implemented yet)
333  *
334  * The lifetime of dynamic rules is regulated by dyn_*_lifetime,
335  * measured in seconds and depending on the flags.
336  *
337  * The total number of dynamic rules is stored in dyn_count.
338  * The max number of dynamic rules is dyn_max. When we reach
339  * the maximum number of rules we do not create anymore. This is
340  * done to avoid consuming too much memory, but also too much
341  * time when searching on each packet (ideally, we should try instead
342  * to put a limit on the length of the list on each bucket...).
343  *
344  * Each dynamic rule holds a pointer to the parent ipfw rule so
345  * we know what action to perform. Dynamic rules are removed when
346  * the parent rule is deleted. XXX we should make them survive.
347  *
348  * There are some limitations with dynamic rules -- we do not
349  * obey the 'randomized match', and we do not do multiple
350  * passes through the firewall. XXX check the latter!!!
351  *
352  * NOTE about the SHARED LOCKMGR LOCK during dynamic rule looking up:
353  * Only TCP state transition will change dynamic rule's state and ack
354  * sequences, while all packets of one TCP connection only goes through
355  * one TCP thread, so it is safe to use shared lockmgr lock during dynamic
356  * rule looking up.  The keep alive callout uses exclusive lockmgr lock
357  * when it tries to find suitable dynamic rules to send keep alive, so
358  * it will not see half updated state and ack sequences.  Though the expire
359  * field updating looks racy for other protocols, the resolution (second)
360  * of expire field makes this kind of race harmless.
361  * XXX statistics' updating is _not_ MPsafe!!!
362  * XXX once UDP output path is fixed, we could use lockless dynamic rule
363  *     hash table
364  */
365 static ipfw_dyn_rule **ipfw_dyn_v = NULL;
366 static uint32_t dyn_buckets = 256; /* must be power of 2 */
367 static uint32_t curr_dyn_buckets = 256; /* must be power of 2 */
368 static uint32_t dyn_buckets_gen; /* generation of dyn buckets array */
369 static struct lock dyn_lock; /* dynamic rules' hash table lock */
370 static struct callout ipfw_timeout_h;
371
372 /*
373  * Timeouts for various events in handing dynamic rules.
374  */
375 static uint32_t dyn_ack_lifetime = 300;
376 static uint32_t dyn_syn_lifetime = 20;
377 static uint32_t dyn_fin_lifetime = 1;
378 static uint32_t dyn_rst_lifetime = 1;
379 static uint32_t dyn_udp_lifetime = 10;
380 static uint32_t dyn_short_lifetime = 5;
381
382 /*
383  * Keepalives are sent if dyn_keepalive is set. They are sent every
384  * dyn_keepalive_period seconds, in the last dyn_keepalive_interval
385  * seconds of lifetime of a rule.
386  * dyn_rst_lifetime and dyn_fin_lifetime should be strictly lower
387  * than dyn_keepalive_period.
388  */
389
390 static uint32_t dyn_keepalive_interval = 20;
391 static uint32_t dyn_keepalive_period = 5;
392 static uint32_t dyn_keepalive = 1;      /* do send keepalives */
393
394 static uint32_t dyn_count;              /* # of dynamic rules */
395 static uint32_t dyn_max = 4096;         /* max # of dynamic rules */
396
397 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, dyn_buckets, CTLTYPE_INT | CTLFLAG_RW,
398     &dyn_buckets, 0, ipfw_sysctl_dyn_buckets, "I", "Number of dyn. buckets");
399 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, curr_dyn_buckets, CTLFLAG_RD,
400     &curr_dyn_buckets, 0, "Current Number of dyn. buckets");
401 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_count, CTLFLAG_RD,
402     &dyn_count, 0, "Number of dyn. rules");
403 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_max, CTLFLAG_RW,
404     &dyn_max, 0, "Max number of dyn. rules");
405 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, static_count, CTLFLAG_RD,
406     &static_count, 0, "Number of static rules");
407 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_ack_lifetime, CTLFLAG_RW,
408     &dyn_ack_lifetime, 0, "Lifetime of dyn. rules for acks");
409 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_syn_lifetime, CTLFLAG_RW,
410     &dyn_syn_lifetime, 0, "Lifetime of dyn. rules for syn");
411 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, dyn_fin_lifetime,
412     CTLTYPE_INT | CTLFLAG_RW, &dyn_fin_lifetime, 0, ipfw_sysctl_dyn_fin, "I",
413     "Lifetime of dyn. rules for fin");
414 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, dyn_rst_lifetime,
415     CTLTYPE_INT | CTLFLAG_RW, &dyn_rst_lifetime, 0, ipfw_sysctl_dyn_rst, "I",
416     "Lifetime of dyn. rules for rst");
417 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_udp_lifetime, CTLFLAG_RW,
418     &dyn_udp_lifetime, 0, "Lifetime of dyn. rules for UDP");
419 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_short_lifetime, CTLFLAG_RW,
420     &dyn_short_lifetime, 0, "Lifetime of dyn. rules for other situations");
421 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_keepalive, CTLFLAG_RW,
422     &dyn_keepalive, 0, "Enable keepalives for dyn. rules");
423
424 static ip_fw_chk_t      ipfw_chk;
425
426 static __inline int
427 ipfw_free_rule(struct ip_fw *rule)
428 {
429         KASSERT(rule->cpuid == mycpuid, ("rule freed on cpu%d\n", mycpuid));
430         KASSERT(rule->refcnt > 0, ("invalid refcnt %u\n", rule->refcnt));
431         rule->refcnt--;
432         if (rule->refcnt == 0) {
433                 kfree(rule, M_IPFW);
434                 return 1;
435         }
436         return 0;
437 }
438
439 static void
440 ipfw_unref_rule(void *priv)
441 {
442         ipfw_free_rule(priv);
443 #ifdef KLD_MODULE
444         atomic_subtract_int(&ipfw_refcnt, 1);
445 #endif
446 }
447
448 static __inline void
449 ipfw_ref_rule(struct ip_fw *rule)
450 {
451         KASSERT(rule->cpuid == mycpuid, ("rule used on cpu%d\n", mycpuid));
452 #ifdef KLD_MODULE
453         atomic_add_int(&ipfw_refcnt, 1);
454 #endif
455         rule->refcnt++;
456 }
457
458 /*
459  * This macro maps an ip pointer into a layer3 header pointer of type T
460  */
461 #define L3HDR(T, ip) ((T *)((uint32_t *)(ip) + (ip)->ip_hl))
462
463 static __inline int
464 icmptype_match(struct ip *ip, ipfw_insn_u32 *cmd)
465 {
466         int type = L3HDR(struct icmp,ip)->icmp_type;
467
468         return (type <= ICMP_MAXTYPE && (cmd->d[0] & (1 << type)));
469 }
470
471 #define TT      ((1 << ICMP_ECHO) | \
472                  (1 << ICMP_ROUTERSOLICIT) | \
473                  (1 << ICMP_TSTAMP) | \
474                  (1 << ICMP_IREQ) | \
475                  (1 << ICMP_MASKREQ))
476
477 static int
478 is_icmp_query(struct ip *ip)
479 {
480         int type = L3HDR(struct icmp, ip)->icmp_type;
481
482         return (type <= ICMP_MAXTYPE && (TT & (1 << type)));
483 }
484
485 #undef TT
486
487 /*
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].
491  *
492  * We scan options and store the bits we find set. We succeed if
493  *
494  *      (want_set & ~bits) == 0 && (want_clear & ~bits) == want_clear
495  *
496  * The code is sometimes optimized not to store additional variables.
497  */
498
499 static int
500 flags_match(ipfw_insn *cmd, uint8_t bits)
501 {
502         u_char want_clear;
503         bits = ~bits;
504
505         if (((cmd->arg1 & 0xff) & bits) != 0)
506                 return 0; /* some bits we want set were clear */
507
508         want_clear = (cmd->arg1 >> 8) & 0xff;
509         if ((want_clear & bits) != want_clear)
510                 return 0; /* some bits we want clear were set */
511         return 1;
512 }
513
514 static int
515 ipopts_match(struct ip *ip, ipfw_insn *cmd)
516 {
517         int optlen, bits = 0;
518         u_char *cp = (u_char *)(ip + 1);
519         int x = (ip->ip_hl << 2) - sizeof(struct ip);
520
521         for (; x > 0; x -= optlen, cp += optlen) {
522                 int opt = cp[IPOPT_OPTVAL];
523
524                 if (opt == IPOPT_EOL)
525                         break;
526
527                 if (opt == IPOPT_NOP) {
528                         optlen = 1;
529                 } else {
530                         optlen = cp[IPOPT_OLEN];
531                         if (optlen <= 0 || optlen > x)
532                                 return 0; /* invalid or truncated */
533                 }
534
535                 switch (opt) {
536                 case IPOPT_LSRR:
537                         bits |= IP_FW_IPOPT_LSRR;
538                         break;
539
540                 case IPOPT_SSRR:
541                         bits |= IP_FW_IPOPT_SSRR;
542                         break;
543
544                 case IPOPT_RR:
545                         bits |= IP_FW_IPOPT_RR;
546                         break;
547
548                 case IPOPT_TS:
549                         bits |= IP_FW_IPOPT_TS;
550                         break;
551
552                 default:
553                         break;
554                 }
555         }
556         return (flags_match(cmd, bits));
557 }
558
559 static int
560 tcpopts_match(struct ip *ip, ipfw_insn *cmd)
561 {
562         int optlen, bits = 0;
563         struct tcphdr *tcp = L3HDR(struct tcphdr,ip);
564         u_char *cp = (u_char *)(tcp + 1);
565         int x = (tcp->th_off << 2) - sizeof(struct tcphdr);
566
567         for (; x > 0; x -= optlen, cp += optlen) {
568                 int opt = cp[0];
569
570                 if (opt == TCPOPT_EOL)
571                         break;
572
573                 if (opt == TCPOPT_NOP) {
574                         optlen = 1;
575                 } else {
576                         optlen = cp[1];
577                         if (optlen <= 0)
578                                 break;
579                 }
580
581                 switch (opt) {
582                 case TCPOPT_MAXSEG:
583                         bits |= IP_FW_TCPOPT_MSS;
584                         break;
585
586                 case TCPOPT_WINDOW:
587                         bits |= IP_FW_TCPOPT_WINDOW;
588                         break;
589
590                 case TCPOPT_SACK_PERMITTED:
591                 case TCPOPT_SACK:
592                         bits |= IP_FW_TCPOPT_SACK;
593                         break;
594
595                 case TCPOPT_TIMESTAMP:
596                         bits |= IP_FW_TCPOPT_TS;
597                         break;
598
599                 case TCPOPT_CC:
600                 case TCPOPT_CCNEW:
601                 case TCPOPT_CCECHO:
602                         bits |= IP_FW_TCPOPT_CC;
603                         break;
604
605                 default:
606                         break;
607                 }
608         }
609         return (flags_match(cmd, bits));
610 }
611
612 static int
613 iface_match(struct ifnet *ifp, ipfw_insn_if *cmd)
614 {
615         if (ifp == NULL)        /* no iface with this packet, match fails */
616                 return 0;
617
618         /* Check by name or by IP address */
619         if (cmd->name[0] != '\0') { /* match by name */
620                 /* Check name */
621                 if (cmd->p.glob) {
622                         if (kfnmatch(cmd->name, ifp->if_xname, 0) == 0)
623                                 return(1);
624                 } else {
625                         if (strncmp(ifp->if_xname, cmd->name, IFNAMSIZ) == 0)
626                                 return(1);
627                 }
628         } else {
629                 struct ifaddr_container *ifac;
630
631                 TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
632                         struct ifaddr *ia = ifac->ifa;
633
634                         if (ia->ifa_addr == NULL)
635                                 continue;
636                         if (ia->ifa_addr->sa_family != AF_INET)
637                                 continue;
638                         if (cmd->p.ip.s_addr == ((struct sockaddr_in *)
639                             (ia->ifa_addr))->sin_addr.s_addr)
640                                 return(1);      /* match */
641                 }
642         }
643         return(0);      /* no match, fail ... */
644 }
645
646 #define SNPARGS(buf, len) buf + len, sizeof(buf) > len ? sizeof(buf) - len : 0
647
648 /*
649  * We enter here when we have a rule with O_LOG.
650  * XXX this function alone takes about 2Kbytes of code!
651  */
652 static void
653 ipfw_log(struct ip_fw *f, u_int hlen, struct ether_header *eh,
654          struct mbuf *m, struct ifnet *oif)
655 {
656         char *action;
657         int limit_reached = 0;
658         char action2[40], proto[48], fragment[28];
659
660         fragment[0] = '\0';
661         proto[0] = '\0';
662
663         if (f == NULL) {        /* bogus pkt */
664                 struct ipfw_context *ctx = ipfw_ctx[mycpuid];
665
666                 if (verbose_limit != 0 &&
667                     ctx->ipfw_norule_counter >= verbose_limit)
668                         return;
669                 ctx->ipfw_norule_counter++;
670                 if (ctx->ipfw_norule_counter == verbose_limit)
671                         limit_reached = verbose_limit;
672                 action = "Refuse";
673         } else {        /* O_LOG is the first action, find the real one */
674                 ipfw_insn *cmd = ACTION_PTR(f);
675                 ipfw_insn_log *l = (ipfw_insn_log *)cmd;
676
677                 if (l->max_log != 0 && l->log_left == 0)
678                         return;
679                 l->log_left--;
680                 if (l->log_left == 0)
681                         limit_reached = l->max_log;
682                 cmd += F_LEN(cmd);      /* point to first action */
683                 if (cmd->opcode == O_PROB)
684                         cmd += F_LEN(cmd);
685
686                 action = action2;
687                 switch (cmd->opcode) {
688                 case O_DENY:
689                         action = "Deny";
690                         break;
691
692                 case O_REJECT:
693                         if (cmd->arg1==ICMP_REJECT_RST) {
694                                 action = "Reset";
695                         } else if (cmd->arg1==ICMP_UNREACH_HOST) {
696                                 action = "Reject";
697                         } else {
698                                 ksnprintf(SNPARGS(action2, 0), "Unreach %d",
699                                           cmd->arg1);
700                         }
701                         break;
702
703                 case O_ACCEPT:
704                         action = "Accept";
705                         break;
706
707                 case O_COUNT:
708                         action = "Count";
709                         break;
710
711                 case O_DIVERT:
712                         ksnprintf(SNPARGS(action2, 0), "Divert %d", cmd->arg1);
713                         break;
714
715                 case O_TEE:
716                         ksnprintf(SNPARGS(action2, 0), "Tee %d", cmd->arg1);
717                         break;
718
719                 case O_SKIPTO:
720                         ksnprintf(SNPARGS(action2, 0), "SkipTo %d", cmd->arg1);
721                         break;
722
723                 case O_PIPE:
724                         ksnprintf(SNPARGS(action2, 0), "Pipe %d", cmd->arg1);
725                         break;
726
727                 case O_QUEUE:
728                         ksnprintf(SNPARGS(action2, 0), "Queue %d", cmd->arg1);
729                         break;
730
731                 case O_FORWARD_IP:
732                         {
733                                 ipfw_insn_sa *sa = (ipfw_insn_sa *)cmd;
734                                 int len;
735
736                                 len = ksnprintf(SNPARGS(action2, 0),
737                                                 "Forward to %s",
738                                                 inet_ntoa(sa->sa.sin_addr));
739                                 if (sa->sa.sin_port) {
740                                         ksnprintf(SNPARGS(action2, len), ":%d",
741                                                   sa->sa.sin_port);
742                                 }
743                         }
744                         break;
745
746                 default:
747                         action = "UNKNOWN";
748                         break;
749                 }
750         }
751
752         if (hlen == 0) {        /* non-ip */
753                 ksnprintf(SNPARGS(proto, 0), "MAC");
754         } else {
755                 struct ip *ip = mtod(m, struct ip *);
756                 /* these three are all aliases to the same thing */
757                 struct icmp *const icmp = L3HDR(struct icmp, ip);
758                 struct tcphdr *const tcp = (struct tcphdr *)icmp;
759                 struct udphdr *const udp = (struct udphdr *)icmp;
760
761                 int ip_off, offset, ip_len;
762                 int len;
763
764                 if (eh != NULL) { /* layer 2 packets are as on the wire */
765                         ip_off = ntohs(ip->ip_off);
766                         ip_len = ntohs(ip->ip_len);
767                 } else {
768                         ip_off = ip->ip_off;
769                         ip_len = ip->ip_len;
770                 }
771                 offset = ip_off & IP_OFFMASK;
772                 switch (ip->ip_p) {
773                 case IPPROTO_TCP:
774                         len = ksnprintf(SNPARGS(proto, 0), "TCP %s",
775                                         inet_ntoa(ip->ip_src));
776                         if (offset == 0) {
777                                 ksnprintf(SNPARGS(proto, len), ":%d %s:%d",
778                                           ntohs(tcp->th_sport),
779                                           inet_ntoa(ip->ip_dst),
780                                           ntohs(tcp->th_dport));
781                         } else {
782                                 ksnprintf(SNPARGS(proto, len), " %s",
783                                           inet_ntoa(ip->ip_dst));
784                         }
785                         break;
786
787                 case IPPROTO_UDP:
788                         len = ksnprintf(SNPARGS(proto, 0), "UDP %s",
789                                         inet_ntoa(ip->ip_src));
790                         if (offset == 0) {
791                                 ksnprintf(SNPARGS(proto, len), ":%d %s:%d",
792                                           ntohs(udp->uh_sport),
793                                           inet_ntoa(ip->ip_dst),
794                                           ntohs(udp->uh_dport));
795                         } else {
796                                 ksnprintf(SNPARGS(proto, len), " %s",
797                                           inet_ntoa(ip->ip_dst));
798                         }
799                         break;
800
801                 case IPPROTO_ICMP:
802                         if (offset == 0) {
803                                 len = ksnprintf(SNPARGS(proto, 0),
804                                                 "ICMP:%u.%u ",
805                                                 icmp->icmp_type,
806                                                 icmp->icmp_code);
807                         } else {
808                                 len = ksnprintf(SNPARGS(proto, 0), "ICMP ");
809                         }
810                         len += ksnprintf(SNPARGS(proto, len), "%s",
811                                          inet_ntoa(ip->ip_src));
812                         ksnprintf(SNPARGS(proto, len), " %s",
813                                   inet_ntoa(ip->ip_dst));
814                         break;
815
816                 default:
817                         len = ksnprintf(SNPARGS(proto, 0), "P:%d %s", ip->ip_p,
818                                         inet_ntoa(ip->ip_src));
819                         ksnprintf(SNPARGS(proto, len), " %s",
820                                   inet_ntoa(ip->ip_dst));
821                         break;
822                 }
823
824                 if (ip_off & (IP_MF | IP_OFFMASK)) {
825                         ksnprintf(SNPARGS(fragment, 0), " (frag %d:%d@%d%s)",
826                                   ntohs(ip->ip_id), ip_len - (ip->ip_hl << 2),
827                                   offset << 3, (ip_off & IP_MF) ? "+" : "");
828                 }
829         }
830
831         if (oif || m->m_pkthdr.rcvif) {
832                 log(LOG_SECURITY | LOG_INFO,
833                     "ipfw: %d %s %s %s via %s%s\n",
834                     f ? f->rulenum : -1,
835                     action, proto, oif ? "out" : "in",
836                     oif ? oif->if_xname : m->m_pkthdr.rcvif->if_xname,
837                     fragment);
838         } else {
839                 log(LOG_SECURITY | LOG_INFO,
840                     "ipfw: %d %s %s [no if info]%s\n",
841                     f ? f->rulenum : -1,
842                     action, proto, fragment);
843         }
844
845         if (limit_reached) {
846                 log(LOG_SECURITY | LOG_NOTICE,
847                     "ipfw: limit %d reached on entry %d\n",
848                     limit_reached, f ? f->rulenum : -1);
849         }
850 }
851
852 #undef SNPARGS
853
854 /*
855  * IMPORTANT: the hash function for dynamic rules must be commutative
856  * in source and destination (ip,port), because rules are bidirectional
857  * and we want to find both in the same bucket.
858  */
859 static __inline int
860 hash_packet(struct ipfw_flow_id *id)
861 {
862         uint32_t i;
863
864         i = (id->dst_ip) ^ (id->src_ip) ^ (id->dst_port) ^ (id->src_port);
865         i &= (curr_dyn_buckets - 1);
866         return i;
867 }
868
869 /**
870  * unlink a dynamic rule from a chain. prev is a pointer to
871  * the previous one, q is a pointer to the rule to delete,
872  * head is a pointer to the head of the queue.
873  * Modifies q and potentially also head.
874  */
875 #define UNLINK_DYN_RULE(prev, head, q)                                  \
876 do {                                                                    \
877         ipfw_dyn_rule *old_q = q;                                       \
878                                                                         \
879         /* remove a refcount to the parent */                           \
880         if (q->dyn_type == O_LIMIT)                                     \
881                 q->parent->count--;                                     \
882         DPRINTF("-- unlink entry 0x%08x %d -> 0x%08x %d, %d left\n",    \
883                 q->id.src_ip, q->id.src_port,                           \
884                 q->id.dst_ip, q->id.dst_port, dyn_count - 1);           \
885         if (prev != NULL)                                               \
886                 prev->next = q = q->next;                               \
887         else                                                            \
888                 head = q = q->next;                                     \
889         KASSERT(dyn_count > 0, ("invalid dyn count %u\n", dyn_count));  \
890         dyn_count--;                                                    \
891         kfree(old_q, M_IPFW);                                           \
892 } while (0)
893
894 #define TIME_LEQ(a, b)  ((int)((a) - (b)) <= 0)
895
896 /**
897  * Remove dynamic rules pointing to "rule", or all of them if rule == NULL.
898  *
899  * If keep_me == NULL, rules are deleted even if not expired,
900  * otherwise only expired rules are removed.
901  *
902  * The value of the second parameter is also used to point to identify
903  * a rule we absolutely do not want to remove (e.g. because we are
904  * holding a reference to it -- this is the case with O_LIMIT_PARENT
905  * rules). The pointer is only used for comparison, so any non-null
906  * value will do.
907  */
908 static void
909 remove_dyn_rule_locked(struct ip_fw *rule, ipfw_dyn_rule *keep_me)
910 {
911         static uint32_t last_remove = 0; /* XXX */
912
913 #define FORCE   (keep_me == NULL)
914
915         ipfw_dyn_rule *prev, *q;
916         int i, pass = 0, max_pass = 0, unlinked = 0;
917
918         if (ipfw_dyn_v == NULL || dyn_count == 0)
919                 return;
920         /* do not expire more than once per second, it is useless */
921         if (!FORCE && last_remove == time_second)
922                 return;
923         last_remove = time_second;
924
925         /*
926          * because O_LIMIT refer to parent rules, during the first pass only
927          * remove child and mark any pending LIMIT_PARENT, and remove
928          * them in a second pass.
929          */
930 next_pass:
931         for (i = 0; i < curr_dyn_buckets; i++) {
932                 for (prev = NULL, q = ipfw_dyn_v[i]; q;) {
933                         /*
934                          * Logic can become complex here, so we split tests.
935                          */
936                         if (q == keep_me)
937                                 goto next;
938                         if (rule != NULL && rule->stub != q->stub)
939                                 goto next; /* not the one we are looking for */
940                         if (q->dyn_type == O_LIMIT_PARENT) {
941                                 /*
942                                  * handle parent in the second pass,
943                                  * record we need one.
944                                  */
945                                 max_pass = 1;
946                                 if (pass == 0)
947                                         goto next;
948                                 if (FORCE && q->count != 0) {
949                                         /* XXX should not happen! */
950                                         kprintf("OUCH! cannot remove rule, "
951                                                 "count %d\n", q->count);
952                                 }
953                         } else {
954                                 if (!FORCE && !TIME_LEQ(q->expire, time_second))
955                                         goto next;
956                         }
957                         unlinked = 1;
958                         UNLINK_DYN_RULE(prev, ipfw_dyn_v[i], q);
959                         continue;
960 next:
961                         prev = q;
962                         q = q->next;
963                 }
964         }
965         if (pass++ < max_pass)
966                 goto next_pass;
967
968         if (unlinked)
969                 ++dyn_buckets_gen;
970
971 #undef FORCE
972 }
973
974 /**
975  * lookup a dynamic rule.
976  */
977 static ipfw_dyn_rule *
978 lookup_dyn_rule(struct ipfw_flow_id *pkt, int *match_direction,
979                 struct tcphdr *tcp)
980 {
981         /*
982          * stateful ipfw extensions.
983          * Lookup into dynamic session queue
984          */
985 #define MATCH_REVERSE   0
986 #define MATCH_FORWARD   1
987 #define MATCH_NONE      2
988 #define MATCH_UNKNOWN   3
989         int i, dir = MATCH_NONE;
990         ipfw_dyn_rule *prev, *q=NULL;
991
992         if (ipfw_dyn_v == NULL)
993                 goto done;      /* not found */
994
995         i = hash_packet(pkt);
996         for (prev = NULL, q = ipfw_dyn_v[i]; q != NULL;) {
997                 if (q->dyn_type == O_LIMIT_PARENT)
998                         goto next;
999
1000                 if (TIME_LEQ(q->expire, time_second)) {
1001                         /*
1002                          * Entry expired; skip.
1003                          * Let ipfw_tick() take care of it
1004                          */
1005                         goto next;
1006                 }
1007
1008                 if (pkt->proto == q->id.proto) {
1009                         if (pkt->src_ip == q->id.src_ip &&
1010                             pkt->dst_ip == q->id.dst_ip &&
1011                             pkt->src_port == q->id.src_port &&
1012                             pkt->dst_port == q->id.dst_port) {
1013                                 dir = MATCH_FORWARD;
1014                                 break;
1015                         }
1016                         if (pkt->src_ip == q->id.dst_ip &&
1017                             pkt->dst_ip == q->id.src_ip &&
1018                             pkt->src_port == q->id.dst_port &&
1019                             pkt->dst_port == q->id.src_port) {
1020                                 dir = MATCH_REVERSE;
1021                                 break;
1022                         }
1023                 }
1024 next:
1025                 prev = q;
1026                 q = q->next;
1027         }
1028         if (q == NULL)
1029                 goto done; /* q = NULL, not found */
1030
1031         if (pkt->proto == IPPROTO_TCP) { /* update state according to flags */
1032                 u_char flags = pkt->flags & (TH_FIN|TH_SYN|TH_RST);
1033
1034 #define BOTH_SYN        (TH_SYN | (TH_SYN << 8))
1035 #define BOTH_FIN        (TH_FIN | (TH_FIN << 8))
1036
1037                 q->state |= (dir == MATCH_FORWARD ) ? flags : (flags << 8);
1038                 switch (q->state) {
1039                 case TH_SYN:                            /* opening */
1040                         q->expire = time_second + dyn_syn_lifetime;
1041                         break;
1042
1043                 case BOTH_SYN:                  /* move to established */
1044                 case BOTH_SYN | TH_FIN :        /* one side tries to close */
1045                 case BOTH_SYN | (TH_FIN << 8) :
1046                         if (tcp) {
1047                                 uint32_t ack = ntohl(tcp->th_ack);
1048
1049 #define _SEQ_GE(a, b)   ((int)(a) - (int)(b) >= 0)
1050
1051                                 if (dir == MATCH_FORWARD) {
1052                                         if (q->ack_fwd == 0 ||
1053                                             _SEQ_GE(ack, q->ack_fwd))
1054                                                 q->ack_fwd = ack;
1055                                         else /* ignore out-of-sequence */
1056                                                 break;
1057                                 } else {
1058                                         if (q->ack_rev == 0 ||
1059                                             _SEQ_GE(ack, q->ack_rev))
1060                                                 q->ack_rev = ack;
1061                                         else /* ignore out-of-sequence */
1062                                                 break;
1063                                 }
1064 #undef _SEQ_GE
1065                         }
1066                         q->expire = time_second + dyn_ack_lifetime;
1067                         break;
1068
1069                 case BOTH_SYN | BOTH_FIN:       /* both sides closed */
1070                         KKASSERT(dyn_fin_lifetime < dyn_keepalive_period);
1071                         q->expire = time_second + dyn_fin_lifetime;
1072                         break;
1073
1074                 default:
1075 #if 0
1076                         /*
1077                          * reset or some invalid combination, but can also
1078                          * occur if we use keep-state the wrong way.
1079                          */
1080                         if ((q->state & ((TH_RST << 8) | TH_RST)) == 0)
1081                                 kprintf("invalid state: 0x%x\n", q->state);
1082 #endif
1083                         KKASSERT(dyn_rst_lifetime < dyn_keepalive_period);
1084                         q->expire = time_second + dyn_rst_lifetime;
1085                         break;
1086                 }
1087         } else if (pkt->proto == IPPROTO_UDP) {
1088                 q->expire = time_second + dyn_udp_lifetime;
1089         } else {
1090                 /* other protocols */
1091                 q->expire = time_second + dyn_short_lifetime;
1092         }
1093 done:
1094         if (match_direction)
1095                 *match_direction = dir;
1096         return q;
1097 }
1098
1099 static struct ip_fw *
1100 lookup_rule(struct ipfw_flow_id *pkt, int *match_direction, struct tcphdr *tcp,
1101             uint16_t len, int *deny)
1102 {
1103         struct ip_fw *rule = NULL;
1104         ipfw_dyn_rule *q;
1105         struct ipfw_context *ctx = ipfw_ctx[mycpuid];
1106         uint32_t gen;
1107
1108         *deny = 0;
1109         gen = ctx->ipfw_gen;
1110
1111         lockmgr(&dyn_lock, LK_SHARED);
1112
1113         if (ctx->ipfw_gen != gen) {
1114                 /*
1115                  * Static rules had been change when we were waiting
1116                  * for the dynamic hash table lock; deny this packet,
1117                  * since it is _not_ known whether it is safe to keep
1118                  * iterating the static rules.
1119                  */
1120                 *deny = 1;
1121                 goto back;
1122         }
1123
1124         q = lookup_dyn_rule(pkt, match_direction, tcp);
1125         if (q == NULL) {
1126                 rule = NULL;
1127         } else {
1128                 rule = q->stub->rule[mycpuid];
1129                 KKASSERT(rule->stub == q->stub && rule->cpuid == mycpuid);
1130
1131                 /* XXX */
1132                 q->pcnt++;
1133                 q->bcnt += len;
1134         }
1135 back:
1136         lockmgr(&dyn_lock, LK_RELEASE);
1137         return rule;
1138 }
1139
1140 static void
1141 realloc_dynamic_table(void)
1142 {
1143         ipfw_dyn_rule **old_dyn_v;
1144         uint32_t old_curr_dyn_buckets;
1145
1146         KASSERT(dyn_buckets <= 65536 && (dyn_buckets & (dyn_buckets - 1)) == 0,
1147                 ("invalid dyn_buckets %d\n", dyn_buckets));
1148
1149         /* Save the current buckets array for later error recovery */
1150         old_dyn_v = ipfw_dyn_v;
1151         old_curr_dyn_buckets = curr_dyn_buckets;
1152
1153         curr_dyn_buckets = dyn_buckets;
1154         for (;;) {
1155                 ipfw_dyn_v = kmalloc(curr_dyn_buckets * sizeof(ipfw_dyn_rule *),
1156                                      M_IPFW, M_NOWAIT | M_ZERO);
1157                 if (ipfw_dyn_v != NULL || curr_dyn_buckets <= 2)
1158                         break;
1159
1160                 curr_dyn_buckets /= 2;
1161                 if (curr_dyn_buckets <= old_curr_dyn_buckets &&
1162                     old_dyn_v != NULL) {
1163                         /*
1164                          * Don't try allocating smaller buckets array, reuse
1165                          * the old one, which alreay contains enough buckets
1166                          */
1167                         break;
1168                 }
1169         }
1170
1171         if (ipfw_dyn_v != NULL) {
1172                 if (old_dyn_v != NULL)
1173                         kfree(old_dyn_v, M_IPFW);
1174         } else {
1175                 /* Allocation failed, restore old buckets array */
1176                 ipfw_dyn_v = old_dyn_v;
1177                 curr_dyn_buckets = old_curr_dyn_buckets;
1178         }
1179
1180         if (ipfw_dyn_v != NULL)
1181                 ++dyn_buckets_gen;
1182 }
1183
1184 /**
1185  * Install state of type 'type' for a dynamic session.
1186  * The hash table contains two type of rules:
1187  * - regular rules (O_KEEP_STATE)
1188  * - rules for sessions with limited number of sess per user
1189  *   (O_LIMIT). When they are created, the parent is
1190  *   increased by 1, and decreased on delete. In this case,
1191  *   the third parameter is the parent rule and not the chain.
1192  * - "parent" rules for the above (O_LIMIT_PARENT).
1193  */
1194 static ipfw_dyn_rule *
1195 add_dyn_rule(struct ipfw_flow_id *id, uint8_t dyn_type, struct ip_fw *rule)
1196 {
1197         ipfw_dyn_rule *r;
1198         int i;
1199
1200         if (ipfw_dyn_v == NULL ||
1201             (dyn_count == 0 && dyn_buckets != curr_dyn_buckets)) {
1202                 realloc_dynamic_table();
1203                 if (ipfw_dyn_v == NULL)
1204                         return NULL; /* failed ! */
1205         }
1206         i = hash_packet(id);
1207
1208         r = kmalloc(sizeof(*r), M_IPFW, M_NOWAIT | M_ZERO);
1209         if (r == NULL) {
1210                 kprintf ("sorry cannot allocate state\n");
1211                 return NULL;
1212         }
1213
1214         /* increase refcount on parent, and set pointer */
1215         if (dyn_type == O_LIMIT) {
1216                 ipfw_dyn_rule *parent = (ipfw_dyn_rule *)rule;
1217
1218                 if (parent->dyn_type != O_LIMIT_PARENT)
1219                         panic("invalid parent");
1220                 parent->count++;
1221                 r->parent = parent;
1222                 rule = parent->stub->rule[mycpuid];
1223                 KKASSERT(rule->stub == parent->stub);
1224         }
1225         KKASSERT(rule->cpuid == mycpuid && rule->stub != NULL);
1226
1227         r->id = *id;
1228         r->expire = time_second + dyn_syn_lifetime;
1229         r->stub = rule->stub;
1230         r->dyn_type = dyn_type;
1231         r->pcnt = r->bcnt = 0;
1232         r->count = 0;
1233
1234         r->bucket = i;
1235         r->next = ipfw_dyn_v[i];
1236         ipfw_dyn_v[i] = r;
1237         dyn_count++;
1238         dyn_buckets_gen++;
1239         DPRINTF("-- add dyn entry ty %d 0x%08x %d -> 0x%08x %d, total %d\n",
1240                 dyn_type,
1241                 r->id.src_ip, r->id.src_port,
1242                 r->id.dst_ip, r->id.dst_port, dyn_count);
1243         return r;
1244 }
1245
1246 /**
1247  * lookup dynamic parent rule using pkt and rule as search keys.
1248  * If the lookup fails, then install one.
1249  */
1250 static ipfw_dyn_rule *
1251 lookup_dyn_parent(struct ipfw_flow_id *pkt, struct ip_fw *rule)
1252 {
1253         ipfw_dyn_rule *q;
1254         int i;
1255
1256         if (ipfw_dyn_v) {
1257                 i = hash_packet(pkt);
1258                 for (q = ipfw_dyn_v[i]; q != NULL; q = q->next) {
1259                         if (q->dyn_type == O_LIMIT_PARENT &&
1260                             rule->stub == q->stub &&
1261                             pkt->proto == q->id.proto &&
1262                             pkt->src_ip == q->id.src_ip &&
1263                             pkt->dst_ip == q->id.dst_ip &&
1264                             pkt->src_port == q->id.src_port &&
1265                             pkt->dst_port == q->id.dst_port) {
1266                                 q->expire = time_second + dyn_short_lifetime;
1267                                 DPRINTF("lookup_dyn_parent found 0x%p\n", q);
1268                                 return q;
1269                         }
1270                 }
1271         }
1272         return add_dyn_rule(pkt, O_LIMIT_PARENT, rule);
1273 }
1274
1275 /**
1276  * Install dynamic state for rule type cmd->o.opcode
1277  *
1278  * Returns 1 (failure) if state is not installed because of errors or because
1279  * session limitations are enforced.
1280  */
1281 static int
1282 install_state_locked(struct ip_fw *rule, ipfw_insn_limit *cmd,
1283                      struct ip_fw_args *args)
1284 {
1285         static int last_log; /* XXX */
1286
1287         ipfw_dyn_rule *q;
1288
1289         DPRINTF("-- install state type %d 0x%08x %u -> 0x%08x %u\n",
1290                 cmd->o.opcode,
1291                 args->f_id.src_ip, args->f_id.src_port,
1292                 args->f_id.dst_ip, args->f_id.dst_port);
1293
1294         q = lookup_dyn_rule(&args->f_id, NULL, NULL);
1295         if (q != NULL) { /* should never occur */
1296                 if (last_log != time_second) {
1297                         last_log = time_second;
1298                         kprintf(" install_state: entry already present, done\n");
1299                 }
1300                 return 0;
1301         }
1302
1303         if (dyn_count >= dyn_max) {
1304                 /*
1305                  * Run out of slots, try to remove any expired rule.
1306                  */
1307                 remove_dyn_rule_locked(NULL, (ipfw_dyn_rule *)1);
1308                 if (dyn_count >= dyn_max) {
1309                         if (last_log != time_second) {
1310                                 last_log = time_second;
1311                                 kprintf("install_state: "
1312                                         "Too many dynamic rules\n");
1313                         }
1314                         return 1; /* cannot install, notify caller */
1315                 }
1316         }
1317
1318         switch (cmd->o.opcode) {
1319         case O_KEEP_STATE: /* bidir rule */
1320                 if (add_dyn_rule(&args->f_id, O_KEEP_STATE, rule) == NULL)
1321                         return 1;
1322                 break;
1323
1324         case O_LIMIT: /* limit number of sessions */
1325                 {
1326                         uint16_t limit_mask = cmd->limit_mask;
1327                         struct ipfw_flow_id id;
1328                         ipfw_dyn_rule *parent;
1329
1330                         DPRINTF("installing dyn-limit rule %d\n",
1331                                 cmd->conn_limit);
1332
1333                         id.dst_ip = id.src_ip = 0;
1334                         id.dst_port = id.src_port = 0;
1335                         id.proto = args->f_id.proto;
1336
1337                         if (limit_mask & DYN_SRC_ADDR)
1338                                 id.src_ip = args->f_id.src_ip;
1339                         if (limit_mask & DYN_DST_ADDR)
1340                                 id.dst_ip = args->f_id.dst_ip;
1341                         if (limit_mask & DYN_SRC_PORT)
1342                                 id.src_port = args->f_id.src_port;
1343                         if (limit_mask & DYN_DST_PORT)
1344                                 id.dst_port = args->f_id.dst_port;
1345
1346                         parent = lookup_dyn_parent(&id, rule);
1347                         if (parent == NULL) {
1348                                 kprintf("add parent failed\n");
1349                                 return 1;
1350                         }
1351
1352                         if (parent->count >= cmd->conn_limit) {
1353                                 /*
1354                                  * See if we can remove some expired rule.
1355                                  */
1356                                 remove_dyn_rule_locked(rule, parent);
1357                                 if (parent->count >= cmd->conn_limit) {
1358                                         if (fw_verbose &&
1359                                             last_log != time_second) {
1360                                                 last_log = time_second;
1361                                                 log(LOG_SECURITY | LOG_DEBUG,
1362                                                     "drop session, "
1363                                                     "too many entries\n");
1364                                         }
1365                                         return 1;
1366                                 }
1367                         }
1368                         if (add_dyn_rule(&args->f_id, O_LIMIT,
1369                                          (struct ip_fw *)parent) == NULL)
1370                                 return 1;
1371                 }
1372                 break;
1373         default:
1374                 kprintf("unknown dynamic rule type %u\n", cmd->o.opcode);
1375                 return 1;
1376         }
1377         lookup_dyn_rule(&args->f_id, NULL, NULL); /* XXX just set lifetime */
1378         return 0;
1379 }
1380
1381 static int
1382 install_state(struct ip_fw *rule, ipfw_insn_limit *cmd,
1383               struct ip_fw_args *args, int *deny)
1384 {
1385         struct ipfw_context *ctx = ipfw_ctx[mycpuid];
1386         uint32_t gen;
1387         int ret = 0;
1388
1389         *deny = 0;
1390         gen = ctx->ipfw_gen;
1391
1392         lockmgr(&dyn_lock, LK_EXCLUSIVE);
1393         if (ctx->ipfw_gen != gen) {
1394                 /* See the comment in lookup_rule() */
1395                 *deny = 1;
1396         } else {
1397                 ret = install_state_locked(rule, cmd, args);
1398         }
1399         lockmgr(&dyn_lock, LK_RELEASE);
1400
1401         return ret;
1402 }
1403
1404 /*
1405  * Transmit a TCP packet, containing either a RST or a keepalive.
1406  * When flags & TH_RST, we are sending a RST packet, because of a
1407  * "reset" action matched the packet.
1408  * Otherwise we are sending a keepalive, and flags & TH_
1409  */
1410 static void
1411 send_pkt(struct ipfw_flow_id *id, uint32_t seq, uint32_t ack, int flags)
1412 {
1413         struct mbuf *m;
1414         struct ip *ip;
1415         struct tcphdr *tcp;
1416         struct route sro;       /* fake route */
1417
1418         MGETHDR(m, MB_DONTWAIT, MT_HEADER);
1419         if (m == NULL)
1420                 return;
1421         m->m_pkthdr.rcvif = NULL;
1422         m->m_pkthdr.len = m->m_len = sizeof(struct ip) + sizeof(struct tcphdr);
1423         m->m_data += max_linkhdr;
1424
1425         ip = mtod(m, struct ip *);
1426         bzero(ip, m->m_len);
1427         tcp = (struct tcphdr *)(ip + 1); /* no IP options */
1428         ip->ip_p = IPPROTO_TCP;
1429         tcp->th_off = 5;
1430
1431         /*
1432          * Assume we are sending a RST (or a keepalive in the reverse
1433          * direction), swap src and destination addresses and ports.
1434          */
1435         ip->ip_src.s_addr = htonl(id->dst_ip);
1436         ip->ip_dst.s_addr = htonl(id->src_ip);
1437         tcp->th_sport = htons(id->dst_port);
1438         tcp->th_dport = htons(id->src_port);
1439         if (flags & TH_RST) {   /* we are sending a RST */
1440                 if (flags & TH_ACK) {
1441                         tcp->th_seq = htonl(ack);
1442                         tcp->th_ack = htonl(0);
1443                         tcp->th_flags = TH_RST;
1444                 } else {
1445                         if (flags & TH_SYN)
1446                                 seq++;
1447                         tcp->th_seq = htonl(0);
1448                         tcp->th_ack = htonl(seq);
1449                         tcp->th_flags = TH_RST | TH_ACK;
1450                 }
1451         } else {
1452                 /*
1453                  * We are sending a keepalive. flags & TH_SYN determines
1454                  * the direction, forward if set, reverse if clear.
1455                  * NOTE: seq and ack are always assumed to be correct
1456                  * as set by the caller. This may be confusing...
1457                  */
1458                 if (flags & TH_SYN) {
1459                         /*
1460                          * we have to rewrite the correct addresses!
1461                          */
1462                         ip->ip_dst.s_addr = htonl(id->dst_ip);
1463                         ip->ip_src.s_addr = htonl(id->src_ip);
1464                         tcp->th_dport = htons(id->dst_port);
1465                         tcp->th_sport = htons(id->src_port);
1466                 }
1467                 tcp->th_seq = htonl(seq);
1468                 tcp->th_ack = htonl(ack);
1469                 tcp->th_flags = TH_ACK;
1470         }
1471
1472         /*
1473          * set ip_len to the payload size so we can compute
1474          * the tcp checksum on the pseudoheader
1475          * XXX check this, could save a couple of words ?
1476          */
1477         ip->ip_len = htons(sizeof(struct tcphdr));
1478         tcp->th_sum = in_cksum(m, m->m_pkthdr.len);
1479
1480         /*
1481          * now fill fields left out earlier
1482          */
1483         ip->ip_ttl = ip_defttl;
1484         ip->ip_len = m->m_pkthdr.len;
1485
1486         bzero(&sro, sizeof(sro));
1487         ip_rtaddr(ip->ip_dst, &sro);
1488
1489         m->m_pkthdr.fw_flags |= IPFW_MBUF_GENERATED;
1490         ip_output(m, NULL, &sro, 0, NULL, NULL);
1491         if (sro.ro_rt)
1492                 RTFREE(sro.ro_rt);
1493 }
1494
1495 /*
1496  * sends a reject message, consuming the mbuf passed as an argument.
1497  */
1498 static void
1499 send_reject(struct ip_fw_args *args, int code, int offset, int ip_len)
1500 {
1501         if (code != ICMP_REJECT_RST) { /* Send an ICMP unreach */
1502                 /* We need the IP header in host order for icmp_error(). */
1503                 if (args->eh != NULL) {
1504                         struct ip *ip = mtod(args->m, struct ip *);
1505
1506                         ip->ip_len = ntohs(ip->ip_len);
1507                         ip->ip_off = ntohs(ip->ip_off);
1508                 }
1509                 icmp_error(args->m, ICMP_UNREACH, code, 0L, 0);
1510         } else if (offset == 0 && args->f_id.proto == IPPROTO_TCP) {
1511                 struct tcphdr *const tcp =
1512                     L3HDR(struct tcphdr, mtod(args->m, struct ip *));
1513
1514                 if ((tcp->th_flags & TH_RST) == 0) {
1515                         send_pkt(&args->f_id, ntohl(tcp->th_seq),
1516                                  ntohl(tcp->th_ack), tcp->th_flags | TH_RST);
1517                 }
1518                 m_freem(args->m);
1519         } else {
1520                 m_freem(args->m);
1521         }
1522         args->m = NULL;
1523 }
1524
1525 /**
1526  *
1527  * Given an ip_fw *, lookup_next_rule will return a pointer
1528  * to the next rule, which can be either the jump
1529  * target (for skipto instructions) or the next one in the list (in
1530  * all other cases including a missing jump target).
1531  * The result is also written in the "next_rule" field of the rule.
1532  * Backward jumps are not allowed, so start looking from the next
1533  * rule...
1534  *
1535  * This never returns NULL -- in case we do not have an exact match,
1536  * the next rule is returned. When the ruleset is changed,
1537  * pointers are flushed so we are always correct.
1538  */
1539
1540 static struct ip_fw *
1541 lookup_next_rule(struct ip_fw *me)
1542 {
1543         struct ip_fw *rule = NULL;
1544         ipfw_insn *cmd;
1545
1546         /* look for action, in case it is a skipto */
1547         cmd = ACTION_PTR(me);
1548         if (cmd->opcode == O_LOG)
1549                 cmd += F_LEN(cmd);
1550         if (cmd->opcode == O_SKIPTO) {
1551                 for (rule = me->next; rule; rule = rule->next) {
1552                         if (rule->rulenum >= cmd->arg1)
1553                                 break;
1554                 }
1555         }
1556         if (rule == NULL)                       /* failure or not a skipto */
1557                 rule = me->next;
1558         me->next_rule = rule;
1559         return rule;
1560 }
1561
1562 static int
1563 _ipfw_match_uid(const struct ipfw_flow_id *fid, struct ifnet *oif,
1564                 enum ipfw_opcodes opcode, uid_t uid)
1565 {
1566         struct in_addr src_ip, dst_ip;
1567         struct inpcbinfo *pi;
1568         int wildcard;
1569         struct inpcb *pcb;
1570
1571         if (fid->proto == IPPROTO_TCP) {
1572                 wildcard = 0;
1573                 pi = &tcbinfo[mycpuid];
1574         } else if (fid->proto == IPPROTO_UDP) {
1575                 wildcard = 1;
1576                 pi = &udbinfo;
1577         } else {
1578                 return 0;
1579         }
1580
1581         /*
1582          * Values in 'fid' are in host byte order
1583          */
1584         dst_ip.s_addr = htonl(fid->dst_ip);
1585         src_ip.s_addr = htonl(fid->src_ip);
1586         if (oif) {
1587                 pcb = in_pcblookup_hash(pi,
1588                         dst_ip, htons(fid->dst_port),
1589                         src_ip, htons(fid->src_port),
1590                         wildcard, oif);
1591         } else {
1592                 pcb = in_pcblookup_hash(pi,
1593                         src_ip, htons(fid->src_port),
1594                         dst_ip, htons(fid->dst_port),
1595                         wildcard, NULL);
1596         }
1597         if (pcb == NULL || pcb->inp_socket == NULL)
1598                 return 0;
1599
1600         if (opcode == O_UID) {
1601 #define socheckuid(a,b) ((a)->so_cred->cr_uid != (b))
1602                 return !socheckuid(pcb->inp_socket, uid);
1603 #undef socheckuid
1604         } else  {
1605                 return groupmember(uid, pcb->inp_socket->so_cred);
1606         }
1607 }
1608
1609 static int
1610 ipfw_match_uid(const struct ipfw_flow_id *fid, struct ifnet *oif,
1611                enum ipfw_opcodes opcode, uid_t uid, int *deny)
1612 {
1613         struct ipfw_context *ctx = ipfw_ctx[mycpuid];
1614         uint32_t gen;
1615         int match = 0;
1616
1617         *deny = 0;
1618         gen = ctx->ipfw_gen;
1619
1620         get_mplock();
1621         if (gen != ctx->ipfw_gen) {
1622                 /* See the comment in lookup_rule() */
1623                 *deny = 1;
1624         } else {
1625                 match = _ipfw_match_uid(fid, oif, opcode, uid);
1626         }
1627         rel_mplock();
1628         return match;
1629 }
1630
1631 /*
1632  * The main check routine for the firewall.
1633  *
1634  * All arguments are in args so we can modify them and return them
1635  * back to the caller.
1636  *
1637  * Parameters:
1638  *
1639  *      args->m (in/out) The packet; we set to NULL when/if we nuke it.
1640  *              Starts with the IP header.
1641  *      args->eh (in)   Mac header if present, or NULL for layer3 packet.
1642  *      args->oif       Outgoing interface, or NULL if packet is incoming.
1643  *              The incoming interface is in the mbuf. (in)
1644  *
1645  *      args->rule      Pointer to the last matching rule (in/out)
1646  *      args->f_id      Addresses grabbed from the packet (out)
1647  *
1648  * Return value:
1649  *
1650  *      If the packet was denied/rejected and has been dropped, *m is equal
1651  *      to NULL upon return.
1652  *
1653  *      IP_FW_DENY      the packet must be dropped.
1654  *      IP_FW_PASS      The packet is to be accepted and routed normally.
1655  *      IP_FW_DIVERT    Divert the packet to port (args->cookie)
1656  *      IP_FW_TEE       Tee the packet to port (args->cookie)
1657  *      IP_FW_DUMMYNET  Send the packet to pipe/queue (args->cookie)
1658  */
1659
1660 static int
1661 ipfw_chk(struct ip_fw_args *args)
1662 {
1663         /*
1664          * Local variables hold state during the processing of a packet.
1665          *
1666          * IMPORTANT NOTE: to speed up the processing of rules, there
1667          * are some assumption on the values of the variables, which
1668          * are documented here. Should you change them, please check
1669          * the implementation of the various instructions to make sure
1670          * that they still work.
1671          *
1672          * args->eh     The MAC header. It is non-null for a layer2
1673          *      packet, it is NULL for a layer-3 packet.
1674          *
1675          * m | args->m  Pointer to the mbuf, as received from the caller.
1676          *      It may change if ipfw_chk() does an m_pullup, or if it
1677          *      consumes the packet because it calls send_reject().
1678          *      XXX This has to change, so that ipfw_chk() never modifies
1679          *      or consumes the buffer.
1680          * ip   is simply an alias of the value of m, and it is kept
1681          *      in sync with it (the packet is  supposed to start with
1682          *      the ip header).
1683          */
1684         struct mbuf *m = args->m;
1685         struct ip *ip = mtod(m, struct ip *);
1686
1687         /*
1688          * oif | args->oif      If NULL, ipfw_chk has been called on the
1689          *      inbound path (ether_input, ip_input).
1690          *      If non-NULL, ipfw_chk has been called on the outbound path
1691          *      (ether_output, ip_output).
1692          */
1693         struct ifnet *oif = args->oif;
1694
1695         struct ip_fw *f = NULL;         /* matching rule */
1696         int retval = IP_FW_PASS;
1697         struct m_tag *mtag;
1698         struct divert_info *divinfo;
1699
1700         /*
1701          * hlen The length of the IPv4 header.
1702          *      hlen >0 means we have an IPv4 packet.
1703          */
1704         u_int hlen = 0;         /* hlen >0 means we have an IP pkt */
1705
1706         /*
1707          * offset       The offset of a fragment. offset != 0 means that
1708          *      we have a fragment at this offset of an IPv4 packet.
1709          *      offset == 0 means that (if this is an IPv4 packet)
1710          *      this is the first or only fragment.
1711          */
1712         u_short offset = 0;
1713
1714         /*
1715          * Local copies of addresses. They are only valid if we have
1716          * an IP packet.
1717          *
1718          * proto        The protocol. Set to 0 for non-ip packets,
1719          *      or to the protocol read from the packet otherwise.
1720          *      proto != 0 means that we have an IPv4 packet.
1721          *
1722          * src_port, dst_port   port numbers, in HOST format. Only
1723          *      valid for TCP and UDP packets.
1724          *
1725          * src_ip, dst_ip       ip addresses, in NETWORK format.
1726          *      Only valid for IPv4 packets.
1727          */
1728         uint8_t proto;
1729         uint16_t src_port = 0, dst_port = 0;    /* NOTE: host format    */
1730         struct in_addr src_ip, dst_ip;          /* NOTE: network format */
1731         uint16_t ip_len = 0;
1732
1733         /*
1734          * dyn_dir = MATCH_UNKNOWN when rules unchecked,
1735          *      MATCH_NONE when checked and not matched (dyn_f = NULL),
1736          *      MATCH_FORWARD or MATCH_REVERSE otherwise (dyn_f != NULL)
1737          */
1738         int dyn_dir = MATCH_UNKNOWN;
1739         struct ip_fw *dyn_f = NULL;
1740         struct ipfw_context *ctx = ipfw_ctx[mycpuid];
1741
1742         if (m->m_pkthdr.fw_flags & IPFW_MBUF_GENERATED)
1743                 return IP_FW_PASS;      /* accept */
1744
1745         if (args->eh == NULL ||         /* layer 3 packet */
1746             (m->m_pkthdr.len >= sizeof(struct ip) &&
1747              ntohs(args->eh->ether_type) == ETHERTYPE_IP))
1748                 hlen = ip->ip_hl << 2;
1749
1750         /*
1751          * Collect parameters into local variables for faster matching.
1752          */
1753         if (hlen == 0) {        /* do not grab addresses for non-ip pkts */
1754                 proto = args->f_id.proto = 0;   /* mark f_id invalid */
1755                 goto after_ip_checks;
1756         }
1757
1758         proto = args->f_id.proto = ip->ip_p;
1759         src_ip = ip->ip_src;
1760         dst_ip = ip->ip_dst;
1761         if (args->eh != NULL) { /* layer 2 packets are as on the wire */
1762                 offset = ntohs(ip->ip_off) & IP_OFFMASK;
1763                 ip_len = ntohs(ip->ip_len);
1764         } else {
1765                 offset = ip->ip_off & IP_OFFMASK;
1766                 ip_len = ip->ip_len;
1767         }
1768
1769 #define PULLUP_TO(len)                          \
1770 do {                                            \
1771         if (m->m_len < (len)) {                 \
1772                 args->m = m = m_pullup(m, (len));\
1773                 if (m == NULL)                  \
1774                         goto pullup_failed;     \
1775                 ip = mtod(m, struct ip *);      \
1776         }                                       \
1777 } while (0)
1778
1779         if (offset == 0) {
1780                 switch (proto) {
1781                 case IPPROTO_TCP:
1782                         {
1783                                 struct tcphdr *tcp;
1784
1785                                 PULLUP_TO(hlen + sizeof(struct tcphdr));
1786                                 tcp = L3HDR(struct tcphdr, ip);
1787                                 dst_port = tcp->th_dport;
1788                                 src_port = tcp->th_sport;
1789                                 args->f_id.flags = tcp->th_flags;
1790                         }
1791                         break;
1792
1793                 case IPPROTO_UDP:
1794                         {
1795                                 struct udphdr *udp;
1796
1797                                 PULLUP_TO(hlen + sizeof(struct udphdr));
1798                                 udp = L3HDR(struct udphdr, ip);
1799                                 dst_port = udp->uh_dport;
1800                                 src_port = udp->uh_sport;
1801                         }
1802                         break;
1803
1804                 case IPPROTO_ICMP:
1805                         PULLUP_TO(hlen + 4);    /* type, code and checksum. */
1806                         args->f_id.flags = L3HDR(struct icmp, ip)->icmp_type;
1807                         break;
1808
1809                 default:
1810                         break;
1811                 }
1812         }
1813
1814 #undef PULLUP_TO
1815
1816         args->f_id.src_ip = ntohl(src_ip.s_addr);
1817         args->f_id.dst_ip = ntohl(dst_ip.s_addr);
1818         args->f_id.src_port = src_port = ntohs(src_port);
1819         args->f_id.dst_port = dst_port = ntohs(dst_port);
1820
1821 after_ip_checks:
1822         if (args->rule) {
1823                 /*
1824                  * Packet has already been tagged. Look for the next rule
1825                  * to restart processing.
1826                  *
1827                  * If fw_one_pass != 0 then just accept it.
1828                  * XXX should not happen here, but optimized out in
1829                  * the caller.
1830                  */
1831                 if (fw_one_pass)
1832                         return IP_FW_PASS;
1833
1834                 /* This rule is being/has been flushed */
1835                 if (ipfw_flushing)
1836                         return IP_FW_DENY;
1837
1838                 KASSERT(args->rule->cpuid == mycpuid,
1839                         ("rule used on cpu%d\n", mycpuid));
1840
1841                 /* This rule was deleted */
1842                 if (args->rule->rule_flags & IPFW_RULE_F_INVALID)
1843                         return IP_FW_DENY;
1844
1845                 f = args->rule->next_rule;
1846                 if (f == NULL)
1847                         f = lookup_next_rule(args->rule);
1848         } else {
1849                 /*
1850                  * Find the starting rule. It can be either the first
1851                  * one, or the one after divert_rule if asked so.
1852                  */
1853                 int skipto;
1854
1855                 mtag = m_tag_find(m, PACKET_TAG_IPFW_DIVERT, NULL);
1856                 if (mtag != NULL) {
1857                         divinfo = m_tag_data(mtag);
1858                         skipto = divinfo->skipto;
1859                 } else {
1860                         skipto = 0;
1861                 }
1862
1863                 f = ctx->ipfw_layer3_chain;
1864                 if (args->eh == NULL && skipto != 0) {
1865                         /* No skipto during rule flushing */
1866                         if (ipfw_flushing)
1867                                 return IP_FW_DENY;
1868
1869                         if (skipto >= IPFW_DEFAULT_RULE)
1870                                 return IP_FW_DENY; /* invalid */
1871
1872                         while (f && f->rulenum <= skipto)
1873                                 f = f->next;
1874                         if (f == NULL)  /* drop packet */
1875                                 return IP_FW_DENY;
1876                 } else if (ipfw_flushing) {
1877                         /* Rules are being flushed; skip to default rule */
1878                         f = ctx->ipfw_default_rule;
1879                 }
1880         }
1881         if ((mtag = m_tag_find(m, PACKET_TAG_IPFW_DIVERT, NULL)) != NULL)
1882                 m_tag_delete(m, mtag);
1883
1884         /*
1885          * Now scan the rules, and parse microinstructions for each rule.
1886          */
1887         for (; f; f = f->next) {
1888                 int l, cmdlen;
1889                 ipfw_insn *cmd;
1890                 int skip_or; /* skip rest of OR block */
1891
1892 again:
1893                 if (ctx->ipfw_set_disable & (1 << f->set))
1894                         continue;
1895
1896                 skip_or = 0;
1897                 for (l = f->cmd_len, cmd = f->cmd; l > 0;
1898                      l -= cmdlen, cmd += cmdlen) {
1899                         int match, deny;
1900
1901                         /*
1902                          * check_body is a jump target used when we find a
1903                          * CHECK_STATE, and need to jump to the body of
1904                          * the target rule.
1905                          */
1906
1907 check_body:
1908                         cmdlen = F_LEN(cmd);
1909                         /*
1910                          * An OR block (insn_1 || .. || insn_n) has the
1911                          * F_OR bit set in all but the last instruction.
1912                          * The first match will set "skip_or", and cause
1913                          * the following instructions to be skipped until
1914                          * past the one with the F_OR bit clear.
1915                          */
1916                         if (skip_or) {          /* skip this instruction */
1917                                 if ((cmd->len & F_OR) == 0)
1918                                         skip_or = 0;    /* next one is good */
1919                                 continue;
1920                         }
1921                         match = 0; /* set to 1 if we succeed */
1922
1923                         switch (cmd->opcode) {
1924                         /*
1925                          * The first set of opcodes compares the packet's
1926                          * fields with some pattern, setting 'match' if a
1927                          * match is found. At the end of the loop there is
1928                          * logic to deal with F_NOT and F_OR flags associated
1929                          * with the opcode.
1930                          */
1931                         case O_NOP:
1932                                 match = 1;
1933                                 break;
1934
1935                         case O_FORWARD_MAC:
1936                                 kprintf("ipfw: opcode %d unimplemented\n",
1937                                         cmd->opcode);
1938                                 break;
1939
1940                         case O_GID:
1941                         case O_UID:
1942                                 /*
1943                                  * We only check offset == 0 && proto != 0,
1944                                  * as this ensures that we have an IPv4
1945                                  * packet with the ports info.
1946                                  */
1947                                 if (offset!=0)
1948                                         break;
1949
1950                                 match = ipfw_match_uid(&args->f_id, oif,
1951                                         cmd->opcode,
1952                                         (uid_t)((ipfw_insn_u32 *)cmd)->d[0],
1953                                         &deny);
1954                                 if (deny)
1955                                         return IP_FW_DENY;
1956                                 break;
1957
1958                         case O_RECV:
1959                                 match = iface_match(m->m_pkthdr.rcvif,
1960                                     (ipfw_insn_if *)cmd);
1961                                 break;
1962
1963                         case O_XMIT:
1964                                 match = iface_match(oif, (ipfw_insn_if *)cmd);
1965                                 break;
1966
1967                         case O_VIA:
1968                                 match = iface_match(oif ? oif :
1969                                     m->m_pkthdr.rcvif, (ipfw_insn_if *)cmd);
1970                                 break;
1971
1972                         case O_MACADDR2:
1973                                 if (args->eh != NULL) { /* have MAC header */
1974                                         uint32_t *want = (uint32_t *)
1975                                                 ((ipfw_insn_mac *)cmd)->addr;
1976                                         uint32_t *mask = (uint32_t *)
1977                                                 ((ipfw_insn_mac *)cmd)->mask;
1978                                         uint32_t *hdr = (uint32_t *)args->eh;
1979
1980                                         match =
1981                                         (want[0] == (hdr[0] & mask[0]) &&
1982                                          want[1] == (hdr[1] & mask[1]) &&
1983                                          want[2] == (hdr[2] & mask[2]));
1984                                 }
1985                                 break;
1986
1987                         case O_MAC_TYPE:
1988                                 if (args->eh != NULL) {
1989                                         uint16_t t =
1990                                             ntohs(args->eh->ether_type);
1991                                         uint16_t *p =
1992                                             ((ipfw_insn_u16 *)cmd)->ports;
1993                                         int i;
1994
1995                                         /* Special vlan handling */
1996                                         if (m->m_flags & M_VLANTAG)
1997                                                 t = ETHERTYPE_VLAN;
1998
1999                                         for (i = cmdlen - 1; !match && i > 0;
2000                                              i--, p += 2) {
2001                                                 match =
2002                                                 (t >= p[0] && t <= p[1]);
2003                                         }
2004                                 }
2005                                 break;
2006
2007                         case O_FRAG:
2008                                 match = (hlen > 0 && offset != 0);
2009                                 break;
2010
2011                         case O_IN:      /* "out" is "not in" */
2012                                 match = (oif == NULL);
2013                                 break;
2014
2015                         case O_LAYER2:
2016                                 match = (args->eh != NULL);
2017                                 break;
2018
2019                         case O_PROTO:
2020                                 /*
2021                                  * We do not allow an arg of 0 so the
2022                                  * check of "proto" only suffices.
2023                                  */
2024                                 match = (proto == cmd->arg1);
2025                                 break;
2026
2027                         case O_IP_SRC:
2028                                 match = (hlen > 0 &&
2029                                     ((ipfw_insn_ip *)cmd)->addr.s_addr ==
2030                                     src_ip.s_addr);
2031                                 break;
2032
2033                         case O_IP_SRC_MASK:
2034                                 match = (hlen > 0 &&
2035                                     ((ipfw_insn_ip *)cmd)->addr.s_addr ==
2036                                      (src_ip.s_addr &
2037                                      ((ipfw_insn_ip *)cmd)->mask.s_addr));
2038                                 break;
2039
2040                         case O_IP_SRC_ME:
2041                                 if (hlen > 0) {
2042                                         struct ifnet *tif;
2043
2044                                         tif = INADDR_TO_IFP(&src_ip);
2045                                         match = (tif != NULL);
2046                                 }
2047                                 break;
2048
2049                         case O_IP_DST_SET:
2050                         case O_IP_SRC_SET:
2051                                 if (hlen > 0) {
2052                                         uint32_t *d = (uint32_t *)(cmd + 1);
2053                                         uint32_t addr =
2054                                             cmd->opcode == O_IP_DST_SET ?
2055                                                 args->f_id.dst_ip :
2056                                                 args->f_id.src_ip;
2057
2058                                         if (addr < d[0])
2059                                                 break;
2060                                         addr -= d[0]; /* subtract base */
2061                                         match =
2062                                         (addr < cmd->arg1) &&
2063                                          (d[1 + (addr >> 5)] &
2064                                           (1 << (addr & 0x1f)));
2065                                 }
2066                                 break;
2067
2068                         case O_IP_DST:
2069                                 match = (hlen > 0 &&
2070                                     ((ipfw_insn_ip *)cmd)->addr.s_addr ==
2071                                     dst_ip.s_addr);
2072                                 break;
2073
2074                         case O_IP_DST_MASK:
2075                                 match = (hlen > 0) &&
2076                                     (((ipfw_insn_ip *)cmd)->addr.s_addr ==
2077                                      (dst_ip.s_addr &
2078                                      ((ipfw_insn_ip *)cmd)->mask.s_addr));
2079                                 break;
2080
2081                         case O_IP_DST_ME:
2082                                 if (hlen > 0) {
2083                                         struct ifnet *tif;
2084
2085                                         tif = INADDR_TO_IFP(&dst_ip);
2086                                         match = (tif != NULL);
2087                                 }
2088                                 break;
2089
2090                         case O_IP_SRCPORT:
2091                         case O_IP_DSTPORT:
2092                                 /*
2093                                  * offset == 0 && proto != 0 is enough
2094                                  * to guarantee that we have an IPv4
2095                                  * packet with port info.
2096                                  */
2097                                 if ((proto==IPPROTO_UDP || proto==IPPROTO_TCP)
2098                                     && offset == 0) {
2099                                         uint16_t x =
2100                                             (cmd->opcode == O_IP_SRCPORT) ?
2101                                                 src_port : dst_port ;
2102                                         uint16_t *p =
2103                                             ((ipfw_insn_u16 *)cmd)->ports;
2104                                         int i;
2105
2106                                         for (i = cmdlen - 1; !match && i > 0;
2107                                              i--, p += 2) {
2108                                                 match =
2109                                                 (x >= p[0] && x <= p[1]);
2110                                         }
2111                                 }
2112                                 break;
2113
2114                         case O_ICMPTYPE:
2115                                 match = (offset == 0 && proto==IPPROTO_ICMP &&
2116                                     icmptype_match(ip, (ipfw_insn_u32 *)cmd));
2117                                 break;
2118
2119                         case O_IPOPT:
2120                                 match = (hlen > 0 && ipopts_match(ip, cmd));
2121                                 break;
2122
2123                         case O_IPVER:
2124                                 match = (hlen > 0 && cmd->arg1 == ip->ip_v);
2125                                 break;
2126
2127                         case O_IPTTL:
2128                                 match = (hlen > 0 && cmd->arg1 == ip->ip_ttl);
2129                                 break;
2130
2131                         case O_IPID:
2132                                 match = (hlen > 0 &&
2133                                     cmd->arg1 == ntohs(ip->ip_id));
2134                                 break;
2135
2136                         case O_IPLEN:
2137                                 match = (hlen > 0 && cmd->arg1 == ip_len);
2138                                 break;
2139
2140                         case O_IPPRECEDENCE:
2141                                 match = (hlen > 0 &&
2142                                     (cmd->arg1 == (ip->ip_tos & 0xe0)));
2143                                 break;
2144
2145                         case O_IPTOS:
2146                                 match = (hlen > 0 &&
2147                                     flags_match(cmd, ip->ip_tos));
2148                                 break;
2149
2150                         case O_TCPFLAGS:
2151                                 match = (proto == IPPROTO_TCP && offset == 0 &&
2152                                     flags_match(cmd,
2153                                         L3HDR(struct tcphdr,ip)->th_flags));
2154                                 break;
2155
2156                         case O_TCPOPTS:
2157                                 match = (proto == IPPROTO_TCP && offset == 0 &&
2158                                     tcpopts_match(ip, cmd));
2159                                 break;
2160
2161                         case O_TCPSEQ:
2162                                 match = (proto == IPPROTO_TCP && offset == 0 &&
2163                                     ((ipfw_insn_u32 *)cmd)->d[0] ==
2164                                         L3HDR(struct tcphdr,ip)->th_seq);
2165                                 break;
2166
2167                         case O_TCPACK:
2168                                 match = (proto == IPPROTO_TCP && offset == 0 &&
2169                                     ((ipfw_insn_u32 *)cmd)->d[0] ==
2170                                         L3HDR(struct tcphdr,ip)->th_ack);
2171                                 break;
2172
2173                         case O_TCPWIN:
2174                                 match = (proto == IPPROTO_TCP && offset == 0 &&
2175                                     cmd->arg1 ==
2176                                         L3HDR(struct tcphdr,ip)->th_win);
2177                                 break;
2178
2179                         case O_ESTAB:
2180                                 /* reject packets which have SYN only */
2181                                 /* XXX should i also check for TH_ACK ? */
2182                                 match = (proto == IPPROTO_TCP && offset == 0 &&
2183                                     (L3HDR(struct tcphdr,ip)->th_flags &
2184                                      (TH_RST | TH_ACK | TH_SYN)) != TH_SYN);
2185                                 break;
2186
2187                         case O_LOG:
2188                                 if (fw_verbose)
2189                                         ipfw_log(f, hlen, args->eh, m, oif);
2190                                 match = 1;
2191                                 break;
2192
2193                         case O_PROB:
2194                                 match = (krandom() <
2195                                         ((ipfw_insn_u32 *)cmd)->d[0]);
2196                                 break;
2197
2198                         /*
2199                          * The second set of opcodes represents 'actions',
2200                          * i.e. the terminal part of a rule once the packet
2201                          * matches all previous patterns.
2202                          * Typically there is only one action for each rule,
2203                          * and the opcode is stored at the end of the rule
2204                          * (but there are exceptions -- see below).
2205                          *
2206                          * In general, here we set retval and terminate the
2207                          * outer loop (would be a 'break 3' in some language,
2208                          * but we need to do a 'goto done').
2209                          *
2210                          * Exceptions:
2211                          * O_COUNT and O_SKIPTO actions:
2212                          *   instead of terminating, we jump to the next rule
2213                          *   ('goto next_rule', equivalent to a 'break 2'),
2214                          *   or to the SKIPTO target ('goto again' after
2215                          *   having set f, cmd and l), respectively.
2216                          *
2217                          * O_LIMIT and O_KEEP_STATE: these opcodes are
2218                          *   not real 'actions', and are stored right
2219                          *   before the 'action' part of the rule.
2220                          *   These opcodes try to install an entry in the
2221                          *   state tables; if successful, we continue with
2222                          *   the next opcode (match=1; break;), otherwise
2223                          *   the packet must be dropped ('goto done' after
2224                          *   setting retval).  If static rules are changed
2225                          *   during the state installation, the packet will
2226                          *   be dropped and rule's stats will not beupdated
2227                          *   ('return IP_FW_DENY').
2228                          *
2229                          * O_PROBE_STATE and O_CHECK_STATE: these opcodes
2230                          *   cause a lookup of the state table, and a jump
2231                          *   to the 'action' part of the parent rule
2232                          *   ('goto check_body') if an entry is found, or
2233                          *   (CHECK_STATE only) a jump to the next rule if
2234                          *   the entry is not found ('goto next_rule').
2235                          *   The result of the lookup is cached to make
2236                          *   further instances of these opcodes are
2237                          *   effectively NOPs.  If static rules are changed
2238                          *   during the state looking up, the packet will
2239                          *   be dropped and rule's stats will not be updated
2240                          *   ('return IP_FW_DENY').
2241                          */
2242                         case O_LIMIT:
2243                         case O_KEEP_STATE:
2244                                 if (!(f->rule_flags & IPFW_RULE_F_STATE)) {
2245                                         kprintf("%s rule (%d) is not ready "
2246                                                 "on cpu%d\n",
2247                                                 cmd->opcode == O_LIMIT ?
2248                                                 "limit" : "keep state",
2249                                                 f->rulenum, f->cpuid);
2250                                         goto next_rule;
2251                                 }
2252                                 if (install_state(f,
2253                                     (ipfw_insn_limit *)cmd, args, &deny)) {
2254                                         if (deny)
2255                                                 return IP_FW_DENY;
2256
2257                                         retval = IP_FW_DENY;
2258                                         goto done; /* error/limit violation */
2259                                 }
2260                                 if (deny)
2261                                         return IP_FW_DENY;
2262                                 match = 1;
2263                                 break;
2264
2265                         case O_PROBE_STATE:
2266                         case O_CHECK_STATE:
2267                                 /*
2268                                  * dynamic rules are checked at the first
2269                                  * keep-state or check-state occurrence,
2270                                  * with the result being stored in dyn_dir.
2271                                  * The compiler introduces a PROBE_STATE
2272                                  * instruction for us when we have a
2273                                  * KEEP_STATE (because PROBE_STATE needs
2274                                  * to be run first).
2275                                  */
2276                                 if (dyn_dir == MATCH_UNKNOWN) {
2277                                         dyn_f = lookup_rule(&args->f_id,
2278                                                 &dyn_dir,
2279                                                 proto == IPPROTO_TCP ?
2280                                                 L3HDR(struct tcphdr, ip) : NULL,
2281                                                 ip_len, &deny);
2282                                         if (deny)
2283                                                 return IP_FW_DENY;
2284                                         if (dyn_f != NULL) {
2285                                                 /*
2286                                                  * Found a rule from a dynamic
2287                                                  * entry; jump to the 'action'
2288                                                  * part of the rule.
2289                                                  */
2290                                                 f = dyn_f;
2291                                                 cmd = ACTION_PTR(f);
2292                                                 l = f->cmd_len - f->act_ofs;
2293                                                 goto check_body;
2294                                         }
2295                                 }
2296                                 /*
2297                                  * Dynamic entry not found. If CHECK_STATE,
2298                                  * skip to next rule, if PROBE_STATE just
2299                                  * ignore and continue with next opcode.
2300                                  */
2301                                 if (cmd->opcode == O_CHECK_STATE)
2302                                         goto next_rule;
2303                                 else if (!(f->rule_flags & IPFW_RULE_F_STATE))
2304                                         goto next_rule; /* not ready yet */
2305                                 match = 1;
2306                                 break;
2307
2308                         case O_ACCEPT:
2309                                 retval = IP_FW_PASS;    /* accept */
2310                                 goto done;
2311
2312                         case O_PIPE:
2313                         case O_QUEUE:
2314                                 args->rule = f; /* report matching rule */
2315                                 args->cookie = cmd->arg1;
2316                                 retval = IP_FW_DUMMYNET;
2317                                 goto done;
2318
2319                         case O_DIVERT:
2320                         case O_TEE:
2321                                 if (args->eh) /* not on layer 2 */
2322                                         break;
2323
2324                                 mtag = m_tag_get(PACKET_TAG_IPFW_DIVERT,
2325                                                  sizeof(*divinfo), MB_DONTWAIT);
2326                                 if (mtag == NULL) {
2327                                         retval = IP_FW_DENY;
2328                                         goto done;
2329                                 }
2330                                 divinfo = m_tag_data(mtag);
2331
2332                                 divinfo->skipto = f->rulenum;
2333                                 divinfo->port = cmd->arg1;
2334                                 divinfo->tee = (cmd->opcode == O_TEE);
2335                                 m_tag_prepend(m, mtag);
2336
2337                                 args->cookie = cmd->arg1;
2338                                 retval = (cmd->opcode == O_DIVERT) ?
2339                                          IP_FW_DIVERT : IP_FW_TEE;
2340                                 goto done;
2341
2342                         case O_COUNT:
2343                         case O_SKIPTO:
2344                                 f->pcnt++;      /* update stats */
2345                                 f->bcnt += ip_len;
2346                                 f->timestamp = time_second;
2347                                 if (cmd->opcode == O_COUNT)
2348                                         goto next_rule;
2349                                 /* handle skipto */
2350                                 if (f->next_rule == NULL)
2351                                         lookup_next_rule(f);
2352                                 f = f->next_rule;
2353                                 goto again;
2354
2355                         case O_REJECT:
2356                                 /*
2357                                  * Drop the packet and send a reject notice
2358                                  * if the packet is not ICMP (or is an ICMP
2359                                  * query), and it is not multicast/broadcast.
2360                                  */
2361                                 if (hlen > 0 &&
2362                                     (proto != IPPROTO_ICMP ||
2363                                      is_icmp_query(ip)) &&
2364                                     !(m->m_flags & (M_BCAST|M_MCAST)) &&
2365                                     !IN_MULTICAST(ntohl(dst_ip.s_addr))) {
2366                                         /*
2367                                          * Update statistics before the possible
2368                                          * blocking 'send_reject'
2369                                          */
2370                                         f->pcnt++;
2371                                         f->bcnt += ip_len;
2372                                         f->timestamp = time_second;
2373
2374                                         send_reject(args, cmd->arg1,
2375                                             offset,ip_len);
2376                                         m = args->m;
2377
2378                                         /*
2379                                          * Return directly here, rule stats
2380                                          * have been updated above.
2381                                          */
2382                                         return IP_FW_DENY;
2383                                 }
2384                                 /* FALLTHROUGH */
2385                         case O_DENY:
2386                                 retval = IP_FW_DENY;
2387                                 goto done;
2388
2389                         case O_FORWARD_IP:
2390                                 if (args->eh)   /* not valid on layer2 pkts */
2391                                         break;
2392                                 if (!dyn_f || dyn_dir == MATCH_FORWARD) {
2393                                         struct sockaddr_in *sin;
2394
2395                                         mtag = m_tag_get(PACKET_TAG_IPFORWARD,
2396                                                sizeof(*sin), MB_DONTWAIT);
2397                                         if (mtag == NULL) {
2398                                                 retval = IP_FW_DENY;
2399                                                 goto done;
2400                                         }
2401                                         sin = m_tag_data(mtag);
2402
2403                                         /* Structure copy */
2404                                         *sin = ((ipfw_insn_sa *)cmd)->sa;
2405
2406                                         m_tag_prepend(m, mtag);
2407                                         m->m_pkthdr.fw_flags |=
2408                                                 IPFORWARD_MBUF_TAGGED;
2409                                 }
2410                                 retval = IP_FW_PASS;
2411                                 goto done;
2412
2413                         default:
2414                                 panic("-- unknown opcode %d\n", cmd->opcode);
2415                         } /* end of switch() on opcodes */
2416
2417                         if (cmd->len & F_NOT)
2418                                 match = !match;
2419
2420                         if (match) {
2421                                 if (cmd->len & F_OR)
2422                                         skip_or = 1;
2423                         } else {
2424                                 if (!(cmd->len & F_OR)) /* not an OR block, */
2425                                         break;          /* try next rule    */
2426                         }
2427
2428                 }       /* end of inner for, scan opcodes */
2429
2430 next_rule:;             /* try next rule                */
2431
2432         }               /* end of outer for, scan rules */
2433         kprintf("+++ ipfw: ouch!, skip past end of rules, denying packet\n");
2434         return IP_FW_DENY;
2435
2436 done:
2437         /* Update statistics */
2438         f->pcnt++;
2439         f->bcnt += ip_len;
2440         f->timestamp = time_second;
2441         return retval;
2442
2443 pullup_failed:
2444         if (fw_verbose)
2445                 kprintf("pullup failed\n");
2446         return IP_FW_DENY;
2447 }
2448
2449 static void
2450 ipfw_dummynet_io(struct mbuf *m, int pipe_nr, int dir, struct ip_fw_args *fwa)
2451 {
2452         struct m_tag *mtag;
2453         struct dn_pkt *pkt;
2454         ipfw_insn *cmd;
2455         const struct ipfw_flow_id *id;
2456         struct dn_flow_id *fid;
2457
2458         M_ASSERTPKTHDR(m);
2459
2460         mtag = m_tag_get(PACKET_TAG_DUMMYNET, sizeof(*pkt), MB_DONTWAIT);
2461         if (mtag == NULL) {
2462                 m_freem(m);
2463                 return;
2464         }
2465         m_tag_prepend(m, mtag);
2466
2467         pkt = m_tag_data(mtag);
2468         bzero(pkt, sizeof(*pkt));
2469
2470         cmd = fwa->rule->cmd + fwa->rule->act_ofs;
2471         if (cmd->opcode == O_LOG)
2472                 cmd += F_LEN(cmd);
2473         KASSERT(cmd->opcode == O_PIPE || cmd->opcode == O_QUEUE,
2474                 ("Rule is not PIPE or QUEUE, opcode %d\n", cmd->opcode));
2475
2476         pkt->dn_m = m;
2477         pkt->dn_flags = (dir & DN_FLAGS_DIR_MASK);
2478         pkt->ifp = fwa->oif;
2479         pkt->cpuid = mycpuid;
2480         pkt->pipe_nr = pipe_nr;
2481
2482         id = &fwa->f_id;
2483         fid = &pkt->id;
2484         fid->fid_dst_ip = id->dst_ip;
2485         fid->fid_src_ip = id->src_ip;
2486         fid->fid_dst_port = id->dst_port;
2487         fid->fid_src_port = id->src_port;
2488         fid->fid_proto = id->proto;
2489         fid->fid_flags = id->flags;
2490
2491         ipfw_ref_rule(fwa->rule);
2492         pkt->dn_priv = fwa->rule;
2493         pkt->dn_unref_priv = ipfw_unref_rule;
2494
2495         if (cmd->opcode == O_PIPE)
2496                 pkt->dn_flags |= DN_FLAGS_IS_PIPE;
2497
2498         m->m_pkthdr.fw_flags |= DUMMYNET_MBUF_TAGGED;
2499 }
2500
2501 /*
2502  * When a rule is added/deleted, clear the next_rule pointers in all rules.
2503  * These will be reconstructed on the fly as packets are matched.
2504  * Must be called at splimp().
2505  */
2506 static void
2507 ipfw_flush_rule_ptrs(struct ipfw_context *ctx)
2508 {
2509         struct ip_fw *rule;
2510
2511         for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next)
2512                 rule->next_rule = NULL;
2513 }
2514
2515 static __inline void
2516 ipfw_inc_static_count(struct ip_fw *rule)
2517 {
2518         KKASSERT(mycpuid == 0);
2519
2520         static_count++;
2521         static_ioc_len += IOC_RULESIZE(rule);
2522 }
2523
2524 static __inline void
2525 ipfw_dec_static_count(struct ip_fw *rule)
2526 {
2527         int l = IOC_RULESIZE(rule);
2528
2529         KKASSERT(mycpuid == 0);
2530
2531         KASSERT(static_count > 0, ("invalid static count %u\n", static_count));
2532         static_count--;
2533
2534         KASSERT(static_ioc_len >= l,
2535                 ("invalid static len %u\n", static_ioc_len));
2536         static_ioc_len -= l;
2537 }
2538
2539 static void
2540 ipfw_link_sibling(struct netmsg_ipfw *fwmsg, struct ip_fw *rule)
2541 {
2542         if (fwmsg->sibling != NULL) {
2543                 KKASSERT(mycpuid > 0 && fwmsg->sibling->cpuid == mycpuid - 1);
2544                 fwmsg->sibling->sibling = rule;
2545         }
2546         fwmsg->sibling = rule;
2547 }
2548
2549 static struct ip_fw *
2550 ipfw_create_rule(const struct ipfw_ioc_rule *ioc_rule, struct ip_fw_stub *stub)
2551 {
2552         struct ip_fw *rule;
2553
2554         rule = kmalloc(RULESIZE(ioc_rule), M_IPFW, M_WAITOK | M_ZERO);
2555
2556         rule->act_ofs = ioc_rule->act_ofs;
2557         rule->cmd_len = ioc_rule->cmd_len;
2558         rule->rulenum = ioc_rule->rulenum;
2559         rule->set = ioc_rule->set;
2560         rule->usr_flags = ioc_rule->usr_flags;
2561
2562         bcopy(ioc_rule->cmd, rule->cmd, rule->cmd_len * 4 /* XXX */);
2563
2564         rule->refcnt = 1;
2565         rule->cpuid = mycpuid;
2566
2567         rule->stub = stub;
2568         if (stub != NULL)
2569                 stub->rule[mycpuid] = rule;
2570
2571         return rule;
2572 }
2573
2574 static void
2575 ipfw_add_rule_dispatch(struct netmsg *nmsg)
2576 {
2577         struct netmsg_ipfw *fwmsg = (struct netmsg_ipfw *)nmsg;
2578         struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2579         struct ip_fw *rule;
2580
2581         rule = ipfw_create_rule(fwmsg->ioc_rule, fwmsg->stub);
2582
2583         /*
2584          * Bump generation after ipfw_create_rule(),
2585          * since this function is blocking
2586          */
2587         ctx->ipfw_gen++;
2588
2589         /*
2590          * Insert rule into the pre-determined position
2591          */
2592         if (fwmsg->prev_rule != NULL) {
2593                 struct ip_fw *prev, *next;
2594
2595                 prev = fwmsg->prev_rule;
2596                 KKASSERT(prev->cpuid == mycpuid);
2597
2598                 next = fwmsg->next_rule;
2599                 KKASSERT(next->cpuid == mycpuid);
2600
2601                 rule->next = next;
2602                 prev->next = rule;
2603
2604                 /*
2605                  * Move to the position on the next CPU
2606                  * before the msg is forwarded.
2607                  */
2608                 fwmsg->prev_rule = prev->sibling;
2609                 fwmsg->next_rule = next->sibling;
2610         } else {
2611                 KKASSERT(fwmsg->next_rule == NULL);
2612                 rule->next = ctx->ipfw_layer3_chain;
2613                 ctx->ipfw_layer3_chain = rule;
2614         }
2615
2616         /* Link rule CPU sibling */
2617         ipfw_link_sibling(fwmsg, rule);
2618
2619         ipfw_flush_rule_ptrs(ctx);
2620
2621         if (mycpuid == 0) {
2622                 /* Statistics only need to be updated once */
2623                 ipfw_inc_static_count(rule);
2624
2625                 /* Return the rule on CPU0 */
2626                 nmsg->nm_lmsg.u.ms_resultp = rule;
2627         }
2628
2629         ifnet_forwardmsg(&nmsg->nm_lmsg, mycpuid + 1);
2630 }
2631
2632 static void
2633 ipfw_enable_state_dispatch(struct netmsg *nmsg)
2634 {
2635         struct lwkt_msg *lmsg = &nmsg->nm_lmsg;
2636         struct ip_fw *rule = lmsg->u.ms_resultp;
2637         struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2638
2639         ctx->ipfw_gen++;
2640
2641         KKASSERT(rule->cpuid == mycpuid);
2642         KKASSERT(rule->stub != NULL && rule->stub->rule[mycpuid] == rule);
2643         KKASSERT(!(rule->rule_flags & IPFW_RULE_F_STATE));
2644         rule->rule_flags |= IPFW_RULE_F_STATE;
2645         lmsg->u.ms_resultp = rule->sibling;
2646
2647         ifnet_forwardmsg(lmsg, mycpuid + 1);
2648 }
2649
2650 /*
2651  * Add a new rule to the list.  Copy the rule into a malloc'ed area,
2652  * then possibly create a rule number and add the rule to the list.
2653  * Update the rule_number in the input struct so the caller knows
2654  * it as well.
2655  */
2656 static void
2657 ipfw_add_rule(struct ipfw_ioc_rule *ioc_rule, uint32_t rule_flags)
2658 {
2659         struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2660         struct netmsg_ipfw fwmsg;
2661         struct netmsg *nmsg;
2662         struct ip_fw *f, *prev, *rule;
2663         struct ip_fw_stub *stub;
2664
2665         IPFW_ASSERT_CFGPORT(&curthread->td_msgport);
2666
2667         /*
2668          * If rulenum is 0, find highest numbered rule before the
2669          * default rule, and add rule number incremental step.
2670          */
2671         if (ioc_rule->rulenum == 0) {
2672                 int step = autoinc_step;
2673
2674                 KKASSERT(step >= IPFW_AUTOINC_STEP_MIN &&
2675                          step <= IPFW_AUTOINC_STEP_MAX);
2676
2677                 /*
2678                  * Locate the highest numbered rule before default
2679                  */
2680                 for (f = ctx->ipfw_layer3_chain; f; f = f->next) {
2681                         if (f->rulenum == IPFW_DEFAULT_RULE)
2682                                 break;
2683                         ioc_rule->rulenum = f->rulenum;
2684                 }
2685                 if (ioc_rule->rulenum < IPFW_DEFAULT_RULE - step)
2686                         ioc_rule->rulenum += step;
2687         }
2688         KASSERT(ioc_rule->rulenum != IPFW_DEFAULT_RULE &&
2689                 ioc_rule->rulenum != 0,
2690                 ("invalid rule num %d\n", ioc_rule->rulenum));
2691
2692         /*
2693          * Now find the right place for the new rule in the sorted list.
2694          */
2695         for (prev = NULL, f = ctx->ipfw_layer3_chain; f;
2696              prev = f, f = f->next) {
2697                 if (f->rulenum > ioc_rule->rulenum) {
2698                         /* Found the location */
2699                         break;
2700                 }
2701         }
2702         KASSERT(f != NULL, ("no default rule?!\n"));
2703
2704         if (rule_flags & IPFW_RULE_F_STATE) {
2705                 int size;
2706
2707                 /*
2708                  * If the new rule will create states, then allocate
2709                  * a rule stub, which will be referenced by states
2710                  * (dyn rules)
2711                  */
2712                 size = sizeof(*stub) + ((ncpus - 1) * sizeof(struct ip_fw *));
2713                 stub = kmalloc(size, M_IPFW, M_WAITOK | M_ZERO);
2714         } else {
2715                 stub = NULL;
2716         }
2717
2718         /*
2719          * Duplicate the rule onto each CPU.
2720          * The rule duplicated on CPU0 will be returned.
2721          */
2722         bzero(&fwmsg, sizeof(fwmsg));
2723         nmsg = &fwmsg.nmsg;
2724         netmsg_init(nmsg, &curthread->td_msgport, 0, ipfw_add_rule_dispatch);
2725         fwmsg.ioc_rule = ioc_rule;
2726         fwmsg.prev_rule = prev;
2727         fwmsg.next_rule = prev == NULL ? NULL : f;
2728         fwmsg.stub = stub;
2729
2730         ifnet_domsg(&nmsg->nm_lmsg, 0);
2731         KKASSERT(fwmsg.prev_rule == NULL && fwmsg.next_rule == NULL);
2732
2733         rule = nmsg->nm_lmsg.u.ms_resultp;
2734         KKASSERT(rule != NULL && rule->cpuid == mycpuid);
2735
2736         if (rule_flags & IPFW_RULE_F_STATE) {
2737                 /*
2738                  * Turn on state flag, _after_ everything on all
2739                  * CPUs have been setup.
2740                  */
2741                 bzero(nmsg, sizeof(*nmsg));
2742                 netmsg_init(nmsg, &curthread->td_msgport, 0,
2743                             ipfw_enable_state_dispatch);
2744                 nmsg->nm_lmsg.u.ms_resultp = rule;
2745
2746                 ifnet_domsg(&nmsg->nm_lmsg, 0);
2747                 KKASSERT(nmsg->nm_lmsg.u.ms_resultp == NULL);
2748         }
2749
2750         DPRINTF("++ installed rule %d, static count now %d\n",
2751                 rule->rulenum, static_count);
2752 }
2753
2754 /**
2755  * Free storage associated with a static rule (including derived
2756  * dynamic rules).
2757  * The caller is in charge of clearing rule pointers to avoid
2758  * dangling pointers.
2759  * @return a pointer to the next entry.
2760  * Arguments are not checked, so they better be correct.
2761  * Must be called at splimp().
2762  */
2763 static struct ip_fw *
2764 ipfw_delete_rule(struct ipfw_context *ctx,
2765                  struct ip_fw *prev, struct ip_fw *rule)
2766 {
2767         struct ip_fw *n;
2768         struct ip_fw_stub *stub;
2769
2770         ctx->ipfw_gen++;
2771
2772         /* STATE flag should have been cleared before we reach here */
2773         KKASSERT((rule->rule_flags & IPFW_RULE_F_STATE) == 0);
2774
2775         stub = rule->stub;
2776         n = rule->next;
2777         if (prev == NULL)
2778                 ctx->ipfw_layer3_chain = n;
2779         else
2780                 prev->next = n;
2781
2782         /* Mark the rule as invalid */
2783         rule->rule_flags |= IPFW_RULE_F_INVALID;
2784         rule->next_rule = NULL;
2785         rule->sibling = NULL;
2786         rule->stub = NULL;
2787 #ifdef foo
2788         /* Don't reset cpuid here; keep various assertion working */
2789         rule->cpuid = -1;
2790 #endif
2791
2792         /* Statistics only need to be updated once */
2793         if (mycpuid == 0)
2794                 ipfw_dec_static_count(rule);
2795
2796         /* Free 'stub' on the last CPU */
2797         if (stub != NULL && mycpuid == ncpus - 1)
2798                 kfree(stub, M_IPFW);
2799
2800         /* Try to free this rule */
2801         ipfw_free_rule(rule);
2802
2803         /* Return the next rule */
2804         return n;
2805 }
2806
2807 static void
2808 ipfw_flush_dispatch(struct netmsg *nmsg)
2809 {
2810         struct lwkt_msg *lmsg = &nmsg->nm_lmsg;
2811         int kill_default = lmsg->u.ms_result;
2812         struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2813         struct ip_fw *rule;
2814
2815         ipfw_flush_rule_ptrs(ctx); /* more efficient to do outside the loop */
2816
2817         while ((rule = ctx->ipfw_layer3_chain) != NULL &&
2818                (kill_default || rule->rulenum != IPFW_DEFAULT_RULE))
2819                 ipfw_delete_rule(ctx, NULL, rule);
2820
2821         ifnet_forwardmsg(lmsg, mycpuid + 1);
2822 }
2823
2824 static void
2825 ipfw_disable_rule_state_dispatch(struct netmsg *nmsg)
2826 {
2827         struct netmsg_del *dmsg = (struct netmsg_del *)nmsg;
2828         struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2829         struct ip_fw *rule;
2830
2831         ctx->ipfw_gen++;
2832
2833         rule = dmsg->start_rule;
2834         if (rule != NULL) {
2835                 KKASSERT(rule->cpuid == mycpuid);
2836
2837                 /*
2838                  * Move to the position on the next CPU
2839                  * before the msg is forwarded.
2840                  */
2841                 dmsg->start_rule = rule->sibling;
2842         } else {
2843                 KKASSERT(dmsg->rulenum == 0);
2844                 rule = ctx->ipfw_layer3_chain;
2845         }
2846
2847         while (rule != NULL) {
2848                 if (dmsg->rulenum && rule->rulenum != dmsg->rulenum)
2849                         break;
2850                 rule->rule_flags &= ~IPFW_RULE_F_STATE;
2851                 rule = rule->next;
2852         }
2853
2854         ifnet_forwardmsg(&nmsg->nm_lmsg, mycpuid + 1);
2855 }
2856
2857 /*
2858  * Deletes all rules from a chain (including the default rule
2859  * if the second argument is set).
2860  * Must be called at splimp().
2861  */
2862 static void
2863 ipfw_flush(int kill_default)
2864 {
2865         struct netmsg_del dmsg;
2866         struct netmsg nmsg;
2867         struct lwkt_msg *lmsg;
2868         struct ip_fw *rule;
2869         struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2870
2871         IPFW_ASSERT_CFGPORT(&curthread->td_msgport);
2872
2873         /*
2874          * If 'kill_default' then caller has done the necessary
2875          * msgport syncing; unnecessary to do it again.
2876          */
2877         if (!kill_default) {
2878                 /*
2879                  * Let ipfw_chk() know the rules are going to
2880                  * be flushed, so it could jump directly to
2881                  * the default rule.
2882                  */
2883                 ipfw_flushing = 1;
2884                 netmsg_service_sync();
2885         }
2886
2887         /*
2888          * Clear STATE flag on rules, so no more states (dyn rules)
2889          * will be created.
2890          */
2891         bzero(&dmsg, sizeof(dmsg));
2892         netmsg_init(&dmsg.nmsg, &curthread->td_msgport, 0,
2893                     ipfw_disable_rule_state_dispatch);
2894         ifnet_domsg(&dmsg.nmsg.nm_lmsg, 0);
2895
2896         /*
2897          * This actually nukes all states (dyn rules)
2898          */
2899         lockmgr(&dyn_lock, LK_EXCLUSIVE);
2900         for (rule = ctx->ipfw_layer3_chain; rule != NULL; rule = rule->next) {
2901                 /*
2902                  * Can't check IPFW_RULE_F_STATE here,
2903                  * since it has been cleared previously.
2904                  * Check 'stub' instead.
2905                  */
2906                 if (rule->stub != NULL) {
2907                         /* Force removal */
2908                         remove_dyn_rule_locked(rule, NULL);
2909                 }
2910         }
2911         lockmgr(&dyn_lock, LK_RELEASE);
2912
2913         /*
2914          * Press the 'flush' button
2915          */
2916         bzero(&nmsg, sizeof(nmsg));
2917         netmsg_init(&nmsg, &curthread->td_msgport, 0, ipfw_flush_dispatch);
2918         lmsg = &nmsg.nm_lmsg;
2919         lmsg->u.ms_result = kill_default;
2920         ifnet_domsg(lmsg, 0);
2921
2922         KASSERT(dyn_count == 0, ("%u dyn rule remains\n", dyn_count));
2923
2924         if (kill_default) {
2925                 if (ipfw_dyn_v != NULL) {
2926                         /*
2927                          * Free dynamic rules(state) hash table
2928                          */
2929                         kfree(ipfw_dyn_v, M_IPFW);
2930                         ipfw_dyn_v = NULL;
2931                 }
2932
2933                 KASSERT(static_count == 0,
2934                         ("%u static rules remains\n", static_count));
2935                 KASSERT(static_ioc_len == 0,
2936                         ("%u bytes of static rules remains\n", static_ioc_len));
2937         } else {
2938                 KASSERT(static_count == 1,
2939                         ("%u static rules remains\n", static_count));
2940                 KASSERT(static_ioc_len == IOC_RULESIZE(ctx->ipfw_default_rule),
2941                         ("%u bytes of static rules remains, should be %u\n",
2942                          static_ioc_len, IOC_RULESIZE(ctx->ipfw_default_rule)));
2943         }
2944
2945         /* Flush is done */
2946         ipfw_flushing = 0;
2947 }
2948
2949 static void
2950 ipfw_alt_delete_rule_dispatch(struct netmsg *nmsg)
2951 {
2952         struct netmsg_del *dmsg = (struct netmsg_del *)nmsg;
2953         struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2954         struct ip_fw *rule, *prev;
2955
2956         rule = dmsg->start_rule;
2957         KKASSERT(rule->cpuid == mycpuid);
2958         dmsg->start_rule = rule->sibling;
2959
2960         prev = dmsg->prev_rule;
2961         if (prev != NULL) {
2962                 KKASSERT(prev->cpuid == mycpuid);
2963
2964                 /*
2965                  * Move to the position on the next CPU
2966                  * before the msg is forwarded.
2967                  */
2968                 dmsg->prev_rule = prev->sibling;
2969         }
2970
2971         /*
2972          * flush pointers outside the loop, then delete all matching
2973          * rules.  'prev' remains the same throughout the cycle.
2974          */
2975         ipfw_flush_rule_ptrs(ctx);
2976         while (rule && rule->rulenum == dmsg->rulenum)
2977                 rule = ipfw_delete_rule(ctx, prev, rule);
2978
2979         ifnet_forwardmsg(&nmsg->nm_lmsg, mycpuid + 1);
2980 }
2981
2982 static int
2983 ipfw_alt_delete_rule(uint16_t rulenum)
2984 {
2985         struct ip_fw *prev, *rule, *f;
2986         struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2987         struct netmsg_del dmsg;
2988         struct netmsg *nmsg;
2989         int state;
2990
2991         /*
2992          * Locate first rule to delete
2993          */
2994         for (prev = NULL, rule = ctx->ipfw_layer3_chain;
2995              rule && rule->rulenum < rulenum;
2996              prev = rule, rule = rule->next)
2997                 ; /* EMPTY */
2998         if (rule->rulenum != rulenum)
2999                 return EINVAL;
3000
3001         /*
3002          * Check whether any rules with the given number will
3003          * create states.
3004          */
3005         state = 0;
3006         for (f = rule; f && f->rulenum == rulenum; f = f->next) {
3007                 if (f->rule_flags & IPFW_RULE_F_STATE) {
3008                         state = 1;
3009                         break;
3010                 }
3011         }
3012
3013         if (state) {
3014                 /*
3015                  * Clear the STATE flag, so no more states will be
3016                  * created based the rules numbered 'rulenum'.
3017                  */
3018                 bzero(&dmsg, sizeof(dmsg));
3019                 nmsg = &dmsg.nmsg;
3020                 netmsg_init(nmsg, &curthread->td_msgport, 0,
3021                             ipfw_disable_rule_state_dispatch);
3022                 dmsg.start_rule = rule;
3023                 dmsg.rulenum = rulenum;
3024
3025                 ifnet_domsg(&nmsg->nm_lmsg, 0);
3026                 KKASSERT(dmsg.start_rule == NULL);
3027
3028                 /*
3029                  * Nuke all related states
3030                  */
3031                 lockmgr(&dyn_lock, LK_EXCLUSIVE);
3032                 for (f = rule; f && f->rulenum == rulenum; f = f->next) {
3033                         /*
3034                          * Can't check IPFW_RULE_F_STATE here,
3035                          * since it has been cleared previously.
3036                          * Check 'stub' instead.
3037                          */
3038                         if (f->stub != NULL) {
3039                                 /* Force removal */
3040                                 remove_dyn_rule_locked(f, NULL);
3041                         }
3042                 }
3043                 lockmgr(&dyn_lock, LK_RELEASE);
3044         }
3045
3046         /*
3047          * Get rid of the rule duplications on all CPUs
3048          */
3049         bzero(&dmsg, sizeof(dmsg));
3050         nmsg = &dmsg.nmsg;
3051         netmsg_init(nmsg, &curthread->td_msgport, 0,
3052                     ipfw_alt_delete_rule_dispatch);
3053         dmsg.prev_rule = prev;
3054         dmsg.start_rule = rule;
3055         dmsg.rulenum = rulenum;
3056
3057         ifnet_domsg(&nmsg->nm_lmsg, 0);
3058         KKASSERT(dmsg.prev_rule == NULL && dmsg.start_rule == NULL);
3059         return 0;
3060 }
3061
3062 static void
3063 ipfw_alt_delete_ruleset_dispatch(struct netmsg *nmsg)
3064 {
3065         struct netmsg_del *dmsg = (struct netmsg_del *)nmsg;
3066         struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3067         struct ip_fw *prev, *rule;
3068 #ifdef INVARIANTS
3069         int del = 0;
3070 #endif
3071
3072         ipfw_flush_rule_ptrs(ctx);
3073
3074         prev = NULL;
3075         rule = ctx->ipfw_layer3_chain;
3076         while (rule != NULL) {
3077                 if (rule->set == dmsg->from_set) {
3078                         rule = ipfw_delete_rule(ctx, prev, rule);
3079 #ifdef INVARIANTS
3080                         del = 1;
3081 #endif
3082                 } else {
3083                         prev = rule;
3084                         rule = rule->next;
3085                 }
3086         }
3087         KASSERT(del, ("no match set?!\n"));
3088
3089         ifnet_forwardmsg(&nmsg->nm_lmsg, mycpuid + 1);
3090 }
3091
3092 static void
3093 ipfw_disable_ruleset_state_dispatch(struct netmsg *nmsg)
3094 {
3095         struct netmsg_del *dmsg = (struct netmsg_del *)nmsg;
3096         struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3097         struct ip_fw *rule;
3098 #ifdef INVARIANTS
3099         int cleared = 0;
3100 #endif
3101
3102         ctx->ipfw_gen++;
3103
3104         for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next) {
3105                 if (rule->set == dmsg->from_set) {
3106 #ifdef INVARIANTS
3107                         cleared = 1;
3108 #endif
3109                         rule->rule_flags &= ~IPFW_RULE_F_STATE;
3110                 }
3111         }
3112         KASSERT(cleared, ("no match set?!\n"));
3113
3114         ifnet_forwardmsg(&nmsg->nm_lmsg, mycpuid + 1);
3115 }
3116
3117 static int
3118 ipfw_alt_delete_ruleset(uint8_t set)
3119 {
3120         struct netmsg_del dmsg;
3121         struct netmsg *nmsg;
3122         int state, del;
3123         struct ip_fw *rule;
3124         struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3125
3126         /*
3127          * Check whether the 'set' exists.  If it exists,
3128          * then check whether any rules within the set will
3129          * try to create states.
3130          */
3131         state = 0;
3132         del = 0;
3133         for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next) {
3134                 if (rule->set == set) {
3135                         del = 1;
3136                         if (rule->rule_flags & IPFW_RULE_F_STATE) {
3137                                 state = 1;
3138                                 break;
3139                         }
3140                 }
3141         }
3142         if (!del)
3143                 return 0; /* XXX EINVAL? */
3144
3145         if (state) {
3146                 /*
3147                  * Clear the STATE flag, so no more states will be
3148                  * created based the rules in this set.
3149                  */
3150                 bzero(&dmsg, sizeof(dmsg));
3151                 nmsg = &dmsg.nmsg;
3152                 netmsg_init(nmsg, &curthread->td_msgport, 0,
3153                             ipfw_disable_ruleset_state_dispatch);
3154                 dmsg.from_set = set;
3155
3156                 ifnet_domsg(&nmsg->nm_lmsg, 0);
3157
3158                 /*
3159                  * Nuke all related states
3160                  */
3161                 lockmgr(&dyn_lock, LK_EXCLUSIVE);
3162                 for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next) {
3163                         if (rule->set != set)
3164                                 continue;
3165
3166                         /*
3167                          * Can't check IPFW_RULE_F_STATE here,
3168                          * since it has been cleared previously.
3169                          * Check 'stub' instead.
3170                          */
3171                         if (rule->stub != NULL) {
3172                                 /* Force removal */
3173                                 remove_dyn_rule_locked(rule, NULL);
3174                         }
3175                 }
3176                 lockmgr(&dyn_lock, LK_RELEASE);
3177         }
3178
3179         /*
3180          * Delete this set
3181          */
3182         bzero(&dmsg, sizeof(dmsg));
3183         nmsg = &dmsg.nmsg;
3184         netmsg_init(nmsg, &curthread->td_msgport, 0,
3185                     ipfw_alt_delete_ruleset_dispatch);
3186         dmsg.from_set = set;
3187
3188         ifnet_domsg(&nmsg->nm_lmsg, 0);
3189         return 0;
3190 }
3191
3192 static void
3193 ipfw_alt_move_rule_dispatch(struct netmsg *nmsg)
3194 {
3195         struct netmsg_del *dmsg = (struct netmsg_del *)nmsg;
3196         struct ip_fw *rule;
3197
3198         rule = dmsg->start_rule;
3199         KKASSERT(rule->cpuid == mycpuid);
3200
3201         /*
3202          * Move to the position on the next CPU
3203          * before the msg is forwarded.
3204          */
3205         dmsg->start_rule = rule->sibling;
3206
3207         while (rule && rule->rulenum <= dmsg->rulenum) {
3208                 if (rule->rulenum == dmsg->rulenum)
3209                         rule->set = dmsg->to_set;
3210                 rule = rule->next;
3211         }
3212         ifnet_forwardmsg(&nmsg->nm_lmsg, mycpuid + 1);
3213 }
3214
3215 static int
3216 ipfw_alt_move_rule(uint16_t rulenum, uint8_t set)
3217 {
3218         struct netmsg_del dmsg;
3219         struct netmsg *nmsg;
3220         struct ip_fw *rule;
3221         struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3222
3223         /*
3224          * Locate first rule to move
3225          */
3226         for (rule = ctx->ipfw_layer3_chain; rule && rule->rulenum <= rulenum;
3227              rule = rule->next) {
3228                 if (rule->rulenum == rulenum && rule->set != set)
3229                         break;
3230         }
3231         if (rule == NULL || rule->rulenum > rulenum)
3232                 return 0; /* XXX error? */
3233
3234         bzero(&dmsg, sizeof(dmsg));
3235         nmsg = &dmsg.nmsg;
3236         netmsg_init(nmsg, &curthread->td_msgport, 0,
3237                     ipfw_alt_move_rule_dispatch);
3238         dmsg.start_rule = rule;
3239         dmsg.rulenum = rulenum;
3240         dmsg.to_set = set;
3241
3242         ifnet_domsg(&nmsg->nm_lmsg, 0);
3243         KKASSERT(dmsg.start_rule == NULL);
3244         return 0;
3245 }
3246
3247 static void
3248 ipfw_alt_move_ruleset_dispatch(struct netmsg *nmsg)
3249 {
3250         struct netmsg_del *dmsg = (struct netmsg_del *)nmsg;
3251         struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3252         struct ip_fw *rule;
3253
3254         for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next) {
3255                 if (rule->set == dmsg->from_set)
3256                         rule->set = dmsg->to_set;
3257         }
3258         ifnet_forwardmsg(&nmsg->nm_lmsg, mycpuid + 1);
3259 }
3260
3261 static int
3262 ipfw_alt_move_ruleset(uint8_t from_set, uint8_t to_set)
3263 {
3264         struct netmsg_del dmsg;
3265         struct netmsg *nmsg;
3266
3267         bzero(&dmsg, sizeof(dmsg));
3268         nmsg = &dmsg.nmsg;
3269         netmsg_init(nmsg, &curthread->td_msgport, 0,
3270                     ipfw_alt_move_ruleset_dispatch);
3271         dmsg.from_set = from_set;
3272         dmsg.to_set = to_set;
3273
3274         ifnet_domsg(&nmsg->nm_lmsg, 0);
3275         return 0;
3276 }
3277
3278 static void
3279 ipfw_alt_swap_ruleset_dispatch(struct netmsg *nmsg)
3280 {
3281         struct netmsg_del *dmsg = (struct netmsg_del *)nmsg;
3282         struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3283         struct ip_fw *rule;
3284
3285         for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next) {
3286                 if (rule->set == dmsg->from_set)
3287                         rule->set = dmsg->to_set;
3288                 else if (rule->set == dmsg->to_set)
3289                         rule->set = dmsg->from_set;
3290         }
3291         ifnet_forwardmsg(&nmsg->nm_lmsg, mycpuid + 1);
3292 }
3293
3294 static int
3295 ipfw_alt_swap_ruleset(uint8_t set1, uint8_t set2)
3296 {
3297         struct netmsg_del dmsg;
3298         struct netmsg *nmsg;
3299
3300         bzero(&dmsg, sizeof(dmsg));
3301         nmsg = &dmsg.nmsg;
3302         netmsg_init(nmsg, &curthread->td_msgport, 0,
3303                     ipfw_alt_swap_ruleset_dispatch);
3304         dmsg.from_set = set1;
3305         dmsg.to_set = set2;
3306
3307         ifnet_domsg(&nmsg->nm_lmsg, 0);
3308         return 0;
3309 }
3310
3311 /**
3312  * Remove all rules with given number, and also do set manipulation.
3313  *
3314  * The argument is an uint32_t. The low 16 bit are the rule or set number,
3315  * the next 8 bits are the new set, the top 8 bits are the command:
3316  *
3317  *      0       delete rules with given number
3318  *      1       delete rules with given set number
3319  *      2       move rules with given number to new set
3320  *      3       move rules with given set number to new set
3321  *      4       swap sets with given numbers
3322  */
3323 static int
3324 ipfw_ctl_alter(uint32_t arg)
3325 {
3326         uint16_t rulenum;
3327         uint8_t cmd, new_set;
3328         int error = 0;
3329
3330         rulenum = arg & 0xffff;
3331         cmd = (arg >> 24) & 0xff;
3332         new_set = (arg >> 16) & 0xff;
3333
3334         if (cmd > 4)
3335                 return EINVAL;
3336         if (new_set >= IPFW_DEFAULT_SET)
3337                 return EINVAL;
3338         if (cmd == 0 || cmd == 2) {
3339                 if (rulenum == IPFW_DEFAULT_RULE)
3340                         return EINVAL;
3341         } else {
3342                 if (rulenum >= IPFW_DEFAULT_SET)
3343                         return EINVAL;
3344         }
3345
3346         switch (cmd) {
3347         case 0: /* delete rules with given number */
3348                 error = ipfw_alt_delete_rule(rulenum);
3349                 break;
3350
3351         case 1: /* delete all rules with given set number */
3352                 error = ipfw_alt_delete_ruleset(rulenum);
3353                 break;
3354
3355         case 2: /* move rules with given number to new set */
3356                 error = ipfw_alt_move_rule(rulenum, new_set);
3357                 break;
3358
3359         case 3: /* move rules with given set number to new set */
3360                 error = ipfw_alt_move_ruleset(rulenum, new_set);
3361                 break;
3362
3363         case 4: /* swap two sets */
3364                 error = ipfw_alt_swap_ruleset(rulenum, new_set);
3365                 break;
3366         }
3367         return error;
3368 }
3369
3370 /*
3371  * Clear counters for a specific rule.
3372  */
3373 static void
3374 clear_counters(struct ip_fw *rule, int log_only)
3375 {
3376         ipfw_insn_log *l = (ipfw_insn_log *)ACTION_PTR(rule);
3377
3378         if (log_only == 0) {
3379                 rule->bcnt = rule->pcnt = 0;
3380                 rule->timestamp = 0;
3381         }
3382         if (l->o.opcode == O_LOG)
3383                 l->log_left = l->max_log;
3384 }
3385
3386 static void
3387 ipfw_zero_entry_dispatch(struct netmsg *nmsg)
3388 {
3389         struct netmsg_zent *zmsg = (struct netmsg_zent *)nmsg;
3390         struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3391         struct ip_fw *rule;
3392
3393         if (zmsg->rulenum == 0) {
3394                 KKASSERT(zmsg->start_rule == NULL);
3395
3396                 ctx->ipfw_norule_counter = 0;
3397                 for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next)
3398                         clear_counters(rule, zmsg->log_only);
3399         } else {
3400                 struct ip_fw *start = zmsg->start_rule;
3401
3402                 KKASSERT(start->cpuid == mycpuid);
3403                 KKASSERT(start->rulenum == zmsg->rulenum);
3404
3405                 /*
3406                  * We can have multiple rules with the same number, so we
3407                  * need to clear them all.
3408                  */
3409                 for (rule = start; rule && rule->rulenum == zmsg->rulenum;
3410                      rule = rule->next)
3411                         clear_counters(rule, zmsg->log_only);
3412
3413                 /*
3414                  * Move to the position on the next CPU
3415                  * before the msg is forwarded.
3416                  */
3417                 zmsg->start_rule = start->sibling;
3418         }
3419         ifnet_forwardmsg(&nmsg->nm_lmsg, mycpuid + 1);
3420 }
3421
3422 /**
3423  * Reset some or all counters on firewall rules.
3424  * @arg frwl is null to clear all entries, or contains a specific
3425  * rule number.
3426  * @arg log_only is 1 if we only want to reset logs, zero otherwise.
3427  */
3428 static int
3429 ipfw_ctl_zero_entry(int rulenum, int log_only)
3430 {
3431         struct netmsg_zent zmsg;
3432         struct netmsg *nmsg;
3433         const char *msg;
3434         struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3435
3436         bzero(&zmsg, sizeof(zmsg));
3437         nmsg = &zmsg.nmsg;
3438         netmsg_init(nmsg, &curthread->td_msgport, 0, ipfw_zero_entry_dispatch);
3439         zmsg.log_only = log_only;
3440
3441         if (rulenum == 0) {
3442                 msg = log_only ? "ipfw: All logging counts reset.\n"
3443                                : "ipfw: Accounting cleared.\n";
3444         } else {
3445                 struct ip_fw *rule;
3446
3447                 /*
3448                  * Locate the first rule with 'rulenum'
3449                  */
3450                 for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next) {
3451                         if (rule->rulenum == rulenum)
3452                                 break;
3453                 }
3454                 if (rule == NULL) /* we did not find any matching rules */
3455                         return (EINVAL);
3456                 zmsg.start_rule = rule;
3457                 zmsg.rulenum = rulenum;
3458
3459                 msg = log_only ? "ipfw: Entry %d logging count reset.\n"
3460                                : "ipfw: Entry %d cleared.\n";
3461         }
3462         ifnet_domsg(&nmsg->nm_lmsg, 0);
3463         KKASSERT(zmsg.start_rule == NULL);
3464
3465         if (fw_verbose)
3466                 log(LOG_SECURITY | LOG_NOTICE, msg, rulenum);
3467         return (0);
3468 }
3469
3470 /*
3471  * Check validity of the structure before insert.
3472  * Fortunately rules are simple, so this mostly need to check rule sizes.
3473  */
3474 static int
3475 ipfw_check_ioc_rule(struct ipfw_ioc_rule *rule, int size, uint32_t *rule_flags)
3476 {
3477         int l, cmdlen = 0;
3478         int have_action = 0;
3479         ipfw_insn *cmd;
3480
3481         *rule_flags = 0;
3482
3483         /* Check for valid size */
3484         if (size < sizeof(*rule)) {
3485                 kprintf("ipfw: rule too short\n");
3486                 return EINVAL;
3487         }
3488         l = IOC_RULESIZE(rule);
3489         if (l != size) {
3490                 kprintf("ipfw: size mismatch (have %d want %d)\n", size, l);
3491                 return EINVAL;
3492         }
3493
3494         /* Check rule number */
3495         if (rule->rulenum == IPFW_DEFAULT_RULE) {
3496                 kprintf("ipfw: invalid rule number\n");
3497                 return EINVAL;
3498         }
3499
3500         /*
3501          * Now go for the individual checks. Very simple ones, basically only
3502          * instruction sizes.
3503          */
3504         for (l = rule->cmd_len, cmd = rule->cmd; l > 0;
3505              l -= cmdlen, cmd += cmdlen) {
3506                 cmdlen = F_LEN(cmd);
3507                 if (cmdlen > l) {
3508                         kprintf("ipfw: opcode %d size truncated\n",
3509                                 cmd->opcode);
3510                         return EINVAL;
3511                 }
3512
3513                 DPRINTF("ipfw: opcode %d\n", cmd->opcode);
3514
3515                 if (cmd->opcode == O_KEEP_STATE || cmd->opcode == O_LIMIT) {
3516                         /* This rule will create states */
3517                         *rule_flags |= IPFW_RULE_F_STATE;
3518                 }
3519
3520                 switch (cmd->opcode) {
3521                 case O_NOP:
3522                 case O_PROBE_STATE:
3523                 case O_KEEP_STATE:
3524                 case O_PROTO:
3525                 case O_IP_SRC_ME:
3526                 case O_IP_DST_ME:
3527                 case O_LAYER2:
3528                 case O_IN:
3529                 case O_FRAG:
3530                 case O_IPOPT:
3531                 case O_IPLEN:
3532                 case O_IPID:
3533                 case O_IPTOS:
3534                 case O_IPPRECEDENCE:
3535                 case O_IPTTL:
3536                 case O_IPVER:
3537                 case O_TCPWIN:
3538                 case O_TCPFLAGS:
3539                 case O_TCPOPTS:
3540                 case O_ESTAB:
3541                         if (cmdlen != F_INSN_SIZE(ipfw_insn))
3542                                 goto bad_size;
3543                         break;
3544
3545                 case O_UID:
3546                 case O_GID:
3547                 case O_IP_SRC:
3548                 case O_IP_DST:
3549                 case O_TCPSEQ:
3550                 case O_TCPACK:
3551                 case O_PROB:
3552                 case O_ICMPTYPE:
3553                         if (cmdlen != F_INSN_SIZE(ipfw_insn_u32))
3554                                 goto bad_size;
3555                         break;
3556
3557                 case O_LIMIT:
3558                         if (cmdlen != F_INSN_SIZE(ipfw_insn_limit))
3559                                 goto bad_size;
3560                         break;
3561
3562                 case O_LOG:
3563                         if (cmdlen != F_INSN_SIZE(ipfw_insn_log))
3564                                 goto bad_size;
3565
3566                         ((ipfw_insn_log *)cmd)->log_left =
3567                             ((ipfw_insn_log *)cmd)->max_log;
3568
3569                         break;
3570
3571                 case O_IP_SRC_MASK:
3572                 case O_IP_DST_MASK:
3573                         if (cmdlen != F_INSN_SIZE(ipfw_insn_ip))
3574                                 goto bad_size;
3575                         if (((ipfw_insn_ip *)cmd)->mask.s_addr == 0) {
3576                                 kprintf("ipfw: opcode %d, useless rule\n",
3577                                         cmd->opcode);
3578                                 return EINVAL;
3579                         }
3580                         break;
3581
3582                 case O_IP_SRC_SET:
3583                 case O_IP_DST_SET:
3584                         if (cmd->arg1 == 0 || cmd->arg1 > 256) {
3585                                 kprintf("ipfw: invalid set size %d\n",
3586                                         cmd->arg1);
3587                                 return EINVAL;
3588                         }
3589                         if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
3590                             (cmd->arg1+31)/32 )
3591                                 goto bad_size;
3592                         break;
3593
3594                 case O_MACADDR2:
3595                         if (cmdlen != F_INSN_SIZE(ipfw_insn_mac))
3596                                 goto bad_size;
3597                         break;
3598
3599                 case O_MAC_TYPE:
3600                 case O_IP_SRCPORT:
3601                 case O_IP_DSTPORT: /* XXX artificial limit, 30 port pairs */
3602                         if (cmdlen < 2 || cmdlen > 31)
3603                                 goto bad_size;
3604                         break;
3605
3606                 case O_RECV:
3607                 case O_XMIT:
3608                 case O_VIA:
3609                         if (cmdlen != F_INSN_SIZE(ipfw_insn_if))
3610                                 goto bad_size;
3611                         break;
3612
3613                 case O_PIPE:
3614                 case O_QUEUE:
3615                         if (cmdlen != F_INSN_SIZE(ipfw_insn_pipe))
3616                                 goto bad_size;
3617                         goto check_action;
3618
3619                 case O_FORWARD_IP:
3620                         if (cmdlen != F_INSN_SIZE(ipfw_insn_sa)) {
3621                                 goto bad_size;
3622                         } else {
3623                                 in_addr_t fwd_addr;
3624
3625                                 fwd_addr = ((ipfw_insn_sa *)cmd)->
3626                                            sa.sin_addr.s_addr;
3627                                 if (IN_MULTICAST(ntohl(fwd_addr))) {
3628                                         kprintf("ipfw: try forwarding to "
3629                                                 "multicast address\n");
3630                                         return EINVAL;
3631                                 }
3632                         }
3633                         goto check_action;
3634
3635                 case O_FORWARD_MAC: /* XXX not implemented yet */
3636                 case O_CHECK_STATE:
3637                 case O_COUNT:
3638                 case O_ACCEPT:
3639                 case O_DENY:
3640                 case O_REJECT:
3641                 case O_SKIPTO:
3642                 case O_DIVERT:
3643                 case O_TEE:
3644                         if (cmdlen != F_INSN_SIZE(ipfw_insn))
3645                                 goto bad_size;
3646 check_action:
3647                         if (have_action) {
3648                                 kprintf("ipfw: opcode %d, multiple actions"
3649                                         " not allowed\n",
3650                                         cmd->opcode);
3651                                 return EINVAL;
3652                         }
3653                         have_action = 1;
3654                         if (l != cmdlen) {
3655                                 kprintf("ipfw: opcode %d, action must be"
3656                                         " last opcode\n",
3657                                         cmd->opcode);
3658                                 return EINVAL;
3659                         }
3660                         break;
3661                 default:
3662                         kprintf("ipfw: opcode %d, unknown opcode\n",
3663                                 cmd->opcode);
3664                         return EINVAL;
3665                 }
3666         }
3667         if (have_action == 0) {
3668                 kprintf("ipfw: missing action\n");
3669                 return EINVAL;
3670         }
3671         return 0;
3672
3673 bad_size:
3674         kprintf("ipfw: opcode %d size %d wrong\n",
3675                 cmd->opcode, cmdlen);
3676         return EINVAL;
3677 }
3678
3679 static int
3680 ipfw_ctl_add_rule(struct sockopt *sopt)
3681 {
3682         struct ipfw_ioc_rule *ioc_rule;
3683         size_t size;
3684         uint32_t rule_flags;
3685         int error;
3686         
3687         size = sopt->sopt_valsize;
3688         if (size > (sizeof(uint32_t) * IPFW_RULE_SIZE_MAX) ||
3689             size < sizeof(*ioc_rule)) {
3690                 return EINVAL;
3691         }
3692         if (size != (sizeof(uint32_t) * IPFW_RULE_SIZE_MAX)) {
3693                 sopt->sopt_val = krealloc(sopt->sopt_val, sizeof(uint32_t) *
3694                                           IPFW_RULE_SIZE_MAX, M_TEMP, M_WAITOK);
3695         }
3696         ioc_rule = sopt->sopt_val;
3697
3698         error = ipfw_check_ioc_rule(ioc_rule, size, &rule_flags);
3699         if (error)
3700                 return error;
3701
3702         ipfw_add_rule(ioc_rule, rule_flags);
3703
3704         if (sopt->sopt_dir == SOPT_GET)
3705                 sopt->sopt_valsize = IOC_RULESIZE(ioc_rule);
3706         return 0;
3707 }
3708
3709 static void *
3710 ipfw_copy_rule(const struct ip_fw *rule, struct ipfw_ioc_rule *ioc_rule)
3711 {
3712         const struct ip_fw *sibling;
3713 #ifdef INVARIANTS
3714         int i;
3715 #endif
3716
3717         KKASSERT(rule->cpuid == 0);
3718
3719         ioc_rule->act_ofs = rule->act_ofs;
3720         ioc_rule->cmd_len = rule->cmd_len;
3721         ioc_rule->rulenum = rule->rulenum;
3722         ioc_rule->set = rule->set;
3723         ioc_rule->usr_flags = rule->usr_flags;
3724
3725         ioc_rule->set_disable = ipfw_ctx[mycpuid]->ipfw_set_disable;
3726         ioc_rule->static_count = static_count;
3727         ioc_rule->static_len = static_ioc_len;
3728
3729         /*
3730          * Visit (read-only) all of the rule's duplications to get
3731          * the necessary statistics
3732          */
3733 #ifdef INVARIANTS
3734         i = 0;
3735 #endif
3736         ioc_rule->pcnt = 0;
3737         ioc_rule->bcnt = 0;
3738         ioc_rule->timestamp = 0;
3739         for (sibling = rule; sibling != NULL; sibling = sibling->sibling) {
3740                 ioc_rule->pcnt += sibling->pcnt;
3741                 ioc_rule->bcnt += sibling->bcnt;
3742                 if (sibling->timestamp > ioc_rule->timestamp)
3743                         ioc_rule->timestamp = sibling->timestamp;
3744 #ifdef INVARIANTS
3745                 ++i;
3746 #endif
3747         }
3748         KASSERT(i == ncpus, ("static rule is not duplicated on every cpu\n"));
3749
3750         bcopy(rule->cmd, ioc_rule->cmd, ioc_rule->cmd_len * 4 /* XXX */);
3751
3752         return ((uint8_t *)ioc_rule + IOC_RULESIZE(ioc_rule));
3753 }
3754
3755 static void
3756 ipfw_copy_state(const ipfw_dyn_rule *dyn_rule,
3757                 struct ipfw_ioc_state *ioc_state)
3758 {
3759         const struct ipfw_flow_id *id;
3760         struct ipfw_ioc_flowid *ioc_id;
3761
3762         ioc_state->expire = TIME_LEQ(dyn_rule->expire, time_second) ?
3763                             0 : dyn_rule->expire - time_second;
3764         ioc_state->pcnt = dyn_rule->pcnt;
3765         ioc_state->bcnt = dyn_rule->bcnt;
3766
3767         ioc_state->dyn_type = dyn_rule->dyn_type;
3768         ioc_state->count = dyn_rule->count;
3769
3770         ioc_state->rulenum = dyn_rule->stub->rule[mycpuid]->rulenum;
3771
3772         id = &dyn_rule->id;
3773         ioc_id = &ioc_state->id;
3774
3775         ioc_id->type = ETHERTYPE_IP;
3776         ioc_id->u.ip.dst_ip = id->dst_ip;
3777         ioc_id->u.ip.src_ip = id->src_ip;
3778         ioc_id->u.ip.dst_port = id->dst_port;
3779         ioc_id->u.ip.src_port = id->src_port;
3780         ioc_id->u.ip.proto = id->proto;
3781 }
3782
3783 static int
3784 ipfw_ctl_get_rules(struct sockopt *sopt)
3785 {
3786         struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3787         struct ip_fw *rule;
3788         void *bp;
3789         size_t size;
3790         uint32_t dcount = 0;
3791
3792         /*
3793          * pass up a copy of the current rules. Static rules
3794          * come first (the last of which has number IPFW_DEFAULT_RULE),
3795          * followed by a possibly empty list of dynamic rule.
3796          */
3797
3798         size = static_ioc_len;  /* size of static rules */
3799         if (ipfw_dyn_v) {       /* add size of dyn.rules */
3800                 dcount = dyn_count;
3801                 size += dcount * sizeof(struct ipfw_ioc_state);
3802         }
3803
3804         if (sopt->sopt_valsize < size) {
3805                 /* short length, no need to return incomplete rules */
3806                 /* XXX: if superuser, no need to zero buffer */
3807                 bzero(sopt->sopt_val, sopt->sopt_valsize); 
3808                 return 0;
3809         }
3810         bp = sopt->sopt_val;
3811
3812         for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next)
3813                 bp = ipfw_copy_rule(rule, bp);
3814
3815         if (ipfw_dyn_v && dcount != 0) {
3816                 struct ipfw_ioc_state *ioc_state = bp;
3817                 uint32_t dcount2 = 0;
3818 #ifdef INVARIANTS
3819                 size_t old_size = size;
3820 #endif
3821                 int i;
3822
3823                 lockmgr(&dyn_lock, LK_SHARED);
3824
3825                 /* Check 'ipfw_dyn_v' again with lock held */
3826                 if (ipfw_dyn_v == NULL)
3827                         goto skip;
3828
3829                 for (i = 0; i < curr_dyn_buckets; i++) {
3830                         ipfw_dyn_rule *p;
3831
3832                         /*
3833                          * The # of dynamic rules may have grown after the
3834                          * snapshot of 'dyn_count' was taken, so we will have
3835                          * to check 'dcount' (snapshot of dyn_count) here to
3836                          * make sure that we don't overflow the pre-allocated
3837                          * buffer.
3838                          */
3839                         for (p = ipfw_dyn_v[i]; p != NULL && dcount != 0;
3840                              p = p->next, ioc_state++, dcount--, dcount2++)
3841                                 ipfw_copy_state(p, ioc_state);
3842                 }
3843 skip:
3844                 lockmgr(&dyn_lock, LK_RELEASE);
3845
3846                 /*
3847                  * The # of dynamic rules may be shrinked after the
3848                  * snapshot of 'dyn_count' was taken.  To give user a
3849                  * correct dynamic rule count, we use the 'dcount2'
3850                  * calculated above (with shared lockmgr lock held).
3851                  */
3852                 size = static_ioc_len +
3853                        (dcount2 * sizeof(struct ipfw_ioc_state));
3854                 KKASSERT(size <= old_size);
3855         }
3856
3857         sopt->sopt_valsize = size;
3858         return 0;
3859 }
3860
3861 static void
3862 ipfw_set_disable_dispatch(struct netmsg *nmsg)
3863 {
3864         struct lwkt_msg *lmsg = &nmsg->nm_lmsg;
3865         struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3866
3867         ctx->ipfw_gen++;
3868         ctx->ipfw_set_disable = lmsg->u.ms_result32;
3869
3870         ifnet_forwardmsg(lmsg, mycpuid + 1);
3871 }
3872
3873 static void
3874 ipfw_ctl_set_disable(uint32_t disable, uint32_t enable)
3875 {
3876         struct netmsg nmsg;
3877         struct lwkt_msg *lmsg;
3878         uint32_t set_disable;
3879
3880         /* IPFW_DEFAULT_SET is always enabled */
3881         enable |= (1 << IPFW_DEFAULT_SET);
3882         set_disable = (ipfw_ctx[mycpuid]->ipfw_set_disable | disable) & ~enable;
3883
3884         bzero(&nmsg, sizeof(nmsg));
3885         netmsg_init(&nmsg, &curthread->td_msgport, 0, ipfw_set_disable_dispatch);
3886         lmsg = &nmsg.nm_lmsg;
3887         lmsg->u.ms_result32 = set_disable;
3888
3889         ifnet_domsg(lmsg, 0);
3890 }
3891
3892 /**
3893  * {set|get}sockopt parser.
3894  */
3895 static int
3896 ipfw_ctl(struct sockopt *sopt)
3897 {
3898         int error, rulenum;
3899         uint32_t *masks;
3900         size_t size;
3901
3902         error = 0;
3903
3904         switch (sopt->sopt_name) {
3905         case IP_FW_GET:
3906                 error = ipfw_ctl_get_rules(sopt);
3907                 break;
3908
3909         case IP_FW_FLUSH:
3910                 ipfw_flush(0 /* keep default rule */);
3911                 break;
3912
3913         case IP_FW_ADD:
3914                 error = ipfw_ctl_add_rule(sopt);
3915                 break;
3916
3917         case IP_FW_DEL:
3918                 /*
3919                  * IP_FW_DEL is used for deleting single rules or sets,
3920                  * and (ab)used to atomically manipulate sets.
3921                  * Argument size is used to distinguish between the two:
3922                  *    sizeof(uint32_t)
3923                  *      delete single rule or set of rules,
3924                  *      or reassign rules (or sets) to a different set.
3925                  *    2 * sizeof(uint32_t)
3926                  *      atomic disable/enable sets.
3927                  *      first uint32_t contains sets to be disabled,
3928                  *      second uint32_t contains sets to be enabled.
3929                  */
3930                 masks = sopt->sopt_val;
3931                 size = sopt->sopt_valsize;
3932                 if (size == sizeof(*masks)) {
3933                         /*
3934                          * Delete or reassign static rule
3935                          */
3936                         error = ipfw_ctl_alter(masks[0]);
3937                 } else if (size == (2 * sizeof(*masks))) {
3938                         /*
3939                          * Set enable/disable
3940                          */
3941                         ipfw_ctl_set_disable(masks[0], masks[1]);
3942                 } else {
3943                         error = EINVAL;
3944                 }
3945                 break;
3946
3947         case IP_FW_ZERO:
3948         case IP_FW_RESETLOG: /* argument is an int, the rule number */
3949                 rulenum = 0;
3950
3951                 if (sopt->sopt_val != 0) {
3952                     error = soopt_to_kbuf(sopt, &rulenum,
3953                             sizeof(int), sizeof(int));
3954                     if (error)
3955                         break;
3956                 }
3957                 error = ipfw_ctl_zero_entry(rulenum,
3958                         sopt->sopt_name == IP_FW_RESETLOG);
3959                 break;
3960
3961         default:
3962                 kprintf("ipfw_ctl invalid option %d\n", sopt->sopt_name);
3963                 error = EINVAL;
3964         }
3965         return error;
3966 }
3967
3968 /*
3969  * This procedure is only used to handle keepalives. It is invoked
3970  * every dyn_keepalive_period
3971  */
3972 static void
3973 ipfw_tick(void *dummy __unused)
3974 {
3975         time_t keep_alive;
3976         uint32_t gen;
3977         int i;
3978
3979         if (ipfw_dyn_v == NULL || dyn_count == 0)
3980                 goto done;
3981
3982         keep_alive = time_second;
3983
3984         lockmgr(&dyn_lock, LK_EXCLUSIVE);
3985 again:
3986         if (ipfw_dyn_v == NULL || dyn_count == 0) {
3987                 lockmgr(&dyn_lock, LK_RELEASE);
3988                 goto done;
3989         }
3990         gen = dyn_buckets_gen;
3991
3992         for (i = 0; i < curr_dyn_buckets; i++) {
3993                 ipfw_dyn_rule *q, *prev;
3994
3995                 for (prev = NULL, q = ipfw_dyn_v[i]; q != NULL;) {
3996                         uint32_t ack_rev, ack_fwd;
3997                         struct ipfw_flow_id id;
3998
3999                         if (q->dyn_type == O_LIMIT_PARENT)
4000                                 goto next;
4001
4002                         if (TIME_LEQ(q->expire, time_second)) {
4003                                 /* State expired */
4004                                 UNLINK_DYN_RULE(prev, ipfw_dyn_v[i], q);
4005                                 continue;
4006                         }
4007
4008                         /*
4009                          * Keep alive processing
4010                          */
4011
4012                         if (!dyn_keepalive)
4013                                 goto next;
4014                         if (q->id.proto != IPPROTO_TCP)
4015                                 goto next;
4016                         if ((q->state & BOTH_SYN) != BOTH_SYN)
4017                                 goto next;
4018                         if (TIME_LEQ(time_second + dyn_keepalive_interval,
4019                             q->expire))
4020                                 goto next;      /* too early */
4021                         if (q->keep_alive == keep_alive)
4022                                 goto next;      /* alreay done */
4023
4024                         /*
4025                          * Save necessary information, so that they could
4026                          * survive after possible blocking in send_pkt()
4027                          */
4028                         id = q->id;
4029                         ack_rev = q->ack_rev;
4030                         ack_fwd = q->ack_fwd;
4031
4032                         /* Sending has been started */
4033                         q->keep_alive = keep_alive;
4034
4035                         /* Release lock to avoid possible dead lock */
4036                         lockmgr(&dyn_lock, LK_RELEASE);
4037                         send_pkt(&id, ack_rev - 1, ack_fwd, TH_SYN);
4038                         send_pkt(&id, ack_fwd - 1, ack_rev, 0);
4039                         lockmgr(&dyn_lock, LK_EXCLUSIVE);
4040
4041                         if (gen != dyn_buckets_gen) {
4042                                 /*
4043                                  * Dyn bucket array has been changed during
4044                                  * the above two sending; reiterate.
4045                                  */
4046                                 goto again;
4047                         }
4048 next:
4049                         prev = q;
4050                         q = q->next;
4051                 }
4052         }
4053         lockmgr(&dyn_lock, LK_RELEASE);
4054 done:
4055         callout_reset(&ipfw_timeout_h, dyn_keepalive_period * hz,
4056                       ipfw_tick, NULL);
4057 }
4058
4059 static int
4060 ipfw_check_in(void *arg, struct mbuf **m0, struct ifnet *ifp, int dir)
4061 {
4062         struct ip_fw_args args;
4063         struct mbuf *m = *m0;
4064         struct m_tag *mtag;
4065         int tee = 0, error = 0, ret;
4066
4067         if (m->m_pkthdr.fw_flags & DUMMYNET_MBUF_TAGGED) {
4068                 /* Extract info from dummynet tag */
4069                 mtag = m_tag_find(m, PACKET_TAG_DUMMYNET, NULL);
4070                 KKASSERT(mtag != NULL);
4071                 args.rule = ((struct dn_pkt *)m_tag_data(mtag))->dn_priv;
4072                 KKASSERT(args.rule != NULL);
4073
4074                 m_tag_delete(m, mtag);
4075                 m->m_pkthdr.fw_flags &= ~DUMMYNET_MBUF_TAGGED;
4076         } else {
4077                 args.rule = NULL;
4078         }
4079
4080         args.eh = NULL;
4081         args.oif = NULL;
4082         args.m = m;
4083         ret = ipfw_chk(&args);
4084         m = args.m;
4085
4086         if (m == NULL) {
4087                 error = EACCES;
4088                 goto back;
4089         }
4090
4091         switch (ret) {
4092         case IP_FW_PASS:
4093                 break;
4094
4095         case IP_FW_DENY:
4096                 m_freem(m);
4097                 m = NULL;
4098                 error = EACCES;
4099                 break;
4100
4101         case IP_FW_DUMMYNET:
4102                 /* Send packet to the appropriate pipe */
4103                 ipfw_dummynet_io(m, args.cookie, DN_TO_IP_IN, &args);
4104                 break;
4105
4106         case IP_FW_TEE:
4107                 tee = 1;
4108                 /* FALL THROUGH */
4109
4110         case IP_FW_DIVERT:
4111                 if (ip_divert_p != NULL) {
4112                         m = ip_divert_p(m, tee, 1);
4113                 } else {
4114                         m_freem(m);
4115                         m = NULL;
4116                         /* not sure this is the right error msg */
4117                         error = EACCES;
4118                 }
4119                 break;
4120
4121         default:
4122                 panic("unknown ipfw return value: %d\n", ret);
4123         }
4124 back:
4125         *m0 = m;
4126         return error;
4127 }
4128
4129 static int
4130 ipfw_check_out(void *arg, struct mbuf **m0, struct ifnet *ifp, int dir)
4131 {
4132         struct ip_fw_args args;
4133         struct mbuf *m = *m0;
4134         struct m_tag *mtag;
4135         int tee = 0, error = 0, ret;
4136
4137         if (m->m_pkthdr.fw_flags & DUMMYNET_MBUF_TAGGED) {
4138                 /* Extract info from dummynet tag */
4139                 mtag = m_tag_find(m, PACKET_TAG_DUMMYNET, NULL);
4140                 KKASSERT(mtag != NULL);
4141                 args.rule = ((struct dn_pkt *)m_tag_data(mtag))->dn_priv;
4142                 KKASSERT(args.rule != NULL);
4143
4144                 m_tag_delete(m, mtag);
4145                 m->m_pkthdr.fw_flags &= ~DUMMYNET_MBUF_TAGGED;
4146         } else {
4147                 args.rule = NULL;
4148         }
4149
4150         args.eh = NULL;
4151         args.m = m;
4152         args.oif = ifp;
4153         ret = ipfw_chk(&args);
4154         m = args.m;
4155
4156         if (m == NULL) {
4157                 error = EACCES;
4158                 goto back;
4159         }
4160
4161         switch (ret) {
4162         case IP_FW_PASS:
4163                 break;
4164
4165         case IP_FW_DENY:
4166                 m_freem(m);
4167                 m = NULL;
4168                 error = EACCES;
4169                 break;
4170
4171         case IP_FW_DUMMYNET:
4172                 ipfw_dummynet_io(m, args.cookie, DN_TO_IP_OUT, &args);
4173                 break;
4174
4175         case IP_FW_TEE:
4176                 tee = 1;
4177                 /* FALL THROUGH */
4178
4179         case IP_FW_DIVERT:
4180                 if (ip_divert_p != NULL) {
4181                         m = ip_divert_p(m, tee, 0);
4182                 } else {
4183                         m_freem(m);
4184                         m = NULL;
4185                         /* not sure this is the right error msg */
4186                         error = EACCES;
4187                 }
4188                 break;
4189
4190         default:
4191                 panic("unknown ipfw return value: %d\n", ret);
4192         }
4193 back:
4194         *m0 = m;
4195         return error;
4196 }
4197
4198 static void
4199 ipfw_hook(void)
4200 {
4201         struct pfil_head *pfh;
4202
4203         IPFW_ASSERT_CFGPORT(&curthread->td_msgport);
4204
4205         pfh = pfil_head_get(PFIL_TYPE_AF, AF_INET);
4206         if (pfh == NULL)
4207                 return;
4208
4209         pfil_add_hook(ipfw_check_in, NULL, PFIL_IN, pfh);
4210         pfil_add_hook(ipfw_check_out, NULL, PFIL_OUT, pfh);
4211 }
4212
4213 static void
4214 ipfw_dehook(void)
4215 {
4216         struct pfil_head *pfh;
4217
4218         IPFW_ASSERT_CFGPORT(&curthread->td_msgport);
4219
4220         pfh = pfil_head_get(PFIL_TYPE_AF, AF_INET);
4221         if (pfh == NULL)
4222                 return;
4223
4224         pfil_remove_hook(ipfw_check_in, NULL, PFIL_IN, pfh);
4225         pfil_remove_hook(ipfw_check_out, NULL, PFIL_OUT, pfh);
4226 }
4227
4228 static void
4229 ipfw_sysctl_enable_dispatch(struct netmsg *nmsg)
4230 {
4231         struct lwkt_msg *lmsg = &nmsg->nm_lmsg;
4232         int enable = lmsg->u.ms_result;
4233
4234         if (fw_enable == enable)
4235                 goto reply;
4236
4237         fw_enable = enable;
4238         if (fw_enable)
4239                 ipfw_hook();
4240         else
4241                 ipfw_dehook();
4242 reply:
4243         lwkt_replymsg(lmsg, 0);
4244 }
4245
4246 static int
4247 ipfw_sysctl_enable(SYSCTL_HANDLER_ARGS)
4248 {
4249         struct netmsg nmsg;
4250         struct lwkt_msg *lmsg;
4251         int enable, error;
4252
4253         enable = fw_enable;
4254         error = sysctl_handle_int(oidp, &enable, 0, req);
4255         if (error || req->newptr == NULL)
4256                 return error;
4257
4258         netmsg_init(&nmsg, &curthread->td_msgport, 0,
4259                     ipfw_sysctl_enable_dispatch);
4260         lmsg = &nmsg.nm_lmsg;
4261         lmsg->u.ms_result = enable;
4262
4263         return lwkt_domsg(IPFW_CFGPORT, lmsg, 0);
4264 }
4265
4266 static int
4267 ipfw_sysctl_autoinc_step(SYSCTL_HANDLER_ARGS)
4268 {
4269         return sysctl_int_range(oidp, arg1, arg2, req,
4270                IPFW_AUTOINC_STEP_MIN, IPFW_AUTOINC_STEP_MAX);
4271 }
4272
4273 static int
4274 ipfw_sysctl_dyn_buckets(SYSCTL_HANDLER_ARGS)
4275 {
4276         int error, value;
4277
4278         lockmgr(&dyn_lock, LK_EXCLUSIVE);
4279
4280         value = dyn_buckets;
4281         error = sysctl_handle_int(oidp, &value, 0, req);
4282         if (error || !req->newptr)
4283                 goto back;
4284
4285         /*
4286          * Make sure we have a power of 2 and
4287          * do not allow more than 64k entries.
4288          */
4289         error = EINVAL;
4290         if (value <= 1 || value > 65536)
4291                 goto back;
4292         if ((value & (value - 1)) != 0)
4293                 goto back;
4294
4295         error = 0;
4296         dyn_buckets = value;
4297 back:
4298         lockmgr(&dyn_lock, LK_RELEASE);
4299         return error;
4300 }
4301
4302 static int
4303 ipfw_sysctl_dyn_fin(SYSCTL_HANDLER_ARGS)
4304 {
4305         return sysctl_int_range(oidp, arg1, arg2, req,
4306                                 1, dyn_keepalive_period - 1);
4307 }
4308
4309 static int
4310 ipfw_sysctl_dyn_rst(SYSCTL_HANDLER_ARGS)
4311 {
4312         return sysctl_int_range(oidp, arg1, arg2, req,
4313                                 1, dyn_keepalive_period - 1);
4314 }
4315
4316 static void
4317 ipfw_ctx_init_dispatch(struct netmsg *nmsg)
4318 {
4319         struct netmsg_ipfw *fwmsg = (struct netmsg_ipfw *)nmsg;
4320         struct ipfw_context *ctx;
4321         struct ip_fw *def_rule;
4322
4323         ctx = kmalloc(sizeof(*ctx), M_IPFW, M_WAITOK | M_ZERO);
4324         ipfw_ctx[mycpuid] = ctx;
4325
4326         def_rule = kmalloc(sizeof(*def_rule), M_IPFW, M_WAITOK | M_ZERO);
4327
4328         def_rule->act_ofs = 0;
4329         def_rule->rulenum = IPFW_DEFAULT_RULE;
4330         def_rule->cmd_len = 1;
4331         def_rule->set = IPFW_DEFAULT_SET;
4332
4333         def_rule->cmd[0].len = 1;
4334 #ifdef IPFIREWALL_DEFAULT_TO_ACCEPT
4335         def_rule->cmd[0].opcode = O_ACCEPT;
4336 #else
4337         def_rule->cmd[0].opcode = O_DENY;
4338 #endif
4339
4340         def_rule->refcnt = 1;
4341         def_rule->cpuid = mycpuid;
4342
4343         /* Install the default rule */
4344         ctx->ipfw_default_rule = def_rule;
4345         ctx->ipfw_layer3_chain = def_rule;
4346
4347         /* Link rule CPU sibling */
4348         ipfw_link_sibling(fwmsg, def_rule);
4349
4350         /* Statistics only need to be updated once */
4351         if (mycpuid == 0)
4352                 ipfw_inc_static_count(def_rule);
4353
4354         ifnet_forwardmsg(&nmsg->nm_lmsg, mycpuid + 1);
4355 }
4356
4357 static void
4358 ipfw_init_dispatch(struct netmsg *nmsg)
4359 {
4360         struct netmsg_ipfw fwmsg;
4361         int error = 0;
4362
4363         if (IPFW_LOADED) {
4364                 kprintf("IP firewall already loaded\n");
4365                 error = EEXIST;
4366                 goto reply;
4367         }
4368
4369         bzero(&fwmsg, sizeof(fwmsg));
4370         netmsg_init(&fwmsg.nmsg, &curthread->td_msgport, 0,
4371                     ipfw_ctx_init_dispatch);
4372         ifnet_domsg(&fwmsg.nmsg.nm_lmsg, 0);
4373
4374         ip_fw_chk_ptr = ipfw_chk;
4375         ip_fw_ctl_ptr = ipfw_ctl;
4376         ip_fw_dn_io_ptr = ipfw_dummynet_io;
4377
4378         kprintf("ipfw2 initialized, default to %s, logging ",
4379                 ipfw_ctx[mycpuid]->ipfw_default_rule->cmd[0].opcode ==
4380                 O_ACCEPT ? "accept" : "deny");
4381
4382 #ifdef IPFIREWALL_VERBOSE
4383         fw_verbose = 1;
4384 #endif
4385 #ifdef IPFIREWALL_VERBOSE_LIMIT
4386         verbose_limit = IPFIREWALL_VERBOSE_LIMIT;
4387 #endif
4388         if (fw_verbose == 0) {
4389                 kprintf("disabled\n");
4390         } else if (verbose_limit == 0) {
4391                 kprintf("unlimited\n");
4392         } else {
4393                 kprintf("limited to %d packets/entry by default\n",
4394                         verbose_limit);
4395         }
4396
4397         callout_init(&ipfw_timeout_h);
4398         lockinit(&dyn_lock, "ipfw_dyn", 0, 0);
4399
4400         ip_fw_loaded = 1;
4401         callout_reset(&ipfw_timeout_h, hz, ipfw_tick, NULL);
4402
4403         if (fw_enable)
4404                 ipfw_hook();
4405 reply:
4406         lwkt_replymsg(&nmsg->nm_lmsg, error);
4407 }
4408
4409 static int
4410 ipfw_init(void)
4411 {
4412         struct netmsg smsg;
4413
4414         netmsg_init(&smsg, &curthread->td_msgport, 0, ipfw_init_dispatch);
4415         return lwkt_domsg(IPFW_CFGPORT, &smsg.nm_lmsg, 0);
4416 }
4417
4418 #ifdef KLD_MODULE
4419
4420 static void
4421 ipfw_fini_dispatch(struct netmsg *nmsg)
4422 {
4423         int error = 0, cpu;
4424
4425         if (ipfw_refcnt != 0) {
4426                 error = EBUSY;
4427                 goto reply;
4428         }
4429
4430         ipfw_dehook();
4431
4432         callout_stop(&ipfw_timeout_h);
4433
4434         ip_fw_loaded = 0;
4435         netmsg_service_sync();
4436
4437         ip_fw_chk_ptr = NULL;
4438         ip_fw_ctl_ptr = NULL;
4439         ip_fw_dn_io_ptr = NULL;
4440         ipfw_flush(1 /* kill default rule */);
4441
4442         /* Free pre-cpu context */
4443         for (cpu = 0; cpu < ncpus; ++cpu)
4444                 kfree(ipfw_ctx[cpu], M_IPFW);
4445
4446         kprintf("IP firewall unloaded\n");
4447 reply:
4448         lwkt_replymsg(&nmsg->nm_lmsg, error);
4449 }
4450
4451 static int
4452 ipfw_fini(void)
4453 {
4454         struct netmsg smsg;
4455
4456         netmsg_init(&smsg, &curthread->td_msgport, 0, ipfw_fini_dispatch);
4457         return lwkt_domsg(IPFW_CFGPORT, &smsg.nm_lmsg, 0);
4458 }
4459
4460 #endif  /* KLD_MODULE */
4461
4462 static int
4463 ipfw_modevent(module_t mod, int type, void *unused)
4464 {
4465         int err = 0;
4466
4467         switch (type) {
4468         case MOD_LOAD:
4469                 err = ipfw_init();
4470                 break;
4471
4472         case MOD_UNLOAD:
4473 #ifndef KLD_MODULE
4474                 kprintf("ipfw statically compiled, cannot unload\n");
4475                 err = EBUSY;
4476 #else
4477                 err = ipfw_fini();
4478 #endif
4479                 break;
4480         default:
4481                 break;
4482         }
4483         return err;
4484 }
4485
4486 static moduledata_t ipfwmod = {
4487         "ipfw",
4488         ipfw_modevent,
4489         0
4490 };
4491 DECLARE_MODULE(ipfw, ipfwmod, SI_SUB_PROTO_END, SI_ORDER_ANY);
4492 MODULE_VERSION(ipfw, 1);