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