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