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