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