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