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