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