]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/netpfil/ipfw/ip_fw2.c
MFV r328249:
[FreeBSD/FreeBSD.git] / sys / netpfil / ipfw / ip_fw2.c
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2002-2009 Luigi Rizzo, Universita` di Pisa
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  */
27
28 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD$");
30
31 /*
32  * The FreeBSD IP packet firewall, main file
33  */
34
35 #include "opt_ipfw.h"
36 #include "opt_ipdivert.h"
37 #include "opt_inet.h"
38 #ifndef INET
39 #error "IPFIREWALL requires INET"
40 #endif /* INET */
41 #include "opt_inet6.h"
42
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/condvar.h>
46 #include <sys/counter.h>
47 #include <sys/eventhandler.h>
48 #include <sys/malloc.h>
49 #include <sys/mbuf.h>
50 #include <sys/kernel.h>
51 #include <sys/lock.h>
52 #include <sys/jail.h>
53 #include <sys/module.h>
54 #include <sys/priv.h>
55 #include <sys/proc.h>
56 #include <sys/rwlock.h>
57 #include <sys/rmlock.h>
58 #include <sys/socket.h>
59 #include <sys/socketvar.h>
60 #include <sys/sysctl.h>
61 #include <sys/syslog.h>
62 #include <sys/ucred.h>
63 #include <net/ethernet.h> /* for ETHERTYPE_IP */
64 #include <net/if.h>
65 #include <net/if_var.h>
66 #include <net/route.h>
67 #include <net/pfil.h>
68 #include <net/vnet.h>
69
70 #include <netpfil/pf/pf_mtag.h>
71
72 #include <netinet/in.h>
73 #include <netinet/in_var.h>
74 #include <netinet/in_pcb.h>
75 #include <netinet/ip.h>
76 #include <netinet/ip_var.h>
77 #include <netinet/ip_icmp.h>
78 #include <netinet/ip_fw.h>
79 #include <netinet/ip_carp.h>
80 #include <netinet/pim.h>
81 #include <netinet/tcp_var.h>
82 #include <netinet/udp.h>
83 #include <netinet/udp_var.h>
84 #include <netinet/sctp.h>
85 #include <netinet/sctp_crc32.h>
86 #include <netinet/sctp_header.h>
87
88 #include <netinet/ip6.h>
89 #include <netinet/icmp6.h>
90 #include <netinet/in_fib.h>
91 #ifdef INET6
92 #include <netinet6/in6_fib.h>
93 #include <netinet6/in6_pcb.h>
94 #include <netinet6/scope6_var.h>
95 #include <netinet6/ip6_var.h>
96 #endif
97
98 #include <net/if_gre.h> /* for struct grehdr */
99
100 #include <netpfil/ipfw/ip_fw_private.h>
101
102 #include <machine/in_cksum.h>   /* XXX for in_cksum */
103
104 #ifdef MAC
105 #include <security/mac/mac_framework.h>
106 #endif
107
108 /*
109  * static variables followed by global ones.
110  * All ipfw global variables are here.
111  */
112
113 static VNET_DEFINE(int, fw_deny_unknown_exthdrs);
114 #define V_fw_deny_unknown_exthdrs       VNET(fw_deny_unknown_exthdrs)
115
116 static VNET_DEFINE(int, fw_permit_single_frag6) = 1;
117 #define V_fw_permit_single_frag6        VNET(fw_permit_single_frag6)
118
119 #ifdef IPFIREWALL_DEFAULT_TO_ACCEPT
120 static int default_to_accept = 1;
121 #else
122 static int default_to_accept;
123 #endif
124
125 VNET_DEFINE(int, autoinc_step);
126 VNET_DEFINE(int, fw_one_pass) = 1;
127
128 VNET_DEFINE(unsigned int, fw_tables_max);
129 VNET_DEFINE(unsigned int, fw_tables_sets) = 0;  /* Don't use set-aware tables */
130 /* Use 128 tables by default */
131 static unsigned int default_fw_tables = IPFW_TABLES_DEFAULT;
132
133 #ifndef LINEAR_SKIPTO
134 static int jump_fast(struct ip_fw_chain *chain, struct ip_fw *f, int num,
135     int tablearg, int jump_backwards);
136 #define JUMP(ch, f, num, targ, back)    jump_fast(ch, f, num, targ, back)
137 #else
138 static int jump_linear(struct ip_fw_chain *chain, struct ip_fw *f, int num,
139     int tablearg, int jump_backwards);
140 #define JUMP(ch, f, num, targ, back)    jump_linear(ch, f, num, targ, back)
141 #endif
142
143 /*
144  * Each rule belongs to one of 32 different sets (0..31).
145  * The variable set_disable contains one bit per set.
146  * If the bit is set, all rules in the corresponding set
147  * are disabled. Set RESVD_SET(31) is reserved for the default rule
148  * and rules that are not deleted by the flush command,
149  * and CANNOT be disabled.
150  * Rules in set RESVD_SET can only be deleted individually.
151  */
152 VNET_DEFINE(u_int32_t, set_disable);
153 #define V_set_disable                   VNET(set_disable)
154
155 VNET_DEFINE(int, fw_verbose);
156 /* counter for ipfw_log(NULL...) */
157 VNET_DEFINE(u_int64_t, norule_counter);
158 VNET_DEFINE(int, verbose_limit);
159
160 /* layer3_chain contains the list of rules for layer 3 */
161 VNET_DEFINE(struct ip_fw_chain, layer3_chain);
162
163 /* ipfw_vnet_ready controls when we are open for business */
164 VNET_DEFINE(int, ipfw_vnet_ready) = 0;
165
166 VNET_DEFINE(int, ipfw_nat_ready) = 0;
167
168 ipfw_nat_t *ipfw_nat_ptr = NULL;
169 struct cfg_nat *(*lookup_nat_ptr)(struct nat_list *, int);
170 ipfw_nat_cfg_t *ipfw_nat_cfg_ptr;
171 ipfw_nat_cfg_t *ipfw_nat_del_ptr;
172 ipfw_nat_cfg_t *ipfw_nat_get_cfg_ptr;
173 ipfw_nat_cfg_t *ipfw_nat_get_log_ptr;
174
175 #ifdef SYSCTL_NODE
176 uint32_t dummy_def = IPFW_DEFAULT_RULE;
177 static int sysctl_ipfw_table_num(SYSCTL_HANDLER_ARGS);
178 static int sysctl_ipfw_tables_sets(SYSCTL_HANDLER_ARGS);
179
180 SYSBEGIN(f3)
181
182 SYSCTL_NODE(_net_inet_ip, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall");
183 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, one_pass,
184     CTLFLAG_VNET | CTLFLAG_RW | CTLFLAG_SECURE3, &VNET_NAME(fw_one_pass), 0,
185     "Only do a single pass through ipfw when using dummynet(4)");
186 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, autoinc_step,
187     CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(autoinc_step), 0,
188     "Rule number auto-increment step");
189 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose,
190     CTLFLAG_VNET | CTLFLAG_RW | CTLFLAG_SECURE3, &VNET_NAME(fw_verbose), 0,
191     "Log matches to ipfw rules");
192 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose_limit,
193     CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(verbose_limit), 0,
194     "Set upper limit of matches of ipfw rules logged");
195 SYSCTL_UINT(_net_inet_ip_fw, OID_AUTO, default_rule, CTLFLAG_RD,
196     &dummy_def, 0,
197     "The default/max possible rule number.");
198 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, tables_max,
199     CTLFLAG_VNET | CTLTYPE_UINT | CTLFLAG_RW, 0, 0, sysctl_ipfw_table_num, "IU",
200     "Maximum number of concurrently used tables");
201 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, tables_sets,
202     CTLFLAG_VNET | CTLTYPE_UINT | CTLFLAG_RW,
203     0, 0, sysctl_ipfw_tables_sets, "IU",
204     "Use per-set namespace for tables");
205 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, default_to_accept, CTLFLAG_RDTUN,
206     &default_to_accept, 0,
207     "Make the default rule accept all packets.");
208 TUNABLE_INT("net.inet.ip.fw.tables_max", (int *)&default_fw_tables);
209 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, static_count,
210     CTLFLAG_VNET | CTLFLAG_RD, &VNET_NAME(layer3_chain.n_rules), 0,
211     "Number of static rules");
212
213 #ifdef INET6
214 SYSCTL_DECL(_net_inet6_ip6);
215 SYSCTL_NODE(_net_inet6_ip6, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall");
216 SYSCTL_INT(_net_inet6_ip6_fw, OID_AUTO, deny_unknown_exthdrs,
217     CTLFLAG_VNET | CTLFLAG_RW | CTLFLAG_SECURE,
218     &VNET_NAME(fw_deny_unknown_exthdrs), 0,
219     "Deny packets with unknown IPv6 Extension Headers");
220 SYSCTL_INT(_net_inet6_ip6_fw, OID_AUTO, permit_single_frag6,
221     CTLFLAG_VNET | CTLFLAG_RW | CTLFLAG_SECURE,
222     &VNET_NAME(fw_permit_single_frag6), 0,
223     "Permit single packet IPv6 fragments");
224 #endif /* INET6 */
225
226 SYSEND
227
228 #endif /* SYSCTL_NODE */
229
230
231 /*
232  * Some macros used in the various matching options.
233  * L3HDR maps an ipv4 pointer into a layer3 header pointer of type T
234  * Other macros just cast void * into the appropriate type
235  */
236 #define L3HDR(T, ip)    ((T *)((u_int32_t *)(ip) + (ip)->ip_hl))
237 #define TCP(p)          ((struct tcphdr *)(p))
238 #define SCTP(p)         ((struct sctphdr *)(p))
239 #define UDP(p)          ((struct udphdr *)(p))
240 #define ICMP(p)         ((struct icmphdr *)(p))
241 #define ICMP6(p)        ((struct icmp6_hdr *)(p))
242
243 static __inline int
244 icmptype_match(struct icmphdr *icmp, ipfw_insn_u32 *cmd)
245 {
246         int type = icmp->icmp_type;
247
248         return (type <= ICMP_MAXTYPE && (cmd->d[0] & (1<<type)) );
249 }
250
251 #define TT      ( (1 << ICMP_ECHO) | (1 << ICMP_ROUTERSOLICIT) | \
252     (1 << ICMP_TSTAMP) | (1 << ICMP_IREQ) | (1 << ICMP_MASKREQ) )
253
254 static int
255 is_icmp_query(struct icmphdr *icmp)
256 {
257         int type = icmp->icmp_type;
258
259         return (type <= ICMP_MAXTYPE && (TT & (1<<type)) );
260 }
261 #undef TT
262
263 /*
264  * The following checks use two arrays of 8 or 16 bits to store the
265  * bits that we want set or clear, respectively. They are in the
266  * low and high half of cmd->arg1 or cmd->d[0].
267  *
268  * We scan options and store the bits we find set. We succeed if
269  *
270  *      (want_set & ~bits) == 0 && (want_clear & ~bits) == want_clear
271  *
272  * The code is sometimes optimized not to store additional variables.
273  */
274
275 static int
276 flags_match(ipfw_insn *cmd, u_int8_t bits)
277 {
278         u_char want_clear;
279         bits = ~bits;
280
281         if ( ((cmd->arg1 & 0xff) & bits) != 0)
282                 return 0; /* some bits we want set were clear */
283         want_clear = (cmd->arg1 >> 8) & 0xff;
284         if ( (want_clear & bits) != want_clear)
285                 return 0; /* some bits we want clear were set */
286         return 1;
287 }
288
289 static int
290 ipopts_match(struct ip *ip, ipfw_insn *cmd)
291 {
292         int optlen, bits = 0;
293         u_char *cp = (u_char *)(ip + 1);
294         int x = (ip->ip_hl << 2) - sizeof (struct ip);
295
296         for (; x > 0; x -= optlen, cp += optlen) {
297                 int opt = cp[IPOPT_OPTVAL];
298
299                 if (opt == IPOPT_EOL)
300                         break;
301                 if (opt == IPOPT_NOP)
302                         optlen = 1;
303                 else {
304                         optlen = cp[IPOPT_OLEN];
305                         if (optlen <= 0 || optlen > x)
306                                 return 0; /* invalid or truncated */
307                 }
308                 switch (opt) {
309
310                 default:
311                         break;
312
313                 case IPOPT_LSRR:
314                         bits |= IP_FW_IPOPT_LSRR;
315                         break;
316
317                 case IPOPT_SSRR:
318                         bits |= IP_FW_IPOPT_SSRR;
319                         break;
320
321                 case IPOPT_RR:
322                         bits |= IP_FW_IPOPT_RR;
323                         break;
324
325                 case IPOPT_TS:
326                         bits |= IP_FW_IPOPT_TS;
327                         break;
328                 }
329         }
330         return (flags_match(cmd, bits));
331 }
332
333 static int
334 tcpopts_match(struct tcphdr *tcp, ipfw_insn *cmd)
335 {
336         int optlen, bits = 0;
337         u_char *cp = (u_char *)(tcp + 1);
338         int x = (tcp->th_off << 2) - sizeof(struct tcphdr);
339
340         for (; x > 0; x -= optlen, cp += optlen) {
341                 int opt = cp[0];
342                 if (opt == TCPOPT_EOL)
343                         break;
344                 if (opt == TCPOPT_NOP)
345                         optlen = 1;
346                 else {
347                         optlen = cp[1];
348                         if (optlen <= 0)
349                                 break;
350                 }
351
352                 switch (opt) {
353
354                 default:
355                         break;
356
357                 case TCPOPT_MAXSEG:
358                         bits |= IP_FW_TCPOPT_MSS;
359                         break;
360
361                 case TCPOPT_WINDOW:
362                         bits |= IP_FW_TCPOPT_WINDOW;
363                         break;
364
365                 case TCPOPT_SACK_PERMITTED:
366                 case TCPOPT_SACK:
367                         bits |= IP_FW_TCPOPT_SACK;
368                         break;
369
370                 case TCPOPT_TIMESTAMP:
371                         bits |= IP_FW_TCPOPT_TS;
372                         break;
373
374                 }
375         }
376         return (flags_match(cmd, bits));
377 }
378
379 static int
380 iface_match(struct ifnet *ifp, ipfw_insn_if *cmd, struct ip_fw_chain *chain,
381     uint32_t *tablearg)
382 {
383
384         if (ifp == NULL)        /* no iface with this packet, match fails */
385                 return (0);
386
387         /* Check by name or by IP address */
388         if (cmd->name[0] != '\0') { /* match by name */
389                 if (cmd->name[0] == '\1') /* use tablearg to match */
390                         return ipfw_lookup_table(chain, cmd->p.kidx, 0,
391                             &ifp->if_index, tablearg);
392                 /* Check name */
393                 if (cmd->p.glob) {
394                         if (fnmatch(cmd->name, ifp->if_xname, 0) == 0)
395                                 return(1);
396                 } else {
397                         if (strncmp(ifp->if_xname, cmd->name, IFNAMSIZ) == 0)
398                                 return(1);
399                 }
400         } else {
401 #if !defined(USERSPACE) && defined(__FreeBSD__) /* and OSX too ? */
402                 struct ifaddr *ia;
403
404                 if_addr_rlock(ifp);
405                 TAILQ_FOREACH(ia, &ifp->if_addrhead, ifa_link) {
406                         if (ia->ifa_addr->sa_family != AF_INET)
407                                 continue;
408                         if (cmd->p.ip.s_addr == ((struct sockaddr_in *)
409                             (ia->ifa_addr))->sin_addr.s_addr) {
410                                 if_addr_runlock(ifp);
411                                 return(1);      /* match */
412                         }
413                 }
414                 if_addr_runlock(ifp);
415 #endif /* __FreeBSD__ */
416         }
417         return(0);      /* no match, fail ... */
418 }
419
420 /*
421  * The verify_path function checks if a route to the src exists and
422  * if it is reachable via ifp (when provided).
423  * 
424  * The 'verrevpath' option checks that the interface that an IP packet
425  * arrives on is the same interface that traffic destined for the
426  * packet's source address would be routed out of.
427  * The 'versrcreach' option just checks that the source address is
428  * reachable via any route (except default) in the routing table.
429  * These two are a measure to block forged packets. This is also
430  * commonly known as "anti-spoofing" or Unicast Reverse Path
431  * Forwarding (Unicast RFP) in Cisco-ese. The name of the knobs
432  * is purposely reminiscent of the Cisco IOS command,
433  *
434  *   ip verify unicast reverse-path
435  *   ip verify unicast source reachable-via any
436  *
437  * which implements the same functionality. But note that the syntax
438  * is misleading, and the check may be performed on all IP packets
439  * whether unicast, multicast, or broadcast.
440  */
441 static int
442 verify_path(struct in_addr src, struct ifnet *ifp, u_int fib)
443 {
444 #if defined(USERSPACE) || !defined(__FreeBSD__)
445         return 0;
446 #else
447         struct nhop4_basic nh4;
448
449         if (fib4_lookup_nh_basic(fib, src, NHR_IFAIF, 0, &nh4) != 0)
450                 return (0);
451
452         /*
453          * If ifp is provided, check for equality with rtentry.
454          * We should use rt->rt_ifa->ifa_ifp, instead of rt->rt_ifp,
455          * in order to pass packets injected back by if_simloop():
456          * routing entry (via lo0) for our own address
457          * may exist, so we need to handle routing assymetry.
458          */
459         if (ifp != NULL && ifp != nh4.nh_ifp)
460                 return (0);
461
462         /* if no ifp provided, check if rtentry is not default route */
463         if (ifp == NULL && (nh4.nh_flags & NHF_DEFAULT) != 0)
464                 return (0);
465
466         /* or if this is a blackhole/reject route */
467         if (ifp == NULL && (nh4.nh_flags & (NHF_REJECT|NHF_BLACKHOLE)) != 0)
468                 return (0);
469
470         /* found valid route */
471         return 1;
472 #endif /* __FreeBSD__ */
473 }
474
475 /*
476  * Generate an SCTP packet containing an ABORT chunk. The verification tag
477  * is given by vtag. The T-bit is set in the ABORT chunk if and only if
478  * reflected is not 0.
479  */
480
481 static struct mbuf *
482 ipfw_send_abort(struct mbuf *replyto, struct ipfw_flow_id *id, u_int32_t vtag,
483     int reflected)
484 {
485         struct mbuf *m;
486         struct ip *ip;
487 #ifdef INET6
488         struct ip6_hdr *ip6;
489 #endif
490         struct sctphdr *sctp;
491         struct sctp_chunkhdr *chunk;
492         u_int16_t hlen, plen, tlen;
493
494         MGETHDR(m, M_NOWAIT, MT_DATA);
495         if (m == NULL)
496                 return (NULL);
497
498         M_SETFIB(m, id->fib);
499 #ifdef MAC
500         if (replyto != NULL)
501                 mac_netinet_firewall_reply(replyto, m);
502         else
503                 mac_netinet_firewall_send(m);
504 #else
505         (void)replyto;          /* don't warn about unused arg */
506 #endif
507
508         switch (id->addr_type) {
509         case 4:
510                 hlen = sizeof(struct ip);
511                 break;
512 #ifdef INET6
513         case 6:
514                 hlen = sizeof(struct ip6_hdr);
515                 break;
516 #endif
517         default:
518                 /* XXX: log me?!? */
519                 FREE_PKT(m);
520                 return (NULL);
521         }
522         plen = sizeof(struct sctphdr) + sizeof(struct sctp_chunkhdr);
523         tlen = hlen + plen;
524         m->m_data += max_linkhdr;
525         m->m_flags |= M_SKIP_FIREWALL;
526         m->m_pkthdr.len = m->m_len = tlen;
527         m->m_pkthdr.rcvif = NULL;
528         bzero(m->m_data, tlen);
529
530         switch (id->addr_type) {
531         case 4:
532                 ip = mtod(m, struct ip *);
533
534                 ip->ip_v = 4;
535                 ip->ip_hl = sizeof(struct ip) >> 2;
536                 ip->ip_tos = IPTOS_LOWDELAY;
537                 ip->ip_len = htons(tlen);
538                 ip->ip_id = htons(0);
539                 ip->ip_off = htons(0);
540                 ip->ip_ttl = V_ip_defttl;
541                 ip->ip_p = IPPROTO_SCTP;
542                 ip->ip_sum = 0;
543                 ip->ip_src.s_addr = htonl(id->dst_ip);
544                 ip->ip_dst.s_addr = htonl(id->src_ip);
545
546                 sctp = (struct sctphdr *)(ip + 1);
547                 break;
548 #ifdef INET6
549         case 6:
550                 ip6 = mtod(m, struct ip6_hdr *);
551
552                 ip6->ip6_vfc = IPV6_VERSION;
553                 ip6->ip6_plen = htons(plen);
554                 ip6->ip6_nxt = IPPROTO_SCTP;
555                 ip6->ip6_hlim = IPV6_DEFHLIM;
556                 ip6->ip6_src = id->dst_ip6;
557                 ip6->ip6_dst = id->src_ip6;
558
559                 sctp = (struct sctphdr *)(ip6 + 1);
560                 break;
561 #endif
562         }
563
564         sctp->src_port = htons(id->dst_port);
565         sctp->dest_port = htons(id->src_port);
566         sctp->v_tag = htonl(vtag);
567         sctp->checksum = htonl(0);
568
569         chunk = (struct sctp_chunkhdr *)(sctp + 1);
570         chunk->chunk_type = SCTP_ABORT_ASSOCIATION;
571         chunk->chunk_flags = 0;
572         if (reflected != 0) {
573                 chunk->chunk_flags |= SCTP_HAD_NO_TCB;
574         }
575         chunk->chunk_length = htons(sizeof(struct sctp_chunkhdr));
576
577         sctp->checksum = sctp_calculate_cksum(m, hlen);
578
579         return (m);
580 }
581
582 /*
583  * Generate a TCP packet, containing either a RST or a keepalive.
584  * When flags & TH_RST, we are sending a RST packet, because of a
585  * "reset" action matched the packet.
586  * Otherwise we are sending a keepalive, and flags & TH_
587  * The 'replyto' mbuf is the mbuf being replied to, if any, and is required
588  * so that MAC can label the reply appropriately.
589  */
590 struct mbuf *
591 ipfw_send_pkt(struct mbuf *replyto, struct ipfw_flow_id *id, u_int32_t seq,
592     u_int32_t ack, int flags)
593 {
594         struct mbuf *m = NULL;          /* stupid compiler */
595         struct ip *h = NULL;            /* stupid compiler */
596 #ifdef INET6
597         struct ip6_hdr *h6 = NULL;
598 #endif
599         struct tcphdr *th = NULL;
600         int len, dir;
601
602         MGETHDR(m, M_NOWAIT, MT_DATA);
603         if (m == NULL)
604                 return (NULL);
605
606         M_SETFIB(m, id->fib);
607 #ifdef MAC
608         if (replyto != NULL)
609                 mac_netinet_firewall_reply(replyto, m);
610         else
611                 mac_netinet_firewall_send(m);
612 #else
613         (void)replyto;          /* don't warn about unused arg */
614 #endif
615
616         switch (id->addr_type) {
617         case 4:
618                 len = sizeof(struct ip) + sizeof(struct tcphdr);
619                 break;
620 #ifdef INET6
621         case 6:
622                 len = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
623                 break;
624 #endif
625         default:
626                 /* XXX: log me?!? */
627                 FREE_PKT(m);
628                 return (NULL);
629         }
630         dir = ((flags & (TH_SYN | TH_RST)) == TH_SYN);
631
632         m->m_data += max_linkhdr;
633         m->m_flags |= M_SKIP_FIREWALL;
634         m->m_pkthdr.len = m->m_len = len;
635         m->m_pkthdr.rcvif = NULL;
636         bzero(m->m_data, len);
637
638         switch (id->addr_type) {
639         case 4:
640                 h = mtod(m, struct ip *);
641
642                 /* prepare for checksum */
643                 h->ip_p = IPPROTO_TCP;
644                 h->ip_len = htons(sizeof(struct tcphdr));
645                 if (dir) {
646                         h->ip_src.s_addr = htonl(id->src_ip);
647                         h->ip_dst.s_addr = htonl(id->dst_ip);
648                 } else {
649                         h->ip_src.s_addr = htonl(id->dst_ip);
650                         h->ip_dst.s_addr = htonl(id->src_ip);
651                 }
652
653                 th = (struct tcphdr *)(h + 1);
654                 break;
655 #ifdef INET6
656         case 6:
657                 h6 = mtod(m, struct ip6_hdr *);
658
659                 /* prepare for checksum */
660                 h6->ip6_nxt = IPPROTO_TCP;
661                 h6->ip6_plen = htons(sizeof(struct tcphdr));
662                 if (dir) {
663                         h6->ip6_src = id->src_ip6;
664                         h6->ip6_dst = id->dst_ip6;
665                 } else {
666                         h6->ip6_src = id->dst_ip6;
667                         h6->ip6_dst = id->src_ip6;
668                 }
669
670                 th = (struct tcphdr *)(h6 + 1);
671                 break;
672 #endif
673         }
674
675         if (dir) {
676                 th->th_sport = htons(id->src_port);
677                 th->th_dport = htons(id->dst_port);
678         } else {
679                 th->th_sport = htons(id->dst_port);
680                 th->th_dport = htons(id->src_port);
681         }
682         th->th_off = sizeof(struct tcphdr) >> 2;
683
684         if (flags & TH_RST) {
685                 if (flags & TH_ACK) {
686                         th->th_seq = htonl(ack);
687                         th->th_flags = TH_RST;
688                 } else {
689                         if (flags & TH_SYN)
690                                 seq++;
691                         th->th_ack = htonl(seq);
692                         th->th_flags = TH_RST | TH_ACK;
693                 }
694         } else {
695                 /*
696                  * Keepalive - use caller provided sequence numbers
697                  */
698                 th->th_seq = htonl(seq);
699                 th->th_ack = htonl(ack);
700                 th->th_flags = TH_ACK;
701         }
702
703         switch (id->addr_type) {
704         case 4:
705                 th->th_sum = in_cksum(m, len);
706
707                 /* finish the ip header */
708                 h->ip_v = 4;
709                 h->ip_hl = sizeof(*h) >> 2;
710                 h->ip_tos = IPTOS_LOWDELAY;
711                 h->ip_off = htons(0);
712                 h->ip_len = htons(len);
713                 h->ip_ttl = V_ip_defttl;
714                 h->ip_sum = 0;
715                 break;
716 #ifdef INET6
717         case 6:
718                 th->th_sum = in6_cksum(m, IPPROTO_TCP, sizeof(*h6),
719                     sizeof(struct tcphdr));
720
721                 /* finish the ip6 header */
722                 h6->ip6_vfc |= IPV6_VERSION;
723                 h6->ip6_hlim = IPV6_DEFHLIM;
724                 break;
725 #endif
726         }
727
728         return (m);
729 }
730
731 #ifdef INET6
732 /*
733  * ipv6 specific rules here...
734  */
735 static __inline int
736 icmp6type_match (int type, ipfw_insn_u32 *cmd)
737 {
738         return (type <= ICMP6_MAXTYPE && (cmd->d[type/32] & (1<<(type%32)) ) );
739 }
740
741 static int
742 flow6id_match( int curr_flow, ipfw_insn_u32 *cmd )
743 {
744         int i;
745         for (i=0; i <= cmd->o.arg1; ++i )
746                 if (curr_flow == cmd->d[i] )
747                         return 1;
748         return 0;
749 }
750
751 /* support for IP6_*_ME opcodes */
752 static const struct in6_addr lla_mask = {{{
753         0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff,
754         0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff
755 }}};
756
757 static int
758 ipfw_localip6(struct in6_addr *in6)
759 {
760         struct rm_priotracker in6_ifa_tracker;
761         struct in6_ifaddr *ia;
762
763         if (IN6_IS_ADDR_MULTICAST(in6))
764                 return (0);
765
766         if (!IN6_IS_ADDR_LINKLOCAL(in6))
767                 return (in6_localip(in6));
768
769         IN6_IFADDR_RLOCK(&in6_ifa_tracker);
770         TAILQ_FOREACH(ia, &V_in6_ifaddrhead, ia_link) {
771                 if (!IN6_IS_ADDR_LINKLOCAL(&ia->ia_addr.sin6_addr))
772                         continue;
773                 if (IN6_ARE_MASKED_ADDR_EQUAL(&ia->ia_addr.sin6_addr,
774                     in6, &lla_mask)) {
775                         IN6_IFADDR_RUNLOCK(&in6_ifa_tracker);
776                         return (1);
777                 }
778         }
779         IN6_IFADDR_RUNLOCK(&in6_ifa_tracker);
780         return (0);
781 }
782
783 static int
784 verify_path6(struct in6_addr *src, struct ifnet *ifp, u_int fib)
785 {
786         struct nhop6_basic nh6;
787
788         if (IN6_IS_SCOPE_LINKLOCAL(src))
789                 return (1);
790
791         if (fib6_lookup_nh_basic(fib, src, 0, NHR_IFAIF, 0, &nh6) != 0)
792                 return (0);
793
794         /* If ifp is provided, check for equality with route table. */
795         if (ifp != NULL && ifp != nh6.nh_ifp)
796                 return (0);
797
798         /* if no ifp provided, check if rtentry is not default route */
799         if (ifp == NULL && (nh6.nh_flags & NHF_DEFAULT) != 0)
800                 return (0);
801
802         /* or if this is a blackhole/reject route */
803         if (ifp == NULL && (nh6.nh_flags & (NHF_REJECT|NHF_BLACKHOLE)) != 0)
804                 return (0);
805
806         /* found valid route */
807         return 1;
808 }
809
810 static int
811 is_icmp6_query(int icmp6_type)
812 {
813         if ((icmp6_type <= ICMP6_MAXTYPE) &&
814             (icmp6_type == ICMP6_ECHO_REQUEST ||
815             icmp6_type == ICMP6_MEMBERSHIP_QUERY ||
816             icmp6_type == ICMP6_WRUREQUEST ||
817             icmp6_type == ICMP6_FQDN_QUERY ||
818             icmp6_type == ICMP6_NI_QUERY))
819                 return (1);
820
821         return (0);
822 }
823
824 static void
825 send_reject6(struct ip_fw_args *args, int code, u_int hlen, struct ip6_hdr *ip6)
826 {
827         struct mbuf *m;
828
829         m = args->m;
830         if (code == ICMP6_UNREACH_RST && args->f_id.proto == IPPROTO_TCP) {
831                 struct tcphdr *tcp;
832                 tcp = (struct tcphdr *)((char *)ip6 + hlen);
833
834                 if ((tcp->th_flags & TH_RST) == 0) {
835                         struct mbuf *m0;
836                         m0 = ipfw_send_pkt(args->m, &(args->f_id),
837                             ntohl(tcp->th_seq), ntohl(tcp->th_ack),
838                             tcp->th_flags | TH_RST);
839                         if (m0 != NULL)
840                                 ip6_output(m0, NULL, NULL, 0, NULL, NULL,
841                                     NULL);
842                 }
843                 FREE_PKT(m);
844         } else if (code == ICMP6_UNREACH_ABORT &&
845             args->f_id.proto == IPPROTO_SCTP) {
846                 struct mbuf *m0;
847                 struct sctphdr *sctp;
848                 u_int32_t v_tag;
849                 int reflected;
850
851                 sctp = (struct sctphdr *)((char *)ip6 + hlen);
852                 reflected = 1;
853                 v_tag = ntohl(sctp->v_tag);
854                 /* Investigate the first chunk header if available */
855                 if (m->m_len >= hlen + sizeof(struct sctphdr) +
856                     sizeof(struct sctp_chunkhdr)) {
857                         struct sctp_chunkhdr *chunk;
858
859                         chunk = (struct sctp_chunkhdr *)(sctp + 1);
860                         switch (chunk->chunk_type) {
861                         case SCTP_INITIATION:
862                                 /*
863                                  * Packets containing an INIT chunk MUST have
864                                  * a zero v-tag.
865                                  */
866                                 if (v_tag != 0) {
867                                         v_tag = 0;
868                                         break;
869                                 }
870                                 /* INIT chunk MUST NOT be bundled */
871                                 if (m->m_pkthdr.len >
872                                     hlen + sizeof(struct sctphdr) +
873                                     ntohs(chunk->chunk_length) + 3) {
874                                         break;
875                                 }
876                                 /* Use the initiate tag if available */
877                                 if ((m->m_len >= hlen + sizeof(struct sctphdr) +
878                                     sizeof(struct sctp_chunkhdr) +
879                                     offsetof(struct sctp_init, a_rwnd))) {
880                                         struct sctp_init *init;
881
882                                         init = (struct sctp_init *)(chunk + 1);
883                                         v_tag = ntohl(init->initiate_tag);
884                                         reflected = 0;
885                                 }
886                                 break;
887                         case SCTP_ABORT_ASSOCIATION:
888                                 /*
889                                  * If the packet contains an ABORT chunk, don't
890                                  * reply.
891                                  * XXX: We should search through all chunks,
892                                  *      but don't do to avoid attacks.
893                                  */
894                                 v_tag = 0;
895                                 break;
896                         }
897                 }
898                 if (v_tag == 0) {
899                         m0 = NULL;
900                 } else {
901                         m0 = ipfw_send_abort(args->m, &(args->f_id), v_tag,
902                             reflected);
903                 }
904                 if (m0 != NULL)
905                         ip6_output(m0, NULL, NULL, 0, NULL, NULL, NULL);
906                 FREE_PKT(m);
907         } else if (code != ICMP6_UNREACH_RST && code != ICMP6_UNREACH_ABORT) {
908                 /* Send an ICMPv6 unreach. */
909 #if 0
910                 /*
911                  * Unlike above, the mbufs need to line up with the ip6 hdr,
912                  * as the contents are read. We need to m_adj() the
913                  * needed amount.
914                  * The mbuf will however be thrown away so we can adjust it.
915                  * Remember we did an m_pullup on it already so we
916                  * can make some assumptions about contiguousness.
917                  */
918                 if (args->L3offset)
919                         m_adj(m, args->L3offset);
920 #endif
921                 icmp6_error(m, ICMP6_DST_UNREACH, code, 0);
922         } else
923                 FREE_PKT(m);
924
925         args->m = NULL;
926 }
927
928 #endif /* INET6 */
929
930
931 /*
932  * sends a reject message, consuming the mbuf passed as an argument.
933  */
934 static void
935 send_reject(struct ip_fw_args *args, int code, int iplen, struct ip *ip)
936 {
937
938 #if 0
939         /* XXX When ip is not guaranteed to be at mtod() we will
940          * need to account for this */
941          * The mbuf will however be thrown away so we can adjust it.
942          * Remember we did an m_pullup on it already so we
943          * can make some assumptions about contiguousness.
944          */
945         if (args->L3offset)
946                 m_adj(m, args->L3offset);
947 #endif
948         if (code != ICMP_REJECT_RST && code != ICMP_REJECT_ABORT) {
949                 /* Send an ICMP unreach */
950                 icmp_error(args->m, ICMP_UNREACH, code, 0L, 0);
951         } else if (code == ICMP_REJECT_RST && args->f_id.proto == IPPROTO_TCP) {
952                 struct tcphdr *const tcp =
953                     L3HDR(struct tcphdr, mtod(args->m, struct ip *));
954                 if ( (tcp->th_flags & TH_RST) == 0) {
955                         struct mbuf *m;
956                         m = ipfw_send_pkt(args->m, &(args->f_id),
957                                 ntohl(tcp->th_seq), ntohl(tcp->th_ack),
958                                 tcp->th_flags | TH_RST);
959                         if (m != NULL)
960                                 ip_output(m, NULL, NULL, 0, NULL, NULL);
961                 }
962                 FREE_PKT(args->m);
963         } else if (code == ICMP_REJECT_ABORT &&
964             args->f_id.proto == IPPROTO_SCTP) {
965                 struct mbuf *m;
966                 struct sctphdr *sctp;
967                 struct sctp_chunkhdr *chunk;
968                 struct sctp_init *init;
969                 u_int32_t v_tag;
970                 int reflected;
971
972                 sctp = L3HDR(struct sctphdr, mtod(args->m, struct ip *));
973                 reflected = 1;
974                 v_tag = ntohl(sctp->v_tag);
975                 if (iplen >= (ip->ip_hl << 2) + sizeof(struct sctphdr) +
976                     sizeof(struct sctp_chunkhdr)) {
977                         /* Look at the first chunk header if available */
978                         chunk = (struct sctp_chunkhdr *)(sctp + 1);
979                         switch (chunk->chunk_type) {
980                         case SCTP_INITIATION:
981                                 /*
982                                  * Packets containing an INIT chunk MUST have
983                                  * a zero v-tag.
984                                  */
985                                 if (v_tag != 0) {
986                                         v_tag = 0;
987                                         break;
988                                 }
989                                 /* INIT chunk MUST NOT be bundled */
990                                 if (iplen >
991                                     (ip->ip_hl << 2) + sizeof(struct sctphdr) +
992                                     ntohs(chunk->chunk_length) + 3) {
993                                         break;
994                                 }
995                                 /* Use the initiate tag if available */
996                                 if ((iplen >= (ip->ip_hl << 2) +
997                                     sizeof(struct sctphdr) +
998                                     sizeof(struct sctp_chunkhdr) +
999                                     offsetof(struct sctp_init, a_rwnd))) {
1000                                         init = (struct sctp_init *)(chunk + 1);
1001                                         v_tag = ntohl(init->initiate_tag);
1002                                         reflected = 0;
1003                                 }
1004                                 break;
1005                         case SCTP_ABORT_ASSOCIATION:
1006                                 /*
1007                                  * If the packet contains an ABORT chunk, don't
1008                                  * reply.
1009                                  * XXX: We should search through all chunks,
1010                                  * but don't do to avoid attacks.
1011                                  */
1012                                 v_tag = 0;
1013                                 break;
1014                         }
1015                 }
1016                 if (v_tag == 0) {
1017                         m = NULL;
1018                 } else {
1019                         m = ipfw_send_abort(args->m, &(args->f_id), v_tag,
1020                             reflected);
1021                 }
1022                 if (m != NULL)
1023                         ip_output(m, NULL, NULL, 0, NULL, NULL);
1024                 FREE_PKT(args->m);
1025         } else
1026                 FREE_PKT(args->m);
1027         args->m = NULL;
1028 }
1029
1030 /*
1031  * Support for uid/gid/jail lookup. These tests are expensive
1032  * (because we may need to look into the list of active sockets)
1033  * so we cache the results. ugid_lookupp is 0 if we have not
1034  * yet done a lookup, 1 if we succeeded, and -1 if we tried
1035  * and failed. The function always returns the match value.
1036  * We could actually spare the variable and use *uc, setting
1037  * it to '(void *)check_uidgid if we have no info, NULL if
1038  * we tried and failed, or any other value if successful.
1039  */
1040 static int
1041 check_uidgid(ipfw_insn_u32 *insn, struct ip_fw_args *args, int *ugid_lookupp,
1042     struct ucred **uc)
1043 {
1044 #if defined(USERSPACE)
1045         return 0;       // not supported in userspace
1046 #else
1047 #ifndef __FreeBSD__
1048         /* XXX */
1049         return cred_check(insn, proto, oif,
1050             dst_ip, dst_port, src_ip, src_port,
1051             (struct bsd_ucred *)uc, ugid_lookupp, ((struct mbuf *)inp)->m_skb);
1052 #else  /* FreeBSD */
1053         struct in_addr src_ip, dst_ip;
1054         struct inpcbinfo *pi;
1055         struct ipfw_flow_id *id;
1056         struct inpcb *pcb, *inp;
1057         struct ifnet *oif;
1058         int lookupflags;
1059         int match;
1060
1061         id = &args->f_id;
1062         inp = args->inp;
1063         oif = args->oif;
1064
1065         /*
1066          * Check to see if the UDP or TCP stack supplied us with
1067          * the PCB. If so, rather then holding a lock and looking
1068          * up the PCB, we can use the one that was supplied.
1069          */
1070         if (inp && *ugid_lookupp == 0) {
1071                 INP_LOCK_ASSERT(inp);
1072                 if (inp->inp_socket != NULL) {
1073                         *uc = crhold(inp->inp_cred);
1074                         *ugid_lookupp = 1;
1075                 } else
1076                         *ugid_lookupp = -1;
1077         }
1078         /*
1079          * If we have already been here and the packet has no
1080          * PCB entry associated with it, then we can safely
1081          * assume that this is a no match.
1082          */
1083         if (*ugid_lookupp == -1)
1084                 return (0);
1085         if (id->proto == IPPROTO_TCP) {
1086                 lookupflags = 0;
1087                 pi = &V_tcbinfo;
1088         } else if (id->proto == IPPROTO_UDP) {
1089                 lookupflags = INPLOOKUP_WILDCARD;
1090                 pi = &V_udbinfo;
1091         } else if (id->proto == IPPROTO_UDPLITE) {
1092                 lookupflags = INPLOOKUP_WILDCARD;
1093                 pi = &V_ulitecbinfo;
1094         } else
1095                 return 0;
1096         lookupflags |= INPLOOKUP_RLOCKPCB;
1097         match = 0;
1098         if (*ugid_lookupp == 0) {
1099                 if (id->addr_type == 6) {
1100 #ifdef INET6
1101                         if (oif == NULL)
1102                                 pcb = in6_pcblookup_mbuf(pi,
1103                                     &id->src_ip6, htons(id->src_port),
1104                                     &id->dst_ip6, htons(id->dst_port),
1105                                     lookupflags, oif, args->m);
1106                         else
1107                                 pcb = in6_pcblookup_mbuf(pi,
1108                                     &id->dst_ip6, htons(id->dst_port),
1109                                     &id->src_ip6, htons(id->src_port),
1110                                     lookupflags, oif, args->m);
1111 #else
1112                         *ugid_lookupp = -1;
1113                         return (0);
1114 #endif
1115                 } else {
1116                         src_ip.s_addr = htonl(id->src_ip);
1117                         dst_ip.s_addr = htonl(id->dst_ip);
1118                         if (oif == NULL)
1119                                 pcb = in_pcblookup_mbuf(pi,
1120                                     src_ip, htons(id->src_port),
1121                                     dst_ip, htons(id->dst_port),
1122                                     lookupflags, oif, args->m);
1123                         else
1124                                 pcb = in_pcblookup_mbuf(pi,
1125                                     dst_ip, htons(id->dst_port),
1126                                     src_ip, htons(id->src_port),
1127                                     lookupflags, oif, args->m);
1128                 }
1129                 if (pcb != NULL) {
1130                         INP_RLOCK_ASSERT(pcb);
1131                         *uc = crhold(pcb->inp_cred);
1132                         *ugid_lookupp = 1;
1133                         INP_RUNLOCK(pcb);
1134                 }
1135                 if (*ugid_lookupp == 0) {
1136                         /*
1137                          * We tried and failed, set the variable to -1
1138                          * so we will not try again on this packet.
1139                          */
1140                         *ugid_lookupp = -1;
1141                         return (0);
1142                 }
1143         }
1144         if (insn->o.opcode == O_UID)
1145                 match = ((*uc)->cr_uid == (uid_t)insn->d[0]);
1146         else if (insn->o.opcode == O_GID)
1147                 match = groupmember((gid_t)insn->d[0], *uc);
1148         else if (insn->o.opcode == O_JAIL)
1149                 match = ((*uc)->cr_prison->pr_id == (int)insn->d[0]);
1150         return (match);
1151 #endif /* __FreeBSD__ */
1152 #endif /* not supported in userspace */
1153 }
1154
1155 /*
1156  * Helper function to set args with info on the rule after the matching
1157  * one. slot is precise, whereas we guess rule_id as they are
1158  * assigned sequentially.
1159  */
1160 static inline void
1161 set_match(struct ip_fw_args *args, int slot,
1162         struct ip_fw_chain *chain)
1163 {
1164         args->rule.chain_id = chain->id;
1165         args->rule.slot = slot + 1; /* we use 0 as a marker */
1166         args->rule.rule_id = 1 + chain->map[slot]->id;
1167         args->rule.rulenum = chain->map[slot]->rulenum;
1168 }
1169
1170 #ifndef LINEAR_SKIPTO
1171 /*
1172  * Helper function to enable cached rule lookups using
1173  * cached_id and cached_pos fields in ipfw rule.
1174  */
1175 static int
1176 jump_fast(struct ip_fw_chain *chain, struct ip_fw *f, int num,
1177     int tablearg, int jump_backwards)
1178 {
1179         int f_pos;
1180
1181         /* If possible use cached f_pos (in f->cached_pos),
1182          * whose version is written in f->cached_id
1183          * (horrible hacks to avoid changing the ABI).
1184          */
1185         if (num != IP_FW_TARG && f->cached_id == chain->id)
1186                 f_pos = f->cached_pos;
1187         else {
1188                 int i = IP_FW_ARG_TABLEARG(chain, num, skipto);
1189                 /* make sure we do not jump backward */
1190                 if (jump_backwards == 0 && i <= f->rulenum)
1191                         i = f->rulenum + 1;
1192                 if (chain->idxmap != NULL)
1193                         f_pos = chain->idxmap[i];
1194                 else
1195                         f_pos = ipfw_find_rule(chain, i, 0);
1196                 /* update the cache */
1197                 if (num != IP_FW_TARG) {
1198                         f->cached_id = chain->id;
1199                         f->cached_pos = f_pos;
1200                 }
1201         }
1202
1203         return (f_pos);
1204 }
1205 #else
1206 /*
1207  * Helper function to enable real fast rule lookups.
1208  */
1209 static int
1210 jump_linear(struct ip_fw_chain *chain, struct ip_fw *f, int num,
1211     int tablearg, int jump_backwards)
1212 {
1213         int f_pos;
1214
1215         num = IP_FW_ARG_TABLEARG(chain, num, skipto);
1216         /* make sure we do not jump backward */
1217         if (jump_backwards == 0 && num <= f->rulenum)
1218                 num = f->rulenum + 1;
1219         f_pos = chain->idxmap[num];
1220
1221         return (f_pos);
1222 }
1223 #endif
1224
1225 #define TARG(k, f)      IP_FW_ARG_TABLEARG(chain, k, f)
1226 /*
1227  * The main check routine for the firewall.
1228  *
1229  * All arguments are in args so we can modify them and return them
1230  * back to the caller.
1231  *
1232  * Parameters:
1233  *
1234  *      args->m (in/out) The packet; we set to NULL when/if we nuke it.
1235  *              Starts with the IP header.
1236  *      args->eh (in)   Mac header if present, NULL for layer3 packet.
1237  *      args->L3offset  Number of bytes bypassed if we came from L2.
1238  *                      e.g. often sizeof(eh)  ** NOTYET **
1239  *      args->oif       Outgoing interface, NULL if packet is incoming.
1240  *              The incoming interface is in the mbuf. (in)
1241  *      args->divert_rule (in/out)
1242  *              Skip up to the first rule past this rule number;
1243  *              upon return, non-zero port number for divert or tee.
1244  *
1245  *      args->rule      Pointer to the last matching rule (in/out)
1246  *      args->next_hop  Socket we are forwarding to (out).
1247  *      args->next_hop6 IPv6 next hop we are forwarding to (out).
1248  *      args->f_id      Addresses grabbed from the packet (out)
1249  *      args->rule.info a cookie depending on rule action
1250  *
1251  * Return value:
1252  *
1253  *      IP_FW_PASS      the packet must be accepted
1254  *      IP_FW_DENY      the packet must be dropped
1255  *      IP_FW_DIVERT    divert packet, port in m_tag
1256  *      IP_FW_TEE       tee packet, port in m_tag
1257  *      IP_FW_DUMMYNET  to dummynet, pipe in args->cookie
1258  *      IP_FW_NETGRAPH  into netgraph, cookie args->cookie
1259  *              args->rule contains the matching rule,
1260  *              args->rule.info has additional information.
1261  *
1262  */
1263 int
1264 ipfw_chk(struct ip_fw_args *args)
1265 {
1266
1267         /*
1268          * Local variables holding state while processing a packet:
1269          *
1270          * IMPORTANT NOTE: to speed up the processing of rules, there
1271          * are some assumption on the values of the variables, which
1272          * are documented here. Should you change them, please check
1273          * the implementation of the various instructions to make sure
1274          * that they still work.
1275          *
1276          * args->eh     The MAC header. It is non-null for a layer2
1277          *      packet, it is NULL for a layer-3 packet.
1278          * **notyet**
1279          * args->L3offset Offset in the packet to the L3 (IP or equiv.) header.
1280          *
1281          * m | args->m  Pointer to the mbuf, as received from the caller.
1282          *      It may change if ipfw_chk() does an m_pullup, or if it
1283          *      consumes the packet because it calls send_reject().
1284          *      XXX This has to change, so that ipfw_chk() never modifies
1285          *      or consumes the buffer.
1286          * ip   is the beginning of the ip(4 or 6) header.
1287          *      Calculated by adding the L3offset to the start of data.
1288          *      (Until we start using L3offset, the packet is
1289          *      supposed to start with the ip header).
1290          */
1291         struct mbuf *m = args->m;
1292         struct ip *ip = mtod(m, struct ip *);
1293
1294         /*
1295          * For rules which contain uid/gid or jail constraints, cache
1296          * a copy of the users credentials after the pcb lookup has been
1297          * executed. This will speed up the processing of rules with
1298          * these types of constraints, as well as decrease contention
1299          * on pcb related locks.
1300          */
1301 #ifndef __FreeBSD__
1302         struct bsd_ucred ucred_cache;
1303 #else
1304         struct ucred *ucred_cache = NULL;
1305 #endif
1306         int ucred_lookup = 0;
1307
1308         /*
1309          * oif | args->oif      If NULL, ipfw_chk has been called on the
1310          *      inbound path (ether_input, ip_input).
1311          *      If non-NULL, ipfw_chk has been called on the outbound path
1312          *      (ether_output, ip_output).
1313          */
1314         struct ifnet *oif = args->oif;
1315
1316         int f_pos = 0;          /* index of current rule in the array */
1317         int retval = 0;
1318
1319         /*
1320          * hlen The length of the IP header.
1321          */
1322         u_int hlen = 0;         /* hlen >0 means we have an IP pkt */
1323
1324         /*
1325          * offset       The offset of a fragment. offset != 0 means that
1326          *      we have a fragment at this offset of an IPv4 packet.
1327          *      offset == 0 means that (if this is an IPv4 packet)
1328          *      this is the first or only fragment.
1329          *      For IPv6 offset|ip6f_mf == 0 means there is no Fragment Header
1330          *      or there is a single packet fragment (fragment header added
1331          *      without needed).  We will treat a single packet fragment as if
1332          *      there was no fragment header (or log/block depending on the
1333          *      V_fw_permit_single_frag6 sysctl setting).
1334          */
1335         u_short offset = 0;
1336         u_short ip6f_mf = 0;
1337
1338         /*
1339          * Local copies of addresses. They are only valid if we have
1340          * an IP packet.
1341          *
1342          * proto        The protocol. Set to 0 for non-ip packets,
1343          *      or to the protocol read from the packet otherwise.
1344          *      proto != 0 means that we have an IPv4 packet.
1345          *
1346          * src_port, dst_port   port numbers, in HOST format. Only
1347          *      valid for TCP and UDP packets.
1348          *
1349          * src_ip, dst_ip       ip addresses, in NETWORK format.
1350          *      Only valid for IPv4 packets.
1351          */
1352         uint8_t proto;
1353         uint16_t src_port = 0, dst_port = 0;    /* NOTE: host format    */
1354         struct in_addr src_ip, dst_ip;          /* NOTE: network format */
1355         int iplen = 0;
1356         int pktlen;
1357         uint16_t        etype = 0;      /* Host order stored ether type */
1358
1359         /*
1360          * dyn_dir = MATCH_UNKNOWN when rules unchecked,
1361          *      MATCH_NONE when checked and not matched (q = NULL),
1362          *      MATCH_FORWARD or MATCH_REVERSE otherwise (q != NULL)
1363          */
1364         int dyn_dir = MATCH_UNKNOWN;
1365         uint16_t dyn_name = 0;
1366         struct ip_fw *q = NULL;
1367         struct ip_fw_chain *chain = &V_layer3_chain;
1368
1369         /*
1370          * We store in ulp a pointer to the upper layer protocol header.
1371          * In the ipv4 case this is easy to determine from the header,
1372          * but for ipv6 we might have some additional headers in the middle.
1373          * ulp is NULL if not found.
1374          */
1375         void *ulp = NULL;               /* upper layer protocol pointer. */
1376
1377         /* XXX ipv6 variables */
1378         int is_ipv6 = 0;
1379         uint8_t icmp6_type = 0;
1380         uint16_t ext_hd = 0;    /* bits vector for extension header filtering */
1381         /* end of ipv6 variables */
1382
1383         int is_ipv4 = 0;
1384
1385         int done = 0;           /* flag to exit the outer loop */
1386
1387         if (m->m_flags & M_SKIP_FIREWALL || (! V_ipfw_vnet_ready))
1388                 return (IP_FW_PASS);    /* accept */
1389
1390         dst_ip.s_addr = 0;              /* make sure it is initialized */
1391         src_ip.s_addr = 0;              /* make sure it is initialized */
1392         pktlen = m->m_pkthdr.len;
1393         args->f_id.fib = M_GETFIB(m); /* note mbuf not altered) */
1394         proto = args->f_id.proto = 0;   /* mark f_id invalid */
1395                 /* XXX 0 is a valid proto: IP/IPv6 Hop-by-Hop Option */
1396
1397 /*
1398  * PULLUP_TO(len, p, T) makes sure that len + sizeof(T) is contiguous,
1399  * then it sets p to point at the offset "len" in the mbuf. WARNING: the
1400  * pointer might become stale after other pullups (but we never use it
1401  * this way).
1402  */
1403 #define PULLUP_TO(_len, p, T)   PULLUP_LEN(_len, p, sizeof(T))
1404 #define PULLUP_LEN(_len, p, T)                                  \
1405 do {                                                            \
1406         int x = (_len) + T;                                     \
1407         if ((m)->m_len < x) {                                   \
1408                 args->m = m = m_pullup(m, x);                   \
1409                 if (m == NULL)                                  \
1410                         goto pullup_failed;                     \
1411         }                                                       \
1412         p = (mtod(m, char *) + (_len));                         \
1413 } while (0)
1414
1415         /*
1416          * if we have an ether header,
1417          */
1418         if (args->eh)
1419                 etype = ntohs(args->eh->ether_type);
1420
1421         /* Identify IP packets and fill up variables. */
1422         if (pktlen >= sizeof(struct ip6_hdr) &&
1423             (args->eh == NULL || etype == ETHERTYPE_IPV6) && ip->ip_v == 6) {
1424                 struct ip6_hdr *ip6 = (struct ip6_hdr *)ip;
1425                 is_ipv6 = 1;
1426                 args->f_id.addr_type = 6;
1427                 hlen = sizeof(struct ip6_hdr);
1428                 proto = ip6->ip6_nxt;
1429
1430                 /* Search extension headers to find upper layer protocols */
1431                 while (ulp == NULL && offset == 0) {
1432                         switch (proto) {
1433                         case IPPROTO_ICMPV6:
1434                                 PULLUP_TO(hlen, ulp, struct icmp6_hdr);
1435                                 icmp6_type = ICMP6(ulp)->icmp6_type;
1436                                 break;
1437
1438                         case IPPROTO_TCP:
1439                                 PULLUP_TO(hlen, ulp, struct tcphdr);
1440                                 dst_port = TCP(ulp)->th_dport;
1441                                 src_port = TCP(ulp)->th_sport;
1442                                 /* save flags for dynamic rules */
1443                                 args->f_id._flags = TCP(ulp)->th_flags;
1444                                 break;
1445
1446                         case IPPROTO_SCTP:
1447                                 if (pktlen >= hlen + sizeof(struct sctphdr) +
1448                                     sizeof(struct sctp_chunkhdr) +
1449                                     offsetof(struct sctp_init, a_rwnd))
1450                                         PULLUP_LEN(hlen, ulp,
1451                                             sizeof(struct sctphdr) +
1452                                             sizeof(struct sctp_chunkhdr) +
1453                                             offsetof(struct sctp_init, a_rwnd));
1454                                 else if (pktlen >= hlen + sizeof(struct sctphdr))
1455                                         PULLUP_LEN(hlen, ulp, pktlen - hlen);
1456                                 else
1457                                         PULLUP_LEN(hlen, ulp,
1458                                             sizeof(struct sctphdr));
1459                                 src_port = SCTP(ulp)->src_port;
1460                                 dst_port = SCTP(ulp)->dest_port;
1461                                 break;
1462
1463                         case IPPROTO_UDP:
1464                         case IPPROTO_UDPLITE:
1465                                 PULLUP_TO(hlen, ulp, struct udphdr);
1466                                 dst_port = UDP(ulp)->uh_dport;
1467                                 src_port = UDP(ulp)->uh_sport;
1468                                 break;
1469
1470                         case IPPROTO_HOPOPTS:   /* RFC 2460 */
1471                                 PULLUP_TO(hlen, ulp, struct ip6_hbh);
1472                                 ext_hd |= EXT_HOPOPTS;
1473                                 hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3;
1474                                 proto = ((struct ip6_hbh *)ulp)->ip6h_nxt;
1475                                 ulp = NULL;
1476                                 break;
1477
1478                         case IPPROTO_ROUTING:   /* RFC 2460 */
1479                                 PULLUP_TO(hlen, ulp, struct ip6_rthdr);
1480                                 switch (((struct ip6_rthdr *)ulp)->ip6r_type) {
1481                                 case 0:
1482                                         ext_hd |= EXT_RTHDR0;
1483                                         break;
1484                                 case 2:
1485                                         ext_hd |= EXT_RTHDR2;
1486                                         break;
1487                                 default:
1488                                         if (V_fw_verbose)
1489                                                 printf("IPFW2: IPV6 - Unknown "
1490                                                     "Routing Header type(%d)\n",
1491                                                     ((struct ip6_rthdr *)
1492                                                     ulp)->ip6r_type);
1493                                         if (V_fw_deny_unknown_exthdrs)
1494                                             return (IP_FW_DENY);
1495                                         break;
1496                                 }
1497                                 ext_hd |= EXT_ROUTING;
1498                                 hlen += (((struct ip6_rthdr *)ulp)->ip6r_len + 1) << 3;
1499                                 proto = ((struct ip6_rthdr *)ulp)->ip6r_nxt;
1500                                 ulp = NULL;
1501                                 break;
1502
1503                         case IPPROTO_FRAGMENT:  /* RFC 2460 */
1504                                 PULLUP_TO(hlen, ulp, struct ip6_frag);
1505                                 ext_hd |= EXT_FRAGMENT;
1506                                 hlen += sizeof (struct ip6_frag);
1507                                 proto = ((struct ip6_frag *)ulp)->ip6f_nxt;
1508                                 offset = ((struct ip6_frag *)ulp)->ip6f_offlg &
1509                                         IP6F_OFF_MASK;
1510                                 ip6f_mf = ((struct ip6_frag *)ulp)->ip6f_offlg &
1511                                         IP6F_MORE_FRAG;
1512                                 if (V_fw_permit_single_frag6 == 0 &&
1513                                     offset == 0 && ip6f_mf == 0) {
1514                                         if (V_fw_verbose)
1515                                                 printf("IPFW2: IPV6 - Invalid "
1516                                                     "Fragment Header\n");
1517                                         if (V_fw_deny_unknown_exthdrs)
1518                                             return (IP_FW_DENY);
1519                                         break;
1520                                 }
1521                                 args->f_id.extra =
1522                                     ntohl(((struct ip6_frag *)ulp)->ip6f_ident);
1523                                 ulp = NULL;
1524                                 break;
1525
1526                         case IPPROTO_DSTOPTS:   /* RFC 2460 */
1527                                 PULLUP_TO(hlen, ulp, struct ip6_hbh);
1528                                 ext_hd |= EXT_DSTOPTS;
1529                                 hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3;
1530                                 proto = ((struct ip6_hbh *)ulp)->ip6h_nxt;
1531                                 ulp = NULL;
1532                                 break;
1533
1534                         case IPPROTO_AH:        /* RFC 2402 */
1535                                 PULLUP_TO(hlen, ulp, struct ip6_ext);
1536                                 ext_hd |= EXT_AH;
1537                                 hlen += (((struct ip6_ext *)ulp)->ip6e_len + 2) << 2;
1538                                 proto = ((struct ip6_ext *)ulp)->ip6e_nxt;
1539                                 ulp = NULL;
1540                                 break;
1541
1542                         case IPPROTO_ESP:       /* RFC 2406 */
1543                                 PULLUP_TO(hlen, ulp, uint32_t); /* SPI, Seq# */
1544                                 /* Anything past Seq# is variable length and
1545                                  * data past this ext. header is encrypted. */
1546                                 ext_hd |= EXT_ESP;
1547                                 break;
1548
1549                         case IPPROTO_NONE:      /* RFC 2460 */
1550                                 /*
1551                                  * Packet ends here, and IPv6 header has
1552                                  * already been pulled up. If ip6e_len!=0
1553                                  * then octets must be ignored.
1554                                  */
1555                                 ulp = ip; /* non-NULL to get out of loop. */
1556                                 break;
1557
1558                         case IPPROTO_OSPFIGP:
1559                                 /* XXX OSPF header check? */
1560                                 PULLUP_TO(hlen, ulp, struct ip6_ext);
1561                                 break;
1562
1563                         case IPPROTO_PIM:
1564                                 /* XXX PIM header check? */
1565                                 PULLUP_TO(hlen, ulp, struct pim);
1566                                 break;
1567
1568                         case IPPROTO_GRE:       /* RFC 1701 */
1569                                 /* XXX GRE header check? */
1570                                 PULLUP_TO(hlen, ulp, struct grehdr);
1571                                 break;
1572
1573                         case IPPROTO_CARP:
1574                                 PULLUP_TO(hlen, ulp, struct carp_header);
1575                                 if (((struct carp_header *)ulp)->carp_version !=
1576                                     CARP_VERSION) 
1577                                         return (IP_FW_DENY);
1578                                 if (((struct carp_header *)ulp)->carp_type !=
1579                                     CARP_ADVERTISEMENT) 
1580                                         return (IP_FW_DENY);
1581                                 break;
1582
1583                         case IPPROTO_IPV6:      /* RFC 2893 */
1584                                 PULLUP_TO(hlen, ulp, struct ip6_hdr);
1585                                 break;
1586
1587                         case IPPROTO_IPV4:      /* RFC 2893 */
1588                                 PULLUP_TO(hlen, ulp, struct ip);
1589                                 break;
1590
1591                         default:
1592                                 if (V_fw_verbose)
1593                                         printf("IPFW2: IPV6 - Unknown "
1594                                             "Extension Header(%d), ext_hd=%x\n",
1595                                              proto, ext_hd);
1596                                 if (V_fw_deny_unknown_exthdrs)
1597                                     return (IP_FW_DENY);
1598                                 PULLUP_TO(hlen, ulp, struct ip6_ext);
1599                                 break;
1600                         } /*switch */
1601                 }
1602                 ip = mtod(m, struct ip *);
1603                 ip6 = (struct ip6_hdr *)ip;
1604                 args->f_id.src_ip6 = ip6->ip6_src;
1605                 args->f_id.dst_ip6 = ip6->ip6_dst;
1606                 args->f_id.src_ip = 0;
1607                 args->f_id.dst_ip = 0;
1608                 args->f_id.flow_id6 = ntohl(ip6->ip6_flow);
1609                 iplen = ntohs(ip6->ip6_plen) + sizeof(*ip6);
1610         } else if (pktlen >= sizeof(struct ip) &&
1611             (args->eh == NULL || etype == ETHERTYPE_IP) && ip->ip_v == 4) {
1612                 is_ipv4 = 1;
1613                 hlen = ip->ip_hl << 2;
1614                 args->f_id.addr_type = 4;
1615
1616                 /*
1617                  * Collect parameters into local variables for faster matching.
1618                  */
1619                 proto = ip->ip_p;
1620                 src_ip = ip->ip_src;
1621                 dst_ip = ip->ip_dst;
1622                 offset = ntohs(ip->ip_off) & IP_OFFMASK;
1623                 iplen = ntohs(ip->ip_len);
1624
1625                 if (offset == 0) {
1626                         switch (proto) {
1627                         case IPPROTO_TCP:
1628                                 PULLUP_TO(hlen, ulp, struct tcphdr);
1629                                 dst_port = TCP(ulp)->th_dport;
1630                                 src_port = TCP(ulp)->th_sport;
1631                                 /* save flags for dynamic rules */
1632                                 args->f_id._flags = TCP(ulp)->th_flags;
1633                                 break;
1634
1635                         case IPPROTO_SCTP:
1636                                 if (pktlen >= hlen + sizeof(struct sctphdr) +
1637                                     sizeof(struct sctp_chunkhdr) +
1638                                     offsetof(struct sctp_init, a_rwnd))
1639                                         PULLUP_LEN(hlen, ulp,
1640                                             sizeof(struct sctphdr) +
1641                                             sizeof(struct sctp_chunkhdr) +
1642                                             offsetof(struct sctp_init, a_rwnd));
1643                                 else if (pktlen >= hlen + sizeof(struct sctphdr))
1644                                         PULLUP_LEN(hlen, ulp, pktlen - hlen);
1645                                 else
1646                                         PULLUP_LEN(hlen, ulp,
1647                                             sizeof(struct sctphdr));
1648                                 src_port = SCTP(ulp)->src_port;
1649                                 dst_port = SCTP(ulp)->dest_port;
1650                                 break;
1651
1652                         case IPPROTO_UDP:
1653                         case IPPROTO_UDPLITE:
1654                                 PULLUP_TO(hlen, ulp, struct udphdr);
1655                                 dst_port = UDP(ulp)->uh_dport;
1656                                 src_port = UDP(ulp)->uh_sport;
1657                                 break;
1658
1659                         case IPPROTO_ICMP:
1660                                 PULLUP_TO(hlen, ulp, struct icmphdr);
1661                                 //args->f_id.flags = ICMP(ulp)->icmp_type;
1662                                 break;
1663
1664                         default:
1665                                 break;
1666                         }
1667                 }
1668
1669                 ip = mtod(m, struct ip *);
1670                 args->f_id.src_ip = ntohl(src_ip.s_addr);
1671                 args->f_id.dst_ip = ntohl(dst_ip.s_addr);
1672         }
1673 #undef PULLUP_TO
1674         pktlen = iplen < pktlen ? iplen: pktlen;
1675         if (proto) { /* we may have port numbers, store them */
1676                 args->f_id.proto = proto;
1677                 args->f_id.src_port = src_port = ntohs(src_port);
1678                 args->f_id.dst_port = dst_port = ntohs(dst_port);
1679         }
1680
1681         IPFW_PF_RLOCK(chain);
1682         if (! V_ipfw_vnet_ready) { /* shutting down, leave NOW. */
1683                 IPFW_PF_RUNLOCK(chain);
1684                 return (IP_FW_PASS);    /* accept */
1685         }
1686         if (args->rule.slot) {
1687                 /*
1688                  * Packet has already been tagged as a result of a previous
1689                  * match on rule args->rule aka args->rule_id (PIPE, QUEUE,
1690                  * REASS, NETGRAPH, DIVERT/TEE...)
1691                  * Validate the slot and continue from the next one
1692                  * if still present, otherwise do a lookup.
1693                  */
1694                 f_pos = (args->rule.chain_id == chain->id) ?
1695                     args->rule.slot :
1696                     ipfw_find_rule(chain, args->rule.rulenum,
1697                         args->rule.rule_id);
1698         } else {
1699                 f_pos = 0;
1700         }
1701
1702         /*
1703          * Now scan the rules, and parse microinstructions for each rule.
1704          * We have two nested loops and an inner switch. Sometimes we
1705          * need to break out of one or both loops, or re-enter one of
1706          * the loops with updated variables. Loop variables are:
1707          *
1708          *      f_pos (outer loop) points to the current rule.
1709          *              On output it points to the matching rule.
1710          *      done (outer loop) is used as a flag to break the loop.
1711          *      l (inner loop)  residual length of current rule.
1712          *              cmd points to the current microinstruction.
1713          *
1714          * We break the inner loop by setting l=0 and possibly
1715          * cmdlen=0 if we don't want to advance cmd.
1716          * We break the outer loop by setting done=1
1717          * We can restart the inner loop by setting l>0 and f_pos, f, cmd
1718          * as needed.
1719          */
1720         for (; f_pos < chain->n_rules; f_pos++) {
1721                 ipfw_insn *cmd;
1722                 uint32_t tablearg = 0;
1723                 int l, cmdlen, skip_or; /* skip rest of OR block */
1724                 struct ip_fw *f;
1725
1726                 f = chain->map[f_pos];
1727                 if (V_set_disable & (1 << f->set) )
1728                         continue;
1729
1730                 skip_or = 0;
1731                 for (l = f->cmd_len, cmd = f->cmd ; l > 0 ;
1732                     l -= cmdlen, cmd += cmdlen) {
1733                         int match;
1734
1735                         /*
1736                          * check_body is a jump target used when we find a
1737                          * CHECK_STATE, and need to jump to the body of
1738                          * the target rule.
1739                          */
1740
1741 /* check_body: */
1742                         cmdlen = F_LEN(cmd);
1743                         /*
1744                          * An OR block (insn_1 || .. || insn_n) has the
1745                          * F_OR bit set in all but the last instruction.
1746                          * The first match will set "skip_or", and cause
1747                          * the following instructions to be skipped until
1748                          * past the one with the F_OR bit clear.
1749                          */
1750                         if (skip_or) {          /* skip this instruction */
1751                                 if ((cmd->len & F_OR) == 0)
1752                                         skip_or = 0;    /* next one is good */
1753                                 continue;
1754                         }
1755                         match = 0; /* set to 1 if we succeed */
1756
1757                         switch (cmd->opcode) {
1758                         /*
1759                          * The first set of opcodes compares the packet's
1760                          * fields with some pattern, setting 'match' if a
1761                          * match is found. At the end of the loop there is
1762                          * logic to deal with F_NOT and F_OR flags associated
1763                          * with the opcode.
1764                          */
1765                         case O_NOP:
1766                                 match = 1;
1767                                 break;
1768
1769                         case O_FORWARD_MAC:
1770                                 printf("ipfw: opcode %d unimplemented\n",
1771                                     cmd->opcode);
1772                                 break;
1773
1774                         case O_GID:
1775                         case O_UID:
1776                         case O_JAIL:
1777                                 /*
1778                                  * We only check offset == 0 && proto != 0,
1779                                  * as this ensures that we have a
1780                                  * packet with the ports info.
1781                                  */
1782                                 if (offset != 0)
1783                                         break;
1784                                 if (proto == IPPROTO_TCP ||
1785                                     proto == IPPROTO_UDP ||
1786                                     proto == IPPROTO_UDPLITE)
1787                                         match = check_uidgid(
1788                                                     (ipfw_insn_u32 *)cmd,
1789                                                     args, &ucred_lookup,
1790 #ifdef __FreeBSD__
1791                                                     &ucred_cache);
1792 #else
1793                                                     (void *)&ucred_cache);
1794 #endif
1795                                 break;
1796
1797                         case O_RECV:
1798                                 match = iface_match(m->m_pkthdr.rcvif,
1799                                     (ipfw_insn_if *)cmd, chain, &tablearg);
1800                                 break;
1801
1802                         case O_XMIT:
1803                                 match = iface_match(oif, (ipfw_insn_if *)cmd,
1804                                     chain, &tablearg);
1805                                 break;
1806
1807                         case O_VIA:
1808                                 match = iface_match(oif ? oif :
1809                                     m->m_pkthdr.rcvif, (ipfw_insn_if *)cmd,
1810                                     chain, &tablearg);
1811                                 break;
1812
1813                         case O_MACADDR2:
1814                                 if (args->eh != NULL) { /* have MAC header */
1815                                         u_int32_t *want = (u_int32_t *)
1816                                                 ((ipfw_insn_mac *)cmd)->addr;
1817                                         u_int32_t *mask = (u_int32_t *)
1818                                                 ((ipfw_insn_mac *)cmd)->mask;
1819                                         u_int32_t *hdr = (u_int32_t *)args->eh;
1820
1821                                         match =
1822                                             ( want[0] == (hdr[0] & mask[0]) &&
1823                                               want[1] == (hdr[1] & mask[1]) &&
1824                                               want[2] == (hdr[2] & mask[2]) );
1825                                 }
1826                                 break;
1827
1828                         case O_MAC_TYPE:
1829                                 if (args->eh != NULL) {
1830                                         u_int16_t *p =
1831                                             ((ipfw_insn_u16 *)cmd)->ports;
1832                                         int i;
1833
1834                                         for (i = cmdlen - 1; !match && i>0;
1835                                             i--, p += 2)
1836                                                 match = (etype >= p[0] &&
1837                                                     etype <= p[1]);
1838                                 }
1839                                 break;
1840
1841                         case O_FRAG:
1842                                 match = (offset != 0);
1843                                 break;
1844
1845                         case O_IN:      /* "out" is "not in" */
1846                                 match = (oif == NULL);
1847                                 break;
1848
1849                         case O_LAYER2:
1850                                 match = (args->eh != NULL);
1851                                 break;
1852
1853                         case O_DIVERTED:
1854                             {
1855                                 /* For diverted packets, args->rule.info
1856                                  * contains the divert port (in host format)
1857                                  * reason and direction.
1858                                  */
1859                                 uint32_t i = args->rule.info;
1860                                 match = (i&IPFW_IS_MASK) == IPFW_IS_DIVERT &&
1861                                     cmd->arg1 & ((i & IPFW_INFO_IN) ? 1 : 2);
1862                             }
1863                                 break;
1864
1865                         case O_PROTO:
1866                                 /*
1867                                  * We do not allow an arg of 0 so the
1868                                  * check of "proto" only suffices.
1869                                  */
1870                                 match = (proto == cmd->arg1);
1871                                 break;
1872
1873                         case O_IP_SRC:
1874                                 match = is_ipv4 &&
1875                                     (((ipfw_insn_ip *)cmd)->addr.s_addr ==
1876                                     src_ip.s_addr);
1877                                 break;
1878
1879                         case O_IP_DST_LOOKUP:
1880                         {
1881                                 void *pkey;
1882                                 uint32_t vidx, key;
1883                                 uint16_t keylen;
1884
1885                                 if (cmdlen > F_INSN_SIZE(ipfw_insn_u32)) {
1886                                         /* Determine lookup key type */
1887                                         vidx = ((ipfw_insn_u32 *)cmd)->d[1];
1888                                         if (vidx != 4 /* uid */ &&
1889                                             vidx != 5 /* jail */ &&
1890                                             is_ipv6 == 0 && is_ipv4 == 0)
1891                                                 break;
1892                                         /* Determine key length */
1893                                         if (vidx == 0 /* dst-ip */ ||
1894                                             vidx == 1 /* src-ip */)
1895                                                 keylen = is_ipv6 ?
1896                                                     sizeof(struct in6_addr):
1897                                                     sizeof(in_addr_t);
1898                                         else {
1899                                                 keylen = sizeof(key);
1900                                                 pkey = &key;
1901                                         }
1902                                         if (vidx == 0 /* dst-ip */)
1903                                                 pkey = is_ipv4 ? (void *)&dst_ip:
1904                                                     (void *)&args->f_id.dst_ip6;
1905                                         else if (vidx == 1 /* src-ip */)
1906                                                 pkey = is_ipv4 ? (void *)&src_ip:
1907                                                     (void *)&args->f_id.src_ip6;
1908                                         else if (vidx == 6 /* dscp */) {
1909                                                 if (is_ipv4)
1910                                                         key = ip->ip_tos >> 2;
1911                                                 else {
1912                                                         key = args->f_id.flow_id6;
1913                                                         key = (key & 0x0f) << 2 |
1914                                                             (key & 0xf000) >> 14;
1915                                                 }
1916                                                 key &= 0x3f;
1917                                         } else if (vidx == 2 /* dst-port */ ||
1918                                             vidx == 3 /* src-port */) {
1919                                                 /* Skip fragments */
1920                                                 if (offset != 0)
1921                                                         break;
1922                                                 /* Skip proto without ports */
1923                                                 if (proto != IPPROTO_TCP &&
1924                                                     proto != IPPROTO_UDP &&
1925                                                     proto != IPPROTO_UDPLITE &&
1926                                                     proto != IPPROTO_SCTP)
1927                                                         break;
1928                                                 if (vidx == 2 /* dst-port */)
1929                                                         key = dst_port;
1930                                                 else
1931                                                         key = src_port;
1932                                         }
1933 #ifndef USERSPACE
1934                                         else if (vidx == 4 /* uid */ ||
1935                                             vidx == 5 /* jail */) {
1936                                                 check_uidgid(
1937                                                     (ipfw_insn_u32 *)cmd,
1938                                                     args, &ucred_lookup,
1939 #ifdef __FreeBSD__
1940                                                     &ucred_cache);
1941                                                 if (vidx == 4 /* uid */)
1942                                                         key = ucred_cache->cr_uid;
1943                                                 else if (vidx == 5 /* jail */)
1944                                                         key = ucred_cache->cr_prison->pr_id;
1945 #else /* !__FreeBSD__ */
1946                                                     (void *)&ucred_cache);
1947                                                 if (vidx == 4 /* uid */)
1948                                                         key = ucred_cache.uid;
1949                                                 else if (vidx == 5 /* jail */)
1950                                                         key = ucred_cache.xid;
1951 #endif /* !__FreeBSD__ */
1952                                         }
1953 #endif /* !USERSPACE */
1954                                         else
1955                                                 break;
1956                                         match = ipfw_lookup_table(chain,
1957                                             cmd->arg1, keylen, pkey, &vidx);
1958                                         if (!match)
1959                                                 break;
1960                                         tablearg = vidx;
1961                                         break;
1962                                 }
1963                                 /* cmdlen =< F_INSN_SIZE(ipfw_insn_u32) */
1964                                 /* FALLTHROUGH */
1965                         }
1966                         case O_IP_SRC_LOOKUP:
1967                         {
1968                                 void *pkey;
1969                                 uint32_t vidx;
1970                                 uint16_t keylen;
1971
1972                                 if (is_ipv4) {
1973                                         keylen = sizeof(in_addr_t);
1974                                         if (cmd->opcode == O_IP_DST_LOOKUP)
1975                                                 pkey = &dst_ip;
1976                                         else
1977                                                 pkey = &src_ip;
1978                                 } else if (is_ipv6) {
1979                                         keylen = sizeof(struct in6_addr);
1980                                         if (cmd->opcode == O_IP_DST_LOOKUP)
1981                                                 pkey = &args->f_id.dst_ip6;
1982                                         else
1983                                                 pkey = &args->f_id.src_ip6;
1984                                 } else
1985                                         break;
1986                                 match = ipfw_lookup_table(chain, cmd->arg1,
1987                                     keylen, pkey, &vidx);
1988                                 if (!match)
1989                                         break;
1990                                 if (cmdlen == F_INSN_SIZE(ipfw_insn_u32)) {
1991                                         match = ((ipfw_insn_u32 *)cmd)->d[0] ==
1992                                             TARG_VAL(chain, vidx, tag);
1993                                         if (!match)
1994                                                 break;
1995                                 }
1996                                 tablearg = vidx;
1997                                 break;
1998                         }
1999
2000                         case O_IP_FLOW_LOOKUP:
2001                                 {
2002                                         uint32_t v = 0;
2003                                         match = ipfw_lookup_table(chain,
2004                                             cmd->arg1, 0, &args->f_id, &v);
2005                                         if (cmdlen == F_INSN_SIZE(ipfw_insn_u32))
2006                                                 match = ((ipfw_insn_u32 *)cmd)->d[0] ==
2007                                                     TARG_VAL(chain, v, tag);
2008                                         if (match)
2009                                                 tablearg = v;
2010                                 }
2011                                 break;
2012                         case O_IP_SRC_MASK:
2013                         case O_IP_DST_MASK:
2014                                 if (is_ipv4) {
2015                                     uint32_t a =
2016                                         (cmd->opcode == O_IP_DST_MASK) ?
2017                                             dst_ip.s_addr : src_ip.s_addr;
2018                                     uint32_t *p = ((ipfw_insn_u32 *)cmd)->d;
2019                                     int i = cmdlen-1;
2020
2021                                     for (; !match && i>0; i-= 2, p+= 2)
2022                                         match = (p[0] == (a & p[1]));
2023                                 }
2024                                 break;
2025
2026                         case O_IP_SRC_ME:
2027                                 if (is_ipv4) {
2028                                         match = in_localip(src_ip);
2029                                         break;
2030                                 }
2031 #ifdef INET6
2032                                 /* FALLTHROUGH */
2033                         case O_IP6_SRC_ME:
2034                                 match= is_ipv6 && ipfw_localip6(&args->f_id.src_ip6);
2035 #endif
2036                                 break;
2037
2038                         case O_IP_DST_SET:
2039                         case O_IP_SRC_SET:
2040                                 if (is_ipv4) {
2041                                         u_int32_t *d = (u_int32_t *)(cmd+1);
2042                                         u_int32_t addr =
2043                                             cmd->opcode == O_IP_DST_SET ?
2044                                                 args->f_id.dst_ip :
2045                                                 args->f_id.src_ip;
2046
2047                                             if (addr < d[0])
2048                                                     break;
2049                                             addr -= d[0]; /* subtract base */
2050                                             match = (addr < cmd->arg1) &&
2051                                                 ( d[ 1 + (addr>>5)] &
2052                                                   (1<<(addr & 0x1f)) );
2053                                 }
2054                                 break;
2055
2056                         case O_IP_DST:
2057                                 match = is_ipv4 &&
2058                                     (((ipfw_insn_ip *)cmd)->addr.s_addr ==
2059                                     dst_ip.s_addr);
2060                                 break;
2061
2062                         case O_IP_DST_ME:
2063                                 if (is_ipv4) {
2064                                         match = in_localip(dst_ip);
2065                                         break;
2066                                 }
2067 #ifdef INET6
2068                                 /* FALLTHROUGH */
2069                         case O_IP6_DST_ME:
2070                                 match= is_ipv6 && ipfw_localip6(&args->f_id.dst_ip6);
2071 #endif
2072                                 break;
2073
2074
2075                         case O_IP_SRCPORT:
2076                         case O_IP_DSTPORT:
2077                                 /*
2078                                  * offset == 0 && proto != 0 is enough
2079                                  * to guarantee that we have a
2080                                  * packet with port info.
2081                                  */
2082                                 if ((proto == IPPROTO_UDP ||
2083                                     proto == IPPROTO_UDPLITE ||
2084                                     proto == IPPROTO_TCP ||
2085                                     proto == IPPROTO_SCTP) && offset == 0) {
2086                                         u_int16_t x =
2087                                             (cmd->opcode == O_IP_SRCPORT) ?
2088                                                 src_port : dst_port ;
2089                                         u_int16_t *p =
2090                                             ((ipfw_insn_u16 *)cmd)->ports;
2091                                         int i;
2092
2093                                         for (i = cmdlen - 1; !match && i>0;
2094                                             i--, p += 2)
2095                                                 match = (x>=p[0] && x<=p[1]);
2096                                 }
2097                                 break;
2098
2099                         case O_ICMPTYPE:
2100                                 match = (offset == 0 && proto==IPPROTO_ICMP &&
2101                                     icmptype_match(ICMP(ulp), (ipfw_insn_u32 *)cmd) );
2102                                 break;
2103
2104 #ifdef INET6
2105                         case O_ICMP6TYPE:
2106                                 match = is_ipv6 && offset == 0 &&
2107                                     proto==IPPROTO_ICMPV6 &&
2108                                     icmp6type_match(
2109                                         ICMP6(ulp)->icmp6_type,
2110                                         (ipfw_insn_u32 *)cmd);
2111                                 break;
2112 #endif /* INET6 */
2113
2114                         case O_IPOPT:
2115                                 match = (is_ipv4 &&
2116                                     ipopts_match(ip, cmd) );
2117                                 break;
2118
2119                         case O_IPVER:
2120                                 match = (is_ipv4 &&
2121                                     cmd->arg1 == ip->ip_v);
2122                                 break;
2123
2124                         case O_IPID:
2125                         case O_IPLEN:
2126                         case O_IPTTL:
2127                                 if (is_ipv4) {  /* only for IP packets */
2128                                     uint16_t x;
2129                                     uint16_t *p;
2130                                     int i;
2131
2132                                     if (cmd->opcode == O_IPLEN)
2133                                         x = iplen;
2134                                     else if (cmd->opcode == O_IPTTL)
2135                                         x = ip->ip_ttl;
2136                                     else /* must be IPID */
2137                                         x = ntohs(ip->ip_id);
2138                                     if (cmdlen == 1) {
2139                                         match = (cmd->arg1 == x);
2140                                         break;
2141                                     }
2142                                     /* otherwise we have ranges */
2143                                     p = ((ipfw_insn_u16 *)cmd)->ports;
2144                                     i = cmdlen - 1;
2145                                     for (; !match && i>0; i--, p += 2)
2146                                         match = (x >= p[0] && x <= p[1]);
2147                                 }
2148                                 break;
2149
2150                         case O_IPPRECEDENCE:
2151                                 match = (is_ipv4 &&
2152                                     (cmd->arg1 == (ip->ip_tos & 0xe0)) );
2153                                 break;
2154
2155                         case O_IPTOS:
2156                                 match = (is_ipv4 &&
2157                                     flags_match(cmd, ip->ip_tos));
2158                                 break;
2159
2160                         case O_DSCP:
2161                             {
2162                                 uint32_t *p;
2163                                 uint16_t x;
2164
2165                                 p = ((ipfw_insn_u32 *)cmd)->d;
2166
2167                                 if (is_ipv4)
2168                                         x = ip->ip_tos >> 2;
2169                                 else if (is_ipv6) {
2170                                         uint8_t *v;
2171                                         v = &((struct ip6_hdr *)ip)->ip6_vfc;
2172                                         x = (*v & 0x0F) << 2;
2173                                         v++;
2174                                         x |= *v >> 6;
2175                                 } else
2176                                         break;
2177
2178                                 /* DSCP bitmask is stored as low_u32 high_u32 */
2179                                 if (x >= 32)
2180                                         match = *(p + 1) & (1 << (x - 32));
2181                                 else
2182                                         match = *p & (1 << x);
2183                             }
2184                                 break;
2185
2186                         case O_TCPDATALEN:
2187                                 if (proto == IPPROTO_TCP && offset == 0) {
2188                                     struct tcphdr *tcp;
2189                                     uint16_t x;
2190                                     uint16_t *p;
2191                                     int i;
2192 #ifdef INET6
2193                                     if (is_ipv6) {
2194                                             struct ip6_hdr *ip6;
2195
2196                                             ip6 = (struct ip6_hdr *)ip;
2197                                             if (ip6->ip6_plen == 0) {
2198                                                     /*
2199                                                      * Jumbo payload is not
2200                                                      * supported by this
2201                                                      * opcode.
2202                                                      */
2203                                                     break;
2204                                             }
2205                                             x = iplen - hlen;
2206                                     } else
2207 #endif /* INET6 */
2208                                             x = iplen - (ip->ip_hl << 2);
2209                                     tcp = TCP(ulp);
2210                                     x -= tcp->th_off << 2;
2211                                     if (cmdlen == 1) {
2212                                         match = (cmd->arg1 == x);
2213                                         break;
2214                                     }
2215                                     /* otherwise we have ranges */
2216                                     p = ((ipfw_insn_u16 *)cmd)->ports;
2217                                     i = cmdlen - 1;
2218                                     for (; !match && i>0; i--, p += 2)
2219                                         match = (x >= p[0] && x <= p[1]);
2220                                 }
2221                                 break;
2222
2223                         case O_TCPFLAGS:
2224                                 match = (proto == IPPROTO_TCP && offset == 0 &&
2225                                     flags_match(cmd, TCP(ulp)->th_flags));
2226                                 break;
2227
2228                         case O_TCPOPTS:
2229                                 if (proto == IPPROTO_TCP && offset == 0 && ulp){
2230                                         PULLUP_LEN(hlen, ulp,
2231                                             (TCP(ulp)->th_off << 2));
2232                                         match = tcpopts_match(TCP(ulp), cmd);
2233                                 }
2234                                 break;
2235
2236                         case O_TCPSEQ:
2237                                 match = (proto == IPPROTO_TCP && offset == 0 &&
2238                                     ((ipfw_insn_u32 *)cmd)->d[0] ==
2239                                         TCP(ulp)->th_seq);
2240                                 break;
2241
2242                         case O_TCPACK:
2243                                 match = (proto == IPPROTO_TCP && offset == 0 &&
2244                                     ((ipfw_insn_u32 *)cmd)->d[0] ==
2245                                         TCP(ulp)->th_ack);
2246                                 break;
2247
2248                         case O_TCPWIN:
2249                                 if (proto == IPPROTO_TCP && offset == 0) {
2250                                     uint16_t x;
2251                                     uint16_t *p;
2252                                     int i;
2253
2254                                     x = ntohs(TCP(ulp)->th_win);
2255                                     if (cmdlen == 1) {
2256                                         match = (cmd->arg1 == x);
2257                                         break;
2258                                     }
2259                                     /* Otherwise we have ranges. */
2260                                     p = ((ipfw_insn_u16 *)cmd)->ports;
2261                                     i = cmdlen - 1;
2262                                     for (; !match && i > 0; i--, p += 2)
2263                                         match = (x >= p[0] && x <= p[1]);
2264                                 }
2265                                 break;
2266
2267                         case O_ESTAB:
2268                                 /* reject packets which have SYN only */
2269                                 /* XXX should i also check for TH_ACK ? */
2270                                 match = (proto == IPPROTO_TCP && offset == 0 &&
2271                                     (TCP(ulp)->th_flags &
2272                                      (TH_RST | TH_ACK | TH_SYN)) != TH_SYN);
2273                                 break;
2274
2275                         case O_ALTQ: {
2276                                 struct pf_mtag *at;
2277                                 struct m_tag *mtag;
2278                                 ipfw_insn_altq *altq = (ipfw_insn_altq *)cmd;
2279
2280                                 /*
2281                                  * ALTQ uses mbuf tags from another
2282                                  * packet filtering system - pf(4).
2283                                  * We allocate a tag in its format
2284                                  * and fill it in, pretending to be pf(4).
2285                                  */
2286                                 match = 1;
2287                                 at = pf_find_mtag(m);
2288                                 if (at != NULL && at->qid != 0)
2289                                         break;
2290                                 mtag = m_tag_get(PACKET_TAG_PF,
2291                                     sizeof(struct pf_mtag), M_NOWAIT | M_ZERO);
2292                                 if (mtag == NULL) {
2293                                         /*
2294                                          * Let the packet fall back to the
2295                                          * default ALTQ.
2296                                          */
2297                                         break;
2298                                 }
2299                                 m_tag_prepend(m, mtag);
2300                                 at = (struct pf_mtag *)(mtag + 1);
2301                                 at->qid = altq->qid;
2302                                 at->hdr = ip;
2303                                 break;
2304                         }
2305
2306                         case O_LOG:
2307                                 ipfw_log(chain, f, hlen, args, m,
2308                                     oif, offset | ip6f_mf, tablearg, ip);
2309                                 match = 1;
2310                                 break;
2311
2312                         case O_PROB:
2313                                 match = (random()<((ipfw_insn_u32 *)cmd)->d[0]);
2314                                 break;
2315
2316                         case O_VERREVPATH:
2317                                 /* Outgoing packets automatically pass/match */
2318                                 match = ((oif != NULL) ||
2319                                     (m->m_pkthdr.rcvif == NULL) ||
2320                                     (
2321 #ifdef INET6
2322                                     is_ipv6 ?
2323                                         verify_path6(&(args->f_id.src_ip6),
2324                                             m->m_pkthdr.rcvif, args->f_id.fib) :
2325 #endif
2326                                     verify_path(src_ip, m->m_pkthdr.rcvif,
2327                                         args->f_id.fib)));
2328                                 break;
2329
2330                         case O_VERSRCREACH:
2331                                 /* Outgoing packets automatically pass/match */
2332                                 match = (hlen > 0 && ((oif != NULL) ||
2333 #ifdef INET6
2334                                     is_ipv6 ?
2335                                         verify_path6(&(args->f_id.src_ip6),
2336                                             NULL, args->f_id.fib) :
2337 #endif
2338                                     verify_path(src_ip, NULL, args->f_id.fib)));
2339                                 break;
2340
2341                         case O_ANTISPOOF:
2342                                 /* Outgoing packets automatically pass/match */
2343                                 if (oif == NULL && hlen > 0 &&
2344                                     (  (is_ipv4 && in_localaddr(src_ip))
2345 #ifdef INET6
2346                                     || (is_ipv6 &&
2347                                         in6_localaddr(&(args->f_id.src_ip6)))
2348 #endif
2349                                     ))
2350                                         match =
2351 #ifdef INET6
2352                                             is_ipv6 ? verify_path6(
2353                                                 &(args->f_id.src_ip6),
2354                                                 m->m_pkthdr.rcvif,
2355                                                 args->f_id.fib) :
2356 #endif
2357                                             verify_path(src_ip,
2358                                                 m->m_pkthdr.rcvif,
2359                                                 args->f_id.fib);
2360                                 else
2361                                         match = 1;
2362                                 break;
2363
2364                         case O_IPSEC:
2365                                 match = (m_tag_find(m,
2366                                     PACKET_TAG_IPSEC_IN_DONE, NULL) != NULL);
2367                                 /* otherwise no match */
2368                                 break;
2369
2370 #ifdef INET6
2371                         case O_IP6_SRC:
2372                                 match = is_ipv6 &&
2373                                     IN6_ARE_ADDR_EQUAL(&args->f_id.src_ip6,
2374                                     &((ipfw_insn_ip6 *)cmd)->addr6);
2375                                 break;
2376
2377                         case O_IP6_DST:
2378                                 match = is_ipv6 &&
2379                                 IN6_ARE_ADDR_EQUAL(&args->f_id.dst_ip6,
2380                                     &((ipfw_insn_ip6 *)cmd)->addr6);
2381                                 break;
2382                         case O_IP6_SRC_MASK:
2383                         case O_IP6_DST_MASK:
2384                                 if (is_ipv6) {
2385                                         int i = cmdlen - 1;
2386                                         struct in6_addr p;
2387                                         struct in6_addr *d =
2388                                             &((ipfw_insn_ip6 *)cmd)->addr6;
2389
2390                                         for (; !match && i > 0; d += 2,
2391                                             i -= F_INSN_SIZE(struct in6_addr)
2392                                             * 2) {
2393                                                 p = (cmd->opcode ==
2394                                                     O_IP6_SRC_MASK) ?
2395                                                     args->f_id.src_ip6:
2396                                                     args->f_id.dst_ip6;
2397                                                 APPLY_MASK(&p, &d[1]);
2398                                                 match =
2399                                                     IN6_ARE_ADDR_EQUAL(&d[0],
2400                                                     &p);
2401                                         }
2402                                 }
2403                                 break;
2404
2405                         case O_FLOW6ID:
2406                                 match = is_ipv6 &&
2407                                     flow6id_match(args->f_id.flow_id6,
2408                                     (ipfw_insn_u32 *) cmd);
2409                                 break;
2410
2411                         case O_EXT_HDR:
2412                                 match = is_ipv6 &&
2413                                     (ext_hd & ((ipfw_insn *) cmd)->arg1);
2414                                 break;
2415
2416                         case O_IP6:
2417                                 match = is_ipv6;
2418                                 break;
2419 #endif
2420
2421                         case O_IP4:
2422                                 match = is_ipv4;
2423                                 break;
2424
2425                         case O_TAG: {
2426                                 struct m_tag *mtag;
2427                                 uint32_t tag = TARG(cmd->arg1, tag);
2428
2429                                 /* Packet is already tagged with this tag? */
2430                                 mtag = m_tag_locate(m, MTAG_IPFW, tag, NULL);
2431
2432                                 /* We have `untag' action when F_NOT flag is
2433                                  * present. And we must remove this mtag from
2434                                  * mbuf and reset `match' to zero (`match' will
2435                                  * be inversed later).
2436                                  * Otherwise we should allocate new mtag and
2437                                  * push it into mbuf.
2438                                  */
2439                                 if (cmd->len & F_NOT) { /* `untag' action */
2440                                         if (mtag != NULL)
2441                                                 m_tag_delete(m, mtag);
2442                                         match = 0;
2443                                 } else {
2444                                         if (mtag == NULL) {
2445                                                 mtag = m_tag_alloc( MTAG_IPFW,
2446                                                     tag, 0, M_NOWAIT);
2447                                                 if (mtag != NULL)
2448                                                         m_tag_prepend(m, mtag);
2449                                         }
2450                                         match = 1;
2451                                 }
2452                                 break;
2453                         }
2454
2455                         case O_FIB: /* try match the specified fib */
2456                                 if (args->f_id.fib == cmd->arg1)
2457                                         match = 1;
2458                                 break;
2459
2460                         case O_SOCKARG: {
2461 #ifndef USERSPACE       /* not supported in userspace */
2462                                 struct inpcb *inp = args->inp;
2463                                 struct inpcbinfo *pi;
2464                                 
2465                                 if (is_ipv6) /* XXX can we remove this ? */
2466                                         break;
2467
2468                                 if (proto == IPPROTO_TCP)
2469                                         pi = &V_tcbinfo;
2470                                 else if (proto == IPPROTO_UDP)
2471                                         pi = &V_udbinfo;
2472                                 else if (proto == IPPROTO_UDPLITE)
2473                                         pi = &V_ulitecbinfo;
2474                                 else
2475                                         break;
2476
2477                                 /*
2478                                  * XXXRW: so_user_cookie should almost
2479                                  * certainly be inp_user_cookie?
2480                                  */
2481
2482                                 /* For incoming packet, lookup up the 
2483                                 inpcb using the src/dest ip/port tuple */
2484                                 if (inp == NULL) {
2485                                         inp = in_pcblookup(pi, 
2486                                                 src_ip, htons(src_port),
2487                                                 dst_ip, htons(dst_port),
2488                                                 INPLOOKUP_RLOCKPCB, NULL);
2489                                         if (inp != NULL) {
2490                                                 tablearg =
2491                                                     inp->inp_socket->so_user_cookie;
2492                                                 if (tablearg)
2493                                                         match = 1;
2494                                                 INP_RUNLOCK(inp);
2495                                         }
2496                                 } else {
2497                                         if (inp->inp_socket) {
2498                                                 tablearg =
2499                                                     inp->inp_socket->so_user_cookie;
2500                                                 if (tablearg)
2501                                                         match = 1;
2502                                         }
2503                                 }
2504 #endif /* !USERSPACE */
2505                                 break;
2506                         }
2507
2508                         case O_TAGGED: {
2509                                 struct m_tag *mtag;
2510                                 uint32_t tag = TARG(cmd->arg1, tag);
2511
2512                                 if (cmdlen == 1) {
2513                                         match = m_tag_locate(m, MTAG_IPFW,
2514                                             tag, NULL) != NULL;
2515                                         break;
2516                                 }
2517
2518                                 /* we have ranges */
2519                                 for (mtag = m_tag_first(m);
2520                                     mtag != NULL && !match;
2521                                     mtag = m_tag_next(m, mtag)) {
2522                                         uint16_t *p;
2523                                         int i;
2524
2525                                         if (mtag->m_tag_cookie != MTAG_IPFW)
2526                                                 continue;
2527
2528                                         p = ((ipfw_insn_u16 *)cmd)->ports;
2529                                         i = cmdlen - 1;
2530                                         for(; !match && i > 0; i--, p += 2)
2531                                                 match =
2532                                                     mtag->m_tag_id >= p[0] &&
2533                                                     mtag->m_tag_id <= p[1];
2534                                 }
2535                                 break;
2536                         }
2537                                 
2538                         /*
2539                          * The second set of opcodes represents 'actions',
2540                          * i.e. the terminal part of a rule once the packet
2541                          * matches all previous patterns.
2542                          * Typically there is only one action for each rule,
2543                          * and the opcode is stored at the end of the rule
2544                          * (but there are exceptions -- see below).
2545                          *
2546                          * In general, here we set retval and terminate the
2547                          * outer loop (would be a 'break 3' in some language,
2548                          * but we need to set l=0, done=1)
2549                          *
2550                          * Exceptions:
2551                          * O_COUNT and O_SKIPTO actions:
2552                          *   instead of terminating, we jump to the next rule
2553                          *   (setting l=0), or to the SKIPTO target (setting
2554                          *   f/f_len, cmd and l as needed), respectively.
2555                          *
2556                          * O_TAG, O_LOG and O_ALTQ action parameters:
2557                          *   perform some action and set match = 1;
2558                          *
2559                          * O_LIMIT and O_KEEP_STATE: these opcodes are
2560                          *   not real 'actions', and are stored right
2561                          *   before the 'action' part of the rule.
2562                          *   These opcodes try to install an entry in the
2563                          *   state tables; if successful, we continue with
2564                          *   the next opcode (match=1; break;), otherwise
2565                          *   the packet must be dropped (set retval,
2566                          *   break loops with l=0, done=1)
2567                          *
2568                          * O_PROBE_STATE and O_CHECK_STATE: these opcodes
2569                          *   cause a lookup of the state table, and a jump
2570                          *   to the 'action' part of the parent rule
2571                          *   if an entry is found, or
2572                          *   (CHECK_STATE only) a jump to the next rule if
2573                          *   the entry is not found.
2574                          *   The result of the lookup is cached so that
2575                          *   further instances of these opcodes become NOPs.
2576                          *   The jump to the next rule is done by setting
2577                          *   l=0, cmdlen=0.
2578                          */
2579                         case O_LIMIT:
2580                         case O_KEEP_STATE:
2581                                 if (ipfw_dyn_install_state(chain, f,
2582                                     (ipfw_insn_limit *)cmd, args, tablearg)) {
2583                                         /* error or limit violation */
2584                                         retval = IP_FW_DENY;
2585                                         l = 0;  /* exit inner loop */
2586                                         done = 1; /* exit outer loop */
2587                                 }
2588                                 match = 1;
2589                                 break;
2590
2591                         case O_PROBE_STATE:
2592                         case O_CHECK_STATE:
2593                                 /*
2594                                  * dynamic rules are checked at the first
2595                                  * keep-state or check-state occurrence,
2596                                  * with the result being stored in dyn_dir
2597                                  * and dyn_name.
2598                                  * The compiler introduces a PROBE_STATE
2599                                  * instruction for us when we have a
2600                                  * KEEP_STATE (because PROBE_STATE needs
2601                                  * to be run first).
2602                                  *
2603                                  * (dyn_dir == MATCH_UNKNOWN) means this is
2604                                  * first lookup for such f_id. Do lookup.
2605                                  *
2606                                  * (dyn_dir != MATCH_UNKNOWN &&
2607                                  *  dyn_name != 0 && dyn_name != cmd->arg1)
2608                                  * means previous lookup didn't find dynamic
2609                                  * rule for specific state name and current
2610                                  * lookup will search rule with another state
2611                                  * name. Redo lookup.
2612                                  *
2613                                  * (dyn_dir != MATCH_UNKNOWN && dyn_name == 0)
2614                                  * means previous lookup was for `any' name
2615                                  * and it didn't find rule. No need to do
2616                                  * lookup again.
2617                                  */
2618                                 if ((dyn_dir == MATCH_UNKNOWN ||
2619                                     (dyn_name != 0 &&
2620                                     dyn_name != cmd->arg1)) &&
2621                                     (q = ipfw_dyn_lookup_state(&args->f_id,
2622                                      ulp, pktlen, &dyn_dir,
2623                                      (dyn_name = cmd->arg1))) != NULL) {
2624                                         /*
2625                                          * Found dynamic entry, jump to the
2626                                          * 'action' part of the parent rule
2627                                          * by setting f, cmd, l and clearing
2628                                          * cmdlen.
2629                                          */
2630                                         f = q;
2631                                         /* XXX we would like to have f_pos
2632                                          * readily accessible in the dynamic
2633                                          * rule, instead of having to
2634                                          * lookup q->rule.
2635                                          */
2636                                         f_pos = ipfw_find_rule(chain,
2637                                             f->rulenum, f->id);
2638                                         cmd = ACTION_PTR(f);
2639                                         l = f->cmd_len - f->act_ofs;
2640                                         cmdlen = 0;
2641                                         match = 1;
2642                                         break;
2643                                 }
2644                                 /*
2645                                  * Dynamic entry not found. If CHECK_STATE,
2646                                  * skip to next rule, if PROBE_STATE just
2647                                  * ignore and continue with next opcode.
2648                                  */
2649                                 if (cmd->opcode == O_CHECK_STATE)
2650                                         l = 0;  /* exit inner loop */
2651                                 match = 1;
2652                                 break;
2653
2654                         case O_ACCEPT:
2655                                 retval = 0;     /* accept */
2656                                 l = 0;          /* exit inner loop */
2657                                 done = 1;       /* exit outer loop */
2658                                 break;
2659
2660                         case O_PIPE:
2661                         case O_QUEUE:
2662                                 set_match(args, f_pos, chain);
2663                                 args->rule.info = TARG(cmd->arg1, pipe);
2664                                 if (cmd->opcode == O_PIPE)
2665                                         args->rule.info |= IPFW_IS_PIPE;
2666                                 if (V_fw_one_pass)
2667                                         args->rule.info |= IPFW_ONEPASS;
2668                                 retval = IP_FW_DUMMYNET;
2669                                 l = 0;          /* exit inner loop */
2670                                 done = 1;       /* exit outer loop */
2671                                 break;
2672
2673                         case O_DIVERT:
2674                         case O_TEE:
2675                                 if (args->eh) /* not on layer 2 */
2676                                     break;
2677                                 /* otherwise this is terminal */
2678                                 l = 0;          /* exit inner loop */
2679                                 done = 1;       /* exit outer loop */
2680                                 retval = (cmd->opcode == O_DIVERT) ?
2681                                         IP_FW_DIVERT : IP_FW_TEE;
2682                                 set_match(args, f_pos, chain);
2683                                 args->rule.info = TARG(cmd->arg1, divert);
2684                                 break;
2685
2686                         case O_COUNT:
2687                                 IPFW_INC_RULE_COUNTER(f, pktlen);
2688                                 l = 0;          /* exit inner loop */
2689                                 break;
2690
2691                         case O_SKIPTO:
2692                             IPFW_INC_RULE_COUNTER(f, pktlen);
2693                             f_pos = JUMP(chain, f, cmd->arg1, tablearg, 0);
2694                             /*
2695                              * Skip disabled rules, and re-enter
2696                              * the inner loop with the correct
2697                              * f_pos, f, l and cmd.
2698                              * Also clear cmdlen and skip_or
2699                              */
2700                             for (; f_pos < chain->n_rules - 1 &&
2701                                     (V_set_disable &
2702                                      (1 << chain->map[f_pos]->set));
2703                                     f_pos++)
2704                                 ;
2705                             /* Re-enter the inner loop at the skipto rule. */
2706                             f = chain->map[f_pos];
2707                             l = f->cmd_len;
2708                             cmd = f->cmd;
2709                             match = 1;
2710                             cmdlen = 0;
2711                             skip_or = 0;
2712                             continue;
2713                             break;      /* not reached */
2714
2715                         case O_CALLRETURN: {
2716                                 /*
2717                                  * Implementation of `subroutine' call/return,
2718                                  * in the stack carried in an mbuf tag. This
2719                                  * is different from `skipto' in that any call
2720                                  * address is possible (`skipto' must prevent
2721                                  * backward jumps to avoid endless loops).
2722                                  * We have `return' action when F_NOT flag is
2723                                  * present. The `m_tag_id' field is used as
2724                                  * stack pointer.
2725                                  */
2726                                 struct m_tag *mtag;
2727                                 uint16_t jmpto, *stack;
2728
2729 #define IS_CALL         ((cmd->len & F_NOT) == 0)
2730 #define IS_RETURN       ((cmd->len & F_NOT) != 0)
2731                                 /*
2732                                  * Hand-rolled version of m_tag_locate() with
2733                                  * wildcard `type'.
2734                                  * If not already tagged, allocate new tag.
2735                                  */
2736                                 mtag = m_tag_first(m);
2737                                 while (mtag != NULL) {
2738                                         if (mtag->m_tag_cookie ==
2739                                             MTAG_IPFW_CALL)
2740                                                 break;
2741                                         mtag = m_tag_next(m, mtag);
2742                                 }
2743                                 if (mtag == NULL && IS_CALL) {
2744                                         mtag = m_tag_alloc(MTAG_IPFW_CALL, 0,
2745                                             IPFW_CALLSTACK_SIZE *
2746                                             sizeof(uint16_t), M_NOWAIT);
2747                                         if (mtag != NULL)
2748                                                 m_tag_prepend(m, mtag);
2749                                 }
2750
2751                                 /*
2752                                  * On error both `call' and `return' just
2753                                  * continue with next rule.
2754                                  */
2755                                 if (IS_RETURN && (mtag == NULL ||
2756                                     mtag->m_tag_id == 0)) {
2757                                         l = 0;          /* exit inner loop */
2758                                         break;
2759                                 }
2760                                 if (IS_CALL && (mtag == NULL ||
2761                                     mtag->m_tag_id >= IPFW_CALLSTACK_SIZE)) {
2762                                         printf("ipfw: call stack error, "
2763                                             "go to next rule\n");
2764                                         l = 0;          /* exit inner loop */
2765                                         break;
2766                                 }
2767
2768                                 IPFW_INC_RULE_COUNTER(f, pktlen);
2769                                 stack = (uint16_t *)(mtag + 1);
2770
2771                                 /*
2772                                  * The `call' action may use cached f_pos
2773                                  * (in f->next_rule), whose version is written
2774                                  * in f->next_rule.
2775                                  * The `return' action, however, doesn't have
2776                                  * fixed jump address in cmd->arg1 and can't use
2777                                  * cache.
2778                                  */
2779                                 if (IS_CALL) {
2780                                         stack[mtag->m_tag_id] = f->rulenum;
2781                                         mtag->m_tag_id++;
2782                                         f_pos = JUMP(chain, f, cmd->arg1,
2783                                             tablearg, 1);
2784                                 } else {        /* `return' action */
2785                                         mtag->m_tag_id--;
2786                                         jmpto = stack[mtag->m_tag_id] + 1;
2787                                         f_pos = ipfw_find_rule(chain, jmpto, 0);
2788                                 }
2789
2790                                 /*
2791                                  * Skip disabled rules, and re-enter
2792                                  * the inner loop with the correct
2793                                  * f_pos, f, l and cmd.
2794                                  * Also clear cmdlen and skip_or
2795                                  */
2796                                 for (; f_pos < chain->n_rules - 1 &&
2797                                     (V_set_disable &
2798                                     (1 << chain->map[f_pos]->set)); f_pos++)
2799                                         ;
2800                                 /* Re-enter the inner loop at the dest rule. */
2801                                 f = chain->map[f_pos];
2802                                 l = f->cmd_len;
2803                                 cmd = f->cmd;
2804                                 cmdlen = 0;
2805                                 skip_or = 0;
2806                                 continue;
2807                                 break;  /* NOTREACHED */
2808                         }
2809 #undef IS_CALL
2810 #undef IS_RETURN
2811
2812                         case O_REJECT:
2813                                 /*
2814                                  * Drop the packet and send a reject notice
2815                                  * if the packet is not ICMP (or is an ICMP
2816                                  * query), and it is not multicast/broadcast.
2817                                  */
2818                                 if (hlen > 0 && is_ipv4 && offset == 0 &&
2819                                     (proto != IPPROTO_ICMP ||
2820                                      is_icmp_query(ICMP(ulp))) &&
2821                                     !(m->m_flags & (M_BCAST|M_MCAST)) &&
2822                                     !IN_MULTICAST(ntohl(dst_ip.s_addr))) {
2823                                         send_reject(args, cmd->arg1, iplen, ip);
2824                                         m = args->m;
2825                                 }
2826                                 /* FALLTHROUGH */
2827 #ifdef INET6
2828                         case O_UNREACH6:
2829                                 if (hlen > 0 && is_ipv6 &&
2830                                     ((offset & IP6F_OFF_MASK) == 0) &&
2831                                     (proto != IPPROTO_ICMPV6 ||
2832                                      (is_icmp6_query(icmp6_type) == 1)) &&
2833                                     !(m->m_flags & (M_BCAST|M_MCAST)) &&
2834                                     !IN6_IS_ADDR_MULTICAST(&args->f_id.dst_ip6)) {
2835                                         send_reject6(
2836                                             args, cmd->arg1, hlen,
2837                                             (struct ip6_hdr *)ip);
2838                                         m = args->m;
2839                                 }
2840                                 /* FALLTHROUGH */
2841 #endif
2842                         case O_DENY:
2843                                 retval = IP_FW_DENY;
2844                                 l = 0;          /* exit inner loop */
2845                                 done = 1;       /* exit outer loop */
2846                                 break;
2847
2848                         case O_FORWARD_IP:
2849                                 if (args->eh)   /* not valid on layer2 pkts */
2850                                         break;
2851                                 if (q != f || dyn_dir == MATCH_FORWARD) {
2852                                     struct sockaddr_in *sa;
2853
2854                                     sa = &(((ipfw_insn_sa *)cmd)->sa);
2855                                     if (sa->sin_addr.s_addr == INADDR_ANY) {
2856 #ifdef INET6
2857                                         /*
2858                                          * We use O_FORWARD_IP opcode for
2859                                          * fwd rule with tablearg, but tables
2860                                          * now support IPv6 addresses. And
2861                                          * when we are inspecting IPv6 packet,
2862                                          * we can use nh6 field from
2863                                          * table_value as next_hop6 address.
2864                                          */
2865                                         if (is_ipv6) {
2866                                                 struct sockaddr_in6 *sa6;
2867
2868                                                 sa6 = args->next_hop6 =
2869                                                     &args->hopstore6;
2870                                                 sa6->sin6_family = AF_INET6;
2871                                                 sa6->sin6_len = sizeof(*sa6);
2872                                                 sa6->sin6_addr = TARG_VAL(
2873                                                     chain, tablearg, nh6);
2874                                                 sa6->sin6_port = sa->sin_port;
2875                                                 /*
2876                                                  * Set sin6_scope_id only for
2877                                                  * link-local unicast addresses.
2878                                                  */
2879                                                 if (IN6_IS_ADDR_LINKLOCAL(
2880                                                     &sa6->sin6_addr))
2881                                                         sa6->sin6_scope_id =
2882                                                             TARG_VAL(chain,
2883                                                                 tablearg,
2884                                                                 zoneid);
2885                                         } else
2886 #endif
2887                                         {
2888                                                 args->hopstore.sin_port =
2889                                                     sa->sin_port;
2890                                                 sa = args->next_hop =
2891                                                     &args->hopstore;
2892                                                 sa->sin_family = AF_INET;
2893                                                 sa->sin_len = sizeof(*sa);
2894                                                 sa->sin_addr.s_addr = htonl(
2895                                                     TARG_VAL(chain, tablearg,
2896                                                     nh4));
2897                                         }
2898                                     } else {
2899                                         args->next_hop = sa;
2900                                     }
2901                                 }
2902                                 retval = IP_FW_PASS;
2903                                 l = 0;          /* exit inner loop */
2904                                 done = 1;       /* exit outer loop */
2905                                 break;
2906
2907 #ifdef INET6
2908                         case O_FORWARD_IP6:
2909                                 if (args->eh)   /* not valid on layer2 pkts */
2910                                         break;
2911                                 if (q != f || dyn_dir == MATCH_FORWARD) {
2912                                         struct sockaddr_in6 *sin6;
2913
2914                                         sin6 = &(((ipfw_insn_sa6 *)cmd)->sa);
2915                                         args->next_hop6 = sin6;
2916                                 }
2917                                 retval = IP_FW_PASS;
2918                                 l = 0;          /* exit inner loop */
2919                                 done = 1;       /* exit outer loop */
2920                                 break;
2921 #endif
2922
2923                         case O_NETGRAPH:
2924                         case O_NGTEE:
2925                                 set_match(args, f_pos, chain);
2926                                 args->rule.info = TARG(cmd->arg1, netgraph);
2927                                 if (V_fw_one_pass)
2928                                         args->rule.info |= IPFW_ONEPASS;
2929                                 retval = (cmd->opcode == O_NETGRAPH) ?
2930                                     IP_FW_NETGRAPH : IP_FW_NGTEE;
2931                                 l = 0;          /* exit inner loop */
2932                                 done = 1;       /* exit outer loop */
2933                                 break;
2934
2935                         case O_SETFIB: {
2936                                 uint32_t fib;
2937
2938                                 IPFW_INC_RULE_COUNTER(f, pktlen);
2939                                 fib = TARG(cmd->arg1, fib) & 0x7FFF;
2940                                 if (fib >= rt_numfibs)
2941                                         fib = 0;
2942                                 M_SETFIB(m, fib);
2943                                 args->f_id.fib = fib;
2944                                 l = 0;          /* exit inner loop */
2945                                 break;
2946                         }
2947
2948                         case O_SETDSCP: {
2949                                 uint16_t code;
2950
2951                                 code = TARG(cmd->arg1, dscp) & 0x3F;
2952                                 l = 0;          /* exit inner loop */
2953                                 if (is_ipv4) {
2954                                         uint16_t old;
2955
2956                                         old = *(uint16_t *)ip;
2957                                         ip->ip_tos = (code << 2) |
2958                                             (ip->ip_tos & 0x03);
2959                                         ip->ip_sum = cksum_adjust(ip->ip_sum,
2960                                             old, *(uint16_t *)ip);
2961                                 } else if (is_ipv6) {
2962                                         uint8_t *v;
2963
2964                                         v = &((struct ip6_hdr *)ip)->ip6_vfc;
2965                                         *v = (*v & 0xF0) | (code >> 2);
2966                                         v++;
2967                                         *v = (*v & 0x3F) | ((code & 0x03) << 6);
2968                                 } else
2969                                         break;
2970
2971                                 IPFW_INC_RULE_COUNTER(f, pktlen);
2972                                 break;
2973                         }
2974
2975                         case O_NAT:
2976                                 l = 0;          /* exit inner loop */
2977                                 done = 1;       /* exit outer loop */
2978                                 /*
2979                                  * Ensure that we do not invoke NAT handler for
2980                                  * non IPv4 packets. Libalias expects only IPv4.
2981                                  */
2982                                 if (!is_ipv4 || !IPFW_NAT_LOADED) {
2983                                     retval = IP_FW_DENY;
2984                                     break;
2985                                 }
2986
2987                                 struct cfg_nat *t;
2988                                 int nat_id;
2989
2990                                 set_match(args, f_pos, chain);
2991                                 /* Check if this is 'global' nat rule */
2992                                 if (cmd->arg1 == IP_FW_NAT44_GLOBAL) {
2993                                         retval = ipfw_nat_ptr(args, NULL, m);
2994                                         break;
2995                                 }
2996                                 t = ((ipfw_insn_nat *)cmd)->nat;
2997                                 if (t == NULL) {
2998                                         nat_id = TARG(cmd->arg1, nat);
2999                                         t = (*lookup_nat_ptr)(&chain->nat, nat_id);
3000
3001                                         if (t == NULL) {
3002                                             retval = IP_FW_DENY;
3003                                             break;
3004                                         }
3005                                         if (cmd->arg1 != IP_FW_TARG)
3006                                             ((ipfw_insn_nat *)cmd)->nat = t;
3007                                 }
3008                                 retval = ipfw_nat_ptr(args, t, m);
3009                                 break;
3010
3011                         case O_REASS: {
3012                                 int ip_off;
3013
3014                                 IPFW_INC_RULE_COUNTER(f, pktlen);
3015                                 l = 0;  /* in any case exit inner loop */
3016                                 ip_off = ntohs(ip->ip_off);
3017
3018                                 /* if not fragmented, go to next rule */
3019                                 if ((ip_off & (IP_MF | IP_OFFMASK)) == 0)
3020                                     break;
3021
3022                                 args->m = m = ip_reass(m);
3023
3024                                 /*
3025                                  * do IP header checksum fixup.
3026                                  */
3027                                 if (m == NULL) { /* fragment got swallowed */
3028                                     retval = IP_FW_DENY;
3029                                 } else { /* good, packet complete */
3030                                     int hlen;
3031
3032                                     ip = mtod(m, struct ip *);
3033                                     hlen = ip->ip_hl << 2;
3034                                     ip->ip_sum = 0;
3035                                     if (hlen == sizeof(struct ip))
3036                                         ip->ip_sum = in_cksum_hdr(ip);
3037                                     else
3038                                         ip->ip_sum = in_cksum(m, hlen);
3039                                     retval = IP_FW_REASS;
3040                                     set_match(args, f_pos, chain);
3041                                 }
3042                                 done = 1;       /* exit outer loop */
3043                                 break;
3044                         }
3045                         case O_EXTERNAL_ACTION:
3046                                 l = 0; /* in any case exit inner loop */
3047                                 retval = ipfw_run_eaction(chain, args,
3048                                     cmd, &done);
3049                                 /*
3050                                  * If both @retval and @done are zero,
3051                                  * consider this as rule matching and
3052                                  * update counters.
3053                                  */
3054                                 if (retval == 0 && done == 0) {
3055                                         IPFW_INC_RULE_COUNTER(f, pktlen);
3056                                         /*
3057                                          * Reset the result of the last
3058                                          * dynamic state lookup.
3059                                          * External action can change
3060                                          * @args content, and it may be
3061                                          * used for new state lookup later.
3062                                          */
3063                                         dyn_dir = MATCH_UNKNOWN;
3064                                 }
3065                                 break;
3066
3067                         default:
3068                                 panic("-- unknown opcode %d\n", cmd->opcode);
3069                         } /* end of switch() on opcodes */
3070                         /*
3071                          * if we get here with l=0, then match is irrelevant.
3072                          */
3073
3074                         if (cmd->len & F_NOT)
3075                                 match = !match;
3076
3077                         if (match) {
3078                                 if (cmd->len & F_OR)
3079                                         skip_or = 1;
3080                         } else {
3081                                 if (!(cmd->len & F_OR)) /* not an OR block, */
3082                                         break;          /* try next rule    */
3083                         }
3084
3085                 }       /* end of inner loop, scan opcodes */
3086 #undef PULLUP_LEN
3087
3088                 if (done)
3089                         break;
3090
3091 /* next_rule:; */       /* try next rule                */
3092
3093         }               /* end of outer for, scan rules */
3094
3095         if (done) {
3096                 struct ip_fw *rule = chain->map[f_pos];
3097                 /* Update statistics */
3098                 IPFW_INC_RULE_COUNTER(rule, pktlen);
3099         } else {
3100                 retval = IP_FW_DENY;
3101                 printf("ipfw: ouch!, skip past end of rules, denying packet\n");
3102         }
3103         IPFW_PF_RUNLOCK(chain);
3104 #ifdef __FreeBSD__
3105         if (ucred_cache != NULL)
3106                 crfree(ucred_cache);
3107 #endif
3108         return (retval);
3109
3110 pullup_failed:
3111         if (V_fw_verbose)
3112                 printf("ipfw: pullup failed\n");
3113         return (IP_FW_DENY);
3114 }
3115
3116 /*
3117  * Set maximum number of tables that can be used in given VNET ipfw instance.
3118  */
3119 #ifdef SYSCTL_NODE
3120 static int
3121 sysctl_ipfw_table_num(SYSCTL_HANDLER_ARGS)
3122 {
3123         int error;
3124         unsigned int ntables;
3125
3126         ntables = V_fw_tables_max;
3127
3128         error = sysctl_handle_int(oidp, &ntables, 0, req);
3129         /* Read operation or some error */
3130         if ((error != 0) || (req->newptr == NULL))
3131                 return (error);
3132
3133         return (ipfw_resize_tables(&V_layer3_chain, ntables));
3134 }
3135
3136 /*
3137  * Switches table namespace between global and per-set.
3138  */
3139 static int
3140 sysctl_ipfw_tables_sets(SYSCTL_HANDLER_ARGS)
3141 {
3142         int error;
3143         unsigned int sets;
3144
3145         sets = V_fw_tables_sets;
3146
3147         error = sysctl_handle_int(oidp, &sets, 0, req);
3148         /* Read operation or some error */
3149         if ((error != 0) || (req->newptr == NULL))
3150                 return (error);
3151
3152         return (ipfw_switch_tables_namespace(&V_layer3_chain, sets));
3153 }
3154 #endif
3155
3156 /*
3157  * Module and VNET glue
3158  */
3159
3160 /*
3161  * Stuff that must be initialised only on boot or module load
3162  */
3163 static int
3164 ipfw_init(void)
3165 {
3166         int error = 0;
3167
3168         /*
3169          * Only print out this stuff the first time around,
3170          * when called from the sysinit code.
3171          */
3172         printf("ipfw2 "
3173 #ifdef INET6
3174                 "(+ipv6) "
3175 #endif
3176                 "initialized, divert %s, nat %s, "
3177                 "default to %s, logging ",
3178 #ifdef IPDIVERT
3179                 "enabled",
3180 #else
3181                 "loadable",
3182 #endif
3183 #ifdef IPFIREWALL_NAT
3184                 "enabled",
3185 #else
3186                 "loadable",
3187 #endif
3188                 default_to_accept ? "accept" : "deny");
3189
3190         /*
3191          * Note: V_xxx variables can be accessed here but the vnet specific
3192          * initializer may not have been called yet for the VIMAGE case.
3193          * Tuneables will have been processed. We will print out values for
3194          * the default vnet. 
3195          * XXX This should all be rationalized AFTER 8.0
3196          */
3197         if (V_fw_verbose == 0)
3198                 printf("disabled\n");
3199         else if (V_verbose_limit == 0)
3200                 printf("unlimited\n");
3201         else
3202                 printf("limited to %d packets/entry by default\n",
3203                     V_verbose_limit);
3204
3205         /* Check user-supplied table count for validness */
3206         if (default_fw_tables > IPFW_TABLES_MAX)
3207           default_fw_tables = IPFW_TABLES_MAX;
3208
3209         ipfw_init_sopt_handler();
3210         ipfw_init_obj_rewriter();
3211         ipfw_iface_init();
3212         return (error);
3213 }
3214
3215 /*
3216  * Called for the removal of the last instance only on module unload.
3217  */
3218 static void
3219 ipfw_destroy(void)
3220 {
3221
3222         ipfw_iface_destroy();
3223         ipfw_destroy_sopt_handler();
3224         ipfw_destroy_obj_rewriter();
3225         printf("IP firewall unloaded\n");
3226 }
3227
3228 /*
3229  * Stuff that must be initialized for every instance
3230  * (including the first of course).
3231  */
3232 static int
3233 vnet_ipfw_init(const void *unused)
3234 {
3235         int error, first;
3236         struct ip_fw *rule = NULL;
3237         struct ip_fw_chain *chain;
3238
3239         chain = &V_layer3_chain;
3240
3241         first = IS_DEFAULT_VNET(curvnet) ? 1 : 0;
3242
3243         /* First set up some values that are compile time options */
3244         V_autoinc_step = 100;   /* bounded to 1..1000 in add_rule() */
3245         V_fw_deny_unknown_exthdrs = 1;
3246 #ifdef IPFIREWALL_VERBOSE
3247         V_fw_verbose = 1;
3248 #endif
3249 #ifdef IPFIREWALL_VERBOSE_LIMIT
3250         V_verbose_limit = IPFIREWALL_VERBOSE_LIMIT;
3251 #endif
3252 #ifdef IPFIREWALL_NAT
3253         LIST_INIT(&chain->nat);
3254 #endif
3255
3256         /* Init shared services hash table */
3257         ipfw_init_srv(chain);
3258
3259         ipfw_init_counters();
3260         /* Set initial number of tables */
3261         V_fw_tables_max = default_fw_tables;
3262         error = ipfw_init_tables(chain, first);
3263         if (error) {
3264                 printf("ipfw2: setting up tables failed\n");
3265                 free(chain->map, M_IPFW);
3266                 free(rule, M_IPFW);
3267                 return (ENOSPC);
3268         }
3269
3270         IPFW_LOCK_INIT(chain);
3271
3272         /* fill and insert the default rule */
3273         rule = ipfw_alloc_rule(chain, sizeof(struct ip_fw));
3274         rule->cmd_len = 1;
3275         rule->cmd[0].len = 1;
3276         rule->cmd[0].opcode = default_to_accept ? O_ACCEPT : O_DENY;
3277         chain->default_rule = rule;
3278         ipfw_add_protected_rule(chain, rule, 0);
3279
3280         ipfw_dyn_init(chain);
3281         ipfw_eaction_init(chain, first);
3282 #ifdef LINEAR_SKIPTO
3283         ipfw_init_skipto_cache(chain);
3284 #endif
3285         ipfw_bpf_init(first);
3286
3287         /* First set up some values that are compile time options */
3288         V_ipfw_vnet_ready = 1;          /* Open for business */
3289
3290         /*
3291          * Hook the sockopt handler and pfil hooks for ipv4 and ipv6.
3292          * Even if the latter two fail we still keep the module alive
3293          * because the sockopt and layer2 paths are still useful.
3294          * ipfw[6]_hook return 0 on success, ENOENT on failure,
3295          * so we can ignore the exact return value and just set a flag.
3296          *
3297          * Note that V_fw[6]_enable are manipulated by a SYSCTL_PROC so
3298          * changes in the underlying (per-vnet) variables trigger
3299          * immediate hook()/unhook() calls.
3300          * In layer2 we have the same behaviour, except that V_ether_ipfw
3301          * is checked on each packet because there are no pfil hooks.
3302          */
3303         V_ip_fw_ctl_ptr = ipfw_ctl3;
3304         error = ipfw_attach_hooks(1);
3305         return (error);
3306 }
3307
3308 /*
3309  * Called for the removal of each instance.
3310  */
3311 static int
3312 vnet_ipfw_uninit(const void *unused)
3313 {
3314         struct ip_fw *reap;
3315         struct ip_fw_chain *chain = &V_layer3_chain;
3316         int i, last;
3317
3318         V_ipfw_vnet_ready = 0; /* tell new callers to go away */
3319         /*
3320          * disconnect from ipv4, ipv6, layer2 and sockopt.
3321          * Then grab, release and grab again the WLOCK so we make
3322          * sure the update is propagated and nobody will be in.
3323          */
3324         (void)ipfw_attach_hooks(0 /* detach */);
3325         V_ip_fw_ctl_ptr = NULL;
3326
3327         last = IS_DEFAULT_VNET(curvnet) ? 1 : 0;
3328
3329         IPFW_UH_WLOCK(chain);
3330         IPFW_UH_WUNLOCK(chain);
3331
3332         ipfw_dyn_uninit(0);     /* run the callout_drain */
3333
3334         IPFW_UH_WLOCK(chain);
3335
3336         reap = NULL;
3337         IPFW_WLOCK(chain);
3338         for (i = 0; i < chain->n_rules; i++)
3339                 ipfw_reap_add(chain, &reap, chain->map[i]);
3340         free(chain->map, M_IPFW);
3341 #ifdef LINEAR_SKIPTO
3342         ipfw_destroy_skipto_cache(chain);
3343 #endif
3344         IPFW_WUNLOCK(chain);
3345         IPFW_UH_WUNLOCK(chain);
3346         ipfw_destroy_tables(chain, last);
3347         ipfw_eaction_uninit(chain, last);
3348         if (reap != NULL)
3349                 ipfw_reap_rules(reap);
3350         vnet_ipfw_iface_destroy(chain);
3351         ipfw_destroy_srv(chain);
3352         IPFW_LOCK_DESTROY(chain);
3353         ipfw_dyn_uninit(1);     /* free the remaining parts */
3354         ipfw_destroy_counters();
3355         ipfw_bpf_uninit(last);
3356         return (0);
3357 }
3358
3359 /*
3360  * Module event handler.
3361  * In general we have the choice of handling most of these events by the
3362  * event handler or by the (VNET_)SYS(UN)INIT handlers. I have chosen to
3363  * use the SYSINIT handlers as they are more capable of expressing the
3364  * flow of control during module and vnet operations, so this is just
3365  * a skeleton. Note there is no SYSINIT equivalent of the module
3366  * SHUTDOWN handler, but we don't have anything to do in that case anyhow.
3367  */
3368 static int
3369 ipfw_modevent(module_t mod, int type, void *unused)
3370 {
3371         int err = 0;
3372
3373         switch (type) {
3374         case MOD_LOAD:
3375                 /* Called once at module load or
3376                  * system boot if compiled in. */
3377                 break;
3378         case MOD_QUIESCE:
3379                 /* Called before unload. May veto unloading. */
3380                 break;
3381         case MOD_UNLOAD:
3382                 /* Called during unload. */
3383                 break;
3384         case MOD_SHUTDOWN:
3385                 /* Called during system shutdown. */
3386                 break;
3387         default:
3388                 err = EOPNOTSUPP;
3389                 break;
3390         }
3391         return err;
3392 }
3393
3394 static moduledata_t ipfwmod = {
3395         "ipfw",
3396         ipfw_modevent,
3397         0
3398 };
3399
3400 /* Define startup order. */
3401 #define IPFW_SI_SUB_FIREWALL    SI_SUB_PROTO_FIREWALL
3402 #define IPFW_MODEVENT_ORDER     (SI_ORDER_ANY - 255) /* On boot slot in here. */
3403 #define IPFW_MODULE_ORDER       (IPFW_MODEVENT_ORDER + 1) /* A little later. */
3404 #define IPFW_VNET_ORDER         (IPFW_MODEVENT_ORDER + 2) /* Later still. */
3405
3406 DECLARE_MODULE(ipfw, ipfwmod, IPFW_SI_SUB_FIREWALL, IPFW_MODEVENT_ORDER);
3407 FEATURE(ipfw_ctl3, "ipfw new sockopt calls");
3408 MODULE_VERSION(ipfw, 3);
3409 /* should declare some dependencies here */
3410
3411 /*
3412  * Starting up. Done in order after ipfwmod() has been called.
3413  * VNET_SYSINIT is also called for each existing vnet and each new vnet.
3414  */
3415 SYSINIT(ipfw_init, IPFW_SI_SUB_FIREWALL, IPFW_MODULE_ORDER,
3416             ipfw_init, NULL);
3417 VNET_SYSINIT(vnet_ipfw_init, IPFW_SI_SUB_FIREWALL, IPFW_VNET_ORDER,
3418             vnet_ipfw_init, NULL);
3419  
3420 /*
3421  * Closing up shop. These are done in REVERSE ORDER, but still
3422  * after ipfwmod() has been called. Not called on reboot.
3423  * VNET_SYSUNINIT is also called for each exiting vnet as it exits.
3424  * or when the module is unloaded.
3425  */
3426 SYSUNINIT(ipfw_destroy, IPFW_SI_SUB_FIREWALL, IPFW_MODULE_ORDER,
3427             ipfw_destroy, NULL);
3428 VNET_SYSUNINIT(vnet_ipfw_uninit, IPFW_SI_SUB_FIREWALL, IPFW_VNET_ORDER,
3429             vnet_ipfw_uninit, NULL);
3430 /* end of file */