]> CyberLeo.Net >> Repos - FreeBSD/releng/7.2.git/blob - sys/netinet/ip_fw2.c
Create releng/7.2 from stable/7 in preparation for 7.2-RELEASE.
[FreeBSD/releng/7.2.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
26 #include <sys/cdefs.h>
27 __FBSDID("$FreeBSD$");
28
29 #define        DEB(x)
30 #define        DDB(x) x
31
32 /*
33  * Implement IP packet firewall (new version)
34  */
35
36 #if !defined(KLD_MODULE)
37 #include "opt_ipfw.h"
38 #include "opt_ipdivert.h"
39 #include "opt_ipdn.h"
40 #include "opt_inet.h"
41 #ifndef INET
42 #error IPFIREWALL requires INET.
43 #endif /* INET */
44 #endif
45 #include "opt_inet6.h"
46 #include "opt_ipsec.h"
47 #include "opt_mac.h"
48
49 #include <sys/param.h>
50 #include <sys/systm.h>
51 #include <sys/malloc.h>
52 #include <sys/mbuf.h>
53 #include <sys/kernel.h>
54 #include <sys/lock.h>
55 #include <sys/jail.h>
56 #include <sys/module.h>
57 #include <sys/priv.h>
58 #include <sys/proc.h>
59 #include <sys/socket.h>
60 #include <sys/socketvar.h>
61 #include <sys/sysctl.h>
62 #include <sys/syslog.h>
63 #include <sys/ucred.h>
64 #include <net/ethernet.h> /* for ETHERTYPE_IP */
65 #include <net/if.h>
66 #include <net/radix.h>
67 #include <net/route.h>
68 #include <net/pf_mtag.h>
69
70 #define IPFW_INTERNAL   /* Access to protected data structures in ip_fw.h. */
71
72 #include <netinet/in.h>
73 #include <netinet/in_var.h>
74 #include <netinet/in_pcb.h>
75 #include <netinet/ip.h>
76 #include <netinet/ip_var.h>
77 #include <netinet/ip_icmp.h>
78 #include <netinet/ip_fw.h>
79 #include <netinet/ip_divert.h>
80 #include <netinet/ip_dummynet.h>
81 #include <netinet/ip_carp.h>
82 #include <netinet/pim.h>
83 #include <netinet/tcp_var.h>
84 #include <netinet/udp.h>
85 #include <netinet/udp_var.h>
86 #include <netinet/sctp.h>
87 #include <netgraph/ng_ipfw.h>
88
89 #include <netinet/ip6.h>
90 #include <netinet/icmp6.h>
91 #ifdef INET6
92 #include <netinet6/scope6_var.h>
93 #endif
94
95 #include <machine/in_cksum.h>   /* XXX for in_cksum */
96
97 #ifdef MAC
98 #include <security/mac/mac_framework.h>
99 #endif
100
101 /*
102  * set_disable contains one bit per set value (0..31).
103  * If the bit is set, all rules with the corresponding set
104  * are disabled. Set RESVD_SET(31) is reserved for the default rule
105  * and rules that are not deleted by the flush command,
106  * and CANNOT be disabled.
107  * Rules in set RESVD_SET can only be deleted explicitly.
108  */
109 static u_int32_t set_disable;
110 static int fw_verbose;
111 static struct callout ipfw_timeout;
112 static int verbose_limit;
113
114 static uma_zone_t ipfw_dyn_rule_zone;
115
116 /*
117  * Data structure to cache our ucred related
118  * information. This structure only gets used if
119  * the user specified UID/GID based constraints in
120  * a firewall rule.
121  */
122 struct ip_fw_ugid {
123         gid_t           fw_groups[NGROUPS];
124         int             fw_ngroups;
125         uid_t           fw_uid;
126         int             fw_prid;
127 };
128
129 /*
130  * list of rules for layer 3
131  */
132 struct ip_fw_chain layer3_chain;
133
134 MALLOC_DEFINE(M_IPFW, "IpFw/IpAcct", "IpFw/IpAcct chain's");
135 MALLOC_DEFINE(M_IPFW_TBL, "ipfw_tbl", "IpFw tables");
136 #define IPFW_NAT_LOADED (ipfw_nat_ptr != NULL)
137 ipfw_nat_t *ipfw_nat_ptr = NULL;
138 ipfw_nat_cfg_t *ipfw_nat_cfg_ptr;
139 ipfw_nat_cfg_t *ipfw_nat_del_ptr;
140 ipfw_nat_cfg_t *ipfw_nat_get_cfg_ptr;
141 ipfw_nat_cfg_t *ipfw_nat_get_log_ptr;
142
143 struct table_entry {
144         struct radix_node       rn[2];
145         struct sockaddr_in      addr, mask;
146         u_int32_t               value;
147 };
148
149 static int autoinc_step = 100; /* bounded to 1..1000 in add_rule() */
150
151 extern int ipfw_chg_hook(SYSCTL_HANDLER_ARGS);
152
153 #ifdef SYSCTL_NODE
154 SYSCTL_NODE(_net_inet_ip, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall");
155 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, enable,
156     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE3, &fw_enable, 0,
157     ipfw_chg_hook, "I", "Enable ipfw");
158 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, autoinc_step, CTLFLAG_RW,
159     &autoinc_step, 0, "Rule number autincrement step");
160 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, one_pass,
161     CTLFLAG_RW | CTLFLAG_SECURE3,
162     &fw_one_pass, 0,
163     "Only do a single pass through ipfw when using dummynet(4)");
164 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose,
165     CTLFLAG_RW | CTLFLAG_SECURE3,
166     &fw_verbose, 0, "Log matches to ipfw rules");
167 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose_limit, CTLFLAG_RW,
168     &verbose_limit, 0, "Set upper limit of matches of ipfw rules logged");
169 SYSCTL_UINT(_net_inet_ip_fw, OID_AUTO, default_rule, CTLFLAG_RD,
170     NULL, IPFW_DEFAULT_RULE, "The default/max possible rule number.");
171 SYSCTL_UINT(_net_inet_ip_fw, OID_AUTO, tables_max, CTLFLAG_RD,
172     NULL, IPFW_TABLES_MAX, "The maximum number of tables.");
173 #endif /* SYSCTL_NODE */
174
175 /*
176  * Description of dynamic rules.
177  *
178  * Dynamic rules are stored in lists accessed through a hash table
179  * (ipfw_dyn_v) whose size is curr_dyn_buckets. This value can
180  * be modified through the sysctl variable dyn_buckets which is
181  * updated when the table becomes empty.
182  *
183  * XXX currently there is only one list, ipfw_dyn.
184  *
185  * When a packet is received, its address fields are first masked
186  * with the mask defined for the rule, then hashed, then matched
187  * against the entries in the corresponding list.
188  * Dynamic rules can be used for different purposes:
189  *  + stateful rules;
190  *  + enforcing limits on the number of sessions;
191  *  + in-kernel NAT (not implemented yet)
192  *
193  * The lifetime of dynamic rules is regulated by dyn_*_lifetime,
194  * measured in seconds and depending on the flags.
195  *
196  * The total number of dynamic rules is stored in dyn_count.
197  * The max number of dynamic rules is dyn_max. When we reach
198  * the maximum number of rules we do not create anymore. This is
199  * done to avoid consuming too much memory, but also too much
200  * time when searching on each packet (ideally, we should try instead
201  * to put a limit on the length of the list on each bucket...).
202  *
203  * Each dynamic rule holds a pointer to the parent ipfw rule so
204  * we know what action to perform. Dynamic rules are removed when
205  * the parent rule is deleted. XXX we should make them survive.
206  *
207  * There are some limitations with dynamic rules -- we do not
208  * obey the 'randomized match', and we do not do multiple
209  * passes through the firewall. XXX check the latter!!!
210  */
211 static ipfw_dyn_rule **ipfw_dyn_v = NULL;
212 static u_int32_t dyn_buckets = 256; /* must be power of 2 */
213 static u_int32_t curr_dyn_buckets = 256; /* must be power of 2 */
214
215 static struct mtx ipfw_dyn_mtx;         /* mutex guarding dynamic rules */
216 #define IPFW_DYN_LOCK_INIT() \
217         mtx_init(&ipfw_dyn_mtx, "IPFW dynamic rules", NULL, MTX_DEF)
218 #define IPFW_DYN_LOCK_DESTROY() mtx_destroy(&ipfw_dyn_mtx)
219 #define IPFW_DYN_LOCK()         mtx_lock(&ipfw_dyn_mtx)
220 #define IPFW_DYN_UNLOCK()       mtx_unlock(&ipfw_dyn_mtx)
221 #define IPFW_DYN_LOCK_ASSERT()  mtx_assert(&ipfw_dyn_mtx, MA_OWNED)
222
223 /*
224  * Timeouts for various events in handing dynamic rules.
225  */
226 static u_int32_t dyn_ack_lifetime = 300;
227 static u_int32_t dyn_syn_lifetime = 20;
228 static u_int32_t dyn_fin_lifetime = 1;
229 static u_int32_t dyn_rst_lifetime = 1;
230 static u_int32_t dyn_udp_lifetime = 10;
231 static u_int32_t dyn_short_lifetime = 5;
232
233 /*
234  * Keepalives are sent if dyn_keepalive is set. They are sent every
235  * dyn_keepalive_period seconds, in the last dyn_keepalive_interval
236  * seconds of lifetime of a rule.
237  * dyn_rst_lifetime and dyn_fin_lifetime should be strictly lower
238  * than dyn_keepalive_period.
239  */
240
241 static u_int32_t dyn_keepalive_interval = 20;
242 static u_int32_t dyn_keepalive_period = 5;
243 static u_int32_t dyn_keepalive = 1;     /* do send keepalives */
244
245 static u_int32_t static_count;  /* # of static rules */
246 static u_int32_t static_len;    /* size in bytes of static rules */
247 static u_int32_t dyn_count;             /* # of dynamic rules */
248 static u_int32_t dyn_max = 4096;        /* max # of dynamic rules */
249
250 #ifdef SYSCTL_NODE
251 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_buckets, CTLFLAG_RW,
252     &dyn_buckets, 0, "Number of dyn. buckets");
253 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, curr_dyn_buckets, CTLFLAG_RD,
254     &curr_dyn_buckets, 0, "Current Number of dyn. buckets");
255 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_count, CTLFLAG_RD,
256     &dyn_count, 0, "Number of dyn. rules");
257 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_max, CTLFLAG_RW,
258     &dyn_max, 0, "Max number of dyn. rules");
259 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, static_count, CTLFLAG_RD,
260     &static_count, 0, "Number of static rules");
261 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_ack_lifetime, CTLFLAG_RW,
262     &dyn_ack_lifetime, 0, "Lifetime of dyn. rules for acks");
263 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_syn_lifetime, CTLFLAG_RW,
264     &dyn_syn_lifetime, 0, "Lifetime of dyn. rules for syn");
265 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_fin_lifetime, CTLFLAG_RW,
266     &dyn_fin_lifetime, 0, "Lifetime of dyn. rules for fin");
267 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_rst_lifetime, CTLFLAG_RW,
268     &dyn_rst_lifetime, 0, "Lifetime of dyn. rules for rst");
269 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_udp_lifetime, CTLFLAG_RW,
270     &dyn_udp_lifetime, 0, "Lifetime of dyn. rules for UDP");
271 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_short_lifetime, CTLFLAG_RW,
272     &dyn_short_lifetime, 0, "Lifetime of dyn. rules for other situations");
273 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_keepalive, CTLFLAG_RW,
274     &dyn_keepalive, 0, "Enable keepalives for dyn. rules");
275 #endif /* SYSCTL_NODE */
276
277 #ifdef INET6
278 /*
279  * IPv6 specific variables
280  */
281 #ifdef SYSCTL_NODE
282 SYSCTL_DECL(_net_inet6_ip6);
283 #endif /* SYSCTL_NODE */
284
285 static struct sysctl_ctx_list ip6_fw_sysctl_ctx;
286 static struct sysctl_oid *ip6_fw_sysctl_tree;
287 #endif /* INET6 */
288
289 static int fw_deny_unknown_exthdrs = 1;
290
291
292 /*
293  * L3HDR maps an ipv4 pointer into a layer3 header pointer of type T
294  * Other macros just cast void * into the appropriate type
295  */
296 #define L3HDR(T, ip)    ((T *)((u_int32_t *)(ip) + (ip)->ip_hl))
297 #define TCP(p)          ((struct tcphdr *)(p))
298 #define SCTP(p)         ((struct sctphdr *)(p))
299 #define UDP(p)          ((struct udphdr *)(p))
300 #define ICMP(p)         ((struct icmphdr *)(p))
301 #define ICMP6(p)        ((struct icmp6_hdr *)(p))
302
303 static __inline int
304 icmptype_match(struct icmphdr *icmp, ipfw_insn_u32 *cmd)
305 {
306         int type = icmp->icmp_type;
307
308         return (type <= ICMP_MAXTYPE && (cmd->d[0] & (1<<type)) );
309 }
310
311 #define TT      ( (1 << ICMP_ECHO) | (1 << ICMP_ROUTERSOLICIT) | \
312     (1 << ICMP_TSTAMP) | (1 << ICMP_IREQ) | (1 << ICMP_MASKREQ) )
313
314 static int
315 is_icmp_query(struct icmphdr *icmp)
316 {
317         int type = icmp->icmp_type;
318
319         return (type <= ICMP_MAXTYPE && (TT & (1<<type)) );
320 }
321 #undef TT
322
323 /*
324  * The following checks use two arrays of 8 or 16 bits to store the
325  * bits that we want set or clear, respectively. They are in the
326  * low and high half of cmd->arg1 or cmd->d[0].
327  *
328  * We scan options and store the bits we find set. We succeed if
329  *
330  *      (want_set & ~bits) == 0 && (want_clear & ~bits) == want_clear
331  *
332  * The code is sometimes optimized not to store additional variables.
333  */
334
335 static int
336 flags_match(ipfw_insn *cmd, u_int8_t bits)
337 {
338         u_char want_clear;
339         bits = ~bits;
340
341         if ( ((cmd->arg1 & 0xff) & bits) != 0)
342                 return 0; /* some bits we want set were clear */
343         want_clear = (cmd->arg1 >> 8) & 0xff;
344         if ( (want_clear & bits) != want_clear)
345                 return 0; /* some bits we want clear were set */
346         return 1;
347 }
348
349 static int
350 ipopts_match(struct ip *ip, ipfw_insn *cmd)
351 {
352         int optlen, bits = 0;
353         u_char *cp = (u_char *)(ip + 1);
354         int x = (ip->ip_hl << 2) - sizeof (struct ip);
355
356         for (; x > 0; x -= optlen, cp += optlen) {
357                 int opt = cp[IPOPT_OPTVAL];
358
359                 if (opt == IPOPT_EOL)
360                         break;
361                 if (opt == IPOPT_NOP)
362                         optlen = 1;
363                 else {
364                         optlen = cp[IPOPT_OLEN];
365                         if (optlen <= 0 || optlen > x)
366                                 return 0; /* invalid or truncated */
367                 }
368                 switch (opt) {
369
370                 default:
371                         break;
372
373                 case IPOPT_LSRR:
374                         bits |= IP_FW_IPOPT_LSRR;
375                         break;
376
377                 case IPOPT_SSRR:
378                         bits |= IP_FW_IPOPT_SSRR;
379                         break;
380
381                 case IPOPT_RR:
382                         bits |= IP_FW_IPOPT_RR;
383                         break;
384
385                 case IPOPT_TS:
386                         bits |= IP_FW_IPOPT_TS;
387                         break;
388                 }
389         }
390         return (flags_match(cmd, bits));
391 }
392
393 static int
394 tcpopts_match(struct tcphdr *tcp, ipfw_insn *cmd)
395 {
396         int optlen, bits = 0;
397         u_char *cp = (u_char *)(tcp + 1);
398         int x = (tcp->th_off << 2) - sizeof(struct tcphdr);
399
400         for (; x > 0; x -= optlen, cp += optlen) {
401                 int opt = cp[0];
402                 if (opt == TCPOPT_EOL)
403                         break;
404                 if (opt == TCPOPT_NOP)
405                         optlen = 1;
406                 else {
407                         optlen = cp[1];
408                         if (optlen <= 0)
409                                 break;
410                 }
411
412                 switch (opt) {
413
414                 default:
415                         break;
416
417                 case TCPOPT_MAXSEG:
418                         bits |= IP_FW_TCPOPT_MSS;
419                         break;
420
421                 case TCPOPT_WINDOW:
422                         bits |= IP_FW_TCPOPT_WINDOW;
423                         break;
424
425                 case TCPOPT_SACK_PERMITTED:
426                 case TCPOPT_SACK:
427                         bits |= IP_FW_TCPOPT_SACK;
428                         break;
429
430                 case TCPOPT_TIMESTAMP:
431                         bits |= IP_FW_TCPOPT_TS;
432                         break;
433
434                 }
435         }
436         return (flags_match(cmd, bits));
437 }
438
439 static int
440 iface_match(struct ifnet *ifp, ipfw_insn_if *cmd)
441 {
442         if (ifp == NULL)        /* no iface with this packet, match fails */
443                 return 0;
444         /* Check by name or by IP address */
445         if (cmd->name[0] != '\0') { /* match by name */
446                 /* Check name */
447                 if (cmd->p.glob) {
448                         if (fnmatch(cmd->name, ifp->if_xname, 0) == 0)
449                                 return(1);
450                 } else {
451                         if (strncmp(ifp->if_xname, cmd->name, IFNAMSIZ) == 0)
452                                 return(1);
453                 }
454         } else {
455                 struct ifaddr *ia;
456
457                 /* XXX lock? */
458                 TAILQ_FOREACH(ia, &ifp->if_addrhead, ifa_link) {
459                         if (ia->ifa_addr->sa_family != AF_INET)
460                                 continue;
461                         if (cmd->p.ip.s_addr == ((struct sockaddr_in *)
462                             (ia->ifa_addr))->sin_addr.s_addr)
463                                 return(1);      /* match */
464                 }
465         }
466         return(0);      /* no match, fail ... */
467 }
468
469 /*
470  * The verify_path function checks if a route to the src exists and
471  * if it is reachable via ifp (when provided).
472  * 
473  * The 'verrevpath' option checks that the interface that an IP packet
474  * arrives on is the same interface that traffic destined for the
475  * packet's source address would be routed out of.  The 'versrcreach'
476  * option just checks that the source address is reachable via any route
477  * (except default) in the routing table.  These two are a measure to block
478  * forged packets.  This is also commonly known as "anti-spoofing" or Unicast
479  * Reverse Path Forwarding (Unicast RFP) in Cisco-ese. The name of the knobs
480  * is purposely reminiscent of the Cisco IOS command,
481  *
482  *   ip verify unicast reverse-path
483  *   ip verify unicast source reachable-via any
484  *
485  * which implements the same functionality. But note that syntax is
486  * misleading. The check may be performed on all IP packets whether unicast,
487  * multicast, or broadcast.
488  */
489 static int
490 verify_path(struct in_addr src, struct ifnet *ifp, u_int fib)
491 {
492         struct route ro;
493         struct sockaddr_in *dst;
494
495         bzero(&ro, sizeof(ro));
496
497         dst = (struct sockaddr_in *)&(ro.ro_dst);
498         dst->sin_family = AF_INET;
499         dst->sin_len = sizeof(*dst);
500         dst->sin_addr = src;
501         in_rtalloc_ign(&ro, RTF_CLONING, fib);
502
503         if (ro.ro_rt == NULL)
504                 return 0;
505
506         /*
507          * If ifp is provided, check for equality with rtentry.
508          * We should use rt->rt_ifa->ifa_ifp, instead of rt->rt_ifp,
509          * in order to pass packets injected back by if_simloop():
510          * if useloopback == 1 routing entry (via lo0) for our own address
511          * may exist, so we need to handle routing assymetry.
512          */
513         if (ifp != NULL && ro.ro_rt->rt_ifa->ifa_ifp != ifp) {
514                 RTFREE(ro.ro_rt);
515                 return 0;
516         }
517
518         /* if no ifp provided, check if rtentry is not default route */
519         if (ifp == NULL &&
520              satosin(rt_key(ro.ro_rt))->sin_addr.s_addr == INADDR_ANY) {
521                 RTFREE(ro.ro_rt);
522                 return 0;
523         }
524
525         /* or if this is a blackhole/reject route */
526         if (ifp == NULL && ro.ro_rt->rt_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
527                 RTFREE(ro.ro_rt);
528                 return 0;
529         }
530
531         /* found valid route */
532         RTFREE(ro.ro_rt);
533         return 1;
534 }
535
536 #ifdef INET6
537 /*
538  * ipv6 specific rules here...
539  */
540 static __inline int
541 icmp6type_match (int type, ipfw_insn_u32 *cmd)
542 {
543         return (type <= ICMP6_MAXTYPE && (cmd->d[type/32] & (1<<(type%32)) ) );
544 }
545
546 static int
547 flow6id_match( int curr_flow, ipfw_insn_u32 *cmd )
548 {
549         int i;
550         for (i=0; i <= cmd->o.arg1; ++i )
551                 if (curr_flow == cmd->d[i] )
552                         return 1;
553         return 0;
554 }
555
556 /* support for IP6_*_ME opcodes */
557 static int
558 search_ip6_addr_net (struct in6_addr * ip6_addr)
559 {
560         struct ifnet *mdc;
561         struct ifaddr *mdc2;
562         struct in6_ifaddr *fdm;
563         struct in6_addr copia;
564
565         TAILQ_FOREACH(mdc, &ifnet, if_link)
566                 TAILQ_FOREACH(mdc2, &mdc->if_addrlist, ifa_list) {
567                         if (mdc2->ifa_addr->sa_family == AF_INET6) {
568                                 fdm = (struct in6_ifaddr *)mdc2;
569                                 copia = fdm->ia_addr.sin6_addr;
570                                 /* need for leaving scope_id in the sock_addr */
571                                 in6_clearscope(&copia);
572                                 if (IN6_ARE_ADDR_EQUAL(ip6_addr, &copia))
573                                         return 1;
574                         }
575                 }
576         return 0;
577 }
578
579 static int
580 verify_path6(struct in6_addr *src, struct ifnet *ifp)
581 {
582         struct route_in6 ro;
583         struct sockaddr_in6 *dst;
584
585         bzero(&ro, sizeof(ro));
586
587         dst = (struct sockaddr_in6 * )&(ro.ro_dst);
588         dst->sin6_family = AF_INET6;
589         dst->sin6_len = sizeof(*dst);
590         dst->sin6_addr = *src;
591         /* XXX MRT 0 for ipv6 at this time */
592         rtalloc_ign((struct route *)&ro, RTF_CLONING);
593
594         if (ro.ro_rt == NULL)
595                 return 0;
596
597         /* 
598          * if ifp is provided, check for equality with rtentry
599          * We should use rt->rt_ifa->ifa_ifp, instead of rt->rt_ifp,
600          * to support the case of sending packets to an address of our own.
601          * (where the former interface is the first argument of if_simloop()
602          *  (=ifp), the latter is lo0)
603          */
604         if (ifp != NULL && ro.ro_rt->rt_ifa->ifa_ifp != ifp) {
605                 RTFREE(ro.ro_rt);
606                 return 0;
607         }
608
609         /* if no ifp provided, check if rtentry is not default route */
610         if (ifp == NULL &&
611             IN6_IS_ADDR_UNSPECIFIED(&satosin6(rt_key(ro.ro_rt))->sin6_addr)) {
612                 RTFREE(ro.ro_rt);
613                 return 0;
614         }
615
616         /* or if this is a blackhole/reject route */
617         if (ifp == NULL && ro.ro_rt->rt_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
618                 RTFREE(ro.ro_rt);
619                 return 0;
620         }
621
622         /* found valid route */
623         RTFREE(ro.ro_rt);
624         return 1;
625
626 }
627 static __inline int
628 hash_packet6(struct ipfw_flow_id *id)
629 {
630         u_int32_t i;
631         i = (id->dst_ip6.__u6_addr.__u6_addr32[2]) ^
632             (id->dst_ip6.__u6_addr.__u6_addr32[3]) ^
633             (id->src_ip6.__u6_addr.__u6_addr32[2]) ^
634             (id->src_ip6.__u6_addr.__u6_addr32[3]) ^
635             (id->dst_port) ^ (id->src_port);
636         return i;
637 }
638
639 static int
640 is_icmp6_query(int icmp6_type)
641 {
642         if ((icmp6_type <= ICMP6_MAXTYPE) &&
643             (icmp6_type == ICMP6_ECHO_REQUEST ||
644             icmp6_type == ICMP6_MEMBERSHIP_QUERY ||
645             icmp6_type == ICMP6_WRUREQUEST ||
646             icmp6_type == ICMP6_FQDN_QUERY ||
647             icmp6_type == ICMP6_NI_QUERY))
648                 return (1);
649
650         return (0);
651 }
652
653 static void
654 send_reject6(struct ip_fw_args *args, int code, u_int hlen, struct ip6_hdr *ip6)
655 {
656         struct mbuf *m;
657
658         m = args->m;
659         if (code == ICMP6_UNREACH_RST && args->f_id.proto == IPPROTO_TCP) {
660                 struct tcphdr *tcp;
661                 tcp_seq ack, seq;
662                 int flags;
663                 struct {
664                         struct ip6_hdr ip6;
665                         struct tcphdr th;
666                 } ti;
667                 tcp = (struct tcphdr *)((char *)ip6 + hlen);
668
669                 if ((tcp->th_flags & TH_RST) != 0) {
670                         m_freem(m);
671                         args->m = NULL;
672                         return;
673                 }
674
675                 ti.ip6 = *ip6;
676                 ti.th = *tcp;
677                 ti.th.th_seq = ntohl(ti.th.th_seq);
678                 ti.th.th_ack = ntohl(ti.th.th_ack);
679                 ti.ip6.ip6_nxt = IPPROTO_TCP;
680
681                 if (ti.th.th_flags & TH_ACK) {
682                         ack = 0;
683                         seq = ti.th.th_ack;
684                         flags = TH_RST;
685                 } else {
686                         ack = ti.th.th_seq;
687                         if ((m->m_flags & M_PKTHDR) != 0) {
688                                 /*
689                                  * total new data to ACK is:
690                                  * total packet length,
691                                  * minus the header length,
692                                  * minus the tcp header length.
693                                  */
694                                 ack += m->m_pkthdr.len - hlen
695                                         - (ti.th.th_off << 2);
696                         } else if (ip6->ip6_plen) {
697                                 ack += ntohs(ip6->ip6_plen) + sizeof(*ip6) -
698                                     hlen - (ti.th.th_off << 2);
699                         } else {
700                                 m_freem(m);
701                                 return;
702                         }
703                         if (tcp->th_flags & TH_SYN)
704                                 ack++;
705                         seq = 0;
706                         flags = TH_RST|TH_ACK;
707                 }
708                 bcopy(&ti, ip6, sizeof(ti));
709                 /*
710                  * m is only used to recycle the mbuf
711                  * The data in it is never read so we don't need
712                  * to correct the offsets or anything
713                  */
714                 tcp_respond(NULL, ip6, tcp, m, ack, seq, flags);
715         } else if (code != ICMP6_UNREACH_RST) { /* Send an ICMPv6 unreach. */
716 #if 0
717                 /*
718                  * Unlike above, the mbufs need to line up with the ip6 hdr,
719                  * as the contents are read. We need to m_adj() the
720                  * needed amount.
721                  * The mbuf will however be thrown away so we can adjust it.
722                  * Remember we did an m_pullup on it already so we
723                  * can make some assumptions about contiguousness.
724                  */
725                 if (args->L3offset)
726                         m_adj(m, args->L3offset);
727 #endif
728                 icmp6_error(m, ICMP6_DST_UNREACH, code, 0);
729         } else
730                 m_freem(m);
731
732         args->m = NULL;
733 }
734
735 #endif /* INET6 */
736
737 static u_int64_t norule_counter;        /* counter for ipfw_log(NULL...) */
738
739 #define SNPARGS(buf, len) buf + len, sizeof(buf) > len ? sizeof(buf) - len : 0
740 #define SNP(buf) buf, sizeof(buf)
741
742 /*
743  * We enter here when we have a rule with O_LOG.
744  * XXX this function alone takes about 2Kbytes of code!
745  */
746 static void
747 ipfw_log(struct ip_fw *f, u_int hlen, struct ip_fw_args *args,
748     struct mbuf *m, struct ifnet *oif, u_short offset, uint32_t tablearg,
749     struct ip *ip)
750 {
751         struct ether_header *eh = args->eh;
752         char *action;
753         int limit_reached = 0;
754         char action2[40], proto[128], fragment[32];
755
756         fragment[0] = '\0';
757         proto[0] = '\0';
758
759         if (f == NULL) {        /* bogus pkt */
760                 if (verbose_limit != 0 && norule_counter >= verbose_limit)
761                         return;
762                 norule_counter++;
763                 if (norule_counter == verbose_limit)
764                         limit_reached = verbose_limit;
765                 action = "Refuse";
766         } else {        /* O_LOG is the first action, find the real one */
767                 ipfw_insn *cmd = ACTION_PTR(f);
768                 ipfw_insn_log *l = (ipfw_insn_log *)cmd;
769
770                 if (l->max_log != 0 && l->log_left == 0)
771                         return;
772                 l->log_left--;
773                 if (l->log_left == 0)
774                         limit_reached = l->max_log;
775                 cmd += F_LEN(cmd);      /* point to first action */
776                 if (cmd->opcode == O_ALTQ) {
777                         ipfw_insn_altq *altq = (ipfw_insn_altq *)cmd;
778
779                         snprintf(SNPARGS(action2, 0), "Altq %d",
780                                 altq->qid);
781                         cmd += F_LEN(cmd);
782                 }
783                 if (cmd->opcode == O_PROB)
784                         cmd += F_LEN(cmd);
785
786                 if (cmd->opcode == O_TAG)
787                         cmd += F_LEN(cmd);
788
789                 action = action2;
790                 switch (cmd->opcode) {
791                 case O_DENY:
792                         action = "Deny";
793                         break;
794
795                 case O_REJECT:
796                         if (cmd->arg1==ICMP_REJECT_RST)
797                                 action = "Reset";
798                         else if (cmd->arg1==ICMP_UNREACH_HOST)
799                                 action = "Reject";
800                         else
801                                 snprintf(SNPARGS(action2, 0), "Unreach %d",
802                                         cmd->arg1);
803                         break;
804
805                 case O_UNREACH6:
806                         if (cmd->arg1==ICMP6_UNREACH_RST)
807                                 action = "Reset";
808                         else
809                                 snprintf(SNPARGS(action2, 0), "Unreach %d",
810                                         cmd->arg1);
811                         break;
812
813                 case O_ACCEPT:
814                         action = "Accept";
815                         break;
816                 case O_COUNT:
817                         action = "Count";
818                         break;
819                 case O_DIVERT:
820                         snprintf(SNPARGS(action2, 0), "Divert %d",
821                                 cmd->arg1);
822                         break;
823                 case O_TEE:
824                         snprintf(SNPARGS(action2, 0), "Tee %d",
825                                 cmd->arg1);
826                         break;
827                 case O_SETFIB:
828                         snprintf(SNPARGS(action2, 0), "SetFib %d",
829                                 cmd->arg1);
830                         break;
831                 case O_SKIPTO:
832                         snprintf(SNPARGS(action2, 0), "SkipTo %d",
833                                 cmd->arg1);
834                         break;
835                 case O_PIPE:
836                         snprintf(SNPARGS(action2, 0), "Pipe %d",
837                                 cmd->arg1);
838                         break;
839                 case O_QUEUE:
840                         snprintf(SNPARGS(action2, 0), "Queue %d",
841                                 cmd->arg1);
842                         break;
843                 case O_FORWARD_IP: {
844                         ipfw_insn_sa *sa = (ipfw_insn_sa *)cmd;
845                         int len;
846                         struct in_addr dummyaddr;
847                         if (sa->sa.sin_addr.s_addr == INADDR_ANY)
848                                 dummyaddr.s_addr = htonl(tablearg);
849                         else
850                                 dummyaddr.s_addr = sa->sa.sin_addr.s_addr;
851
852                         len = snprintf(SNPARGS(action2, 0), "Forward to %s",
853                                 inet_ntoa(dummyaddr));
854
855                         if (sa->sa.sin_port)
856                                 snprintf(SNPARGS(action2, len), ":%d",
857                                     sa->sa.sin_port);
858                         }
859                         break;
860                 case O_NETGRAPH:
861                         snprintf(SNPARGS(action2, 0), "Netgraph %d",
862                                 cmd->arg1);
863                         break;
864                 case O_NGTEE:
865                         snprintf(SNPARGS(action2, 0), "Ngtee %d",
866                                 cmd->arg1);
867                         break;
868                 case O_NAT:
869                         action = "Nat";
870                         break;
871                 default:
872                         action = "UNKNOWN";
873                         break;
874                 }
875         }
876
877         if (hlen == 0) {        /* non-ip */
878                 snprintf(SNPARGS(proto, 0), "MAC");
879
880         } else {
881                 int len;
882                 char src[48], dst[48];
883                 struct icmphdr *icmp;
884                 struct tcphdr *tcp;
885                 struct udphdr *udp;
886 #ifdef INET6
887                 struct ip6_hdr *ip6 = NULL;
888                 struct icmp6_hdr *icmp6;
889 #endif
890                 src[0] = '\0';
891                 dst[0] = '\0';
892 #ifdef INET6
893                 if (IS_IP6_FLOW_ID(&(args->f_id))) {
894                         char ip6buf[INET6_ADDRSTRLEN];
895                         snprintf(src, sizeof(src), "[%s]",
896                             ip6_sprintf(ip6buf, &args->f_id.src_ip6));
897                         snprintf(dst, sizeof(dst), "[%s]",
898                             ip6_sprintf(ip6buf, &args->f_id.dst_ip6));
899
900                         ip6 = (struct ip6_hdr *)ip;
901                         tcp = (struct tcphdr *)(((char *)ip) + hlen);
902                         udp = (struct udphdr *)(((char *)ip) + hlen);
903                 } else
904 #endif
905                 {
906                         tcp = L3HDR(struct tcphdr, ip);
907                         udp = L3HDR(struct udphdr, ip);
908
909                         inet_ntoa_r(ip->ip_src, src);
910                         inet_ntoa_r(ip->ip_dst, dst);
911                 }
912
913                 switch (args->f_id.proto) {
914                 case IPPROTO_TCP:
915                         len = snprintf(SNPARGS(proto, 0), "TCP %s", src);
916                         if (offset == 0)
917                                 snprintf(SNPARGS(proto, len), ":%d %s:%d",
918                                     ntohs(tcp->th_sport),
919                                     dst,
920                                     ntohs(tcp->th_dport));
921                         else
922                                 snprintf(SNPARGS(proto, len), " %s", dst);
923                         break;
924
925                 case IPPROTO_UDP:
926                         len = snprintf(SNPARGS(proto, 0), "UDP %s", src);
927                         if (offset == 0)
928                                 snprintf(SNPARGS(proto, len), ":%d %s:%d",
929                                     ntohs(udp->uh_sport),
930                                     dst,
931                                     ntohs(udp->uh_dport));
932                         else
933                                 snprintf(SNPARGS(proto, len), " %s", dst);
934                         break;
935
936                 case IPPROTO_ICMP:
937                         icmp = L3HDR(struct icmphdr, ip);
938                         if (offset == 0)
939                                 len = snprintf(SNPARGS(proto, 0),
940                                     "ICMP:%u.%u ",
941                                     icmp->icmp_type, icmp->icmp_code);
942                         else
943                                 len = snprintf(SNPARGS(proto, 0), "ICMP ");
944                         len += snprintf(SNPARGS(proto, len), "%s", src);
945                         snprintf(SNPARGS(proto, len), " %s", dst);
946                         break;
947 #ifdef INET6
948                 case IPPROTO_ICMPV6:
949                         icmp6 = (struct icmp6_hdr *)(((char *)ip) + hlen);
950                         if (offset == 0)
951                                 len = snprintf(SNPARGS(proto, 0),
952                                     "ICMPv6:%u.%u ",
953                                     icmp6->icmp6_type, icmp6->icmp6_code);
954                         else
955                                 len = snprintf(SNPARGS(proto, 0), "ICMPv6 ");
956                         len += snprintf(SNPARGS(proto, len), "%s", src);
957                         snprintf(SNPARGS(proto, len), " %s", dst);
958                         break;
959 #endif
960                 default:
961                         len = snprintf(SNPARGS(proto, 0), "P:%d %s",
962                             args->f_id.proto, src);
963                         snprintf(SNPARGS(proto, len), " %s", dst);
964                         break;
965                 }
966
967 #ifdef INET6
968                 if (IS_IP6_FLOW_ID(&(args->f_id))) {
969                         if (offset & (IP6F_OFF_MASK | IP6F_MORE_FRAG))
970                                 snprintf(SNPARGS(fragment, 0),
971                                     " (frag %08x:%d@%d%s)",
972                                     args->f_id.frag_id6,
973                                     ntohs(ip6->ip6_plen) - hlen,
974                                     ntohs(offset & IP6F_OFF_MASK) << 3,
975                                     (offset & IP6F_MORE_FRAG) ? "+" : "");
976                 } else
977 #endif
978                 {
979                         int ip_off, ip_len;
980                         if (eh != NULL) { /* layer 2 packets are as on the wire */
981                                 ip_off = ntohs(ip->ip_off);
982                                 ip_len = ntohs(ip->ip_len);
983                         } else {
984                                 ip_off = ip->ip_off;
985                                 ip_len = ip->ip_len;
986                         }
987                         if (ip_off & (IP_MF | IP_OFFMASK))
988                                 snprintf(SNPARGS(fragment, 0),
989                                     " (frag %d:%d@%d%s)",
990                                     ntohs(ip->ip_id), ip_len - (ip->ip_hl << 2),
991                                     offset << 3,
992                                     (ip_off & IP_MF) ? "+" : "");
993                 }
994         }
995         if (oif || m->m_pkthdr.rcvif)
996                 log(LOG_SECURITY | LOG_INFO,
997                     "ipfw: %d %s %s %s via %s%s\n",
998                     f ? f->rulenum : -1,
999                     action, proto, oif ? "out" : "in",
1000                     oif ? oif->if_xname : m->m_pkthdr.rcvif->if_xname,
1001                     fragment);
1002         else
1003                 log(LOG_SECURITY | LOG_INFO,
1004                     "ipfw: %d %s %s [no if info]%s\n",
1005                     f ? f->rulenum : -1,
1006                     action, proto, fragment);
1007         if (limit_reached)
1008                 log(LOG_SECURITY | LOG_NOTICE,
1009                     "ipfw: limit %d reached on entry %d\n",
1010                     limit_reached, f ? f->rulenum : -1);
1011 }
1012
1013 /*
1014  * IMPORTANT: the hash function for dynamic rules must be commutative
1015  * in source and destination (ip,port), because rules are bidirectional
1016  * and we want to find both in the same bucket.
1017  */
1018 static __inline int
1019 hash_packet(struct ipfw_flow_id *id)
1020 {
1021         u_int32_t i;
1022
1023 #ifdef INET6
1024         if (IS_IP6_FLOW_ID(id)) 
1025                 i = hash_packet6(id);
1026         else
1027 #endif /* INET6 */
1028         i = (id->dst_ip) ^ (id->src_ip) ^ (id->dst_port) ^ (id->src_port);
1029         i &= (curr_dyn_buckets - 1);
1030         return i;
1031 }
1032
1033 /**
1034  * unlink a dynamic rule from a chain. prev is a pointer to
1035  * the previous one, q is a pointer to the rule to delete,
1036  * head is a pointer to the head of the queue.
1037  * Modifies q and potentially also head.
1038  */
1039 #define UNLINK_DYN_RULE(prev, head, q) {                                \
1040         ipfw_dyn_rule *old_q = q;                                       \
1041                                                                         \
1042         /* remove a refcount to the parent */                           \
1043         if (q->dyn_type == O_LIMIT)                                     \
1044                 q->parent->count--;                                     \
1045         DEB(printf("ipfw: unlink entry 0x%08x %d -> 0x%08x %d, %d left\n",\
1046                 (q->id.src_ip), (q->id.src_port),                       \
1047                 (q->id.dst_ip), (q->id.dst_port), dyn_count-1 ); )      \
1048         if (prev != NULL)                                               \
1049                 prev->next = q = q->next;                               \
1050         else                                                            \
1051                 head = q = q->next;                                     \
1052         dyn_count--;                                                    \
1053         uma_zfree(ipfw_dyn_rule_zone, old_q); }
1054
1055 #define TIME_LEQ(a,b)       ((int)((a)-(b)) <= 0)
1056
1057 /**
1058  * Remove dynamic rules pointing to "rule", or all of them if rule == NULL.
1059  *
1060  * If keep_me == NULL, rules are deleted even if not expired,
1061  * otherwise only expired rules are removed.
1062  *
1063  * The value of the second parameter is also used to point to identify
1064  * a rule we absolutely do not want to remove (e.g. because we are
1065  * holding a reference to it -- this is the case with O_LIMIT_PARENT
1066  * rules). The pointer is only used for comparison, so any non-null
1067  * value will do.
1068  */
1069 static void
1070 remove_dyn_rule(struct ip_fw *rule, ipfw_dyn_rule *keep_me)
1071 {
1072         static u_int32_t last_remove = 0;
1073
1074 #define FORCE (keep_me == NULL)
1075
1076         ipfw_dyn_rule *prev, *q;
1077         int i, pass = 0, max_pass = 0;
1078
1079         IPFW_DYN_LOCK_ASSERT();
1080
1081         if (ipfw_dyn_v == NULL || dyn_count == 0)
1082                 return;
1083         /* do not expire more than once per second, it is useless */
1084         if (!FORCE && last_remove == time_uptime)
1085                 return;
1086         last_remove = time_uptime;
1087
1088         /*
1089          * because O_LIMIT refer to parent rules, during the first pass only
1090          * remove child and mark any pending LIMIT_PARENT, and remove
1091          * them in a second pass.
1092          */
1093 next_pass:
1094         for (i = 0 ; i < curr_dyn_buckets ; i++) {
1095                 for (prev=NULL, q = ipfw_dyn_v[i] ; q ; ) {
1096                         /*
1097                          * Logic can become complex here, so we split tests.
1098                          */
1099                         if (q == keep_me)
1100                                 goto next;
1101                         if (rule != NULL && rule != q->rule)
1102                                 goto next; /* not the one we are looking for */
1103                         if (q->dyn_type == O_LIMIT_PARENT) {
1104                                 /*
1105                                  * handle parent in the second pass,
1106                                  * record we need one.
1107                                  */
1108                                 max_pass = 1;
1109                                 if (pass == 0)
1110                                         goto next;
1111                                 if (FORCE && q->count != 0 ) {
1112                                         /* XXX should not happen! */
1113                                         printf("ipfw: OUCH! cannot remove rule,"
1114                                              " count %d\n", q->count);
1115                                 }
1116                         } else {
1117                                 if (!FORCE &&
1118                                     !TIME_LEQ( q->expire, time_uptime ))
1119                                         goto next;
1120                         }
1121              if (q->dyn_type != O_LIMIT_PARENT || !q->count) {
1122                      UNLINK_DYN_RULE(prev, ipfw_dyn_v[i], q);
1123                      continue;
1124              }
1125 next:
1126                         prev=q;
1127                         q=q->next;
1128                 }
1129         }
1130         if (pass++ < max_pass)
1131                 goto next_pass;
1132 }
1133
1134
1135 /**
1136  * lookup a dynamic rule.
1137  */
1138 static ipfw_dyn_rule *
1139 lookup_dyn_rule_locked(struct ipfw_flow_id *pkt, int *match_direction,
1140     struct tcphdr *tcp)
1141 {
1142         /*
1143          * stateful ipfw extensions.
1144          * Lookup into dynamic session queue
1145          */
1146 #define MATCH_REVERSE   0
1147 #define MATCH_FORWARD   1
1148 #define MATCH_NONE      2
1149 #define MATCH_UNKNOWN   3
1150         int i, dir = MATCH_NONE;
1151         ipfw_dyn_rule *prev, *q=NULL;
1152
1153         IPFW_DYN_LOCK_ASSERT();
1154
1155         if (ipfw_dyn_v == NULL)
1156                 goto done;      /* not found */
1157         i = hash_packet( pkt );
1158         for (prev=NULL, q = ipfw_dyn_v[i] ; q != NULL ; ) {
1159                 if (q->dyn_type == O_LIMIT_PARENT && q->count)
1160                         goto next;
1161                 if (TIME_LEQ( q->expire, time_uptime)) { /* expire entry */
1162                         UNLINK_DYN_RULE(prev, ipfw_dyn_v[i], q);
1163                         continue;
1164                 }
1165                 if (pkt->proto == q->id.proto &&
1166                     q->dyn_type != O_LIMIT_PARENT) {
1167                         if (IS_IP6_FLOW_ID(pkt)) {
1168                             if (IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
1169                                 &(q->id.src_ip6)) &&
1170                             IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
1171                                 &(q->id.dst_ip6)) &&
1172                             pkt->src_port == q->id.src_port &&
1173                             pkt->dst_port == q->id.dst_port ) {
1174                                 dir = MATCH_FORWARD;
1175                                 break;
1176                             }
1177                             if (IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
1178                                     &(q->id.dst_ip6)) &&
1179                                 IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
1180                                     &(q->id.src_ip6)) &&
1181                                 pkt->src_port == q->id.dst_port &&
1182                                 pkt->dst_port == q->id.src_port ) {
1183                                     dir = MATCH_REVERSE;
1184                                     break;
1185                             }
1186                         } else {
1187                             if (pkt->src_ip == q->id.src_ip &&
1188                                 pkt->dst_ip == q->id.dst_ip &&
1189                                 pkt->src_port == q->id.src_port &&
1190                                 pkt->dst_port == q->id.dst_port ) {
1191                                     dir = MATCH_FORWARD;
1192                                     break;
1193                             }
1194                             if (pkt->src_ip == q->id.dst_ip &&
1195                                 pkt->dst_ip == q->id.src_ip &&
1196                                 pkt->src_port == q->id.dst_port &&
1197                                 pkt->dst_port == q->id.src_port ) {
1198                                     dir = MATCH_REVERSE;
1199                                     break;
1200                             }
1201                         }
1202                 }
1203 next:
1204                 prev = q;
1205                 q = q->next;
1206         }
1207         if (q == NULL)
1208                 goto done; /* q = NULL, not found */
1209
1210         if ( prev != NULL) { /* found and not in front */
1211                 prev->next = q->next;
1212                 q->next = ipfw_dyn_v[i];
1213                 ipfw_dyn_v[i] = q;
1214         }
1215         if (pkt->proto == IPPROTO_TCP) { /* update state according to flags */
1216                 u_char flags = pkt->flags & (TH_FIN|TH_SYN|TH_RST);
1217
1218 #define BOTH_SYN        (TH_SYN | (TH_SYN << 8))
1219 #define BOTH_FIN        (TH_FIN | (TH_FIN << 8))
1220                 q->state |= (dir == MATCH_FORWARD ) ? flags : (flags << 8);
1221                 switch (q->state) {
1222                 case TH_SYN:                            /* opening */
1223                         q->expire = time_uptime + dyn_syn_lifetime;
1224                         break;
1225
1226                 case BOTH_SYN:                  /* move to established */
1227                 case BOTH_SYN | TH_FIN :        /* one side tries to close */
1228                 case BOTH_SYN | (TH_FIN << 8) :
1229                         if (tcp) {
1230 #define _SEQ_GE(a,b) ((int)(a) - (int)(b) >= 0)
1231                             u_int32_t ack = ntohl(tcp->th_ack);
1232                             if (dir == MATCH_FORWARD) {
1233                                 if (q->ack_fwd == 0 || _SEQ_GE(ack, q->ack_fwd))
1234                                     q->ack_fwd = ack;
1235                                 else { /* ignore out-of-sequence */
1236                                     break;
1237                                 }
1238                             } else {
1239                                 if (q->ack_rev == 0 || _SEQ_GE(ack, q->ack_rev))
1240                                     q->ack_rev = ack;
1241                                 else { /* ignore out-of-sequence */
1242                                     break;
1243                                 }
1244                             }
1245                         }
1246                         q->expire = time_uptime + dyn_ack_lifetime;
1247                         break;
1248
1249                 case BOTH_SYN | BOTH_FIN:       /* both sides closed */
1250                         if (dyn_fin_lifetime >= dyn_keepalive_period)
1251                                 dyn_fin_lifetime = dyn_keepalive_period - 1;
1252                         q->expire = time_uptime + dyn_fin_lifetime;
1253                         break;
1254
1255                 default:
1256 #if 0
1257                         /*
1258                          * reset or some invalid combination, but can also
1259                          * occur if we use keep-state the wrong way.
1260                          */
1261                         if ( (q->state & ((TH_RST << 8)|TH_RST)) == 0)
1262                                 printf("invalid state: 0x%x\n", q->state);
1263 #endif
1264                         if (dyn_rst_lifetime >= dyn_keepalive_period)
1265                                 dyn_rst_lifetime = dyn_keepalive_period - 1;
1266                         q->expire = time_uptime + dyn_rst_lifetime;
1267                         break;
1268                 }
1269         } else if (pkt->proto == IPPROTO_UDP) {
1270                 q->expire = time_uptime + dyn_udp_lifetime;
1271         } else {
1272                 /* other protocols */
1273                 q->expire = time_uptime + dyn_short_lifetime;
1274         }
1275 done:
1276         if (match_direction)
1277                 *match_direction = dir;
1278         return q;
1279 }
1280
1281 static ipfw_dyn_rule *
1282 lookup_dyn_rule(struct ipfw_flow_id *pkt, int *match_direction,
1283     struct tcphdr *tcp)
1284 {
1285         ipfw_dyn_rule *q;
1286
1287         IPFW_DYN_LOCK();
1288         q = lookup_dyn_rule_locked(pkt, match_direction, tcp);
1289         if (q == NULL)
1290                 IPFW_DYN_UNLOCK();
1291         /* NB: return table locked when q is not NULL */
1292         return q;
1293 }
1294
1295 static void
1296 realloc_dynamic_table(void)
1297 {
1298         IPFW_DYN_LOCK_ASSERT();
1299
1300         /*
1301          * Try reallocation, make sure we have a power of 2 and do
1302          * not allow more than 64k entries. In case of overflow,
1303          * default to 1024.
1304          */
1305
1306         if (dyn_buckets > 65536)
1307                 dyn_buckets = 1024;
1308         if ((dyn_buckets & (dyn_buckets-1)) != 0) { /* not a power of 2 */
1309                 dyn_buckets = curr_dyn_buckets; /* reset */
1310                 return;
1311         }
1312         curr_dyn_buckets = dyn_buckets;
1313         if (ipfw_dyn_v != NULL)
1314                 free(ipfw_dyn_v, M_IPFW);
1315         for (;;) {
1316                 ipfw_dyn_v = malloc(curr_dyn_buckets * sizeof(ipfw_dyn_rule *),
1317                        M_IPFW, M_NOWAIT | M_ZERO);
1318                 if (ipfw_dyn_v != NULL || curr_dyn_buckets <= 2)
1319                         break;
1320                 curr_dyn_buckets /= 2;
1321         }
1322 }
1323
1324 /**
1325  * Install state of type 'type' for a dynamic session.
1326  * The hash table contains two type of rules:
1327  * - regular rules (O_KEEP_STATE)
1328  * - rules for sessions with limited number of sess per user
1329  *   (O_LIMIT). When they are created, the parent is
1330  *   increased by 1, and decreased on delete. In this case,
1331  *   the third parameter is the parent rule and not the chain.
1332  * - "parent" rules for the above (O_LIMIT_PARENT).
1333  */
1334 static ipfw_dyn_rule *
1335 add_dyn_rule(struct ipfw_flow_id *id, u_int8_t dyn_type, struct ip_fw *rule)
1336 {
1337         ipfw_dyn_rule *r;
1338         int i;
1339
1340         IPFW_DYN_LOCK_ASSERT();
1341
1342         if (ipfw_dyn_v == NULL ||
1343             (dyn_count == 0 && dyn_buckets != curr_dyn_buckets)) {
1344                 realloc_dynamic_table();
1345                 if (ipfw_dyn_v == NULL)
1346                         return NULL; /* failed ! */
1347         }
1348         i = hash_packet(id);
1349
1350         r = uma_zalloc(ipfw_dyn_rule_zone, M_NOWAIT | M_ZERO);
1351         if (r == NULL) {
1352                 printf ("ipfw: sorry cannot allocate state\n");
1353                 return NULL;
1354         }
1355
1356         /* increase refcount on parent, and set pointer */
1357         if (dyn_type == O_LIMIT) {
1358                 ipfw_dyn_rule *parent = (ipfw_dyn_rule *)rule;
1359                 if ( parent->dyn_type != O_LIMIT_PARENT)
1360                         panic("invalid parent");
1361                 parent->count++;
1362                 r->parent = parent;
1363                 rule = parent->rule;
1364         }
1365
1366         r->id = *id;
1367         r->expire = time_uptime + dyn_syn_lifetime;
1368         r->rule = rule;
1369         r->dyn_type = dyn_type;
1370         r->pcnt = r->bcnt = 0;
1371         r->count = 0;
1372
1373         r->bucket = i;
1374         r->next = ipfw_dyn_v[i];
1375         ipfw_dyn_v[i] = r;
1376         dyn_count++;
1377         DEB(printf("ipfw: add dyn entry ty %d 0x%08x %d -> 0x%08x %d, total %d\n",
1378            dyn_type,
1379            (r->id.src_ip), (r->id.src_port),
1380            (r->id.dst_ip), (r->id.dst_port),
1381            dyn_count ); )
1382         return r;
1383 }
1384
1385 /**
1386  * lookup dynamic parent rule using pkt and rule as search keys.
1387  * If the lookup fails, then install one.
1388  */
1389 static ipfw_dyn_rule *
1390 lookup_dyn_parent(struct ipfw_flow_id *pkt, struct ip_fw *rule)
1391 {
1392         ipfw_dyn_rule *q;
1393         int i;
1394
1395         IPFW_DYN_LOCK_ASSERT();
1396
1397         if (ipfw_dyn_v) {
1398                 int is_v6 = IS_IP6_FLOW_ID(pkt);
1399                 i = hash_packet( pkt );
1400                 for (q = ipfw_dyn_v[i] ; q != NULL ; q=q->next)
1401                         if (q->dyn_type == O_LIMIT_PARENT &&
1402                             rule== q->rule &&
1403                             pkt->proto == q->id.proto &&
1404                             pkt->src_port == q->id.src_port &&
1405                             pkt->dst_port == q->id.dst_port &&
1406                             (
1407                                 (is_v6 &&
1408                                  IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
1409                                         &(q->id.src_ip6)) &&
1410                                  IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
1411                                         &(q->id.dst_ip6))) ||
1412                                 (!is_v6 &&
1413                                  pkt->src_ip == q->id.src_ip &&
1414                                  pkt->dst_ip == q->id.dst_ip)
1415                             )
1416                         ) {
1417                                 q->expire = time_uptime + dyn_short_lifetime;
1418                                 DEB(printf("ipfw: lookup_dyn_parent found 0x%p\n",q);)
1419                                 return q;
1420                         }
1421         }
1422         return add_dyn_rule(pkt, O_LIMIT_PARENT, rule);
1423 }
1424
1425 /**
1426  * Install dynamic state for rule type cmd->o.opcode
1427  *
1428  * Returns 1 (failure) if state is not installed because of errors or because
1429  * session limitations are enforced.
1430  */
1431 static int
1432 install_state(struct ip_fw *rule, ipfw_insn_limit *cmd,
1433     struct ip_fw_args *args, uint32_t tablearg)
1434 {
1435         static int last_log;
1436         ipfw_dyn_rule *q;
1437         struct in_addr da;
1438         char src[48], dst[48];
1439
1440         src[0] = '\0';
1441         dst[0] = '\0';
1442
1443         DEB(
1444         printf("ipfw: %s: type %d 0x%08x %u -> 0x%08x %u\n",
1445             __func__, cmd->o.opcode,
1446             (args->f_id.src_ip), (args->f_id.src_port),
1447             (args->f_id.dst_ip), (args->f_id.dst_port));
1448         )
1449
1450         IPFW_DYN_LOCK();
1451
1452         q = lookup_dyn_rule_locked(&args->f_id, NULL, NULL);
1453
1454         if (q != NULL) {        /* should never occur */
1455                 if (last_log != time_uptime) {
1456                         last_log = time_uptime;
1457                         printf("ipfw: %s: entry already present, done\n",
1458                             __func__);
1459                 }
1460                 IPFW_DYN_UNLOCK();
1461                 return (0);
1462         }
1463
1464         if (dyn_count >= dyn_max)
1465                 /* Run out of slots, try to remove any expired rule. */
1466                 remove_dyn_rule(NULL, (ipfw_dyn_rule *)1);
1467
1468         if (dyn_count >= dyn_max) {
1469                 if (last_log != time_uptime) {
1470                         last_log = time_uptime;
1471                         printf("ipfw: %s: Too many dynamic rules\n", __func__);
1472                 }
1473                 IPFW_DYN_UNLOCK();
1474                 return (1);     /* cannot install, notify caller */
1475         }
1476
1477         switch (cmd->o.opcode) {
1478         case O_KEEP_STATE:      /* bidir rule */
1479                 add_dyn_rule(&args->f_id, O_KEEP_STATE, rule);
1480                 break;
1481
1482         case O_LIMIT: {         /* limit number of sessions */
1483                 struct ipfw_flow_id id;
1484                 ipfw_dyn_rule *parent;
1485                 uint32_t conn_limit;
1486                 uint16_t limit_mask = cmd->limit_mask;
1487
1488                 conn_limit = (cmd->conn_limit == IP_FW_TABLEARG) ?
1489                     tablearg : cmd->conn_limit;
1490                   
1491                 DEB(
1492                 if (cmd->conn_limit == IP_FW_TABLEARG)
1493                         printf("ipfw: %s: O_LIMIT rule, conn_limit: %u "
1494                             "(tablearg)\n", __func__, conn_limit);
1495                 else
1496                         printf("ipfw: %s: O_LIMIT rule, conn_limit: %u\n",
1497                             __func__, conn_limit);
1498                 )
1499
1500                 id.dst_ip = id.src_ip = id.dst_port = id.src_port = 0;
1501                 id.proto = args->f_id.proto;
1502                 id.addr_type = args->f_id.addr_type;
1503                 id.fib = M_GETFIB(args->m);
1504
1505                 if (IS_IP6_FLOW_ID (&(args->f_id))) {
1506                         if (limit_mask & DYN_SRC_ADDR)
1507                                 id.src_ip6 = args->f_id.src_ip6;
1508                         if (limit_mask & DYN_DST_ADDR)
1509                                 id.dst_ip6 = args->f_id.dst_ip6;
1510                 } else {
1511                         if (limit_mask & DYN_SRC_ADDR)
1512                                 id.src_ip = args->f_id.src_ip;
1513                         if (limit_mask & DYN_DST_ADDR)
1514                                 id.dst_ip = args->f_id.dst_ip;
1515                 }
1516                 if (limit_mask & DYN_SRC_PORT)
1517                         id.src_port = args->f_id.src_port;
1518                 if (limit_mask & DYN_DST_PORT)
1519                         id.dst_port = args->f_id.dst_port;
1520                 if ((parent = lookup_dyn_parent(&id, rule)) == NULL) {
1521                         printf("ipfw: %s: add parent failed\n", __func__);
1522                         IPFW_DYN_UNLOCK();
1523                         return (1);
1524                 }
1525
1526                 if (parent->count >= conn_limit) {
1527                         /* See if we can remove some expired rule. */
1528                         remove_dyn_rule(rule, parent);
1529                         if (parent->count >= conn_limit) {
1530                                 if (fw_verbose && last_log != time_uptime) {
1531                                         last_log = time_uptime;
1532 #ifdef INET6
1533                                         /*
1534                                          * XXX IPv6 flows are not
1535                                          * supported yet.
1536                                          */
1537                                         if (IS_IP6_FLOW_ID(&(args->f_id))) {
1538                                                 char ip6buf[INET6_ADDRSTRLEN];
1539                                                 snprintf(src, sizeof(src),
1540                                                     "[%s]", ip6_sprintf(ip6buf,
1541                                                         &args->f_id.src_ip6));
1542                                                 snprintf(dst, sizeof(dst),
1543                                                     "[%s]", ip6_sprintf(ip6buf,
1544                                                         &args->f_id.dst_ip6));
1545                                         } else
1546 #endif
1547                                         {
1548                                                 da.s_addr =
1549                                                     htonl(args->f_id.src_ip);
1550                                                 inet_ntoa_r(da, src);
1551                                                 da.s_addr =
1552                                                     htonl(args->f_id.dst_ip);
1553                                                 inet_ntoa_r(da, dst);
1554                                         }
1555                                         log(LOG_SECURITY | LOG_DEBUG,
1556                                             "ipfw: %d %s %s:%u -> %s:%u, %s\n",
1557                                             parent->rule->rulenum,
1558                                             "drop session",
1559                                             src, (args->f_id.src_port),
1560                                             dst, (args->f_id.dst_port),
1561                                             "too many entries");
1562                                 }
1563                                 IPFW_DYN_UNLOCK();
1564                                 return (1);
1565                         }
1566                 }
1567                 add_dyn_rule(&args->f_id, O_LIMIT, (struct ip_fw *)parent);
1568                 break;
1569         }
1570         default:
1571                 printf("ipfw: %s: unknown dynamic rule type %u\n",
1572                     __func__, cmd->o.opcode);
1573                 IPFW_DYN_UNLOCK();
1574                 return (1);
1575         }
1576
1577         /* XXX just set lifetime */
1578         lookup_dyn_rule_locked(&args->f_id, NULL, NULL);
1579
1580         IPFW_DYN_UNLOCK();
1581         return (0);
1582 }
1583
1584 /*
1585  * Generate a TCP packet, containing either a RST or a keepalive.
1586  * When flags & TH_RST, we are sending a RST packet, because of a
1587  * "reset" action matched the packet.
1588  * Otherwise we are sending a keepalive, and flags & TH_
1589  * The 'replyto' mbuf is the mbuf being replied to, if any, and is required
1590  * so that MAC can label the reply appropriately.
1591  */
1592 static struct mbuf *
1593 send_pkt(struct mbuf *replyto, struct ipfw_flow_id *id, u_int32_t seq,
1594     u_int32_t ack, int flags)
1595 {
1596         struct mbuf *m;
1597         struct ip *ip;
1598         struct tcphdr *tcp;
1599
1600         MGETHDR(m, M_DONTWAIT, MT_DATA);
1601         if (m == 0)
1602                 return (NULL);
1603         m->m_pkthdr.rcvif = (struct ifnet *)0;
1604
1605         M_SETFIB(m, id->fib);
1606 #ifdef MAC
1607         if (replyto != NULL)
1608                 mac_create_mbuf_netlayer(replyto, m);
1609         else
1610                 mac_create_mbuf_from_firewall(m);
1611 #else
1612         (void)replyto;          /* don't warn about unused arg */
1613 #endif
1614
1615         m->m_pkthdr.len = m->m_len = sizeof(struct ip) + sizeof(struct tcphdr);
1616         m->m_data += max_linkhdr;
1617
1618         ip = mtod(m, struct ip *);
1619         bzero(ip, m->m_len);
1620         tcp = (struct tcphdr *)(ip + 1); /* no IP options */
1621         ip->ip_p = IPPROTO_TCP;
1622         tcp->th_off = 5;
1623         /*
1624          * Assume we are sending a RST (or a keepalive in the reverse
1625          * direction), swap src and destination addresses and ports.
1626          */
1627         ip->ip_src.s_addr = htonl(id->dst_ip);
1628         ip->ip_dst.s_addr = htonl(id->src_ip);
1629         tcp->th_sport = htons(id->dst_port);
1630         tcp->th_dport = htons(id->src_port);
1631         if (flags & TH_RST) {   /* we are sending a RST */
1632                 if (flags & TH_ACK) {
1633                         tcp->th_seq = htonl(ack);
1634                         tcp->th_ack = htonl(0);
1635                         tcp->th_flags = TH_RST;
1636                 } else {
1637                         if (flags & TH_SYN)
1638                                 seq++;
1639                         tcp->th_seq = htonl(0);
1640                         tcp->th_ack = htonl(seq);
1641                         tcp->th_flags = TH_RST | TH_ACK;
1642                 }
1643         } else {
1644                 /*
1645                  * We are sending a keepalive. flags & TH_SYN determines
1646                  * the direction, forward if set, reverse if clear.
1647                  * NOTE: seq and ack are always assumed to be correct
1648                  * as set by the caller. This may be confusing...
1649                  */
1650                 if (flags & TH_SYN) {
1651                         /*
1652                          * we have to rewrite the correct addresses!
1653                          */
1654                         ip->ip_dst.s_addr = htonl(id->dst_ip);
1655                         ip->ip_src.s_addr = htonl(id->src_ip);
1656                         tcp->th_dport = htons(id->dst_port);
1657                         tcp->th_sport = htons(id->src_port);
1658                 }
1659                 tcp->th_seq = htonl(seq);
1660                 tcp->th_ack = htonl(ack);
1661                 tcp->th_flags = TH_ACK;
1662         }
1663         /*
1664          * set ip_len to the payload size so we can compute
1665          * the tcp checksum on the pseudoheader
1666          * XXX check this, could save a couple of words ?
1667          */
1668         ip->ip_len = htons(sizeof(struct tcphdr));
1669         tcp->th_sum = in_cksum(m, m->m_pkthdr.len);
1670         /*
1671          * now fill fields left out earlier
1672          */
1673         ip->ip_ttl = ip_defttl;
1674         ip->ip_len = m->m_pkthdr.len;
1675         m->m_flags |= M_SKIP_FIREWALL;
1676         return (m);
1677 }
1678
1679 /*
1680  * sends a reject message, consuming the mbuf passed as an argument.
1681  */
1682 static void
1683 send_reject(struct ip_fw_args *args, int code, int ip_len, struct ip *ip)
1684 {
1685
1686 #if 0
1687         /* XXX When ip is not guaranteed to be at mtod() we will
1688          * need to account for this */
1689          * The mbuf will however be thrown away so we can adjust it.
1690          * Remember we did an m_pullup on it already so we
1691          * can make some assumptions about contiguousness.
1692          */
1693         if (args->L3offset)
1694                 m_adj(m, args->L3offset);
1695 #endif
1696         if (code != ICMP_REJECT_RST) { /* Send an ICMP unreach */
1697                 /* We need the IP header in host order for icmp_error(). */
1698                 if (args->eh != NULL) {
1699                         ip->ip_len = ntohs(ip->ip_len);
1700                         ip->ip_off = ntohs(ip->ip_off);
1701                 }
1702                 icmp_error(args->m, ICMP_UNREACH, code, 0L, 0);
1703         } else if (args->f_id.proto == IPPROTO_TCP) {
1704                 struct tcphdr *const tcp =
1705                     L3HDR(struct tcphdr, mtod(args->m, struct ip *));
1706                 if ( (tcp->th_flags & TH_RST) == 0) {
1707                         struct mbuf *m;
1708                         m = send_pkt(args->m, &(args->f_id),
1709                                 ntohl(tcp->th_seq), ntohl(tcp->th_ack),
1710                                 tcp->th_flags | TH_RST);
1711                         if (m != NULL)
1712                                 ip_output(m, NULL, NULL, 0, NULL, NULL);
1713                 }
1714                 m_freem(args->m);
1715         } else
1716                 m_freem(args->m);
1717         args->m = NULL;
1718 }
1719
1720 /**
1721  *
1722  * Given an ip_fw *, lookup_next_rule will return a pointer
1723  * to the next rule, which can be either the jump
1724  * target (for skipto instructions) or the next one in the list (in
1725  * all other cases including a missing jump target).
1726  * The result is also written in the "next_rule" field of the rule.
1727  * Backward jumps are not allowed, so start looking from the next
1728  * rule...
1729  *
1730  * This never returns NULL -- in case we do not have an exact match,
1731  * the next rule is returned. When the ruleset is changed,
1732  * pointers are flushed so we are always correct.
1733  */
1734
1735 static struct ip_fw *
1736 lookup_next_rule(struct ip_fw *me, u_int32_t tablearg)
1737 {
1738         struct ip_fw *rule = NULL;
1739         ipfw_insn *cmd;
1740         u_int16_t       rulenum;
1741
1742         /* look for action, in case it is a skipto */
1743         cmd = ACTION_PTR(me);
1744         if (cmd->opcode == O_LOG)
1745                 cmd += F_LEN(cmd);
1746         if (cmd->opcode == O_ALTQ)
1747                 cmd += F_LEN(cmd);
1748         if (cmd->opcode == O_TAG)
1749                 cmd += F_LEN(cmd);
1750         if (cmd->opcode == O_SKIPTO ) {
1751                 if (tablearg != 0) {
1752                         rulenum = (u_int16_t)tablearg;
1753                 } else {
1754                         rulenum = cmd->arg1;
1755                 }
1756                 for (rule = me->next; rule ; rule = rule->next) {
1757                         if (rule->rulenum >= rulenum) {
1758                                 break;
1759                         }
1760                 }
1761         }
1762         if (rule == NULL)                       /* failure or not a skipto */
1763                 rule = me->next;
1764         me->next_rule = rule;
1765         return rule;
1766 }
1767
1768 static int
1769 add_table_entry(struct ip_fw_chain *ch, uint16_t tbl, in_addr_t addr,
1770     uint8_t mlen, uint32_t value)
1771 {
1772         struct radix_node_head *rnh;
1773         struct table_entry *ent;
1774         struct radix_node *rn;
1775
1776         if (tbl >= IPFW_TABLES_MAX)
1777                 return (EINVAL);
1778         rnh = ch->tables[tbl];
1779         ent = malloc(sizeof(*ent), M_IPFW_TBL, M_NOWAIT | M_ZERO);
1780         if (ent == NULL)
1781                 return (ENOMEM);
1782         ent->value = value;
1783         ent->addr.sin_len = ent->mask.sin_len = 8;
1784         ent->mask.sin_addr.s_addr = htonl(mlen ? ~((1 << (32 - mlen)) - 1) : 0);
1785         ent->addr.sin_addr.s_addr = addr & ent->mask.sin_addr.s_addr;
1786         IPFW_WLOCK(ch);
1787         rn = rnh->rnh_addaddr(&ent->addr, &ent->mask, rnh, (void *)ent);
1788         if (rn == NULL) {
1789                 IPFW_WUNLOCK(ch);
1790                 free(ent, M_IPFW_TBL);
1791                 return (EEXIST);
1792         }
1793         IPFW_WUNLOCK(ch);
1794         return (0);
1795 }
1796
1797 static int
1798 del_table_entry(struct ip_fw_chain *ch, uint16_t tbl, in_addr_t addr,
1799     uint8_t mlen)
1800 {
1801         struct radix_node_head *rnh;
1802         struct table_entry *ent;
1803         struct sockaddr_in sa, mask;
1804
1805         if (tbl >= IPFW_TABLES_MAX)
1806                 return (EINVAL);
1807         rnh = ch->tables[tbl];
1808         sa.sin_len = mask.sin_len = 8;
1809         mask.sin_addr.s_addr = htonl(mlen ? ~((1 << (32 - mlen)) - 1) : 0);
1810         sa.sin_addr.s_addr = addr & mask.sin_addr.s_addr;
1811         IPFW_WLOCK(ch);
1812         ent = (struct table_entry *)rnh->rnh_deladdr(&sa, &mask, rnh);
1813         if (ent == NULL) {
1814                 IPFW_WUNLOCK(ch);
1815                 return (ESRCH);
1816         }
1817         IPFW_WUNLOCK(ch);
1818         free(ent, M_IPFW_TBL);
1819         return (0);
1820 }
1821
1822 static int
1823 flush_table_entry(struct radix_node *rn, void *arg)
1824 {
1825         struct radix_node_head * const rnh = arg;
1826         struct table_entry *ent;
1827
1828         ent = (struct table_entry *)
1829             rnh->rnh_deladdr(rn->rn_key, rn->rn_mask, rnh);
1830         if (ent != NULL)
1831                 free(ent, M_IPFW_TBL);
1832         return (0);
1833 }
1834
1835 static int
1836 flush_table(struct ip_fw_chain *ch, uint16_t tbl)
1837 {
1838         struct radix_node_head *rnh;
1839
1840         IPFW_WLOCK_ASSERT(ch);
1841
1842         if (tbl >= IPFW_TABLES_MAX)
1843                 return (EINVAL);
1844         rnh = ch->tables[tbl];
1845         KASSERT(rnh != NULL, ("NULL IPFW table"));
1846         rnh->rnh_walktree(rnh, flush_table_entry, rnh);
1847         return (0);
1848 }
1849
1850 static void
1851 flush_tables(struct ip_fw_chain *ch)
1852 {
1853         uint16_t tbl;
1854
1855         IPFW_WLOCK_ASSERT(ch);
1856
1857         for (tbl = 0; tbl < IPFW_TABLES_MAX; tbl++)
1858                 flush_table(ch, tbl);
1859 }
1860
1861 static int
1862 init_tables(struct ip_fw_chain *ch)
1863
1864         int i;
1865         uint16_t j;
1866
1867         for (i = 0; i < IPFW_TABLES_MAX; i++) {
1868                 if (!rn_inithead((void **)&ch->tables[i], 32)) {
1869                         for (j = 0; j < i; j++) {
1870                                 (void) flush_table(ch, j);
1871                         }
1872                         return (ENOMEM);
1873                 }
1874         }
1875         return (0);
1876 }
1877
1878 static int
1879 lookup_table(struct ip_fw_chain *ch, uint16_t tbl, in_addr_t addr,
1880     uint32_t *val)
1881 {
1882         struct radix_node_head *rnh;
1883         struct table_entry *ent;
1884         struct sockaddr_in sa;
1885
1886         if (tbl >= IPFW_TABLES_MAX)
1887                 return (0);
1888         rnh = ch->tables[tbl];
1889         sa.sin_len = 8;
1890         sa.sin_addr.s_addr = addr;
1891         ent = (struct table_entry *)(rnh->rnh_lookup(&sa, NULL, rnh));
1892         if (ent != NULL) {
1893                 *val = ent->value;
1894                 return (1);
1895         }
1896         return (0);
1897 }
1898
1899 static int
1900 count_table_entry(struct radix_node *rn, void *arg)
1901 {
1902         u_int32_t * const cnt = arg;
1903
1904         (*cnt)++;
1905         return (0);
1906 }
1907
1908 static int
1909 count_table(struct ip_fw_chain *ch, uint32_t tbl, uint32_t *cnt)
1910 {
1911         struct radix_node_head *rnh;
1912
1913         if (tbl >= IPFW_TABLES_MAX)
1914                 return (EINVAL);
1915         rnh = ch->tables[tbl];
1916         *cnt = 0;
1917         rnh->rnh_walktree(rnh, count_table_entry, cnt);
1918         return (0);
1919 }
1920
1921 static int
1922 dump_table_entry(struct radix_node *rn, void *arg)
1923 {
1924         struct table_entry * const n = (struct table_entry *)rn;
1925         ipfw_table * const tbl = arg;
1926         ipfw_table_entry *ent;
1927
1928         if (tbl->cnt == tbl->size)
1929                 return (1);
1930         ent = &tbl->ent[tbl->cnt];
1931         ent->tbl = tbl->tbl;
1932         if (in_nullhost(n->mask.sin_addr))
1933                 ent->masklen = 0;
1934         else
1935                 ent->masklen = 33 - ffs(ntohl(n->mask.sin_addr.s_addr));
1936         ent->addr = n->addr.sin_addr.s_addr;
1937         ent->value = n->value;
1938         tbl->cnt++;
1939         return (0);
1940 }
1941
1942 static int
1943 dump_table(struct ip_fw_chain *ch, ipfw_table *tbl)
1944 {
1945         struct radix_node_head *rnh;
1946
1947         if (tbl->tbl >= IPFW_TABLES_MAX)
1948                 return (EINVAL);
1949         rnh = ch->tables[tbl->tbl];
1950         tbl->cnt = 0;
1951         rnh->rnh_walktree(rnh, dump_table_entry, tbl);
1952         return (0);
1953 }
1954
1955 static void
1956 fill_ugid_cache(struct inpcb *inp, struct ip_fw_ugid *ugp)
1957 {
1958         struct ucred *cr;
1959
1960         cr = inp->inp_cred;
1961         ugp->fw_prid = jailed(cr) ? cr->cr_prison->pr_id : -1;
1962         ugp->fw_uid = cr->cr_uid;
1963         ugp->fw_ngroups = cr->cr_ngroups;
1964         bcopy(cr->cr_groups, ugp->fw_groups, sizeof(ugp->fw_groups));
1965 }
1966
1967 static int
1968 check_uidgid(ipfw_insn_u32 *insn, int proto, struct ifnet *oif,
1969     struct in_addr dst_ip, u_int16_t dst_port, struct in_addr src_ip,
1970     u_int16_t src_port, struct ip_fw_ugid *ugp, int *ugid_lookupp,
1971     struct inpcb *inp)
1972 {
1973         struct inpcbinfo *pi;
1974         int wildcard;
1975         struct inpcb *pcb;
1976         int match;
1977         gid_t *gp;
1978
1979         /*
1980          * Check to see if the UDP or TCP stack supplied us with
1981          * the PCB. If so, rather then holding a lock and looking
1982          * up the PCB, we can use the one that was supplied.
1983          */
1984         if (inp && *ugid_lookupp == 0) {
1985                 INP_LOCK_ASSERT(inp);
1986                 if (inp->inp_socket != NULL) {
1987                         fill_ugid_cache(inp, ugp);
1988                         *ugid_lookupp = 1;
1989                 } else
1990                         *ugid_lookupp = -1;
1991         }
1992         /*
1993          * If we have already been here and the packet has no
1994          * PCB entry associated with it, then we can safely
1995          * assume that this is a no match.
1996          */
1997         if (*ugid_lookupp == -1)
1998                 return (0);
1999         if (proto == IPPROTO_TCP) {
2000                 wildcard = 0;
2001                 pi = &tcbinfo;
2002         } else if (proto == IPPROTO_UDP) {
2003                 wildcard = INPLOOKUP_WILDCARD;
2004                 pi = &udbinfo;
2005         } else
2006                 return 0;
2007         match = 0;
2008         if (*ugid_lookupp == 0) {
2009                 INP_INFO_RLOCK(pi);
2010                 pcb =  (oif) ?
2011                         in_pcblookup_hash(pi,
2012                                 dst_ip, htons(dst_port),
2013                                 src_ip, htons(src_port),
2014                                 wildcard, oif) :
2015                         in_pcblookup_hash(pi,
2016                                 src_ip, htons(src_port),
2017                                 dst_ip, htons(dst_port),
2018                                 wildcard, NULL);
2019                 if (pcb != NULL) {
2020                         fill_ugid_cache(pcb, ugp);
2021                         *ugid_lookupp = 1;
2022                 }
2023                 INP_INFO_RUNLOCK(pi);
2024                 if (*ugid_lookupp == 0) {
2025                         /*
2026                          * If the lookup did not yield any results, there
2027                          * is no sense in coming back and trying again. So
2028                          * we can set lookup to -1 and ensure that we wont
2029                          * bother the pcb system again.
2030                          */
2031                         *ugid_lookupp = -1;
2032                         return (0);
2033                 }
2034         } 
2035         if (insn->o.opcode == O_UID)
2036                 match = (ugp->fw_uid == (uid_t)insn->d[0]);
2037         else if (insn->o.opcode == O_GID) {
2038                 for (gp = ugp->fw_groups;
2039                         gp < &ugp->fw_groups[ugp->fw_ngroups]; gp++)
2040                         if (*gp == (gid_t)insn->d[0]) {
2041                                 match = 1;
2042                                 break;
2043                         }
2044         } else if (insn->o.opcode == O_JAIL)
2045                 match = (ugp->fw_prid == (int)insn->d[0]);
2046         return match;
2047 }
2048
2049 /*
2050  * The main check routine for the firewall.
2051  *
2052  * All arguments are in args so we can modify them and return them
2053  * back to the caller.
2054  *
2055  * Parameters:
2056  *
2057  *      args->m (in/out) The packet; we set to NULL when/if we nuke it.
2058  *              Starts with the IP header.
2059  *      args->eh (in)   Mac header if present, or NULL for layer3 packet.
2060  *      args->L3offset  Number of bytes bypassed if we came from L2.
2061  *                      e.g. often sizeof(eh)  ** NOTYET **
2062  *      args->oif       Outgoing interface, or NULL if packet is incoming.
2063  *              The incoming interface is in the mbuf. (in)
2064  *      args->divert_rule (in/out)
2065  *              Skip up to the first rule past this rule number;
2066  *              upon return, non-zero port number for divert or tee.
2067  *
2068  *      args->rule      Pointer to the last matching rule (in/out)
2069  *      args->next_hop  Socket we are forwarding to (out).
2070  *      args->f_id      Addresses grabbed from the packet (out)
2071  *      args->cookie    a cookie depending on rule action
2072  *
2073  * Return value:
2074  *
2075  *      IP_FW_PASS      the packet must be accepted
2076  *      IP_FW_DENY      the packet must be dropped
2077  *      IP_FW_DIVERT    divert packet, port in m_tag
2078  *      IP_FW_TEE       tee packet, port in m_tag
2079  *      IP_FW_DUMMYNET  to dummynet, pipe in args->cookie
2080  *      IP_FW_NETGRAPH  into netgraph, cookie args->cookie
2081  *
2082  */
2083 int
2084 ipfw_chk(struct ip_fw_args *args)
2085 {
2086         /*
2087          * Local variables holding state during the processing of a packet:
2088          *
2089          * IMPORTANT NOTE: to speed up the processing of rules, there
2090          * are some assumption on the values of the variables, which
2091          * are documented here. Should you change them, please check
2092          * the implementation of the various instructions to make sure
2093          * that they still work.
2094          *
2095          * args->eh     The MAC header. It is non-null for a layer2
2096          *      packet, it is NULL for a layer-3 packet.
2097          * **notyet**
2098          * args->L3offset Offset in the packet to the L3 (IP or equiv.) header.
2099          *
2100          * m | args->m  Pointer to the mbuf, as received from the caller.
2101          *      It may change if ipfw_chk() does an m_pullup, or if it
2102          *      consumes the packet because it calls send_reject().
2103          *      XXX This has to change, so that ipfw_chk() never modifies
2104          *      or consumes the buffer.
2105          * ip   is the beginning of the ip(4 or 6) header.
2106          *      Calculated by adding the L3offset to the start of data.
2107          *      (Until we start using L3offset, the packet is
2108          *      supposed to start with the ip header).
2109          */
2110         struct mbuf *m = args->m;
2111         struct ip *ip = mtod(m, struct ip *);
2112
2113         /*
2114          * For rules which contain uid/gid or jail constraints, cache
2115          * a copy of the users credentials after the pcb lookup has been
2116          * executed. This will speed up the processing of rules with
2117          * these types of constraints, as well as decrease contention
2118          * on pcb related locks.
2119          */
2120         struct ip_fw_ugid fw_ugid_cache;
2121         int ugid_lookup = 0;
2122
2123         /*
2124          * divinput_flags       If non-zero, set to the IP_FW_DIVERT_*_FLAG
2125          *      associated with a packet input on a divert socket.  This
2126          *      will allow to distinguish traffic and its direction when
2127          *      it originates from a divert socket.
2128          */
2129         u_int divinput_flags = 0;
2130
2131         /*
2132          * oif | args->oif      If NULL, ipfw_chk has been called on the
2133          *      inbound path (ether_input, ip_input).
2134          *      If non-NULL, ipfw_chk has been called on the outbound path
2135          *      (ether_output, ip_output).
2136          */
2137         struct ifnet *oif = args->oif;
2138
2139         struct ip_fw *f = NULL;         /* matching rule */
2140         int retval = 0;
2141
2142         /*
2143          * hlen The length of the IP header.
2144          */
2145         u_int hlen = 0;         /* hlen >0 means we have an IP pkt */
2146
2147         /*
2148          * offset       The offset of a fragment. offset != 0 means that
2149          *      we have a fragment at this offset of an IPv4 packet.
2150          *      offset == 0 means that (if this is an IPv4 packet)
2151          *      this is the first or only fragment.
2152          *      For IPv6 offset == 0 means there is no Fragment Header. 
2153          *      If offset != 0 for IPv6 always use correct mask to
2154          *      get the correct offset because we add IP6F_MORE_FRAG
2155          *      to be able to dectect the first fragment which would
2156          *      otherwise have offset = 0.
2157          */
2158         u_short offset = 0;
2159
2160         /*
2161          * Local copies of addresses. They are only valid if we have
2162          * an IP packet.
2163          *
2164          * proto        The protocol. Set to 0 for non-ip packets,
2165          *      or to the protocol read from the packet otherwise.
2166          *      proto != 0 means that we have an IPv4 packet.
2167          *
2168          * src_port, dst_port   port numbers, in HOST format. Only
2169          *      valid for TCP and UDP packets.
2170          *
2171          * src_ip, dst_ip       ip addresses, in NETWORK format.
2172          *      Only valid for IPv4 packets.
2173          */
2174         u_int8_t proto;
2175         u_int16_t src_port = 0, dst_port = 0;   /* NOTE: host format    */
2176         struct in_addr src_ip, dst_ip;          /* NOTE: network format */
2177         u_int16_t ip_len=0;
2178         int pktlen;
2179         u_int16_t       etype = 0;      /* Host order stored ether type */
2180
2181         /*
2182          * dyn_dir = MATCH_UNKNOWN when rules unchecked,
2183          *      MATCH_NONE when checked and not matched (q = NULL),
2184          *      MATCH_FORWARD or MATCH_REVERSE otherwise (q != NULL)
2185          */
2186         int dyn_dir = MATCH_UNKNOWN;
2187         ipfw_dyn_rule *q = NULL;
2188         struct ip_fw_chain *chain = &layer3_chain;
2189         struct m_tag *mtag;
2190
2191         /*
2192          * We store in ulp a pointer to the upper layer protocol header.
2193          * In the ipv4 case this is easy to determine from the header,
2194          * but for ipv6 we might have some additional headers in the middle.
2195          * ulp is NULL if not found.
2196          */
2197         void *ulp = NULL;               /* upper layer protocol pointer. */
2198         /* XXX ipv6 variables */
2199         int is_ipv6 = 0;
2200         u_int16_t ext_hd = 0;   /* bits vector for extension header filtering */
2201         /* end of ipv6 variables */
2202         int is_ipv4 = 0;
2203
2204         if (m->m_flags & M_SKIP_FIREWALL)
2205                 return (IP_FW_PASS);    /* accept */
2206
2207         dst_ip.s_addr = 0;              /* make sure it is initialized */
2208         src_ip.s_addr = 0;              /* make sure it is initialized */
2209         pktlen = m->m_pkthdr.len;
2210         args->f_id.fib = M_GETFIB(m); /* note mbuf not altered) */
2211         proto = args->f_id.proto = 0;   /* mark f_id invalid */
2212                 /* XXX 0 is a valid proto: IP/IPv6 Hop-by-Hop Option */
2213
2214 /*
2215  * PULLUP_TO(len, p, T) makes sure that len + sizeof(T) is contiguous,
2216  * then it sets p to point at the offset "len" in the mbuf. WARNING: the
2217  * pointer might become stale after other pullups (but we never use it
2218  * this way).
2219  */
2220 #define PULLUP_TO(_len, p, T)                                           \
2221 do {                                                                    \
2222         int x = (_len) + sizeof(T);                                     \
2223         if ((m)->m_len < x) {                                           \
2224                 args->m = m = m_pullup(m, x);                           \
2225                 if (m == NULL)                                          \
2226                         goto pullup_failed;                             \
2227         }                                                               \
2228         p = (mtod(m, char *) + (_len));                                 \
2229 } while (0)
2230
2231         /*
2232          * if we have an ether header,
2233          */
2234         if (args->eh)
2235                 etype = ntohs(args->eh->ether_type);
2236
2237         /* Identify IP packets and fill up variables. */
2238         if (pktlen >= sizeof(struct ip6_hdr) &&
2239             (args->eh == NULL || etype == ETHERTYPE_IPV6) && ip->ip_v == 6) {
2240                 struct ip6_hdr *ip6 = (struct ip6_hdr *)ip;
2241                 is_ipv6 = 1;
2242                 args->f_id.addr_type = 6;
2243                 hlen = sizeof(struct ip6_hdr);
2244                 proto = ip6->ip6_nxt;
2245
2246                 /* Search extension headers to find upper layer protocols */
2247                 while (ulp == NULL) {
2248                         switch (proto) {
2249                         case IPPROTO_ICMPV6:
2250                                 PULLUP_TO(hlen, ulp, struct icmp6_hdr);
2251                                 args->f_id.flags = ICMP6(ulp)->icmp6_type;
2252                                 break;
2253
2254                         case IPPROTO_TCP:
2255                                 PULLUP_TO(hlen, ulp, struct tcphdr);
2256                                 dst_port = TCP(ulp)->th_dport;
2257                                 src_port = TCP(ulp)->th_sport;
2258                                 args->f_id.flags = TCP(ulp)->th_flags;
2259                                 break;
2260
2261                         case IPPROTO_SCTP:
2262                                 PULLUP_TO(hlen, ulp, struct sctphdr);
2263                                 src_port = SCTP(ulp)->src_port;
2264                                 dst_port = SCTP(ulp)->dest_port;
2265                                 break;
2266
2267                         case IPPROTO_UDP:
2268                                 PULLUP_TO(hlen, ulp, struct udphdr);
2269                                 dst_port = UDP(ulp)->uh_dport;
2270                                 src_port = UDP(ulp)->uh_sport;
2271                                 break;
2272
2273                         case IPPROTO_HOPOPTS:   /* RFC 2460 */
2274                                 PULLUP_TO(hlen, ulp, struct ip6_hbh);
2275                                 ext_hd |= EXT_HOPOPTS;
2276                                 hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3;
2277                                 proto = ((struct ip6_hbh *)ulp)->ip6h_nxt;
2278                                 ulp = NULL;
2279                                 break;
2280
2281                         case IPPROTO_ROUTING:   /* RFC 2460 */
2282                                 PULLUP_TO(hlen, ulp, struct ip6_rthdr);
2283                                 switch (((struct ip6_rthdr *)ulp)->ip6r_type) {
2284                                 case 0:
2285                                         ext_hd |= EXT_RTHDR0;
2286                                         break;
2287                                 case 2:
2288                                         ext_hd |= EXT_RTHDR2;
2289                                         break;
2290                                 default:
2291                                         printf("IPFW2: IPV6 - Unknown Routing "
2292                                             "Header type(%d)\n",
2293                                             ((struct ip6_rthdr *)ulp)->ip6r_type);
2294                                         if (fw_deny_unknown_exthdrs)
2295                                             return (IP_FW_DENY);
2296                                         break;
2297                                 }
2298                                 ext_hd |= EXT_ROUTING;
2299                                 hlen += (((struct ip6_rthdr *)ulp)->ip6r_len + 1) << 3;
2300                                 proto = ((struct ip6_rthdr *)ulp)->ip6r_nxt;
2301                                 ulp = NULL;
2302                                 break;
2303
2304                         case IPPROTO_FRAGMENT:  /* RFC 2460 */
2305                                 PULLUP_TO(hlen, ulp, struct ip6_frag);
2306                                 ext_hd |= EXT_FRAGMENT;
2307                                 hlen += sizeof (struct ip6_frag);
2308                                 proto = ((struct ip6_frag *)ulp)->ip6f_nxt;
2309                                 offset = ((struct ip6_frag *)ulp)->ip6f_offlg &
2310                                         IP6F_OFF_MASK;
2311                                 /* Add IP6F_MORE_FRAG for offset of first
2312                                  * fragment to be != 0. */
2313                                 offset |= ((struct ip6_frag *)ulp)->ip6f_offlg &
2314                                         IP6F_MORE_FRAG;
2315                                 if (offset == 0) {
2316                                         printf("IPFW2: IPV6 - Invalid Fragment "
2317                                             "Header\n");
2318                                         if (fw_deny_unknown_exthdrs)
2319                                             return (IP_FW_DENY);
2320                                         break;
2321                                 }
2322                                 args->f_id.frag_id6 =
2323                                     ntohl(((struct ip6_frag *)ulp)->ip6f_ident);
2324                                 ulp = NULL;
2325                                 break;
2326
2327                         case IPPROTO_DSTOPTS:   /* RFC 2460 */
2328                                 PULLUP_TO(hlen, ulp, struct ip6_hbh);
2329                                 ext_hd |= EXT_DSTOPTS;
2330                                 hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3;
2331                                 proto = ((struct ip6_hbh *)ulp)->ip6h_nxt;
2332                                 ulp = NULL;
2333                                 break;
2334
2335                         case IPPROTO_AH:        /* RFC 2402 */
2336                                 PULLUP_TO(hlen, ulp, struct ip6_ext);
2337                                 ext_hd |= EXT_AH;
2338                                 hlen += (((struct ip6_ext *)ulp)->ip6e_len + 2) << 2;
2339                                 proto = ((struct ip6_ext *)ulp)->ip6e_nxt;
2340                                 ulp = NULL;
2341                                 break;
2342
2343                         case IPPROTO_ESP:       /* RFC 2406 */
2344                                 PULLUP_TO(hlen, ulp, uint32_t); /* SPI, Seq# */
2345                                 /* Anything past Seq# is variable length and
2346                                  * data past this ext. header is encrypted. */
2347                                 ext_hd |= EXT_ESP;
2348                                 break;
2349
2350                         case IPPROTO_NONE:      /* RFC 2460 */
2351                                 /*
2352                                  * Packet ends here, and IPv6 header has
2353                                  * already been pulled up. If ip6e_len!=0
2354                                  * then octets must be ignored.
2355                                  */
2356                                 ulp = ip; /* non-NULL to get out of loop. */
2357                                 break;
2358
2359                         case IPPROTO_OSPFIGP:
2360                                 /* XXX OSPF header check? */
2361                                 PULLUP_TO(hlen, ulp, struct ip6_ext);
2362                                 break;
2363
2364                         case IPPROTO_PIM:
2365                                 /* XXX PIM header check? */
2366                                 PULLUP_TO(hlen, ulp, struct pim);
2367                                 break;
2368
2369                         case IPPROTO_CARP:
2370                                 PULLUP_TO(hlen, ulp, struct carp_header);
2371                                 if (((struct carp_header *)ulp)->carp_version !=
2372                                     CARP_VERSION) 
2373                                         return (IP_FW_DENY);
2374                                 if (((struct carp_header *)ulp)->carp_type !=
2375                                     CARP_ADVERTISEMENT) 
2376                                         return (IP_FW_DENY);
2377                                 break;
2378
2379                         case IPPROTO_IPV6:      /* RFC 2893 */
2380                                 PULLUP_TO(hlen, ulp, struct ip6_hdr);
2381                                 break;
2382
2383                         case IPPROTO_IPV4:      /* RFC 2893 */
2384                                 PULLUP_TO(hlen, ulp, struct ip);
2385                                 break;
2386
2387                         default:
2388                                 printf("IPFW2: IPV6 - Unknown Extension "
2389                                     "Header(%d), ext_hd=%x\n", proto, ext_hd);
2390                                 if (fw_deny_unknown_exthdrs)
2391                                     return (IP_FW_DENY);
2392                                 PULLUP_TO(hlen, ulp, struct ip6_ext);
2393                                 break;
2394                         } /*switch */
2395                 }
2396                 ip = mtod(m, struct ip *);
2397                 ip6 = (struct ip6_hdr *)ip;
2398                 args->f_id.src_ip6 = ip6->ip6_src;
2399                 args->f_id.dst_ip6 = ip6->ip6_dst;
2400                 args->f_id.src_ip = 0;
2401                 args->f_id.dst_ip = 0;
2402                 args->f_id.flow_id6 = ntohl(ip6->ip6_flow);
2403         } else if (pktlen >= sizeof(struct ip) &&
2404             (args->eh == NULL || etype == ETHERTYPE_IP) && ip->ip_v == 4) {
2405                 is_ipv4 = 1;
2406                 hlen = ip->ip_hl << 2;
2407                 args->f_id.addr_type = 4;
2408
2409                 /*
2410                  * Collect parameters into local variables for faster matching.
2411                  */
2412                 proto = ip->ip_p;
2413                 src_ip = ip->ip_src;
2414                 dst_ip = ip->ip_dst;
2415                 if (args->eh != NULL) { /* layer 2 packets are as on the wire */
2416                         offset = ntohs(ip->ip_off) & IP_OFFMASK;
2417                         ip_len = ntohs(ip->ip_len);
2418                 } else {
2419                         offset = ip->ip_off & IP_OFFMASK;
2420                         ip_len = ip->ip_len;
2421                 }
2422                 pktlen = ip_len < pktlen ? ip_len : pktlen;
2423
2424                 if (offset == 0) {
2425                         switch (proto) {
2426                         case IPPROTO_TCP:
2427                                 PULLUP_TO(hlen, ulp, struct tcphdr);
2428                                 dst_port = TCP(ulp)->th_dport;
2429                                 src_port = TCP(ulp)->th_sport;
2430                                 args->f_id.flags = TCP(ulp)->th_flags;
2431                                 break;
2432
2433                         case IPPROTO_UDP:
2434                                 PULLUP_TO(hlen, ulp, struct udphdr);
2435                                 dst_port = UDP(ulp)->uh_dport;
2436                                 src_port = UDP(ulp)->uh_sport;
2437                                 break;
2438
2439                         case IPPROTO_ICMP:
2440                                 PULLUP_TO(hlen, ulp, struct icmphdr);
2441                                 args->f_id.flags = ICMP(ulp)->icmp_type;
2442                                 break;
2443
2444                         default:
2445                                 break;
2446                         }
2447                 }
2448
2449                 ip = mtod(m, struct ip *);
2450                 args->f_id.src_ip = ntohl(src_ip.s_addr);
2451                 args->f_id.dst_ip = ntohl(dst_ip.s_addr);
2452         }
2453 #undef PULLUP_TO
2454         if (proto) { /* we may have port numbers, store them */
2455                 args->f_id.proto = proto;
2456                 args->f_id.src_port = src_port = ntohs(src_port);
2457                 args->f_id.dst_port = dst_port = ntohs(dst_port);
2458         }
2459
2460         IPFW_RLOCK(chain);
2461         mtag = m_tag_find(m, PACKET_TAG_DIVERT, NULL);
2462         if (args->rule) {
2463                 /*
2464                  * Packet has already been tagged. Look for the next rule
2465                  * to restart processing.
2466                  *
2467                  * If fw_one_pass != 0 then just accept it.
2468                  * XXX should not happen here, but optimized out in
2469                  * the caller.
2470                  */
2471                 if (fw_one_pass) {
2472                         IPFW_RUNLOCK(chain);
2473                         return (IP_FW_PASS);
2474                 }
2475
2476                 f = args->rule->next_rule;
2477                 if (f == NULL)
2478                         f = lookup_next_rule(args->rule, 0);
2479         } else {
2480                 /*
2481                  * Find the starting rule. It can be either the first
2482                  * one, or the one after divert_rule if asked so.
2483                  */
2484                 int skipto = mtag ? divert_cookie(mtag) : 0;
2485
2486                 f = chain->rules;
2487                 if (args->eh == NULL && skipto != 0) {
2488                         if (skipto >= IPFW_DEFAULT_RULE) {
2489                                 IPFW_RUNLOCK(chain);
2490                                 return (IP_FW_DENY); /* invalid */
2491                         }
2492                         while (f && f->rulenum <= skipto)
2493                                 f = f->next;
2494                         if (f == NULL) {        /* drop packet */
2495                                 IPFW_RUNLOCK(chain);
2496                                 return (IP_FW_DENY);
2497                         }
2498                 }
2499         }
2500         /* reset divert rule to avoid confusion later */
2501         if (mtag) {
2502                 divinput_flags = divert_info(mtag) &
2503                     (IP_FW_DIVERT_OUTPUT_FLAG | IP_FW_DIVERT_LOOPBACK_FLAG);
2504                 m_tag_delete(m, mtag);
2505         }
2506
2507         /*
2508          * Now scan the rules, and parse microinstructions for each rule.
2509          */
2510         for (; f; f = f->next) {
2511                 ipfw_insn *cmd;
2512                 uint32_t tablearg = 0;
2513                 int l, cmdlen, skip_or; /* skip rest of OR block */
2514
2515 again:
2516                 if (set_disable & (1 << f->set) )
2517                         continue;
2518
2519                 skip_or = 0;
2520                 for (l = f->cmd_len, cmd = f->cmd ; l > 0 ;
2521                     l -= cmdlen, cmd += cmdlen) {
2522                         int match;
2523
2524                         /*
2525                          * check_body is a jump target used when we find a
2526                          * CHECK_STATE, and need to jump to the body of
2527                          * the target rule.
2528                          */
2529
2530 check_body:
2531                         cmdlen = F_LEN(cmd);
2532                         /*
2533                          * An OR block (insn_1 || .. || insn_n) has the
2534                          * F_OR bit set in all but the last instruction.
2535                          * The first match will set "skip_or", and cause
2536                          * the following instructions to be skipped until
2537                          * past the one with the F_OR bit clear.
2538                          */
2539                         if (skip_or) {          /* skip this instruction */
2540                                 if ((cmd->len & F_OR) == 0)
2541                                         skip_or = 0;    /* next one is good */
2542                                 continue;
2543                         }
2544                         match = 0; /* set to 1 if we succeed */
2545
2546                         switch (cmd->opcode) {
2547                         /*
2548                          * The first set of opcodes compares the packet's
2549                          * fields with some pattern, setting 'match' if a
2550                          * match is found. At the end of the loop there is
2551                          * logic to deal with F_NOT and F_OR flags associated
2552                          * with the opcode.
2553                          */
2554                         case O_NOP:
2555                                 match = 1;
2556                                 break;
2557
2558                         case O_FORWARD_MAC:
2559                                 printf("ipfw: opcode %d unimplemented\n",
2560                                     cmd->opcode);
2561                                 break;
2562
2563                         case O_GID:
2564                         case O_UID:
2565                         case O_JAIL:
2566                                 /*
2567                                  * We only check offset == 0 && proto != 0,
2568                                  * as this ensures that we have a
2569                                  * packet with the ports info.
2570                                  */
2571                                 if (offset!=0)
2572                                         break;
2573                                 if (is_ipv6) /* XXX to be fixed later */
2574                                         break;
2575                                 if (proto == IPPROTO_TCP ||
2576                                     proto == IPPROTO_UDP)
2577                                         match = check_uidgid(
2578                                                     (ipfw_insn_u32 *)cmd,
2579                                                     proto, oif,
2580                                                     dst_ip, dst_port,
2581                                                     src_ip, src_port, &fw_ugid_cache,
2582                                                     &ugid_lookup, args->inp);
2583                                 break;
2584
2585                         case O_RECV:
2586                                 match = iface_match(m->m_pkthdr.rcvif,
2587                                     (ipfw_insn_if *)cmd);
2588                                 break;
2589
2590                         case O_XMIT:
2591                                 match = iface_match(oif, (ipfw_insn_if *)cmd);
2592                                 break;
2593
2594                         case O_VIA:
2595                                 match = iface_match(oif ? oif :
2596                                     m->m_pkthdr.rcvif, (ipfw_insn_if *)cmd);
2597                                 break;
2598
2599                         case O_MACADDR2:
2600                                 if (args->eh != NULL) { /* have MAC header */
2601                                         u_int32_t *want = (u_int32_t *)
2602                                                 ((ipfw_insn_mac *)cmd)->addr;
2603                                         u_int32_t *mask = (u_int32_t *)
2604                                                 ((ipfw_insn_mac *)cmd)->mask;
2605                                         u_int32_t *hdr = (u_int32_t *)args->eh;
2606
2607                                         match =
2608                                             ( want[0] == (hdr[0] & mask[0]) &&
2609                                               want[1] == (hdr[1] & mask[1]) &&
2610                                               want[2] == (hdr[2] & mask[2]) );
2611                                 }
2612                                 break;
2613
2614                         case O_MAC_TYPE:
2615                                 if (args->eh != NULL) {
2616                                         u_int16_t *p =
2617                                             ((ipfw_insn_u16 *)cmd)->ports;
2618                                         int i;
2619
2620                                         for (i = cmdlen - 1; !match && i>0;
2621                                             i--, p += 2)
2622                                                 match = (etype >= p[0] &&
2623                                                     etype <= p[1]);
2624                                 }
2625                                 break;
2626
2627                         case O_FRAG:
2628                                 match = (offset != 0);
2629                                 break;
2630
2631                         case O_IN:      /* "out" is "not in" */
2632                                 match = (oif == NULL);
2633                                 break;
2634
2635                         case O_LAYER2:
2636                                 match = (args->eh != NULL);
2637                                 break;
2638
2639                         case O_DIVERTED:
2640                                 match = (cmd->arg1 & 1 && divinput_flags &
2641                                     IP_FW_DIVERT_LOOPBACK_FLAG) ||
2642                                         (cmd->arg1 & 2 && divinput_flags &
2643                                     IP_FW_DIVERT_OUTPUT_FLAG);
2644                                 break;
2645
2646                         case O_PROTO:
2647                                 /*
2648                                  * We do not allow an arg of 0 so the
2649                                  * check of "proto" only suffices.
2650                                  */
2651                                 match = (proto == cmd->arg1);
2652                                 break;
2653
2654                         case O_IP_SRC:
2655                                 match = is_ipv4 &&
2656                                     (((ipfw_insn_ip *)cmd)->addr.s_addr ==
2657                                     src_ip.s_addr);
2658                                 break;
2659
2660                         case O_IP_SRC_LOOKUP:
2661                         case O_IP_DST_LOOKUP:
2662                                 if (is_ipv4) {
2663                                     uint32_t a =
2664                                         (cmd->opcode == O_IP_DST_LOOKUP) ?
2665                                             dst_ip.s_addr : src_ip.s_addr;
2666                                     uint32_t v = 0;
2667
2668                                     match = lookup_table(chain, cmd->arg1, a,
2669                                         &v);
2670                                     if (!match)
2671                                         break;
2672                                     if (cmdlen == F_INSN_SIZE(ipfw_insn_u32))
2673                                         match =
2674                                             ((ipfw_insn_u32 *)cmd)->d[0] == v;
2675                                     else
2676                                         tablearg = v;
2677                                 }
2678                                 break;
2679
2680                         case O_IP_SRC_MASK:
2681                         case O_IP_DST_MASK:
2682                                 if (is_ipv4) {
2683                                     uint32_t a =
2684                                         (cmd->opcode == O_IP_DST_MASK) ?
2685                                             dst_ip.s_addr : src_ip.s_addr;
2686                                     uint32_t *p = ((ipfw_insn_u32 *)cmd)->d;
2687                                     int i = cmdlen-1;
2688
2689                                     for (; !match && i>0; i-= 2, p+= 2)
2690                                         match = (p[0] == (a & p[1]));
2691                                 }
2692                                 break;
2693
2694                         case O_IP_SRC_ME:
2695                                 if (is_ipv4) {
2696                                         struct ifnet *tif;
2697
2698                                         INADDR_TO_IFP(src_ip, tif);
2699                                         match = (tif != NULL);
2700                                 }
2701                                 break;
2702
2703                         case O_IP_DST_SET:
2704                         case O_IP_SRC_SET:
2705                                 if (is_ipv4) {
2706                                         u_int32_t *d = (u_int32_t *)(cmd+1);
2707                                         u_int32_t addr =
2708                                             cmd->opcode == O_IP_DST_SET ?
2709                                                 args->f_id.dst_ip :
2710                                                 args->f_id.src_ip;
2711
2712                                             if (addr < d[0])
2713                                                     break;
2714                                             addr -= d[0]; /* subtract base */
2715                                             match = (addr < cmd->arg1) &&
2716                                                 ( d[ 1 + (addr>>5)] &
2717                                                   (1<<(addr & 0x1f)) );
2718                                 }
2719                                 break;
2720
2721                         case O_IP_DST:
2722                                 match = is_ipv4 &&
2723                                     (((ipfw_insn_ip *)cmd)->addr.s_addr ==
2724                                     dst_ip.s_addr);
2725                                 break;
2726
2727                         case O_IP_DST_ME:
2728                                 if (is_ipv4) {
2729                                         struct ifnet *tif;
2730
2731                                         INADDR_TO_IFP(dst_ip, tif);
2732                                         match = (tif != NULL);
2733                                 }
2734                                 break;
2735
2736                         case O_IP_SRCPORT:
2737                         case O_IP_DSTPORT:
2738                                 /*
2739                                  * offset == 0 && proto != 0 is enough
2740                                  * to guarantee that we have a
2741                                  * packet with port info.
2742                                  */
2743                                 if ((proto==IPPROTO_UDP || proto==IPPROTO_TCP)
2744                                     && offset == 0) {
2745                                         u_int16_t x =
2746                                             (cmd->opcode == O_IP_SRCPORT) ?
2747                                                 src_port : dst_port ;
2748                                         u_int16_t *p =
2749                                             ((ipfw_insn_u16 *)cmd)->ports;
2750                                         int i;
2751
2752                                         for (i = cmdlen - 1; !match && i>0;
2753                                             i--, p += 2)
2754                                                 match = (x>=p[0] && x<=p[1]);
2755                                 }
2756                                 break;
2757
2758                         case O_ICMPTYPE:
2759                                 match = (offset == 0 && proto==IPPROTO_ICMP &&
2760                                     icmptype_match(ICMP(ulp), (ipfw_insn_u32 *)cmd) );
2761                                 break;
2762
2763 #ifdef INET6
2764                         case O_ICMP6TYPE:
2765                                 match = is_ipv6 && offset == 0 &&
2766                                     proto==IPPROTO_ICMPV6 &&
2767                                     icmp6type_match(
2768                                         ICMP6(ulp)->icmp6_type,
2769                                         (ipfw_insn_u32 *)cmd);
2770                                 break;
2771 #endif /* INET6 */
2772
2773                         case O_IPOPT:
2774                                 match = (is_ipv4 &&
2775                                     ipopts_match(ip, cmd) );
2776                                 break;
2777
2778                         case O_IPVER:
2779                                 match = (is_ipv4 &&
2780                                     cmd->arg1 == ip->ip_v);
2781                                 break;
2782
2783                         case O_IPID:
2784                         case O_IPLEN:
2785                         case O_IPTTL:
2786                                 if (is_ipv4) {  /* only for IP packets */
2787                                     uint16_t x;
2788                                     uint16_t *p;
2789                                     int i;
2790
2791                                     if (cmd->opcode == O_IPLEN)
2792                                         x = ip_len;
2793                                     else if (cmd->opcode == O_IPTTL)
2794                                         x = ip->ip_ttl;
2795                                     else /* must be IPID */
2796                                         x = ntohs(ip->ip_id);
2797                                     if (cmdlen == 1) {
2798                                         match = (cmd->arg1 == x);
2799                                         break;
2800                                     }
2801                                     /* otherwise we have ranges */
2802                                     p = ((ipfw_insn_u16 *)cmd)->ports;
2803                                     i = cmdlen - 1;
2804                                     for (; !match && i>0; i--, p += 2)
2805                                         match = (x >= p[0] && x <= p[1]);
2806                                 }
2807                                 break;
2808
2809                         case O_IPPRECEDENCE:
2810                                 match = (is_ipv4 &&
2811                                     (cmd->arg1 == (ip->ip_tos & 0xe0)) );
2812                                 break;
2813
2814                         case O_IPTOS:
2815                                 match = (is_ipv4 &&
2816                                     flags_match(cmd, ip->ip_tos));
2817                                 break;
2818
2819                         case O_TCPDATALEN:
2820                                 if (proto == IPPROTO_TCP && offset == 0) {
2821                                     struct tcphdr *tcp;
2822                                     uint16_t x;
2823                                     uint16_t *p;
2824                                     int i;
2825
2826                                     tcp = TCP(ulp);
2827                                     x = ip_len -
2828                                         ((ip->ip_hl + tcp->th_off) << 2);
2829                                     if (cmdlen == 1) {
2830                                         match = (cmd->arg1 == x);
2831                                         break;
2832                                     }
2833                                     /* otherwise we have ranges */
2834                                     p = ((ipfw_insn_u16 *)cmd)->ports;
2835                                     i = cmdlen - 1;
2836                                     for (; !match && i>0; i--, p += 2)
2837                                         match = (x >= p[0] && x <= p[1]);
2838                                 }
2839                                 break;
2840
2841                         case O_TCPFLAGS:
2842                                 match = (proto == IPPROTO_TCP && offset == 0 &&
2843                                     flags_match(cmd, TCP(ulp)->th_flags));
2844                                 break;
2845
2846                         case O_TCPOPTS:
2847                                 match = (proto == IPPROTO_TCP && offset == 0 &&
2848                                     tcpopts_match(TCP(ulp), cmd));
2849                                 break;
2850
2851                         case O_TCPSEQ:
2852                                 match = (proto == IPPROTO_TCP && offset == 0 &&
2853                                     ((ipfw_insn_u32 *)cmd)->d[0] ==
2854                                         TCP(ulp)->th_seq);
2855                                 break;
2856
2857                         case O_TCPACK:
2858                                 match = (proto == IPPROTO_TCP && offset == 0 &&
2859                                     ((ipfw_insn_u32 *)cmd)->d[0] ==
2860                                         TCP(ulp)->th_ack);
2861                                 break;
2862
2863                         case O_TCPWIN:
2864                                 match = (proto == IPPROTO_TCP && offset == 0 &&
2865                                     cmd->arg1 == TCP(ulp)->th_win);
2866                                 break;
2867
2868                         case O_ESTAB:
2869                                 /* reject packets which have SYN only */
2870                                 /* XXX should i also check for TH_ACK ? */
2871                                 match = (proto == IPPROTO_TCP && offset == 0 &&
2872                                     (TCP(ulp)->th_flags &
2873                                      (TH_RST | TH_ACK | TH_SYN)) != TH_SYN);
2874                                 break;
2875
2876                         case O_ALTQ: {
2877                                 struct pf_mtag *at;
2878                                 ipfw_insn_altq *altq = (ipfw_insn_altq *)cmd;
2879
2880                                 match = 1;
2881                                 at = pf_find_mtag(m);
2882                                 if (at != NULL && at->qid != 0)
2883                                         break;
2884                                 at = pf_get_mtag(m);
2885                                 if (at == NULL) {
2886                                         /*
2887                                          * Let the packet fall back to the
2888                                          * default ALTQ.
2889                                          */
2890                                         break;
2891                                 }
2892                                 at->qid = altq->qid;
2893                                 if (is_ipv4)
2894                                         at->af = AF_INET;
2895                                 else
2896                                         at->af = AF_LINK;
2897                                 at->hdr = ip;
2898                                 break;
2899                         }
2900
2901                         case O_LOG:
2902                                 if (fw_verbose)
2903                                         ipfw_log(f, hlen, args, m,
2904                                             oif, offset, tablearg, ip);
2905                                 match = 1;
2906                                 break;
2907
2908                         case O_PROB:
2909                                 match = (random()<((ipfw_insn_u32 *)cmd)->d[0]);
2910                                 break;
2911
2912                         case O_VERREVPATH:
2913                                 /* Outgoing packets automatically pass/match */
2914                                 match = ((oif != NULL) ||
2915                                     (m->m_pkthdr.rcvif == NULL) ||
2916                                     (
2917 #ifdef INET6
2918                                     is_ipv6 ?
2919                                         verify_path6(&(args->f_id.src_ip6),
2920                                             m->m_pkthdr.rcvif) :
2921 #endif
2922                                     verify_path(src_ip, m->m_pkthdr.rcvif,
2923                                         args->f_id.fib)));
2924                                 break;
2925
2926                         case O_VERSRCREACH:
2927                                 /* Outgoing packets automatically pass/match */
2928                                 match = (hlen > 0 && ((oif != NULL) ||
2929 #ifdef INET6
2930                                     is_ipv6 ?
2931                                         verify_path6(&(args->f_id.src_ip6),
2932                                             NULL) :
2933 #endif
2934                                     verify_path(src_ip, NULL, args->f_id.fib)));
2935                                 break;
2936
2937                         case O_ANTISPOOF:
2938                                 /* Outgoing packets automatically pass/match */
2939                                 if (oif == NULL && hlen > 0 &&
2940                                     (  (is_ipv4 && in_localaddr(src_ip))
2941 #ifdef INET6
2942                                     || (is_ipv6 &&
2943                                         in6_localaddr(&(args->f_id.src_ip6)))
2944 #endif
2945                                     ))
2946                                         match =
2947 #ifdef INET6
2948                                             is_ipv6 ? verify_path6(
2949                                                 &(args->f_id.src_ip6),
2950                                                 m->m_pkthdr.rcvif) :
2951 #endif
2952                                             verify_path(src_ip,
2953                                                 m->m_pkthdr.rcvif,
2954                                                 args->f_id.fib);
2955                                 else
2956                                         match = 1;
2957                                 break;
2958
2959                         case O_IPSEC:
2960 #ifdef IPSEC
2961                                 match = (m_tag_find(m,
2962                                     PACKET_TAG_IPSEC_IN_DONE, NULL) != NULL);
2963 #endif
2964                                 /* otherwise no match */
2965                                 break;
2966
2967 #ifdef INET6
2968                         case O_IP6_SRC:
2969                                 match = is_ipv6 &&
2970                                     IN6_ARE_ADDR_EQUAL(&args->f_id.src_ip6,
2971                                     &((ipfw_insn_ip6 *)cmd)->addr6);
2972                                 break;
2973
2974                         case O_IP6_DST:
2975                                 match = is_ipv6 &&
2976                                 IN6_ARE_ADDR_EQUAL(&args->f_id.dst_ip6,
2977                                     &((ipfw_insn_ip6 *)cmd)->addr6);
2978                                 break;
2979                         case O_IP6_SRC_MASK:
2980                         case O_IP6_DST_MASK:
2981                                 if (is_ipv6) {
2982                                         int i = cmdlen - 1;
2983                                         struct in6_addr p;
2984                                         struct in6_addr *d =
2985                                             &((ipfw_insn_ip6 *)cmd)->addr6;
2986
2987                                         for (; !match && i > 0; d += 2,
2988                                             i -= F_INSN_SIZE(struct in6_addr)
2989                                             * 2) {
2990                                                 p = (cmd->opcode ==
2991                                                     O_IP6_SRC_MASK) ?
2992                                                     args->f_id.src_ip6:
2993                                                     args->f_id.dst_ip6;
2994                                                 APPLY_MASK(&p, &d[1]);
2995                                                 match =
2996                                                     IN6_ARE_ADDR_EQUAL(&d[0],
2997                                                     &p);
2998                                         }
2999                                 }
3000                                 break;
3001
3002                         case O_IP6_SRC_ME:
3003                                 match= is_ipv6 && search_ip6_addr_net(&args->f_id.src_ip6);
3004                                 break;
3005
3006                         case O_IP6_DST_ME:
3007                                 match= is_ipv6 && search_ip6_addr_net(&args->f_id.dst_ip6);
3008                                 break;
3009
3010                         case O_FLOW6ID:
3011                                 match = is_ipv6 &&
3012                                     flow6id_match(args->f_id.flow_id6,
3013                                     (ipfw_insn_u32 *) cmd);
3014                                 break;
3015
3016                         case O_EXT_HDR:
3017                                 match = is_ipv6 &&
3018                                     (ext_hd & ((ipfw_insn *) cmd)->arg1);
3019                                 break;
3020
3021                         case O_IP6:
3022                                 match = is_ipv6;
3023                                 break;
3024 #endif
3025
3026                         case O_IP4:
3027                                 match = is_ipv4;
3028                                 break;
3029
3030                         case O_TAG: {
3031                                 uint32_t tag = (cmd->arg1 == IP_FW_TABLEARG) ?
3032                                     tablearg : cmd->arg1;
3033
3034                                 /* Packet is already tagged with this tag? */
3035                                 mtag = m_tag_locate(m, MTAG_IPFW, tag, NULL);
3036
3037                                 /* We have `untag' action when F_NOT flag is
3038                                  * present. And we must remove this mtag from
3039                                  * mbuf and reset `match' to zero (`match' will
3040                                  * be inversed later).
3041                                  * Otherwise we should allocate new mtag and
3042                                  * push it into mbuf.
3043                                  */
3044                                 if (cmd->len & F_NOT) { /* `untag' action */
3045                                         if (mtag != NULL)
3046                                                 m_tag_delete(m, mtag);
3047                                 } else if (mtag == NULL) {
3048                                         if ((mtag = m_tag_alloc(MTAG_IPFW,
3049                                             tag, 0, M_NOWAIT)) != NULL)
3050                                                 m_tag_prepend(m, mtag);
3051                                 }
3052                                 match = (cmd->len & F_NOT) ? 0: 1;
3053                                 break;
3054                         }
3055
3056                         case O_FIB: /* try match the specified fib */
3057                                 if (args->f_id.fib == cmd->arg1)
3058                                         match = 1;
3059                                 break;
3060
3061                         case O_TAGGED: {
3062                                 uint32_t tag = (cmd->arg1 == IP_FW_TABLEARG) ?
3063                                     tablearg : cmd->arg1;
3064
3065                                 if (cmdlen == 1) {
3066                                         match = m_tag_locate(m, MTAG_IPFW,
3067                                             tag, NULL) != NULL;
3068                                         break;
3069                                 }
3070
3071                                 /* we have ranges */
3072                                 for (mtag = m_tag_first(m);
3073                                     mtag != NULL && !match;
3074                                     mtag = m_tag_next(m, mtag)) {
3075                                         uint16_t *p;
3076                                         int i;
3077
3078                                         if (mtag->m_tag_cookie != MTAG_IPFW)
3079                                                 continue;
3080
3081                                         p = ((ipfw_insn_u16 *)cmd)->ports;
3082                                         i = cmdlen - 1;
3083                                         for(; !match && i > 0; i--, p += 2)
3084                                                 match =
3085                                                     mtag->m_tag_id >= p[0] &&
3086                                                     mtag->m_tag_id <= p[1];
3087                                 }
3088                                 break;
3089                         }
3090                                 
3091                         /*
3092                          * The second set of opcodes represents 'actions',
3093                          * i.e. the terminal part of a rule once the packet
3094                          * matches all previous patterns.
3095                          * Typically there is only one action for each rule,
3096                          * and the opcode is stored at the end of the rule
3097                          * (but there are exceptions -- see below).
3098                          *
3099                          * In general, here we set retval and terminate the
3100                          * outer loop (would be a 'break 3' in some language,
3101                          * but we need to do a 'goto done').
3102                          *
3103                          * Exceptions:
3104                          * O_COUNT and O_SKIPTO actions:
3105                          *   instead of terminating, we jump to the next rule
3106                          *   ('goto next_rule', equivalent to a 'break 2'),
3107                          *   or to the SKIPTO target ('goto again' after
3108                          *   having set f, cmd and l), respectively.
3109                          *
3110                          * O_TAG, O_LOG and O_ALTQ action parameters:
3111                          *   perform some action and set match = 1;
3112                          *
3113                          * O_LIMIT and O_KEEP_STATE: these opcodes are
3114                          *   not real 'actions', and are stored right
3115                          *   before the 'action' part of the rule.
3116                          *   These opcodes try to install an entry in the
3117                          *   state tables; if successful, we continue with
3118                          *   the next opcode (match=1; break;), otherwise
3119                          *   the packet *   must be dropped
3120                          *   ('goto done' after setting retval);
3121                          *
3122                          * O_PROBE_STATE and O_CHECK_STATE: these opcodes
3123                          *   cause a lookup of the state table, and a jump
3124                          *   to the 'action' part of the parent rule
3125                          *   ('goto check_body') if an entry is found, or
3126                          *   (CHECK_STATE only) a jump to the next rule if
3127                          *   the entry is not found ('goto next_rule').
3128                          *   The result of the lookup is cached to make
3129                          *   further instances of these opcodes are
3130                          *   effectively NOPs.
3131                          */
3132                         case O_LIMIT:
3133                         case O_KEEP_STATE:
3134                                 if (install_state(f,
3135                                     (ipfw_insn_limit *)cmd, args, tablearg)) {
3136                                         retval = IP_FW_DENY;
3137                                         goto done; /* error/limit violation */
3138                                 }
3139                                 match = 1;
3140                                 break;
3141
3142                         case O_PROBE_STATE:
3143                         case O_CHECK_STATE:
3144                                 /*
3145                                  * dynamic rules are checked at the first
3146                                  * keep-state or check-state occurrence,
3147                                  * with the result being stored in dyn_dir.
3148                                  * The compiler introduces a PROBE_STATE
3149                                  * instruction for us when we have a
3150                                  * KEEP_STATE (because PROBE_STATE needs
3151                                  * to be run first).
3152                                  */
3153                                 if (dyn_dir == MATCH_UNKNOWN &&
3154                                     (q = lookup_dyn_rule(&args->f_id,
3155                                      &dyn_dir, proto == IPPROTO_TCP ?
3156                                         TCP(ulp) : NULL))
3157                                         != NULL) {
3158                                         /*
3159                                          * Found dynamic entry, update stats
3160                                          * and jump to the 'action' part of
3161                                          * the parent rule.
3162                                          */
3163                                         q->pcnt++;
3164                                         q->bcnt += pktlen;
3165                                         f = q->rule;
3166                                         cmd = ACTION_PTR(f);
3167                                         l = f->cmd_len - f->act_ofs;
3168                                         IPFW_DYN_UNLOCK();
3169                                         goto check_body;
3170                                 }
3171                                 /*
3172                                  * Dynamic entry not found. If CHECK_STATE,
3173                                  * skip to next rule, if PROBE_STATE just
3174                                  * ignore and continue with next opcode.
3175                                  */
3176                                 if (cmd->opcode == O_CHECK_STATE)
3177                                         goto next_rule;
3178                                 match = 1;
3179                                 break;
3180
3181                         case O_ACCEPT:
3182                                 retval = 0;     /* accept */
3183                                 goto done;
3184
3185                         case O_PIPE:
3186                         case O_QUEUE:
3187                                 args->rule = f; /* report matching rule */
3188                                 if (cmd->arg1 == IP_FW_TABLEARG)
3189                                         args->cookie = tablearg;
3190                                 else
3191                                         args->cookie = cmd->arg1;
3192                                 retval = IP_FW_DUMMYNET;
3193                                 goto done;
3194
3195                         case O_DIVERT:
3196                         case O_TEE: {
3197                                 struct divert_tag *dt;
3198
3199                                 if (args->eh) /* not on layer 2 */
3200                                         break;
3201                                 mtag = m_tag_get(PACKET_TAG_DIVERT,
3202                                                 sizeof(struct divert_tag),
3203                                                 M_NOWAIT);
3204                                 if (mtag == NULL) {
3205                                         /* XXX statistic */
3206                                         /* drop packet */
3207                                         IPFW_RUNLOCK(chain);
3208                                         return (IP_FW_DENY);
3209                                 }
3210                                 dt = (struct divert_tag *)(mtag+1);
3211                                 dt->cookie = f->rulenum;
3212                                 if (cmd->arg1 == IP_FW_TABLEARG)
3213                                         dt->info = tablearg;
3214                                 else
3215                                         dt->info = cmd->arg1;
3216                                 m_tag_prepend(m, mtag);
3217                                 retval = (cmd->opcode == O_DIVERT) ?
3218                                     IP_FW_DIVERT : IP_FW_TEE;
3219                                 goto done;
3220                         }
3221
3222                         case O_COUNT:
3223                         case O_SKIPTO:
3224                                 f->pcnt++;      /* update stats */
3225                                 f->bcnt += pktlen;
3226                                 f->timestamp = time_uptime;
3227                                 if (cmd->opcode == O_COUNT)
3228                                         goto next_rule;
3229                                 /* handle skipto */
3230                                 if (cmd->arg1 == IP_FW_TABLEARG) {
3231                                         f = lookup_next_rule(f, tablearg);
3232                                 } else {
3233                                         if (f->next_rule == NULL)
3234                                                 lookup_next_rule(f, 0);
3235                                         f = f->next_rule;
3236                                 }
3237                                 goto again;
3238
3239                         case O_REJECT:
3240                                 /*
3241                                  * Drop the packet and send a reject notice
3242                                  * if the packet is not ICMP (or is an ICMP
3243                                  * query), and it is not multicast/broadcast.
3244                                  */
3245                                 if (hlen > 0 && is_ipv4 && offset == 0 &&
3246                                     (proto != IPPROTO_ICMP ||
3247                                      is_icmp_query(ICMP(ulp))) &&
3248                                     !(m->m_flags & (M_BCAST|M_MCAST)) &&
3249                                     !IN_MULTICAST(ntohl(dst_ip.s_addr))) {
3250                                         send_reject(args, cmd->arg1, ip_len, ip);
3251                                         m = args->m;
3252                                 }
3253                                 /* FALLTHROUGH */
3254 #ifdef INET6
3255                         case O_UNREACH6:
3256                                 if (hlen > 0 && is_ipv6 &&
3257                                     ((offset & IP6F_OFF_MASK) == 0) &&
3258                                     (proto != IPPROTO_ICMPV6 ||
3259                                      (is_icmp6_query(args->f_id.flags) == 1)) &&
3260                                     !(m->m_flags & (M_BCAST|M_MCAST)) &&
3261                                     !IN6_IS_ADDR_MULTICAST(&args->f_id.dst_ip6)) {
3262                                         send_reject6(
3263                                             args, cmd->arg1, hlen,
3264                                             (struct ip6_hdr *)ip);
3265                                         m = args->m;
3266                                 }
3267                                 /* FALLTHROUGH */
3268 #endif
3269                         case O_DENY:
3270                                 retval = IP_FW_DENY;
3271                                 goto done;
3272
3273                         case O_FORWARD_IP: {
3274                                 struct sockaddr_in *sa;
3275                                 sa = &(((ipfw_insn_sa *)cmd)->sa);
3276                                 if (args->eh)   /* not valid on layer2 pkts */
3277                                         break;
3278                                 if (!q || dyn_dir == MATCH_FORWARD) {
3279                                         if (sa->sin_addr.s_addr == INADDR_ANY) {
3280                                                 bcopy(sa, &args->hopstore,
3281                                                         sizeof(*sa));
3282                                                 args->hopstore.sin_addr.s_addr =
3283                                                     htonl(tablearg);
3284                                                 args->next_hop =
3285                                                     &args->hopstore;
3286                                         } else {
3287                                                 args->next_hop = sa;
3288                                         }
3289                                 }
3290                                 retval = IP_FW_PASS;
3291                             }
3292                             goto done;
3293
3294                         case O_NETGRAPH:
3295                         case O_NGTEE:
3296                                 args->rule = f; /* report matching rule */
3297                                 if (cmd->arg1 == IP_FW_TABLEARG)
3298                                         args->cookie = tablearg;
3299                                 else
3300                                         args->cookie = cmd->arg1;
3301                                 retval = (cmd->opcode == O_NETGRAPH) ?
3302                                     IP_FW_NETGRAPH : IP_FW_NGTEE;
3303                                 goto done;
3304
3305                         case O_SETFIB:
3306                                 f->pcnt++;      /* update stats */
3307                                 f->bcnt += pktlen;
3308                                 f->timestamp = time_uptime;
3309                                 M_SETFIB(m, cmd->arg1);
3310                                 args->f_id.fib = cmd->arg1;
3311                                 goto next_rule;
3312
3313                         case O_NAT: {
3314                                 struct cfg_nat *t;
3315                                 int nat_id;
3316
3317                                 if (IPFW_NAT_LOADED) {
3318                                         args->rule = f; /* Report matching rule. */
3319                                         t = ((ipfw_insn_nat *)cmd)->nat;
3320                                         if (t == NULL) {
3321                                                 nat_id = (cmd->arg1 == IP_FW_TABLEARG) ?
3322                                                     tablearg : cmd->arg1;
3323                                                 LOOKUP_NAT(layer3_chain, nat_id, t);
3324                                                 if (t == NULL) {
3325                                                         retval = IP_FW_DENY;
3326                                                         goto done;
3327                                                 }
3328                                                 if (cmd->arg1 != IP_FW_TABLEARG)
3329                                                         ((ipfw_insn_nat *)cmd)->nat = t;
3330                                         }
3331                                         retval = ipfw_nat_ptr(args, t, m);
3332                                 } else
3333                                         retval = IP_FW_DENY;
3334                                 goto done;
3335                         }
3336
3337                         default:
3338                                 panic("-- unknown opcode %d\n", cmd->opcode);
3339                         } /* end of switch() on opcodes */
3340
3341                         if (cmd->len & F_NOT)
3342                                 match = !match;
3343
3344                         if (match) {
3345                                 if (cmd->len & F_OR)
3346                                         skip_or = 1;
3347                         } else {
3348                                 if (!(cmd->len & F_OR)) /* not an OR block, */
3349                                         break;          /* try next rule    */
3350                         }
3351
3352                 }       /* end of inner for, scan opcodes */
3353
3354 next_rule:;             /* try next rule                */
3355
3356         }               /* end of outer for, scan rules */
3357         printf("ipfw: ouch!, skip past end of rules, denying packet\n");
3358         IPFW_RUNLOCK(chain);
3359         return (IP_FW_DENY);
3360
3361 done:
3362         /* Update statistics */
3363         f->pcnt++;
3364         f->bcnt += pktlen;
3365         f->timestamp = time_uptime;
3366         IPFW_RUNLOCK(chain);
3367         return (retval);
3368
3369 pullup_failed:
3370         if (fw_verbose)
3371                 printf("ipfw: pullup failed\n");
3372         return (IP_FW_DENY);
3373 }
3374
3375 /*
3376  * When a rule is added/deleted, clear the next_rule pointers in all rules.
3377  * These will be reconstructed on the fly as packets are matched.
3378  */
3379 static void
3380 flush_rule_ptrs(struct ip_fw_chain *chain)
3381 {
3382         struct ip_fw *rule;
3383
3384         IPFW_WLOCK_ASSERT(chain);
3385
3386         for (rule = chain->rules; rule; rule = rule->next)
3387                 rule->next_rule = NULL;
3388 }
3389
3390 /*
3391  * Add a new rule to the list. Copy the rule into a malloc'ed area, then
3392  * possibly create a rule number and add the rule to the list.
3393  * Update the rule_number in the input struct so the caller knows it as well.
3394  */
3395 static int
3396 add_rule(struct ip_fw_chain *chain, struct ip_fw *input_rule)
3397 {
3398         struct ip_fw *rule, *f, *prev;
3399         int l = RULESIZE(input_rule);
3400
3401         if (chain->rules == NULL && input_rule->rulenum != IPFW_DEFAULT_RULE)
3402                 return (EINVAL);
3403
3404         rule = malloc(l, M_IPFW, M_NOWAIT | M_ZERO);
3405         if (rule == NULL)
3406                 return (ENOSPC);
3407
3408         bcopy(input_rule, rule, l);
3409
3410         rule->next = NULL;
3411         rule->next_rule = NULL;
3412
3413         rule->pcnt = 0;
3414         rule->bcnt = 0;
3415         rule->timestamp = 0;
3416
3417         IPFW_WLOCK(chain);
3418
3419         if (chain->rules == NULL) {     /* default rule */
3420                 chain->rules = rule;
3421                 goto done;
3422         }
3423
3424         /*
3425          * If rulenum is 0, find highest numbered rule before the
3426          * default rule, and add autoinc_step
3427          */
3428         if (autoinc_step < 1)
3429                 autoinc_step = 1;
3430         else if (autoinc_step > 1000)
3431                 autoinc_step = 1000;
3432         if (rule->rulenum == 0) {
3433                 /*
3434                  * locate the highest numbered rule before default
3435                  */
3436                 for (f = chain->rules; f; f = f->next) {
3437                         if (f->rulenum == IPFW_DEFAULT_RULE)
3438                                 break;
3439                         rule->rulenum = f->rulenum;
3440                 }
3441                 if (rule->rulenum < IPFW_DEFAULT_RULE - autoinc_step)
3442                         rule->rulenum += autoinc_step;
3443                 input_rule->rulenum = rule->rulenum;
3444         }
3445
3446         /*
3447          * Now insert the new rule in the right place in the sorted list.
3448          */
3449         for (prev = NULL, f = chain->rules; f; prev = f, f = f->next) {
3450                 if (f->rulenum > rule->rulenum) { /* found the location */
3451                         if (prev) {
3452                                 rule->next = f;
3453                                 prev->next = rule;
3454                         } else { /* head insert */
3455                                 rule->next = chain->rules;
3456                                 chain->rules = rule;
3457                         }
3458                         break;
3459                 }
3460         }
3461         flush_rule_ptrs(chain);
3462 done:
3463         static_count++;
3464         static_len += l;
3465         IPFW_WUNLOCK(chain);
3466         DEB(printf("ipfw: installed rule %d, static count now %d\n",
3467                 rule->rulenum, static_count);)
3468         return (0);
3469 }
3470
3471 /**
3472  * Remove a static rule (including derived * dynamic rules)
3473  * and place it on the ``reap list'' for later reclamation.
3474  * The caller is in charge of clearing rule pointers to avoid
3475  * dangling pointers.
3476  * @return a pointer to the next entry.
3477  * Arguments are not checked, so they better be correct.
3478  */
3479 static struct ip_fw *
3480 remove_rule(struct ip_fw_chain *chain, struct ip_fw *rule,
3481     struct ip_fw *prev)
3482 {
3483         struct ip_fw *n;
3484         int l = RULESIZE(rule);
3485
3486         IPFW_WLOCK_ASSERT(chain);
3487
3488         n = rule->next;
3489         IPFW_DYN_LOCK();
3490         remove_dyn_rule(rule, NULL /* force removal */);
3491         IPFW_DYN_UNLOCK();
3492         if (prev == NULL)
3493                 chain->rules = n;
3494         else
3495                 prev->next = n;
3496         static_count--;
3497         static_len -= l;
3498
3499         rule->next = chain->reap;
3500         chain->reap = rule;
3501
3502         return n;
3503 }
3504
3505 /**
3506  * Reclaim storage associated with a list of rules.  This is
3507  * typically the list created using remove_rule.
3508  */
3509 static void
3510 reap_rules(struct ip_fw *head)
3511 {
3512         struct ip_fw *rule;
3513
3514         while ((rule = head) != NULL) {
3515                 head = head->next;
3516                 if (DUMMYNET_LOADED)
3517                         ip_dn_ruledel_ptr(rule);
3518                 free(rule, M_IPFW);
3519         }
3520 }
3521
3522 /*
3523  * Remove all rules from a chain (except rules in set RESVD_SET
3524  * unless kill_default = 1).  The caller is responsible for
3525  * reclaiming storage for the rules left in chain->reap.
3526  */
3527 static void
3528 free_chain(struct ip_fw_chain *chain, int kill_default)
3529 {
3530         struct ip_fw *prev, *rule;
3531
3532         IPFW_WLOCK_ASSERT(chain);
3533
3534         flush_rule_ptrs(chain); /* more efficient to do outside the loop */
3535         for (prev = NULL, rule = chain->rules; rule ; )
3536                 if (kill_default || rule->set != RESVD_SET)
3537                         rule = remove_rule(chain, rule, prev);
3538                 else {
3539                         prev = rule;
3540                         rule = rule->next;
3541                 }
3542 }
3543
3544 /**
3545  * Remove all rules with given number, and also do set manipulation.
3546  * Assumes chain != NULL && *chain != NULL.
3547  *
3548  * The argument is an u_int32_t. The low 16 bit are the rule or set number,
3549  * the next 8 bits are the new set, the top 8 bits are the command:
3550  *
3551  *      0       delete rules with given number
3552  *      1       delete rules with given set number
3553  *      2       move rules with given number to new set
3554  *      3       move rules with given set number to new set
3555  *      4       swap sets with given numbers
3556  *      5       delete rules with given number and with given set number
3557  */
3558 static int
3559 del_entry(struct ip_fw_chain *chain, u_int32_t arg)
3560 {
3561         struct ip_fw *prev = NULL, *rule;
3562         u_int16_t rulenum;      /* rule or old_set */
3563         u_int8_t cmd, new_set;
3564
3565         rulenum = arg & 0xffff;
3566         cmd = (arg >> 24) & 0xff;
3567         new_set = (arg >> 16) & 0xff;
3568
3569         if (cmd > 5 || new_set > RESVD_SET)
3570                 return EINVAL;
3571         if (cmd == 0 || cmd == 2 || cmd == 5) {
3572                 if (rulenum >= IPFW_DEFAULT_RULE)
3573                         return EINVAL;
3574         } else {
3575                 if (rulenum > RESVD_SET)        /* old_set */
3576                         return EINVAL;
3577         }
3578
3579         IPFW_WLOCK(chain);
3580         rule = chain->rules;
3581         chain->reap = NULL;
3582         switch (cmd) {
3583         case 0: /* delete rules with given number */
3584                 /*
3585                  * locate first rule to delete
3586                  */
3587                 for (; rule->rulenum < rulenum; prev = rule, rule = rule->next)
3588                         ;
3589                 if (rule->rulenum != rulenum) {
3590                         IPFW_WUNLOCK(chain);
3591                         return EINVAL;
3592                 }
3593
3594                 /*
3595                  * flush pointers outside the loop, then delete all matching
3596                  * rules. prev remains the same throughout the cycle.
3597                  */
3598                 flush_rule_ptrs(chain);
3599                 while (rule->rulenum == rulenum)
3600                         rule = remove_rule(chain, rule, prev);
3601                 break;
3602
3603         case 1: /* delete all rules with given set number */
3604                 flush_rule_ptrs(chain);
3605                 rule = chain->rules;
3606                 while (rule->rulenum < IPFW_DEFAULT_RULE)
3607                         if (rule->set == rulenum)
3608                                 rule = remove_rule(chain, rule, prev);
3609                         else {
3610                                 prev = rule;
3611                                 rule = rule->next;
3612                         }
3613                 break;
3614
3615         case 2: /* move rules with given number to new set */
3616                 rule = chain->rules;
3617                 for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
3618                         if (rule->rulenum == rulenum)
3619                                 rule->set = new_set;
3620                 break;
3621
3622         case 3: /* move rules with given set number to new set */
3623                 for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
3624                         if (rule->set == rulenum)
3625                                 rule->set = new_set;
3626                 break;
3627
3628         case 4: /* swap two sets */
3629                 for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
3630                         if (rule->set == rulenum)
3631                                 rule->set = new_set;
3632                         else if (rule->set == new_set)
3633                                 rule->set = rulenum;
3634                 break;
3635         case 5: /* delete rules with given number and with given set number.
3636                  * rulenum - given rule number;
3637                  * new_set - given set number.
3638                  */
3639                 for (; rule->rulenum < rulenum; prev = rule, rule = rule->next)
3640                         ;
3641                 if (rule->rulenum != rulenum) {
3642                         IPFW_WUNLOCK(chain);
3643                         return (EINVAL);
3644                 }
3645                 flush_rule_ptrs(chain);
3646                 while (rule->rulenum == rulenum) {
3647                         if (rule->set == new_set)
3648                                 rule = remove_rule(chain, rule, prev);
3649                         else {
3650                                 prev = rule;
3651                                 rule = rule->next;
3652                         }
3653                 }
3654         }
3655         /*
3656          * Look for rules to reclaim.  We grab the list before
3657          * releasing the lock then reclaim them w/o the lock to
3658          * avoid a LOR with dummynet.
3659          */
3660         rule = chain->reap;
3661         chain->reap = NULL;
3662         IPFW_WUNLOCK(chain);
3663         if (rule)
3664                 reap_rules(rule);
3665         return 0;
3666 }
3667
3668 /*
3669  * Clear counters for a specific rule.
3670  * The enclosing "table" is assumed locked.
3671  */
3672 static void
3673 clear_counters(struct ip_fw *rule, int log_only)
3674 {
3675         ipfw_insn_log *l = (ipfw_insn_log *)ACTION_PTR(rule);
3676
3677         if (log_only == 0) {
3678                 rule->bcnt = rule->pcnt = 0;
3679                 rule->timestamp = 0;
3680         }
3681         if (l->o.opcode == O_LOG)
3682                 l->log_left = l->max_log;
3683 }
3684
3685 /**
3686  * Reset some or all counters on firewall rules.
3687  * The argument `arg' is an u_int32_t. The low 16 bit are the rule number,
3688  * the next 8 bits are the set number, the top 8 bits are the command:
3689  *      0       work with rules from all set's;
3690  *      1       work with rules only from specified set.
3691  * Specified rule number is zero if we want to clear all entries.
3692  * log_only is 1 if we only want to reset logs, zero otherwise.
3693  */
3694 static int
3695 zero_entry(struct ip_fw_chain *chain, u_int32_t arg, int log_only)
3696 {
3697         struct ip_fw *rule;
3698         char *msg;
3699
3700         uint16_t rulenum = arg & 0xffff;
3701         uint8_t set = (arg >> 16) & 0xff;
3702         uint8_t cmd = (arg >> 24) & 0xff;
3703
3704         if (cmd > 1)
3705                 return (EINVAL);
3706         if (cmd == 1 && set > RESVD_SET)
3707                 return (EINVAL);
3708
3709         IPFW_WLOCK(chain);
3710         if (rulenum == 0) {
3711                 norule_counter = 0;
3712                 for (rule = chain->rules; rule; rule = rule->next) {
3713                         /* Skip rules from another set. */
3714                         if (cmd == 1 && rule->set != set)
3715                                 continue;
3716                         clear_counters(rule, log_only);
3717                 }
3718                 msg = log_only ? "All logging counts reset" :
3719                     "Accounting cleared";
3720         } else {
3721                 int cleared = 0;
3722                 /*
3723                  * We can have multiple rules with the same number, so we
3724                  * need to clear them all.
3725                  */
3726                 for (rule = chain->rules; rule; rule = rule->next)
3727                         if (rule->rulenum == rulenum) {
3728                                 while (rule && rule->rulenum == rulenum) {
3729                                         if (cmd == 0 || rule->set == set)
3730                                                 clear_counters(rule, log_only);
3731                                         rule = rule->next;
3732                                 }
3733                                 cleared = 1;
3734                                 break;
3735                         }
3736                 if (!cleared) { /* we did not find any matching rules */
3737                         IPFW_WUNLOCK(chain);
3738                         return (EINVAL);
3739                 }
3740                 msg = log_only ? "logging count reset" : "cleared";
3741         }
3742         IPFW_WUNLOCK(chain);
3743
3744         if (fw_verbose) {
3745                 int lev = LOG_SECURITY | LOG_NOTICE;
3746
3747                 if (rulenum)
3748                         log(lev, "ipfw: Entry %d %s.\n", rulenum, msg);
3749                 else
3750                         log(lev, "ipfw: %s.\n", msg);
3751         }
3752         return (0);
3753 }
3754
3755 /*
3756  * Check validity of the structure before insert.
3757  * Fortunately rules are simple, so this mostly need to check rule sizes.
3758  */
3759 static int
3760 check_ipfw_struct(struct ip_fw *rule, int size)
3761 {
3762         int l, cmdlen = 0;
3763         int have_action=0;
3764         ipfw_insn *cmd;
3765
3766         if (size < sizeof(*rule)) {
3767                 printf("ipfw: rule too short\n");
3768                 return (EINVAL);
3769         }
3770         /* first, check for valid size */
3771         l = RULESIZE(rule);
3772         if (l != size) {
3773                 printf("ipfw: size mismatch (have %d want %d)\n", size, l);
3774                 return (EINVAL);
3775         }
3776         if (rule->act_ofs >= rule->cmd_len) {
3777                 printf("ipfw: bogus action offset (%u > %u)\n",
3778                     rule->act_ofs, rule->cmd_len - 1);
3779                 return (EINVAL);
3780         }
3781         /*
3782          * Now go for the individual checks. Very simple ones, basically only
3783          * instruction sizes.
3784          */
3785         for (l = rule->cmd_len, cmd = rule->cmd ;
3786                         l > 0 ; l -= cmdlen, cmd += cmdlen) {
3787                 cmdlen = F_LEN(cmd);
3788                 if (cmdlen > l) {
3789                         printf("ipfw: opcode %d size truncated\n",
3790                             cmd->opcode);
3791                         return EINVAL;
3792                 }
3793                 DEB(printf("ipfw: opcode %d\n", cmd->opcode);)
3794                 switch (cmd->opcode) {
3795                 case O_PROBE_STATE:
3796                 case O_KEEP_STATE:
3797                 case O_PROTO:
3798                 case O_IP_SRC_ME:
3799                 case O_IP_DST_ME:
3800                 case O_LAYER2:
3801                 case O_IN:
3802                 case O_FRAG:
3803                 case O_DIVERTED:
3804                 case O_IPOPT:
3805                 case O_IPTOS:
3806                 case O_IPPRECEDENCE:
3807                 case O_IPVER:
3808                 case O_TCPWIN:
3809                 case O_TCPFLAGS:
3810                 case O_TCPOPTS:
3811                 case O_ESTAB:
3812                 case O_VERREVPATH:
3813                 case O_VERSRCREACH:
3814                 case O_ANTISPOOF:
3815                 case O_IPSEC:
3816 #ifdef INET6
3817                 case O_IP6_SRC_ME:
3818                 case O_IP6_DST_ME:
3819                 case O_EXT_HDR:
3820                 case O_IP6:
3821 #endif
3822                 case O_IP4:
3823                 case O_TAG:
3824                         if (cmdlen != F_INSN_SIZE(ipfw_insn))
3825                                 goto bad_size;
3826                         break;
3827
3828                 case O_FIB:
3829                         if (cmdlen != F_INSN_SIZE(ipfw_insn))
3830                                 goto bad_size;
3831                         if (cmd->arg1 >= rt_numfibs) {
3832                                 printf("ipfw: invalid fib number %d\n",
3833                                         cmd->arg1);
3834                                 return EINVAL;
3835                         }
3836                         break;
3837
3838                 case O_SETFIB:
3839                         if (cmdlen != F_INSN_SIZE(ipfw_insn))
3840                                 goto bad_size;
3841                         if (cmd->arg1 >= rt_numfibs) {
3842                                 printf("ipfw: invalid fib number %d\n",
3843                                         cmd->arg1);
3844                                 return EINVAL;
3845                         }
3846                         goto check_action;
3847
3848                 case O_UID:
3849                 case O_GID:
3850                 case O_JAIL:
3851                 case O_IP_SRC:
3852                 case O_IP_DST:
3853                 case O_TCPSEQ:
3854                 case O_TCPACK:
3855                 case O_PROB:
3856                 case O_ICMPTYPE:
3857                         if (cmdlen != F_INSN_SIZE(ipfw_insn_u32))
3858                                 goto bad_size;
3859                         break;
3860
3861                 case O_LIMIT:
3862                         if (cmdlen != F_INSN_SIZE(ipfw_insn_limit))
3863                                 goto bad_size;
3864                         break;
3865
3866                 case O_LOG:
3867                         if (cmdlen != F_INSN_SIZE(ipfw_insn_log))
3868                                 goto bad_size;
3869
3870                         ((ipfw_insn_log *)cmd)->log_left =
3871                             ((ipfw_insn_log *)cmd)->max_log;
3872
3873                         break;
3874
3875                 case O_IP_SRC_MASK:
3876                 case O_IP_DST_MASK:
3877                         /* only odd command lengths */
3878                         if ( !(cmdlen & 1) || cmdlen > 31)
3879                                 goto bad_size;
3880                         break;
3881
3882                 case O_IP_SRC_SET:
3883                 case O_IP_DST_SET:
3884                         if (cmd->arg1 == 0 || cmd->arg1 > 256) {
3885                                 printf("ipfw: invalid set size %d\n",
3886                                         cmd->arg1);
3887                                 return EINVAL;
3888                         }
3889                         if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
3890                             (cmd->arg1+31)/32 )
3891                                 goto bad_size;
3892                         break;
3893
3894                 case O_IP_SRC_LOOKUP:
3895                 case O_IP_DST_LOOKUP:
3896                         if (cmd->arg1 >= IPFW_TABLES_MAX) {
3897                                 printf("ipfw: invalid table number %d\n",
3898                                     cmd->arg1);
3899                                 return (EINVAL);
3900                         }
3901                         if (cmdlen != F_INSN_SIZE(ipfw_insn) &&
3902                             cmdlen != F_INSN_SIZE(ipfw_insn_u32))
3903                                 goto bad_size;
3904                         break;
3905
3906                 case O_MACADDR2:
3907                         if (cmdlen != F_INSN_SIZE(ipfw_insn_mac))
3908                                 goto bad_size;
3909                         break;
3910
3911                 case O_NOP:
3912                 case O_IPID:
3913                 case O_IPTTL:
3914                 case O_IPLEN:
3915                 case O_TCPDATALEN:
3916                 case O_TAGGED:
3917                         if (cmdlen < 1 || cmdlen > 31)
3918                                 goto bad_size;
3919                         break;
3920
3921                 case O_MAC_TYPE:
3922                 case O_IP_SRCPORT:
3923                 case O_IP_DSTPORT: /* XXX artificial limit, 30 port pairs */
3924                         if (cmdlen < 2 || cmdlen > 31)
3925                                 goto bad_size;
3926                         break;
3927
3928                 case O_RECV:
3929                 case O_XMIT:
3930                 case O_VIA:
3931                         if (cmdlen != F_INSN_SIZE(ipfw_insn_if))
3932                                 goto bad_size;
3933                         break;
3934
3935                 case O_ALTQ:
3936                         if (cmdlen != F_INSN_SIZE(ipfw_insn_altq))
3937                                 goto bad_size;
3938                         break;
3939
3940                 case O_PIPE:
3941                 case O_QUEUE:
3942                         if (cmdlen != F_INSN_SIZE(ipfw_insn))
3943                                 goto bad_size;
3944                         goto check_action;
3945
3946                 case O_FORWARD_IP:
3947 #ifdef  IPFIREWALL_FORWARD
3948                         if (cmdlen != F_INSN_SIZE(ipfw_insn_sa))
3949                                 goto bad_size;
3950                         goto check_action;
3951 #else
3952                         return EINVAL;
3953 #endif
3954
3955                 case O_DIVERT:
3956                 case O_TEE:
3957                         if (ip_divert_ptr == NULL)
3958                                 return EINVAL;
3959                         else
3960                                 goto check_size;
3961                 case O_NETGRAPH:
3962                 case O_NGTEE:
3963                         if (!NG_IPFW_LOADED)
3964                                 return EINVAL;
3965                         else
3966                                 goto check_size;
3967                 case O_NAT:
3968                         if (!IPFW_NAT_LOADED)
3969                                 return EINVAL;
3970                         if (cmdlen != F_INSN_SIZE(ipfw_insn_nat))
3971                                 goto bad_size;          
3972                         goto check_action;
3973                 case O_FORWARD_MAC: /* XXX not implemented yet */
3974                 case O_CHECK_STATE:
3975                 case O_COUNT:
3976                 case O_ACCEPT:
3977                 case O_DENY:
3978                 case O_REJECT:
3979 #ifdef INET6
3980                 case O_UNREACH6:
3981 #endif
3982                 case O_SKIPTO:
3983 check_size:
3984                         if (cmdlen != F_INSN_SIZE(ipfw_insn))
3985                                 goto bad_size;
3986 check_action:
3987                         if (have_action) {
3988                                 printf("ipfw: opcode %d, multiple actions"
3989                                         " not allowed\n",
3990                                         cmd->opcode);
3991                                 return EINVAL;
3992                         }
3993                         have_action = 1;
3994                         if (l != cmdlen) {
3995                                 printf("ipfw: opcode %d, action must be"
3996                                         " last opcode\n",
3997                                         cmd->opcode);
3998                                 return EINVAL;
3999                         }
4000                         break;
4001 #ifdef INET6
4002                 case O_IP6_SRC:
4003                 case O_IP6_DST:
4004                         if (cmdlen != F_INSN_SIZE(struct in6_addr) +
4005                             F_INSN_SIZE(ipfw_insn))
4006                                 goto bad_size;
4007                         break;
4008
4009                 case O_FLOW6ID:
4010                         if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
4011                             ((ipfw_insn_u32 *)cmd)->o.arg1)
4012                                 goto bad_size;
4013                         break;
4014
4015                 case O_IP6_SRC_MASK:
4016                 case O_IP6_DST_MASK:
4017                         if ( !(cmdlen & 1) || cmdlen > 127)
4018                                 goto bad_size;
4019                         break;
4020                 case O_ICMP6TYPE:
4021                         if( cmdlen != F_INSN_SIZE( ipfw_insn_icmp6 ) )
4022                                 goto bad_size;
4023                         break;
4024 #endif
4025
4026                 default:
4027                         switch (cmd->opcode) {
4028 #ifndef INET6
4029                         case O_IP6_SRC_ME:
4030                         case O_IP6_DST_ME:
4031                         case O_EXT_HDR:
4032                         case O_IP6:
4033                         case O_UNREACH6:
4034                         case O_IP6_SRC:
4035                         case O_IP6_DST:
4036                         case O_FLOW6ID:
4037                         case O_IP6_SRC_MASK:
4038                         case O_IP6_DST_MASK:
4039                         case O_ICMP6TYPE:
4040                                 printf("ipfw: no IPv6 support in kernel\n");
4041                                 return EPROTONOSUPPORT;
4042 #endif
4043                         default:
4044                                 printf("ipfw: opcode %d, unknown opcode\n",
4045                                         cmd->opcode);
4046                                 return EINVAL;
4047                         }
4048                 }
4049         }
4050         if (have_action == 0) {
4051                 printf("ipfw: missing action\n");
4052                 return EINVAL;
4053         }
4054         return 0;
4055
4056 bad_size:
4057         printf("ipfw: opcode %d size %d wrong\n",
4058                 cmd->opcode, cmdlen);
4059         return EINVAL;
4060 }
4061
4062 /*
4063  * Copy the static and dynamic rules to the supplied buffer
4064  * and return the amount of space actually used.
4065  */
4066 static size_t
4067 ipfw_getrules(struct ip_fw_chain *chain, void *buf, size_t space)
4068 {
4069         char *bp = buf;
4070         char *ep = bp + space;
4071         struct ip_fw *rule;
4072         int i;
4073         time_t  boot_seconds;
4074
4075         boot_seconds = boottime.tv_sec;
4076         /* XXX this can take a long time and locking will block packet flow */
4077         IPFW_RLOCK(chain);
4078         for (rule = chain->rules; rule ; rule = rule->next) {
4079                 /*
4080                  * Verify the entry fits in the buffer in case the
4081                  * rules changed between calculating buffer space and
4082                  * now.  This would be better done using a generation
4083                  * number but should suffice for now.
4084                  */
4085                 i = RULESIZE(rule);
4086                 if (bp + i <= ep) {
4087                         bcopy(rule, bp, i);
4088                         /*
4089                          * XXX HACK. Store the disable mask in the "next" pointer
4090                          * in a wild attempt to keep the ABI the same.
4091                          * Why do we do this on EVERY rule?
4092                          */
4093                         bcopy(&set_disable, &(((struct ip_fw *)bp)->next_rule),
4094                             sizeof(set_disable));
4095                         if (((struct ip_fw *)bp)->timestamp)
4096                                 ((struct ip_fw *)bp)->timestamp += boot_seconds;
4097                         bp += i;
4098                 }
4099         }
4100         IPFW_RUNLOCK(chain);
4101         if (ipfw_dyn_v) {
4102                 ipfw_dyn_rule *p, *last = NULL;
4103
4104                 IPFW_DYN_LOCK();
4105                 for (i = 0 ; i < curr_dyn_buckets; i++)
4106                         for (p = ipfw_dyn_v[i] ; p != NULL; p = p->next) {
4107                                 if (bp + sizeof *p <= ep) {
4108                                         ipfw_dyn_rule *dst =
4109                                                 (ipfw_dyn_rule *)bp;
4110                                         bcopy(p, dst, sizeof *p);
4111                                         bcopy(&(p->rule->rulenum), &(dst->rule),
4112                                             sizeof(p->rule->rulenum));
4113                                         /*
4114                                          * store set number into high word of
4115                                          * dst->rule pointer.
4116                                          */
4117                                         bcopy(&(p->rule->set),
4118                                             (char *)&dst->rule +
4119                                             sizeof(p->rule->rulenum),
4120                                             sizeof(p->rule->set));
4121                                         /*
4122                                          * store a non-null value in "next".
4123                                          * The userland code will interpret a
4124                                          * NULL here as a marker
4125                                          * for the last dynamic rule.
4126                                          */
4127                                         bcopy(&dst, &dst->next, sizeof(dst));
4128                                         last = dst;
4129                                         dst->expire =
4130                                             TIME_LEQ(dst->expire, time_uptime) ?
4131                                                 0 : dst->expire - time_uptime ;
4132                                         bp += sizeof(ipfw_dyn_rule);
4133                                 }
4134                         }
4135                 IPFW_DYN_UNLOCK();
4136                 if (last != NULL) /* mark last dynamic rule */
4137                         bzero(&last->next, sizeof(last));
4138         }
4139         return (bp - (char *)buf);
4140 }
4141
4142
4143 /**
4144  * {set|get}sockopt parser.
4145  */
4146 static int
4147 ipfw_ctl(struct sockopt *sopt)
4148 {
4149 #define RULE_MAXSIZE    (256*sizeof(u_int32_t))
4150         int error;
4151         size_t size;
4152         struct ip_fw *buf, *rule;
4153         u_int32_t rulenum[2];
4154
4155         error = priv_check(sopt->sopt_td, PRIV_NETINET_IPFW);
4156         if (error)
4157                 return (error);
4158
4159         /*
4160          * Disallow modifications in really-really secure mode, but still allow
4161          * the logging counters to be reset.
4162          */
4163         if (sopt->sopt_name == IP_FW_ADD ||
4164             (sopt->sopt_dir == SOPT_SET && sopt->sopt_name != IP_FW_RESETLOG)) {
4165                 error = securelevel_ge(sopt->sopt_td->td_ucred, 3);
4166                 if (error)
4167                         return (error);
4168         }
4169
4170         error = 0;
4171
4172         switch (sopt->sopt_name) {
4173         case IP_FW_GET:
4174                 /*
4175                  * pass up a copy of the current rules. Static rules
4176                  * come first (the last of which has number IPFW_DEFAULT_RULE),
4177                  * followed by a possibly empty list of dynamic rule.
4178                  * The last dynamic rule has NULL in the "next" field.
4179                  *
4180                  * Note that the calculated size is used to bound the
4181                  * amount of data returned to the user.  The rule set may
4182                  * change between calculating the size and returning the
4183                  * data in which case we'll just return what fits.
4184                  */
4185                 size = static_len;      /* size of static rules */
4186                 if (ipfw_dyn_v)         /* add size of dyn.rules */
4187                         size += (dyn_count * sizeof(ipfw_dyn_rule));
4188
4189                 /*
4190                  * XXX todo: if the user passes a short length just to know
4191                  * how much room is needed, do not bother filling up the
4192                  * buffer, just jump to the sooptcopyout.
4193                  */
4194                 buf = malloc(size, M_TEMP, M_WAITOK);
4195                 error = sooptcopyout(sopt, buf,
4196                                 ipfw_getrules(&layer3_chain, buf, size));
4197                 free(buf, M_TEMP);
4198                 break;
4199
4200         case IP_FW_FLUSH:
4201                 /*
4202                  * Normally we cannot release the lock on each iteration.
4203                  * We could do it here only because we start from the head all
4204                  * the times so there is no risk of missing some entries.
4205                  * On the other hand, the risk is that we end up with
4206                  * a very inconsistent ruleset, so better keep the lock
4207                  * around the whole cycle.
4208                  *
4209                  * XXX this code can be improved by resetting the head of
4210                  * the list to point to the default rule, and then freeing
4211                  * the old list without the need for a lock.
4212                  */
4213
4214                 IPFW_WLOCK(&layer3_chain);
4215                 layer3_chain.reap = NULL;
4216                 free_chain(&layer3_chain, 0 /* keep default rule */);
4217                 rule = layer3_chain.reap;
4218                 layer3_chain.reap = NULL;
4219                 IPFW_WUNLOCK(&layer3_chain);
4220                 if (rule != NULL)
4221                         reap_rules(rule);
4222                 break;
4223
4224         case IP_FW_ADD:
4225                 rule = malloc(RULE_MAXSIZE, M_TEMP, M_WAITOK);
4226                 error = sooptcopyin(sopt, rule, RULE_MAXSIZE,
4227                         sizeof(struct ip_fw) );
4228                 if (error == 0)
4229                         error = check_ipfw_struct(rule, sopt->sopt_valsize);
4230                 if (error == 0) {
4231                         error = add_rule(&layer3_chain, rule);
4232                         size = RULESIZE(rule);
4233                         if (!error && sopt->sopt_dir == SOPT_GET)
4234                                 error = sooptcopyout(sopt, rule, size);
4235                 }
4236                 free(rule, M_TEMP);
4237                 break;
4238
4239         case IP_FW_DEL:
4240                 /*
4241                  * IP_FW_DEL is used for deleting single rules or sets,
4242                  * and (ab)used to atomically manipulate sets. Argument size
4243                  * is used to distinguish between the two:
4244                  *    sizeof(u_int32_t)
4245                  *      delete single rule or set of rules,
4246                  *      or reassign rules (or sets) to a different set.
4247                  *    2*sizeof(u_int32_t)
4248                  *      atomic disable/enable sets.
4249                  *      first u_int32_t contains sets to be disabled,
4250                  *      second u_int32_t contains sets to be enabled.
4251                  */
4252                 error = sooptcopyin(sopt, rulenum,
4253                         2*sizeof(u_int32_t), sizeof(u_int32_t));
4254                 if (error)
4255                         break;
4256                 size = sopt->sopt_valsize;
4257                 if (size == sizeof(u_int32_t))  /* delete or reassign */
4258                         error = del_entry(&layer3_chain, rulenum[0]);
4259                 else if (size == 2*sizeof(u_int32_t)) /* set enable/disable */
4260                         set_disable =
4261                             (set_disable | rulenum[0]) & ~rulenum[1] &
4262                             ~(1<<RESVD_SET); /* set RESVD_SET always enabled */
4263                 else
4264                         error = EINVAL;
4265                 break;
4266
4267         case IP_FW_ZERO:
4268         case IP_FW_RESETLOG: /* argument is an u_int_32, the rule number */
4269                 rulenum[0] = 0;
4270                 if (sopt->sopt_val != 0) {
4271                     error = sooptcopyin(sopt, rulenum,
4272                             sizeof(u_int32_t), sizeof(u_int32_t));
4273                     if (error)
4274                         break;
4275                 }
4276                 error = zero_entry(&layer3_chain, rulenum[0],
4277                         sopt->sopt_name == IP_FW_RESETLOG);
4278                 break;
4279
4280         case IP_FW_TABLE_ADD:
4281                 {
4282                         ipfw_table_entry ent;
4283
4284                         error = sooptcopyin(sopt, &ent,
4285                             sizeof(ent), sizeof(ent));
4286                         if (error)
4287                                 break;
4288                         error = add_table_entry(&layer3_chain, ent.tbl,
4289                             ent.addr, ent.masklen, ent.value);
4290                 }
4291                 break;
4292
4293         case IP_FW_TABLE_DEL:
4294                 {
4295                         ipfw_table_entry ent;
4296
4297                         error = sooptcopyin(sopt, &ent,
4298                             sizeof(ent), sizeof(ent));
4299                         if (error)
4300                                 break;
4301                         error = del_table_entry(&layer3_chain, ent.tbl,
4302                             ent.addr, ent.masklen);
4303                 }
4304                 break;
4305
4306         case IP_FW_TABLE_FLUSH:
4307                 {
4308                         u_int16_t tbl;
4309
4310                         error = sooptcopyin(sopt, &tbl,
4311                             sizeof(tbl), sizeof(tbl));
4312                         if (error)
4313                                 break;
4314                         IPFW_WLOCK(&layer3_chain);
4315                         error = flush_table(&layer3_chain, tbl);
4316                         IPFW_WUNLOCK(&layer3_chain);
4317                 }
4318                 break;
4319
4320         case IP_FW_TABLE_GETSIZE:
4321                 {
4322                         u_int32_t tbl, cnt;
4323
4324                         if ((error = sooptcopyin(sopt, &tbl, sizeof(tbl),
4325                             sizeof(tbl))))
4326                                 break;
4327                         IPFW_RLOCK(&layer3_chain);
4328                         error = count_table(&layer3_chain, tbl, &cnt);
4329                         IPFW_RUNLOCK(&layer3_chain);
4330                         if (error)
4331                                 break;
4332                         error = sooptcopyout(sopt, &cnt, sizeof(cnt));
4333                 }
4334                 break;
4335
4336         case IP_FW_TABLE_LIST:
4337                 {
4338                         ipfw_table *tbl;
4339
4340                         if (sopt->sopt_valsize < sizeof(*tbl)) {
4341                                 error = EINVAL;
4342                                 break;
4343                         }
4344                         size = sopt->sopt_valsize;
4345                         tbl = malloc(size, M_TEMP, M_WAITOK);
4346                         error = sooptcopyin(sopt, tbl, size, sizeof(*tbl));
4347                         if (error) {
4348                                 free(tbl, M_TEMP);
4349                                 break;
4350                         }
4351                         tbl->size = (size - sizeof(*tbl)) /
4352                             sizeof(ipfw_table_entry);
4353                         IPFW_RLOCK(&layer3_chain);
4354                         error = dump_table(&layer3_chain, tbl);
4355                         IPFW_RUNLOCK(&layer3_chain);
4356                         if (error) {
4357                                 free(tbl, M_TEMP);
4358                                 break;
4359                         }
4360                         error = sooptcopyout(sopt, tbl, size);
4361                         free(tbl, M_TEMP);
4362                 }
4363                 break;
4364
4365         case IP_FW_NAT_CFG:
4366                 if (IPFW_NAT_LOADED)
4367                         error = ipfw_nat_cfg_ptr(sopt);
4368                 else {
4369                         printf("IP_FW_NAT_CFG: %s\n",
4370                                 "ipfw_nat not present, please load it");
4371                         error = EINVAL;
4372                 }
4373                 break;
4374
4375         case IP_FW_NAT_DEL:
4376                 if (IPFW_NAT_LOADED)
4377                         error = ipfw_nat_del_ptr(sopt);
4378                 else {
4379                         printf("IP_FW_NAT_DEL: %s\n",
4380                                 "ipfw_nat not present, please load it");
4381                         error = EINVAL;
4382                 }
4383                 break;
4384
4385         case IP_FW_NAT_GET_CONFIG:
4386                 if (IPFW_NAT_LOADED)
4387                         error = ipfw_nat_get_cfg_ptr(sopt);
4388                 else {
4389                         printf("IP_FW_NAT_GET_CFG: %s\n",
4390                                 "ipfw_nat not present, please load it");
4391                         error = EINVAL;
4392                 }
4393                 break;
4394
4395         case IP_FW_NAT_GET_LOG:
4396                 if (IPFW_NAT_LOADED)
4397                         error = ipfw_nat_get_log_ptr(sopt);
4398                 else {
4399                         printf("IP_FW_NAT_GET_LOG: %s\n",
4400                                 "ipfw_nat not present, please load it");
4401                         error = EINVAL;
4402                 }
4403                 break;
4404
4405         default:
4406                 printf("ipfw: ipfw_ctl invalid option %d\n", sopt->sopt_name);
4407                 error = EINVAL;
4408         }
4409
4410         return (error);
4411 #undef RULE_MAXSIZE
4412 }
4413
4414 /**
4415  * dummynet needs a reference to the default rule, because rules can be
4416  * deleted while packets hold a reference to them. When this happens,
4417  * dummynet changes the reference to the default rule (it could well be a
4418  * NULL pointer, but this way we do not need to check for the special
4419  * case, plus here he have info on the default behaviour).
4420  */
4421 struct ip_fw *ip_fw_default_rule;
4422
4423 /*
4424  * This procedure is only used to handle keepalives. It is invoked
4425  * every dyn_keepalive_period
4426  */
4427 static void
4428 ipfw_tick(void * __unused unused)
4429 {
4430         struct mbuf *m0, *m, *mnext, **mtailp;
4431         int i;
4432         ipfw_dyn_rule *q;
4433
4434         if (dyn_keepalive == 0 || ipfw_dyn_v == NULL || dyn_count == 0)
4435                 goto done;
4436
4437         /*
4438          * We make a chain of packets to go out here -- not deferring
4439          * until after we drop the IPFW dynamic rule lock would result
4440          * in a lock order reversal with the normal packet input -> ipfw
4441          * call stack.
4442          */
4443         m0 = NULL;
4444         mtailp = &m0;
4445         IPFW_DYN_LOCK();
4446         for (i = 0 ; i < curr_dyn_buckets ; i++) {
4447                 for (q = ipfw_dyn_v[i] ; q ; q = q->next ) {
4448                         if (q->dyn_type == O_LIMIT_PARENT)
4449                                 continue;
4450                         if (q->id.proto != IPPROTO_TCP)
4451                                 continue;
4452                         if ( (q->state & BOTH_SYN) != BOTH_SYN)
4453                                 continue;
4454                         if (TIME_LEQ( time_uptime+dyn_keepalive_interval,
4455                             q->expire))
4456                                 continue;       /* too early */
4457                         if (TIME_LEQ(q->expire, time_uptime))
4458                                 continue;       /* too late, rule expired */
4459
4460                         *mtailp = send_pkt(NULL, &(q->id), q->ack_rev - 1,
4461                                 q->ack_fwd, TH_SYN);
4462                         if (*mtailp != NULL)
4463                                 mtailp = &(*mtailp)->m_nextpkt;
4464                         *mtailp = send_pkt(NULL, &(q->id), q->ack_fwd - 1,
4465                                 q->ack_rev, 0);
4466                         if (*mtailp != NULL)
4467                                 mtailp = &(*mtailp)->m_nextpkt;
4468                 }
4469         }
4470         IPFW_DYN_UNLOCK();
4471         for (m = mnext = m0; m != NULL; m = mnext) {
4472                 mnext = m->m_nextpkt;
4473                 m->m_nextpkt = NULL;
4474                 ip_output(m, NULL, NULL, 0, NULL, NULL);
4475         }
4476 done:
4477         callout_reset(&ipfw_timeout, dyn_keepalive_period*hz, ipfw_tick, NULL);
4478 }
4479
4480 int
4481 ipfw_init(void)
4482 {
4483         struct ip_fw default_rule;
4484         int error;
4485
4486 #ifdef INET6
4487         /* Setup IPv6 fw sysctl tree. */
4488         sysctl_ctx_init(&ip6_fw_sysctl_ctx);
4489         ip6_fw_sysctl_tree = SYSCTL_ADD_NODE(&ip6_fw_sysctl_ctx,
4490             SYSCTL_STATIC_CHILDREN(_net_inet6_ip6), OID_AUTO, "fw",
4491             CTLFLAG_RW | CTLFLAG_SECURE, 0, "Firewall");
4492         SYSCTL_ADD_PROC(&ip6_fw_sysctl_ctx, SYSCTL_CHILDREN(ip6_fw_sysctl_tree),
4493             OID_AUTO, "enable", CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE3,
4494             &fw6_enable, 0, ipfw_chg_hook, "I", "Enable ipfw+6");
4495         SYSCTL_ADD_INT(&ip6_fw_sysctl_ctx, SYSCTL_CHILDREN(ip6_fw_sysctl_tree),
4496             OID_AUTO, "deny_unknown_exthdrs", CTLFLAG_RW | CTLFLAG_SECURE,
4497             &fw_deny_unknown_exthdrs, 0,
4498             "Deny packets with unknown IPv6 Extension Headers");
4499 #endif
4500
4501         layer3_chain.rules = NULL;
4502         IPFW_LOCK_INIT(&layer3_chain);
4503         ipfw_dyn_rule_zone = uma_zcreate("IPFW dynamic rule",
4504             sizeof(ipfw_dyn_rule), NULL, NULL, NULL, NULL,
4505             UMA_ALIGN_PTR, 0);
4506         IPFW_DYN_LOCK_INIT();
4507         callout_init(&ipfw_timeout, CALLOUT_MPSAFE);
4508
4509         bzero(&default_rule, sizeof default_rule);
4510
4511         default_rule.act_ofs = 0;
4512         default_rule.rulenum = IPFW_DEFAULT_RULE;
4513         default_rule.cmd_len = 1;
4514         default_rule.set = RESVD_SET;
4515
4516         default_rule.cmd[0].len = 1;
4517         default_rule.cmd[0].opcode =
4518 #ifdef IPFIREWALL_DEFAULT_TO_ACCEPT
4519                                 1 ? O_ACCEPT :
4520 #endif
4521                                 O_DENY;
4522
4523         error = add_rule(&layer3_chain, &default_rule);
4524         if (error != 0) {
4525                 printf("ipfw2: error %u initializing default rule "
4526                         "(support disabled)\n", error);
4527                 IPFW_DYN_LOCK_DESTROY();
4528                 IPFW_LOCK_DESTROY(&layer3_chain);
4529                 uma_zdestroy(ipfw_dyn_rule_zone);
4530                 return (error);
4531         }
4532
4533         ip_fw_default_rule = layer3_chain.rules;
4534         printf("ipfw2 "
4535 #ifdef INET6
4536                 "(+ipv6) "
4537 #endif
4538                 "initialized, divert %s, nat %s, "
4539                 "rule-based forwarding "
4540 #ifdef IPFIREWALL_FORWARD
4541                 "enabled, "
4542 #else
4543                 "disabled, "
4544 #endif
4545                 "default to %s, logging ",
4546 #ifdef IPDIVERT
4547                 "enabled",
4548 #else
4549                 "loadable",
4550 #endif
4551 #ifdef IPFIREWALL_NAT
4552                 "enabled",
4553 #else
4554                 "loadable",
4555 #endif
4556
4557                 default_rule.cmd[0].opcode == O_ACCEPT ? "accept" : "deny");
4558
4559 #ifdef IPFIREWALL_VERBOSE
4560         fw_verbose = 1;
4561 #endif
4562 #ifdef IPFIREWALL_VERBOSE_LIMIT
4563         verbose_limit = IPFIREWALL_VERBOSE_LIMIT;
4564 #endif
4565         if (fw_verbose == 0)
4566                 printf("disabled\n");
4567         else if (verbose_limit == 0)
4568                 printf("unlimited\n");
4569         else
4570                 printf("limited to %d packets/entry by default\n",
4571                     verbose_limit);
4572
4573         error = init_tables(&layer3_chain);
4574         if (error) {
4575                 IPFW_DYN_LOCK_DESTROY();
4576                 IPFW_LOCK_DESTROY(&layer3_chain);
4577                 uma_zdestroy(ipfw_dyn_rule_zone);
4578                 return (error);
4579         }
4580         ip_fw_ctl_ptr = ipfw_ctl;
4581         ip_fw_chk_ptr = ipfw_chk;
4582         callout_reset(&ipfw_timeout, hz, ipfw_tick, NULL);      
4583         LIST_INIT(&layer3_chain.nat);
4584         return (0);
4585 }
4586
4587 void
4588 ipfw_destroy(void)
4589 {
4590         struct ip_fw *reap;
4591
4592         ip_fw_chk_ptr = NULL;
4593         ip_fw_ctl_ptr = NULL;
4594         callout_drain(&ipfw_timeout);
4595         IPFW_WLOCK(&layer3_chain);
4596         flush_tables(&layer3_chain);
4597         layer3_chain.reap = NULL;
4598         free_chain(&layer3_chain, 1 /* kill default rule */);
4599         reap = layer3_chain.reap, layer3_chain.reap = NULL;
4600         IPFW_WUNLOCK(&layer3_chain);
4601         if (reap != NULL)
4602                 reap_rules(reap);
4603         IPFW_DYN_LOCK_DESTROY();
4604         uma_zdestroy(ipfw_dyn_rule_zone);
4605         if (ipfw_dyn_v != NULL)
4606                 free(ipfw_dyn_v, M_IPFW);
4607         IPFW_LOCK_DESTROY(&layer3_chain);
4608
4609 #ifdef INET6
4610         /* Free IPv6 fw sysctl tree. */
4611         sysctl_ctx_free(&ip6_fw_sysctl_ctx);
4612 #endif
4613
4614         printf("IP firewall unloaded\n");
4615 }