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