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