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