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