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