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