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