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