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.50 2008/07/30 12:31:51 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 = (struct ifnet *)0;
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          * Assume we are sending a RST (or a keepalive in the reverse
1101          * direction), swap src and destination addresses and ports.
1102          */
1103         ip->ip_src.s_addr = htonl(id->dst_ip);
1104         ip->ip_dst.s_addr = htonl(id->src_ip);
1105         tcp->th_sport = htons(id->dst_port);
1106         tcp->th_dport = htons(id->src_port);
1107         if (flags & TH_RST) {   /* we are sending a RST */
1108                 if (flags & TH_ACK) {
1109                         tcp->th_seq = htonl(ack);
1110                         tcp->th_ack = htonl(0);
1111                         tcp->th_flags = TH_RST;
1112                 } else {
1113                         if (flags & TH_SYN)
1114                                 seq++;
1115                         tcp->th_seq = htonl(0);
1116                         tcp->th_ack = htonl(seq);
1117                         tcp->th_flags = TH_RST | TH_ACK;
1118                 }
1119         } else {
1120                 /*
1121                  * We are sending a keepalive. flags & TH_SYN determines
1122                  * the direction, forward if set, reverse if clear.
1123                  * NOTE: seq and ack are always assumed to be correct
1124                  * as set by the caller. This may be confusing...
1125                  */
1126                 if (flags & TH_SYN) {
1127                         /*
1128                          * we have to rewrite the correct addresses!
1129                          */
1130                         ip->ip_dst.s_addr = htonl(id->dst_ip);
1131                         ip->ip_src.s_addr = htonl(id->src_ip);
1132                         tcp->th_dport = htons(id->dst_port);
1133                         tcp->th_sport = htons(id->src_port);
1134                 }
1135                 tcp->th_seq = htonl(seq);
1136                 tcp->th_ack = htonl(ack);
1137                 tcp->th_flags = TH_ACK;
1138         }
1139         /*
1140          * set ip_len to the payload size so we can compute
1141          * the tcp checksum on the pseudoheader
1142          * XXX check this, could save a couple of words ?
1143          */
1144         ip->ip_len = htons(sizeof(struct tcphdr));
1145         tcp->th_sum = in_cksum(m, m->m_pkthdr.len);
1146         /*
1147          * now fill fields left out earlier
1148          */
1149         ip->ip_ttl = ip_defttl;
1150         ip->ip_len = m->m_pkthdr.len;
1151         bzero (&sro, sizeof (sro));
1152         ip_rtaddr(ip->ip_dst, &sro);
1153         m->m_pkthdr.fw_flags |= IPFW_MBUF_GENERATED;
1154         ip_output(m, NULL, &sro, 0, NULL, NULL);
1155         if (sro.ro_rt)
1156                 RTFREE(sro.ro_rt);
1157 }
1158
1159 /*
1160  * sends a reject message, consuming the mbuf passed as an argument.
1161  */
1162 static void
1163 send_reject(struct ip_fw_args *args, int code, int offset, int ip_len)
1164 {
1165
1166         if (code != ICMP_REJECT_RST) { /* Send an ICMP unreach */
1167                 /* We need the IP header in host order for icmp_error(). */
1168                 if (args->eh != NULL) {
1169                         struct ip *ip = mtod(args->m, struct ip *);
1170                         ip->ip_len = ntohs(ip->ip_len);
1171                         ip->ip_off = ntohs(ip->ip_off);
1172                 }
1173                 icmp_error(args->m, ICMP_UNREACH, code, 0L, 0);
1174         } else if (offset == 0 && args->f_id.proto == IPPROTO_TCP) {
1175                 struct tcphdr *const tcp =
1176                     L3HDR(struct tcphdr, mtod(args->m, struct ip *));
1177                 if ( (tcp->th_flags & TH_RST) == 0)
1178                         send_pkt(&(args->f_id), ntohl(tcp->th_seq),
1179                                 ntohl(tcp->th_ack),
1180                                 tcp->th_flags | TH_RST);
1181                 m_freem(args->m);
1182         } else
1183                 m_freem(args->m);
1184         args->m = NULL;
1185 }
1186
1187 /**
1188  *
1189  * Given an ip_fw *, lookup_next_rule will return a pointer
1190  * to the next rule, which can be either the jump
1191  * target (for skipto instructions) or the next one in the list (in
1192  * all other cases including a missing jump target).
1193  * The result is also written in the "next_rule" field of the rule.
1194  * Backward jumps are not allowed, so start looking from the next
1195  * rule...
1196  *
1197  * This never returns NULL -- in case we do not have an exact match,
1198  * the next rule is returned. When the ruleset is changed,
1199  * pointers are flushed so we are always correct.
1200  */
1201
1202 static struct ip_fw *
1203 lookup_next_rule(struct ip_fw *me)
1204 {
1205         struct ip_fw *rule = NULL;
1206         ipfw_insn *cmd;
1207
1208         /* look for action, in case it is a skipto */
1209         cmd = ACTION_PTR(me);
1210         if (cmd->opcode == O_LOG)
1211                 cmd += F_LEN(cmd);
1212         if ( cmd->opcode == O_SKIPTO )
1213                 for (rule = me->next; rule ; rule = rule->next)
1214                         if (rule->rulenum >= cmd->arg1)
1215                                 break;
1216         if (rule == NULL)                       /* failure or not a skipto */
1217                 rule = me->next;
1218         me->next_rule = rule;
1219         return rule;
1220 }
1221
1222 /*
1223  * The main check routine for the firewall.
1224  *
1225  * All arguments are in args so we can modify them and return them
1226  * back to the caller.
1227  *
1228  * Parameters:
1229  *
1230  *      args->m (in/out) The packet; we set to NULL when/if we nuke it.
1231  *              Starts with the IP header.
1232  *      args->eh (in)   Mac header if present, or NULL for layer3 packet.
1233  *      args->oif       Outgoing interface, or NULL if packet is incoming.
1234  *              The incoming interface is in the mbuf. (in)
1235  *
1236  *      args->rule      Pointer to the last matching rule (in/out)
1237  *      args->next_hop  Socket we are forwarding to (out).
1238  *      args->f_id      Addresses grabbed from the packet (out)
1239  *
1240  * Return value:
1241  *
1242  *      IP_FW_PORT_DENY_FLAG    the packet must be dropped.
1243  *      0       The packet is to be accepted and routed normally OR
1244  *              the packet was denied/rejected and has been dropped;
1245  *              in the latter case, *m is equal to NULL upon return.
1246  *      port    Divert the packet to port, with these caveats:
1247  *
1248  *              - If IP_FW_PORT_TEE_FLAG is set, tee the packet instead
1249  *                of diverting it (ie, 'ipfw tee').
1250  *
1251  *              - If IP_FW_PORT_DYNT_FLAG is set, interpret the lower
1252  *                16 bits as a dummynet pipe number instead of diverting
1253  */
1254
1255 static int
1256 ipfw_chk(struct ip_fw_args *args)
1257 {
1258         /*
1259          * Local variables hold state during the processing of a packet.
1260          *
1261          * IMPORTANT NOTE: to speed up the processing of rules, there
1262          * are some assumption on the values of the variables, which
1263          * are documented here. Should you change them, please check
1264          * the implementation of the various instructions to make sure
1265          * that they still work.
1266          *
1267          * args->eh     The MAC header. It is non-null for a layer2
1268          *      packet, it is NULL for a layer-3 packet.
1269          *
1270          * m | args->m  Pointer to the mbuf, as received from the caller.
1271          *      It may change if ipfw_chk() does an m_pullup, or if it
1272          *      consumes the packet because it calls send_reject().
1273          *      XXX This has to change, so that ipfw_chk() never modifies
1274          *      or consumes the buffer.
1275          * ip   is simply an alias of the value of m, and it is kept
1276          *      in sync with it (the packet is  supposed to start with
1277          *      the ip header).
1278          */
1279         struct mbuf *m = args->m;
1280         struct ip *ip = mtod(m, struct ip *);
1281
1282         /*
1283          * oif | args->oif      If NULL, ipfw_chk has been called on the
1284          *      inbound path (ether_input, ip_input).
1285          *      If non-NULL, ipfw_chk has been called on the outbound path
1286          *      (ether_output, ip_output).
1287          */
1288         struct ifnet *oif = args->oif;
1289
1290         struct ip_fw *f = NULL;         /* matching rule */
1291         int retval = 0;
1292         struct m_tag *mtag;
1293
1294         /*
1295          * hlen The length of the IPv4 header.
1296          *      hlen >0 means we have an IPv4 packet.
1297          */
1298         u_int hlen = 0;         /* hlen >0 means we have an IP pkt */
1299
1300         /*
1301          * offset       The offset of a fragment. offset != 0 means that
1302          *      we have a fragment at this offset of an IPv4 packet.
1303          *      offset == 0 means that (if this is an IPv4 packet)
1304          *      this is the first or only fragment.
1305          */
1306         u_short offset = 0;
1307
1308         /*
1309          * Local copies of addresses. They are only valid if we have
1310          * an IP packet.
1311          *
1312          * proto        The protocol. Set to 0 for non-ip packets,
1313          *      or to the protocol read from the packet otherwise.
1314          *      proto != 0 means that we have an IPv4 packet.
1315          *
1316          * src_port, dst_port   port numbers, in HOST format. Only
1317          *      valid for TCP and UDP packets.
1318          *
1319          * src_ip, dst_ip       ip addresses, in NETWORK format.
1320          *      Only valid for IPv4 packets.
1321          */
1322         uint8_t proto;
1323         uint16_t src_port = 0, dst_port = 0;    /* NOTE: host format    */
1324         struct in_addr src_ip, dst_ip;          /* NOTE: network format */
1325         uint16_t ip_len=0;
1326         int dyn_dir = MATCH_UNKNOWN;
1327         ipfw_dyn_rule *q = NULL;
1328
1329         if (m->m_pkthdr.fw_flags & IPFW_MBUF_GENERATED)
1330                 return 0;       /* accept */
1331         /*
1332          * dyn_dir = MATCH_UNKNOWN when rules unchecked,
1333          *      MATCH_NONE when checked and not matched (q = NULL),
1334          *      MATCH_FORWARD or MATCH_REVERSE otherwise (q != NULL)
1335          */
1336
1337         if (args->eh == NULL ||         /* layer 3 packet */
1338                 ( m->m_pkthdr.len >= sizeof(struct ip) &&
1339                     ntohs(args->eh->ether_type) == ETHERTYPE_IP))
1340                         hlen = ip->ip_hl << 2;
1341
1342         /*
1343          * Collect parameters into local variables for faster matching.
1344          */
1345         if (hlen == 0) {        /* do not grab addresses for non-ip pkts */
1346                 proto = args->f_id.proto = 0;   /* mark f_id invalid */
1347                 goto after_ip_checks;
1348         }
1349
1350         proto = args->f_id.proto = ip->ip_p;
1351         src_ip = ip->ip_src;
1352         dst_ip = ip->ip_dst;
1353         if (args->eh != NULL) { /* layer 2 packets are as on the wire */
1354                 offset = ntohs(ip->ip_off) & IP_OFFMASK;
1355                 ip_len = ntohs(ip->ip_len);
1356         } else {
1357                 offset = ip->ip_off & IP_OFFMASK;
1358                 ip_len = ip->ip_len;
1359         }
1360
1361 #define PULLUP_TO(len)                                          \
1362                 do {                                            \
1363                         if ((m)->m_len < (len)) {               \
1364                             args->m = m = m_pullup(m, (len));   \
1365                             if (m == 0)                         \
1366                                 goto pullup_failed;             \
1367                             ip = mtod(m, struct ip *);          \
1368                         }                                       \
1369                 } while (0)
1370
1371         if (offset == 0) {
1372                 switch (proto) {
1373                 case IPPROTO_TCP:
1374                     {
1375                         struct tcphdr *tcp;
1376
1377                         PULLUP_TO(hlen + sizeof(struct tcphdr));
1378                         tcp = L3HDR(struct tcphdr, ip);
1379                         dst_port = tcp->th_dport;
1380                         src_port = tcp->th_sport;
1381                         args->f_id.flags = tcp->th_flags;
1382                         }
1383                         break;
1384
1385                 case IPPROTO_UDP:
1386                     {
1387                         struct udphdr *udp;
1388
1389                         PULLUP_TO(hlen + sizeof(struct udphdr));
1390                         udp = L3HDR(struct udphdr, ip);
1391                         dst_port = udp->uh_dport;
1392                         src_port = udp->uh_sport;
1393                         }
1394                         break;
1395
1396                 case IPPROTO_ICMP:
1397                         PULLUP_TO(hlen + 4);    /* type, code and checksum. */
1398                         args->f_id.flags = L3HDR(struct icmp, ip)->icmp_type;
1399                         break;
1400
1401                 default:
1402                         break;
1403                 }
1404 #undef PULLUP_TO
1405         }
1406
1407         args->f_id.src_ip = ntohl(src_ip.s_addr);
1408         args->f_id.dst_ip = ntohl(dst_ip.s_addr);
1409         args->f_id.src_port = src_port = ntohs(src_port);
1410         args->f_id.dst_port = dst_port = ntohs(dst_port);
1411
1412 after_ip_checks:
1413         if (args->rule) {
1414                 /*
1415                  * Packet has already been tagged. Look for the next rule
1416                  * to restart processing.
1417                  *
1418                  * If fw_one_pass != 0 then just accept it.
1419                  * XXX should not happen here, but optimized out in
1420                  * the caller.
1421                  */
1422                 if (fw_one_pass)
1423                         return 0;
1424
1425                 /* This rule was deleted */
1426                 if (args->rule->rule_flags & IPFW_RULE_F_INVALID)
1427                         return IP_FW_PORT_DENY_FLAG;
1428
1429                 f = args->rule->next_rule;
1430                 if (f == NULL)
1431                         f = lookup_next_rule(args->rule);
1432         } else {
1433                 /*
1434                  * Find the starting rule. It can be either the first
1435                  * one, or the one after divert_rule if asked so.
1436                  */
1437                 int skipto;
1438
1439                 mtag = m_tag_find(m, PACKET_TAG_IPFW_DIVERT, NULL);
1440                 if (mtag != NULL)
1441                         skipto = *(uint16_t *)m_tag_data(mtag);
1442                 else
1443                         skipto = 0;
1444
1445                 f = layer3_chain;
1446                 if (args->eh == NULL && skipto != 0) {
1447                         if (skipto >= IPFW_DEFAULT_RULE)
1448                                 return(IP_FW_PORT_DENY_FLAG); /* invalid */
1449                         while (f && f->rulenum <= skipto)
1450                                 f = f->next;
1451                         if (f == NULL)  /* drop packet */
1452                                 return(IP_FW_PORT_DENY_FLAG);
1453                 }
1454         }
1455         if ((mtag = m_tag_find(m, PACKET_TAG_IPFW_DIVERT, NULL)) != NULL)
1456                 m_tag_delete(m, mtag);
1457
1458         /*
1459          * Now scan the rules, and parse microinstructions for each rule.
1460          */
1461         for (; f; f = f->next) {
1462                 int l, cmdlen;
1463                 ipfw_insn *cmd;
1464                 int skip_or; /* skip rest of OR block */
1465
1466 again:
1467                 if (set_disable & (1 << f->set) )
1468                         continue;
1469
1470                 skip_or = 0;
1471                 for (l = f->cmd_len, cmd = f->cmd ; l > 0 ;
1472                     l -= cmdlen, cmd += cmdlen) {
1473                         int match;
1474
1475                         /*
1476                          * check_body is a jump target used when we find a
1477                          * CHECK_STATE, and need to jump to the body of
1478                          * the target rule.
1479                          */
1480
1481 check_body:
1482                         cmdlen = F_LEN(cmd);
1483                         /*
1484                          * An OR block (insn_1 || .. || insn_n) has the
1485                          * F_OR bit set in all but the last instruction.
1486                          * The first match will set "skip_or", and cause
1487                          * the following instructions to be skipped until
1488                          * past the one with the F_OR bit clear.
1489                          */
1490                         if (skip_or) {          /* skip this instruction */
1491                                 if ((cmd->len & F_OR) == 0)
1492                                         skip_or = 0;    /* next one is good */
1493                                 continue;
1494                         }
1495                         match = 0; /* set to 1 if we succeed */
1496
1497                         switch (cmd->opcode) {
1498                         /*
1499                          * The first set of opcodes compares the packet's
1500                          * fields with some pattern, setting 'match' if a
1501                          * match is found. At the end of the loop there is
1502                          * logic to deal with F_NOT and F_OR flags associated
1503                          * with the opcode.
1504                          */
1505                         case O_NOP:
1506                                 match = 1;
1507                                 break;
1508
1509                         case O_FORWARD_MAC:
1510                                 kprintf("ipfw: opcode %d unimplemented\n",
1511                                     cmd->opcode);
1512                                 break;
1513
1514                         case O_GID:
1515                         case O_UID:
1516                                 /*
1517                                  * We only check offset == 0 && proto != 0,
1518                                  * as this ensures that we have an IPv4
1519                                  * packet with the ports info.
1520                                  */
1521                                 if (offset!=0)
1522                                         break;
1523                             {
1524                                 struct inpcbinfo *pi;
1525                                 int wildcard;
1526                                 struct inpcb *pcb;
1527
1528                                 if (proto == IPPROTO_TCP) {
1529                                         wildcard = 0;
1530                                         pi = &tcbinfo[mycpu->gd_cpuid];
1531                                 } else if (proto == IPPROTO_UDP) {
1532                                         wildcard = 1;
1533                                         pi = &udbinfo;
1534                                 } else
1535                                         break;
1536
1537                                 pcb =  (oif) ?
1538                                         in_pcblookup_hash(pi,
1539                                             dst_ip, htons(dst_port),
1540                                             src_ip, htons(src_port),
1541                                             wildcard, oif) :
1542                                         in_pcblookup_hash(pi,
1543                                             src_ip, htons(src_port),
1544                                             dst_ip, htons(dst_port),
1545                                             wildcard, NULL);
1546
1547                                 if (pcb == NULL || pcb->inp_socket == NULL)
1548                                         break;
1549 #if defined(__DragonFly__) || (defined(__FreeBSD__) && __FreeBSD_version < 500034)
1550 #define socheckuid(a,b) ((a)->so_cred->cr_uid != (b))
1551 #endif
1552                                 if (cmd->opcode == O_UID) {
1553                                         match =
1554                                           !socheckuid(pcb->inp_socket,
1555                                            (uid_t)((ipfw_insn_u32 *)cmd)->d[0]);
1556                                 } else  {
1557                                         match = groupmember(
1558                                             (uid_t)((ipfw_insn_u32 *)cmd)->d[0],
1559                                             pcb->inp_socket->so_cred);
1560                                 }
1561                             }
1562                                 break;
1563
1564                         case O_RECV:
1565                                 match = iface_match(m->m_pkthdr.rcvif,
1566                                     (ipfw_insn_if *)cmd);
1567                                 break;
1568
1569                         case O_XMIT:
1570                                 match = iface_match(oif, (ipfw_insn_if *)cmd);
1571                                 break;
1572
1573                         case O_VIA:
1574                                 match = iface_match(oif ? oif :
1575                                     m->m_pkthdr.rcvif, (ipfw_insn_if *)cmd);
1576                                 break;
1577
1578                         case O_MACADDR2:
1579                                 if (args->eh != NULL) { /* have MAC header */
1580                                         uint32_t *want = (uint32_t *)
1581                                                 ((ipfw_insn_mac *)cmd)->addr;
1582                                         uint32_t *mask = (uint32_t *)
1583                                                 ((ipfw_insn_mac *)cmd)->mask;
1584                                         uint32_t *hdr = (uint32_t *)args->eh;
1585
1586                                         match =
1587                                             ( want[0] == (hdr[0] & mask[0]) &&
1588                                               want[1] == (hdr[1] & mask[1]) &&
1589                                               want[2] == (hdr[2] & mask[2]) );
1590                                 }
1591                                 break;
1592
1593                         case O_MAC_TYPE:
1594                                 if (args->eh != NULL) {
1595                                         uint16_t t =
1596                                             ntohs(args->eh->ether_type);
1597                                         uint16_t *p =
1598                                             ((ipfw_insn_u16 *)cmd)->ports;
1599                                         int i;
1600
1601                                         /* Special vlan handling */
1602                                         if (m->m_flags & M_VLANTAG)
1603                                                 t = ETHERTYPE_VLAN;
1604
1605                                         for (i = cmdlen - 1; !match && i>0;
1606                                             i--, p += 2)
1607                                                 match = (t>=p[0] && t<=p[1]);
1608                                 }
1609                                 break;
1610
1611                         case O_FRAG:
1612                                 match = (hlen > 0 && offset != 0);
1613                                 break;
1614
1615                         case O_IN:      /* "out" is "not in" */
1616                                 match = (oif == NULL);
1617                                 break;
1618
1619                         case O_LAYER2:
1620                                 match = (args->eh != NULL);
1621                                 break;
1622
1623                         case O_PROTO:
1624                                 /*
1625                                  * We do not allow an arg of 0 so the
1626                                  * check of "proto" only suffices.
1627                                  */
1628                                 match = (proto == cmd->arg1);
1629                                 break;
1630
1631                         case O_IP_SRC:
1632                                 match = (hlen > 0 &&
1633                                     ((ipfw_insn_ip *)cmd)->addr.s_addr ==
1634                                     src_ip.s_addr);
1635                                 break;
1636
1637                         case O_IP_SRC_MASK:
1638                                 match = (hlen > 0 &&
1639                                     ((ipfw_insn_ip *)cmd)->addr.s_addr ==
1640                                      (src_ip.s_addr &
1641                                      ((ipfw_insn_ip *)cmd)->mask.s_addr));
1642                                 break;
1643
1644                         case O_IP_SRC_ME:
1645                                 if (hlen > 0) {
1646                                         struct ifnet *tif;
1647
1648                                         tif = INADDR_TO_IFP(&src_ip);
1649                                         match = (tif != NULL);
1650                                 }
1651                                 break;
1652
1653                         case O_IP_DST_SET:
1654                         case O_IP_SRC_SET:
1655                                 if (hlen > 0) {
1656                                         uint32_t *d = (uint32_t *)(cmd+1);
1657                                         uint32_t addr =
1658                                             cmd->opcode == O_IP_DST_SET ?
1659                                                 args->f_id.dst_ip :
1660                                                 args->f_id.src_ip;
1661
1662                                             if (addr < d[0])
1663                                                     break;
1664                                             addr -= d[0]; /* subtract base */
1665                                             match = (addr < cmd->arg1) &&
1666                                                 ( d[ 1 + (addr>>5)] &
1667                                                   (1<<(addr & 0x1f)) );
1668                                 }
1669                                 break;
1670
1671                         case O_IP_DST:
1672                                 match = (hlen > 0 &&
1673                                     ((ipfw_insn_ip *)cmd)->addr.s_addr ==
1674                                     dst_ip.s_addr);
1675                                 break;
1676
1677                         case O_IP_DST_MASK:
1678                                 match = (hlen > 0) &&
1679                                     (((ipfw_insn_ip *)cmd)->addr.s_addr ==
1680                                      (dst_ip.s_addr &
1681                                      ((ipfw_insn_ip *)cmd)->mask.s_addr));
1682                                 break;
1683
1684                         case O_IP_DST_ME:
1685                                 if (hlen > 0) {
1686                                         struct ifnet *tif;
1687
1688                                         tif = INADDR_TO_IFP(&dst_ip);
1689                                         match = (tif != NULL);
1690                                 }
1691                                 break;
1692
1693                         case O_IP_SRCPORT:
1694                         case O_IP_DSTPORT:
1695                                 /*
1696                                  * offset == 0 && proto != 0 is enough
1697                                  * to guarantee that we have an IPv4
1698                                  * packet with port info.
1699                                  */
1700                                 if ((proto==IPPROTO_UDP || proto==IPPROTO_TCP)
1701                                     && offset == 0) {
1702                                         uint16_t x =
1703                                             (cmd->opcode == O_IP_SRCPORT) ?
1704                                                 src_port : dst_port ;
1705                                         uint16_t *p =
1706                                             ((ipfw_insn_u16 *)cmd)->ports;
1707                                         int i;
1708
1709                                         for (i = cmdlen - 1; !match && i>0;
1710                                             i--, p += 2)
1711                                                 match = (x>=p[0] && x<=p[1]);
1712                                 }
1713                                 break;
1714
1715                         case O_ICMPTYPE:
1716                                 match = (offset == 0 && proto==IPPROTO_ICMP &&
1717                                     icmptype_match(ip, (ipfw_insn_u32 *)cmd) );
1718                                 break;
1719
1720                         case O_IPOPT:
1721                                 match = (hlen > 0 && ipopts_match(ip, cmd) );
1722                                 break;
1723
1724                         case O_IPVER:
1725                                 match = (hlen > 0 && cmd->arg1 == ip->ip_v);
1726                                 break;
1727
1728                         case O_IPTTL:
1729                                 match = (hlen > 0 && cmd->arg1 == ip->ip_ttl);
1730                                 break;
1731
1732                         case O_IPID:
1733                                 match = (hlen > 0 &&
1734                                     cmd->arg1 == ntohs(ip->ip_id));
1735                                 break;
1736
1737                         case O_IPLEN:
1738                                 match = (hlen > 0 && cmd->arg1 == ip_len);
1739                                 break;
1740
1741                         case O_IPPRECEDENCE:
1742                                 match = (hlen > 0 &&
1743                                     (cmd->arg1 == (ip->ip_tos & 0xe0)) );
1744                                 break;
1745
1746                         case O_IPTOS:
1747                                 match = (hlen > 0 &&
1748                                     flags_match(cmd, ip->ip_tos));
1749                                 break;
1750
1751                         case O_TCPFLAGS:
1752                                 match = (proto == IPPROTO_TCP && offset == 0 &&
1753                                     flags_match(cmd,
1754                                         L3HDR(struct tcphdr,ip)->th_flags));
1755                                 break;
1756
1757                         case O_TCPOPTS:
1758                                 match = (proto == IPPROTO_TCP && offset == 0 &&
1759                                     tcpopts_match(ip, cmd));
1760                                 break;
1761
1762                         case O_TCPSEQ:
1763                                 match = (proto == IPPROTO_TCP && offset == 0 &&
1764                                     ((ipfw_insn_u32 *)cmd)->d[0] ==
1765                                         L3HDR(struct tcphdr,ip)->th_seq);
1766                                 break;
1767
1768                         case O_TCPACK:
1769                                 match = (proto == IPPROTO_TCP && offset == 0 &&
1770                                     ((ipfw_insn_u32 *)cmd)->d[0] ==
1771                                         L3HDR(struct tcphdr,ip)->th_ack);
1772                                 break;
1773
1774                         case O_TCPWIN:
1775                                 match = (proto == IPPROTO_TCP && offset == 0 &&
1776                                     cmd->arg1 ==
1777                                         L3HDR(struct tcphdr,ip)->th_win);
1778                                 break;
1779
1780                         case O_ESTAB:
1781                                 /* reject packets which have SYN only */
1782                                 /* XXX should i also check for TH_ACK ? */
1783                                 match = (proto == IPPROTO_TCP && offset == 0 &&
1784                                     (L3HDR(struct tcphdr,ip)->th_flags &
1785                                      (TH_RST | TH_ACK | TH_SYN)) != TH_SYN);
1786                                 break;
1787
1788                         case O_LOG:
1789                                 if (fw_verbose)
1790                                         ipfw_log(f, hlen, args->eh, m, oif);
1791                                 match = 1;
1792                                 break;
1793
1794                         case O_PROB:
1795                                 match = (krandom() <
1796                                         ((ipfw_insn_u32 *)cmd)->d[0]);
1797                                 break;
1798
1799                         /*
1800                          * The second set of opcodes represents 'actions',
1801                          * i.e. the terminal part of a rule once the packet
1802                          * matches all previous patterns.
1803                          * Typically there is only one action for each rule,
1804                          * and the opcode is stored at the end of the rule
1805                          * (but there are exceptions -- see below).
1806                          *
1807                          * In general, here we set retval and terminate the
1808                          * outer loop (would be a 'break 3' in some language,
1809                          * but we need to do a 'goto done').
1810                          *
1811                          * Exceptions:
1812                          * O_COUNT and O_SKIPTO actions:
1813                          *   instead of terminating, we jump to the next rule
1814                          *   ('goto next_rule', equivalent to a 'break 2'),
1815                          *   or to the SKIPTO target ('goto again' after
1816                          *   having set f, cmd and l), respectively.
1817                          *
1818                          * O_LIMIT and O_KEEP_STATE: these opcodes are
1819                          *   not real 'actions', and are stored right
1820                          *   before the 'action' part of the rule.
1821                          *   These opcodes try to install an entry in the
1822                          *   state tables; if successful, we continue with
1823                          *   the next opcode (match=1; break;), otherwise
1824                          *   the packet *   must be dropped
1825                          *   ('goto done' after setting retval);
1826                          *
1827                          * O_PROBE_STATE and O_CHECK_STATE: these opcodes
1828                          *   cause a lookup of the state table, and a jump
1829                          *   to the 'action' part of the parent rule
1830                          *   ('goto check_body') if an entry is found, or
1831                          *   (CHECK_STATE only) a jump to the next rule if
1832                          *   the entry is not found ('goto next_rule').
1833                          *   The result of the lookup is cached to make
1834                          *   further instances of these opcodes are
1835                          *   effectively NOPs.
1836                          */
1837                         case O_LIMIT:
1838                         case O_KEEP_STATE:
1839                                 if (install_state(f,
1840                                     (ipfw_insn_limit *)cmd, args)) {
1841                                         retval = IP_FW_PORT_DENY_FLAG;
1842                                         goto done; /* error/limit violation */
1843                                 }
1844                                 match = 1;
1845                                 break;
1846
1847                         case O_PROBE_STATE:
1848                         case O_CHECK_STATE:
1849                                 /*
1850                                  * dynamic rules are checked at the first
1851                                  * keep-state or check-state occurrence,
1852                                  * with the result being stored in dyn_dir.
1853                                  * The compiler introduces a PROBE_STATE
1854                                  * instruction for us when we have a
1855                                  * KEEP_STATE (because PROBE_STATE needs
1856                                  * to be run first).
1857                                  */
1858                                 if (dyn_dir == MATCH_UNKNOWN &&
1859                                     (q = lookup_dyn_rule(&args->f_id,
1860                                      &dyn_dir, proto == IPPROTO_TCP ?
1861                                         L3HDR(struct tcphdr, ip) : NULL))
1862                                         != NULL) {
1863                                         /*
1864                                          * Found dynamic entry, update stats
1865                                          * and jump to the 'action' part of
1866                                          * the parent rule.
1867                                          */
1868                                         q->pcnt++;
1869                                         q->bcnt += ip_len;
1870                                         f = q->rule;
1871                                         cmd = ACTION_PTR(f);
1872                                         l = f->cmd_len - f->act_ofs;
1873                                         goto check_body;
1874                                 }
1875                                 /*
1876                                  * Dynamic entry not found. If CHECK_STATE,
1877                                  * skip to next rule, if PROBE_STATE just
1878                                  * ignore and continue with next opcode.
1879                                  */
1880                                 if (cmd->opcode == O_CHECK_STATE)
1881                                         goto next_rule;
1882                                 match = 1;
1883                                 break;
1884
1885                         case O_ACCEPT:
1886                                 retval = 0;     /* accept */
1887                                 goto done;
1888
1889                         case O_PIPE:
1890                         case O_QUEUE:
1891                                 args->rule = f; /* report matching rule */
1892                                 retval = cmd->arg1 | IP_FW_PORT_DYNT_FLAG;
1893                                 goto done;
1894
1895                         case O_DIVERT:
1896                         case O_TEE:
1897                                 if (args->eh) /* not on layer 2 */
1898                                         break;
1899
1900                                 mtag = m_tag_get(PACKET_TAG_IPFW_DIVERT,
1901                                                  sizeof(uint16_t), MB_DONTWAIT);
1902                                 if (mtag == NULL) {
1903                                         retval = IP_FW_PORT_DENY_FLAG;
1904                                         goto done;
1905                                 }
1906                                 *(uint16_t *)m_tag_data(mtag) = f->rulenum;
1907                                 m_tag_prepend(m, mtag);
1908                                 retval = (cmd->opcode == O_DIVERT) ?
1909                                     cmd->arg1 :
1910                                     cmd->arg1 | IP_FW_PORT_TEE_FLAG;
1911                                 goto done;
1912
1913                         case O_COUNT:
1914                         case O_SKIPTO:
1915                                 f->pcnt++;      /* update stats */
1916                                 f->bcnt += ip_len;
1917                                 f->timestamp = time_second;
1918                                 if (cmd->opcode == O_COUNT)
1919                                         goto next_rule;
1920                                 /* handle skipto */
1921                                 if (f->next_rule == NULL)
1922                                         lookup_next_rule(f);
1923                                 f = f->next_rule;
1924                                 goto again;
1925
1926                         case O_REJECT:
1927                                 /*
1928                                  * Drop the packet and send a reject notice
1929                                  * if the packet is not ICMP (or is an ICMP
1930                                  * query), and it is not multicast/broadcast.
1931                                  */
1932                                 if (hlen > 0 &&
1933                                     (proto != IPPROTO_ICMP ||
1934                                      is_icmp_query(ip)) &&
1935                                     !(m->m_flags & (M_BCAST|M_MCAST)) &&
1936                                     !IN_MULTICAST(ntohl(dst_ip.s_addr))) {
1937                                         send_reject(args, cmd->arg1,
1938                                             offset,ip_len);
1939                                         m = args->m;
1940                                 }
1941                                 /* FALLTHROUGH */
1942                         case O_DENY:
1943                                 retval = IP_FW_PORT_DENY_FLAG;
1944                                 goto done;
1945
1946                         case O_FORWARD_IP:
1947                                 if (args->eh)   /* not valid on layer2 pkts */
1948                                         break;
1949                                 if (!q || dyn_dir == MATCH_FORWARD)
1950                                         args->next_hop =
1951                                             &((ipfw_insn_sa *)cmd)->sa;
1952                                 retval = 0;
1953                                 goto done;
1954
1955                         default:
1956                                 panic("-- unknown opcode %d\n", cmd->opcode);
1957                         } /* end of switch() on opcodes */
1958
1959                         if (cmd->len & F_NOT)
1960                                 match = !match;
1961
1962                         if (match) {
1963                                 if (cmd->len & F_OR)
1964                                         skip_or = 1;
1965                         } else {
1966                                 if (!(cmd->len & F_OR)) /* not an OR block, */
1967                                         break;          /* try next rule    */
1968                         }
1969
1970                 }       /* end of inner for, scan opcodes */
1971
1972 next_rule:;             /* try next rule                */
1973
1974         }               /* end of outer for, scan rules */
1975         kprintf("+++ ipfw: ouch!, skip past end of rules, denying packet\n");
1976         return(IP_FW_PORT_DENY_FLAG);
1977
1978 done:
1979         /* Update statistics */
1980         f->pcnt++;
1981         f->bcnt += ip_len;
1982         f->timestamp = time_second;
1983         return retval;
1984
1985 pullup_failed:
1986         if (fw_verbose)
1987                 kprintf("pullup failed\n");
1988         return(IP_FW_PORT_DENY_FLAG);
1989 }
1990
1991 static void
1992 ipfw_dummynet_io(struct mbuf *m, int pipe_nr, int dir, struct ip_fw_args *fwa)
1993 {
1994         struct m_tag *mtag;
1995         struct dn_pkt *pkt;
1996         ipfw_insn *cmd;
1997         const struct ipfw_flow_id *id;
1998         struct dn_flow_id *fid;
1999
2000         M_ASSERTPKTHDR(m);
2001
2002         mtag = m_tag_get(PACKET_TAG_DUMMYNET, sizeof(*pkt), MB_DONTWAIT);
2003         if (mtag == NULL) {
2004                 m_freem(m);
2005                 return;
2006         }
2007         m_tag_prepend(m, mtag);
2008
2009         pkt = m_tag_data(mtag);
2010         bzero(pkt, sizeof(*pkt));
2011
2012         cmd = fwa->rule->cmd + fwa->rule->act_ofs;
2013         if (cmd->opcode == O_LOG)
2014                 cmd += F_LEN(cmd);
2015         KASSERT(cmd->opcode == O_PIPE || cmd->opcode == O_QUEUE,
2016                 ("Rule is not PIPE or QUEUE, opcode %d\n", cmd->opcode));
2017
2018         pkt->dn_m = m;
2019         pkt->dn_flags = (dir & DN_FLAGS_DIR_MASK);
2020         pkt->ifp = fwa->oif;
2021         pkt->cpuid = mycpu->gd_cpuid;
2022         pkt->pipe_nr = pipe_nr;
2023
2024         id = &fwa->f_id;
2025         fid = &pkt->id;
2026         fid->fid_dst_ip = id->dst_ip;
2027         fid->fid_src_ip = id->src_ip;
2028         fid->fid_dst_port = id->dst_port;
2029         fid->fid_src_port = id->src_port;
2030         fid->fid_proto = id->proto;
2031         fid->fid_flags = id->flags;
2032
2033         ipfw_ref_rule(fwa->rule);
2034         pkt->dn_priv = fwa->rule;
2035         pkt->dn_unref_priv = ipfw_unref_rule;
2036
2037         if (cmd->opcode == O_PIPE)
2038                 pkt->dn_flags |= DN_FLAGS_IS_PIPE;
2039
2040         if (dir == DN_TO_IP_OUT) {
2041                 /*
2042                  * We need to copy *ro because for ICMP pkts (and maybe
2043                  * others) the caller passed a pointer into the stack;
2044                  * dst might also be a pointer into *ro so it needs to
2045                  * be updated.
2046                  */
2047                 pkt->ro = *(fwa->ro);
2048                 if (fwa->ro->ro_rt)
2049                         fwa->ro->ro_rt->rt_refcnt++;
2050                 if (fwa->dst == (struct sockaddr_in *)&fwa->ro->ro_dst) {
2051                         /* 'dst' points into 'ro' */
2052                         fwa->dst = (struct sockaddr_in *)&(pkt->ro.ro_dst);
2053                 }
2054                 pkt->dn_dst = fwa->dst;
2055                 pkt->flags = fwa->flags;
2056         }
2057
2058         m->m_pkthdr.fw_flags |= DUMMYNET_MBUF_TAGGED;
2059         ip_dn_queue(m);
2060 }
2061
2062 /*
2063  * When a rule is added/deleted, clear the next_rule pointers in all rules.
2064  * These will be reconstructed on the fly as packets are matched.
2065  * Must be called at splimp().
2066  */
2067 static void
2068 flush_rule_ptrs(void)
2069 {
2070         struct ip_fw *rule;
2071
2072         for (rule = layer3_chain; rule; rule = rule->next)
2073                 rule->next_rule = NULL;
2074 }
2075
2076 static __inline void
2077 ipfw_inc_static_count(struct ip_fw *rule)
2078 {
2079         static_count++;
2080         static_ioc_len += IOC_RULESIZE(rule);
2081 }
2082
2083 static __inline void
2084 ipfw_dec_static_count(struct ip_fw *rule)
2085 {
2086         int l = IOC_RULESIZE(rule);
2087
2088         KASSERT(static_count > 0, ("invalid static count %u\n", static_count));
2089         static_count--;
2090
2091         KASSERT(static_ioc_len >= l,
2092                 ("invalid static len %u\n", static_ioc_len));
2093         static_ioc_len -= l;
2094 }
2095
2096 static struct ip_fw *
2097 ipfw_create_rule(const struct ipfw_ioc_rule *ioc_rule)
2098 {
2099         struct ip_fw *rule;
2100
2101         rule = kmalloc(RULESIZE(ioc_rule), M_IPFW, M_WAITOK | M_ZERO);
2102
2103         rule->act_ofs = ioc_rule->act_ofs;
2104         rule->cmd_len = ioc_rule->cmd_len;
2105         rule->rulenum = ioc_rule->rulenum;
2106         rule->set = ioc_rule->set;
2107         rule->usr_flags = ioc_rule->usr_flags;
2108
2109         bcopy(ioc_rule->cmd, rule->cmd, rule->cmd_len * 4 /* XXX */);
2110
2111         rule->refcnt = 1;
2112
2113         return rule;
2114 }
2115
2116 /*
2117  * Add a new rule to the list. Copy the rule into a malloc'ed area, then
2118  * possibly create a rule number and add the rule to the list.
2119  * Update the rule_number in the input struct so the caller knows it as well.
2120  */
2121 static int
2122 ipfw_add_rule(struct ip_fw **head, struct ipfw_ioc_rule *ioc_rule)
2123 {
2124         struct ip_fw *rule, *f, *prev;
2125
2126         KKASSERT(*head != NULL);
2127
2128         rule = ipfw_create_rule(ioc_rule);
2129
2130         crit_enter();
2131
2132         /*
2133          * If rulenum is 0, find highest numbered rule before the
2134          * default rule, and add autoinc_step
2135          */
2136         if (autoinc_step < 1)
2137                 autoinc_step = 1;
2138         else if (autoinc_step > 1000)
2139                 autoinc_step = 1000;
2140         if (rule->rulenum == 0) {
2141                 /*
2142                  * locate the highest numbered rule before default
2143                  */
2144                 for (f = *head; f; f = f->next) {
2145                         if (f->rulenum == IPFW_DEFAULT_RULE)
2146                                 break;
2147                         rule->rulenum = f->rulenum;
2148                 }
2149                 if (rule->rulenum < IPFW_DEFAULT_RULE - autoinc_step)
2150                         rule->rulenum += autoinc_step;
2151                 ioc_rule->rulenum = rule->rulenum;
2152         }
2153
2154         /*
2155          * Now insert the new rule in the right place in the sorted list.
2156          */
2157         for (prev = NULL, f = *head; f; prev = f, f = f->next) {
2158                 if (f->rulenum > rule->rulenum) { /* found the location */
2159                         if (prev) {
2160                                 rule->next = f;
2161                                 prev->next = rule;
2162                         } else { /* head insert */
2163                                 rule->next = *head;
2164                                 *head = rule;
2165                         }
2166                         break;
2167                 }
2168         }
2169
2170         flush_rule_ptrs();
2171         ipfw_inc_static_count(rule);
2172
2173         crit_exit();
2174
2175         DEB(kprintf("++ installed rule %d, static count now %d\n",
2176                 rule->rulenum, static_count);)
2177         return (0);
2178 }
2179
2180 /**
2181  * Free storage associated with a static rule (including derived
2182  * dynamic rules).
2183  * The caller is in charge of clearing rule pointers to avoid
2184  * dangling pointers.
2185  * @return a pointer to the next entry.
2186  * Arguments are not checked, so they better be correct.
2187  * Must be called at splimp().
2188  */
2189 static struct ip_fw *
2190 delete_rule(struct ip_fw **head, struct ip_fw *prev, struct ip_fw *rule)
2191 {
2192         struct ip_fw *n;
2193
2194         n = rule->next;
2195         remove_dyn_rule(rule, NULL /* force removal */);
2196         if (prev == NULL)
2197                 *head = n;
2198         else
2199                 prev->next = n;
2200         ipfw_dec_static_count(rule);
2201
2202         /* Mark the rule as invalid */
2203         rule->rule_flags |= IPFW_RULE_F_INVALID;
2204         rule->next_rule = NULL;
2205
2206         /* Try to free this rule */
2207         ipfw_free_rule(rule);
2208
2209         return n;
2210 }
2211
2212 /*
2213  * Deletes all rules from a chain (including the default rule
2214  * if the second argument is set).
2215  * Must be called at splimp().
2216  */
2217 static void
2218 free_chain(struct ip_fw **chain, int kill_default)
2219 {
2220         struct ip_fw *rule;
2221
2222         flush_rule_ptrs(); /* more efficient to do outside the loop */
2223
2224         while ((rule = *chain) != NULL &&
2225                (kill_default || rule->rulenum != IPFW_DEFAULT_RULE))
2226                 delete_rule(chain, NULL, rule);
2227
2228         KASSERT(dyn_count == 0, ("%u dyn rule remains\n", dyn_count));
2229
2230         if (kill_default) {
2231                 ip_fw_default_rule = NULL;      /* Reset default rule */
2232
2233                 if (ipfw_dyn_v != NULL) {
2234                         /*
2235                          * Free dynamic rules(state) hash table
2236                          */
2237                         kfree(ipfw_dyn_v, M_IPFW);
2238                         ipfw_dyn_v = NULL;
2239                 }
2240
2241                 KASSERT(static_count == 0,
2242                         ("%u static rules remains\n", static_count));
2243                 KASSERT(static_ioc_len == 0,
2244                         ("%u bytes of static rules remains\n", static_ioc_len));
2245         } else {
2246                 KASSERT(static_count == 1,
2247                         ("%u static rules remains\n", static_count));
2248                 KASSERT(static_ioc_len == IOC_RULESIZE(ip_fw_default_rule),
2249                         ("%u bytes of static rules remains, should be %u\n",
2250                          static_ioc_len, IOC_RULESIZE(ip_fw_default_rule)));
2251         }
2252 }
2253
2254 /**
2255  * Remove all rules with given number, and also do set manipulation.
2256  *
2257  * The argument is an uint32_t. The low 16 bit are the rule or set number,
2258  * the next 8 bits are the new set, the top 8 bits are the command:
2259  *
2260  *      0       delete rules with given number
2261  *      1       delete rules with given set number
2262  *      2       move rules with given number to new set
2263  *      3       move rules with given set number to new set
2264  *      4       swap sets with given numbers
2265  */
2266 static int
2267 del_entry(struct ip_fw **chain, uint32_t arg)
2268 {
2269         struct ip_fw *prev, *rule;
2270         uint16_t rulenum;
2271         uint8_t cmd, new_set;
2272
2273         rulenum = arg & 0xffff;
2274         cmd = (arg >> 24) & 0xff;
2275         new_set = (arg >> 16) & 0xff;
2276
2277         if (cmd > 4)
2278                 return EINVAL;
2279         if (new_set > 30)
2280                 return EINVAL;
2281         if (cmd == 0 || cmd == 2) {
2282                 if (rulenum == IPFW_DEFAULT_RULE)
2283                         return EINVAL;
2284         } else {
2285                 if (rulenum > 30)
2286                         return EINVAL;
2287         }
2288
2289         switch (cmd) {
2290         case 0: /* delete rules with given number */
2291                 /*
2292                  * locate first rule to delete
2293                  */
2294                 for (prev = NULL, rule = *chain;
2295                      rule && rule->rulenum < rulenum;
2296                      prev = rule, rule = rule->next)
2297                         ;
2298                 if (rule->rulenum != rulenum)
2299                         return EINVAL;
2300
2301                 crit_enter(); /* no access to rules while removing */
2302                 /*
2303                  * flush pointers outside the loop, then delete all matching
2304                  * rules. prev remains the same throughout the cycle.
2305                  */
2306                 flush_rule_ptrs();
2307                 while (rule && rule->rulenum == rulenum)
2308                         rule = delete_rule(chain, prev, rule);
2309                 crit_exit();
2310                 break;
2311
2312         case 1: /* delete all rules with given set number */
2313                 crit_enter();
2314                 flush_rule_ptrs();
2315                 for (prev = NULL, rule = *chain; rule;) {
2316                         if (rule->set == rulenum) {
2317                                 rule = delete_rule(chain, prev, rule);
2318                         } else {
2319                                 prev = rule;
2320                                 rule = rule->next;
2321                         }
2322                 }
2323                 crit_exit();
2324                 break;
2325
2326         case 2: /* move rules with given number to new set */
2327                 crit_enter();
2328                 for (rule = *chain; rule; rule = rule->next) {
2329                         if (rule->rulenum == rulenum)
2330                                 rule->set = new_set;
2331                 }
2332                 crit_exit();
2333                 break;
2334
2335         case 3: /* move rules with given set number to new set */
2336                 crit_enter();
2337                 for (rule = *chain; rule; rule = rule->next) {
2338                         if (rule->set == rulenum)
2339                                 rule->set = new_set;
2340                 }
2341                 crit_exit();
2342                 break;
2343
2344         case 4: /* swap two sets */
2345                 crit_enter();
2346                 for (rule = *chain; rule; rule = rule->next) {
2347                         if (rule->set == rulenum)
2348                                 rule->set = new_set;
2349                         else if (rule->set == new_set)
2350                                 rule->set = rulenum;
2351                 }
2352                 crit_exit();
2353                 break;
2354         }
2355         return 0;
2356 }
2357
2358 /*
2359  * Clear counters for a specific rule.
2360  */
2361 static void
2362 clear_counters(struct ip_fw *rule, int log_only)
2363 {
2364         ipfw_insn_log *l = (ipfw_insn_log *)ACTION_PTR(rule);
2365
2366         if (log_only == 0) {
2367                 rule->bcnt = rule->pcnt = 0;
2368                 rule->timestamp = 0;
2369         }
2370         if (l->o.opcode == O_LOG)
2371                 l->log_left = l->max_log;
2372 }
2373
2374 /**
2375  * Reset some or all counters on firewall rules.
2376  * @arg frwl is null to clear all entries, or contains a specific
2377  * rule number.
2378  * @arg log_only is 1 if we only want to reset logs, zero otherwise.
2379  */
2380 static int
2381 zero_entry(int rulenum, int log_only)
2382 {
2383         struct ip_fw *rule;
2384         char *msg;
2385
2386         if (rulenum == 0) {
2387                 crit_enter();
2388                 norule_counter = 0;
2389                 for (rule = layer3_chain; rule; rule = rule->next)
2390                         clear_counters(rule, log_only);
2391                 crit_exit();
2392                 msg = log_only ? "ipfw: All logging counts reset.\n"
2393                                : "ipfw: Accounting cleared.\n";
2394         } else {
2395                 int cleared = 0;
2396
2397                 /*
2398                  * We can have multiple rules with the same number, so we
2399                  * need to clear them all.
2400                  */
2401                 for (rule = layer3_chain; rule; rule = rule->next) {
2402                         if (rule->rulenum == rulenum) {
2403                                 crit_enter();
2404                                 while (rule && rule->rulenum == rulenum) {
2405                                         clear_counters(rule, log_only);
2406                                         rule = rule->next;
2407                                 }
2408                                 crit_exit();
2409                                 cleared = 1;
2410                                 break;
2411                         }
2412                 }
2413                 if (!cleared)   /* we did not find any matching rules */
2414                         return (EINVAL);
2415                 msg = log_only ? "ipfw: Entry %d logging count reset.\n"
2416                                : "ipfw: Entry %d cleared.\n";
2417         }
2418         if (fw_verbose)
2419                 log(LOG_SECURITY | LOG_NOTICE, msg, rulenum);
2420         return (0);
2421 }
2422
2423 /*
2424  * Check validity of the structure before insert.
2425  * Fortunately rules are simple, so this mostly need to check rule sizes.
2426  */
2427 static int
2428 ipfw_ctl_check_rule(struct ipfw_ioc_rule *rule, int size)
2429 {
2430         int l, cmdlen = 0;
2431         int have_action = 0;
2432         ipfw_insn *cmd;
2433
2434         /* Check for valid size */
2435         if (size < sizeof(*rule)) {
2436                 kprintf("ipfw: rule too short\n");
2437                 return EINVAL;
2438         }
2439         l = IOC_RULESIZE(rule);
2440         if (l != size) {
2441                 kprintf("ipfw: size mismatch (have %d want %d)\n", size, l);
2442                 return EINVAL;
2443         }
2444
2445         /*
2446          * Now go for the individual checks. Very simple ones, basically only
2447          * instruction sizes.
2448          */
2449         for (l = rule->cmd_len, cmd = rule->cmd; l > 0;
2450              l -= cmdlen, cmd += cmdlen) {
2451                 cmdlen = F_LEN(cmd);
2452                 if (cmdlen > l) {
2453                         kprintf("ipfw: opcode %d size truncated\n",
2454                                 cmd->opcode);
2455                         return EINVAL;
2456                 }
2457                 DEB(kprintf("ipfw: opcode %d\n", cmd->opcode);)
2458                 switch (cmd->opcode) {
2459                 case O_NOP:
2460                 case O_PROBE_STATE:
2461                 case O_KEEP_STATE:
2462                 case O_PROTO:
2463                 case O_IP_SRC_ME:
2464                 case O_IP_DST_ME:
2465                 case O_LAYER2:
2466                 case O_IN:
2467                 case O_FRAG:
2468                 case O_IPOPT:
2469                 case O_IPLEN:
2470                 case O_IPID:
2471                 case O_IPTOS:
2472                 case O_IPPRECEDENCE:
2473                 case O_IPTTL:
2474                 case O_IPVER:
2475                 case O_TCPWIN:
2476                 case O_TCPFLAGS:
2477                 case O_TCPOPTS:
2478                 case O_ESTAB:
2479                         if (cmdlen != F_INSN_SIZE(ipfw_insn))
2480                                 goto bad_size;
2481                         break;
2482
2483                 case O_UID:
2484                 case O_GID:
2485                 case O_IP_SRC:
2486                 case O_IP_DST:
2487                 case O_TCPSEQ:
2488                 case O_TCPACK:
2489                 case O_PROB:
2490                 case O_ICMPTYPE:
2491                         if (cmdlen != F_INSN_SIZE(ipfw_insn_u32))
2492                                 goto bad_size;
2493                         break;
2494
2495                 case O_LIMIT:
2496                         if (cmdlen != F_INSN_SIZE(ipfw_insn_limit))
2497                                 goto bad_size;
2498                         break;
2499
2500                 case O_LOG:
2501                         if (cmdlen != F_INSN_SIZE(ipfw_insn_log))
2502                                 goto bad_size;
2503
2504                         ((ipfw_insn_log *)cmd)->log_left =
2505                             ((ipfw_insn_log *)cmd)->max_log;
2506
2507                         break;
2508
2509                 case O_IP_SRC_MASK:
2510                 case O_IP_DST_MASK:
2511                         if (cmdlen != F_INSN_SIZE(ipfw_insn_ip))
2512                                 goto bad_size;
2513                         if (((ipfw_insn_ip *)cmd)->mask.s_addr == 0) {
2514                                 kprintf("ipfw: opcode %d, useless rule\n",
2515                                         cmd->opcode);
2516                                 return EINVAL;
2517                         }
2518                         break;
2519
2520                 case O_IP_SRC_SET:
2521                 case O_IP_DST_SET:
2522                         if (cmd->arg1 == 0 || cmd->arg1 > 256) {
2523                                 kprintf("ipfw: invalid set size %d\n",
2524                                         cmd->arg1);
2525                                 return EINVAL;
2526                         }
2527                         if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
2528                             (cmd->arg1+31)/32 )
2529                                 goto bad_size;
2530                         break;
2531
2532                 case O_MACADDR2:
2533                         if (cmdlen != F_INSN_SIZE(ipfw_insn_mac))
2534                                 goto bad_size;
2535                         break;
2536
2537                 case O_MAC_TYPE:
2538                 case O_IP_SRCPORT:
2539                 case O_IP_DSTPORT: /* XXX artificial limit, 30 port pairs */
2540                         if (cmdlen < 2 || cmdlen > 31)
2541                                 goto bad_size;
2542                         break;
2543
2544                 case O_RECV:
2545                 case O_XMIT:
2546                 case O_VIA:
2547                         if (cmdlen != F_INSN_SIZE(ipfw_insn_if))
2548                                 goto bad_size;
2549                         break;
2550
2551                 case O_PIPE:
2552                 case O_QUEUE:
2553                         if (cmdlen != F_INSN_SIZE(ipfw_insn_pipe))
2554                                 goto bad_size;
2555                         goto check_action;
2556
2557                 case O_FORWARD_IP:
2558                         if (cmdlen != F_INSN_SIZE(ipfw_insn_sa))
2559                                 goto bad_size;
2560                         goto check_action;
2561
2562                 case O_FORWARD_MAC: /* XXX not implemented yet */
2563                 case O_CHECK_STATE:
2564                 case O_COUNT:
2565                 case O_ACCEPT:
2566                 case O_DENY:
2567                 case O_REJECT:
2568                 case O_SKIPTO:
2569                 case O_DIVERT:
2570                 case O_TEE:
2571                         if (cmdlen != F_INSN_SIZE(ipfw_insn))
2572                                 goto bad_size;
2573 check_action:
2574                         if (have_action) {
2575                                 kprintf("ipfw: opcode %d, multiple actions"
2576                                         " not allowed\n",
2577                                         cmd->opcode);
2578                                 return EINVAL;
2579                         }
2580                         have_action = 1;
2581                         if (l != cmdlen) {
2582                                 kprintf("ipfw: opcode %d, action must be"
2583                                         " last opcode\n",
2584                                         cmd->opcode);
2585                                 return EINVAL;
2586                         }
2587                         break;
2588                 default:
2589                         kprintf("ipfw: opcode %d, unknown opcode\n",
2590                                 cmd->opcode);
2591                         return EINVAL;
2592                 }
2593         }
2594         if (have_action == 0) {
2595                 kprintf("ipfw: missing action\n");
2596                 return EINVAL;
2597         }
2598         return 0;
2599
2600 bad_size:
2601         kprintf("ipfw: opcode %d size %d wrong\n",
2602                 cmd->opcode, cmdlen);
2603         return EINVAL;
2604 }
2605
2606 static int
2607 ipfw_ctl_add_rule(struct sockopt *sopt)
2608 {
2609         struct ipfw_ioc_rule *ioc_rule;
2610         size_t size;
2611         int error;
2612         
2613         size = sopt->sopt_valsize;
2614         if (size > (sizeof(uint32_t) * IPFW_RULE_SIZE_MAX) ||
2615             size < sizeof(*ioc_rule)) {
2616                 return EINVAL;
2617         }
2618         if (size != (sizeof(uint32_t) * IPFW_RULE_SIZE_MAX)) {
2619                 sopt->sopt_val = krealloc(sopt->sopt_val, sizeof(uint32_t) *
2620                                           IPFW_RULE_SIZE_MAX, M_TEMP, M_WAITOK);
2621         }
2622         ioc_rule = sopt->sopt_val;
2623
2624         error = ipfw_ctl_check_rule(ioc_rule, size);
2625         if (error)
2626                 return error;
2627
2628         error = ipfw_add_rule(&layer3_chain, ioc_rule);
2629         if (error)
2630                 return error;
2631
2632         if (sopt->sopt_dir == SOPT_GET)
2633                 sopt->sopt_valsize = IOC_RULESIZE(ioc_rule);
2634         return 0;
2635 }
2636
2637 static void *
2638 ipfw_copy_rule(const struct ip_fw *rule, struct ipfw_ioc_rule *ioc_rule)
2639 {
2640         ioc_rule->act_ofs = rule->act_ofs;
2641         ioc_rule->cmd_len = rule->cmd_len;
2642         ioc_rule->rulenum = rule->rulenum;
2643         ioc_rule->set = rule->set;
2644         ioc_rule->usr_flags = rule->usr_flags;
2645
2646         ioc_rule->set_disable = set_disable;
2647         ioc_rule->static_count = static_count;
2648         ioc_rule->static_len = static_ioc_len;
2649
2650         ioc_rule->pcnt = rule->pcnt;
2651         ioc_rule->bcnt = rule->bcnt;
2652         ioc_rule->timestamp = rule->timestamp;
2653
2654         bcopy(rule->cmd, ioc_rule->cmd, ioc_rule->cmd_len * 4 /* XXX */);
2655
2656         return ((uint8_t *)ioc_rule + IOC_RULESIZE(ioc_rule));
2657 }
2658
2659 static void
2660 ipfw_copy_state(const ipfw_dyn_rule *dyn_rule,
2661                 struct ipfw_ioc_state *ioc_state)
2662 {
2663         const struct ipfw_flow_id *id;
2664         struct ipfw_ioc_flowid *ioc_id;
2665
2666         ioc_state->expire = TIME_LEQ(dyn_rule->expire, time_second) ?
2667                             0 : dyn_rule->expire - time_second;
2668         ioc_state->pcnt = dyn_rule->pcnt;
2669         ioc_state->bcnt = dyn_rule->bcnt;
2670
2671         ioc_state->dyn_type = dyn_rule->dyn_type;
2672         ioc_state->count = dyn_rule->count;
2673
2674         ioc_state->rulenum = dyn_rule->rule->rulenum;
2675
2676         id = &dyn_rule->id;
2677         ioc_id = &ioc_state->id;
2678
2679         ioc_id->type = ETHERTYPE_IP;
2680         ioc_id->u.ip.dst_ip = id->dst_ip;
2681         ioc_id->u.ip.src_ip = id->src_ip;
2682         ioc_id->u.ip.dst_port = id->dst_port;
2683         ioc_id->u.ip.src_port = id->src_port;
2684         ioc_id->u.ip.proto = id->proto;
2685 }
2686
2687 static int
2688 ipfw_ctl_get_rules(struct sockopt *sopt)
2689 {
2690         struct ip_fw *rule;
2691         void *bp;
2692         size_t size;
2693
2694         /*
2695          * pass up a copy of the current rules. Static rules
2696          * come first (the last of which has number IPFW_DEFAULT_RULE),
2697          * followed by a possibly empty list of dynamic rule.
2698          */
2699         crit_enter();
2700
2701         size = static_ioc_len;  /* size of static rules */
2702         if (ipfw_dyn_v)         /* add size of dyn.rules */
2703                 size += (dyn_count * sizeof(struct ipfw_ioc_state));
2704
2705         if (sopt->sopt_valsize < size) {
2706                 /* short length, no need to return incomplete rules */
2707                 /* XXX: if superuser, no need to zero buffer */
2708                 bzero(sopt->sopt_val, sopt->sopt_valsize); 
2709                 return 0;
2710         }
2711         bp = sopt->sopt_val;
2712
2713         for (rule = layer3_chain; rule; rule = rule->next)
2714                 bp = ipfw_copy_rule(rule, bp);
2715
2716         if (ipfw_dyn_v) {
2717                 struct ipfw_ioc_state *ioc_state;
2718                 int i;
2719
2720                 ioc_state = bp;
2721                 for (i = 0; i < curr_dyn_buckets; i++) {
2722                         ipfw_dyn_rule *p;
2723
2724                         for (p = ipfw_dyn_v[i]; p != NULL;
2725                              p = p->next, ioc_state++)
2726                                 ipfw_copy_state(p, ioc_state);
2727                 }
2728         }
2729
2730         crit_exit();
2731
2732         sopt->sopt_valsize = size;
2733         return 0;
2734 }
2735
2736 /**
2737  * {set|get}sockopt parser.
2738  */
2739 static int
2740 ipfw_ctl(struct sockopt *sopt)
2741 {
2742         int error, rulenum;
2743         uint32_t *masks;
2744         size_t size;
2745
2746         error = 0;
2747
2748         switch (sopt->sopt_name) {
2749         case IP_FW_GET:
2750                 error = ipfw_ctl_get_rules(sopt);
2751                 break;
2752
2753         case IP_FW_FLUSH:
2754                 /*
2755                  * Normally we cannot release the lock on each iteration.
2756                  * We could do it here only because we start from the head all
2757                  * the times so there is no risk of missing some entries.
2758                  * On the other hand, the risk is that we end up with
2759                  * a very inconsistent ruleset, so better keep the lock
2760                  * around the whole cycle.
2761                  *
2762                  * XXX this code can be improved by resetting the head of
2763                  * the list to point to the default rule, and then freeing
2764                  * the old list without the need for a lock.
2765                  */
2766
2767                 crit_enter();
2768                 free_chain(&layer3_chain, 0 /* keep default rule */);
2769                 crit_exit();
2770                 break;
2771
2772         case IP_FW_ADD:
2773                 error = ipfw_ctl_add_rule(sopt);
2774                 break;
2775
2776         case IP_FW_DEL:
2777                 /*
2778                  * IP_FW_DEL is used for deleting single rules or sets,
2779                  * and (ab)used to atomically manipulate sets. Argument size
2780                  * is used to distinguish between the two:
2781                  *    sizeof(uint32_t)
2782                  *      delete single rule or set of rules,
2783                  *      or reassign rules (or sets) to a different set.
2784                  *    2*sizeof(uint32_t)
2785                  *      atomic disable/enable sets.
2786                  *      first uint32_t contains sets to be disabled,
2787                  *      second uint32_t contains sets to be enabled.
2788                  */
2789                 masks = sopt->sopt_val;
2790                 size = sopt->sopt_valsize;
2791                 if (size == sizeof(*masks)) {
2792                         /*
2793                          * Delete or reassign static rule
2794                          */
2795                         error = del_entry(&layer3_chain, masks[0]);
2796                 } else if (size == (2 * sizeof(*masks))) {
2797                         /*
2798                          * Set enable/disable
2799                          */
2800                         crit_enter();
2801
2802                         set_disable =
2803                             (set_disable | masks[0]) & ~masks[1] &
2804                             ~(1 << 31); /* set 31 always enabled */
2805
2806                         crit_exit();
2807                 } else {
2808                         error = EINVAL;
2809                 }
2810                 break;
2811
2812         case IP_FW_ZERO:
2813         case IP_FW_RESETLOG: /* argument is an int, the rule number */
2814                 rulenum=0;
2815
2816                 if (sopt->sopt_val != 0) {
2817                     error = soopt_to_kbuf(sopt, &rulenum,
2818                             sizeof(int), sizeof(int));
2819                     if (error)
2820                         break;
2821                 }
2822                 error = zero_entry(rulenum, sopt->sopt_name == IP_FW_RESETLOG);
2823                 break;
2824
2825         default:
2826                 kprintf("ipfw_ctl invalid option %d\n", sopt->sopt_name);
2827                 error = EINVAL;
2828         }
2829         return error;
2830 }
2831
2832 /*
2833  * This procedure is only used to handle keepalives. It is invoked
2834  * every dyn_keepalive_period
2835  */
2836 static void
2837 ipfw_tick(void * __unused unused)
2838 {
2839         int i;
2840         ipfw_dyn_rule *q;
2841
2842         if (dyn_keepalive == 0 || ipfw_dyn_v == NULL || dyn_count == 0)
2843                 goto done;
2844
2845         crit_enter();
2846         for (i = 0 ; i < curr_dyn_buckets ; i++) {
2847                 for (q = ipfw_dyn_v[i] ; q ; q = q->next ) {
2848                         if (q->dyn_type == O_LIMIT_PARENT)
2849                                 continue;
2850                         if (q->id.proto != IPPROTO_TCP)
2851                                 continue;
2852                         if ( (q->state & BOTH_SYN) != BOTH_SYN)
2853                                 continue;
2854                         if (TIME_LEQ( time_second+dyn_keepalive_interval,
2855                             q->expire))
2856                                 continue;       /* too early */
2857                         if (TIME_LEQ(q->expire, time_second))
2858                                 continue;       /* too late, rule expired */
2859
2860                         send_pkt(&(q->id), q->ack_rev - 1, q->ack_fwd, TH_SYN);
2861                         send_pkt(&(q->id), q->ack_fwd - 1, q->ack_rev, 0);
2862                 }
2863         }
2864         crit_exit();
2865 done:
2866         callout_reset(&ipfw_timeout_h, dyn_keepalive_period * hz,
2867                       ipfw_tick, NULL);
2868 }
2869
2870 static void
2871 ipfw_init_default_rule(struct ip_fw **head)
2872 {
2873         struct ip_fw *def_rule;
2874
2875         KKASSERT(*head == NULL);
2876
2877         def_rule = kmalloc(sizeof(*def_rule), M_IPFW, M_WAITOK | M_ZERO);
2878
2879         def_rule->act_ofs = 0;
2880         def_rule->rulenum = IPFW_DEFAULT_RULE;
2881         def_rule->cmd_len = 1;
2882         def_rule->set = 31;
2883
2884         def_rule->cmd[0].len = 1;
2885 #ifdef IPFIREWALL_DEFAULT_TO_ACCEPT
2886         def_rule->cmd[0].opcode = O_ACCEPT;
2887 #else
2888         def_rule->cmd[0].opcode = O_DENY;
2889 #endif
2890
2891         def_rule->refcnt = 1;
2892
2893         *head = def_rule;
2894         ipfw_inc_static_count(def_rule);
2895
2896         /* Install the default rule */
2897         ip_fw_default_rule = def_rule;
2898 }
2899
2900 static void
2901 ipfw_init_dispatch(struct netmsg *nmsg)
2902 {
2903         int error = 0;
2904
2905         crit_enter();
2906
2907         if (IPFW_LOADED) {
2908                 kprintf("IP firewall already loaded\n");
2909                 error = EEXIST;
2910                 goto reply;
2911         }
2912
2913         ip_fw_chk_ptr = ipfw_chk;
2914         ip_fw_ctl_ptr = ipfw_ctl;
2915         ip_fw_dn_io_ptr = ipfw_dummynet_io;
2916
2917         layer3_chain = NULL;
2918         ipfw_init_default_rule(&layer3_chain);
2919
2920         kprintf("ipfw2 initialized, divert %s, "
2921                 "rule-based forwarding enabled, default to %s, logging ",
2922 #ifdef IPDIVERT
2923                 "enabled",
2924 #else
2925                 "disabled",
2926 #endif
2927                 ip_fw_default_rule->cmd[0].opcode == O_ACCEPT ?
2928                 "accept" : "deny");
2929
2930 #ifdef IPFIREWALL_VERBOSE
2931         fw_verbose = 1;
2932 #endif
2933 #ifdef IPFIREWALL_VERBOSE_LIMIT
2934         verbose_limit = IPFIREWALL_VERBOSE_LIMIT;
2935 #endif
2936         if (fw_verbose == 0) {
2937                 kprintf("disabled\n");
2938         } else if (verbose_limit == 0) {
2939                 kprintf("unlimited\n");
2940         } else {
2941                 kprintf("limited to %d packets/entry by default\n",
2942                         verbose_limit);
2943         }
2944         callout_init(&ipfw_timeout_h);
2945
2946         ip_fw_loaded = 1;
2947         callout_reset(&ipfw_timeout_h, hz, ipfw_tick, NULL);
2948 reply:
2949         crit_exit();
2950         lwkt_replymsg(&nmsg->nm_lmsg, error);
2951 }
2952
2953 static int
2954 ipfw_init(void)
2955 {
2956         struct netmsg smsg;
2957
2958         netmsg_init(&smsg, &curthread->td_msgport, 0, ipfw_init_dispatch);
2959         return lwkt_domsg(cpu_portfn(0), &smsg.nm_lmsg, 0);
2960 }
2961
2962 #ifdef KLD_MODULE
2963
2964 static void
2965 ipfw_fini_dispatch(struct netmsg *nmsg)
2966 {
2967         int error = 0;
2968
2969         crit_enter();
2970
2971         if (ipfw_refcnt != 0) {
2972                 error = EBUSY;
2973                 goto reply;
2974         }
2975
2976         callout_stop(&ipfw_timeout_h);
2977
2978         ip_fw_loaded = 0;
2979         netmsg_service_sync();
2980
2981         ip_fw_chk_ptr = NULL;
2982         ip_fw_ctl_ptr = NULL;
2983         ip_fw_dn_io_ptr = NULL;
2984         free_chain(&layer3_chain, 1 /* kill default rule */);
2985
2986         kprintf("IP firewall unloaded\n");
2987 reply:
2988         crit_exit();
2989         lwkt_replymsg(&nmsg->nm_lmsg, error);
2990 }
2991
2992 static int
2993 ipfw_fini(void)
2994 {
2995         struct netmsg smsg;
2996
2997         netmsg_init(&smsg, &curthread->td_msgport, 0, ipfw_fini_dispatch);
2998         return lwkt_domsg(cpu_portfn(0), &smsg.nm_lmsg, 0);
2999 }
3000
3001 #endif  /* KLD_MODULE */
3002
3003 static int
3004 ipfw_modevent(module_t mod, int type, void *unused)
3005 {
3006         int err = 0;
3007
3008         switch (type) {
3009         case MOD_LOAD:
3010                 err = ipfw_init();
3011                 break;
3012
3013         case MOD_UNLOAD:
3014 #ifndef KLD_MODULE
3015                 kprintf("ipfw statically compiled, cannot unload\n");
3016                 err = EBUSY;
3017 #else
3018                 err = ipfw_fini();
3019 #endif
3020                 break;
3021         default:
3022                 break;
3023         }
3024         return err;
3025 }
3026
3027 static moduledata_t ipfwmod = {
3028         "ipfw",
3029         ipfw_modevent,
3030         0
3031 };
3032 DECLARE_MODULE(ipfw, ipfwmod, SI_SUB_PROTO_END, SI_ORDER_ANY);
3033 MODULE_VERSION(ipfw, 1);