- Group together the declaration of static rule related global variables
[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.70 2008/08/09 09:41:54 sephe Exp $
27  */
28
29 #define        DEB(x)
30 #define        DDB(x) x
31
32 /*
33  * Implement IP packet firewall (new version)
34  */
35
36 #ifndef KLD_MODULE
37 #include "opt_ipfw.h"
38 #include "opt_ipdn.h"
39 #include "opt_ipdivert.h"
40 #include "opt_inet.h"
41 #ifndef INET
42 #error IPFIREWALL requires INET.
43 #endif /* INET */
44 #endif
45
46 #include <sys/param.h>
47 #include <sys/systm.h>
48 #include <sys/malloc.h>
49 #include <sys/mbuf.h>
50 #include <sys/kernel.h>
51 #include <sys/proc.h>
52 #include <sys/socket.h>
53 #include <sys/socketvar.h>
54 #include <sys/sysctl.h>
55 #include <sys/syslog.h>
56 #include <sys/thread2.h>
57 #include <sys/ucred.h>
58 #include <sys/in_cksum.h>
59 #include <sys/lock.h>
60
61 #include <net/if.h>
62 #include <net/route.h>
63 #include <net/netmsg2.h>
64
65 #include <netinet/in.h>
66 #include <netinet/in_systm.h>
67 #include <netinet/in_var.h>
68 #include <netinet/in_pcb.h>
69 #include <netinet/ip.h>
70 #include <netinet/ip_var.h>
71 #include <netinet/ip_icmp.h>
72 #include "ip_fw.h"
73 #include <net/dummynet/ip_dummynet.h>
74 #include <netinet/tcp.h>
75 #include <netinet/tcp_timer.h>
76 #include <netinet/tcp_var.h>
77 #include <netinet/tcpip.h>
78 #include <netinet/udp.h>
79 #include <netinet/udp_var.h>
80
81 #include <netinet/if_ether.h> /* XXX for ETHERTYPE_IP */
82
83 #define IPFW_AUTOINC_STEP_MIN   1
84 #define IPFW_AUTOINC_STEP_MAX   1000
85 #define IPFW_AUTOINC_STEP_DEF   100
86
87 /*
88  * set_disable contains one bit per set value (0..31).
89  * If the bit is set, all rules with the corresponding set
90  * are disabled. Set 31 is reserved for the default rule
91  * and CANNOT be disabled.
92  */
93 static uint32_t set_disable;
94
95 static int fw_verbose;
96 static int verbose_limit;
97
98 #ifdef KLD_MODULE
99 static int ipfw_refcnt;
100 #endif
101
102 static struct callout ipfw_timeout_h;
103 #define IPFW_DEFAULT_RULE       65535
104
105 /*
106  * list of rules for layer 3
107  */
108 static struct ip_fw *layer3_chain;
109 static uint64_t norule_counter; /* counter for ipfw_log(NULL...) */
110
111 MALLOC_DEFINE(M_IPFW, "IpFw/IpAcct", "IpFw/IpAcct chain's");
112
113 static int fw_debug = 1;
114 static int autoinc_step = IPFW_AUTOINC_STEP_DEF;
115 static uint32_t static_count;   /* # of static rules */
116 static uint32_t static_ioc_len; /* bytes of static rules */
117 static uint32_t static_gen;     /* generation of static rules */
118
119 static int      ipfw_sysctl_autoinc_step(SYSCTL_HANDLER_ARGS);
120 static int      ipfw_sysctl_dyn_buckets(SYSCTL_HANDLER_ARGS);
121 static int      ipfw_sysctl_dyn_fin(SYSCTL_HANDLER_ARGS);
122 static int      ipfw_sysctl_dyn_rst(SYSCTL_HANDLER_ARGS);
123
124 #ifdef SYSCTL_NODE
125 SYSCTL_NODE(_net_inet_ip, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall");
126 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, enable, CTLFLAG_RW,
127     &fw_enable, 0, "Enable ipfw");
128 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, autoinc_step, CTLTYPE_INT | CTLFLAG_RW,
129     &autoinc_step, 0, ipfw_sysctl_autoinc_step, "I",
130     "Rule number autincrement step");
131 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO,one_pass,CTLFLAG_RW,
132     &fw_one_pass, 0,
133     "Only do a single pass through ipfw when using dummynet(4)");
134 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, debug, CTLFLAG_RW,
135     &fw_debug, 0, "Enable printing of debug ip_fw statements");
136 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose, CTLFLAG_RW,
137     &fw_verbose, 0, "Log matches to ipfw rules");
138 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose_limit, CTLFLAG_RW,
139     &verbose_limit, 0, "Set upper limit of matches of ipfw rules logged");
140
141 /*
142  * Description of dynamic rules.
143  *
144  * Dynamic rules are stored in lists accessed through a hash table
145  * (ipfw_dyn_v) whose size is curr_dyn_buckets. This value can
146  * be modified through the sysctl variable dyn_buckets which is
147  * updated when the table becomes empty.
148  *
149  * XXX currently there is only one list, ipfw_dyn.
150  *
151  * When a packet is received, its address fields are first masked
152  * with the mask defined for the rule, then hashed, then matched
153  * against the entries in the corresponding list.
154  * Dynamic rules can be used for different purposes:
155  *  + stateful rules;
156  *  + enforcing limits on the number of sessions;
157  *  + in-kernel NAT (not implemented yet)
158  *
159  * The lifetime of dynamic rules is regulated by dyn_*_lifetime,
160  * measured in seconds and depending on the flags.
161  *
162  * The total number of dynamic rules is stored in dyn_count.
163  * The max number of dynamic rules is dyn_max. When we reach
164  * the maximum number of rules we do not create anymore. This is
165  * done to avoid consuming too much memory, but also too much
166  * time when searching on each packet (ideally, we should try instead
167  * to put a limit on the length of the list on each bucket...).
168  *
169  * Each dynamic rule holds a pointer to the parent ipfw rule so
170  * we know what action to perform. Dynamic rules are removed when
171  * the parent rule is deleted. XXX we should make them survive.
172  *
173  * There are some limitations with dynamic rules -- we do not
174  * obey the 'randomized match', and we do not do multiple
175  * passes through the firewall. XXX check the latter!!!
176  *
177  * NOTE about the SHARED LOCKMGR LOCK during dynamic rule looking up:
178  * Only TCP state transition will change dynamic rule's state and ack
179  * sequences, while all packets of one TCP connection only goes through
180  * one TCP thread, so it is safe to use shared lockmgr lock during dynamic
181  * rule looking up.  The keep alive callout uses exclusive lockmgr lock
182  * when it tries to find suitable dynamic rules to send keep alive, so
183  * it will not see half updated state and ack sequences.  Though the expire
184  * field updating looks racy for other protocols, the resolution (second)
185  * of expire field makes this kind of race harmless.
186  * XXX statistics' updating is _not_ MPsafe!!!
187  * XXX once UDP output path is fixed, we could use lockless dynamic rule
188  *     hash table
189  */
190 static ipfw_dyn_rule **ipfw_dyn_v = NULL;
191 static uint32_t dyn_buckets = 256; /* must be power of 2 */
192 static uint32_t curr_dyn_buckets = 256; /* must be power of 2 */
193 static uint32_t dyn_buckets_gen; /* generation of dyn buckets array */
194 static struct lock dyn_lock; /* dynamic rules' hash table lock */
195
196 /*
197  * Timeouts for various events in handing dynamic rules.
198  */
199 static uint32_t dyn_ack_lifetime = 300;
200 static uint32_t dyn_syn_lifetime = 20;
201 static uint32_t dyn_fin_lifetime = 1;
202 static uint32_t dyn_rst_lifetime = 1;
203 static uint32_t dyn_udp_lifetime = 10;
204 static uint32_t dyn_short_lifetime = 5;
205
206 /*
207  * Keepalives are sent if dyn_keepalive is set. They are sent every
208  * dyn_keepalive_period seconds, in the last dyn_keepalive_interval
209  * seconds of lifetime of a rule.
210  * dyn_rst_lifetime and dyn_fin_lifetime should be strictly lower
211  * than dyn_keepalive_period.
212  */
213
214 static uint32_t dyn_keepalive_interval = 20;
215 static uint32_t dyn_keepalive_period = 5;
216 static uint32_t dyn_keepalive = 1;      /* do send keepalives */
217
218 static uint32_t dyn_count;              /* # of dynamic rules */
219 static uint32_t dyn_max = 4096;         /* max # of dynamic rules */
220
221 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, dyn_buckets, CTLTYPE_INT | CTLFLAG_RW,
222     &dyn_buckets, 0, ipfw_sysctl_dyn_buckets, "I", "Number of dyn. buckets");
223 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, curr_dyn_buckets, CTLFLAG_RD,
224     &curr_dyn_buckets, 0, "Current Number of dyn. buckets");
225 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_count, CTLFLAG_RD,
226     &dyn_count, 0, "Number of dyn. rules");
227 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_max, CTLFLAG_RW,
228     &dyn_max, 0, "Max number of dyn. rules");
229 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, static_count, CTLFLAG_RD,
230     &static_count, 0, "Number of static rules");
231 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_ack_lifetime, CTLFLAG_RW,
232     &dyn_ack_lifetime, 0, "Lifetime of dyn. rules for acks");
233 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_syn_lifetime, CTLFLAG_RW,
234     &dyn_syn_lifetime, 0, "Lifetime of dyn. rules for syn");
235 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, dyn_fin_lifetime,
236     CTLTYPE_INT | CTLFLAG_RW, &dyn_fin_lifetime, 0, ipfw_sysctl_dyn_fin, "I",
237     "Lifetime of dyn. rules for fin");
238 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, dyn_rst_lifetime,
239     CTLTYPE_INT | CTLFLAG_RW, &dyn_rst_lifetime, 0, ipfw_sysctl_dyn_rst, "I",
240     "Lifetime of dyn. rules for rst");
241 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_udp_lifetime, CTLFLAG_RW,
242     &dyn_udp_lifetime, 0, "Lifetime of dyn. rules for UDP");
243 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_short_lifetime, CTLFLAG_RW,
244     &dyn_short_lifetime, 0, "Lifetime of dyn. rules for other situations");
245 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_keepalive, CTLFLAG_RW,
246     &dyn_keepalive, 0, "Enable keepalives for dyn. rules");
247
248 #endif /* SYSCTL_NODE */
249
250 static struct ip_fw *ip_fw_default_rule;
251
252 static ip_fw_chk_t      ipfw_chk;
253
254 static __inline int
255 ipfw_free_rule(struct ip_fw *rule)
256 {
257         KASSERT(rule->refcnt > 0, ("invalid refcnt %u\n", rule->refcnt));
258         atomic_subtract_int(&rule->refcnt, 1);
259         if (atomic_cmpset_int(&rule->refcnt, 0, 1)) {
260                 kfree(rule, M_IPFW);
261                 return 1;
262         }
263         return 0;
264 }
265
266 static void
267 ipfw_unref_rule(void *priv)
268 {
269         ipfw_free_rule(priv);
270 #ifdef KLD_MODULE
271         atomic_subtract_int(&ipfw_refcnt, 1);
272 #endif
273 }
274
275 static __inline void
276 ipfw_ref_rule(struct ip_fw *rule)
277 {
278 #ifdef KLD_MODULE
279         atomic_add_int(&ipfw_refcnt, 1);
280 #endif
281         atomic_add_int(&rule->refcnt, 1);
282 }
283
284 /*
285  * This macro maps an ip pointer into a layer3 header pointer of type T
286  */
287 #define L3HDR(T, ip) ((T *)((uint32_t *)(ip) + (ip)->ip_hl))
288
289 static __inline int
290 icmptype_match(struct ip *ip, ipfw_insn_u32 *cmd)
291 {
292         int type = L3HDR(struct icmp,ip)->icmp_type;
293
294         return (type <= ICMP_MAXTYPE && (cmd->d[0] & (1 << type)));
295 }
296
297 #define TT      ((1 << ICMP_ECHO) | \
298                  (1 << ICMP_ROUTERSOLICIT) | \
299                  (1 << ICMP_TSTAMP) | \
300                  (1 << ICMP_IREQ) | \
301                  (1 << ICMP_MASKREQ))
302
303 static int
304 is_icmp_query(struct ip *ip)
305 {
306         int type = L3HDR(struct icmp, ip)->icmp_type;
307
308         return (type <= ICMP_MAXTYPE && (TT & (1 << type)));
309 }
310
311 #undef TT
312
313 /*
314  * The following checks use two arrays of 8 or 16 bits to store the
315  * bits that we want set or clear, respectively. They are in the
316  * low and high half of cmd->arg1 or cmd->d[0].
317  *
318  * We scan options and store the bits we find set. We succeed if
319  *
320  *      (want_set & ~bits) == 0 && (want_clear & ~bits) == want_clear
321  *
322  * The code is sometimes optimized not to store additional variables.
323  */
324
325 static int
326 flags_match(ipfw_insn *cmd, uint8_t bits)
327 {
328         u_char want_clear;
329         bits = ~bits;
330
331         if (((cmd->arg1 & 0xff) & bits) != 0)
332                 return 0; /* some bits we want set were clear */
333
334         want_clear = (cmd->arg1 >> 8) & 0xff;
335         if ((want_clear & bits) != want_clear)
336                 return 0; /* some bits we want clear were set */
337         return 1;
338 }
339
340 static int
341 ipopts_match(struct ip *ip, ipfw_insn *cmd)
342 {
343         int optlen, bits = 0;
344         u_char *cp = (u_char *)(ip + 1);
345         int x = (ip->ip_hl << 2) - sizeof(struct ip);
346
347         for (; x > 0; x -= optlen, cp += optlen) {
348                 int opt = cp[IPOPT_OPTVAL];
349
350                 if (opt == IPOPT_EOL)
351                         break;
352
353                 if (opt == IPOPT_NOP) {
354                         optlen = 1;
355                 } else {
356                         optlen = cp[IPOPT_OLEN];
357                         if (optlen <= 0 || optlen > x)
358                                 return 0; /* invalid or truncated */
359                 }
360
361                 switch (opt) {
362                 case IPOPT_LSRR:
363                         bits |= IP_FW_IPOPT_LSRR;
364                         break;
365
366                 case IPOPT_SSRR:
367                         bits |= IP_FW_IPOPT_SSRR;
368                         break;
369
370                 case IPOPT_RR:
371                         bits |= IP_FW_IPOPT_RR;
372                         break;
373
374                 case IPOPT_TS:
375                         bits |= IP_FW_IPOPT_TS;
376                         break;
377
378                 default:
379                         break;
380                 }
381         }
382         return (flags_match(cmd, bits));
383 }
384
385 static int
386 tcpopts_match(struct ip *ip, ipfw_insn *cmd)
387 {
388         int optlen, bits = 0;
389         struct tcphdr *tcp = L3HDR(struct tcphdr,ip);
390         u_char *cp = (u_char *)(tcp + 1);
391         int x = (tcp->th_off << 2) - sizeof(struct tcphdr);
392
393         for (; x > 0; x -= optlen, cp += optlen) {
394                 int opt = cp[0];
395
396                 if (opt == TCPOPT_EOL)
397                         break;
398
399                 if (opt == TCPOPT_NOP) {
400                         optlen = 1;
401                 } else {
402                         optlen = cp[1];
403                         if (optlen <= 0)
404                                 break;
405                 }
406
407                 switch (opt) {
408                 case TCPOPT_MAXSEG:
409                         bits |= IP_FW_TCPOPT_MSS;
410                         break;
411
412                 case TCPOPT_WINDOW:
413                         bits |= IP_FW_TCPOPT_WINDOW;
414                         break;
415
416                 case TCPOPT_SACK_PERMITTED:
417                 case TCPOPT_SACK:
418                         bits |= IP_FW_TCPOPT_SACK;
419                         break;
420
421                 case TCPOPT_TIMESTAMP:
422                         bits |= IP_FW_TCPOPT_TS;
423                         break;
424
425                 case TCPOPT_CC:
426                 case TCPOPT_CCNEW:
427                 case TCPOPT_CCECHO:
428                         bits |= IP_FW_TCPOPT_CC;
429                         break;
430
431                 default:
432                         break;
433                 }
434         }
435         return (flags_match(cmd, bits));
436 }
437
438 static int
439 iface_match(struct ifnet *ifp, ipfw_insn_if *cmd)
440 {
441         if (ifp == NULL)        /* no iface with this packet, match fails */
442                 return 0;
443
444         /* Check by name or by IP address */
445         if (cmd->name[0] != '\0') { /* match by name */
446                 /* Check name */
447                 if (cmd->p.glob) {
448                         if (kfnmatch(cmd->name, ifp->if_xname, 0) == 0)
449                                 return(1);
450                 } else {
451                         if (strncmp(ifp->if_xname, cmd->name, IFNAMSIZ) == 0)
452                                 return(1);
453                 }
454         } else {
455                 struct ifaddr_container *ifac;
456
457                 TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
458                         struct ifaddr *ia = ifac->ifa;
459
460                         if (ia->ifa_addr == NULL)
461                                 continue;
462                         if (ia->ifa_addr->sa_family != AF_INET)
463                                 continue;
464                         if (cmd->p.ip.s_addr == ((struct sockaddr_in *)
465                             (ia->ifa_addr))->sin_addr.s_addr)
466                                 return(1);      /* match */
467                 }
468         }
469         return(0);      /* no match, fail ... */
470 }
471
472 #define SNPARGS(buf, len) buf + len, sizeof(buf) > len ? sizeof(buf) - len : 0
473
474 /*
475  * We enter here when we have a rule with O_LOG.
476  * XXX this function alone takes about 2Kbytes of code!
477  */
478 static void
479 ipfw_log(struct ip_fw *f, u_int hlen, struct ether_header *eh,
480          struct mbuf *m, struct ifnet *oif)
481 {
482         char *action;
483         int limit_reached = 0;
484         char action2[40], proto[48], fragment[28];
485
486         fragment[0] = '\0';
487         proto[0] = '\0';
488
489         if (f == NULL) {        /* bogus pkt */
490                 if (verbose_limit != 0 && norule_counter >= verbose_limit)
491                         return;
492                 norule_counter++;
493                 if (norule_counter == verbose_limit)
494                         limit_reached = verbose_limit;
495                 action = "Refuse";
496         } else {        /* O_LOG is the first action, find the real one */
497                 ipfw_insn *cmd = ACTION_PTR(f);
498                 ipfw_insn_log *l = (ipfw_insn_log *)cmd;
499
500                 if (l->max_log != 0 && l->log_left == 0)
501                         return;
502                 l->log_left--;
503                 if (l->log_left == 0)
504                         limit_reached = l->max_log;
505                 cmd += F_LEN(cmd);      /* point to first action */
506                 if (cmd->opcode == O_PROB)
507                         cmd += F_LEN(cmd);
508
509                 action = action2;
510                 switch (cmd->opcode) {
511                 case O_DENY:
512                         action = "Deny";
513                         break;
514
515                 case O_REJECT:
516                         if (cmd->arg1==ICMP_REJECT_RST) {
517                                 action = "Reset";
518                         } else if (cmd->arg1==ICMP_UNREACH_HOST) {
519                                 action = "Reject";
520                         } else {
521                                 ksnprintf(SNPARGS(action2, 0), "Unreach %d",
522                                           cmd->arg1);
523                         }
524                         break;
525
526                 case O_ACCEPT:
527                         action = "Accept";
528                         break;
529
530                 case O_COUNT:
531                         action = "Count";
532                         break;
533
534                 case O_DIVERT:
535                         ksnprintf(SNPARGS(action2, 0), "Divert %d", cmd->arg1);
536                         break;
537
538                 case O_TEE:
539                         ksnprintf(SNPARGS(action2, 0), "Tee %d", cmd->arg1);
540                         break;
541
542                 case O_SKIPTO:
543                         ksnprintf(SNPARGS(action2, 0), "SkipTo %d", cmd->arg1);
544                         break;
545
546                 case O_PIPE:
547                         ksnprintf(SNPARGS(action2, 0), "Pipe %d", cmd->arg1);
548                         break;
549
550                 case O_QUEUE:
551                         ksnprintf(SNPARGS(action2, 0), "Queue %d", cmd->arg1);
552                         break;
553
554                 case O_FORWARD_IP:
555                         {
556                                 ipfw_insn_sa *sa = (ipfw_insn_sa *)cmd;
557                                 int len;
558
559                                 len = ksnprintf(SNPARGS(action2, 0),
560                                                 "Forward to %s",
561                                                 inet_ntoa(sa->sa.sin_addr));
562                                 if (sa->sa.sin_port) {
563                                         ksnprintf(SNPARGS(action2, len), ":%d",
564                                                   sa->sa.sin_port);
565                                 }
566                         }
567                         break;
568
569                 default:
570                         action = "UNKNOWN";
571                         break;
572                 }
573         }
574
575         if (hlen == 0) {        /* non-ip */
576                 ksnprintf(SNPARGS(proto, 0), "MAC");
577         } else {
578                 struct ip *ip = mtod(m, struct ip *);
579                 /* these three are all aliases to the same thing */
580                 struct icmp *const icmp = L3HDR(struct icmp, ip);
581                 struct tcphdr *const tcp = (struct tcphdr *)icmp;
582                 struct udphdr *const udp = (struct udphdr *)icmp;
583
584                 int ip_off, offset, ip_len;
585                 int len;
586
587                 if (eh != NULL) { /* layer 2 packets are as on the wire */
588                         ip_off = ntohs(ip->ip_off);
589                         ip_len = ntohs(ip->ip_len);
590                 } else {
591                         ip_off = ip->ip_off;
592                         ip_len = ip->ip_len;
593                 }
594                 offset = ip_off & IP_OFFMASK;
595                 switch (ip->ip_p) {
596                 case IPPROTO_TCP:
597                         len = ksnprintf(SNPARGS(proto, 0), "TCP %s",
598                                         inet_ntoa(ip->ip_src));
599                         if (offset == 0) {
600                                 ksnprintf(SNPARGS(proto, len), ":%d %s:%d",
601                                           ntohs(tcp->th_sport),
602                                           inet_ntoa(ip->ip_dst),
603                                           ntohs(tcp->th_dport));
604                         } else {
605                                 ksnprintf(SNPARGS(proto, len), " %s",
606                                           inet_ntoa(ip->ip_dst));
607                         }
608                         break;
609
610                 case IPPROTO_UDP:
611                         len = ksnprintf(SNPARGS(proto, 0), "UDP %s",
612                                         inet_ntoa(ip->ip_src));
613                         if (offset == 0) {
614                                 ksnprintf(SNPARGS(proto, len), ":%d %s:%d",
615                                           ntohs(udp->uh_sport),
616                                           inet_ntoa(ip->ip_dst),
617                                           ntohs(udp->uh_dport));
618                         } else {
619                                 ksnprintf(SNPARGS(proto, len), " %s",
620                                           inet_ntoa(ip->ip_dst));
621                         }
622                         break;
623
624                 case IPPROTO_ICMP:
625                         if (offset == 0) {
626                                 len = ksnprintf(SNPARGS(proto, 0),
627                                                 "ICMP:%u.%u ",
628                                                 icmp->icmp_type,
629                                                 icmp->icmp_code);
630                         } else {
631                                 len = ksnprintf(SNPARGS(proto, 0), "ICMP ");
632                         }
633                         len += ksnprintf(SNPARGS(proto, len), "%s",
634                                          inet_ntoa(ip->ip_src));
635                         ksnprintf(SNPARGS(proto, len), " %s",
636                                   inet_ntoa(ip->ip_dst));
637                         break;
638
639                 default:
640                         len = ksnprintf(SNPARGS(proto, 0), "P:%d %s", ip->ip_p,
641                                         inet_ntoa(ip->ip_src));
642                         ksnprintf(SNPARGS(proto, len), " %s",
643                                   inet_ntoa(ip->ip_dst));
644                         break;
645                 }
646
647                 if (ip_off & (IP_MF | IP_OFFMASK)) {
648                         ksnprintf(SNPARGS(fragment, 0), " (frag %d:%d@%d%s)",
649                                   ntohs(ip->ip_id), ip_len - (ip->ip_hl << 2),
650                                   offset << 3, (ip_off & IP_MF) ? "+" : "");
651                 }
652         }
653
654         if (oif || m->m_pkthdr.rcvif) {
655                 log(LOG_SECURITY | LOG_INFO,
656                     "ipfw: %d %s %s %s via %s%s\n",
657                     f ? f->rulenum : -1,
658                     action, proto, oif ? "out" : "in",
659                     oif ? oif->if_xname : m->m_pkthdr.rcvif->if_xname,
660                     fragment);
661         } else {
662                 log(LOG_SECURITY | LOG_INFO,
663                     "ipfw: %d %s %s [no if info]%s\n",
664                     f ? f->rulenum : -1,
665                     action, proto, fragment);
666         }
667
668         if (limit_reached) {
669                 log(LOG_SECURITY | LOG_NOTICE,
670                     "ipfw: limit %d reached on entry %d\n",
671                     limit_reached, f ? f->rulenum : -1);
672         }
673 }
674
675 #undef SNPARGS
676
677 /*
678  * IMPORTANT: the hash function for dynamic rules must be commutative
679  * in source and destination (ip,port), because rules are bidirectional
680  * and we want to find both in the same bucket.
681  */
682 static __inline int
683 hash_packet(struct ipfw_flow_id *id)
684 {
685         uint32_t i;
686
687         i = (id->dst_ip) ^ (id->src_ip) ^ (id->dst_port) ^ (id->src_port);
688         i &= (curr_dyn_buckets - 1);
689         return i;
690 }
691
692 /**
693  * unlink a dynamic rule from a chain. prev is a pointer to
694  * the previous one, q is a pointer to the rule to delete,
695  * head is a pointer to the head of the queue.
696  * Modifies q and potentially also head.
697  */
698 #define UNLINK_DYN_RULE(prev, head, q)                                  \
699 do {                                                                    \
700         ipfw_dyn_rule *old_q = q;                                       \
701                                                                         \
702         /* remove a refcount to the parent */                           \
703         if (q->dyn_type == O_LIMIT)                                     \
704                 q->parent->count--;                                     \
705         DEB(kprintf("-- unlink entry 0x%08x %d -> 0x%08x %d, %d left\n", \
706                 (q->id.src_ip), (q->id.src_port),                       \
707                 (q->id.dst_ip), (q->id.dst_port), dyn_count-1 ); )      \
708         if (prev != NULL)                                               \
709                 prev->next = q = q->next;                               \
710         else                                                            \
711                 head = q = q->next;                                     \
712         KASSERT(dyn_count > 0, ("invalid dyn count %u\n", dyn_count));  \
713         dyn_count--;                                                    \
714         kfree(old_q, M_IPFW);                                           \
715 } while (0)
716
717 #define TIME_LEQ(a, b)  ((int)((a) - (b)) <= 0)
718
719 /**
720  * Remove dynamic rules pointing to "rule", or all of them if rule == NULL.
721  *
722  * If keep_me == NULL, rules are deleted even if not expired,
723  * otherwise only expired rules are removed.
724  *
725  * The value of the second parameter is also used to point to identify
726  * a rule we absolutely do not want to remove (e.g. because we are
727  * holding a reference to it -- this is the case with O_LIMIT_PARENT
728  * rules). The pointer is only used for comparison, so any non-null
729  * value will do.
730  */
731 static void
732 remove_dyn_rule_locked(struct ip_fw *rule, ipfw_dyn_rule *keep_me)
733 {
734         static uint32_t last_remove = 0; /* XXX */
735
736 #define FORCE   (keep_me == NULL)
737
738         ipfw_dyn_rule *prev, *q;
739         int i, pass = 0, max_pass = 0, unlinked = 0;
740
741         if (ipfw_dyn_v == NULL || dyn_count == 0)
742                 return;
743         /* do not expire more than once per second, it is useless */
744         if (!FORCE && last_remove == time_second)
745                 return;
746         last_remove = time_second;
747
748         /*
749          * because O_LIMIT refer to parent rules, during the first pass only
750          * remove child and mark any pending LIMIT_PARENT, and remove
751          * them in a second pass.
752          */
753 next_pass:
754         for (i = 0; i < curr_dyn_buckets; i++) {
755                 for (prev = NULL, q = ipfw_dyn_v[i]; q;) {
756                         /*
757                          * Logic can become complex here, so we split tests.
758                          */
759                         if (q == keep_me)
760                                 goto next;
761                         if (rule != NULL && rule != q->rule)
762                                 goto next; /* not the one we are looking for */
763                         if (q->dyn_type == O_LIMIT_PARENT) {
764                                 /*
765                                  * handle parent in the second pass,
766                                  * record we need one.
767                                  */
768                                 max_pass = 1;
769                                 if (pass == 0)
770                                         goto next;
771                                 if (FORCE && q->count != 0) {
772                                         /* XXX should not happen! */
773                                         kprintf("OUCH! cannot remove rule, "
774                                                 "count %d\n", q->count);
775                                 }
776                         } else {
777                                 if (!FORCE && !TIME_LEQ(q->expire, time_second))
778                                         goto next;
779                         }
780                         unlinked = 1;
781                         UNLINK_DYN_RULE(prev, ipfw_dyn_v[i], q);
782                         continue;
783 next:
784                         prev = q;
785                         q = q->next;
786                 }
787         }
788         if (pass++ < max_pass)
789                 goto next_pass;
790
791         if (unlinked)
792                 ++dyn_buckets_gen;
793
794 #undef FORCE
795 }
796
797 static void
798 remove_dyn_rule(struct ip_fw *rule, ipfw_dyn_rule *keep_me)
799 {
800         lockmgr(&dyn_lock, LK_EXCLUSIVE);
801         remove_dyn_rule_locked(rule, keep_me);
802         lockmgr(&dyn_lock, LK_RELEASE);
803 }
804
805 /**
806  * lookup a dynamic rule.
807  */
808 static ipfw_dyn_rule *
809 lookup_dyn_rule(struct ipfw_flow_id *pkt, int *match_direction,
810                 struct tcphdr *tcp)
811 {
812         /*
813          * stateful ipfw extensions.
814          * Lookup into dynamic session queue
815          */
816 #define MATCH_REVERSE   0
817 #define MATCH_FORWARD   1
818 #define MATCH_NONE      2
819 #define MATCH_UNKNOWN   3
820         int i, dir = MATCH_NONE;
821         ipfw_dyn_rule *prev, *q=NULL;
822
823         if (ipfw_dyn_v == NULL)
824                 goto done;      /* not found */
825
826         i = hash_packet(pkt);
827         for (prev = NULL, q = ipfw_dyn_v[i]; q != NULL;) {
828                 if (q->dyn_type == O_LIMIT_PARENT)
829                         goto next;
830
831                 if (TIME_LEQ(q->expire, time_second)) {
832                         /*
833                          * Entry expired; skip.
834                          * Let ipfw_tick() take care of it
835                          */
836                         goto next;
837                 }
838
839                 if (pkt->proto == q->id.proto) {
840                         if (pkt->src_ip == q->id.src_ip &&
841                             pkt->dst_ip == q->id.dst_ip &&
842                             pkt->src_port == q->id.src_port &&
843                             pkt->dst_port == q->id.dst_port) {
844                                 dir = MATCH_FORWARD;
845                                 break;
846                         }
847                         if (pkt->src_ip == q->id.dst_ip &&
848                             pkt->dst_ip == q->id.src_ip &&
849                             pkt->src_port == q->id.dst_port &&
850                             pkt->dst_port == q->id.src_port) {
851                                 dir = MATCH_REVERSE;
852                                 break;
853                         }
854                 }
855 next:
856                 prev = q;
857                 q = q->next;
858         }
859         if (q == NULL)
860                 goto done; /* q = NULL, not found */
861
862         if (pkt->proto == IPPROTO_TCP) { /* update state according to flags */
863                 u_char flags = pkt->flags & (TH_FIN|TH_SYN|TH_RST);
864
865 #define BOTH_SYN        (TH_SYN | (TH_SYN << 8))
866 #define BOTH_FIN        (TH_FIN | (TH_FIN << 8))
867
868                 q->state |= (dir == MATCH_FORWARD ) ? flags : (flags << 8);
869                 switch (q->state) {
870                 case TH_SYN:                            /* opening */
871                         q->expire = time_second + dyn_syn_lifetime;
872                         break;
873
874                 case BOTH_SYN:                  /* move to established */
875                 case BOTH_SYN | TH_FIN :        /* one side tries to close */
876                 case BOTH_SYN | (TH_FIN << 8) :
877                         if (tcp) {
878                                 uint32_t ack = ntohl(tcp->th_ack);
879
880 #define _SEQ_GE(a, b)   ((int)(a) - (int)(b) >= 0)
881
882                                 if (dir == MATCH_FORWARD) {
883                                         if (q->ack_fwd == 0 ||
884                                             _SEQ_GE(ack, q->ack_fwd))
885                                                 q->ack_fwd = ack;
886                                         else /* ignore out-of-sequence */
887                                                 break;
888                                 } else {
889                                         if (q->ack_rev == 0 ||
890                                             _SEQ_GE(ack, q->ack_rev))
891                                                 q->ack_rev = ack;
892                                         else /* ignore out-of-sequence */
893                                                 break;
894                                 }
895 #undef _SEQ_GE
896                         }
897                         q->expire = time_second + dyn_ack_lifetime;
898                         break;
899
900                 case BOTH_SYN | BOTH_FIN:       /* both sides closed */
901                         KKASSERT(dyn_fin_lifetime < dyn_keepalive_period);
902                         q->expire = time_second + dyn_fin_lifetime;
903                         break;
904
905                 default:
906 #if 0
907                         /*
908                          * reset or some invalid combination, but can also
909                          * occur if we use keep-state the wrong way.
910                          */
911                         if ((q->state & ((TH_RST << 8) | TH_RST)) == 0)
912                                 kprintf("invalid state: 0x%x\n", q->state);
913 #endif
914                         KKASSERT(dyn_rst_lifetime < dyn_keepalive_period);
915                         q->expire = time_second + dyn_rst_lifetime;
916                         break;
917                 }
918         } else if (pkt->proto == IPPROTO_UDP) {
919                 q->expire = time_second + dyn_udp_lifetime;
920         } else {
921                 /* other protocols */
922                 q->expire = time_second + dyn_short_lifetime;
923         }
924 done:
925         if (match_direction)
926                 *match_direction = dir;
927         return q;
928 }
929
930 static struct ip_fw *
931 lookup_rule(struct ipfw_flow_id *pkt, int *match_direction, struct tcphdr *tcp,
932             uint16_t len, int *deny)
933 {
934         struct ip_fw *rule = NULL;
935         ipfw_dyn_rule *q;
936         uint32_t gen;
937
938         *deny = 0;
939         gen = static_gen;
940
941         lockmgr(&dyn_lock, LK_SHARED);
942
943         if (static_gen != gen) {
944                 /*
945                  * Static rules had been change when we were waiting
946                  * for the dynamic hash table lock; deny this packet,
947                  * since it is _not_ known whether it is safe to keep
948                  * iterating the static rules.
949                  */
950                 *deny = 1;
951                 goto back;
952         }
953
954         q = lookup_dyn_rule(pkt, match_direction, tcp);
955         if (q == NULL) {
956                 rule = NULL;
957         } else {
958                 rule = q->rule;
959
960                 /* XXX */
961                 q->pcnt++;
962                 q->bcnt += len;
963         }
964 back:
965         lockmgr(&dyn_lock, LK_RELEASE);
966         return rule;
967 }
968
969 static void
970 realloc_dynamic_table(void)
971 {
972         ipfw_dyn_rule **old_dyn_v;
973         uint32_t old_curr_dyn_buckets;
974
975         KASSERT(dyn_buckets <= 65536 && (dyn_buckets & (dyn_buckets - 1)) == 0,
976                 ("invalid dyn_buckets %d\n", dyn_buckets));
977
978         /* Save the current buckets array for later error recovery */
979         old_dyn_v = ipfw_dyn_v;
980         old_curr_dyn_buckets = curr_dyn_buckets;
981
982         curr_dyn_buckets = dyn_buckets;
983         for (;;) {
984                 ipfw_dyn_v = kmalloc(curr_dyn_buckets * sizeof(ipfw_dyn_rule *),
985                                      M_IPFW, M_NOWAIT | M_ZERO);
986                 if (ipfw_dyn_v != NULL || curr_dyn_buckets <= 2)
987                         break;
988
989                 curr_dyn_buckets /= 2;
990                 if (curr_dyn_buckets <= old_curr_dyn_buckets &&
991                     old_dyn_v != NULL) {
992                         /*
993                          * Don't try allocating smaller buckets array, reuse
994                          * the old one, which alreay contains enough buckets
995                          */
996                         break;
997                 }
998         }
999
1000         if (ipfw_dyn_v != NULL) {
1001                 if (old_dyn_v != NULL)
1002                         kfree(old_dyn_v, M_IPFW);
1003         } else {
1004                 /* Allocation failed, restore old buckets array */
1005                 ipfw_dyn_v = old_dyn_v;
1006                 curr_dyn_buckets = old_curr_dyn_buckets;
1007         }
1008
1009         if (ipfw_dyn_v != NULL)
1010                 ++dyn_buckets_gen;
1011 }
1012
1013 /**
1014  * Install state of type 'type' for a dynamic session.
1015  * The hash table contains two type of rules:
1016  * - regular rules (O_KEEP_STATE)
1017  * - rules for sessions with limited number of sess per user
1018  *   (O_LIMIT). When they are created, the parent is
1019  *   increased by 1, and decreased on delete. In this case,
1020  *   the third parameter is the parent rule and not the chain.
1021  * - "parent" rules for the above (O_LIMIT_PARENT).
1022  */
1023 static ipfw_dyn_rule *
1024 add_dyn_rule(struct ipfw_flow_id *id, uint8_t dyn_type, struct ip_fw *rule)
1025 {
1026         ipfw_dyn_rule *r;
1027         int i;
1028
1029         if (ipfw_dyn_v == NULL ||
1030             (dyn_count == 0 && dyn_buckets != curr_dyn_buckets)) {
1031                 realloc_dynamic_table();
1032                 if (ipfw_dyn_v == NULL)
1033                         return NULL; /* failed ! */
1034         }
1035         i = hash_packet(id);
1036
1037         r = kmalloc(sizeof(*r), M_IPFW, M_NOWAIT | M_ZERO);
1038         if (r == NULL) {
1039                 kprintf ("sorry cannot allocate state\n");
1040                 return NULL;
1041         }
1042
1043         /* increase refcount on parent, and set pointer */
1044         if (dyn_type == O_LIMIT) {
1045                 ipfw_dyn_rule *parent = (ipfw_dyn_rule *)rule;
1046
1047                 if (parent->dyn_type != O_LIMIT_PARENT)
1048                         panic("invalid parent");
1049                 parent->count++;
1050                 r->parent = parent;
1051                 rule = parent->rule;
1052         }
1053
1054         r->id = *id;
1055         r->expire = time_second + dyn_syn_lifetime;
1056         r->rule = rule;
1057         r->dyn_type = dyn_type;
1058         r->pcnt = r->bcnt = 0;
1059         r->count = 0;
1060
1061         r->bucket = i;
1062         r->next = ipfw_dyn_v[i];
1063         ipfw_dyn_v[i] = r;
1064         dyn_count++;
1065         dyn_buckets_gen++;
1066         DEB(kprintf("-- add dyn entry ty %d 0x%08x %d -> 0x%08x %d, total %d\n",
1067            dyn_type,
1068            (r->id.src_ip), (r->id.src_port),
1069            (r->id.dst_ip), (r->id.dst_port),
1070            dyn_count );)
1071         return r;
1072 }
1073
1074 /**
1075  * lookup dynamic parent rule using pkt and rule as search keys.
1076  * If the lookup fails, then install one.
1077  */
1078 static ipfw_dyn_rule *
1079 lookup_dyn_parent(struct ipfw_flow_id *pkt, struct ip_fw *rule)
1080 {
1081         ipfw_dyn_rule *q;
1082         int i;
1083
1084         if (ipfw_dyn_v) {
1085                 i = hash_packet(pkt);
1086                 for (q = ipfw_dyn_v[i]; q != NULL; q = q->next) {
1087                         if (q->dyn_type == O_LIMIT_PARENT &&
1088                             rule == q->rule &&
1089                             pkt->proto == q->id.proto &&
1090                             pkt->src_ip == q->id.src_ip &&
1091                             pkt->dst_ip == q->id.dst_ip &&
1092                             pkt->src_port == q->id.src_port &&
1093                             pkt->dst_port == q->id.dst_port) {
1094                                 q->expire = time_second + dyn_short_lifetime;
1095                                 DEB(kprintf("lookup_dyn_parent found 0x%p\n",q);)
1096                                 return q;
1097                         }
1098                 }
1099         }
1100         return add_dyn_rule(pkt, O_LIMIT_PARENT, rule);
1101 }
1102
1103 /**
1104  * Install dynamic state for rule type cmd->o.opcode
1105  *
1106  * Returns 1 (failure) if state is not installed because of errors or because
1107  * session limitations are enforced.
1108  */
1109 static int
1110 install_state_locked(struct ip_fw *rule, ipfw_insn_limit *cmd,
1111                      struct ip_fw_args *args)
1112 {
1113         static int last_log; /* XXX */
1114
1115         ipfw_dyn_rule *q;
1116
1117         DEB(kprintf("-- install state type %d 0x%08x %u -> 0x%08x %u\n",
1118             cmd->o.opcode,
1119             (args->f_id.src_ip), (args->f_id.src_port),
1120             (args->f_id.dst_ip), (args->f_id.dst_port) );)
1121
1122         q = lookup_dyn_rule(&args->f_id, NULL, NULL);
1123         if (q != NULL) { /* should never occur */
1124                 if (last_log != time_second) {
1125                         last_log = time_second;
1126                         kprintf(" install_state: entry already present, done\n");
1127                 }
1128                 return 0;
1129         }
1130
1131         if (dyn_count >= dyn_max) {
1132                 /*
1133                  * Run out of slots, try to remove any expired rule.
1134                  */
1135                 remove_dyn_rule_locked(NULL, (ipfw_dyn_rule *)1);
1136                 if (dyn_count >= dyn_max) {
1137                         if (last_log != time_second) {
1138                                 last_log = time_second;
1139                                 kprintf("install_state: "
1140                                         "Too many dynamic rules\n");
1141                         }
1142                         return 1; /* cannot install, notify caller */
1143                 }
1144         }
1145
1146         switch (cmd->o.opcode) {
1147         case O_KEEP_STATE: /* bidir rule */
1148                 if (add_dyn_rule(&args->f_id, O_KEEP_STATE, rule) == NULL)
1149                         return 1;
1150                 break;
1151
1152         case O_LIMIT: /* limit number of sessions */
1153                 {
1154                         uint16_t limit_mask = cmd->limit_mask;
1155                         struct ipfw_flow_id id;
1156                         ipfw_dyn_rule *parent;
1157
1158                         DEB(kprintf("installing dyn-limit rule %d\n",
1159                             cmd->conn_limit);)
1160
1161                         id.dst_ip = id.src_ip = 0;
1162                         id.dst_port = id.src_port = 0;
1163                         id.proto = args->f_id.proto;
1164
1165                         if (limit_mask & DYN_SRC_ADDR)
1166                                 id.src_ip = args->f_id.src_ip;
1167                         if (limit_mask & DYN_DST_ADDR)
1168                                 id.dst_ip = args->f_id.dst_ip;
1169                         if (limit_mask & DYN_SRC_PORT)
1170                                 id.src_port = args->f_id.src_port;
1171                         if (limit_mask & DYN_DST_PORT)
1172                                 id.dst_port = args->f_id.dst_port;
1173
1174                         parent = lookup_dyn_parent(&id, rule);
1175                         if (parent == NULL) {
1176                                 kprintf("add parent failed\n");
1177                                 return 1;
1178                         }
1179
1180                         if (parent->count >= cmd->conn_limit) {
1181                                 /*
1182                                  * See if we can remove some expired rule.
1183                                  */
1184                                 remove_dyn_rule_locked(rule, parent);
1185                                 if (parent->count >= cmd->conn_limit) {
1186                                         if (fw_verbose &&
1187                                             last_log != time_second) {
1188                                                 last_log = time_second;
1189                                                 log(LOG_SECURITY | LOG_DEBUG,
1190                                                     "drop session, "
1191                                                     "too many entries\n");
1192                                         }
1193                                         return 1;
1194                                 }
1195                         }
1196                         if (add_dyn_rule(&args->f_id, O_LIMIT,
1197                                          (struct ip_fw *)parent) == NULL)
1198                                 return 1;
1199                 }
1200                 break;
1201         default:
1202                 kprintf("unknown dynamic rule type %u\n", cmd->o.opcode);
1203                 return 1;
1204         }
1205         lookup_dyn_rule(&args->f_id, NULL, NULL); /* XXX just set lifetime */
1206         return 0;
1207 }
1208
1209 static int
1210 install_state(struct ip_fw *rule, ipfw_insn_limit *cmd,
1211               struct ip_fw_args *args, int *deny)
1212 {
1213         uint32_t gen;
1214         int ret = 0;
1215
1216         *deny = 0;
1217         gen = static_gen;
1218
1219         lockmgr(&dyn_lock, LK_EXCLUSIVE);
1220         if (static_gen != gen) {
1221                 /* See the comment in lookup_rule() */
1222                 *deny = 1;
1223         } else {
1224                 ret = install_state_locked(rule, cmd, args);
1225         }
1226         lockmgr(&dyn_lock, LK_RELEASE);
1227
1228         return ret;
1229 }
1230
1231 /*
1232  * Transmit a TCP packet, containing either a RST or a keepalive.
1233  * When flags & TH_RST, we are sending a RST packet, because of a
1234  * "reset" action matched the packet.
1235  * Otherwise we are sending a keepalive, and flags & TH_
1236  */
1237 static void
1238 send_pkt(struct ipfw_flow_id *id, uint32_t seq, uint32_t ack, int flags)
1239 {
1240         struct mbuf *m;
1241         struct ip *ip;
1242         struct tcphdr *tcp;
1243         struct route sro;       /* fake route */
1244
1245         MGETHDR(m, MB_DONTWAIT, MT_HEADER);
1246         if (m == NULL)
1247                 return;
1248         m->m_pkthdr.rcvif = NULL;
1249         m->m_pkthdr.len = m->m_len = sizeof(struct ip) + sizeof(struct tcphdr);
1250         m->m_data += max_linkhdr;
1251
1252         ip = mtod(m, struct ip *);
1253         bzero(ip, m->m_len);
1254         tcp = (struct tcphdr *)(ip + 1); /* no IP options */
1255         ip->ip_p = IPPROTO_TCP;
1256         tcp->th_off = 5;
1257
1258         /*
1259          * Assume we are sending a RST (or a keepalive in the reverse
1260          * direction), swap src and destination addresses and ports.
1261          */
1262         ip->ip_src.s_addr = htonl(id->dst_ip);
1263         ip->ip_dst.s_addr = htonl(id->src_ip);
1264         tcp->th_sport = htons(id->dst_port);
1265         tcp->th_dport = htons(id->src_port);
1266         if (flags & TH_RST) {   /* we are sending a RST */
1267                 if (flags & TH_ACK) {
1268                         tcp->th_seq = htonl(ack);
1269                         tcp->th_ack = htonl(0);
1270                         tcp->th_flags = TH_RST;
1271                 } else {
1272                         if (flags & TH_SYN)
1273                                 seq++;
1274                         tcp->th_seq = htonl(0);
1275                         tcp->th_ack = htonl(seq);
1276                         tcp->th_flags = TH_RST | TH_ACK;
1277                 }
1278         } else {
1279                 /*
1280                  * We are sending a keepalive. flags & TH_SYN determines
1281                  * the direction, forward if set, reverse if clear.
1282                  * NOTE: seq and ack are always assumed to be correct
1283                  * as set by the caller. This may be confusing...
1284                  */
1285                 if (flags & TH_SYN) {
1286                         /*
1287                          * we have to rewrite the correct addresses!
1288                          */
1289                         ip->ip_dst.s_addr = htonl(id->dst_ip);
1290                         ip->ip_src.s_addr = htonl(id->src_ip);
1291                         tcp->th_dport = htons(id->dst_port);
1292                         tcp->th_sport = htons(id->src_port);
1293                 }
1294                 tcp->th_seq = htonl(seq);
1295                 tcp->th_ack = htonl(ack);
1296                 tcp->th_flags = TH_ACK;
1297         }
1298
1299         /*
1300          * set ip_len to the payload size so we can compute
1301          * the tcp checksum on the pseudoheader
1302          * XXX check this, could save a couple of words ?
1303          */
1304         ip->ip_len = htons(sizeof(struct tcphdr));
1305         tcp->th_sum = in_cksum(m, m->m_pkthdr.len);
1306
1307         /*
1308          * now fill fields left out earlier
1309          */
1310         ip->ip_ttl = ip_defttl;
1311         ip->ip_len = m->m_pkthdr.len;
1312
1313         bzero(&sro, sizeof(sro));
1314         ip_rtaddr(ip->ip_dst, &sro);
1315
1316         m->m_pkthdr.fw_flags |= IPFW_MBUF_GENERATED;
1317         ip_output(m, NULL, &sro, 0, NULL, NULL);
1318         if (sro.ro_rt)
1319                 RTFREE(sro.ro_rt);
1320 }
1321
1322 /*
1323  * sends a reject message, consuming the mbuf passed as an argument.
1324  */
1325 static void
1326 send_reject(struct ip_fw_args *args, int code, int offset, int ip_len)
1327 {
1328         if (code != ICMP_REJECT_RST) { /* Send an ICMP unreach */
1329                 /* We need the IP header in host order for icmp_error(). */
1330                 if (args->eh != NULL) {
1331                         struct ip *ip = mtod(args->m, struct ip *);
1332
1333                         ip->ip_len = ntohs(ip->ip_len);
1334                         ip->ip_off = ntohs(ip->ip_off);
1335                 }
1336                 icmp_error(args->m, ICMP_UNREACH, code, 0L, 0);
1337         } else if (offset == 0 && args->f_id.proto == IPPROTO_TCP) {
1338                 struct tcphdr *const tcp =
1339                     L3HDR(struct tcphdr, mtod(args->m, struct ip *));
1340
1341                 if ((tcp->th_flags & TH_RST) == 0) {
1342                         send_pkt(&args->f_id, ntohl(tcp->th_seq),
1343                                  ntohl(tcp->th_ack), tcp->th_flags | TH_RST);
1344                 }
1345                 m_freem(args->m);
1346         } else {
1347                 m_freem(args->m);
1348         }
1349         args->m = NULL;
1350 }
1351
1352 /**
1353  *
1354  * Given an ip_fw *, lookup_next_rule will return a pointer
1355  * to the next rule, which can be either the jump
1356  * target (for skipto instructions) or the next one in the list (in
1357  * all other cases including a missing jump target).
1358  * The result is also written in the "next_rule" field of the rule.
1359  * Backward jumps are not allowed, so start looking from the next
1360  * rule...
1361  *
1362  * This never returns NULL -- in case we do not have an exact match,
1363  * the next rule is returned. When the ruleset is changed,
1364  * pointers are flushed so we are always correct.
1365  */
1366
1367 static struct ip_fw *
1368 lookup_next_rule(struct ip_fw *me)
1369 {
1370         struct ip_fw *rule = NULL;
1371         ipfw_insn *cmd;
1372
1373         /* look for action, in case it is a skipto */
1374         cmd = ACTION_PTR(me);
1375         if (cmd->opcode == O_LOG)
1376                 cmd += F_LEN(cmd);
1377         if (cmd->opcode == O_SKIPTO) {
1378                 for (rule = me->next; rule; rule = rule->next) {
1379                         if (rule->rulenum >= cmd->arg1)
1380                                 break;
1381                 }
1382         }
1383         if (rule == NULL)                       /* failure or not a skipto */
1384                 rule = me->next;
1385         me->next_rule = rule;
1386         return rule;
1387 }
1388
1389 /*
1390  * The main check routine for the firewall.
1391  *
1392  * All arguments are in args so we can modify them and return them
1393  * back to the caller.
1394  *
1395  * Parameters:
1396  *
1397  *      args->m (in/out) The packet; we set to NULL when/if we nuke it.
1398  *              Starts with the IP header.
1399  *      args->eh (in)   Mac header if present, or NULL for layer3 packet.
1400  *      args->oif       Outgoing interface, or NULL if packet is incoming.
1401  *              The incoming interface is in the mbuf. (in)
1402  *
1403  *      args->rule      Pointer to the last matching rule (in/out)
1404  *      args->next_hop  Socket we are forwarding to (out).
1405  *      args->f_id      Addresses grabbed from the packet (out)
1406  *
1407  * Return value:
1408  *
1409  *      IP_FW_PORT_DENY_FLAG    the packet must be dropped.
1410  *      0       The packet is to be accepted and routed normally OR
1411  *              the packet was denied/rejected and has been dropped;
1412  *              in the latter case, *m is equal to NULL upon return.
1413  *      port    Divert the packet to port, with these caveats:
1414  *
1415  *              - If IP_FW_PORT_TEE_FLAG is set, tee the packet instead
1416  *                of diverting it (ie, 'ipfw tee').
1417  *
1418  *              - If IP_FW_PORT_DYNT_FLAG is set, interpret the lower
1419  *                16 bits as a dummynet pipe number instead of diverting
1420  */
1421
1422 static int
1423 ipfw_chk(struct ip_fw_args *args)
1424 {
1425         /*
1426          * Local variables hold state during the processing of a packet.
1427          *
1428          * IMPORTANT NOTE: to speed up the processing of rules, there
1429          * are some assumption on the values of the variables, which
1430          * are documented here. Should you change them, please check
1431          * the implementation of the various instructions to make sure
1432          * that they still work.
1433          *
1434          * args->eh     The MAC header. It is non-null for a layer2
1435          *      packet, it is NULL for a layer-3 packet.
1436          *
1437          * m | args->m  Pointer to the mbuf, as received from the caller.
1438          *      It may change if ipfw_chk() does an m_pullup, or if it
1439          *      consumes the packet because it calls send_reject().
1440          *      XXX This has to change, so that ipfw_chk() never modifies
1441          *      or consumes the buffer.
1442          * ip   is simply an alias of the value of m, and it is kept
1443          *      in sync with it (the packet is  supposed to start with
1444          *      the ip header).
1445          */
1446         struct mbuf *m = args->m;
1447         struct ip *ip = mtod(m, struct ip *);
1448
1449         /*
1450          * oif | args->oif      If NULL, ipfw_chk has been called on the
1451          *      inbound path (ether_input, ip_input).
1452          *      If non-NULL, ipfw_chk has been called on the outbound path
1453          *      (ether_output, ip_output).
1454          */
1455         struct ifnet *oif = args->oif;
1456
1457         struct ip_fw *f = NULL;         /* matching rule */
1458         int retval = 0;
1459         struct m_tag *mtag;
1460
1461         /*
1462          * hlen The length of the IPv4 header.
1463          *      hlen >0 means we have an IPv4 packet.
1464          */
1465         u_int hlen = 0;         /* hlen >0 means we have an IP pkt */
1466
1467         /*
1468          * offset       The offset of a fragment. offset != 0 means that
1469          *      we have a fragment at this offset of an IPv4 packet.
1470          *      offset == 0 means that (if this is an IPv4 packet)
1471          *      this is the first or only fragment.
1472          */
1473         u_short offset = 0;
1474
1475         /*
1476          * Local copies of addresses. They are only valid if we have
1477          * an IP packet.
1478          *
1479          * proto        The protocol. Set to 0 for non-ip packets,
1480          *      or to the protocol read from the packet otherwise.
1481          *      proto != 0 means that we have an IPv4 packet.
1482          *
1483          * src_port, dst_port   port numbers, in HOST format. Only
1484          *      valid for TCP and UDP packets.
1485          *
1486          * src_ip, dst_ip       ip addresses, in NETWORK format.
1487          *      Only valid for IPv4 packets.
1488          */
1489         uint8_t proto;
1490         uint16_t src_port = 0, dst_port = 0;    /* NOTE: host format    */
1491         struct in_addr src_ip, dst_ip;          /* NOTE: network format */
1492         uint16_t ip_len = 0;
1493         int dyn_dir = MATCH_UNKNOWN;
1494         ipfw_dyn_rule *q = NULL;
1495
1496         if (m->m_pkthdr.fw_flags & IPFW_MBUF_GENERATED)
1497                 return 0;       /* accept */
1498         /*
1499          * dyn_dir = MATCH_UNKNOWN when rules unchecked,
1500          *      MATCH_NONE when checked and not matched (q = NULL),
1501          *      MATCH_FORWARD or MATCH_REVERSE otherwise (q != NULL)
1502          */
1503
1504         if (args->eh == NULL ||         /* layer 3 packet */
1505             (m->m_pkthdr.len >= sizeof(struct ip) &&
1506              ntohs(args->eh->ether_type) == ETHERTYPE_IP))
1507                 hlen = ip->ip_hl << 2;
1508
1509         /*
1510          * Collect parameters into local variables for faster matching.
1511          */
1512         if (hlen == 0) {        /* do not grab addresses for non-ip pkts */
1513                 proto = args->f_id.proto = 0;   /* mark f_id invalid */
1514                 goto after_ip_checks;
1515         }
1516
1517         proto = args->f_id.proto = ip->ip_p;
1518         src_ip = ip->ip_src;
1519         dst_ip = ip->ip_dst;
1520         if (args->eh != NULL) { /* layer 2 packets are as on the wire */
1521                 offset = ntohs(ip->ip_off) & IP_OFFMASK;
1522                 ip_len = ntohs(ip->ip_len);
1523         } else {
1524                 offset = ip->ip_off & IP_OFFMASK;
1525                 ip_len = ip->ip_len;
1526         }
1527
1528 #define PULLUP_TO(len)                          \
1529 do {                                            \
1530         if (m->m_len < (len)) {                 \
1531                 args->m = m = m_pullup(m, (len));\
1532                 if (m == NULL)                  \
1533                         goto pullup_failed;     \
1534                 ip = mtod(m, struct ip *);      \
1535         }                                       \
1536 } while (0)
1537
1538         if (offset == 0) {
1539                 switch (proto) {
1540                 case IPPROTO_TCP:
1541                         {
1542                                 struct tcphdr *tcp;
1543
1544                                 PULLUP_TO(hlen + sizeof(struct tcphdr));
1545                                 tcp = L3HDR(struct tcphdr, ip);
1546                                 dst_port = tcp->th_dport;
1547                                 src_port = tcp->th_sport;
1548                                 args->f_id.flags = tcp->th_flags;
1549                         }
1550                         break;
1551
1552                 case IPPROTO_UDP:
1553                         {
1554                                 struct udphdr *udp;
1555
1556                                 PULLUP_TO(hlen + sizeof(struct udphdr));
1557                                 udp = L3HDR(struct udphdr, ip);
1558                                 dst_port = udp->uh_dport;
1559                                 src_port = udp->uh_sport;
1560                         }
1561                         break;
1562
1563                 case IPPROTO_ICMP:
1564                         PULLUP_TO(hlen + 4);    /* type, code and checksum. */
1565                         args->f_id.flags = L3HDR(struct icmp, ip)->icmp_type;
1566                         break;
1567
1568                 default:
1569                         break;
1570                 }
1571         }
1572
1573 #undef PULLUP_TO
1574
1575         args->f_id.src_ip = ntohl(src_ip.s_addr);
1576         args->f_id.dst_ip = ntohl(dst_ip.s_addr);
1577         args->f_id.src_port = src_port = ntohs(src_port);
1578         args->f_id.dst_port = dst_port = ntohs(dst_port);
1579
1580 after_ip_checks:
1581         if (args->rule) {
1582                 /*
1583                  * Packet has already been tagged. Look for the next rule
1584                  * to restart processing.
1585                  *
1586                  * If fw_one_pass != 0 then just accept it.
1587                  * XXX should not happen here, but optimized out in
1588                  * the caller.
1589                  */
1590                 if (fw_one_pass)
1591                         return 0;
1592
1593                 /* This rule was deleted */
1594                 if (args->rule->rule_flags & IPFW_RULE_F_INVALID)
1595                         return IP_FW_PORT_DENY_FLAG;
1596
1597                 f = args->rule->next_rule;
1598                 if (f == NULL)
1599                         f = lookup_next_rule(args->rule);
1600         } else {
1601                 /*
1602                  * Find the starting rule. It can be either the first
1603                  * one, or the one after divert_rule if asked so.
1604                  */
1605                 int skipto;
1606
1607                 mtag = m_tag_find(m, PACKET_TAG_IPFW_DIVERT, NULL);
1608                 if (mtag != NULL)
1609                         skipto = *(uint16_t *)m_tag_data(mtag);
1610                 else
1611                         skipto = 0;
1612
1613                 f = layer3_chain;
1614                 if (args->eh == NULL && skipto != 0) {
1615                         if (skipto >= IPFW_DEFAULT_RULE)
1616                                 return(IP_FW_PORT_DENY_FLAG); /* invalid */
1617                         while (f && f->rulenum <= skipto)
1618                                 f = f->next;
1619                         if (f == NULL)  /* drop packet */
1620                                 return(IP_FW_PORT_DENY_FLAG);
1621                 }
1622         }
1623         if ((mtag = m_tag_find(m, PACKET_TAG_IPFW_DIVERT, NULL)) != NULL)
1624                 m_tag_delete(m, mtag);
1625
1626         /*
1627          * Now scan the rules, and parse microinstructions for each rule.
1628          */
1629         for (; f; f = f->next) {
1630                 int l, cmdlen;
1631                 ipfw_insn *cmd;
1632                 int skip_or; /* skip rest of OR block */
1633
1634 again:
1635                 if (set_disable & (1 << f->set))
1636                         continue;
1637
1638                 skip_or = 0;
1639                 for (l = f->cmd_len, cmd = f->cmd; l > 0;
1640                      l -= cmdlen, cmd += cmdlen) {
1641                         int match, deny;
1642
1643                         /*
1644                          * check_body is a jump target used when we find a
1645                          * CHECK_STATE, and need to jump to the body of
1646                          * the target rule.
1647                          */
1648
1649 check_body:
1650                         cmdlen = F_LEN(cmd);
1651                         /*
1652                          * An OR block (insn_1 || .. || insn_n) has the
1653                          * F_OR bit set in all but the last instruction.
1654                          * The first match will set "skip_or", and cause
1655                          * the following instructions to be skipped until
1656                          * past the one with the F_OR bit clear.
1657                          */
1658                         if (skip_or) {          /* skip this instruction */
1659                                 if ((cmd->len & F_OR) == 0)
1660                                         skip_or = 0;    /* next one is good */
1661                                 continue;
1662                         }
1663                         match = 0; /* set to 1 if we succeed */
1664
1665                         switch (cmd->opcode) {
1666                         /*
1667                          * The first set of opcodes compares the packet's
1668                          * fields with some pattern, setting 'match' if a
1669                          * match is found. At the end of the loop there is
1670                          * logic to deal with F_NOT and F_OR flags associated
1671                          * with the opcode.
1672                          */
1673                         case O_NOP:
1674                                 match = 1;
1675                                 break;
1676
1677                         case O_FORWARD_MAC:
1678                                 kprintf("ipfw: opcode %d unimplemented\n",
1679                                         cmd->opcode);
1680                                 break;
1681
1682                         case O_GID:
1683                         case O_UID:
1684                                 /*
1685                                  * We only check offset == 0 && proto != 0,
1686                                  * as this ensures that we have an IPv4
1687                                  * packet with the ports info.
1688                                  */
1689                                 if (offset!=0)
1690                                         break;
1691                             {
1692                                 struct inpcbinfo *pi;
1693                                 int wildcard;
1694                                 struct inpcb *pcb;
1695
1696                                 if (proto == IPPROTO_TCP) {
1697                                         wildcard = 0;
1698                                         pi = &tcbinfo[mycpu->gd_cpuid];
1699                                 } else if (proto == IPPROTO_UDP) {
1700                                         wildcard = 1;
1701                                         pi = &udbinfo;
1702                                 } else
1703                                         break;
1704
1705                                 pcb =  (oif) ?
1706                                         in_pcblookup_hash(pi,
1707                                             dst_ip, htons(dst_port),
1708                                             src_ip, htons(src_port),
1709                                             wildcard, oif) :
1710                                         in_pcblookup_hash(pi,
1711                                             src_ip, htons(src_port),
1712                                             dst_ip, htons(dst_port),
1713                                             wildcard, NULL);
1714
1715                                 if (pcb == NULL || pcb->inp_socket == NULL)
1716                                         break;
1717
1718                                 if (cmd->opcode == O_UID) {
1719 #define socheckuid(a,b) ((a)->so_cred->cr_uid != (b))
1720                                         match =
1721                                           !socheckuid(pcb->inp_socket,
1722                                            (uid_t)((ipfw_insn_u32 *)cmd)->d[0]);
1723 #undef socheckuid
1724                                 } else  {
1725                                         match = groupmember(
1726                                             (uid_t)((ipfw_insn_u32 *)cmd)->d[0],
1727                                             pcb->inp_socket->so_cred);
1728                                 }
1729                             }
1730                                 break;
1731
1732                         case O_RECV:
1733                                 match = iface_match(m->m_pkthdr.rcvif,
1734                                     (ipfw_insn_if *)cmd);
1735                                 break;
1736
1737                         case O_XMIT:
1738                                 match = iface_match(oif, (ipfw_insn_if *)cmd);
1739                                 break;
1740
1741                         case O_VIA:
1742                                 match = iface_match(oif ? oif :
1743                                     m->m_pkthdr.rcvif, (ipfw_insn_if *)cmd);
1744                                 break;
1745
1746                         case O_MACADDR2:
1747                                 if (args->eh != NULL) { /* have MAC header */
1748                                         uint32_t *want = (uint32_t *)
1749                                                 ((ipfw_insn_mac *)cmd)->addr;
1750                                         uint32_t *mask = (uint32_t *)
1751                                                 ((ipfw_insn_mac *)cmd)->mask;
1752                                         uint32_t *hdr = (uint32_t *)args->eh;
1753
1754                                         match =
1755                                         (want[0] == (hdr[0] & mask[0]) &&
1756                                          want[1] == (hdr[1] & mask[1]) &&
1757                                          want[2] == (hdr[2] & mask[2]));
1758                                 }
1759                                 break;
1760
1761                         case O_MAC_TYPE:
1762                                 if (args->eh != NULL) {
1763                                         uint16_t t =
1764                                             ntohs(args->eh->ether_type);
1765                                         uint16_t *p =
1766                                             ((ipfw_insn_u16 *)cmd)->ports;
1767                                         int i;
1768
1769                                         /* Special vlan handling */
1770                                         if (m->m_flags & M_VLANTAG)
1771                                                 t = ETHERTYPE_VLAN;
1772
1773                                         for (i = cmdlen - 1; !match && i > 0;
1774                                              i--, p += 2) {
1775                                                 match =
1776                                                 (t >= p[0] && t <= p[1]);
1777                                         }
1778                                 }
1779                                 break;
1780
1781                         case O_FRAG:
1782                                 match = (hlen > 0 && offset != 0);
1783                                 break;
1784
1785                         case O_IN:      /* "out" is "not in" */
1786                                 match = (oif == NULL);
1787                                 break;
1788
1789                         case O_LAYER2:
1790                                 match = (args->eh != NULL);
1791                                 break;
1792
1793                         case O_PROTO:
1794                                 /*
1795                                  * We do not allow an arg of 0 so the
1796                                  * check of "proto" only suffices.
1797                                  */
1798                                 match = (proto == cmd->arg1);
1799                                 break;
1800
1801                         case O_IP_SRC:
1802                                 match = (hlen > 0 &&
1803                                     ((ipfw_insn_ip *)cmd)->addr.s_addr ==
1804                                     src_ip.s_addr);
1805                                 break;
1806
1807                         case O_IP_SRC_MASK:
1808                                 match = (hlen > 0 &&
1809                                     ((ipfw_insn_ip *)cmd)->addr.s_addr ==
1810                                      (src_ip.s_addr &
1811                                      ((ipfw_insn_ip *)cmd)->mask.s_addr));
1812                                 break;
1813
1814                         case O_IP_SRC_ME:
1815                                 if (hlen > 0) {
1816                                         struct ifnet *tif;
1817
1818                                         tif = INADDR_TO_IFP(&src_ip);
1819                                         match = (tif != NULL);
1820                                 }
1821                                 break;
1822
1823                         case O_IP_DST_SET:
1824                         case O_IP_SRC_SET:
1825                                 if (hlen > 0) {
1826                                         uint32_t *d = (uint32_t *)(cmd + 1);
1827                                         uint32_t addr =
1828                                             cmd->opcode == O_IP_DST_SET ?
1829                                                 args->f_id.dst_ip :
1830                                                 args->f_id.src_ip;
1831
1832                                         if (addr < d[0])
1833                                                 break;
1834                                         addr -= d[0]; /* subtract base */
1835                                         match =
1836                                         (addr < cmd->arg1) &&
1837                                          (d[1 + (addr >> 5)] &
1838                                           (1 << (addr & 0x1f)));
1839                                 }
1840                                 break;
1841
1842                         case O_IP_DST:
1843                                 match = (hlen > 0 &&
1844                                     ((ipfw_insn_ip *)cmd)->addr.s_addr ==
1845                                     dst_ip.s_addr);
1846                                 break;
1847
1848                         case O_IP_DST_MASK:
1849                                 match = (hlen > 0) &&
1850                                     (((ipfw_insn_ip *)cmd)->addr.s_addr ==
1851                                      (dst_ip.s_addr &
1852                                      ((ipfw_insn_ip *)cmd)->mask.s_addr));
1853                                 break;
1854
1855                         case O_IP_DST_ME:
1856                                 if (hlen > 0) {
1857                                         struct ifnet *tif;
1858
1859                                         tif = INADDR_TO_IFP(&dst_ip);
1860                                         match = (tif != NULL);
1861                                 }
1862                                 break;
1863
1864                         case O_IP_SRCPORT:
1865                         case O_IP_DSTPORT:
1866                                 /*
1867                                  * offset == 0 && proto != 0 is enough
1868                                  * to guarantee that we have an IPv4
1869                                  * packet with port info.
1870                                  */
1871                                 if ((proto==IPPROTO_UDP || proto==IPPROTO_TCP)
1872                                     && offset == 0) {
1873                                         uint16_t x =
1874                                             (cmd->opcode == O_IP_SRCPORT) ?
1875                                                 src_port : dst_port ;
1876                                         uint16_t *p =
1877                                             ((ipfw_insn_u16 *)cmd)->ports;
1878                                         int i;
1879
1880                                         for (i = cmdlen - 1; !match && i > 0;
1881                                              i--, p += 2) {
1882                                                 match =
1883                                                 (x >= p[0] && x <= p[1]);
1884                                         }
1885                                 }
1886                                 break;
1887
1888                         case O_ICMPTYPE:
1889                                 match = (offset == 0 && proto==IPPROTO_ICMP &&
1890                                     icmptype_match(ip, (ipfw_insn_u32 *)cmd));
1891                                 break;
1892
1893                         case O_IPOPT:
1894                                 match = (hlen > 0 && ipopts_match(ip, cmd));
1895                                 break;
1896
1897                         case O_IPVER:
1898                                 match = (hlen > 0 && cmd->arg1 == ip->ip_v);
1899                                 break;
1900
1901                         case O_IPTTL:
1902                                 match = (hlen > 0 && cmd->arg1 == ip->ip_ttl);
1903                                 break;
1904
1905                         case O_IPID:
1906                                 match = (hlen > 0 &&
1907                                     cmd->arg1 == ntohs(ip->ip_id));
1908                                 break;
1909
1910                         case O_IPLEN:
1911                                 match = (hlen > 0 && cmd->arg1 == ip_len);
1912                                 break;
1913
1914                         case O_IPPRECEDENCE:
1915                                 match = (hlen > 0 &&
1916                                     (cmd->arg1 == (ip->ip_tos & 0xe0)));
1917                                 break;
1918
1919                         case O_IPTOS:
1920                                 match = (hlen > 0 &&
1921                                     flags_match(cmd, ip->ip_tos));
1922                                 break;
1923
1924                         case O_TCPFLAGS:
1925                                 match = (proto == IPPROTO_TCP && offset == 0 &&
1926                                     flags_match(cmd,
1927                                         L3HDR(struct tcphdr,ip)->th_flags));
1928                                 break;
1929
1930                         case O_TCPOPTS:
1931                                 match = (proto == IPPROTO_TCP && offset == 0 &&
1932                                     tcpopts_match(ip, cmd));
1933                                 break;
1934
1935                         case O_TCPSEQ:
1936                                 match = (proto == IPPROTO_TCP && offset == 0 &&
1937                                     ((ipfw_insn_u32 *)cmd)->d[0] ==
1938                                         L3HDR(struct tcphdr,ip)->th_seq);
1939                                 break;
1940
1941                         case O_TCPACK:
1942                                 match = (proto == IPPROTO_TCP && offset == 0 &&
1943                                     ((ipfw_insn_u32 *)cmd)->d[0] ==
1944                                         L3HDR(struct tcphdr,ip)->th_ack);
1945                                 break;
1946
1947                         case O_TCPWIN:
1948                                 match = (proto == IPPROTO_TCP && offset == 0 &&
1949                                     cmd->arg1 ==
1950                                         L3HDR(struct tcphdr,ip)->th_win);
1951                                 break;
1952
1953                         case O_ESTAB:
1954                                 /* reject packets which have SYN only */
1955                                 /* XXX should i also check for TH_ACK ? */
1956                                 match = (proto == IPPROTO_TCP && offset == 0 &&
1957                                     (L3HDR(struct tcphdr,ip)->th_flags &
1958                                      (TH_RST | TH_ACK | TH_SYN)) != TH_SYN);
1959                                 break;
1960
1961                         case O_LOG:
1962                                 if (fw_verbose)
1963                                         ipfw_log(f, hlen, args->eh, m, oif);
1964                                 match = 1;
1965                                 break;
1966
1967                         case O_PROB:
1968                                 match = (krandom() <
1969                                         ((ipfw_insn_u32 *)cmd)->d[0]);
1970                                 break;
1971
1972                         /*
1973                          * The second set of opcodes represents 'actions',
1974                          * i.e. the terminal part of a rule once the packet
1975                          * matches all previous patterns.
1976                          * Typically there is only one action for each rule,
1977                          * and the opcode is stored at the end of the rule
1978                          * (but there are exceptions -- see below).
1979                          *
1980                          * In general, here we set retval and terminate the
1981                          * outer loop (would be a 'break 3' in some language,
1982                          * but we need to do a 'goto done').
1983                          *
1984                          * Exceptions:
1985                          * O_COUNT and O_SKIPTO actions:
1986                          *   instead of terminating, we jump to the next rule
1987                          *   ('goto next_rule', equivalent to a 'break 2'),
1988                          *   or to the SKIPTO target ('goto again' after
1989                          *   having set f, cmd and l), respectively.
1990                          *
1991                          * O_LIMIT and O_KEEP_STATE: these opcodes are
1992                          *   not real 'actions', and are stored right
1993                          *   before the 'action' part of the rule.
1994                          *   These opcodes try to install an entry in the
1995                          *   state tables; if successful, we continue with
1996                          *   the next opcode (match=1; break;), otherwise
1997                          *   the packet must be dropped ('goto done' after
1998                          *   setting retval).  If static rules are changed
1999                          *   during the state installation, the packet will
2000                          *   be dropped ('return IP_FW_PORT_DENY_FLAG').
2001                          *
2002                          * O_PROBE_STATE and O_CHECK_STATE: these opcodes
2003                          *   cause a lookup of the state table, and a jump
2004                          *   to the 'action' part of the parent rule
2005                          *   ('goto check_body') if an entry is found, or
2006                          *   (CHECK_STATE only) a jump to the next rule if
2007                          *   the entry is not found ('goto next_rule').
2008                          *   The result of the lookup is cached to make
2009                          *   further instances of these opcodes are
2010                          *   effectively NOPs.  If static rules are changed
2011                          *   during the state looking up, the packet will
2012                          *   be dropped ('return IP_FW_PORT_DENY_FLAG').
2013                          */
2014                         case O_LIMIT:
2015                         case O_KEEP_STATE:
2016                                 if (install_state(f,
2017                                     (ipfw_insn_limit *)cmd, args, &deny)) {
2018                                         if (deny)
2019                                                 return IP_FW_PORT_DENY_FLAG;
2020
2021                                         retval = IP_FW_PORT_DENY_FLAG;
2022                                         goto done; /* error/limit violation */
2023                                 }
2024                                 if (deny)
2025                                         return IP_FW_PORT_DENY_FLAG;
2026                                 match = 1;
2027                                 break;
2028
2029                         case O_PROBE_STATE:
2030                         case O_CHECK_STATE:
2031                                 /*
2032                                  * dynamic rules are checked at the first
2033                                  * keep-state or check-state occurrence,
2034                                  * with the result being stored in dyn_dir.
2035                                  * The compiler introduces a PROBE_STATE
2036                                  * instruction for us when we have a
2037                                  * KEEP_STATE (because PROBE_STATE needs
2038                                  * to be run first).
2039                                  */
2040                                 if (dyn_dir == MATCH_UNKNOWN) {
2041                                         struct ip_fw *dyn_f;
2042
2043                                         dyn_f = lookup_rule(&args->f_id,
2044                                                 &dyn_dir,
2045                                                 proto == IPPROTO_TCP ?
2046                                                 L3HDR(struct tcphdr, ip) : NULL,
2047                                                 ip_len, &deny);
2048                                         if (deny)
2049                                                 return IP_FW_PORT_DENY_FLAG;
2050                                         if (dyn_f != NULL) {
2051                                                 /*
2052                                                  * Found a rule from a dynamic
2053                                                  * entry; jump to the 'action'
2054                                                  * part of the rule.
2055                                                  */
2056                                                 f = dyn_f;
2057                                                 cmd = ACTION_PTR(f);
2058                                                 l = f->cmd_len - f->act_ofs;
2059                                                 goto check_body;
2060                                         }
2061                                 }
2062                                 /*
2063                                  * Dynamic entry not found. If CHECK_STATE,
2064                                  * skip to next rule, if PROBE_STATE just
2065                                  * ignore and continue with next opcode.
2066                                  */
2067                                 if (cmd->opcode == O_CHECK_STATE)
2068                                         goto next_rule;
2069                                 match = 1;
2070                                 break;
2071
2072                         case O_ACCEPT:
2073                                 retval = 0;     /* accept */
2074                                 goto done;
2075
2076                         case O_PIPE:
2077                         case O_QUEUE:
2078                                 args->rule = f; /* report matching rule */
2079                                 retval = cmd->arg1 | IP_FW_PORT_DYNT_FLAG;
2080                                 goto done;
2081
2082                         case O_DIVERT:
2083                         case O_TEE:
2084                                 if (args->eh) /* not on layer 2 */
2085                                         break;
2086
2087                                 mtag = m_tag_get(PACKET_TAG_IPFW_DIVERT,
2088                                                  sizeof(uint16_t), MB_DONTWAIT);
2089                                 if (mtag == NULL) {
2090                                         retval = IP_FW_PORT_DENY_FLAG;
2091                                         goto done;
2092                                 }
2093                                 *(uint16_t *)m_tag_data(mtag) = f->rulenum;
2094                                 m_tag_prepend(m, mtag);
2095                                 retval = (cmd->opcode == O_DIVERT) ?
2096                                     cmd->arg1 :
2097                                     cmd->arg1 | IP_FW_PORT_TEE_FLAG;
2098                                 goto done;
2099
2100                         case O_COUNT:
2101                         case O_SKIPTO:
2102                                 f->pcnt++;      /* update stats */
2103                                 f->bcnt += ip_len;
2104                                 f->timestamp = time_second;
2105                                 if (cmd->opcode == O_COUNT)
2106                                         goto next_rule;
2107                                 /* handle skipto */
2108                                 if (f->next_rule == NULL)
2109                                         lookup_next_rule(f);
2110                                 f = f->next_rule;
2111                                 goto again;
2112
2113                         case O_REJECT:
2114                                 /*
2115                                  * Drop the packet and send a reject notice
2116                                  * if the packet is not ICMP (or is an ICMP
2117                                  * query), and it is not multicast/broadcast.
2118                                  */
2119                                 if (hlen > 0 &&
2120                                     (proto != IPPROTO_ICMP ||
2121                                      is_icmp_query(ip)) &&
2122                                     !(m->m_flags & (M_BCAST|M_MCAST)) &&
2123                                     !IN_MULTICAST(ntohl(dst_ip.s_addr))) {
2124                                         send_reject(args, cmd->arg1,
2125                                             offset,ip_len);
2126                                         m = args->m;
2127                                 }
2128                                 /* FALLTHROUGH */
2129                         case O_DENY:
2130                                 retval = IP_FW_PORT_DENY_FLAG;
2131                                 goto done;
2132
2133                         case O_FORWARD_IP:
2134                                 if (args->eh)   /* not valid on layer2 pkts */
2135                                         break;
2136                                 if (!q || dyn_dir == MATCH_FORWARD) {
2137                                         args->next_hop =
2138                                             &((ipfw_insn_sa *)cmd)->sa;
2139                                 }
2140                                 retval = 0;
2141                                 goto done;
2142
2143                         default:
2144                                 panic("-- unknown opcode %d\n", cmd->opcode);
2145                         } /* end of switch() on opcodes */
2146
2147                         if (cmd->len & F_NOT)
2148                                 match = !match;
2149
2150                         if (match) {
2151                                 if (cmd->len & F_OR)
2152                                         skip_or = 1;
2153                         } else {
2154                                 if (!(cmd->len & F_OR)) /* not an OR block, */
2155                                         break;          /* try next rule    */
2156                         }
2157
2158                 }       /* end of inner for, scan opcodes */
2159
2160 next_rule:;             /* try next rule                */
2161
2162         }               /* end of outer for, scan rules */
2163         kprintf("+++ ipfw: ouch!, skip past end of rules, denying packet\n");
2164         return(IP_FW_PORT_DENY_FLAG);
2165
2166 done:
2167         /* Update statistics */
2168         f->pcnt++;
2169         f->bcnt += ip_len;
2170         f->timestamp = time_second;
2171         return retval;
2172
2173 pullup_failed:
2174         if (fw_verbose)
2175                 kprintf("pullup failed\n");
2176         return(IP_FW_PORT_DENY_FLAG);
2177 }
2178
2179 static void
2180 ipfw_dummynet_io(struct mbuf *m, int pipe_nr, int dir, struct ip_fw_args *fwa)
2181 {
2182         struct m_tag *mtag;
2183         struct dn_pkt *pkt;
2184         ipfw_insn *cmd;
2185         const struct ipfw_flow_id *id;
2186         struct dn_flow_id *fid;
2187
2188         M_ASSERTPKTHDR(m);
2189
2190         mtag = m_tag_get(PACKET_TAG_DUMMYNET, sizeof(*pkt), MB_DONTWAIT);
2191         if (mtag == NULL) {
2192                 m_freem(m);
2193                 return;
2194         }
2195         m_tag_prepend(m, mtag);
2196
2197         pkt = m_tag_data(mtag);
2198         bzero(pkt, sizeof(*pkt));
2199
2200         cmd = fwa->rule->cmd + fwa->rule->act_ofs;
2201         if (cmd->opcode == O_LOG)
2202                 cmd += F_LEN(cmd);
2203         KASSERT(cmd->opcode == O_PIPE || cmd->opcode == O_QUEUE,
2204                 ("Rule is not PIPE or QUEUE, opcode %d\n", cmd->opcode));
2205
2206         pkt->dn_m = m;
2207         pkt->dn_flags = (dir & DN_FLAGS_DIR_MASK);
2208         pkt->ifp = fwa->oif;
2209         pkt->cpuid = mycpu->gd_cpuid;
2210         pkt->pipe_nr = pipe_nr;
2211
2212         id = &fwa->f_id;
2213         fid = &pkt->id;
2214         fid->fid_dst_ip = id->dst_ip;
2215         fid->fid_src_ip = id->src_ip;
2216         fid->fid_dst_port = id->dst_port;
2217         fid->fid_src_port = id->src_port;
2218         fid->fid_proto = id->proto;
2219         fid->fid_flags = id->flags;
2220
2221         ipfw_ref_rule(fwa->rule);
2222         pkt->dn_priv = fwa->rule;
2223         pkt->dn_unref_priv = ipfw_unref_rule;
2224
2225         if (cmd->opcode == O_PIPE)
2226                 pkt->dn_flags |= DN_FLAGS_IS_PIPE;
2227
2228         if (dir == DN_TO_IP_OUT) {
2229                 /*
2230                  * We need to copy *ro because for ICMP pkts (and maybe
2231                  * others) the caller passed a pointer into the stack;
2232                  * dst might also be a pointer into *ro so it needs to
2233                  * be updated.
2234                  */
2235                 pkt->ro = *(fwa->ro);
2236                 if (fwa->ro->ro_rt)
2237                         fwa->ro->ro_rt->rt_refcnt++;
2238                 if (fwa->dst == (struct sockaddr_in *)&fwa->ro->ro_dst) {
2239                         /* 'dst' points into 'ro' */
2240                         fwa->dst = (struct sockaddr_in *)&(pkt->ro.ro_dst);
2241                 }
2242                 pkt->dn_dst = fwa->dst;
2243                 pkt->flags = fwa->flags;
2244         }
2245
2246         m->m_pkthdr.fw_flags |= DUMMYNET_MBUF_TAGGED;
2247         ip_dn_queue(m);
2248 }
2249
2250 /*
2251  * When a rule is added/deleted, clear the next_rule pointers in all rules.
2252  * These will be reconstructed on the fly as packets are matched.
2253  * Must be called at splimp().
2254  */
2255 static void
2256 flush_rule_ptrs(void)
2257 {
2258         struct ip_fw *rule;
2259
2260         for (rule = layer3_chain; rule; rule = rule->next)
2261                 rule->next_rule = NULL;
2262 }
2263
2264 static __inline void
2265 ipfw_inc_static_count(struct ip_fw *rule)
2266 {
2267         IPFW_ASSERT_CFGPORT(&curthread->td_msgport);
2268
2269         static_count++;
2270         static_ioc_len += IOC_RULESIZE(rule);
2271 }
2272
2273 static __inline void
2274 ipfw_dec_static_count(struct ip_fw *rule)
2275 {
2276         int l = IOC_RULESIZE(rule);
2277
2278         IPFW_ASSERT_CFGPORT(&curthread->td_msgport);
2279
2280         KASSERT(static_count > 0, ("invalid static count %u\n", static_count));
2281         static_count--;
2282
2283         KASSERT(static_ioc_len >= l,
2284                 ("invalid static len %u\n", static_ioc_len));
2285         static_ioc_len -= l;
2286 }
2287
2288 static struct ip_fw *
2289 ipfw_create_rule(const struct ipfw_ioc_rule *ioc_rule)
2290 {
2291         struct ip_fw *rule;
2292
2293         rule = kmalloc(RULESIZE(ioc_rule), M_IPFW, M_WAITOK | M_ZERO);
2294
2295         rule->act_ofs = ioc_rule->act_ofs;
2296         rule->cmd_len = ioc_rule->cmd_len;
2297         rule->rulenum = ioc_rule->rulenum;
2298         rule->set = ioc_rule->set;
2299         rule->usr_flags = ioc_rule->usr_flags;
2300
2301         bcopy(ioc_rule->cmd, rule->cmd, rule->cmd_len * 4 /* XXX */);
2302
2303         rule->refcnt = 1;
2304
2305         return rule;
2306 }
2307
2308 /*
2309  * Add a new rule to the list.  Copy the rule into a malloc'ed area,
2310  * then possibly create a rule number and add the rule to the list.
2311  * Update the rule_number in the input struct so the caller knows
2312  * it as well.
2313  */
2314 static void
2315 ipfw_add_rule(struct ip_fw **head, struct ipfw_ioc_rule *ioc_rule)
2316 {
2317         struct ip_fw *rule, *f, *prev;
2318
2319         KKASSERT(*head != NULL);
2320         IPFW_ASSERT_CFGPORT(&curthread->td_msgport);
2321
2322         ++static_gen;
2323
2324         rule = ipfw_create_rule(ioc_rule);
2325
2326         crit_enter();
2327
2328         /*
2329          * If rulenum is 0, find highest numbered rule before the
2330          * default rule, and add rule number incremental step
2331          */
2332         if (rule->rulenum == 0) {
2333                 int step = autoinc_step;
2334
2335                 KKASSERT(step >= IPFW_AUTOINC_STEP_MIN &&
2336                          step <= IPFW_AUTOINC_STEP_MAX);
2337
2338                 /*
2339                  * Locate the highest numbered rule before default
2340                  */
2341                 for (f = *head; f; f = f->next) {
2342                         if (f->rulenum == IPFW_DEFAULT_RULE)
2343                                 break;
2344                         rule->rulenum = f->rulenum;
2345                 }
2346                 if (rule->rulenum < IPFW_DEFAULT_RULE - step)
2347                         rule->rulenum += step;
2348
2349                 /* Update the input structure */
2350                 ioc_rule->rulenum = rule->rulenum;
2351         }
2352
2353         /*
2354          * Now insert the new rule in the right place in the sorted list.
2355          */
2356         for (prev = NULL, f = *head; f; prev = f, f = f->next) {
2357                 if (f->rulenum > rule->rulenum) {
2358                         /* Found the location */
2359                         if (prev) {
2360                                 rule->next = f;
2361                                 prev->next = rule;
2362                         } else {
2363                                 rule->next = *head;
2364                                 *head = rule;
2365                         }
2366                         break;
2367                 }
2368         }
2369
2370         flush_rule_ptrs();
2371         ipfw_inc_static_count(rule);
2372
2373         crit_exit();
2374
2375         DEB(kprintf("++ installed rule %d, static count now %d\n",
2376                 rule->rulenum, static_count);)
2377 }
2378
2379 /**
2380  * Free storage associated with a static rule (including derived
2381  * dynamic rules).
2382  * The caller is in charge of clearing rule pointers to avoid
2383  * dangling pointers.
2384  * @return a pointer to the next entry.
2385  * Arguments are not checked, so they better be correct.
2386  * Must be called at splimp().
2387  */
2388 static struct ip_fw *
2389 delete_rule(struct ip_fw **head, struct ip_fw *prev, struct ip_fw *rule)
2390 {
2391         struct ip_fw *n;
2392
2393         ++static_gen;
2394
2395         n = rule->next;
2396         remove_dyn_rule(rule, NULL /* force removal */);
2397         if (prev == NULL)
2398                 *head = n;
2399         else
2400                 prev->next = n;
2401         ipfw_dec_static_count(rule);
2402
2403         /* Mark the rule as invalid */
2404         rule->rule_flags |= IPFW_RULE_F_INVALID;
2405         rule->next_rule = NULL;
2406
2407         /* Try to free this rule */
2408         ipfw_free_rule(rule);
2409
2410         return n;
2411 }
2412
2413 /*
2414  * Deletes all rules from a chain (including the default rule
2415  * if the second argument is set).
2416  * Must be called at splimp().
2417  */
2418 static void
2419 free_chain(struct ip_fw **chain, int kill_default)
2420 {
2421         struct ip_fw *rule;
2422
2423         flush_rule_ptrs(); /* more efficient to do outside the loop */
2424
2425         while ((rule = *chain) != NULL &&
2426                (kill_default || rule->rulenum != IPFW_DEFAULT_RULE))
2427                 delete_rule(chain, NULL, rule);
2428
2429         KASSERT(dyn_count == 0, ("%u dyn rule remains\n", dyn_count));
2430
2431         if (kill_default) {
2432                 ip_fw_default_rule = NULL;      /* Reset default rule */
2433
2434                 if (ipfw_dyn_v != NULL) {
2435                         /*
2436                          * Free dynamic rules(state) hash table
2437                          */
2438                         kfree(ipfw_dyn_v, M_IPFW);
2439                         ipfw_dyn_v = NULL;
2440                 }
2441
2442                 KASSERT(static_count == 0,
2443                         ("%u static rules remains\n", static_count));
2444                 KASSERT(static_ioc_len == 0,
2445                         ("%u bytes of static rules remains\n", static_ioc_len));
2446         } else {
2447                 KASSERT(static_count == 1,
2448                         ("%u static rules remains\n", static_count));
2449                 KASSERT(static_ioc_len == IOC_RULESIZE(ip_fw_default_rule),
2450                         ("%u bytes of static rules remains, should be %u\n",
2451                          static_ioc_len, IOC_RULESIZE(ip_fw_default_rule)));
2452         }
2453 }
2454
2455 /**
2456  * Remove all rules with given number, and also do set manipulation.
2457  *
2458  * The argument is an uint32_t. The low 16 bit are the rule or set number,
2459  * the next 8 bits are the new set, the top 8 bits are the command:
2460  *
2461  *      0       delete rules with given number
2462  *      1       delete rules with given set number
2463  *      2       move rules with given number to new set
2464  *      3       move rules with given set number to new set
2465  *      4       swap sets with given numbers
2466  */
2467 static int
2468 del_entry(struct ip_fw **chain, uint32_t arg)
2469 {
2470         struct ip_fw *prev, *rule;
2471         uint16_t rulenum;
2472         uint8_t cmd, new_set;
2473
2474         rulenum = arg & 0xffff;
2475         cmd = (arg >> 24) & 0xff;
2476         new_set = (arg >> 16) & 0xff;
2477
2478         if (cmd > 4)
2479                 return EINVAL;
2480         if (new_set > 30)
2481                 return EINVAL;
2482         if (cmd == 0 || cmd == 2) {
2483                 if (rulenum == IPFW_DEFAULT_RULE)
2484                         return EINVAL;
2485         } else {
2486                 if (rulenum > 30)
2487                         return EINVAL;
2488         }
2489
2490         switch (cmd) {
2491         case 0: /* delete rules with given number */
2492                 /*
2493                  * locate first rule to delete
2494                  */
2495                 for (prev = NULL, rule = *chain;
2496                      rule && rule->rulenum < rulenum;
2497                      prev = rule, rule = rule->next)
2498                         ;
2499                 if (rule->rulenum != rulenum)
2500                         return EINVAL;
2501
2502                 crit_enter(); /* no access to rules while removing */
2503                 /*
2504                  * flush pointers outside the loop, then delete all matching
2505                  * rules. prev remains the same throughout the cycle.
2506                  */
2507                 flush_rule_ptrs();
2508                 while (rule && rule->rulenum == rulenum)
2509                         rule = delete_rule(chain, prev, rule);
2510                 crit_exit();
2511                 break;
2512
2513         case 1: /* delete all rules with given set number */
2514                 crit_enter();
2515                 flush_rule_ptrs();
2516                 for (prev = NULL, rule = *chain; rule;) {
2517                         if (rule->set == rulenum) {
2518                                 rule = delete_rule(chain, prev, rule);
2519                         } else {
2520                                 prev = rule;
2521                                 rule = rule->next;
2522                         }
2523                 }
2524                 crit_exit();
2525                 break;
2526
2527         case 2: /* move rules with given number to new set */
2528                 crit_enter();
2529                 for (rule = *chain; rule; rule = rule->next) {
2530                         if (rule->rulenum == rulenum)
2531                                 rule->set = new_set;
2532                 }
2533                 crit_exit();
2534                 break;
2535
2536         case 3: /* move rules with given set number to new set */
2537                 crit_enter();
2538                 for (rule = *chain; rule; rule = rule->next) {
2539                         if (rule->set == rulenum)
2540                                 rule->set = new_set;
2541                 }
2542                 crit_exit();
2543                 break;
2544
2545         case 4: /* swap two sets */
2546                 crit_enter();
2547                 for (rule = *chain; rule; rule = rule->next) {
2548                         if (rule->set == rulenum)
2549                                 rule->set = new_set;
2550                         else if (rule->set == new_set)
2551                                 rule->set = rulenum;
2552                 }
2553                 crit_exit();
2554                 break;
2555         }
2556         return 0;
2557 }
2558
2559 /*
2560  * Clear counters for a specific rule.
2561  */
2562 static void
2563 clear_counters(struct ip_fw *rule, int log_only)
2564 {
2565         ipfw_insn_log *l = (ipfw_insn_log *)ACTION_PTR(rule);
2566
2567         if (log_only == 0) {
2568                 rule->bcnt = rule->pcnt = 0;
2569                 rule->timestamp = 0;
2570         }
2571         if (l->o.opcode == O_LOG)
2572                 l->log_left = l->max_log;
2573 }
2574
2575 /**
2576  * Reset some or all counters on firewall rules.
2577  * @arg frwl is null to clear all entries, or contains a specific
2578  * rule number.
2579  * @arg log_only is 1 if we only want to reset logs, zero otherwise.
2580  */
2581 static int
2582 zero_entry(int rulenum, int log_only)
2583 {
2584         struct ip_fw *rule;
2585         char *msg;
2586
2587         if (rulenum == 0) {
2588                 crit_enter();
2589                 norule_counter = 0;
2590                 for (rule = layer3_chain; rule; rule = rule->next)
2591                         clear_counters(rule, log_only);
2592                 crit_exit();
2593                 msg = log_only ? "ipfw: All logging counts reset.\n"
2594                                : "ipfw: Accounting cleared.\n";
2595         } else {
2596                 int cleared = 0;
2597
2598                 /*
2599                  * We can have multiple rules with the same number, so we
2600                  * need to clear them all.
2601                  */
2602                 for (rule = layer3_chain; rule; rule = rule->next) {
2603                         if (rule->rulenum == rulenum) {
2604                                 crit_enter();
2605                                 while (rule && rule->rulenum == rulenum) {
2606                                         clear_counters(rule, log_only);
2607                                         rule = rule->next;
2608                                 }
2609                                 crit_exit();
2610                                 cleared = 1;
2611                                 break;
2612                         }
2613                 }
2614                 if (!cleared)   /* we did not find any matching rules */
2615                         return (EINVAL);
2616                 msg = log_only ? "ipfw: Entry %d logging count reset.\n"
2617                                : "ipfw: Entry %d cleared.\n";
2618         }
2619         if (fw_verbose)
2620                 log(LOG_SECURITY | LOG_NOTICE, msg, rulenum);
2621         return (0);
2622 }
2623
2624 /*
2625  * Check validity of the structure before insert.
2626  * Fortunately rules are simple, so this mostly need to check rule sizes.
2627  */
2628 static int
2629 ipfw_ctl_check_rule(struct ipfw_ioc_rule *rule, int size)
2630 {
2631         int l, cmdlen = 0;
2632         int have_action = 0;
2633         ipfw_insn *cmd;
2634
2635         /* Check for valid size */
2636         if (size < sizeof(*rule)) {
2637                 kprintf("ipfw: rule too short\n");
2638                 return EINVAL;
2639         }
2640         l = IOC_RULESIZE(rule);
2641         if (l != size) {
2642                 kprintf("ipfw: size mismatch (have %d want %d)\n", size, l);
2643                 return EINVAL;
2644         }
2645
2646         /*
2647          * Now go for the individual checks. Very simple ones, basically only
2648          * instruction sizes.
2649          */
2650         for (l = rule->cmd_len, cmd = rule->cmd; l > 0;
2651              l -= cmdlen, cmd += cmdlen) {
2652                 cmdlen = F_LEN(cmd);
2653                 if (cmdlen > l) {
2654                         kprintf("ipfw: opcode %d size truncated\n",
2655                                 cmd->opcode);
2656                         return EINVAL;
2657                 }
2658                 DEB(kprintf("ipfw: opcode %d\n", cmd->opcode);)
2659                 switch (cmd->opcode) {
2660                 case O_NOP:
2661                 case O_PROBE_STATE:
2662                 case O_KEEP_STATE:
2663                 case O_PROTO:
2664                 case O_IP_SRC_ME:
2665                 case O_IP_DST_ME:
2666                 case O_LAYER2:
2667                 case O_IN:
2668                 case O_FRAG:
2669                 case O_IPOPT:
2670                 case O_IPLEN:
2671                 case O_IPID:
2672                 case O_IPTOS:
2673                 case O_IPPRECEDENCE:
2674                 case O_IPTTL:
2675                 case O_IPVER:
2676                 case O_TCPWIN:
2677                 case O_TCPFLAGS:
2678                 case O_TCPOPTS:
2679                 case O_ESTAB:
2680                         if (cmdlen != F_INSN_SIZE(ipfw_insn))
2681                                 goto bad_size;
2682                         break;
2683
2684                 case O_UID:
2685                 case O_GID:
2686                 case O_IP_SRC:
2687                 case O_IP_DST:
2688                 case O_TCPSEQ:
2689                 case O_TCPACK:
2690                 case O_PROB:
2691                 case O_ICMPTYPE:
2692                         if (cmdlen != F_INSN_SIZE(ipfw_insn_u32))
2693                                 goto bad_size;
2694                         break;
2695
2696                 case O_LIMIT:
2697                         if (cmdlen != F_INSN_SIZE(ipfw_insn_limit))
2698                                 goto bad_size;
2699                         break;
2700
2701                 case O_LOG:
2702                         if (cmdlen != F_INSN_SIZE(ipfw_insn_log))
2703                                 goto bad_size;
2704
2705                         ((ipfw_insn_log *)cmd)->log_left =
2706                             ((ipfw_insn_log *)cmd)->max_log;
2707
2708                         break;
2709
2710                 case O_IP_SRC_MASK:
2711                 case O_IP_DST_MASK:
2712                         if (cmdlen != F_INSN_SIZE(ipfw_insn_ip))
2713                                 goto bad_size;
2714                         if (((ipfw_insn_ip *)cmd)->mask.s_addr == 0) {
2715                                 kprintf("ipfw: opcode %d, useless rule\n",
2716                                         cmd->opcode);
2717                                 return EINVAL;
2718                         }
2719                         break;
2720
2721                 case O_IP_SRC_SET:
2722                 case O_IP_DST_SET:
2723                         if (cmd->arg1 == 0 || cmd->arg1 > 256) {
2724                                 kprintf("ipfw: invalid set size %d\n",
2725                                         cmd->arg1);
2726                                 return EINVAL;
2727                         }
2728                         if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
2729                             (cmd->arg1+31)/32 )
2730                                 goto bad_size;
2731                         break;
2732
2733                 case O_MACADDR2:
2734                         if (cmdlen != F_INSN_SIZE(ipfw_insn_mac))
2735                                 goto bad_size;
2736                         break;
2737
2738                 case O_MAC_TYPE:
2739                 case O_IP_SRCPORT:
2740                 case O_IP_DSTPORT: /* XXX artificial limit, 30 port pairs */
2741                         if (cmdlen < 2 || cmdlen > 31)
2742                                 goto bad_size;
2743                         break;
2744
2745                 case O_RECV:
2746                 case O_XMIT:
2747                 case O_VIA:
2748                         if (cmdlen != F_INSN_SIZE(ipfw_insn_if))
2749                                 goto bad_size;
2750                         break;
2751
2752                 case O_PIPE:
2753                 case O_QUEUE:
2754                         if (cmdlen != F_INSN_SIZE(ipfw_insn_pipe))
2755                                 goto bad_size;
2756                         goto check_action;
2757
2758                 case O_FORWARD_IP:
2759                         if (cmdlen != F_INSN_SIZE(ipfw_insn_sa))
2760                                 goto bad_size;
2761                         goto check_action;
2762
2763                 case O_FORWARD_MAC: /* XXX not implemented yet */
2764                 case O_CHECK_STATE:
2765                 case O_COUNT:
2766                 case O_ACCEPT:
2767                 case O_DENY:
2768                 case O_REJECT:
2769                 case O_SKIPTO:
2770                 case O_DIVERT:
2771                 case O_TEE:
2772                         if (cmdlen != F_INSN_SIZE(ipfw_insn))
2773                                 goto bad_size;
2774 check_action:
2775                         if (have_action) {
2776                                 kprintf("ipfw: opcode %d, multiple actions"
2777                                         " not allowed\n",
2778                                         cmd->opcode);
2779                                 return EINVAL;
2780                         }
2781                         have_action = 1;
2782                         if (l != cmdlen) {
2783                                 kprintf("ipfw: opcode %d, action must be"
2784                                         " last opcode\n",
2785                                         cmd->opcode);
2786                                 return EINVAL;
2787                         }
2788                         break;
2789                 default:
2790                         kprintf("ipfw: opcode %d, unknown opcode\n",
2791                                 cmd->opcode);
2792                         return EINVAL;
2793                 }
2794         }
2795         if (have_action == 0) {
2796                 kprintf("ipfw: missing action\n");
2797                 return EINVAL;
2798         }
2799         return 0;
2800
2801 bad_size:
2802         kprintf("ipfw: opcode %d size %d wrong\n",
2803                 cmd->opcode, cmdlen);
2804         return EINVAL;
2805 }
2806
2807 static int
2808 ipfw_ctl_add_rule(struct sockopt *sopt)
2809 {
2810         struct ipfw_ioc_rule *ioc_rule;
2811         size_t size;
2812         int error;
2813         
2814         size = sopt->sopt_valsize;
2815         if (size > (sizeof(uint32_t) * IPFW_RULE_SIZE_MAX) ||
2816             size < sizeof(*ioc_rule)) {
2817                 return EINVAL;
2818         }
2819         if (size != (sizeof(uint32_t) * IPFW_RULE_SIZE_MAX)) {
2820                 sopt->sopt_val = krealloc(sopt->sopt_val, sizeof(uint32_t) *
2821                                           IPFW_RULE_SIZE_MAX, M_TEMP, M_WAITOK);
2822         }
2823         ioc_rule = sopt->sopt_val;
2824
2825         error = ipfw_ctl_check_rule(ioc_rule, size);
2826         if (error)
2827                 return error;
2828
2829         ipfw_add_rule(&layer3_chain, ioc_rule);
2830
2831         if (sopt->sopt_dir == SOPT_GET)
2832                 sopt->sopt_valsize = IOC_RULESIZE(ioc_rule);
2833         return 0;
2834 }
2835
2836 static void *
2837 ipfw_copy_rule(const struct ip_fw *rule, struct ipfw_ioc_rule *ioc_rule)
2838 {
2839         ioc_rule->act_ofs = rule->act_ofs;
2840         ioc_rule->cmd_len = rule->cmd_len;
2841         ioc_rule->rulenum = rule->rulenum;
2842         ioc_rule->set = rule->set;
2843         ioc_rule->usr_flags = rule->usr_flags;
2844
2845         ioc_rule->set_disable = set_disable;
2846         ioc_rule->static_count = static_count;
2847         ioc_rule->static_len = static_ioc_len;
2848
2849         ioc_rule->pcnt = rule->pcnt;
2850         ioc_rule->bcnt = rule->bcnt;
2851         ioc_rule->timestamp = rule->timestamp;
2852
2853         bcopy(rule->cmd, ioc_rule->cmd, ioc_rule->cmd_len * 4 /* XXX */);
2854
2855         return ((uint8_t *)ioc_rule + IOC_RULESIZE(ioc_rule));
2856 }
2857
2858 static void
2859 ipfw_copy_state(const ipfw_dyn_rule *dyn_rule,
2860                 struct ipfw_ioc_state *ioc_state)
2861 {
2862         const struct ipfw_flow_id *id;
2863         struct ipfw_ioc_flowid *ioc_id;
2864
2865         ioc_state->expire = TIME_LEQ(dyn_rule->expire, time_second) ?
2866                             0 : dyn_rule->expire - time_second;
2867         ioc_state->pcnt = dyn_rule->pcnt;
2868         ioc_state->bcnt = dyn_rule->bcnt;
2869
2870         ioc_state->dyn_type = dyn_rule->dyn_type;
2871         ioc_state->count = dyn_rule->count;
2872
2873         ioc_state->rulenum = dyn_rule->rule->rulenum;
2874
2875         id = &dyn_rule->id;
2876         ioc_id = &ioc_state->id;
2877
2878         ioc_id->type = ETHERTYPE_IP;
2879         ioc_id->u.ip.dst_ip = id->dst_ip;
2880         ioc_id->u.ip.src_ip = id->src_ip;
2881         ioc_id->u.ip.dst_port = id->dst_port;
2882         ioc_id->u.ip.src_port = id->src_port;
2883         ioc_id->u.ip.proto = id->proto;
2884 }
2885
2886 static int
2887 ipfw_ctl_get_rules(struct sockopt *sopt)
2888 {
2889         struct ip_fw *rule;
2890         void *bp;
2891         size_t size;
2892         uint32_t dcount = 0;
2893
2894         /*
2895          * pass up a copy of the current rules. Static rules
2896          * come first (the last of which has number IPFW_DEFAULT_RULE),
2897          * followed by a possibly empty list of dynamic rule.
2898          */
2899         crit_enter();
2900
2901         size = static_ioc_len;  /* size of static rules */
2902         if (ipfw_dyn_v) {       /* add size of dyn.rules */
2903                 dcount = dyn_count;
2904                 size += dcount * sizeof(struct ipfw_ioc_state);
2905         }
2906
2907         if (sopt->sopt_valsize < size) {
2908                 /* short length, no need to return incomplete rules */
2909                 /* XXX: if superuser, no need to zero buffer */
2910                 bzero(sopt->sopt_val, sopt->sopt_valsize); 
2911                 return 0;
2912         }
2913         bp = sopt->sopt_val;
2914
2915         for (rule = layer3_chain; rule; rule = rule->next)
2916                 bp = ipfw_copy_rule(rule, bp);
2917
2918         if (ipfw_dyn_v && dcount != 0) {
2919                 struct ipfw_ioc_state *ioc_state = bp;
2920                 uint32_t dcount2 = 0;
2921 #ifdef INVARIANTS
2922                 size_t old_size = size;
2923 #endif
2924                 int i;
2925
2926                 lockmgr(&dyn_lock, LK_SHARED);
2927
2928                 /* Check 'ipfw_dyn_v' again with lock held */
2929                 if (ipfw_dyn_v == NULL)
2930                         goto skip;
2931
2932                 for (i = 0; i < curr_dyn_buckets; i++) {
2933                         ipfw_dyn_rule *p;
2934
2935                         /*
2936                          * The # of dynamic rules may have grown after the
2937                          * snapshot of 'dyn_count' was taken, so we will have
2938                          * to check 'dcount' (snapshot of dyn_count) here to
2939                          * make sure that we don't overflow the pre-allocated
2940                          * buffer.
2941                          */
2942                         for (p = ipfw_dyn_v[i]; p != NULL && dcount != 0;
2943                              p = p->next, ioc_state++, dcount--, dcount2++)
2944                                 ipfw_copy_state(p, ioc_state);
2945                 }
2946 skip:
2947                 lockmgr(&dyn_lock, LK_RELEASE);
2948
2949                 /*
2950                  * The # of dynamic rules may be shrinked after the
2951                  * snapshot of 'dyn_count' was taken.  To give user a
2952                  * correct dynamic rule count, we use the 'dcount2'
2953                  * calculated above (with shared lockmgr lock held).
2954                  */
2955                 size = static_ioc_len +
2956                        (dcount2 * sizeof(struct ipfw_ioc_state));
2957                 KKASSERT(size <= old_size);
2958         }
2959
2960         crit_exit();
2961
2962         sopt->sopt_valsize = size;
2963         return 0;
2964 }
2965
2966 /**
2967  * {set|get}sockopt parser.
2968  */
2969 static int
2970 ipfw_ctl(struct sockopt *sopt)
2971 {
2972         int error, rulenum;
2973         uint32_t *masks;
2974         size_t size;
2975
2976         error = 0;
2977
2978         switch (sopt->sopt_name) {
2979         case IP_FW_GET:
2980                 error = ipfw_ctl_get_rules(sopt);
2981                 break;
2982
2983         case IP_FW_FLUSH:
2984                 /*
2985                  * Normally we cannot release the lock on each iteration.
2986                  * We could do it here only because we start from the head all
2987                  * the times so there is no risk of missing some entries.
2988                  * On the other hand, the risk is that we end up with
2989                  * a very inconsistent ruleset, so better keep the lock
2990                  * around the whole cycle.
2991                  *
2992                  * XXX this code can be improved by resetting the head of
2993                  * the list to point to the default rule, and then freeing
2994                  * the old list without the need for a lock.
2995                  */
2996
2997                 crit_enter();
2998                 free_chain(&layer3_chain, 0 /* keep default rule */);
2999                 crit_exit();
3000                 break;
3001
3002         case IP_FW_ADD:
3003                 error = ipfw_ctl_add_rule(sopt);
3004                 break;
3005
3006         case IP_FW_DEL:
3007                 /*
3008                  * IP_FW_DEL is used for deleting single rules or sets,
3009                  * and (ab)used to atomically manipulate sets. Argument size
3010                  * is used to distinguish between the two:
3011                  *    sizeof(uint32_t)
3012                  *      delete single rule or set of rules,
3013                  *      or reassign rules (or sets) to a different set.
3014                  *    2*sizeof(uint32_t)
3015                  *      atomic disable/enable sets.
3016                  *      first uint32_t contains sets to be disabled,
3017                  *      second uint32_t contains sets to be enabled.
3018                  */
3019                 masks = sopt->sopt_val;
3020                 size = sopt->sopt_valsize;
3021                 if (size == sizeof(*masks)) {
3022                         /*
3023                          * Delete or reassign static rule
3024                          */
3025                         error = del_entry(&layer3_chain, masks[0]);
3026                 } else if (size == (2 * sizeof(*masks))) {
3027                         /*
3028                          * Set enable/disable
3029                          */
3030                         crit_enter();
3031
3032                         set_disable =
3033                             (set_disable | masks[0]) & ~masks[1] &
3034                             ~(1 << 31); /* set 31 always enabled */
3035
3036                         crit_exit();
3037                 } else {
3038                         error = EINVAL;
3039                 }
3040                 break;
3041
3042         case IP_FW_ZERO:
3043         case IP_FW_RESETLOG: /* argument is an int, the rule number */
3044                 rulenum=0;
3045
3046                 if (sopt->sopt_val != 0) {
3047                     error = soopt_to_kbuf(sopt, &rulenum,
3048                             sizeof(int), sizeof(int));
3049                     if (error)
3050                         break;
3051                 }
3052                 error = zero_entry(rulenum, sopt->sopt_name == IP_FW_RESETLOG);
3053                 break;
3054
3055         default:
3056                 kprintf("ipfw_ctl invalid option %d\n", sopt->sopt_name);
3057                 error = EINVAL;
3058         }
3059         return error;
3060 }
3061
3062 /*
3063  * This procedure is only used to handle keepalives. It is invoked
3064  * every dyn_keepalive_period
3065  */
3066 static void
3067 ipfw_tick(void *dummy __unused)
3068 {
3069         time_t keep_alive;
3070         uint32_t gen;
3071         int i;
3072
3073         if (ipfw_dyn_v == NULL || dyn_count == 0)
3074                 goto done;
3075
3076         keep_alive = time_second;
3077
3078         lockmgr(&dyn_lock, LK_EXCLUSIVE);
3079 again:
3080         if (ipfw_dyn_v == NULL || dyn_count == 0) {
3081                 lockmgr(&dyn_lock, LK_RELEASE);
3082                 goto done;
3083         }
3084         gen = dyn_buckets_gen;
3085
3086         for (i = 0; i < curr_dyn_buckets; i++) {
3087                 ipfw_dyn_rule *q, *prev;
3088
3089                 for (prev = NULL, q = ipfw_dyn_v[i]; q != NULL;) {
3090                         uint32_t ack_rev, ack_fwd;
3091                         struct ipfw_flow_id id;
3092
3093                         if (q->dyn_type == O_LIMIT_PARENT)
3094                                 goto next;
3095
3096                         if (TIME_LEQ(q->expire, time_second)) {
3097                                 /* State expired */
3098                                 UNLINK_DYN_RULE(prev, ipfw_dyn_v[i], q);
3099                                 continue;
3100                         }
3101
3102                         /*
3103                          * Keep alive processing
3104                          */
3105
3106                         if (!dyn_keepalive)
3107                                 goto next;
3108                         if (q->id.proto != IPPROTO_TCP)
3109                                 goto next;
3110                         if ((q->state & BOTH_SYN) != BOTH_SYN)
3111                                 goto next;
3112                         if (TIME_LEQ(time_second + dyn_keepalive_interval,
3113                             q->expire))
3114                                 goto next;      /* too early */
3115                         if (q->keep_alive == keep_alive)
3116                                 goto next;      /* alreay done */
3117
3118                         /*
3119                          * Save necessary information, so that they could
3120                          * survive after possible blocking in send_pkt()
3121                          */
3122                         id = q->id;
3123                         ack_rev = q->ack_rev;
3124                         ack_fwd = q->ack_fwd;
3125
3126                         /* Sending has been started */
3127                         q->keep_alive = keep_alive;
3128
3129                         /* Release lock to avoid possible dead lock */
3130                         lockmgr(&dyn_lock, LK_RELEASE);
3131                         send_pkt(&id, ack_rev - 1, ack_fwd, TH_SYN);
3132                         send_pkt(&id, ack_fwd - 1, ack_rev, 0);
3133                         lockmgr(&dyn_lock, LK_EXCLUSIVE);
3134
3135                         if (gen != dyn_buckets_gen) {
3136                                 /*
3137                                  * Dyn bucket array has been changed during
3138                                  * the above two sending; reiterate.
3139                                  */
3140                                 goto again;
3141                         }
3142 next:
3143                         prev = q;
3144                         q = q->next;
3145                 }
3146         }
3147         lockmgr(&dyn_lock, LK_RELEASE);
3148 done:
3149         callout_reset(&ipfw_timeout_h, dyn_keepalive_period * hz,
3150                       ipfw_tick, NULL);
3151 }
3152
3153 static void
3154 ipfw_init_default_rule(struct ip_fw **head)
3155 {
3156         struct ip_fw *def_rule;
3157
3158         KKASSERT(*head == NULL);
3159
3160         def_rule = kmalloc(sizeof(*def_rule), M_IPFW, M_WAITOK | M_ZERO);
3161
3162         def_rule->act_ofs = 0;
3163         def_rule->rulenum = IPFW_DEFAULT_RULE;
3164         def_rule->cmd_len = 1;
3165         def_rule->set = 31;
3166
3167         def_rule->cmd[0].len = 1;
3168 #ifdef IPFIREWALL_DEFAULT_TO_ACCEPT
3169         def_rule->cmd[0].opcode = O_ACCEPT;
3170 #else
3171         def_rule->cmd[0].opcode = O_DENY;
3172 #endif
3173
3174         def_rule->refcnt = 1;
3175
3176         *head = def_rule;
3177         ipfw_inc_static_count(def_rule);
3178
3179         /* Install the default rule */
3180         ip_fw_default_rule = def_rule;
3181 }
3182
3183 static int
3184 ipfw_sysctl_autoinc_step(SYSCTL_HANDLER_ARGS)
3185 {
3186         return sysctl_int_range(oidp, arg1, arg2, req,
3187                IPFW_AUTOINC_STEP_MIN, IPFW_AUTOINC_STEP_MAX);
3188 }
3189
3190 static int
3191 ipfw_sysctl_dyn_buckets(SYSCTL_HANDLER_ARGS)
3192 {
3193         int error, value;
3194
3195         lockmgr(&dyn_lock, LK_EXCLUSIVE);
3196
3197         value = dyn_buckets;
3198         error = sysctl_handle_int(oidp, &value, 0, req);
3199         if (error || !req->newptr)
3200                 goto back;
3201
3202         /*
3203          * Make sure we have a power of 2 and
3204          * do not allow more than 64k entries.
3205          */
3206         error = EINVAL;
3207         if (value <= 1 || value > 65536)
3208                 goto back;
3209         if ((value & (value - 1)) != 0)
3210                 goto back;
3211
3212         error = 0;
3213         dyn_buckets = value;
3214 back:
3215         lockmgr(&dyn_lock, LK_RELEASE);
3216         return error;
3217 }
3218
3219 static int
3220 ipfw_sysctl_dyn_fin(SYSCTL_HANDLER_ARGS)
3221 {
3222         return sysctl_int_range(oidp, arg1, arg2, req,
3223                                 1, dyn_keepalive_period - 1);
3224 }
3225
3226 static int
3227 ipfw_sysctl_dyn_rst(SYSCTL_HANDLER_ARGS)
3228 {
3229         return sysctl_int_range(oidp, arg1, arg2, req,
3230                                 1, dyn_keepalive_period - 1);
3231 }
3232
3233 static void
3234 ipfw_init_dispatch(struct netmsg *nmsg)
3235 {
3236         int error = 0;
3237
3238         crit_enter();
3239
3240         if (IPFW_LOADED) {
3241                 kprintf("IP firewall already loaded\n");
3242                 error = EEXIST;
3243                 goto reply;
3244         }
3245
3246         ip_fw_chk_ptr = ipfw_chk;
3247         ip_fw_ctl_ptr = ipfw_ctl;
3248         ip_fw_dn_io_ptr = ipfw_dummynet_io;
3249
3250         layer3_chain = NULL;
3251         ipfw_init_default_rule(&layer3_chain);
3252
3253         kprintf("ipfw2 initialized, divert %s, "
3254                 "rule-based forwarding enabled, default to %s, logging ",
3255 #ifdef IPDIVERT
3256                 "enabled",
3257 #else
3258                 "disabled",
3259 #endif
3260                 ip_fw_default_rule->cmd[0].opcode == O_ACCEPT ?
3261                 "accept" : "deny");
3262
3263 #ifdef IPFIREWALL_VERBOSE
3264         fw_verbose = 1;
3265 #endif
3266 #ifdef IPFIREWALL_VERBOSE_LIMIT
3267         verbose_limit = IPFIREWALL_VERBOSE_LIMIT;
3268 #endif
3269         if (fw_verbose == 0) {
3270                 kprintf("disabled\n");
3271         } else if (verbose_limit == 0) {
3272                 kprintf("unlimited\n");
3273         } else {
3274                 kprintf("limited to %d packets/entry by default\n",
3275                         verbose_limit);
3276         }
3277
3278         callout_init(&ipfw_timeout_h);
3279         lockinit(&dyn_lock, "ipfw_dyn", 0, 0);
3280
3281         ip_fw_loaded = 1;
3282         callout_reset(&ipfw_timeout_h, hz, ipfw_tick, NULL);
3283 reply:
3284         crit_exit();
3285         lwkt_replymsg(&nmsg->nm_lmsg, error);
3286 }
3287
3288 static int
3289 ipfw_init(void)
3290 {
3291         struct netmsg smsg;
3292
3293         netmsg_init(&smsg, &curthread->td_msgport, 0, ipfw_init_dispatch);
3294         return lwkt_domsg(IPFW_CFGPORT, &smsg.nm_lmsg, 0);
3295 }
3296
3297 #ifdef KLD_MODULE
3298
3299 static void
3300 ipfw_fini_dispatch(struct netmsg *nmsg)
3301 {
3302         int error = 0;
3303
3304         crit_enter();
3305
3306         if (ipfw_refcnt != 0) {
3307                 error = EBUSY;
3308                 goto reply;
3309         }
3310
3311         callout_stop(&ipfw_timeout_h);
3312
3313         ip_fw_loaded = 0;
3314         netmsg_service_sync();
3315
3316         ip_fw_chk_ptr = NULL;
3317         ip_fw_ctl_ptr = NULL;
3318         ip_fw_dn_io_ptr = NULL;
3319         free_chain(&layer3_chain, 1 /* kill default rule */);
3320
3321         kprintf("IP firewall unloaded\n");
3322 reply:
3323         crit_exit();
3324         lwkt_replymsg(&nmsg->nm_lmsg, error);
3325 }
3326
3327 static int
3328 ipfw_fini(void)
3329 {
3330         struct netmsg smsg;
3331
3332         netmsg_init(&smsg, &curthread->td_msgport, 0, ipfw_fini_dispatch);
3333         return lwkt_domsg(IPFW_CFGPORT, &smsg.nm_lmsg, 0);
3334 }
3335
3336 #endif  /* KLD_MODULE */
3337
3338 static int
3339 ipfw_modevent(module_t mod, int type, void *unused)
3340 {
3341         int err = 0;
3342
3343         switch (type) {
3344         case MOD_LOAD:
3345                 err = ipfw_init();
3346                 break;
3347
3348         case MOD_UNLOAD:
3349 #ifndef KLD_MODULE
3350                 kprintf("ipfw statically compiled, cannot unload\n");
3351                 err = EBUSY;
3352 #else
3353                 err = ipfw_fini();
3354 #endif
3355                 break;
3356         default:
3357                 break;
3358         }
3359         return err;
3360 }
3361
3362 static moduledata_t ipfwmod = {
3363         "ipfw",
3364         ipfw_modevent,
3365         0
3366 };
3367 DECLARE_MODULE(ipfw, ipfwmod, SI_SUB_PROTO_END, SI_ORDER_ANY);
3368 MODULE_VERSION(ipfw, 1);