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