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