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