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