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