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