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