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