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