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