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