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