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