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