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