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