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