Deleted Added
full compact
ip_fw2.c (225518) ip_fw2.c (227085)
1/*-
2 * Copyright (c) 2002-2009 Luigi Rizzo, Universita` di Pisa
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 *
13 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
14 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
16 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
17 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
19 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
20 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
21 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23 * SUCH DAMAGE.
24 */
25
26#include <sys/cdefs.h>
1/*-
2 * Copyright (c) 2002-2009 Luigi Rizzo, Universita` di Pisa
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 *
13 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
14 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
16 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
17 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
19 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
20 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
21 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23 * SUCH DAMAGE.
24 */
25
26#include <sys/cdefs.h>
27__FBSDID("$FreeBSD: head/sys/netinet/ipfw/ip_fw2.c 225518 2011-09-12 21:09:56Z jhb $");
27__FBSDID("$FreeBSD: head/sys/netinet/ipfw/ip_fw2.c 227085 2011-11-04 16:24:19Z bz $");
28
29/*
30 * The FreeBSD IP packet firewall, main file
31 */
32
33#include "opt_ipfw.h"
28
29/*
30 * The FreeBSD IP packet firewall, main file
31 */
32
33#include "opt_ipfw.h"
34#if !defined(KLD_MODULE)
35#include "opt_ipdivert.h"
34#include "opt_ipdivert.h"
36#include "opt_ipdn.h"
37#include "opt_inet.h"
38#ifndef INET
39#error IPFIREWALL requires INET.
40#endif /* INET */
35#include "opt_inet.h"
36#ifndef INET
37#error IPFIREWALL requires INET.
38#endif /* INET */
41#endif
42#include "opt_inet6.h"
43#include "opt_ipsec.h"
44
45#include <sys/param.h>
46#include <sys/systm.h>
47#include <sys/condvar.h>
48#include <sys/eventhandler.h>
49#include <sys/malloc.h>
50#include <sys/mbuf.h>
51#include <sys/kernel.h>
52#include <sys/lock.h>
53#include <sys/jail.h>
54#include <sys/module.h>
55#include <sys/priv.h>
56#include <sys/proc.h>
57#include <sys/rwlock.h>
58#include <sys/socket.h>
59#include <sys/socketvar.h>
60#include <sys/sysctl.h>
61#include <sys/syslog.h>
62#include <sys/ucred.h>
63#include <net/ethernet.h> /* for ETHERTYPE_IP */
64#include <net/if.h>
65#include <net/route.h>
66#include <net/pf_mtag.h>
67#include <net/vnet.h>
68
69#include <netinet/in.h>
70#include <netinet/in_var.h>
71#include <netinet/in_pcb.h>
72#include <netinet/ip.h>
73#include <netinet/ip_var.h>
74#include <netinet/ip_icmp.h>
75#include <netinet/ip_fw.h>
76#include <netinet/ipfw/ip_fw_private.h>
77#include <netinet/ip_carp.h>
78#include <netinet/pim.h>
79#include <netinet/tcp_var.h>
80#include <netinet/udp.h>
81#include <netinet/udp_var.h>
82#include <netinet/sctp.h>
83
84#include <netinet/ip6.h>
85#include <netinet/icmp6.h>
86#ifdef INET6
87#include <netinet6/in6_pcb.h>
88#include <netinet6/scope6_var.h>
89#include <netinet6/ip6_var.h>
90#endif
91
92#include <machine/in_cksum.h> /* XXX for in_cksum */
93
94#ifdef MAC
95#include <security/mac/mac_framework.h>
96#endif
97
98/*
99 * static variables followed by global ones.
100 * All ipfw global variables are here.
101 */
102
103/* ipfw_vnet_ready controls when we are open for business */
104static VNET_DEFINE(int, ipfw_vnet_ready) = 0;
105#define V_ipfw_vnet_ready VNET(ipfw_vnet_ready)
106
107static VNET_DEFINE(int, fw_deny_unknown_exthdrs);
108#define V_fw_deny_unknown_exthdrs VNET(fw_deny_unknown_exthdrs)
109
110static VNET_DEFINE(int, fw_permit_single_frag6) = 1;
111#define V_fw_permit_single_frag6 VNET(fw_permit_single_frag6)
112
113#ifdef IPFIREWALL_DEFAULT_TO_ACCEPT
114static int default_to_accept = 1;
115#else
116static int default_to_accept;
117#endif
118
119VNET_DEFINE(int, autoinc_step);
120VNET_DEFINE(int, fw_one_pass) = 1;
121
122/*
123 * Each rule belongs to one of 32 different sets (0..31).
124 * The variable set_disable contains one bit per set.
125 * If the bit is set, all rules in the corresponding set
126 * are disabled. Set RESVD_SET(31) is reserved for the default rule
127 * and rules that are not deleted by the flush command,
128 * and CANNOT be disabled.
129 * Rules in set RESVD_SET can only be deleted individually.
130 */
131VNET_DEFINE(u_int32_t, set_disable);
132#define V_set_disable VNET(set_disable)
133
134VNET_DEFINE(int, fw_verbose);
135/* counter for ipfw_log(NULL...) */
136VNET_DEFINE(u_int64_t, norule_counter);
137VNET_DEFINE(int, verbose_limit);
138
139/* layer3_chain contains the list of rules for layer 3 */
140VNET_DEFINE(struct ip_fw_chain, layer3_chain);
141
142ipfw_nat_t *ipfw_nat_ptr = NULL;
143struct cfg_nat *(*lookup_nat_ptr)(struct nat_list *, int);
144ipfw_nat_cfg_t *ipfw_nat_cfg_ptr;
145ipfw_nat_cfg_t *ipfw_nat_del_ptr;
146ipfw_nat_cfg_t *ipfw_nat_get_cfg_ptr;
147ipfw_nat_cfg_t *ipfw_nat_get_log_ptr;
148
149#ifdef SYSCTL_NODE
150uint32_t dummy_def = IPFW_DEFAULT_RULE;
151uint32_t dummy_tables_max = IPFW_TABLES_MAX;
152
153SYSBEGIN(f3)
154
155SYSCTL_NODE(_net_inet_ip, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall");
156SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, one_pass,
157 CTLFLAG_RW | CTLFLAG_SECURE3, &VNET_NAME(fw_one_pass), 0,
158 "Only do a single pass through ipfw when using dummynet(4)");
159SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, autoinc_step,
160 CTLFLAG_RW, &VNET_NAME(autoinc_step), 0,
161 "Rule number auto-increment step");
162SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, verbose,
163 CTLFLAG_RW | CTLFLAG_SECURE3, &VNET_NAME(fw_verbose), 0,
164 "Log matches to ipfw rules");
165SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, verbose_limit,
166 CTLFLAG_RW, &VNET_NAME(verbose_limit), 0,
167 "Set upper limit of matches of ipfw rules logged");
168SYSCTL_UINT(_net_inet_ip_fw, OID_AUTO, default_rule, CTLFLAG_RD,
169 &dummy_def, 0,
170 "The default/max possible rule number.");
171SYSCTL_UINT(_net_inet_ip_fw, OID_AUTO, tables_max, CTLFLAG_RD,
172 &dummy_tables_max, 0,
173 "The maximum number of tables.");
174SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, default_to_accept, CTLFLAG_RDTUN,
175 &default_to_accept, 0,
176 "Make the default rule accept all packets.");
177TUNABLE_INT("net.inet.ip.fw.default_to_accept", &default_to_accept);
178SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, static_count,
179 CTLFLAG_RD, &VNET_NAME(layer3_chain.n_rules), 0,
180 "Number of static rules");
181
182#ifdef INET6
183SYSCTL_DECL(_net_inet6_ip6);
184SYSCTL_NODE(_net_inet6_ip6, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall");
185SYSCTL_VNET_INT(_net_inet6_ip6_fw, OID_AUTO, deny_unknown_exthdrs,
186 CTLFLAG_RW | CTLFLAG_SECURE, &VNET_NAME(fw_deny_unknown_exthdrs), 0,
187 "Deny packets with unknown IPv6 Extension Headers");
188SYSCTL_VNET_INT(_net_inet6_ip6_fw, OID_AUTO, permit_single_frag6,
189 CTLFLAG_RW | CTLFLAG_SECURE, &VNET_NAME(fw_permit_single_frag6), 0,
190 "Permit single packet IPv6 fragments");
191#endif /* INET6 */
192
193SYSEND
194
195#endif /* SYSCTL_NODE */
196
197
198/*
199 * Some macros used in the various matching options.
200 * L3HDR maps an ipv4 pointer into a layer3 header pointer of type T
201 * Other macros just cast void * into the appropriate type
202 */
203#define L3HDR(T, ip) ((T *)((u_int32_t *)(ip) + (ip)->ip_hl))
204#define TCP(p) ((struct tcphdr *)(p))
205#define SCTP(p) ((struct sctphdr *)(p))
206#define UDP(p) ((struct udphdr *)(p))
207#define ICMP(p) ((struct icmphdr *)(p))
208#define ICMP6(p) ((struct icmp6_hdr *)(p))
209
210static __inline int
211icmptype_match(struct icmphdr *icmp, ipfw_insn_u32 *cmd)
212{
213 int type = icmp->icmp_type;
214
215 return (type <= ICMP_MAXTYPE && (cmd->d[0] & (1<<type)) );
216}
217
218#define TT ( (1 << ICMP_ECHO) | (1 << ICMP_ROUTERSOLICIT) | \
219 (1 << ICMP_TSTAMP) | (1 << ICMP_IREQ) | (1 << ICMP_MASKREQ) )
220
221static int
222is_icmp_query(struct icmphdr *icmp)
223{
224 int type = icmp->icmp_type;
225
226 return (type <= ICMP_MAXTYPE && (TT & (1<<type)) );
227}
228#undef TT
229
230/*
231 * The following checks use two arrays of 8 or 16 bits to store the
232 * bits that we want set or clear, respectively. They are in the
233 * low and high half of cmd->arg1 or cmd->d[0].
234 *
235 * We scan options and store the bits we find set. We succeed if
236 *
237 * (want_set & ~bits) == 0 && (want_clear & ~bits) == want_clear
238 *
239 * The code is sometimes optimized not to store additional variables.
240 */
241
242static int
243flags_match(ipfw_insn *cmd, u_int8_t bits)
244{
245 u_char want_clear;
246 bits = ~bits;
247
248 if ( ((cmd->arg1 & 0xff) & bits) != 0)
249 return 0; /* some bits we want set were clear */
250 want_clear = (cmd->arg1 >> 8) & 0xff;
251 if ( (want_clear & bits) != want_clear)
252 return 0; /* some bits we want clear were set */
253 return 1;
254}
255
256static int
257ipopts_match(struct ip *ip, ipfw_insn *cmd)
258{
259 int optlen, bits = 0;
260 u_char *cp = (u_char *)(ip + 1);
261 int x = (ip->ip_hl << 2) - sizeof (struct ip);
262
263 for (; x > 0; x -= optlen, cp += optlen) {
264 int opt = cp[IPOPT_OPTVAL];
265
266 if (opt == IPOPT_EOL)
267 break;
268 if (opt == IPOPT_NOP)
269 optlen = 1;
270 else {
271 optlen = cp[IPOPT_OLEN];
272 if (optlen <= 0 || optlen > x)
273 return 0; /* invalid or truncated */
274 }
275 switch (opt) {
276
277 default:
278 break;
279
280 case IPOPT_LSRR:
281 bits |= IP_FW_IPOPT_LSRR;
282 break;
283
284 case IPOPT_SSRR:
285 bits |= IP_FW_IPOPT_SSRR;
286 break;
287
288 case IPOPT_RR:
289 bits |= IP_FW_IPOPT_RR;
290 break;
291
292 case IPOPT_TS:
293 bits |= IP_FW_IPOPT_TS;
294 break;
295 }
296 }
297 return (flags_match(cmd, bits));
298}
299
300static int
301tcpopts_match(struct tcphdr *tcp, ipfw_insn *cmd)
302{
303 int optlen, bits = 0;
304 u_char *cp = (u_char *)(tcp + 1);
305 int x = (tcp->th_off << 2) - sizeof(struct tcphdr);
306
307 for (; x > 0; x -= optlen, cp += optlen) {
308 int opt = cp[0];
309 if (opt == TCPOPT_EOL)
310 break;
311 if (opt == TCPOPT_NOP)
312 optlen = 1;
313 else {
314 optlen = cp[1];
315 if (optlen <= 0)
316 break;
317 }
318
319 switch (opt) {
320
321 default:
322 break;
323
324 case TCPOPT_MAXSEG:
325 bits |= IP_FW_TCPOPT_MSS;
326 break;
327
328 case TCPOPT_WINDOW:
329 bits |= IP_FW_TCPOPT_WINDOW;
330 break;
331
332 case TCPOPT_SACK_PERMITTED:
333 case TCPOPT_SACK:
334 bits |= IP_FW_TCPOPT_SACK;
335 break;
336
337 case TCPOPT_TIMESTAMP:
338 bits |= IP_FW_TCPOPT_TS;
339 break;
340
341 }
342 }
343 return (flags_match(cmd, bits));
344}
345
346static int
347iface_match(struct ifnet *ifp, ipfw_insn_if *cmd)
348{
349 if (ifp == NULL) /* no iface with this packet, match fails */
350 return 0;
351 /* Check by name or by IP address */
352 if (cmd->name[0] != '\0') { /* match by name */
353 /* Check name */
354 if (cmd->p.glob) {
355 if (fnmatch(cmd->name, ifp->if_xname, 0) == 0)
356 return(1);
357 } else {
358 if (strncmp(ifp->if_xname, cmd->name, IFNAMSIZ) == 0)
359 return(1);
360 }
361 } else {
362#ifdef __FreeBSD__ /* and OSX too ? */
363 struct ifaddr *ia;
364
365 if_addr_rlock(ifp);
366 TAILQ_FOREACH(ia, &ifp->if_addrhead, ifa_link) {
367 if (ia->ifa_addr->sa_family != AF_INET)
368 continue;
369 if (cmd->p.ip.s_addr == ((struct sockaddr_in *)
370 (ia->ifa_addr))->sin_addr.s_addr) {
371 if_addr_runlock(ifp);
372 return(1); /* match */
373 }
374 }
375 if_addr_runlock(ifp);
376#endif /* __FreeBSD__ */
377 }
378 return(0); /* no match, fail ... */
379}
380
381/*
382 * The verify_path function checks if a route to the src exists and
383 * if it is reachable via ifp (when provided).
384 *
385 * The 'verrevpath' option checks that the interface that an IP packet
386 * arrives on is the same interface that traffic destined for the
387 * packet's source address would be routed out of.
388 * The 'versrcreach' option just checks that the source address is
389 * reachable via any route (except default) in the routing table.
390 * These two are a measure to block forged packets. This is also
391 * commonly known as "anti-spoofing" or Unicast Reverse Path
392 * Forwarding (Unicast RFP) in Cisco-ese. The name of the knobs
393 * is purposely reminiscent of the Cisco IOS command,
394 *
395 * ip verify unicast reverse-path
396 * ip verify unicast source reachable-via any
397 *
398 * which implements the same functionality. But note that the syntax
399 * is misleading, and the check may be performed on all IP packets
400 * whether unicast, multicast, or broadcast.
401 */
402static int
403verify_path(struct in_addr src, struct ifnet *ifp, u_int fib)
404{
405#ifndef __FreeBSD__
406 return 0;
407#else
408 struct route ro;
409 struct sockaddr_in *dst;
410
411 bzero(&ro, sizeof(ro));
412
413 dst = (struct sockaddr_in *)&(ro.ro_dst);
414 dst->sin_family = AF_INET;
415 dst->sin_len = sizeof(*dst);
416 dst->sin_addr = src;
417 in_rtalloc_ign(&ro, 0, fib);
418
419 if (ro.ro_rt == NULL)
420 return 0;
421
422 /*
423 * If ifp is provided, check for equality with rtentry.
424 * We should use rt->rt_ifa->ifa_ifp, instead of rt->rt_ifp,
425 * in order to pass packets injected back by if_simloop():
426 * if useloopback == 1 routing entry (via lo0) for our own address
427 * may exist, so we need to handle routing assymetry.
428 */
429 if (ifp != NULL && ro.ro_rt->rt_ifa->ifa_ifp != ifp) {
430 RTFREE(ro.ro_rt);
431 return 0;
432 }
433
434 /* if no ifp provided, check if rtentry is not default route */
435 if (ifp == NULL &&
436 satosin(rt_key(ro.ro_rt))->sin_addr.s_addr == INADDR_ANY) {
437 RTFREE(ro.ro_rt);
438 return 0;
439 }
440
441 /* or if this is a blackhole/reject route */
442 if (ifp == NULL && ro.ro_rt->rt_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
443 RTFREE(ro.ro_rt);
444 return 0;
445 }
446
447 /* found valid route */
448 RTFREE(ro.ro_rt);
449 return 1;
450#endif /* __FreeBSD__ */
451}
452
453#ifdef INET6
454/*
455 * ipv6 specific rules here...
456 */
457static __inline int
458icmp6type_match (int type, ipfw_insn_u32 *cmd)
459{
460 return (type <= ICMP6_MAXTYPE && (cmd->d[type/32] & (1<<(type%32)) ) );
461}
462
463static int
464flow6id_match( int curr_flow, ipfw_insn_u32 *cmd )
465{
466 int i;
467 for (i=0; i <= cmd->o.arg1; ++i )
468 if (curr_flow == cmd->d[i] )
469 return 1;
470 return 0;
471}
472
473/* support for IP6_*_ME opcodes */
474static int
475search_ip6_addr_net (struct in6_addr * ip6_addr)
476{
477 struct ifnet *mdc;
478 struct ifaddr *mdc2;
479 struct in6_ifaddr *fdm;
480 struct in6_addr copia;
481
482 TAILQ_FOREACH(mdc, &V_ifnet, if_link) {
483 if_addr_rlock(mdc);
484 TAILQ_FOREACH(mdc2, &mdc->if_addrhead, ifa_link) {
485 if (mdc2->ifa_addr->sa_family == AF_INET6) {
486 fdm = (struct in6_ifaddr *)mdc2;
487 copia = fdm->ia_addr.sin6_addr;
488 /* need for leaving scope_id in the sock_addr */
489 in6_clearscope(&copia);
490 if (IN6_ARE_ADDR_EQUAL(ip6_addr, &copia)) {
491 if_addr_runlock(mdc);
492 return 1;
493 }
494 }
495 }
496 if_addr_runlock(mdc);
497 }
498 return 0;
499}
500
501static int
502verify_path6(struct in6_addr *src, struct ifnet *ifp)
503{
504 struct route_in6 ro;
505 struct sockaddr_in6 *dst;
506
507 bzero(&ro, sizeof(ro));
508
509 dst = (struct sockaddr_in6 * )&(ro.ro_dst);
510 dst->sin6_family = AF_INET6;
511 dst->sin6_len = sizeof(*dst);
512 dst->sin6_addr = *src;
513 /* XXX MRT 0 for ipv6 at this time */
514 rtalloc_ign((struct route *)&ro, 0);
515
516 if (ro.ro_rt == NULL)
517 return 0;
518
519 /*
520 * if ifp is provided, check for equality with rtentry
521 * We should use rt->rt_ifa->ifa_ifp, instead of rt->rt_ifp,
522 * to support the case of sending packets to an address of our own.
523 * (where the former interface is the first argument of if_simloop()
524 * (=ifp), the latter is lo0)
525 */
526 if (ifp != NULL && ro.ro_rt->rt_ifa->ifa_ifp != ifp) {
527 RTFREE(ro.ro_rt);
528 return 0;
529 }
530
531 /* if no ifp provided, check if rtentry is not default route */
532 if (ifp == NULL &&
533 IN6_IS_ADDR_UNSPECIFIED(&satosin6(rt_key(ro.ro_rt))->sin6_addr)) {
534 RTFREE(ro.ro_rt);
535 return 0;
536 }
537
538 /* or if this is a blackhole/reject route */
539 if (ifp == NULL && ro.ro_rt->rt_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
540 RTFREE(ro.ro_rt);
541 return 0;
542 }
543
544 /* found valid route */
545 RTFREE(ro.ro_rt);
546 return 1;
547
548}
549
550static int
551is_icmp6_query(int icmp6_type)
552{
553 if ((icmp6_type <= ICMP6_MAXTYPE) &&
554 (icmp6_type == ICMP6_ECHO_REQUEST ||
555 icmp6_type == ICMP6_MEMBERSHIP_QUERY ||
556 icmp6_type == ICMP6_WRUREQUEST ||
557 icmp6_type == ICMP6_FQDN_QUERY ||
558 icmp6_type == ICMP6_NI_QUERY))
559 return (1);
560
561 return (0);
562}
563
564static void
565send_reject6(struct ip_fw_args *args, int code, u_int hlen, struct ip6_hdr *ip6)
566{
567 struct mbuf *m;
568
569 m = args->m;
570 if (code == ICMP6_UNREACH_RST && args->f_id.proto == IPPROTO_TCP) {
571 struct tcphdr *tcp;
572 tcp = (struct tcphdr *)((char *)ip6 + hlen);
573
574 if ((tcp->th_flags & TH_RST) == 0) {
575 struct mbuf *m0;
576 m0 = ipfw_send_pkt(args->m, &(args->f_id),
577 ntohl(tcp->th_seq), ntohl(tcp->th_ack),
578 tcp->th_flags | TH_RST);
579 if (m0 != NULL)
580 ip6_output(m0, NULL, NULL, 0, NULL, NULL,
581 NULL);
582 }
583 FREE_PKT(m);
584 } else if (code != ICMP6_UNREACH_RST) { /* Send an ICMPv6 unreach. */
585#if 0
586 /*
587 * Unlike above, the mbufs need to line up with the ip6 hdr,
588 * as the contents are read. We need to m_adj() the
589 * needed amount.
590 * The mbuf will however be thrown away so we can adjust it.
591 * Remember we did an m_pullup on it already so we
592 * can make some assumptions about contiguousness.
593 */
594 if (args->L3offset)
595 m_adj(m, args->L3offset);
596#endif
597 icmp6_error(m, ICMP6_DST_UNREACH, code, 0);
598 } else
599 FREE_PKT(m);
600
601 args->m = NULL;
602}
603
604#endif /* INET6 */
605
606
607/*
608 * sends a reject message, consuming the mbuf passed as an argument.
609 */
610static void
611send_reject(struct ip_fw_args *args, int code, int iplen, struct ip *ip)
612{
613
614#if 0
615 /* XXX When ip is not guaranteed to be at mtod() we will
616 * need to account for this */
617 * The mbuf will however be thrown away so we can adjust it.
618 * Remember we did an m_pullup on it already so we
619 * can make some assumptions about contiguousness.
620 */
621 if (args->L3offset)
622 m_adj(m, args->L3offset);
623#endif
624 if (code != ICMP_REJECT_RST) { /* Send an ICMP unreach */
625 /* We need the IP header in host order for icmp_error(). */
626 SET_HOST_IPLEN(ip);
627 icmp_error(args->m, ICMP_UNREACH, code, 0L, 0);
628 } else if (args->f_id.proto == IPPROTO_TCP) {
629 struct tcphdr *const tcp =
630 L3HDR(struct tcphdr, mtod(args->m, struct ip *));
631 if ( (tcp->th_flags & TH_RST) == 0) {
632 struct mbuf *m;
633 m = ipfw_send_pkt(args->m, &(args->f_id),
634 ntohl(tcp->th_seq), ntohl(tcp->th_ack),
635 tcp->th_flags | TH_RST);
636 if (m != NULL)
637 ip_output(m, NULL, NULL, 0, NULL, NULL);
638 }
639 FREE_PKT(args->m);
640 } else
641 FREE_PKT(args->m);
642 args->m = NULL;
643}
644
645/*
646 * Support for uid/gid/jail lookup. These tests are expensive
647 * (because we may need to look into the list of active sockets)
648 * so we cache the results. ugid_lookupp is 0 if we have not
649 * yet done a lookup, 1 if we succeeded, and -1 if we tried
650 * and failed. The function always returns the match value.
651 * We could actually spare the variable and use *uc, setting
652 * it to '(void *)check_uidgid if we have no info, NULL if
653 * we tried and failed, or any other value if successful.
654 */
655static int
656check_uidgid(ipfw_insn_u32 *insn, struct ip_fw_args *args, int *ugid_lookupp,
657 struct ucred **uc)
658{
659#ifndef __FreeBSD__
660 /* XXX */
661 return cred_check(insn, proto, oif,
662 dst_ip, dst_port, src_ip, src_port,
663 (struct bsd_ucred *)uc, ugid_lookupp, ((struct mbuf *)inp)->m_skb);
664#else /* FreeBSD */
665 struct in_addr src_ip, dst_ip;
666 struct inpcbinfo *pi;
667 struct ipfw_flow_id *id;
668 struct inpcb *pcb, *inp;
669 struct ifnet *oif;
670 int lookupflags;
671 int match;
672
673 id = &args->f_id;
674 inp = args->inp;
675 oif = args->oif;
676
677 /*
678 * Check to see if the UDP or TCP stack supplied us with
679 * the PCB. If so, rather then holding a lock and looking
680 * up the PCB, we can use the one that was supplied.
681 */
682 if (inp && *ugid_lookupp == 0) {
683 INP_LOCK_ASSERT(inp);
684 if (inp->inp_socket != NULL) {
685 *uc = crhold(inp->inp_cred);
686 *ugid_lookupp = 1;
687 } else
688 *ugid_lookupp = -1;
689 }
690 /*
691 * If we have already been here and the packet has no
692 * PCB entry associated with it, then we can safely
693 * assume that this is a no match.
694 */
695 if (*ugid_lookupp == -1)
696 return (0);
697 if (id->proto == IPPROTO_TCP) {
698 lookupflags = 0;
699 pi = &V_tcbinfo;
700 } else if (id->proto == IPPROTO_UDP) {
701 lookupflags = INPLOOKUP_WILDCARD;
702 pi = &V_udbinfo;
703 } else
704 return 0;
705 lookupflags |= INPLOOKUP_RLOCKPCB;
706 match = 0;
707 if (*ugid_lookupp == 0) {
708 if (id->addr_type == 6) {
709#ifdef INET6
710 if (oif == NULL)
711 pcb = in6_pcblookup_mbuf(pi,
712 &id->src_ip6, htons(id->src_port),
713 &id->dst_ip6, htons(id->dst_port),
714 lookupflags, oif, args->m);
715 else
716 pcb = in6_pcblookup_mbuf(pi,
717 &id->dst_ip6, htons(id->dst_port),
718 &id->src_ip6, htons(id->src_port),
719 lookupflags, oif, args->m);
720#else
721 *ugid_lookupp = -1;
722 return (0);
723#endif
724 } else {
725 src_ip.s_addr = htonl(id->src_ip);
726 dst_ip.s_addr = htonl(id->dst_ip);
727 if (oif == NULL)
728 pcb = in_pcblookup_mbuf(pi,
729 src_ip, htons(id->src_port),
730 dst_ip, htons(id->dst_port),
731 lookupflags, oif, args->m);
732 else
733 pcb = in_pcblookup_mbuf(pi,
734 dst_ip, htons(id->dst_port),
735 src_ip, htons(id->src_port),
736 lookupflags, oif, args->m);
737 }
738 if (pcb != NULL) {
739 INP_RLOCK_ASSERT(pcb);
740 *uc = crhold(pcb->inp_cred);
741 *ugid_lookupp = 1;
742 INP_RUNLOCK(pcb);
743 }
744 if (*ugid_lookupp == 0) {
745 /*
746 * We tried and failed, set the variable to -1
747 * so we will not try again on this packet.
748 */
749 *ugid_lookupp = -1;
750 return (0);
751 }
752 }
753 if (insn->o.opcode == O_UID)
754 match = ((*uc)->cr_uid == (uid_t)insn->d[0]);
755 else if (insn->o.opcode == O_GID)
756 match = groupmember((gid_t)insn->d[0], *uc);
757 else if (insn->o.opcode == O_JAIL)
758 match = ((*uc)->cr_prison->pr_id == (int)insn->d[0]);
759 return (match);
760#endif /* __FreeBSD__ */
761}
762
763/*
764 * Helper function to set args with info on the rule after the matching
765 * one. slot is precise, whereas we guess rule_id as they are
766 * assigned sequentially.
767 */
768static inline void
769set_match(struct ip_fw_args *args, int slot,
770 struct ip_fw_chain *chain)
771{
772 args->rule.chain_id = chain->id;
773 args->rule.slot = slot + 1; /* we use 0 as a marker */
774 args->rule.rule_id = 1 + chain->map[slot]->id;
775 args->rule.rulenum = chain->map[slot]->rulenum;
776}
777
778/*
779 * The main check routine for the firewall.
780 *
781 * All arguments are in args so we can modify them and return them
782 * back to the caller.
783 *
784 * Parameters:
785 *
786 * args->m (in/out) The packet; we set to NULL when/if we nuke it.
787 * Starts with the IP header.
788 * args->eh (in) Mac header if present, NULL for layer3 packet.
789 * args->L3offset Number of bytes bypassed if we came from L2.
790 * e.g. often sizeof(eh) ** NOTYET **
791 * args->oif Outgoing interface, NULL if packet is incoming.
792 * The incoming interface is in the mbuf. (in)
793 * args->divert_rule (in/out)
794 * Skip up to the first rule past this rule number;
795 * upon return, non-zero port number for divert or tee.
796 *
797 * args->rule Pointer to the last matching rule (in/out)
798 * args->next_hop Socket we are forwarding to (out).
799 * args->next_hop6 IPv6 next hop we are forwarding to (out).
800 * args->f_id Addresses grabbed from the packet (out)
801 * args->rule.info a cookie depending on rule action
802 *
803 * Return value:
804 *
805 * IP_FW_PASS the packet must be accepted
806 * IP_FW_DENY the packet must be dropped
807 * IP_FW_DIVERT divert packet, port in m_tag
808 * IP_FW_TEE tee packet, port in m_tag
809 * IP_FW_DUMMYNET to dummynet, pipe in args->cookie
810 * IP_FW_NETGRAPH into netgraph, cookie args->cookie
811 * args->rule contains the matching rule,
812 * args->rule.info has additional information.
813 *
814 */
815int
816ipfw_chk(struct ip_fw_args *args)
817{
818
819 /*
820 * Local variables holding state while processing a packet:
821 *
822 * IMPORTANT NOTE: to speed up the processing of rules, there
823 * are some assumption on the values of the variables, which
824 * are documented here. Should you change them, please check
825 * the implementation of the various instructions to make sure
826 * that they still work.
827 *
828 * args->eh The MAC header. It is non-null for a layer2
829 * packet, it is NULL for a layer-3 packet.
830 * **notyet**
831 * args->L3offset Offset in the packet to the L3 (IP or equiv.) header.
832 *
833 * m | args->m Pointer to the mbuf, as received from the caller.
834 * It may change if ipfw_chk() does an m_pullup, or if it
835 * consumes the packet because it calls send_reject().
836 * XXX This has to change, so that ipfw_chk() never modifies
837 * or consumes the buffer.
838 * ip is the beginning of the ip(4 or 6) header.
839 * Calculated by adding the L3offset to the start of data.
840 * (Until we start using L3offset, the packet is
841 * supposed to start with the ip header).
842 */
843 struct mbuf *m = args->m;
844 struct ip *ip = mtod(m, struct ip *);
845
846 /*
847 * For rules which contain uid/gid or jail constraints, cache
848 * a copy of the users credentials after the pcb lookup has been
849 * executed. This will speed up the processing of rules with
850 * these types of constraints, as well as decrease contention
851 * on pcb related locks.
852 */
853#ifndef __FreeBSD__
854 struct bsd_ucred ucred_cache;
855#else
856 struct ucred *ucred_cache = NULL;
857#endif
858 int ucred_lookup = 0;
859
860 /*
861 * oif | args->oif If NULL, ipfw_chk has been called on the
862 * inbound path (ether_input, ip_input).
863 * If non-NULL, ipfw_chk has been called on the outbound path
864 * (ether_output, ip_output).
865 */
866 struct ifnet *oif = args->oif;
867
868 int f_pos = 0; /* index of current rule in the array */
869 int retval = 0;
870
871 /*
872 * hlen The length of the IP header.
873 */
874 u_int hlen = 0; /* hlen >0 means we have an IP pkt */
875
876 /*
877 * offset The offset of a fragment. offset != 0 means that
878 * we have a fragment at this offset of an IPv4 packet.
879 * offset == 0 means that (if this is an IPv4 packet)
880 * this is the first or only fragment.
881 * For IPv6 offset|ip6f_mf == 0 means there is no Fragment Header
882 * or there is a single packet fragement (fragement header added
883 * without needed). We will treat a single packet fragment as if
884 * there was no fragment header (or log/block depending on the
885 * V_fw_permit_single_frag6 sysctl setting).
886 */
887 u_short offset = 0;
888 u_short ip6f_mf = 0;
889
890 /*
891 * Local copies of addresses. They are only valid if we have
892 * an IP packet.
893 *
894 * proto The protocol. Set to 0 for non-ip packets,
895 * or to the protocol read from the packet otherwise.
896 * proto != 0 means that we have an IPv4 packet.
897 *
898 * src_port, dst_port port numbers, in HOST format. Only
899 * valid for TCP and UDP packets.
900 *
901 * src_ip, dst_ip ip addresses, in NETWORK format.
902 * Only valid for IPv4 packets.
903 */
904 uint8_t proto;
905 uint16_t src_port = 0, dst_port = 0; /* NOTE: host format */
906 struct in_addr src_ip, dst_ip; /* NOTE: network format */
907 uint16_t iplen=0;
908 int pktlen;
909 uint16_t etype = 0; /* Host order stored ether type */
910
911 /*
912 * dyn_dir = MATCH_UNKNOWN when rules unchecked,
913 * MATCH_NONE when checked and not matched (q = NULL),
914 * MATCH_FORWARD or MATCH_REVERSE otherwise (q != NULL)
915 */
916 int dyn_dir = MATCH_UNKNOWN;
917 ipfw_dyn_rule *q = NULL;
918 struct ip_fw_chain *chain = &V_layer3_chain;
919
920 /*
921 * We store in ulp a pointer to the upper layer protocol header.
922 * In the ipv4 case this is easy to determine from the header,
923 * but for ipv6 we might have some additional headers in the middle.
924 * ulp is NULL if not found.
925 */
926 void *ulp = NULL; /* upper layer protocol pointer. */
927
928 /* XXX ipv6 variables */
929 int is_ipv6 = 0;
930 uint8_t icmp6_type = 0;
931 uint16_t ext_hd = 0; /* bits vector for extension header filtering */
932 /* end of ipv6 variables */
933
934 int is_ipv4 = 0;
935
936 int done = 0; /* flag to exit the outer loop */
937
938 if (m->m_flags & M_SKIP_FIREWALL || (! V_ipfw_vnet_ready))
939 return (IP_FW_PASS); /* accept */
940
941 dst_ip.s_addr = 0; /* make sure it is initialized */
942 src_ip.s_addr = 0; /* make sure it is initialized */
943 pktlen = m->m_pkthdr.len;
944 args->f_id.fib = M_GETFIB(m); /* note mbuf not altered) */
945 proto = args->f_id.proto = 0; /* mark f_id invalid */
946 /* XXX 0 is a valid proto: IP/IPv6 Hop-by-Hop Option */
947
948/*
949 * PULLUP_TO(len, p, T) makes sure that len + sizeof(T) is contiguous,
950 * then it sets p to point at the offset "len" in the mbuf. WARNING: the
951 * pointer might become stale after other pullups (but we never use it
952 * this way).
953 */
954#define PULLUP_TO(_len, p, T) PULLUP_LEN(_len, p, sizeof(T))
955#define PULLUP_LEN(_len, p, T) \
956do { \
957 int x = (_len) + T; \
958 if ((m)->m_len < x) { \
959 args->m = m = m_pullup(m, x); \
960 if (m == NULL) \
961 goto pullup_failed; \
962 } \
963 p = (mtod(m, char *) + (_len)); \
964} while (0)
965
966 /*
967 * if we have an ether header,
968 */
969 if (args->eh)
970 etype = ntohs(args->eh->ether_type);
971
972 /* Identify IP packets and fill up variables. */
973 if (pktlen >= sizeof(struct ip6_hdr) &&
974 (args->eh == NULL || etype == ETHERTYPE_IPV6) && ip->ip_v == 6) {
975 struct ip6_hdr *ip6 = (struct ip6_hdr *)ip;
976 is_ipv6 = 1;
977 args->f_id.addr_type = 6;
978 hlen = sizeof(struct ip6_hdr);
979 proto = ip6->ip6_nxt;
980
981 /* Search extension headers to find upper layer protocols */
982 while (ulp == NULL && offset == 0) {
983 switch (proto) {
984 case IPPROTO_ICMPV6:
985 PULLUP_TO(hlen, ulp, struct icmp6_hdr);
986 icmp6_type = ICMP6(ulp)->icmp6_type;
987 break;
988
989 case IPPROTO_TCP:
990 PULLUP_TO(hlen, ulp, struct tcphdr);
991 dst_port = TCP(ulp)->th_dport;
992 src_port = TCP(ulp)->th_sport;
993 /* save flags for dynamic rules */
994 args->f_id._flags = TCP(ulp)->th_flags;
995 break;
996
997 case IPPROTO_SCTP:
998 PULLUP_TO(hlen, ulp, struct sctphdr);
999 src_port = SCTP(ulp)->src_port;
1000 dst_port = SCTP(ulp)->dest_port;
1001 break;
1002
1003 case IPPROTO_UDP:
1004 PULLUP_TO(hlen, ulp, struct udphdr);
1005 dst_port = UDP(ulp)->uh_dport;
1006 src_port = UDP(ulp)->uh_sport;
1007 break;
1008
1009 case IPPROTO_HOPOPTS: /* RFC 2460 */
1010 PULLUP_TO(hlen, ulp, struct ip6_hbh);
1011 ext_hd |= EXT_HOPOPTS;
1012 hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3;
1013 proto = ((struct ip6_hbh *)ulp)->ip6h_nxt;
1014 ulp = NULL;
1015 break;
1016
1017 case IPPROTO_ROUTING: /* RFC 2460 */
1018 PULLUP_TO(hlen, ulp, struct ip6_rthdr);
1019 switch (((struct ip6_rthdr *)ulp)->ip6r_type) {
1020 case 0:
1021 ext_hd |= EXT_RTHDR0;
1022 break;
1023 case 2:
1024 ext_hd |= EXT_RTHDR2;
1025 break;
1026 default:
1027 if (V_fw_verbose)
1028 printf("IPFW2: IPV6 - Unknown "
1029 "Routing Header type(%d)\n",
1030 ((struct ip6_rthdr *)
1031 ulp)->ip6r_type);
1032 if (V_fw_deny_unknown_exthdrs)
1033 return (IP_FW_DENY);
1034 break;
1035 }
1036 ext_hd |= EXT_ROUTING;
1037 hlen += (((struct ip6_rthdr *)ulp)->ip6r_len + 1) << 3;
1038 proto = ((struct ip6_rthdr *)ulp)->ip6r_nxt;
1039 ulp = NULL;
1040 break;
1041
1042 case IPPROTO_FRAGMENT: /* RFC 2460 */
1043 PULLUP_TO(hlen, ulp, struct ip6_frag);
1044 ext_hd |= EXT_FRAGMENT;
1045 hlen += sizeof (struct ip6_frag);
1046 proto = ((struct ip6_frag *)ulp)->ip6f_nxt;
1047 offset = ((struct ip6_frag *)ulp)->ip6f_offlg &
1048 IP6F_OFF_MASK;
1049 ip6f_mf = ((struct ip6_frag *)ulp)->ip6f_offlg &
1050 IP6F_MORE_FRAG;
1051 if (V_fw_permit_single_frag6 == 0 &&
1052 offset == 0 && ip6f_mf == 0) {
1053 if (V_fw_verbose)
1054 printf("IPFW2: IPV6 - Invalid "
1055 "Fragment Header\n");
1056 if (V_fw_deny_unknown_exthdrs)
1057 return (IP_FW_DENY);
1058 break;
1059 }
1060 args->f_id.extra =
1061 ntohl(((struct ip6_frag *)ulp)->ip6f_ident);
1062 ulp = NULL;
1063 break;
1064
1065 case IPPROTO_DSTOPTS: /* RFC 2460 */
1066 PULLUP_TO(hlen, ulp, struct ip6_hbh);
1067 ext_hd |= EXT_DSTOPTS;
1068 hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3;
1069 proto = ((struct ip6_hbh *)ulp)->ip6h_nxt;
1070 ulp = NULL;
1071 break;
1072
1073 case IPPROTO_AH: /* RFC 2402 */
1074 PULLUP_TO(hlen, ulp, struct ip6_ext);
1075 ext_hd |= EXT_AH;
1076 hlen += (((struct ip6_ext *)ulp)->ip6e_len + 2) << 2;
1077 proto = ((struct ip6_ext *)ulp)->ip6e_nxt;
1078 ulp = NULL;
1079 break;
1080
1081 case IPPROTO_ESP: /* RFC 2406 */
1082 PULLUP_TO(hlen, ulp, uint32_t); /* SPI, Seq# */
1083 /* Anything past Seq# is variable length and
1084 * data past this ext. header is encrypted. */
1085 ext_hd |= EXT_ESP;
1086 break;
1087
1088 case IPPROTO_NONE: /* RFC 2460 */
1089 /*
1090 * Packet ends here, and IPv6 header has
1091 * already been pulled up. If ip6e_len!=0
1092 * then octets must be ignored.
1093 */
1094 ulp = ip; /* non-NULL to get out of loop. */
1095 break;
1096
1097 case IPPROTO_OSPFIGP:
1098 /* XXX OSPF header check? */
1099 PULLUP_TO(hlen, ulp, struct ip6_ext);
1100 break;
1101
1102 case IPPROTO_PIM:
1103 /* XXX PIM header check? */
1104 PULLUP_TO(hlen, ulp, struct pim);
1105 break;
1106
1107 case IPPROTO_CARP:
1108 PULLUP_TO(hlen, ulp, struct carp_header);
1109 if (((struct carp_header *)ulp)->carp_version !=
1110 CARP_VERSION)
1111 return (IP_FW_DENY);
1112 if (((struct carp_header *)ulp)->carp_type !=
1113 CARP_ADVERTISEMENT)
1114 return (IP_FW_DENY);
1115 break;
1116
1117 case IPPROTO_IPV6: /* RFC 2893 */
1118 PULLUP_TO(hlen, ulp, struct ip6_hdr);
1119 break;
1120
1121 case IPPROTO_IPV4: /* RFC 2893 */
1122 PULLUP_TO(hlen, ulp, struct ip);
1123 break;
1124
1125 default:
1126 if (V_fw_verbose)
1127 printf("IPFW2: IPV6 - Unknown "
1128 "Extension Header(%d), ext_hd=%x\n",
1129 proto, ext_hd);
1130 if (V_fw_deny_unknown_exthdrs)
1131 return (IP_FW_DENY);
1132 PULLUP_TO(hlen, ulp, struct ip6_ext);
1133 break;
1134 } /*switch */
1135 }
1136 ip = mtod(m, struct ip *);
1137 ip6 = (struct ip6_hdr *)ip;
1138 args->f_id.src_ip6 = ip6->ip6_src;
1139 args->f_id.dst_ip6 = ip6->ip6_dst;
1140 args->f_id.src_ip = 0;
1141 args->f_id.dst_ip = 0;
1142 args->f_id.flow_id6 = ntohl(ip6->ip6_flow);
1143 } else if (pktlen >= sizeof(struct ip) &&
1144 (args->eh == NULL || etype == ETHERTYPE_IP) && ip->ip_v == 4) {
1145 is_ipv4 = 1;
1146 hlen = ip->ip_hl << 2;
1147 args->f_id.addr_type = 4;
1148
1149 /*
1150 * Collect parameters into local variables for faster matching.
1151 */
1152 proto = ip->ip_p;
1153 src_ip = ip->ip_src;
1154 dst_ip = ip->ip_dst;
1155 offset = ntohs(ip->ip_off) & IP_OFFMASK;
1156 iplen = ntohs(ip->ip_len);
1157 pktlen = iplen < pktlen ? iplen : pktlen;
1158
1159 if (offset == 0) {
1160 switch (proto) {
1161 case IPPROTO_TCP:
1162 PULLUP_TO(hlen, ulp, struct tcphdr);
1163 dst_port = TCP(ulp)->th_dport;
1164 src_port = TCP(ulp)->th_sport;
1165 /* save flags for dynamic rules */
1166 args->f_id._flags = TCP(ulp)->th_flags;
1167 break;
1168
1169 case IPPROTO_SCTP:
1170 PULLUP_TO(hlen, ulp, struct sctphdr);
1171 src_port = SCTP(ulp)->src_port;
1172 dst_port = SCTP(ulp)->dest_port;
1173 break;
1174
1175 case IPPROTO_UDP:
1176 PULLUP_TO(hlen, ulp, struct udphdr);
1177 dst_port = UDP(ulp)->uh_dport;
1178 src_port = UDP(ulp)->uh_sport;
1179 break;
1180
1181 case IPPROTO_ICMP:
1182 PULLUP_TO(hlen, ulp, struct icmphdr);
1183 //args->f_id.flags = ICMP(ulp)->icmp_type;
1184 break;
1185
1186 default:
1187 break;
1188 }
1189 }
1190
1191 ip = mtod(m, struct ip *);
1192 args->f_id.src_ip = ntohl(src_ip.s_addr);
1193 args->f_id.dst_ip = ntohl(dst_ip.s_addr);
1194 }
1195#undef PULLUP_TO
1196 if (proto) { /* we may have port numbers, store them */
1197 args->f_id.proto = proto;
1198 args->f_id.src_port = src_port = ntohs(src_port);
1199 args->f_id.dst_port = dst_port = ntohs(dst_port);
1200 }
1201
1202 IPFW_RLOCK(chain);
1203 if (! V_ipfw_vnet_ready) { /* shutting down, leave NOW. */
1204 IPFW_RUNLOCK(chain);
1205 return (IP_FW_PASS); /* accept */
1206 }
1207 if (args->rule.slot) {
1208 /*
1209 * Packet has already been tagged as a result of a previous
1210 * match on rule args->rule aka args->rule_id (PIPE, QUEUE,
1211 * REASS, NETGRAPH, DIVERT/TEE...)
1212 * Validate the slot and continue from the next one
1213 * if still present, otherwise do a lookup.
1214 */
1215 f_pos = (args->rule.chain_id == chain->id) ?
1216 args->rule.slot :
1217 ipfw_find_rule(chain, args->rule.rulenum,
1218 args->rule.rule_id);
1219 } else {
1220 f_pos = 0;
1221 }
1222
1223 /*
1224 * Now scan the rules, and parse microinstructions for each rule.
1225 * We have two nested loops and an inner switch. Sometimes we
1226 * need to break out of one or both loops, or re-enter one of
1227 * the loops with updated variables. Loop variables are:
1228 *
1229 * f_pos (outer loop) points to the current rule.
1230 * On output it points to the matching rule.
1231 * done (outer loop) is used as a flag to break the loop.
1232 * l (inner loop) residual length of current rule.
1233 * cmd points to the current microinstruction.
1234 *
1235 * We break the inner loop by setting l=0 and possibly
1236 * cmdlen=0 if we don't want to advance cmd.
1237 * We break the outer loop by setting done=1
1238 * We can restart the inner loop by setting l>0 and f_pos, f, cmd
1239 * as needed.
1240 */
1241 for (; f_pos < chain->n_rules; f_pos++) {
1242 ipfw_insn *cmd;
1243 uint32_t tablearg = 0;
1244 int l, cmdlen, skip_or; /* skip rest of OR block */
1245 struct ip_fw *f;
1246
1247 f = chain->map[f_pos];
1248 if (V_set_disable & (1 << f->set) )
1249 continue;
1250
1251 skip_or = 0;
1252 for (l = f->cmd_len, cmd = f->cmd ; l > 0 ;
1253 l -= cmdlen, cmd += cmdlen) {
1254 int match;
1255
1256 /*
1257 * check_body is a jump target used when we find a
1258 * CHECK_STATE, and need to jump to the body of
1259 * the target rule.
1260 */
1261
1262/* check_body: */
1263 cmdlen = F_LEN(cmd);
1264 /*
1265 * An OR block (insn_1 || .. || insn_n) has the
1266 * F_OR bit set in all but the last instruction.
1267 * The first match will set "skip_or", and cause
1268 * the following instructions to be skipped until
1269 * past the one with the F_OR bit clear.
1270 */
1271 if (skip_or) { /* skip this instruction */
1272 if ((cmd->len & F_OR) == 0)
1273 skip_or = 0; /* next one is good */
1274 continue;
1275 }
1276 match = 0; /* set to 1 if we succeed */
1277
1278 switch (cmd->opcode) {
1279 /*
1280 * The first set of opcodes compares the packet's
1281 * fields with some pattern, setting 'match' if a
1282 * match is found. At the end of the loop there is
1283 * logic to deal with F_NOT and F_OR flags associated
1284 * with the opcode.
1285 */
1286 case O_NOP:
1287 match = 1;
1288 break;
1289
1290 case O_FORWARD_MAC:
1291 printf("ipfw: opcode %d unimplemented\n",
1292 cmd->opcode);
1293 break;
1294
1295 case O_GID:
1296 case O_UID:
1297 case O_JAIL:
1298 /*
1299 * We only check offset == 0 && proto != 0,
1300 * as this ensures that we have a
1301 * packet with the ports info.
1302 */
1303 if (offset != 0)
1304 break;
1305 if (proto == IPPROTO_TCP ||
1306 proto == IPPROTO_UDP)
1307 match = check_uidgid(
1308 (ipfw_insn_u32 *)cmd,
1309 args, &ucred_lookup,
1310#ifdef __FreeBSD__
1311 &ucred_cache);
1312#else
1313 (void *)&ucred_cache);
1314#endif
1315 break;
1316
1317 case O_RECV:
1318 match = iface_match(m->m_pkthdr.rcvif,
1319 (ipfw_insn_if *)cmd);
1320 break;
1321
1322 case O_XMIT:
1323 match = iface_match(oif, (ipfw_insn_if *)cmd);
1324 break;
1325
1326 case O_VIA:
1327 match = iface_match(oif ? oif :
1328 m->m_pkthdr.rcvif, (ipfw_insn_if *)cmd);
1329 break;
1330
1331 case O_MACADDR2:
1332 if (args->eh != NULL) { /* have MAC header */
1333 u_int32_t *want = (u_int32_t *)
1334 ((ipfw_insn_mac *)cmd)->addr;
1335 u_int32_t *mask = (u_int32_t *)
1336 ((ipfw_insn_mac *)cmd)->mask;
1337 u_int32_t *hdr = (u_int32_t *)args->eh;
1338
1339 match =
1340 ( want[0] == (hdr[0] & mask[0]) &&
1341 want[1] == (hdr[1] & mask[1]) &&
1342 want[2] == (hdr[2] & mask[2]) );
1343 }
1344 break;
1345
1346 case O_MAC_TYPE:
1347 if (args->eh != NULL) {
1348 u_int16_t *p =
1349 ((ipfw_insn_u16 *)cmd)->ports;
1350 int i;
1351
1352 for (i = cmdlen - 1; !match && i>0;
1353 i--, p += 2)
1354 match = (etype >= p[0] &&
1355 etype <= p[1]);
1356 }
1357 break;
1358
1359 case O_FRAG:
1360 match = (offset != 0);
1361 break;
1362
1363 case O_IN: /* "out" is "not in" */
1364 match = (oif == NULL);
1365 break;
1366
1367 case O_LAYER2:
1368 match = (args->eh != NULL);
1369 break;
1370
1371 case O_DIVERTED:
1372 {
1373 /* For diverted packets, args->rule.info
1374 * contains the divert port (in host format)
1375 * reason and direction.
1376 */
1377 uint32_t i = args->rule.info;
1378 match = (i&IPFW_IS_MASK) == IPFW_IS_DIVERT &&
1379 cmd->arg1 & ((i & IPFW_INFO_IN) ? 1 : 2);
1380 }
1381 break;
1382
1383 case O_PROTO:
1384 /*
1385 * We do not allow an arg of 0 so the
1386 * check of "proto" only suffices.
1387 */
1388 match = (proto == cmd->arg1);
1389 break;
1390
1391 case O_IP_SRC:
1392 match = is_ipv4 &&
1393 (((ipfw_insn_ip *)cmd)->addr.s_addr ==
1394 src_ip.s_addr);
1395 break;
1396
1397 case O_IP_SRC_LOOKUP:
1398 case O_IP_DST_LOOKUP:
1399 if (is_ipv4) {
1400 uint32_t key =
1401 (cmd->opcode == O_IP_DST_LOOKUP) ?
1402 dst_ip.s_addr : src_ip.s_addr;
1403 uint32_t v = 0;
1404
1405 if (cmdlen > F_INSN_SIZE(ipfw_insn_u32)) {
1406 /* generic lookup. The key must be
1407 * in 32bit big-endian format.
1408 */
1409 v = ((ipfw_insn_u32 *)cmd)->d[1];
1410 if (v == 0)
1411 key = dst_ip.s_addr;
1412 else if (v == 1)
1413 key = src_ip.s_addr;
1414 else if (v == 6) /* dscp */
1415 key = (ip->ip_tos >> 2) & 0x3f;
1416 else if (offset != 0)
1417 break;
1418 else if (proto != IPPROTO_TCP &&
1419 proto != IPPROTO_UDP)
1420 break;
1421 else if (v == 2)
1422 key = htonl(dst_port);
1423 else if (v == 3)
1424 key = htonl(src_port);
1425 else if (v == 4 || v == 5) {
1426 check_uidgid(
1427 (ipfw_insn_u32 *)cmd,
1428 args, &ucred_lookup,
1429#ifdef __FreeBSD__
1430 &ucred_cache);
1431 if (v == 4 /* O_UID */)
1432 key = ucred_cache->cr_uid;
1433 else if (v == 5 /* O_JAIL */)
1434 key = ucred_cache->cr_prison->pr_id;
1435#else /* !__FreeBSD__ */
1436 (void *)&ucred_cache);
1437 if (v ==4 /* O_UID */)
1438 key = ucred_cache.uid;
1439 else if (v == 5 /* O_JAIL */)
1440 key = ucred_cache.xid;
1441#endif /* !__FreeBSD__ */
1442 key = htonl(key);
1443 } else
1444 break;
1445 }
1446 match = ipfw_lookup_table(chain,
1447 cmd->arg1, key, &v);
1448 if (!match)
1449 break;
1450 if (cmdlen == F_INSN_SIZE(ipfw_insn_u32))
1451 match =
1452 ((ipfw_insn_u32 *)cmd)->d[0] == v;
1453 else
1454 tablearg = v;
1455 }
1456 break;
1457
1458 case O_IP_SRC_MASK:
1459 case O_IP_DST_MASK:
1460 if (is_ipv4) {
1461 uint32_t a =
1462 (cmd->opcode == O_IP_DST_MASK) ?
1463 dst_ip.s_addr : src_ip.s_addr;
1464 uint32_t *p = ((ipfw_insn_u32 *)cmd)->d;
1465 int i = cmdlen-1;
1466
1467 for (; !match && i>0; i-= 2, p+= 2)
1468 match = (p[0] == (a & p[1]));
1469 }
1470 break;
1471
1472 case O_IP_SRC_ME:
1473 if (is_ipv4) {
1474 struct ifnet *tif;
1475
1476 INADDR_TO_IFP(src_ip, tif);
1477 match = (tif != NULL);
1478 break;
1479 }
1480#ifdef INET6
1481 /* FALLTHROUGH */
1482 case O_IP6_SRC_ME:
1483 match= is_ipv6 && search_ip6_addr_net(&args->f_id.src_ip6);
1484#endif
1485 break;
1486
1487 case O_IP_DST_SET:
1488 case O_IP_SRC_SET:
1489 if (is_ipv4) {
1490 u_int32_t *d = (u_int32_t *)(cmd+1);
1491 u_int32_t addr =
1492 cmd->opcode == O_IP_DST_SET ?
1493 args->f_id.dst_ip :
1494 args->f_id.src_ip;
1495
1496 if (addr < d[0])
1497 break;
1498 addr -= d[0]; /* subtract base */
1499 match = (addr < cmd->arg1) &&
1500 ( d[ 1 + (addr>>5)] &
1501 (1<<(addr & 0x1f)) );
1502 }
1503 break;
1504
1505 case O_IP_DST:
1506 match = is_ipv4 &&
1507 (((ipfw_insn_ip *)cmd)->addr.s_addr ==
1508 dst_ip.s_addr);
1509 break;
1510
1511 case O_IP_DST_ME:
1512 if (is_ipv4) {
1513 struct ifnet *tif;
1514
1515 INADDR_TO_IFP(dst_ip, tif);
1516 match = (tif != NULL);
1517 break;
1518 }
1519#ifdef INET6
1520 /* FALLTHROUGH */
1521 case O_IP6_DST_ME:
1522 match= is_ipv6 && search_ip6_addr_net(&args->f_id.dst_ip6);
1523#endif
1524 break;
1525
1526
1527 case O_IP_SRCPORT:
1528 case O_IP_DSTPORT:
1529 /*
1530 * offset == 0 && proto != 0 is enough
1531 * to guarantee that we have a
1532 * packet with port info.
1533 */
1534 if ((proto==IPPROTO_UDP || proto==IPPROTO_TCP)
1535 && offset == 0) {
1536 u_int16_t x =
1537 (cmd->opcode == O_IP_SRCPORT) ?
1538 src_port : dst_port ;
1539 u_int16_t *p =
1540 ((ipfw_insn_u16 *)cmd)->ports;
1541 int i;
1542
1543 for (i = cmdlen - 1; !match && i>0;
1544 i--, p += 2)
1545 match = (x>=p[0] && x<=p[1]);
1546 }
1547 break;
1548
1549 case O_ICMPTYPE:
1550 match = (offset == 0 && proto==IPPROTO_ICMP &&
1551 icmptype_match(ICMP(ulp), (ipfw_insn_u32 *)cmd) );
1552 break;
1553
1554#ifdef INET6
1555 case O_ICMP6TYPE:
1556 match = is_ipv6 && offset == 0 &&
1557 proto==IPPROTO_ICMPV6 &&
1558 icmp6type_match(
1559 ICMP6(ulp)->icmp6_type,
1560 (ipfw_insn_u32 *)cmd);
1561 break;
1562#endif /* INET6 */
1563
1564 case O_IPOPT:
1565 match = (is_ipv4 &&
1566 ipopts_match(ip, cmd) );
1567 break;
1568
1569 case O_IPVER:
1570 match = (is_ipv4 &&
1571 cmd->arg1 == ip->ip_v);
1572 break;
1573
1574 case O_IPID:
1575 case O_IPLEN:
1576 case O_IPTTL:
1577 if (is_ipv4) { /* only for IP packets */
1578 uint16_t x;
1579 uint16_t *p;
1580 int i;
1581
1582 if (cmd->opcode == O_IPLEN)
1583 x = iplen;
1584 else if (cmd->opcode == O_IPTTL)
1585 x = ip->ip_ttl;
1586 else /* must be IPID */
1587 x = ntohs(ip->ip_id);
1588 if (cmdlen == 1) {
1589 match = (cmd->arg1 == x);
1590 break;
1591 }
1592 /* otherwise we have ranges */
1593 p = ((ipfw_insn_u16 *)cmd)->ports;
1594 i = cmdlen - 1;
1595 for (; !match && i>0; i--, p += 2)
1596 match = (x >= p[0] && x <= p[1]);
1597 }
1598 break;
1599
1600 case O_IPPRECEDENCE:
1601 match = (is_ipv4 &&
1602 (cmd->arg1 == (ip->ip_tos & 0xe0)) );
1603 break;
1604
1605 case O_IPTOS:
1606 match = (is_ipv4 &&
1607 flags_match(cmd, ip->ip_tos));
1608 break;
1609
1610 case O_TCPDATALEN:
1611 if (proto == IPPROTO_TCP && offset == 0) {
1612 struct tcphdr *tcp;
1613 uint16_t x;
1614 uint16_t *p;
1615 int i;
1616
1617 tcp = TCP(ulp);
1618 x = iplen -
1619 ((ip->ip_hl + tcp->th_off) << 2);
1620 if (cmdlen == 1) {
1621 match = (cmd->arg1 == x);
1622 break;
1623 }
1624 /* otherwise we have ranges */
1625 p = ((ipfw_insn_u16 *)cmd)->ports;
1626 i = cmdlen - 1;
1627 for (; !match && i>0; i--, p += 2)
1628 match = (x >= p[0] && x <= p[1]);
1629 }
1630 break;
1631
1632 case O_TCPFLAGS:
1633 match = (proto == IPPROTO_TCP && offset == 0 &&
1634 flags_match(cmd, TCP(ulp)->th_flags));
1635 break;
1636
1637 case O_TCPOPTS:
1638 PULLUP_LEN(hlen, ulp, (TCP(ulp)->th_off << 2));
1639 match = (proto == IPPROTO_TCP && offset == 0 &&
1640 tcpopts_match(TCP(ulp), cmd));
1641 break;
1642
1643 case O_TCPSEQ:
1644 match = (proto == IPPROTO_TCP && offset == 0 &&
1645 ((ipfw_insn_u32 *)cmd)->d[0] ==
1646 TCP(ulp)->th_seq);
1647 break;
1648
1649 case O_TCPACK:
1650 match = (proto == IPPROTO_TCP && offset == 0 &&
1651 ((ipfw_insn_u32 *)cmd)->d[0] ==
1652 TCP(ulp)->th_ack);
1653 break;
1654
1655 case O_TCPWIN:
1656 match = (proto == IPPROTO_TCP && offset == 0 &&
1657 cmd->arg1 == TCP(ulp)->th_win);
1658 break;
1659
1660 case O_ESTAB:
1661 /* reject packets which have SYN only */
1662 /* XXX should i also check for TH_ACK ? */
1663 match = (proto == IPPROTO_TCP && offset == 0 &&
1664 (TCP(ulp)->th_flags &
1665 (TH_RST | TH_ACK | TH_SYN)) != TH_SYN);
1666 break;
1667
1668 case O_ALTQ: {
1669 struct pf_mtag *at;
1670 ipfw_insn_altq *altq = (ipfw_insn_altq *)cmd;
1671
1672 match = 1;
1673 at = pf_find_mtag(m);
1674 if (at != NULL && at->qid != 0)
1675 break;
1676 at = pf_get_mtag(m);
1677 if (at == NULL) {
1678 /*
1679 * Let the packet fall back to the
1680 * default ALTQ.
1681 */
1682 break;
1683 }
1684 at->qid = altq->qid;
1685 at->hdr = ip;
1686 break;
1687 }
1688
1689 case O_LOG:
1690 ipfw_log(f, hlen, args, m,
1691 oif, offset | ip6f_mf, tablearg, ip);
1692 match = 1;
1693 break;
1694
1695 case O_PROB:
1696 match = (random()<((ipfw_insn_u32 *)cmd)->d[0]);
1697 break;
1698
1699 case O_VERREVPATH:
1700 /* Outgoing packets automatically pass/match */
1701 match = ((oif != NULL) ||
1702 (m->m_pkthdr.rcvif == NULL) ||
1703 (
1704#ifdef INET6
1705 is_ipv6 ?
1706 verify_path6(&(args->f_id.src_ip6),
1707 m->m_pkthdr.rcvif) :
1708#endif
1709 verify_path(src_ip, m->m_pkthdr.rcvif,
1710 args->f_id.fib)));
1711 break;
1712
1713 case O_VERSRCREACH:
1714 /* Outgoing packets automatically pass/match */
1715 match = (hlen > 0 && ((oif != NULL) ||
1716#ifdef INET6
1717 is_ipv6 ?
1718 verify_path6(&(args->f_id.src_ip6),
1719 NULL) :
1720#endif
1721 verify_path(src_ip, NULL, args->f_id.fib)));
1722 break;
1723
1724 case O_ANTISPOOF:
1725 /* Outgoing packets automatically pass/match */
1726 if (oif == NULL && hlen > 0 &&
1727 ( (is_ipv4 && in_localaddr(src_ip))
1728#ifdef INET6
1729 || (is_ipv6 &&
1730 in6_localaddr(&(args->f_id.src_ip6)))
1731#endif
1732 ))
1733 match =
1734#ifdef INET6
1735 is_ipv6 ? verify_path6(
1736 &(args->f_id.src_ip6),
1737 m->m_pkthdr.rcvif) :
1738#endif
1739 verify_path(src_ip,
1740 m->m_pkthdr.rcvif,
1741 args->f_id.fib);
1742 else
1743 match = 1;
1744 break;
1745
1746 case O_IPSEC:
1747#ifdef IPSEC
1748 match = (m_tag_find(m,
1749 PACKET_TAG_IPSEC_IN_DONE, NULL) != NULL);
1750#endif
1751 /* otherwise no match */
1752 break;
1753
1754#ifdef INET6
1755 case O_IP6_SRC:
1756 match = is_ipv6 &&
1757 IN6_ARE_ADDR_EQUAL(&args->f_id.src_ip6,
1758 &((ipfw_insn_ip6 *)cmd)->addr6);
1759 break;
1760
1761 case O_IP6_DST:
1762 match = is_ipv6 &&
1763 IN6_ARE_ADDR_EQUAL(&args->f_id.dst_ip6,
1764 &((ipfw_insn_ip6 *)cmd)->addr6);
1765 break;
1766 case O_IP6_SRC_MASK:
1767 case O_IP6_DST_MASK:
1768 if (is_ipv6) {
1769 int i = cmdlen - 1;
1770 struct in6_addr p;
1771 struct in6_addr *d =
1772 &((ipfw_insn_ip6 *)cmd)->addr6;
1773
1774 for (; !match && i > 0; d += 2,
1775 i -= F_INSN_SIZE(struct in6_addr)
1776 * 2) {
1777 p = (cmd->opcode ==
1778 O_IP6_SRC_MASK) ?
1779 args->f_id.src_ip6:
1780 args->f_id.dst_ip6;
1781 APPLY_MASK(&p, &d[1]);
1782 match =
1783 IN6_ARE_ADDR_EQUAL(&d[0],
1784 &p);
1785 }
1786 }
1787 break;
1788
1789 case O_FLOW6ID:
1790 match = is_ipv6 &&
1791 flow6id_match(args->f_id.flow_id6,
1792 (ipfw_insn_u32 *) cmd);
1793 break;
1794
1795 case O_EXT_HDR:
1796 match = is_ipv6 &&
1797 (ext_hd & ((ipfw_insn *) cmd)->arg1);
1798 break;
1799
1800 case O_IP6:
1801 match = is_ipv6;
1802 break;
1803#endif
1804
1805 case O_IP4:
1806 match = is_ipv4;
1807 break;
1808
1809 case O_TAG: {
1810 struct m_tag *mtag;
1811 uint32_t tag = (cmd->arg1 == IP_FW_TABLEARG) ?
1812 tablearg : cmd->arg1;
1813
1814 /* Packet is already tagged with this tag? */
1815 mtag = m_tag_locate(m, MTAG_IPFW, tag, NULL);
1816
1817 /* We have `untag' action when F_NOT flag is
1818 * present. And we must remove this mtag from
1819 * mbuf and reset `match' to zero (`match' will
1820 * be inversed later).
1821 * Otherwise we should allocate new mtag and
1822 * push it into mbuf.
1823 */
1824 if (cmd->len & F_NOT) { /* `untag' action */
1825 if (mtag != NULL)
1826 m_tag_delete(m, mtag);
1827 match = 0;
1828 } else {
1829 if (mtag == NULL) {
1830 mtag = m_tag_alloc( MTAG_IPFW,
1831 tag, 0, M_NOWAIT);
1832 if (mtag != NULL)
1833 m_tag_prepend(m, mtag);
1834 }
1835 match = 1;
1836 }
1837 break;
1838 }
1839
1840 case O_FIB: /* try match the specified fib */
1841 if (args->f_id.fib == cmd->arg1)
1842 match = 1;
1843 break;
1844
1845 case O_SOCKARG: {
1846 struct inpcb *inp = args->inp;
1847 struct inpcbinfo *pi;
1848
1849 if (is_ipv6) /* XXX can we remove this ? */
1850 break;
1851
1852 if (proto == IPPROTO_TCP)
1853 pi = &V_tcbinfo;
1854 else if (proto == IPPROTO_UDP)
1855 pi = &V_udbinfo;
1856 else
1857 break;
1858
1859 /*
1860 * XXXRW: so_user_cookie should almost
1861 * certainly be inp_user_cookie?
1862 */
1863
1864 /* For incomming packet, lookup up the
1865 inpcb using the src/dest ip/port tuple */
1866 if (inp == NULL) {
1867 inp = in_pcblookup(pi,
1868 src_ip, htons(src_port),
1869 dst_ip, htons(dst_port),
1870 INPLOOKUP_RLOCKPCB, NULL);
1871 if (inp != NULL) {
1872 tablearg =
1873 inp->inp_socket->so_user_cookie;
1874 if (tablearg)
1875 match = 1;
1876 INP_RUNLOCK(inp);
1877 }
1878 } else {
1879 if (inp->inp_socket) {
1880 tablearg =
1881 inp->inp_socket->so_user_cookie;
1882 if (tablearg)
1883 match = 1;
1884 }
1885 }
1886 break;
1887 }
1888
1889 case O_TAGGED: {
1890 struct m_tag *mtag;
1891 uint32_t tag = (cmd->arg1 == IP_FW_TABLEARG) ?
1892 tablearg : cmd->arg1;
1893
1894 if (cmdlen == 1) {
1895 match = m_tag_locate(m, MTAG_IPFW,
1896 tag, NULL) != NULL;
1897 break;
1898 }
1899
1900 /* we have ranges */
1901 for (mtag = m_tag_first(m);
1902 mtag != NULL && !match;
1903 mtag = m_tag_next(m, mtag)) {
1904 uint16_t *p;
1905 int i;
1906
1907 if (mtag->m_tag_cookie != MTAG_IPFW)
1908 continue;
1909
1910 p = ((ipfw_insn_u16 *)cmd)->ports;
1911 i = cmdlen - 1;
1912 for(; !match && i > 0; i--, p += 2)
1913 match =
1914 mtag->m_tag_id >= p[0] &&
1915 mtag->m_tag_id <= p[1];
1916 }
1917 break;
1918 }
1919
1920 /*
1921 * The second set of opcodes represents 'actions',
1922 * i.e. the terminal part of a rule once the packet
1923 * matches all previous patterns.
1924 * Typically there is only one action for each rule,
1925 * and the opcode is stored at the end of the rule
1926 * (but there are exceptions -- see below).
1927 *
1928 * In general, here we set retval and terminate the
1929 * outer loop (would be a 'break 3' in some language,
1930 * but we need to set l=0, done=1)
1931 *
1932 * Exceptions:
1933 * O_COUNT and O_SKIPTO actions:
1934 * instead of terminating, we jump to the next rule
1935 * (setting l=0), or to the SKIPTO target (setting
1936 * f/f_len, cmd and l as needed), respectively.
1937 *
1938 * O_TAG, O_LOG and O_ALTQ action parameters:
1939 * perform some action and set match = 1;
1940 *
1941 * O_LIMIT and O_KEEP_STATE: these opcodes are
1942 * not real 'actions', and are stored right
1943 * before the 'action' part of the rule.
1944 * These opcodes try to install an entry in the
1945 * state tables; if successful, we continue with
1946 * the next opcode (match=1; break;), otherwise
1947 * the packet must be dropped (set retval,
1948 * break loops with l=0, done=1)
1949 *
1950 * O_PROBE_STATE and O_CHECK_STATE: these opcodes
1951 * cause a lookup of the state table, and a jump
1952 * to the 'action' part of the parent rule
1953 * if an entry is found, or
1954 * (CHECK_STATE only) a jump to the next rule if
1955 * the entry is not found.
1956 * The result of the lookup is cached so that
1957 * further instances of these opcodes become NOPs.
1958 * The jump to the next rule is done by setting
1959 * l=0, cmdlen=0.
1960 */
1961 case O_LIMIT:
1962 case O_KEEP_STATE:
1963 if (ipfw_install_state(f,
1964 (ipfw_insn_limit *)cmd, args, tablearg)) {
1965 /* error or limit violation */
1966 retval = IP_FW_DENY;
1967 l = 0; /* exit inner loop */
1968 done = 1; /* exit outer loop */
1969 }
1970 match = 1;
1971 break;
1972
1973 case O_PROBE_STATE:
1974 case O_CHECK_STATE:
1975 /*
1976 * dynamic rules are checked at the first
1977 * keep-state or check-state occurrence,
1978 * with the result being stored in dyn_dir.
1979 * The compiler introduces a PROBE_STATE
1980 * instruction for us when we have a
1981 * KEEP_STATE (because PROBE_STATE needs
1982 * to be run first).
1983 */
1984 if (dyn_dir == MATCH_UNKNOWN &&
1985 (q = ipfw_lookup_dyn_rule(&args->f_id,
1986 &dyn_dir, proto == IPPROTO_TCP ?
1987 TCP(ulp) : NULL))
1988 != NULL) {
1989 /*
1990 * Found dynamic entry, update stats
1991 * and jump to the 'action' part of
1992 * the parent rule by setting
1993 * f, cmd, l and clearing cmdlen.
1994 */
1995 q->pcnt++;
1996 q->bcnt += pktlen;
1997 /* XXX we would like to have f_pos
1998 * readily accessible in the dynamic
1999 * rule, instead of having to
2000 * lookup q->rule.
2001 */
2002 f = q->rule;
2003 f_pos = ipfw_find_rule(chain,
2004 f->rulenum, f->id);
2005 cmd = ACTION_PTR(f);
2006 l = f->cmd_len - f->act_ofs;
2007 ipfw_dyn_unlock();
2008 cmdlen = 0;
2009 match = 1;
2010 break;
2011 }
2012 /*
2013 * Dynamic entry not found. If CHECK_STATE,
2014 * skip to next rule, if PROBE_STATE just
2015 * ignore and continue with next opcode.
2016 */
2017 if (cmd->opcode == O_CHECK_STATE)
2018 l = 0; /* exit inner loop */
2019 match = 1;
2020 break;
2021
2022 case O_ACCEPT:
2023 retval = 0; /* accept */
2024 l = 0; /* exit inner loop */
2025 done = 1; /* exit outer loop */
2026 break;
2027
2028 case O_PIPE:
2029 case O_QUEUE:
2030 set_match(args, f_pos, chain);
2031 args->rule.info = (cmd->arg1 == IP_FW_TABLEARG) ?
2032 tablearg : cmd->arg1;
2033 if (cmd->opcode == O_PIPE)
2034 args->rule.info |= IPFW_IS_PIPE;
2035 if (V_fw_one_pass)
2036 args->rule.info |= IPFW_ONEPASS;
2037 retval = IP_FW_DUMMYNET;
2038 l = 0; /* exit inner loop */
2039 done = 1; /* exit outer loop */
2040 break;
2041
2042 case O_DIVERT:
2043 case O_TEE:
2044 if (args->eh) /* not on layer 2 */
2045 break;
2046 /* otherwise this is terminal */
2047 l = 0; /* exit inner loop */
2048 done = 1; /* exit outer loop */
2049 retval = (cmd->opcode == O_DIVERT) ?
2050 IP_FW_DIVERT : IP_FW_TEE;
2051 set_match(args, f_pos, chain);
2052 args->rule.info = (cmd->arg1 == IP_FW_TABLEARG) ?
2053 tablearg : cmd->arg1;
2054 break;
2055
2056 case O_COUNT:
2057 f->pcnt++; /* update stats */
2058 f->bcnt += pktlen;
2059 f->timestamp = time_uptime;
2060 l = 0; /* exit inner loop */
2061 break;
2062
2063 case O_SKIPTO:
2064 f->pcnt++; /* update stats */
2065 f->bcnt += pktlen;
2066 f->timestamp = time_uptime;
2067 /* If possible use cached f_pos (in f->next_rule),
2068 * whose version is written in f->next_rule
2069 * (horrible hacks to avoid changing the ABI).
2070 */
2071 if (cmd->arg1 != IP_FW_TABLEARG &&
2072 (uintptr_t)f->x_next == chain->id) {
2073 f_pos = (uintptr_t)f->next_rule;
2074 } else {
2075 int i = (cmd->arg1 == IP_FW_TABLEARG) ?
2076 tablearg : cmd->arg1;
2077 /* make sure we do not jump backward */
2078 if (i <= f->rulenum)
2079 i = f->rulenum + 1;
2080 f_pos = ipfw_find_rule(chain, i, 0);
2081 /* update the cache */
2082 if (cmd->arg1 != IP_FW_TABLEARG) {
2083 f->next_rule =
2084 (void *)(uintptr_t)f_pos;
2085 f->x_next =
2086 (void *)(uintptr_t)chain->id;
2087 }
2088 }
2089 /*
2090 * Skip disabled rules, and re-enter
2091 * the inner loop with the correct
2092 * f_pos, f, l and cmd.
2093 * Also clear cmdlen and skip_or
2094 */
2095 for (; f_pos < chain->n_rules - 1 &&
2096 (V_set_disable &
2097 (1 << chain->map[f_pos]->set));
2098 f_pos++)
2099 ;
2100 /* Re-enter the inner loop at the skipto rule. */
2101 f = chain->map[f_pos];
2102 l = f->cmd_len;
2103 cmd = f->cmd;
2104 match = 1;
2105 cmdlen = 0;
2106 skip_or = 0;
2107 continue;
2108 break; /* not reached */
2109
2110 case O_CALLRETURN: {
2111 /*
2112 * Implementation of `subroutine' call/return,
2113 * in the stack carried in an mbuf tag. This
2114 * is different from `skipto' in that any call
2115 * address is possible (`skipto' must prevent
2116 * backward jumps to avoid endless loops).
2117 * We have `return' action when F_NOT flag is
2118 * present. The `m_tag_id' field is used as
2119 * stack pointer.
2120 */
2121 struct m_tag *mtag;
2122 uint16_t jmpto, *stack;
2123
2124#define IS_CALL ((cmd->len & F_NOT) == 0)
2125#define IS_RETURN ((cmd->len & F_NOT) != 0)
2126 /*
2127 * Hand-rolled version of m_tag_locate() with
2128 * wildcard `type'.
2129 * If not already tagged, allocate new tag.
2130 */
2131 mtag = m_tag_first(m);
2132 while (mtag != NULL) {
2133 if (mtag->m_tag_cookie ==
2134 MTAG_IPFW_CALL)
2135 break;
2136 mtag = m_tag_next(m, mtag);
2137 }
2138 if (mtag == NULL && IS_CALL) {
2139 mtag = m_tag_alloc(MTAG_IPFW_CALL, 0,
2140 IPFW_CALLSTACK_SIZE *
2141 sizeof(uint16_t), M_NOWAIT);
2142 if (mtag != NULL)
2143 m_tag_prepend(m, mtag);
2144 }
2145
2146 /*
2147 * On error both `call' and `return' just
2148 * continue with next rule.
2149 */
2150 if (IS_RETURN && (mtag == NULL ||
2151 mtag->m_tag_id == 0)) {
2152 l = 0; /* exit inner loop */
2153 break;
2154 }
2155 if (IS_CALL && (mtag == NULL ||
2156 mtag->m_tag_id >= IPFW_CALLSTACK_SIZE)) {
2157 printf("ipfw: call stack error, "
2158 "go to next rule\n");
2159 l = 0; /* exit inner loop */
2160 break;
2161 }
2162
2163 f->pcnt++; /* update stats */
2164 f->bcnt += pktlen;
2165 f->timestamp = time_uptime;
2166 stack = (uint16_t *)(mtag + 1);
2167
2168 /*
2169 * The `call' action may use cached f_pos
2170 * (in f->next_rule), whose version is written
2171 * in f->next_rule.
2172 * The `return' action, however, doesn't have
2173 * fixed jump address in cmd->arg1 and can't use
2174 * cache.
2175 */
2176 if (IS_CALL) {
2177 stack[mtag->m_tag_id] = f->rulenum;
2178 mtag->m_tag_id++;
2179 if (cmd->arg1 != IP_FW_TABLEARG &&
2180 (uintptr_t)f->x_next == chain->id) {
2181 f_pos = (uintptr_t)f->next_rule;
2182 } else {
2183 jmpto = (cmd->arg1 ==
2184 IP_FW_TABLEARG) ? tablearg:
2185 cmd->arg1;
2186 f_pos = ipfw_find_rule(chain,
2187 jmpto, 0);
2188 /* update the cache */
2189 if (cmd->arg1 !=
2190 IP_FW_TABLEARG) {
2191 f->next_rule =
2192 (void *)(uintptr_t)
2193 f_pos;
2194 f->x_next =
2195 (void *)(uintptr_t)
2196 chain->id;
2197 }
2198 }
2199 } else { /* `return' action */
2200 mtag->m_tag_id--;
2201 jmpto = stack[mtag->m_tag_id] + 1;
2202 f_pos = ipfw_find_rule(chain, jmpto, 0);
2203 }
2204
2205 /*
2206 * Skip disabled rules, and re-enter
2207 * the inner loop with the correct
2208 * f_pos, f, l and cmd.
2209 * Also clear cmdlen and skip_or
2210 */
2211 for (; f_pos < chain->n_rules - 1 &&
2212 (V_set_disable &
2213 (1 << chain->map[f_pos]->set)); f_pos++)
2214 ;
2215 /* Re-enter the inner loop at the dest rule. */
2216 f = chain->map[f_pos];
2217 l = f->cmd_len;
2218 cmd = f->cmd;
2219 cmdlen = 0;
2220 skip_or = 0;
2221 continue;
2222 break; /* NOTREACHED */
2223 }
2224#undef IS_CALL
2225#undef IS_RETURN
2226
2227 case O_REJECT:
2228 /*
2229 * Drop the packet and send a reject notice
2230 * if the packet is not ICMP (or is an ICMP
2231 * query), and it is not multicast/broadcast.
2232 */
2233 if (hlen > 0 && is_ipv4 && offset == 0 &&
2234 (proto != IPPROTO_ICMP ||
2235 is_icmp_query(ICMP(ulp))) &&
2236 !(m->m_flags & (M_BCAST|M_MCAST)) &&
2237 !IN_MULTICAST(ntohl(dst_ip.s_addr))) {
2238 send_reject(args, cmd->arg1, iplen, ip);
2239 m = args->m;
2240 }
2241 /* FALLTHROUGH */
2242#ifdef INET6
2243 case O_UNREACH6:
2244 if (hlen > 0 && is_ipv6 &&
2245 ((offset & IP6F_OFF_MASK) == 0) &&
2246 (proto != IPPROTO_ICMPV6 ||
2247 (is_icmp6_query(icmp6_type) == 1)) &&
2248 !(m->m_flags & (M_BCAST|M_MCAST)) &&
2249 !IN6_IS_ADDR_MULTICAST(&args->f_id.dst_ip6)) {
2250 send_reject6(
2251 args, cmd->arg1, hlen,
2252 (struct ip6_hdr *)ip);
2253 m = args->m;
2254 }
2255 /* FALLTHROUGH */
2256#endif
2257 case O_DENY:
2258 retval = IP_FW_DENY;
2259 l = 0; /* exit inner loop */
2260 done = 1; /* exit outer loop */
2261 break;
2262
2263 case O_FORWARD_IP:
2264 if (args->eh) /* not valid on layer2 pkts */
2265 break;
2266 if (q == NULL || q->rule != f ||
2267 dyn_dir == MATCH_FORWARD) {
2268 struct sockaddr_in *sa;
2269 sa = &(((ipfw_insn_sa *)cmd)->sa);
2270 if (sa->sin_addr.s_addr == INADDR_ANY) {
2271 bcopy(sa, &args->hopstore,
2272 sizeof(*sa));
2273 args->hopstore.sin_addr.s_addr =
2274 htonl(tablearg);
2275 args->next_hop = &args->hopstore;
2276 } else {
2277 args->next_hop = sa;
2278 }
2279 }
2280 retval = IP_FW_PASS;
2281 l = 0; /* exit inner loop */
2282 done = 1; /* exit outer loop */
2283 break;
2284
2285#ifdef INET6
2286 case O_FORWARD_IP6:
2287 if (args->eh) /* not valid on layer2 pkts */
2288 break;
2289 if (q == NULL || q->rule != f ||
2290 dyn_dir == MATCH_FORWARD) {
2291 struct sockaddr_in6 *sin6;
2292
2293 sin6 = &(((ipfw_insn_sa6 *)cmd)->sa);
2294 args->next_hop6 = sin6;
2295 }
2296 retval = IP_FW_PASS;
2297 l = 0; /* exit inner loop */
2298 done = 1; /* exit outer loop */
2299 break;
2300#endif
2301
2302 case O_NETGRAPH:
2303 case O_NGTEE:
2304 set_match(args, f_pos, chain);
2305 args->rule.info = (cmd->arg1 == IP_FW_TABLEARG) ?
2306 tablearg : cmd->arg1;
2307 if (V_fw_one_pass)
2308 args->rule.info |= IPFW_ONEPASS;
2309 retval = (cmd->opcode == O_NETGRAPH) ?
2310 IP_FW_NETGRAPH : IP_FW_NGTEE;
2311 l = 0; /* exit inner loop */
2312 done = 1; /* exit outer loop */
2313 break;
2314
2315 case O_SETFIB: {
2316 uint32_t fib;
2317
2318 f->pcnt++; /* update stats */
2319 f->bcnt += pktlen;
2320 f->timestamp = time_uptime;
2321 fib = (cmd->arg1 == IP_FW_TABLEARG) ? tablearg:
2322 cmd->arg1;
2323 if (fib >= rt_numfibs)
2324 fib = 0;
2325 M_SETFIB(m, fib);
2326 args->f_id.fib = fib;
2327 l = 0; /* exit inner loop */
2328 break;
2329 }
2330
2331 case O_NAT:
2332 if (!IPFW_NAT_LOADED) {
2333 retval = IP_FW_DENY;
2334 } else {
2335 struct cfg_nat *t;
2336 int nat_id;
2337
2338 set_match(args, f_pos, chain);
2339 /* Check if this is 'global' nat rule */
2340 if (cmd->arg1 == 0) {
2341 retval = ipfw_nat_ptr(args, NULL, m);
2342 l = 0;
2343 done = 1;
2344 break;
2345 }
2346 t = ((ipfw_insn_nat *)cmd)->nat;
2347 if (t == NULL) {
2348 nat_id = (cmd->arg1 == IP_FW_TABLEARG) ?
2349 tablearg : cmd->arg1;
2350 t = (*lookup_nat_ptr)(&chain->nat, nat_id);
2351
2352 if (t == NULL) {
2353 retval = IP_FW_DENY;
2354 l = 0; /* exit inner loop */
2355 done = 1; /* exit outer loop */
2356 break;
2357 }
2358 if (cmd->arg1 != IP_FW_TABLEARG)
2359 ((ipfw_insn_nat *)cmd)->nat = t;
2360 }
2361 retval = ipfw_nat_ptr(args, t, m);
2362 }
2363 l = 0; /* exit inner loop */
2364 done = 1; /* exit outer loop */
2365 break;
2366
2367 case O_REASS: {
2368 int ip_off;
2369
2370 f->pcnt++;
2371 f->bcnt += pktlen;
2372 l = 0; /* in any case exit inner loop */
2373 ip_off = ntohs(ip->ip_off);
2374
2375 /* if not fragmented, go to next rule */
2376 if ((ip_off & (IP_MF | IP_OFFMASK)) == 0)
2377 break;
2378 /*
2379 * ip_reass() expects len & off in host
2380 * byte order.
2381 */
2382 SET_HOST_IPLEN(ip);
2383
2384 args->m = m = ip_reass(m);
2385
2386 /*
2387 * do IP header checksum fixup.
2388 */
2389 if (m == NULL) { /* fragment got swallowed */
2390 retval = IP_FW_DENY;
2391 } else { /* good, packet complete */
2392 int hlen;
2393
2394 ip = mtod(m, struct ip *);
2395 hlen = ip->ip_hl << 2;
2396 SET_NET_IPLEN(ip);
2397 ip->ip_sum = 0;
2398 if (hlen == sizeof(struct ip))
2399 ip->ip_sum = in_cksum_hdr(ip);
2400 else
2401 ip->ip_sum = in_cksum(m, hlen);
2402 retval = IP_FW_REASS;
2403 set_match(args, f_pos, chain);
2404 }
2405 done = 1; /* exit outer loop */
2406 break;
2407 }
2408
2409 default:
2410 panic("-- unknown opcode %d\n", cmd->opcode);
2411 } /* end of switch() on opcodes */
2412 /*
2413 * if we get here with l=0, then match is irrelevant.
2414 */
2415
2416 if (cmd->len & F_NOT)
2417 match = !match;
2418
2419 if (match) {
2420 if (cmd->len & F_OR)
2421 skip_or = 1;
2422 } else {
2423 if (!(cmd->len & F_OR)) /* not an OR block, */
2424 break; /* try next rule */
2425 }
2426
2427 } /* end of inner loop, scan opcodes */
2428#undef PULLUP_LEN
2429
2430 if (done)
2431 break;
2432
2433/* next_rule:; */ /* try next rule */
2434
2435 } /* end of outer for, scan rules */
2436
2437 if (done) {
2438 struct ip_fw *rule = chain->map[f_pos];
2439 /* Update statistics */
2440 rule->pcnt++;
2441 rule->bcnt += pktlen;
2442 rule->timestamp = time_uptime;
2443 } else {
2444 retval = IP_FW_DENY;
2445 printf("ipfw: ouch!, skip past end of rules, denying packet\n");
2446 }
2447 IPFW_RUNLOCK(chain);
2448#ifdef __FreeBSD__
2449 if (ucred_cache != NULL)
2450 crfree(ucred_cache);
2451#endif
2452 return (retval);
2453
2454pullup_failed:
2455 if (V_fw_verbose)
2456 printf("ipfw: pullup failed\n");
2457 return (IP_FW_DENY);
2458}
2459
2460/*
2461 * Module and VNET glue
2462 */
2463
2464/*
2465 * Stuff that must be initialised only on boot or module load
2466 */
2467static int
2468ipfw_init(void)
2469{
2470 int error = 0;
2471
2472 ipfw_dyn_attach();
2473 /*
2474 * Only print out this stuff the first time around,
2475 * when called from the sysinit code.
2476 */
2477 printf("ipfw2 "
2478#ifdef INET6
2479 "(+ipv6) "
2480#endif
2481 "initialized, divert %s, nat %s, "
2482 "rule-based forwarding "
2483#ifdef IPFIREWALL_FORWARD
2484 "enabled, "
2485#else
2486 "disabled, "
2487#endif
2488 "default to %s, logging ",
2489#ifdef IPDIVERT
2490 "enabled",
2491#else
2492 "loadable",
2493#endif
2494#ifdef IPFIREWALL_NAT
2495 "enabled",
2496#else
2497 "loadable",
2498#endif
2499 default_to_accept ? "accept" : "deny");
2500
2501 /*
2502 * Note: V_xxx variables can be accessed here but the vnet specific
2503 * initializer may not have been called yet for the VIMAGE case.
2504 * Tuneables will have been processed. We will print out values for
2505 * the default vnet.
2506 * XXX This should all be rationalized AFTER 8.0
2507 */
2508 if (V_fw_verbose == 0)
2509 printf("disabled\n");
2510 else if (V_verbose_limit == 0)
2511 printf("unlimited\n");
2512 else
2513 printf("limited to %d packets/entry by default\n",
2514 V_verbose_limit);
2515
2516 ipfw_log_bpf(1); /* init */
2517 return (error);
2518}
2519
2520/*
2521 * Called for the removal of the last instance only on module unload.
2522 */
2523static void
2524ipfw_destroy(void)
2525{
2526
2527 ipfw_log_bpf(0); /* uninit */
2528 ipfw_dyn_detach();
2529 printf("IP firewall unloaded\n");
2530}
2531
2532/*
2533 * Stuff that must be initialized for every instance
2534 * (including the first of course).
2535 */
2536static int
2537vnet_ipfw_init(const void *unused)
2538{
2539 int error;
2540 struct ip_fw *rule = NULL;
2541 struct ip_fw_chain *chain;
2542
2543 chain = &V_layer3_chain;
2544
2545 /* First set up some values that are compile time options */
2546 V_autoinc_step = 100; /* bounded to 1..1000 in add_rule() */
2547 V_fw_deny_unknown_exthdrs = 1;
2548#ifdef IPFIREWALL_VERBOSE
2549 V_fw_verbose = 1;
2550#endif
2551#ifdef IPFIREWALL_VERBOSE_LIMIT
2552 V_verbose_limit = IPFIREWALL_VERBOSE_LIMIT;
2553#endif
2554#ifdef IPFIREWALL_NAT
2555 LIST_INIT(&chain->nat);
2556#endif
2557
2558 /* insert the default rule and create the initial map */
2559 chain->n_rules = 1;
2560 chain->static_len = sizeof(struct ip_fw);
2561 chain->map = malloc(sizeof(struct ip_fw *), M_IPFW, M_NOWAIT | M_ZERO);
2562 if (chain->map)
2563 rule = malloc(chain->static_len, M_IPFW, M_NOWAIT | M_ZERO);
2564 if (rule == NULL) {
2565 if (chain->map)
2566 free(chain->map, M_IPFW);
2567 printf("ipfw2: ENOSPC initializing default rule "
2568 "(support disabled)\n");
2569 return (ENOSPC);
2570 }
2571 error = ipfw_init_tables(chain);
2572 if (error) {
2573 panic("init_tables"); /* XXX Marko fix this ! */
2574 }
2575
2576 /* fill and insert the default rule */
2577 rule->act_ofs = 0;
2578 rule->rulenum = IPFW_DEFAULT_RULE;
2579 rule->cmd_len = 1;
2580 rule->set = RESVD_SET;
2581 rule->cmd[0].len = 1;
2582 rule->cmd[0].opcode = default_to_accept ? O_ACCEPT : O_DENY;
2583 chain->rules = chain->default_rule = chain->map[0] = rule;
2584 chain->id = rule->id = 1;
2585
2586 IPFW_LOCK_INIT(chain);
2587 ipfw_dyn_init();
2588
2589 /* First set up some values that are compile time options */
2590 V_ipfw_vnet_ready = 1; /* Open for business */
2591
2592 /*
2593 * Hook the sockopt handler, and the layer2 (V_ip_fw_chk_ptr)
2594 * and pfil hooks for ipv4 and ipv6. Even if the latter two fail
2595 * we still keep the module alive because the sockopt and
2596 * layer2 paths are still useful.
2597 * ipfw[6]_hook return 0 on success, ENOENT on failure,
2598 * so we can ignore the exact return value and just set a flag.
2599 *
2600 * Note that V_fw[6]_enable are manipulated by a SYSCTL_PROC so
2601 * changes in the underlying (per-vnet) variables trigger
2602 * immediate hook()/unhook() calls.
2603 * In layer2 we have the same behaviour, except that V_ether_ipfw
2604 * is checked on each packet because there are no pfil hooks.
2605 */
2606 V_ip_fw_ctl_ptr = ipfw_ctl;
2607 V_ip_fw_chk_ptr = ipfw_chk;
2608 error = ipfw_attach_hooks(1);
2609 return (error);
2610}
2611
2612/*
2613 * Called for the removal of each instance.
2614 */
2615static int
2616vnet_ipfw_uninit(const void *unused)
2617{
2618 struct ip_fw *reap, *rule;
2619 struct ip_fw_chain *chain = &V_layer3_chain;
2620 int i;
2621
2622 V_ipfw_vnet_ready = 0; /* tell new callers to go away */
2623 /*
2624 * disconnect from ipv4, ipv6, layer2 and sockopt.
2625 * Then grab, release and grab again the WLOCK so we make
2626 * sure the update is propagated and nobody will be in.
2627 */
2628 (void)ipfw_attach_hooks(0 /* detach */);
2629 V_ip_fw_chk_ptr = NULL;
2630 V_ip_fw_ctl_ptr = NULL;
2631 IPFW_UH_WLOCK(chain);
2632 IPFW_UH_WUNLOCK(chain);
2633 IPFW_UH_WLOCK(chain);
2634
2635 IPFW_WLOCK(chain);
2636 IPFW_WUNLOCK(chain);
2637 IPFW_WLOCK(chain);
2638
2639 ipfw_dyn_uninit(0); /* run the callout_drain */
2640 ipfw_destroy_tables(chain);
2641 reap = NULL;
2642 for (i = 0; i < chain->n_rules; i++) {
2643 rule = chain->map[i];
2644 rule->x_next = reap;
2645 reap = rule;
2646 }
2647 if (chain->map)
2648 free(chain->map, M_IPFW);
2649 IPFW_WUNLOCK(chain);
2650 IPFW_UH_WUNLOCK(chain);
2651 if (reap != NULL)
2652 ipfw_reap_rules(reap);
2653 IPFW_LOCK_DESTROY(chain);
2654 ipfw_dyn_uninit(1); /* free the remaining parts */
2655 return 0;
2656}
2657
2658/*
2659 * Module event handler.
2660 * In general we have the choice of handling most of these events by the
2661 * event handler or by the (VNET_)SYS(UN)INIT handlers. I have chosen to
2662 * use the SYSINIT handlers as they are more capable of expressing the
2663 * flow of control during module and vnet operations, so this is just
2664 * a skeleton. Note there is no SYSINIT equivalent of the module
2665 * SHUTDOWN handler, but we don't have anything to do in that case anyhow.
2666 */
2667static int
2668ipfw_modevent(module_t mod, int type, void *unused)
2669{
2670 int err = 0;
2671
2672 switch (type) {
2673 case MOD_LOAD:
2674 /* Called once at module load or
2675 * system boot if compiled in. */
2676 break;
2677 case MOD_QUIESCE:
2678 /* Called before unload. May veto unloading. */
2679 break;
2680 case MOD_UNLOAD:
2681 /* Called during unload. */
2682 break;
2683 case MOD_SHUTDOWN:
2684 /* Called during system shutdown. */
2685 break;
2686 default:
2687 err = EOPNOTSUPP;
2688 break;
2689 }
2690 return err;
2691}
2692
2693static moduledata_t ipfwmod = {
2694 "ipfw",
2695 ipfw_modevent,
2696 0
2697};
2698
2699/* Define startup order. */
2700#define IPFW_SI_SUB_FIREWALL SI_SUB_PROTO_IFATTACHDOMAIN
2701#define IPFW_MODEVENT_ORDER (SI_ORDER_ANY - 255) /* On boot slot in here. */
2702#define IPFW_MODULE_ORDER (IPFW_MODEVENT_ORDER + 1) /* A little later. */
2703#define IPFW_VNET_ORDER (IPFW_MODEVENT_ORDER + 2) /* Later still. */
2704
2705DECLARE_MODULE(ipfw, ipfwmod, IPFW_SI_SUB_FIREWALL, IPFW_MODEVENT_ORDER);
2706MODULE_VERSION(ipfw, 2);
2707/* should declare some dependencies here */
2708
2709/*
2710 * Starting up. Done in order after ipfwmod() has been called.
2711 * VNET_SYSINIT is also called for each existing vnet and each new vnet.
2712 */
2713SYSINIT(ipfw_init, IPFW_SI_SUB_FIREWALL, IPFW_MODULE_ORDER,
2714 ipfw_init, NULL);
2715VNET_SYSINIT(vnet_ipfw_init, IPFW_SI_SUB_FIREWALL, IPFW_VNET_ORDER,
2716 vnet_ipfw_init, NULL);
2717
2718/*
2719 * Closing up shop. These are done in REVERSE ORDER, but still
2720 * after ipfwmod() has been called. Not called on reboot.
2721 * VNET_SYSUNINIT is also called for each exiting vnet as it exits.
2722 * or when the module is unloaded.
2723 */
2724SYSUNINIT(ipfw_destroy, IPFW_SI_SUB_FIREWALL, IPFW_MODULE_ORDER,
2725 ipfw_destroy, NULL);
2726VNET_SYSUNINIT(vnet_ipfw_uninit, IPFW_SI_SUB_FIREWALL, IPFW_VNET_ORDER,
2727 vnet_ipfw_uninit, NULL);
2728/* end of file */
39#include "opt_inet6.h"
40#include "opt_ipsec.h"
41
42#include <sys/param.h>
43#include <sys/systm.h>
44#include <sys/condvar.h>
45#include <sys/eventhandler.h>
46#include <sys/malloc.h>
47#include <sys/mbuf.h>
48#include <sys/kernel.h>
49#include <sys/lock.h>
50#include <sys/jail.h>
51#include <sys/module.h>
52#include <sys/priv.h>
53#include <sys/proc.h>
54#include <sys/rwlock.h>
55#include <sys/socket.h>
56#include <sys/socketvar.h>
57#include <sys/sysctl.h>
58#include <sys/syslog.h>
59#include <sys/ucred.h>
60#include <net/ethernet.h> /* for ETHERTYPE_IP */
61#include <net/if.h>
62#include <net/route.h>
63#include <net/pf_mtag.h>
64#include <net/vnet.h>
65
66#include <netinet/in.h>
67#include <netinet/in_var.h>
68#include <netinet/in_pcb.h>
69#include <netinet/ip.h>
70#include <netinet/ip_var.h>
71#include <netinet/ip_icmp.h>
72#include <netinet/ip_fw.h>
73#include <netinet/ipfw/ip_fw_private.h>
74#include <netinet/ip_carp.h>
75#include <netinet/pim.h>
76#include <netinet/tcp_var.h>
77#include <netinet/udp.h>
78#include <netinet/udp_var.h>
79#include <netinet/sctp.h>
80
81#include <netinet/ip6.h>
82#include <netinet/icmp6.h>
83#ifdef INET6
84#include <netinet6/in6_pcb.h>
85#include <netinet6/scope6_var.h>
86#include <netinet6/ip6_var.h>
87#endif
88
89#include <machine/in_cksum.h> /* XXX for in_cksum */
90
91#ifdef MAC
92#include <security/mac/mac_framework.h>
93#endif
94
95/*
96 * static variables followed by global ones.
97 * All ipfw global variables are here.
98 */
99
100/* ipfw_vnet_ready controls when we are open for business */
101static VNET_DEFINE(int, ipfw_vnet_ready) = 0;
102#define V_ipfw_vnet_ready VNET(ipfw_vnet_ready)
103
104static VNET_DEFINE(int, fw_deny_unknown_exthdrs);
105#define V_fw_deny_unknown_exthdrs VNET(fw_deny_unknown_exthdrs)
106
107static VNET_DEFINE(int, fw_permit_single_frag6) = 1;
108#define V_fw_permit_single_frag6 VNET(fw_permit_single_frag6)
109
110#ifdef IPFIREWALL_DEFAULT_TO_ACCEPT
111static int default_to_accept = 1;
112#else
113static int default_to_accept;
114#endif
115
116VNET_DEFINE(int, autoinc_step);
117VNET_DEFINE(int, fw_one_pass) = 1;
118
119/*
120 * Each rule belongs to one of 32 different sets (0..31).
121 * The variable set_disable contains one bit per set.
122 * If the bit is set, all rules in the corresponding set
123 * are disabled. Set RESVD_SET(31) is reserved for the default rule
124 * and rules that are not deleted by the flush command,
125 * and CANNOT be disabled.
126 * Rules in set RESVD_SET can only be deleted individually.
127 */
128VNET_DEFINE(u_int32_t, set_disable);
129#define V_set_disable VNET(set_disable)
130
131VNET_DEFINE(int, fw_verbose);
132/* counter for ipfw_log(NULL...) */
133VNET_DEFINE(u_int64_t, norule_counter);
134VNET_DEFINE(int, verbose_limit);
135
136/* layer3_chain contains the list of rules for layer 3 */
137VNET_DEFINE(struct ip_fw_chain, layer3_chain);
138
139ipfw_nat_t *ipfw_nat_ptr = NULL;
140struct cfg_nat *(*lookup_nat_ptr)(struct nat_list *, int);
141ipfw_nat_cfg_t *ipfw_nat_cfg_ptr;
142ipfw_nat_cfg_t *ipfw_nat_del_ptr;
143ipfw_nat_cfg_t *ipfw_nat_get_cfg_ptr;
144ipfw_nat_cfg_t *ipfw_nat_get_log_ptr;
145
146#ifdef SYSCTL_NODE
147uint32_t dummy_def = IPFW_DEFAULT_RULE;
148uint32_t dummy_tables_max = IPFW_TABLES_MAX;
149
150SYSBEGIN(f3)
151
152SYSCTL_NODE(_net_inet_ip, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall");
153SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, one_pass,
154 CTLFLAG_RW | CTLFLAG_SECURE3, &VNET_NAME(fw_one_pass), 0,
155 "Only do a single pass through ipfw when using dummynet(4)");
156SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, autoinc_step,
157 CTLFLAG_RW, &VNET_NAME(autoinc_step), 0,
158 "Rule number auto-increment step");
159SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, verbose,
160 CTLFLAG_RW | CTLFLAG_SECURE3, &VNET_NAME(fw_verbose), 0,
161 "Log matches to ipfw rules");
162SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, verbose_limit,
163 CTLFLAG_RW, &VNET_NAME(verbose_limit), 0,
164 "Set upper limit of matches of ipfw rules logged");
165SYSCTL_UINT(_net_inet_ip_fw, OID_AUTO, default_rule, CTLFLAG_RD,
166 &dummy_def, 0,
167 "The default/max possible rule number.");
168SYSCTL_UINT(_net_inet_ip_fw, OID_AUTO, tables_max, CTLFLAG_RD,
169 &dummy_tables_max, 0,
170 "The maximum number of tables.");
171SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, default_to_accept, CTLFLAG_RDTUN,
172 &default_to_accept, 0,
173 "Make the default rule accept all packets.");
174TUNABLE_INT("net.inet.ip.fw.default_to_accept", &default_to_accept);
175SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, static_count,
176 CTLFLAG_RD, &VNET_NAME(layer3_chain.n_rules), 0,
177 "Number of static rules");
178
179#ifdef INET6
180SYSCTL_DECL(_net_inet6_ip6);
181SYSCTL_NODE(_net_inet6_ip6, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall");
182SYSCTL_VNET_INT(_net_inet6_ip6_fw, OID_AUTO, deny_unknown_exthdrs,
183 CTLFLAG_RW | CTLFLAG_SECURE, &VNET_NAME(fw_deny_unknown_exthdrs), 0,
184 "Deny packets with unknown IPv6 Extension Headers");
185SYSCTL_VNET_INT(_net_inet6_ip6_fw, OID_AUTO, permit_single_frag6,
186 CTLFLAG_RW | CTLFLAG_SECURE, &VNET_NAME(fw_permit_single_frag6), 0,
187 "Permit single packet IPv6 fragments");
188#endif /* INET6 */
189
190SYSEND
191
192#endif /* SYSCTL_NODE */
193
194
195/*
196 * Some macros used in the various matching options.
197 * L3HDR maps an ipv4 pointer into a layer3 header pointer of type T
198 * Other macros just cast void * into the appropriate type
199 */
200#define L3HDR(T, ip) ((T *)((u_int32_t *)(ip) + (ip)->ip_hl))
201#define TCP(p) ((struct tcphdr *)(p))
202#define SCTP(p) ((struct sctphdr *)(p))
203#define UDP(p) ((struct udphdr *)(p))
204#define ICMP(p) ((struct icmphdr *)(p))
205#define ICMP6(p) ((struct icmp6_hdr *)(p))
206
207static __inline int
208icmptype_match(struct icmphdr *icmp, ipfw_insn_u32 *cmd)
209{
210 int type = icmp->icmp_type;
211
212 return (type <= ICMP_MAXTYPE && (cmd->d[0] & (1<<type)) );
213}
214
215#define TT ( (1 << ICMP_ECHO) | (1 << ICMP_ROUTERSOLICIT) | \
216 (1 << ICMP_TSTAMP) | (1 << ICMP_IREQ) | (1 << ICMP_MASKREQ) )
217
218static int
219is_icmp_query(struct icmphdr *icmp)
220{
221 int type = icmp->icmp_type;
222
223 return (type <= ICMP_MAXTYPE && (TT & (1<<type)) );
224}
225#undef TT
226
227/*
228 * The following checks use two arrays of 8 or 16 bits to store the
229 * bits that we want set or clear, respectively. They are in the
230 * low and high half of cmd->arg1 or cmd->d[0].
231 *
232 * We scan options and store the bits we find set. We succeed if
233 *
234 * (want_set & ~bits) == 0 && (want_clear & ~bits) == want_clear
235 *
236 * The code is sometimes optimized not to store additional variables.
237 */
238
239static int
240flags_match(ipfw_insn *cmd, u_int8_t bits)
241{
242 u_char want_clear;
243 bits = ~bits;
244
245 if ( ((cmd->arg1 & 0xff) & bits) != 0)
246 return 0; /* some bits we want set were clear */
247 want_clear = (cmd->arg1 >> 8) & 0xff;
248 if ( (want_clear & bits) != want_clear)
249 return 0; /* some bits we want clear were set */
250 return 1;
251}
252
253static int
254ipopts_match(struct ip *ip, ipfw_insn *cmd)
255{
256 int optlen, bits = 0;
257 u_char *cp = (u_char *)(ip + 1);
258 int x = (ip->ip_hl << 2) - sizeof (struct ip);
259
260 for (; x > 0; x -= optlen, cp += optlen) {
261 int opt = cp[IPOPT_OPTVAL];
262
263 if (opt == IPOPT_EOL)
264 break;
265 if (opt == IPOPT_NOP)
266 optlen = 1;
267 else {
268 optlen = cp[IPOPT_OLEN];
269 if (optlen <= 0 || optlen > x)
270 return 0; /* invalid or truncated */
271 }
272 switch (opt) {
273
274 default:
275 break;
276
277 case IPOPT_LSRR:
278 bits |= IP_FW_IPOPT_LSRR;
279 break;
280
281 case IPOPT_SSRR:
282 bits |= IP_FW_IPOPT_SSRR;
283 break;
284
285 case IPOPT_RR:
286 bits |= IP_FW_IPOPT_RR;
287 break;
288
289 case IPOPT_TS:
290 bits |= IP_FW_IPOPT_TS;
291 break;
292 }
293 }
294 return (flags_match(cmd, bits));
295}
296
297static int
298tcpopts_match(struct tcphdr *tcp, ipfw_insn *cmd)
299{
300 int optlen, bits = 0;
301 u_char *cp = (u_char *)(tcp + 1);
302 int x = (tcp->th_off << 2) - sizeof(struct tcphdr);
303
304 for (; x > 0; x -= optlen, cp += optlen) {
305 int opt = cp[0];
306 if (opt == TCPOPT_EOL)
307 break;
308 if (opt == TCPOPT_NOP)
309 optlen = 1;
310 else {
311 optlen = cp[1];
312 if (optlen <= 0)
313 break;
314 }
315
316 switch (opt) {
317
318 default:
319 break;
320
321 case TCPOPT_MAXSEG:
322 bits |= IP_FW_TCPOPT_MSS;
323 break;
324
325 case TCPOPT_WINDOW:
326 bits |= IP_FW_TCPOPT_WINDOW;
327 break;
328
329 case TCPOPT_SACK_PERMITTED:
330 case TCPOPT_SACK:
331 bits |= IP_FW_TCPOPT_SACK;
332 break;
333
334 case TCPOPT_TIMESTAMP:
335 bits |= IP_FW_TCPOPT_TS;
336 break;
337
338 }
339 }
340 return (flags_match(cmd, bits));
341}
342
343static int
344iface_match(struct ifnet *ifp, ipfw_insn_if *cmd)
345{
346 if (ifp == NULL) /* no iface with this packet, match fails */
347 return 0;
348 /* Check by name or by IP address */
349 if (cmd->name[0] != '\0') { /* match by name */
350 /* Check name */
351 if (cmd->p.glob) {
352 if (fnmatch(cmd->name, ifp->if_xname, 0) == 0)
353 return(1);
354 } else {
355 if (strncmp(ifp->if_xname, cmd->name, IFNAMSIZ) == 0)
356 return(1);
357 }
358 } else {
359#ifdef __FreeBSD__ /* and OSX too ? */
360 struct ifaddr *ia;
361
362 if_addr_rlock(ifp);
363 TAILQ_FOREACH(ia, &ifp->if_addrhead, ifa_link) {
364 if (ia->ifa_addr->sa_family != AF_INET)
365 continue;
366 if (cmd->p.ip.s_addr == ((struct sockaddr_in *)
367 (ia->ifa_addr))->sin_addr.s_addr) {
368 if_addr_runlock(ifp);
369 return(1); /* match */
370 }
371 }
372 if_addr_runlock(ifp);
373#endif /* __FreeBSD__ */
374 }
375 return(0); /* no match, fail ... */
376}
377
378/*
379 * The verify_path function checks if a route to the src exists and
380 * if it is reachable via ifp (when provided).
381 *
382 * The 'verrevpath' option checks that the interface that an IP packet
383 * arrives on is the same interface that traffic destined for the
384 * packet's source address would be routed out of.
385 * The 'versrcreach' option just checks that the source address is
386 * reachable via any route (except default) in the routing table.
387 * These two are a measure to block forged packets. This is also
388 * commonly known as "anti-spoofing" or Unicast Reverse Path
389 * Forwarding (Unicast RFP) in Cisco-ese. The name of the knobs
390 * is purposely reminiscent of the Cisco IOS command,
391 *
392 * ip verify unicast reverse-path
393 * ip verify unicast source reachable-via any
394 *
395 * which implements the same functionality. But note that the syntax
396 * is misleading, and the check may be performed on all IP packets
397 * whether unicast, multicast, or broadcast.
398 */
399static int
400verify_path(struct in_addr src, struct ifnet *ifp, u_int fib)
401{
402#ifndef __FreeBSD__
403 return 0;
404#else
405 struct route ro;
406 struct sockaddr_in *dst;
407
408 bzero(&ro, sizeof(ro));
409
410 dst = (struct sockaddr_in *)&(ro.ro_dst);
411 dst->sin_family = AF_INET;
412 dst->sin_len = sizeof(*dst);
413 dst->sin_addr = src;
414 in_rtalloc_ign(&ro, 0, fib);
415
416 if (ro.ro_rt == NULL)
417 return 0;
418
419 /*
420 * If ifp is provided, check for equality with rtentry.
421 * We should use rt->rt_ifa->ifa_ifp, instead of rt->rt_ifp,
422 * in order to pass packets injected back by if_simloop():
423 * if useloopback == 1 routing entry (via lo0) for our own address
424 * may exist, so we need to handle routing assymetry.
425 */
426 if (ifp != NULL && ro.ro_rt->rt_ifa->ifa_ifp != ifp) {
427 RTFREE(ro.ro_rt);
428 return 0;
429 }
430
431 /* if no ifp provided, check if rtentry is not default route */
432 if (ifp == NULL &&
433 satosin(rt_key(ro.ro_rt))->sin_addr.s_addr == INADDR_ANY) {
434 RTFREE(ro.ro_rt);
435 return 0;
436 }
437
438 /* or if this is a blackhole/reject route */
439 if (ifp == NULL && ro.ro_rt->rt_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
440 RTFREE(ro.ro_rt);
441 return 0;
442 }
443
444 /* found valid route */
445 RTFREE(ro.ro_rt);
446 return 1;
447#endif /* __FreeBSD__ */
448}
449
450#ifdef INET6
451/*
452 * ipv6 specific rules here...
453 */
454static __inline int
455icmp6type_match (int type, ipfw_insn_u32 *cmd)
456{
457 return (type <= ICMP6_MAXTYPE && (cmd->d[type/32] & (1<<(type%32)) ) );
458}
459
460static int
461flow6id_match( int curr_flow, ipfw_insn_u32 *cmd )
462{
463 int i;
464 for (i=0; i <= cmd->o.arg1; ++i )
465 if (curr_flow == cmd->d[i] )
466 return 1;
467 return 0;
468}
469
470/* support for IP6_*_ME opcodes */
471static int
472search_ip6_addr_net (struct in6_addr * ip6_addr)
473{
474 struct ifnet *mdc;
475 struct ifaddr *mdc2;
476 struct in6_ifaddr *fdm;
477 struct in6_addr copia;
478
479 TAILQ_FOREACH(mdc, &V_ifnet, if_link) {
480 if_addr_rlock(mdc);
481 TAILQ_FOREACH(mdc2, &mdc->if_addrhead, ifa_link) {
482 if (mdc2->ifa_addr->sa_family == AF_INET6) {
483 fdm = (struct in6_ifaddr *)mdc2;
484 copia = fdm->ia_addr.sin6_addr;
485 /* need for leaving scope_id in the sock_addr */
486 in6_clearscope(&copia);
487 if (IN6_ARE_ADDR_EQUAL(ip6_addr, &copia)) {
488 if_addr_runlock(mdc);
489 return 1;
490 }
491 }
492 }
493 if_addr_runlock(mdc);
494 }
495 return 0;
496}
497
498static int
499verify_path6(struct in6_addr *src, struct ifnet *ifp)
500{
501 struct route_in6 ro;
502 struct sockaddr_in6 *dst;
503
504 bzero(&ro, sizeof(ro));
505
506 dst = (struct sockaddr_in6 * )&(ro.ro_dst);
507 dst->sin6_family = AF_INET6;
508 dst->sin6_len = sizeof(*dst);
509 dst->sin6_addr = *src;
510 /* XXX MRT 0 for ipv6 at this time */
511 rtalloc_ign((struct route *)&ro, 0);
512
513 if (ro.ro_rt == NULL)
514 return 0;
515
516 /*
517 * if ifp is provided, check for equality with rtentry
518 * We should use rt->rt_ifa->ifa_ifp, instead of rt->rt_ifp,
519 * to support the case of sending packets to an address of our own.
520 * (where the former interface is the first argument of if_simloop()
521 * (=ifp), the latter is lo0)
522 */
523 if (ifp != NULL && ro.ro_rt->rt_ifa->ifa_ifp != ifp) {
524 RTFREE(ro.ro_rt);
525 return 0;
526 }
527
528 /* if no ifp provided, check if rtentry is not default route */
529 if (ifp == NULL &&
530 IN6_IS_ADDR_UNSPECIFIED(&satosin6(rt_key(ro.ro_rt))->sin6_addr)) {
531 RTFREE(ro.ro_rt);
532 return 0;
533 }
534
535 /* or if this is a blackhole/reject route */
536 if (ifp == NULL && ro.ro_rt->rt_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
537 RTFREE(ro.ro_rt);
538 return 0;
539 }
540
541 /* found valid route */
542 RTFREE(ro.ro_rt);
543 return 1;
544
545}
546
547static int
548is_icmp6_query(int icmp6_type)
549{
550 if ((icmp6_type <= ICMP6_MAXTYPE) &&
551 (icmp6_type == ICMP6_ECHO_REQUEST ||
552 icmp6_type == ICMP6_MEMBERSHIP_QUERY ||
553 icmp6_type == ICMP6_WRUREQUEST ||
554 icmp6_type == ICMP6_FQDN_QUERY ||
555 icmp6_type == ICMP6_NI_QUERY))
556 return (1);
557
558 return (0);
559}
560
561static void
562send_reject6(struct ip_fw_args *args, int code, u_int hlen, struct ip6_hdr *ip6)
563{
564 struct mbuf *m;
565
566 m = args->m;
567 if (code == ICMP6_UNREACH_RST && args->f_id.proto == IPPROTO_TCP) {
568 struct tcphdr *tcp;
569 tcp = (struct tcphdr *)((char *)ip6 + hlen);
570
571 if ((tcp->th_flags & TH_RST) == 0) {
572 struct mbuf *m0;
573 m0 = ipfw_send_pkt(args->m, &(args->f_id),
574 ntohl(tcp->th_seq), ntohl(tcp->th_ack),
575 tcp->th_flags | TH_RST);
576 if (m0 != NULL)
577 ip6_output(m0, NULL, NULL, 0, NULL, NULL,
578 NULL);
579 }
580 FREE_PKT(m);
581 } else if (code != ICMP6_UNREACH_RST) { /* Send an ICMPv6 unreach. */
582#if 0
583 /*
584 * Unlike above, the mbufs need to line up with the ip6 hdr,
585 * as the contents are read. We need to m_adj() the
586 * needed amount.
587 * The mbuf will however be thrown away so we can adjust it.
588 * Remember we did an m_pullup on it already so we
589 * can make some assumptions about contiguousness.
590 */
591 if (args->L3offset)
592 m_adj(m, args->L3offset);
593#endif
594 icmp6_error(m, ICMP6_DST_UNREACH, code, 0);
595 } else
596 FREE_PKT(m);
597
598 args->m = NULL;
599}
600
601#endif /* INET6 */
602
603
604/*
605 * sends a reject message, consuming the mbuf passed as an argument.
606 */
607static void
608send_reject(struct ip_fw_args *args, int code, int iplen, struct ip *ip)
609{
610
611#if 0
612 /* XXX When ip is not guaranteed to be at mtod() we will
613 * need to account for this */
614 * The mbuf will however be thrown away so we can adjust it.
615 * Remember we did an m_pullup on it already so we
616 * can make some assumptions about contiguousness.
617 */
618 if (args->L3offset)
619 m_adj(m, args->L3offset);
620#endif
621 if (code != ICMP_REJECT_RST) { /* Send an ICMP unreach */
622 /* We need the IP header in host order for icmp_error(). */
623 SET_HOST_IPLEN(ip);
624 icmp_error(args->m, ICMP_UNREACH, code, 0L, 0);
625 } else if (args->f_id.proto == IPPROTO_TCP) {
626 struct tcphdr *const tcp =
627 L3HDR(struct tcphdr, mtod(args->m, struct ip *));
628 if ( (tcp->th_flags & TH_RST) == 0) {
629 struct mbuf *m;
630 m = ipfw_send_pkt(args->m, &(args->f_id),
631 ntohl(tcp->th_seq), ntohl(tcp->th_ack),
632 tcp->th_flags | TH_RST);
633 if (m != NULL)
634 ip_output(m, NULL, NULL, 0, NULL, NULL);
635 }
636 FREE_PKT(args->m);
637 } else
638 FREE_PKT(args->m);
639 args->m = NULL;
640}
641
642/*
643 * Support for uid/gid/jail lookup. These tests are expensive
644 * (because we may need to look into the list of active sockets)
645 * so we cache the results. ugid_lookupp is 0 if we have not
646 * yet done a lookup, 1 if we succeeded, and -1 if we tried
647 * and failed. The function always returns the match value.
648 * We could actually spare the variable and use *uc, setting
649 * it to '(void *)check_uidgid if we have no info, NULL if
650 * we tried and failed, or any other value if successful.
651 */
652static int
653check_uidgid(ipfw_insn_u32 *insn, struct ip_fw_args *args, int *ugid_lookupp,
654 struct ucred **uc)
655{
656#ifndef __FreeBSD__
657 /* XXX */
658 return cred_check(insn, proto, oif,
659 dst_ip, dst_port, src_ip, src_port,
660 (struct bsd_ucred *)uc, ugid_lookupp, ((struct mbuf *)inp)->m_skb);
661#else /* FreeBSD */
662 struct in_addr src_ip, dst_ip;
663 struct inpcbinfo *pi;
664 struct ipfw_flow_id *id;
665 struct inpcb *pcb, *inp;
666 struct ifnet *oif;
667 int lookupflags;
668 int match;
669
670 id = &args->f_id;
671 inp = args->inp;
672 oif = args->oif;
673
674 /*
675 * Check to see if the UDP or TCP stack supplied us with
676 * the PCB. If so, rather then holding a lock and looking
677 * up the PCB, we can use the one that was supplied.
678 */
679 if (inp && *ugid_lookupp == 0) {
680 INP_LOCK_ASSERT(inp);
681 if (inp->inp_socket != NULL) {
682 *uc = crhold(inp->inp_cred);
683 *ugid_lookupp = 1;
684 } else
685 *ugid_lookupp = -1;
686 }
687 /*
688 * If we have already been here and the packet has no
689 * PCB entry associated with it, then we can safely
690 * assume that this is a no match.
691 */
692 if (*ugid_lookupp == -1)
693 return (0);
694 if (id->proto == IPPROTO_TCP) {
695 lookupflags = 0;
696 pi = &V_tcbinfo;
697 } else if (id->proto == IPPROTO_UDP) {
698 lookupflags = INPLOOKUP_WILDCARD;
699 pi = &V_udbinfo;
700 } else
701 return 0;
702 lookupflags |= INPLOOKUP_RLOCKPCB;
703 match = 0;
704 if (*ugid_lookupp == 0) {
705 if (id->addr_type == 6) {
706#ifdef INET6
707 if (oif == NULL)
708 pcb = in6_pcblookup_mbuf(pi,
709 &id->src_ip6, htons(id->src_port),
710 &id->dst_ip6, htons(id->dst_port),
711 lookupflags, oif, args->m);
712 else
713 pcb = in6_pcblookup_mbuf(pi,
714 &id->dst_ip6, htons(id->dst_port),
715 &id->src_ip6, htons(id->src_port),
716 lookupflags, oif, args->m);
717#else
718 *ugid_lookupp = -1;
719 return (0);
720#endif
721 } else {
722 src_ip.s_addr = htonl(id->src_ip);
723 dst_ip.s_addr = htonl(id->dst_ip);
724 if (oif == NULL)
725 pcb = in_pcblookup_mbuf(pi,
726 src_ip, htons(id->src_port),
727 dst_ip, htons(id->dst_port),
728 lookupflags, oif, args->m);
729 else
730 pcb = in_pcblookup_mbuf(pi,
731 dst_ip, htons(id->dst_port),
732 src_ip, htons(id->src_port),
733 lookupflags, oif, args->m);
734 }
735 if (pcb != NULL) {
736 INP_RLOCK_ASSERT(pcb);
737 *uc = crhold(pcb->inp_cred);
738 *ugid_lookupp = 1;
739 INP_RUNLOCK(pcb);
740 }
741 if (*ugid_lookupp == 0) {
742 /*
743 * We tried and failed, set the variable to -1
744 * so we will not try again on this packet.
745 */
746 *ugid_lookupp = -1;
747 return (0);
748 }
749 }
750 if (insn->o.opcode == O_UID)
751 match = ((*uc)->cr_uid == (uid_t)insn->d[0]);
752 else if (insn->o.opcode == O_GID)
753 match = groupmember((gid_t)insn->d[0], *uc);
754 else if (insn->o.opcode == O_JAIL)
755 match = ((*uc)->cr_prison->pr_id == (int)insn->d[0]);
756 return (match);
757#endif /* __FreeBSD__ */
758}
759
760/*
761 * Helper function to set args with info on the rule after the matching
762 * one. slot is precise, whereas we guess rule_id as they are
763 * assigned sequentially.
764 */
765static inline void
766set_match(struct ip_fw_args *args, int slot,
767 struct ip_fw_chain *chain)
768{
769 args->rule.chain_id = chain->id;
770 args->rule.slot = slot + 1; /* we use 0 as a marker */
771 args->rule.rule_id = 1 + chain->map[slot]->id;
772 args->rule.rulenum = chain->map[slot]->rulenum;
773}
774
775/*
776 * The main check routine for the firewall.
777 *
778 * All arguments are in args so we can modify them and return them
779 * back to the caller.
780 *
781 * Parameters:
782 *
783 * args->m (in/out) The packet; we set to NULL when/if we nuke it.
784 * Starts with the IP header.
785 * args->eh (in) Mac header if present, NULL for layer3 packet.
786 * args->L3offset Number of bytes bypassed if we came from L2.
787 * e.g. often sizeof(eh) ** NOTYET **
788 * args->oif Outgoing interface, NULL if packet is incoming.
789 * The incoming interface is in the mbuf. (in)
790 * args->divert_rule (in/out)
791 * Skip up to the first rule past this rule number;
792 * upon return, non-zero port number for divert or tee.
793 *
794 * args->rule Pointer to the last matching rule (in/out)
795 * args->next_hop Socket we are forwarding to (out).
796 * args->next_hop6 IPv6 next hop we are forwarding to (out).
797 * args->f_id Addresses grabbed from the packet (out)
798 * args->rule.info a cookie depending on rule action
799 *
800 * Return value:
801 *
802 * IP_FW_PASS the packet must be accepted
803 * IP_FW_DENY the packet must be dropped
804 * IP_FW_DIVERT divert packet, port in m_tag
805 * IP_FW_TEE tee packet, port in m_tag
806 * IP_FW_DUMMYNET to dummynet, pipe in args->cookie
807 * IP_FW_NETGRAPH into netgraph, cookie args->cookie
808 * args->rule contains the matching rule,
809 * args->rule.info has additional information.
810 *
811 */
812int
813ipfw_chk(struct ip_fw_args *args)
814{
815
816 /*
817 * Local variables holding state while processing a packet:
818 *
819 * IMPORTANT NOTE: to speed up the processing of rules, there
820 * are some assumption on the values of the variables, which
821 * are documented here. Should you change them, please check
822 * the implementation of the various instructions to make sure
823 * that they still work.
824 *
825 * args->eh The MAC header. It is non-null for a layer2
826 * packet, it is NULL for a layer-3 packet.
827 * **notyet**
828 * args->L3offset Offset in the packet to the L3 (IP or equiv.) header.
829 *
830 * m | args->m Pointer to the mbuf, as received from the caller.
831 * It may change if ipfw_chk() does an m_pullup, or if it
832 * consumes the packet because it calls send_reject().
833 * XXX This has to change, so that ipfw_chk() never modifies
834 * or consumes the buffer.
835 * ip is the beginning of the ip(4 or 6) header.
836 * Calculated by adding the L3offset to the start of data.
837 * (Until we start using L3offset, the packet is
838 * supposed to start with the ip header).
839 */
840 struct mbuf *m = args->m;
841 struct ip *ip = mtod(m, struct ip *);
842
843 /*
844 * For rules which contain uid/gid or jail constraints, cache
845 * a copy of the users credentials after the pcb lookup has been
846 * executed. This will speed up the processing of rules with
847 * these types of constraints, as well as decrease contention
848 * on pcb related locks.
849 */
850#ifndef __FreeBSD__
851 struct bsd_ucred ucred_cache;
852#else
853 struct ucred *ucred_cache = NULL;
854#endif
855 int ucred_lookup = 0;
856
857 /*
858 * oif | args->oif If NULL, ipfw_chk has been called on the
859 * inbound path (ether_input, ip_input).
860 * If non-NULL, ipfw_chk has been called on the outbound path
861 * (ether_output, ip_output).
862 */
863 struct ifnet *oif = args->oif;
864
865 int f_pos = 0; /* index of current rule in the array */
866 int retval = 0;
867
868 /*
869 * hlen The length of the IP header.
870 */
871 u_int hlen = 0; /* hlen >0 means we have an IP pkt */
872
873 /*
874 * offset The offset of a fragment. offset != 0 means that
875 * we have a fragment at this offset of an IPv4 packet.
876 * offset == 0 means that (if this is an IPv4 packet)
877 * this is the first or only fragment.
878 * For IPv6 offset|ip6f_mf == 0 means there is no Fragment Header
879 * or there is a single packet fragement (fragement header added
880 * without needed). We will treat a single packet fragment as if
881 * there was no fragment header (or log/block depending on the
882 * V_fw_permit_single_frag6 sysctl setting).
883 */
884 u_short offset = 0;
885 u_short ip6f_mf = 0;
886
887 /*
888 * Local copies of addresses. They are only valid if we have
889 * an IP packet.
890 *
891 * proto The protocol. Set to 0 for non-ip packets,
892 * or to the protocol read from the packet otherwise.
893 * proto != 0 means that we have an IPv4 packet.
894 *
895 * src_port, dst_port port numbers, in HOST format. Only
896 * valid for TCP and UDP packets.
897 *
898 * src_ip, dst_ip ip addresses, in NETWORK format.
899 * Only valid for IPv4 packets.
900 */
901 uint8_t proto;
902 uint16_t src_port = 0, dst_port = 0; /* NOTE: host format */
903 struct in_addr src_ip, dst_ip; /* NOTE: network format */
904 uint16_t iplen=0;
905 int pktlen;
906 uint16_t etype = 0; /* Host order stored ether type */
907
908 /*
909 * dyn_dir = MATCH_UNKNOWN when rules unchecked,
910 * MATCH_NONE when checked and not matched (q = NULL),
911 * MATCH_FORWARD or MATCH_REVERSE otherwise (q != NULL)
912 */
913 int dyn_dir = MATCH_UNKNOWN;
914 ipfw_dyn_rule *q = NULL;
915 struct ip_fw_chain *chain = &V_layer3_chain;
916
917 /*
918 * We store in ulp a pointer to the upper layer protocol header.
919 * In the ipv4 case this is easy to determine from the header,
920 * but for ipv6 we might have some additional headers in the middle.
921 * ulp is NULL if not found.
922 */
923 void *ulp = NULL; /* upper layer protocol pointer. */
924
925 /* XXX ipv6 variables */
926 int is_ipv6 = 0;
927 uint8_t icmp6_type = 0;
928 uint16_t ext_hd = 0; /* bits vector for extension header filtering */
929 /* end of ipv6 variables */
930
931 int is_ipv4 = 0;
932
933 int done = 0; /* flag to exit the outer loop */
934
935 if (m->m_flags & M_SKIP_FIREWALL || (! V_ipfw_vnet_ready))
936 return (IP_FW_PASS); /* accept */
937
938 dst_ip.s_addr = 0; /* make sure it is initialized */
939 src_ip.s_addr = 0; /* make sure it is initialized */
940 pktlen = m->m_pkthdr.len;
941 args->f_id.fib = M_GETFIB(m); /* note mbuf not altered) */
942 proto = args->f_id.proto = 0; /* mark f_id invalid */
943 /* XXX 0 is a valid proto: IP/IPv6 Hop-by-Hop Option */
944
945/*
946 * PULLUP_TO(len, p, T) makes sure that len + sizeof(T) is contiguous,
947 * then it sets p to point at the offset "len" in the mbuf. WARNING: the
948 * pointer might become stale after other pullups (but we never use it
949 * this way).
950 */
951#define PULLUP_TO(_len, p, T) PULLUP_LEN(_len, p, sizeof(T))
952#define PULLUP_LEN(_len, p, T) \
953do { \
954 int x = (_len) + T; \
955 if ((m)->m_len < x) { \
956 args->m = m = m_pullup(m, x); \
957 if (m == NULL) \
958 goto pullup_failed; \
959 } \
960 p = (mtod(m, char *) + (_len)); \
961} while (0)
962
963 /*
964 * if we have an ether header,
965 */
966 if (args->eh)
967 etype = ntohs(args->eh->ether_type);
968
969 /* Identify IP packets and fill up variables. */
970 if (pktlen >= sizeof(struct ip6_hdr) &&
971 (args->eh == NULL || etype == ETHERTYPE_IPV6) && ip->ip_v == 6) {
972 struct ip6_hdr *ip6 = (struct ip6_hdr *)ip;
973 is_ipv6 = 1;
974 args->f_id.addr_type = 6;
975 hlen = sizeof(struct ip6_hdr);
976 proto = ip6->ip6_nxt;
977
978 /* Search extension headers to find upper layer protocols */
979 while (ulp == NULL && offset == 0) {
980 switch (proto) {
981 case IPPROTO_ICMPV6:
982 PULLUP_TO(hlen, ulp, struct icmp6_hdr);
983 icmp6_type = ICMP6(ulp)->icmp6_type;
984 break;
985
986 case IPPROTO_TCP:
987 PULLUP_TO(hlen, ulp, struct tcphdr);
988 dst_port = TCP(ulp)->th_dport;
989 src_port = TCP(ulp)->th_sport;
990 /* save flags for dynamic rules */
991 args->f_id._flags = TCP(ulp)->th_flags;
992 break;
993
994 case IPPROTO_SCTP:
995 PULLUP_TO(hlen, ulp, struct sctphdr);
996 src_port = SCTP(ulp)->src_port;
997 dst_port = SCTP(ulp)->dest_port;
998 break;
999
1000 case IPPROTO_UDP:
1001 PULLUP_TO(hlen, ulp, struct udphdr);
1002 dst_port = UDP(ulp)->uh_dport;
1003 src_port = UDP(ulp)->uh_sport;
1004 break;
1005
1006 case IPPROTO_HOPOPTS: /* RFC 2460 */
1007 PULLUP_TO(hlen, ulp, struct ip6_hbh);
1008 ext_hd |= EXT_HOPOPTS;
1009 hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3;
1010 proto = ((struct ip6_hbh *)ulp)->ip6h_nxt;
1011 ulp = NULL;
1012 break;
1013
1014 case IPPROTO_ROUTING: /* RFC 2460 */
1015 PULLUP_TO(hlen, ulp, struct ip6_rthdr);
1016 switch (((struct ip6_rthdr *)ulp)->ip6r_type) {
1017 case 0:
1018 ext_hd |= EXT_RTHDR0;
1019 break;
1020 case 2:
1021 ext_hd |= EXT_RTHDR2;
1022 break;
1023 default:
1024 if (V_fw_verbose)
1025 printf("IPFW2: IPV6 - Unknown "
1026 "Routing Header type(%d)\n",
1027 ((struct ip6_rthdr *)
1028 ulp)->ip6r_type);
1029 if (V_fw_deny_unknown_exthdrs)
1030 return (IP_FW_DENY);
1031 break;
1032 }
1033 ext_hd |= EXT_ROUTING;
1034 hlen += (((struct ip6_rthdr *)ulp)->ip6r_len + 1) << 3;
1035 proto = ((struct ip6_rthdr *)ulp)->ip6r_nxt;
1036 ulp = NULL;
1037 break;
1038
1039 case IPPROTO_FRAGMENT: /* RFC 2460 */
1040 PULLUP_TO(hlen, ulp, struct ip6_frag);
1041 ext_hd |= EXT_FRAGMENT;
1042 hlen += sizeof (struct ip6_frag);
1043 proto = ((struct ip6_frag *)ulp)->ip6f_nxt;
1044 offset = ((struct ip6_frag *)ulp)->ip6f_offlg &
1045 IP6F_OFF_MASK;
1046 ip6f_mf = ((struct ip6_frag *)ulp)->ip6f_offlg &
1047 IP6F_MORE_FRAG;
1048 if (V_fw_permit_single_frag6 == 0 &&
1049 offset == 0 && ip6f_mf == 0) {
1050 if (V_fw_verbose)
1051 printf("IPFW2: IPV6 - Invalid "
1052 "Fragment Header\n");
1053 if (V_fw_deny_unknown_exthdrs)
1054 return (IP_FW_DENY);
1055 break;
1056 }
1057 args->f_id.extra =
1058 ntohl(((struct ip6_frag *)ulp)->ip6f_ident);
1059 ulp = NULL;
1060 break;
1061
1062 case IPPROTO_DSTOPTS: /* RFC 2460 */
1063 PULLUP_TO(hlen, ulp, struct ip6_hbh);
1064 ext_hd |= EXT_DSTOPTS;
1065 hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3;
1066 proto = ((struct ip6_hbh *)ulp)->ip6h_nxt;
1067 ulp = NULL;
1068 break;
1069
1070 case IPPROTO_AH: /* RFC 2402 */
1071 PULLUP_TO(hlen, ulp, struct ip6_ext);
1072 ext_hd |= EXT_AH;
1073 hlen += (((struct ip6_ext *)ulp)->ip6e_len + 2) << 2;
1074 proto = ((struct ip6_ext *)ulp)->ip6e_nxt;
1075 ulp = NULL;
1076 break;
1077
1078 case IPPROTO_ESP: /* RFC 2406 */
1079 PULLUP_TO(hlen, ulp, uint32_t); /* SPI, Seq# */
1080 /* Anything past Seq# is variable length and
1081 * data past this ext. header is encrypted. */
1082 ext_hd |= EXT_ESP;
1083 break;
1084
1085 case IPPROTO_NONE: /* RFC 2460 */
1086 /*
1087 * Packet ends here, and IPv6 header has
1088 * already been pulled up. If ip6e_len!=0
1089 * then octets must be ignored.
1090 */
1091 ulp = ip; /* non-NULL to get out of loop. */
1092 break;
1093
1094 case IPPROTO_OSPFIGP:
1095 /* XXX OSPF header check? */
1096 PULLUP_TO(hlen, ulp, struct ip6_ext);
1097 break;
1098
1099 case IPPROTO_PIM:
1100 /* XXX PIM header check? */
1101 PULLUP_TO(hlen, ulp, struct pim);
1102 break;
1103
1104 case IPPROTO_CARP:
1105 PULLUP_TO(hlen, ulp, struct carp_header);
1106 if (((struct carp_header *)ulp)->carp_version !=
1107 CARP_VERSION)
1108 return (IP_FW_DENY);
1109 if (((struct carp_header *)ulp)->carp_type !=
1110 CARP_ADVERTISEMENT)
1111 return (IP_FW_DENY);
1112 break;
1113
1114 case IPPROTO_IPV6: /* RFC 2893 */
1115 PULLUP_TO(hlen, ulp, struct ip6_hdr);
1116 break;
1117
1118 case IPPROTO_IPV4: /* RFC 2893 */
1119 PULLUP_TO(hlen, ulp, struct ip);
1120 break;
1121
1122 default:
1123 if (V_fw_verbose)
1124 printf("IPFW2: IPV6 - Unknown "
1125 "Extension Header(%d), ext_hd=%x\n",
1126 proto, ext_hd);
1127 if (V_fw_deny_unknown_exthdrs)
1128 return (IP_FW_DENY);
1129 PULLUP_TO(hlen, ulp, struct ip6_ext);
1130 break;
1131 } /*switch */
1132 }
1133 ip = mtod(m, struct ip *);
1134 ip6 = (struct ip6_hdr *)ip;
1135 args->f_id.src_ip6 = ip6->ip6_src;
1136 args->f_id.dst_ip6 = ip6->ip6_dst;
1137 args->f_id.src_ip = 0;
1138 args->f_id.dst_ip = 0;
1139 args->f_id.flow_id6 = ntohl(ip6->ip6_flow);
1140 } else if (pktlen >= sizeof(struct ip) &&
1141 (args->eh == NULL || etype == ETHERTYPE_IP) && ip->ip_v == 4) {
1142 is_ipv4 = 1;
1143 hlen = ip->ip_hl << 2;
1144 args->f_id.addr_type = 4;
1145
1146 /*
1147 * Collect parameters into local variables for faster matching.
1148 */
1149 proto = ip->ip_p;
1150 src_ip = ip->ip_src;
1151 dst_ip = ip->ip_dst;
1152 offset = ntohs(ip->ip_off) & IP_OFFMASK;
1153 iplen = ntohs(ip->ip_len);
1154 pktlen = iplen < pktlen ? iplen : pktlen;
1155
1156 if (offset == 0) {
1157 switch (proto) {
1158 case IPPROTO_TCP:
1159 PULLUP_TO(hlen, ulp, struct tcphdr);
1160 dst_port = TCP(ulp)->th_dport;
1161 src_port = TCP(ulp)->th_sport;
1162 /* save flags for dynamic rules */
1163 args->f_id._flags = TCP(ulp)->th_flags;
1164 break;
1165
1166 case IPPROTO_SCTP:
1167 PULLUP_TO(hlen, ulp, struct sctphdr);
1168 src_port = SCTP(ulp)->src_port;
1169 dst_port = SCTP(ulp)->dest_port;
1170 break;
1171
1172 case IPPROTO_UDP:
1173 PULLUP_TO(hlen, ulp, struct udphdr);
1174 dst_port = UDP(ulp)->uh_dport;
1175 src_port = UDP(ulp)->uh_sport;
1176 break;
1177
1178 case IPPROTO_ICMP:
1179 PULLUP_TO(hlen, ulp, struct icmphdr);
1180 //args->f_id.flags = ICMP(ulp)->icmp_type;
1181 break;
1182
1183 default:
1184 break;
1185 }
1186 }
1187
1188 ip = mtod(m, struct ip *);
1189 args->f_id.src_ip = ntohl(src_ip.s_addr);
1190 args->f_id.dst_ip = ntohl(dst_ip.s_addr);
1191 }
1192#undef PULLUP_TO
1193 if (proto) { /* we may have port numbers, store them */
1194 args->f_id.proto = proto;
1195 args->f_id.src_port = src_port = ntohs(src_port);
1196 args->f_id.dst_port = dst_port = ntohs(dst_port);
1197 }
1198
1199 IPFW_RLOCK(chain);
1200 if (! V_ipfw_vnet_ready) { /* shutting down, leave NOW. */
1201 IPFW_RUNLOCK(chain);
1202 return (IP_FW_PASS); /* accept */
1203 }
1204 if (args->rule.slot) {
1205 /*
1206 * Packet has already been tagged as a result of a previous
1207 * match on rule args->rule aka args->rule_id (PIPE, QUEUE,
1208 * REASS, NETGRAPH, DIVERT/TEE...)
1209 * Validate the slot and continue from the next one
1210 * if still present, otherwise do a lookup.
1211 */
1212 f_pos = (args->rule.chain_id == chain->id) ?
1213 args->rule.slot :
1214 ipfw_find_rule(chain, args->rule.rulenum,
1215 args->rule.rule_id);
1216 } else {
1217 f_pos = 0;
1218 }
1219
1220 /*
1221 * Now scan the rules, and parse microinstructions for each rule.
1222 * We have two nested loops and an inner switch. Sometimes we
1223 * need to break out of one or both loops, or re-enter one of
1224 * the loops with updated variables. Loop variables are:
1225 *
1226 * f_pos (outer loop) points to the current rule.
1227 * On output it points to the matching rule.
1228 * done (outer loop) is used as a flag to break the loop.
1229 * l (inner loop) residual length of current rule.
1230 * cmd points to the current microinstruction.
1231 *
1232 * We break the inner loop by setting l=0 and possibly
1233 * cmdlen=0 if we don't want to advance cmd.
1234 * We break the outer loop by setting done=1
1235 * We can restart the inner loop by setting l>0 and f_pos, f, cmd
1236 * as needed.
1237 */
1238 for (; f_pos < chain->n_rules; f_pos++) {
1239 ipfw_insn *cmd;
1240 uint32_t tablearg = 0;
1241 int l, cmdlen, skip_or; /* skip rest of OR block */
1242 struct ip_fw *f;
1243
1244 f = chain->map[f_pos];
1245 if (V_set_disable & (1 << f->set) )
1246 continue;
1247
1248 skip_or = 0;
1249 for (l = f->cmd_len, cmd = f->cmd ; l > 0 ;
1250 l -= cmdlen, cmd += cmdlen) {
1251 int match;
1252
1253 /*
1254 * check_body is a jump target used when we find a
1255 * CHECK_STATE, and need to jump to the body of
1256 * the target rule.
1257 */
1258
1259/* check_body: */
1260 cmdlen = F_LEN(cmd);
1261 /*
1262 * An OR block (insn_1 || .. || insn_n) has the
1263 * F_OR bit set in all but the last instruction.
1264 * The first match will set "skip_or", and cause
1265 * the following instructions to be skipped until
1266 * past the one with the F_OR bit clear.
1267 */
1268 if (skip_or) { /* skip this instruction */
1269 if ((cmd->len & F_OR) == 0)
1270 skip_or = 0; /* next one is good */
1271 continue;
1272 }
1273 match = 0; /* set to 1 if we succeed */
1274
1275 switch (cmd->opcode) {
1276 /*
1277 * The first set of opcodes compares the packet's
1278 * fields with some pattern, setting 'match' if a
1279 * match is found. At the end of the loop there is
1280 * logic to deal with F_NOT and F_OR flags associated
1281 * with the opcode.
1282 */
1283 case O_NOP:
1284 match = 1;
1285 break;
1286
1287 case O_FORWARD_MAC:
1288 printf("ipfw: opcode %d unimplemented\n",
1289 cmd->opcode);
1290 break;
1291
1292 case O_GID:
1293 case O_UID:
1294 case O_JAIL:
1295 /*
1296 * We only check offset == 0 && proto != 0,
1297 * as this ensures that we have a
1298 * packet with the ports info.
1299 */
1300 if (offset != 0)
1301 break;
1302 if (proto == IPPROTO_TCP ||
1303 proto == IPPROTO_UDP)
1304 match = check_uidgid(
1305 (ipfw_insn_u32 *)cmd,
1306 args, &ucred_lookup,
1307#ifdef __FreeBSD__
1308 &ucred_cache);
1309#else
1310 (void *)&ucred_cache);
1311#endif
1312 break;
1313
1314 case O_RECV:
1315 match = iface_match(m->m_pkthdr.rcvif,
1316 (ipfw_insn_if *)cmd);
1317 break;
1318
1319 case O_XMIT:
1320 match = iface_match(oif, (ipfw_insn_if *)cmd);
1321 break;
1322
1323 case O_VIA:
1324 match = iface_match(oif ? oif :
1325 m->m_pkthdr.rcvif, (ipfw_insn_if *)cmd);
1326 break;
1327
1328 case O_MACADDR2:
1329 if (args->eh != NULL) { /* have MAC header */
1330 u_int32_t *want = (u_int32_t *)
1331 ((ipfw_insn_mac *)cmd)->addr;
1332 u_int32_t *mask = (u_int32_t *)
1333 ((ipfw_insn_mac *)cmd)->mask;
1334 u_int32_t *hdr = (u_int32_t *)args->eh;
1335
1336 match =
1337 ( want[0] == (hdr[0] & mask[0]) &&
1338 want[1] == (hdr[1] & mask[1]) &&
1339 want[2] == (hdr[2] & mask[2]) );
1340 }
1341 break;
1342
1343 case O_MAC_TYPE:
1344 if (args->eh != NULL) {
1345 u_int16_t *p =
1346 ((ipfw_insn_u16 *)cmd)->ports;
1347 int i;
1348
1349 for (i = cmdlen - 1; !match && i>0;
1350 i--, p += 2)
1351 match = (etype >= p[0] &&
1352 etype <= p[1]);
1353 }
1354 break;
1355
1356 case O_FRAG:
1357 match = (offset != 0);
1358 break;
1359
1360 case O_IN: /* "out" is "not in" */
1361 match = (oif == NULL);
1362 break;
1363
1364 case O_LAYER2:
1365 match = (args->eh != NULL);
1366 break;
1367
1368 case O_DIVERTED:
1369 {
1370 /* For diverted packets, args->rule.info
1371 * contains the divert port (in host format)
1372 * reason and direction.
1373 */
1374 uint32_t i = args->rule.info;
1375 match = (i&IPFW_IS_MASK) == IPFW_IS_DIVERT &&
1376 cmd->arg1 & ((i & IPFW_INFO_IN) ? 1 : 2);
1377 }
1378 break;
1379
1380 case O_PROTO:
1381 /*
1382 * We do not allow an arg of 0 so the
1383 * check of "proto" only suffices.
1384 */
1385 match = (proto == cmd->arg1);
1386 break;
1387
1388 case O_IP_SRC:
1389 match = is_ipv4 &&
1390 (((ipfw_insn_ip *)cmd)->addr.s_addr ==
1391 src_ip.s_addr);
1392 break;
1393
1394 case O_IP_SRC_LOOKUP:
1395 case O_IP_DST_LOOKUP:
1396 if (is_ipv4) {
1397 uint32_t key =
1398 (cmd->opcode == O_IP_DST_LOOKUP) ?
1399 dst_ip.s_addr : src_ip.s_addr;
1400 uint32_t v = 0;
1401
1402 if (cmdlen > F_INSN_SIZE(ipfw_insn_u32)) {
1403 /* generic lookup. The key must be
1404 * in 32bit big-endian format.
1405 */
1406 v = ((ipfw_insn_u32 *)cmd)->d[1];
1407 if (v == 0)
1408 key = dst_ip.s_addr;
1409 else if (v == 1)
1410 key = src_ip.s_addr;
1411 else if (v == 6) /* dscp */
1412 key = (ip->ip_tos >> 2) & 0x3f;
1413 else if (offset != 0)
1414 break;
1415 else if (proto != IPPROTO_TCP &&
1416 proto != IPPROTO_UDP)
1417 break;
1418 else if (v == 2)
1419 key = htonl(dst_port);
1420 else if (v == 3)
1421 key = htonl(src_port);
1422 else if (v == 4 || v == 5) {
1423 check_uidgid(
1424 (ipfw_insn_u32 *)cmd,
1425 args, &ucred_lookup,
1426#ifdef __FreeBSD__
1427 &ucred_cache);
1428 if (v == 4 /* O_UID */)
1429 key = ucred_cache->cr_uid;
1430 else if (v == 5 /* O_JAIL */)
1431 key = ucred_cache->cr_prison->pr_id;
1432#else /* !__FreeBSD__ */
1433 (void *)&ucred_cache);
1434 if (v ==4 /* O_UID */)
1435 key = ucred_cache.uid;
1436 else if (v == 5 /* O_JAIL */)
1437 key = ucred_cache.xid;
1438#endif /* !__FreeBSD__ */
1439 key = htonl(key);
1440 } else
1441 break;
1442 }
1443 match = ipfw_lookup_table(chain,
1444 cmd->arg1, key, &v);
1445 if (!match)
1446 break;
1447 if (cmdlen == F_INSN_SIZE(ipfw_insn_u32))
1448 match =
1449 ((ipfw_insn_u32 *)cmd)->d[0] == v;
1450 else
1451 tablearg = v;
1452 }
1453 break;
1454
1455 case O_IP_SRC_MASK:
1456 case O_IP_DST_MASK:
1457 if (is_ipv4) {
1458 uint32_t a =
1459 (cmd->opcode == O_IP_DST_MASK) ?
1460 dst_ip.s_addr : src_ip.s_addr;
1461 uint32_t *p = ((ipfw_insn_u32 *)cmd)->d;
1462 int i = cmdlen-1;
1463
1464 for (; !match && i>0; i-= 2, p+= 2)
1465 match = (p[0] == (a & p[1]));
1466 }
1467 break;
1468
1469 case O_IP_SRC_ME:
1470 if (is_ipv4) {
1471 struct ifnet *tif;
1472
1473 INADDR_TO_IFP(src_ip, tif);
1474 match = (tif != NULL);
1475 break;
1476 }
1477#ifdef INET6
1478 /* FALLTHROUGH */
1479 case O_IP6_SRC_ME:
1480 match= is_ipv6 && search_ip6_addr_net(&args->f_id.src_ip6);
1481#endif
1482 break;
1483
1484 case O_IP_DST_SET:
1485 case O_IP_SRC_SET:
1486 if (is_ipv4) {
1487 u_int32_t *d = (u_int32_t *)(cmd+1);
1488 u_int32_t addr =
1489 cmd->opcode == O_IP_DST_SET ?
1490 args->f_id.dst_ip :
1491 args->f_id.src_ip;
1492
1493 if (addr < d[0])
1494 break;
1495 addr -= d[0]; /* subtract base */
1496 match = (addr < cmd->arg1) &&
1497 ( d[ 1 + (addr>>5)] &
1498 (1<<(addr & 0x1f)) );
1499 }
1500 break;
1501
1502 case O_IP_DST:
1503 match = is_ipv4 &&
1504 (((ipfw_insn_ip *)cmd)->addr.s_addr ==
1505 dst_ip.s_addr);
1506 break;
1507
1508 case O_IP_DST_ME:
1509 if (is_ipv4) {
1510 struct ifnet *tif;
1511
1512 INADDR_TO_IFP(dst_ip, tif);
1513 match = (tif != NULL);
1514 break;
1515 }
1516#ifdef INET6
1517 /* FALLTHROUGH */
1518 case O_IP6_DST_ME:
1519 match= is_ipv6 && search_ip6_addr_net(&args->f_id.dst_ip6);
1520#endif
1521 break;
1522
1523
1524 case O_IP_SRCPORT:
1525 case O_IP_DSTPORT:
1526 /*
1527 * offset == 0 && proto != 0 is enough
1528 * to guarantee that we have a
1529 * packet with port info.
1530 */
1531 if ((proto==IPPROTO_UDP || proto==IPPROTO_TCP)
1532 && offset == 0) {
1533 u_int16_t x =
1534 (cmd->opcode == O_IP_SRCPORT) ?
1535 src_port : dst_port ;
1536 u_int16_t *p =
1537 ((ipfw_insn_u16 *)cmd)->ports;
1538 int i;
1539
1540 for (i = cmdlen - 1; !match && i>0;
1541 i--, p += 2)
1542 match = (x>=p[0] && x<=p[1]);
1543 }
1544 break;
1545
1546 case O_ICMPTYPE:
1547 match = (offset == 0 && proto==IPPROTO_ICMP &&
1548 icmptype_match(ICMP(ulp), (ipfw_insn_u32 *)cmd) );
1549 break;
1550
1551#ifdef INET6
1552 case O_ICMP6TYPE:
1553 match = is_ipv6 && offset == 0 &&
1554 proto==IPPROTO_ICMPV6 &&
1555 icmp6type_match(
1556 ICMP6(ulp)->icmp6_type,
1557 (ipfw_insn_u32 *)cmd);
1558 break;
1559#endif /* INET6 */
1560
1561 case O_IPOPT:
1562 match = (is_ipv4 &&
1563 ipopts_match(ip, cmd) );
1564 break;
1565
1566 case O_IPVER:
1567 match = (is_ipv4 &&
1568 cmd->arg1 == ip->ip_v);
1569 break;
1570
1571 case O_IPID:
1572 case O_IPLEN:
1573 case O_IPTTL:
1574 if (is_ipv4) { /* only for IP packets */
1575 uint16_t x;
1576 uint16_t *p;
1577 int i;
1578
1579 if (cmd->opcode == O_IPLEN)
1580 x = iplen;
1581 else if (cmd->opcode == O_IPTTL)
1582 x = ip->ip_ttl;
1583 else /* must be IPID */
1584 x = ntohs(ip->ip_id);
1585 if (cmdlen == 1) {
1586 match = (cmd->arg1 == x);
1587 break;
1588 }
1589 /* otherwise we have ranges */
1590 p = ((ipfw_insn_u16 *)cmd)->ports;
1591 i = cmdlen - 1;
1592 for (; !match && i>0; i--, p += 2)
1593 match = (x >= p[0] && x <= p[1]);
1594 }
1595 break;
1596
1597 case O_IPPRECEDENCE:
1598 match = (is_ipv4 &&
1599 (cmd->arg1 == (ip->ip_tos & 0xe0)) );
1600 break;
1601
1602 case O_IPTOS:
1603 match = (is_ipv4 &&
1604 flags_match(cmd, ip->ip_tos));
1605 break;
1606
1607 case O_TCPDATALEN:
1608 if (proto == IPPROTO_TCP && offset == 0) {
1609 struct tcphdr *tcp;
1610 uint16_t x;
1611 uint16_t *p;
1612 int i;
1613
1614 tcp = TCP(ulp);
1615 x = iplen -
1616 ((ip->ip_hl + tcp->th_off) << 2);
1617 if (cmdlen == 1) {
1618 match = (cmd->arg1 == x);
1619 break;
1620 }
1621 /* otherwise we have ranges */
1622 p = ((ipfw_insn_u16 *)cmd)->ports;
1623 i = cmdlen - 1;
1624 for (; !match && i>0; i--, p += 2)
1625 match = (x >= p[0] && x <= p[1]);
1626 }
1627 break;
1628
1629 case O_TCPFLAGS:
1630 match = (proto == IPPROTO_TCP && offset == 0 &&
1631 flags_match(cmd, TCP(ulp)->th_flags));
1632 break;
1633
1634 case O_TCPOPTS:
1635 PULLUP_LEN(hlen, ulp, (TCP(ulp)->th_off << 2));
1636 match = (proto == IPPROTO_TCP && offset == 0 &&
1637 tcpopts_match(TCP(ulp), cmd));
1638 break;
1639
1640 case O_TCPSEQ:
1641 match = (proto == IPPROTO_TCP && offset == 0 &&
1642 ((ipfw_insn_u32 *)cmd)->d[0] ==
1643 TCP(ulp)->th_seq);
1644 break;
1645
1646 case O_TCPACK:
1647 match = (proto == IPPROTO_TCP && offset == 0 &&
1648 ((ipfw_insn_u32 *)cmd)->d[0] ==
1649 TCP(ulp)->th_ack);
1650 break;
1651
1652 case O_TCPWIN:
1653 match = (proto == IPPROTO_TCP && offset == 0 &&
1654 cmd->arg1 == TCP(ulp)->th_win);
1655 break;
1656
1657 case O_ESTAB:
1658 /* reject packets which have SYN only */
1659 /* XXX should i also check for TH_ACK ? */
1660 match = (proto == IPPROTO_TCP && offset == 0 &&
1661 (TCP(ulp)->th_flags &
1662 (TH_RST | TH_ACK | TH_SYN)) != TH_SYN);
1663 break;
1664
1665 case O_ALTQ: {
1666 struct pf_mtag *at;
1667 ipfw_insn_altq *altq = (ipfw_insn_altq *)cmd;
1668
1669 match = 1;
1670 at = pf_find_mtag(m);
1671 if (at != NULL && at->qid != 0)
1672 break;
1673 at = pf_get_mtag(m);
1674 if (at == NULL) {
1675 /*
1676 * Let the packet fall back to the
1677 * default ALTQ.
1678 */
1679 break;
1680 }
1681 at->qid = altq->qid;
1682 at->hdr = ip;
1683 break;
1684 }
1685
1686 case O_LOG:
1687 ipfw_log(f, hlen, args, m,
1688 oif, offset | ip6f_mf, tablearg, ip);
1689 match = 1;
1690 break;
1691
1692 case O_PROB:
1693 match = (random()<((ipfw_insn_u32 *)cmd)->d[0]);
1694 break;
1695
1696 case O_VERREVPATH:
1697 /* Outgoing packets automatically pass/match */
1698 match = ((oif != NULL) ||
1699 (m->m_pkthdr.rcvif == NULL) ||
1700 (
1701#ifdef INET6
1702 is_ipv6 ?
1703 verify_path6(&(args->f_id.src_ip6),
1704 m->m_pkthdr.rcvif) :
1705#endif
1706 verify_path(src_ip, m->m_pkthdr.rcvif,
1707 args->f_id.fib)));
1708 break;
1709
1710 case O_VERSRCREACH:
1711 /* Outgoing packets automatically pass/match */
1712 match = (hlen > 0 && ((oif != NULL) ||
1713#ifdef INET6
1714 is_ipv6 ?
1715 verify_path6(&(args->f_id.src_ip6),
1716 NULL) :
1717#endif
1718 verify_path(src_ip, NULL, args->f_id.fib)));
1719 break;
1720
1721 case O_ANTISPOOF:
1722 /* Outgoing packets automatically pass/match */
1723 if (oif == NULL && hlen > 0 &&
1724 ( (is_ipv4 && in_localaddr(src_ip))
1725#ifdef INET6
1726 || (is_ipv6 &&
1727 in6_localaddr(&(args->f_id.src_ip6)))
1728#endif
1729 ))
1730 match =
1731#ifdef INET6
1732 is_ipv6 ? verify_path6(
1733 &(args->f_id.src_ip6),
1734 m->m_pkthdr.rcvif) :
1735#endif
1736 verify_path(src_ip,
1737 m->m_pkthdr.rcvif,
1738 args->f_id.fib);
1739 else
1740 match = 1;
1741 break;
1742
1743 case O_IPSEC:
1744#ifdef IPSEC
1745 match = (m_tag_find(m,
1746 PACKET_TAG_IPSEC_IN_DONE, NULL) != NULL);
1747#endif
1748 /* otherwise no match */
1749 break;
1750
1751#ifdef INET6
1752 case O_IP6_SRC:
1753 match = is_ipv6 &&
1754 IN6_ARE_ADDR_EQUAL(&args->f_id.src_ip6,
1755 &((ipfw_insn_ip6 *)cmd)->addr6);
1756 break;
1757
1758 case O_IP6_DST:
1759 match = is_ipv6 &&
1760 IN6_ARE_ADDR_EQUAL(&args->f_id.dst_ip6,
1761 &((ipfw_insn_ip6 *)cmd)->addr6);
1762 break;
1763 case O_IP6_SRC_MASK:
1764 case O_IP6_DST_MASK:
1765 if (is_ipv6) {
1766 int i = cmdlen - 1;
1767 struct in6_addr p;
1768 struct in6_addr *d =
1769 &((ipfw_insn_ip6 *)cmd)->addr6;
1770
1771 for (; !match && i > 0; d += 2,
1772 i -= F_INSN_SIZE(struct in6_addr)
1773 * 2) {
1774 p = (cmd->opcode ==
1775 O_IP6_SRC_MASK) ?
1776 args->f_id.src_ip6:
1777 args->f_id.dst_ip6;
1778 APPLY_MASK(&p, &d[1]);
1779 match =
1780 IN6_ARE_ADDR_EQUAL(&d[0],
1781 &p);
1782 }
1783 }
1784 break;
1785
1786 case O_FLOW6ID:
1787 match = is_ipv6 &&
1788 flow6id_match(args->f_id.flow_id6,
1789 (ipfw_insn_u32 *) cmd);
1790 break;
1791
1792 case O_EXT_HDR:
1793 match = is_ipv6 &&
1794 (ext_hd & ((ipfw_insn *) cmd)->arg1);
1795 break;
1796
1797 case O_IP6:
1798 match = is_ipv6;
1799 break;
1800#endif
1801
1802 case O_IP4:
1803 match = is_ipv4;
1804 break;
1805
1806 case O_TAG: {
1807 struct m_tag *mtag;
1808 uint32_t tag = (cmd->arg1 == IP_FW_TABLEARG) ?
1809 tablearg : cmd->arg1;
1810
1811 /* Packet is already tagged with this tag? */
1812 mtag = m_tag_locate(m, MTAG_IPFW, tag, NULL);
1813
1814 /* We have `untag' action when F_NOT flag is
1815 * present. And we must remove this mtag from
1816 * mbuf and reset `match' to zero (`match' will
1817 * be inversed later).
1818 * Otherwise we should allocate new mtag and
1819 * push it into mbuf.
1820 */
1821 if (cmd->len & F_NOT) { /* `untag' action */
1822 if (mtag != NULL)
1823 m_tag_delete(m, mtag);
1824 match = 0;
1825 } else {
1826 if (mtag == NULL) {
1827 mtag = m_tag_alloc( MTAG_IPFW,
1828 tag, 0, M_NOWAIT);
1829 if (mtag != NULL)
1830 m_tag_prepend(m, mtag);
1831 }
1832 match = 1;
1833 }
1834 break;
1835 }
1836
1837 case O_FIB: /* try match the specified fib */
1838 if (args->f_id.fib == cmd->arg1)
1839 match = 1;
1840 break;
1841
1842 case O_SOCKARG: {
1843 struct inpcb *inp = args->inp;
1844 struct inpcbinfo *pi;
1845
1846 if (is_ipv6) /* XXX can we remove this ? */
1847 break;
1848
1849 if (proto == IPPROTO_TCP)
1850 pi = &V_tcbinfo;
1851 else if (proto == IPPROTO_UDP)
1852 pi = &V_udbinfo;
1853 else
1854 break;
1855
1856 /*
1857 * XXXRW: so_user_cookie should almost
1858 * certainly be inp_user_cookie?
1859 */
1860
1861 /* For incomming packet, lookup up the
1862 inpcb using the src/dest ip/port tuple */
1863 if (inp == NULL) {
1864 inp = in_pcblookup(pi,
1865 src_ip, htons(src_port),
1866 dst_ip, htons(dst_port),
1867 INPLOOKUP_RLOCKPCB, NULL);
1868 if (inp != NULL) {
1869 tablearg =
1870 inp->inp_socket->so_user_cookie;
1871 if (tablearg)
1872 match = 1;
1873 INP_RUNLOCK(inp);
1874 }
1875 } else {
1876 if (inp->inp_socket) {
1877 tablearg =
1878 inp->inp_socket->so_user_cookie;
1879 if (tablearg)
1880 match = 1;
1881 }
1882 }
1883 break;
1884 }
1885
1886 case O_TAGGED: {
1887 struct m_tag *mtag;
1888 uint32_t tag = (cmd->arg1 == IP_FW_TABLEARG) ?
1889 tablearg : cmd->arg1;
1890
1891 if (cmdlen == 1) {
1892 match = m_tag_locate(m, MTAG_IPFW,
1893 tag, NULL) != NULL;
1894 break;
1895 }
1896
1897 /* we have ranges */
1898 for (mtag = m_tag_first(m);
1899 mtag != NULL && !match;
1900 mtag = m_tag_next(m, mtag)) {
1901 uint16_t *p;
1902 int i;
1903
1904 if (mtag->m_tag_cookie != MTAG_IPFW)
1905 continue;
1906
1907 p = ((ipfw_insn_u16 *)cmd)->ports;
1908 i = cmdlen - 1;
1909 for(; !match && i > 0; i--, p += 2)
1910 match =
1911 mtag->m_tag_id >= p[0] &&
1912 mtag->m_tag_id <= p[1];
1913 }
1914 break;
1915 }
1916
1917 /*
1918 * The second set of opcodes represents 'actions',
1919 * i.e. the terminal part of a rule once the packet
1920 * matches all previous patterns.
1921 * Typically there is only one action for each rule,
1922 * and the opcode is stored at the end of the rule
1923 * (but there are exceptions -- see below).
1924 *
1925 * In general, here we set retval and terminate the
1926 * outer loop (would be a 'break 3' in some language,
1927 * but we need to set l=0, done=1)
1928 *
1929 * Exceptions:
1930 * O_COUNT and O_SKIPTO actions:
1931 * instead of terminating, we jump to the next rule
1932 * (setting l=0), or to the SKIPTO target (setting
1933 * f/f_len, cmd and l as needed), respectively.
1934 *
1935 * O_TAG, O_LOG and O_ALTQ action parameters:
1936 * perform some action and set match = 1;
1937 *
1938 * O_LIMIT and O_KEEP_STATE: these opcodes are
1939 * not real 'actions', and are stored right
1940 * before the 'action' part of the rule.
1941 * These opcodes try to install an entry in the
1942 * state tables; if successful, we continue with
1943 * the next opcode (match=1; break;), otherwise
1944 * the packet must be dropped (set retval,
1945 * break loops with l=0, done=1)
1946 *
1947 * O_PROBE_STATE and O_CHECK_STATE: these opcodes
1948 * cause a lookup of the state table, and a jump
1949 * to the 'action' part of the parent rule
1950 * if an entry is found, or
1951 * (CHECK_STATE only) a jump to the next rule if
1952 * the entry is not found.
1953 * The result of the lookup is cached so that
1954 * further instances of these opcodes become NOPs.
1955 * The jump to the next rule is done by setting
1956 * l=0, cmdlen=0.
1957 */
1958 case O_LIMIT:
1959 case O_KEEP_STATE:
1960 if (ipfw_install_state(f,
1961 (ipfw_insn_limit *)cmd, args, tablearg)) {
1962 /* error or limit violation */
1963 retval = IP_FW_DENY;
1964 l = 0; /* exit inner loop */
1965 done = 1; /* exit outer loop */
1966 }
1967 match = 1;
1968 break;
1969
1970 case O_PROBE_STATE:
1971 case O_CHECK_STATE:
1972 /*
1973 * dynamic rules are checked at the first
1974 * keep-state or check-state occurrence,
1975 * with the result being stored in dyn_dir.
1976 * The compiler introduces a PROBE_STATE
1977 * instruction for us when we have a
1978 * KEEP_STATE (because PROBE_STATE needs
1979 * to be run first).
1980 */
1981 if (dyn_dir == MATCH_UNKNOWN &&
1982 (q = ipfw_lookup_dyn_rule(&args->f_id,
1983 &dyn_dir, proto == IPPROTO_TCP ?
1984 TCP(ulp) : NULL))
1985 != NULL) {
1986 /*
1987 * Found dynamic entry, update stats
1988 * and jump to the 'action' part of
1989 * the parent rule by setting
1990 * f, cmd, l and clearing cmdlen.
1991 */
1992 q->pcnt++;
1993 q->bcnt += pktlen;
1994 /* XXX we would like to have f_pos
1995 * readily accessible in the dynamic
1996 * rule, instead of having to
1997 * lookup q->rule.
1998 */
1999 f = q->rule;
2000 f_pos = ipfw_find_rule(chain,
2001 f->rulenum, f->id);
2002 cmd = ACTION_PTR(f);
2003 l = f->cmd_len - f->act_ofs;
2004 ipfw_dyn_unlock();
2005 cmdlen = 0;
2006 match = 1;
2007 break;
2008 }
2009 /*
2010 * Dynamic entry not found. If CHECK_STATE,
2011 * skip to next rule, if PROBE_STATE just
2012 * ignore and continue with next opcode.
2013 */
2014 if (cmd->opcode == O_CHECK_STATE)
2015 l = 0; /* exit inner loop */
2016 match = 1;
2017 break;
2018
2019 case O_ACCEPT:
2020 retval = 0; /* accept */
2021 l = 0; /* exit inner loop */
2022 done = 1; /* exit outer loop */
2023 break;
2024
2025 case O_PIPE:
2026 case O_QUEUE:
2027 set_match(args, f_pos, chain);
2028 args->rule.info = (cmd->arg1 == IP_FW_TABLEARG) ?
2029 tablearg : cmd->arg1;
2030 if (cmd->opcode == O_PIPE)
2031 args->rule.info |= IPFW_IS_PIPE;
2032 if (V_fw_one_pass)
2033 args->rule.info |= IPFW_ONEPASS;
2034 retval = IP_FW_DUMMYNET;
2035 l = 0; /* exit inner loop */
2036 done = 1; /* exit outer loop */
2037 break;
2038
2039 case O_DIVERT:
2040 case O_TEE:
2041 if (args->eh) /* not on layer 2 */
2042 break;
2043 /* otherwise this is terminal */
2044 l = 0; /* exit inner loop */
2045 done = 1; /* exit outer loop */
2046 retval = (cmd->opcode == O_DIVERT) ?
2047 IP_FW_DIVERT : IP_FW_TEE;
2048 set_match(args, f_pos, chain);
2049 args->rule.info = (cmd->arg1 == IP_FW_TABLEARG) ?
2050 tablearg : cmd->arg1;
2051 break;
2052
2053 case O_COUNT:
2054 f->pcnt++; /* update stats */
2055 f->bcnt += pktlen;
2056 f->timestamp = time_uptime;
2057 l = 0; /* exit inner loop */
2058 break;
2059
2060 case O_SKIPTO:
2061 f->pcnt++; /* update stats */
2062 f->bcnt += pktlen;
2063 f->timestamp = time_uptime;
2064 /* If possible use cached f_pos (in f->next_rule),
2065 * whose version is written in f->next_rule
2066 * (horrible hacks to avoid changing the ABI).
2067 */
2068 if (cmd->arg1 != IP_FW_TABLEARG &&
2069 (uintptr_t)f->x_next == chain->id) {
2070 f_pos = (uintptr_t)f->next_rule;
2071 } else {
2072 int i = (cmd->arg1 == IP_FW_TABLEARG) ?
2073 tablearg : cmd->arg1;
2074 /* make sure we do not jump backward */
2075 if (i <= f->rulenum)
2076 i = f->rulenum + 1;
2077 f_pos = ipfw_find_rule(chain, i, 0);
2078 /* update the cache */
2079 if (cmd->arg1 != IP_FW_TABLEARG) {
2080 f->next_rule =
2081 (void *)(uintptr_t)f_pos;
2082 f->x_next =
2083 (void *)(uintptr_t)chain->id;
2084 }
2085 }
2086 /*
2087 * Skip disabled rules, and re-enter
2088 * the inner loop with the correct
2089 * f_pos, f, l and cmd.
2090 * Also clear cmdlen and skip_or
2091 */
2092 for (; f_pos < chain->n_rules - 1 &&
2093 (V_set_disable &
2094 (1 << chain->map[f_pos]->set));
2095 f_pos++)
2096 ;
2097 /* Re-enter the inner loop at the skipto rule. */
2098 f = chain->map[f_pos];
2099 l = f->cmd_len;
2100 cmd = f->cmd;
2101 match = 1;
2102 cmdlen = 0;
2103 skip_or = 0;
2104 continue;
2105 break; /* not reached */
2106
2107 case O_CALLRETURN: {
2108 /*
2109 * Implementation of `subroutine' call/return,
2110 * in the stack carried in an mbuf tag. This
2111 * is different from `skipto' in that any call
2112 * address is possible (`skipto' must prevent
2113 * backward jumps to avoid endless loops).
2114 * We have `return' action when F_NOT flag is
2115 * present. The `m_tag_id' field is used as
2116 * stack pointer.
2117 */
2118 struct m_tag *mtag;
2119 uint16_t jmpto, *stack;
2120
2121#define IS_CALL ((cmd->len & F_NOT) == 0)
2122#define IS_RETURN ((cmd->len & F_NOT) != 0)
2123 /*
2124 * Hand-rolled version of m_tag_locate() with
2125 * wildcard `type'.
2126 * If not already tagged, allocate new tag.
2127 */
2128 mtag = m_tag_first(m);
2129 while (mtag != NULL) {
2130 if (mtag->m_tag_cookie ==
2131 MTAG_IPFW_CALL)
2132 break;
2133 mtag = m_tag_next(m, mtag);
2134 }
2135 if (mtag == NULL && IS_CALL) {
2136 mtag = m_tag_alloc(MTAG_IPFW_CALL, 0,
2137 IPFW_CALLSTACK_SIZE *
2138 sizeof(uint16_t), M_NOWAIT);
2139 if (mtag != NULL)
2140 m_tag_prepend(m, mtag);
2141 }
2142
2143 /*
2144 * On error both `call' and `return' just
2145 * continue with next rule.
2146 */
2147 if (IS_RETURN && (mtag == NULL ||
2148 mtag->m_tag_id == 0)) {
2149 l = 0; /* exit inner loop */
2150 break;
2151 }
2152 if (IS_CALL && (mtag == NULL ||
2153 mtag->m_tag_id >= IPFW_CALLSTACK_SIZE)) {
2154 printf("ipfw: call stack error, "
2155 "go to next rule\n");
2156 l = 0; /* exit inner loop */
2157 break;
2158 }
2159
2160 f->pcnt++; /* update stats */
2161 f->bcnt += pktlen;
2162 f->timestamp = time_uptime;
2163 stack = (uint16_t *)(mtag + 1);
2164
2165 /*
2166 * The `call' action may use cached f_pos
2167 * (in f->next_rule), whose version is written
2168 * in f->next_rule.
2169 * The `return' action, however, doesn't have
2170 * fixed jump address in cmd->arg1 and can't use
2171 * cache.
2172 */
2173 if (IS_CALL) {
2174 stack[mtag->m_tag_id] = f->rulenum;
2175 mtag->m_tag_id++;
2176 if (cmd->arg1 != IP_FW_TABLEARG &&
2177 (uintptr_t)f->x_next == chain->id) {
2178 f_pos = (uintptr_t)f->next_rule;
2179 } else {
2180 jmpto = (cmd->arg1 ==
2181 IP_FW_TABLEARG) ? tablearg:
2182 cmd->arg1;
2183 f_pos = ipfw_find_rule(chain,
2184 jmpto, 0);
2185 /* update the cache */
2186 if (cmd->arg1 !=
2187 IP_FW_TABLEARG) {
2188 f->next_rule =
2189 (void *)(uintptr_t)
2190 f_pos;
2191 f->x_next =
2192 (void *)(uintptr_t)
2193 chain->id;
2194 }
2195 }
2196 } else { /* `return' action */
2197 mtag->m_tag_id--;
2198 jmpto = stack[mtag->m_tag_id] + 1;
2199 f_pos = ipfw_find_rule(chain, jmpto, 0);
2200 }
2201
2202 /*
2203 * Skip disabled rules, and re-enter
2204 * the inner loop with the correct
2205 * f_pos, f, l and cmd.
2206 * Also clear cmdlen and skip_or
2207 */
2208 for (; f_pos < chain->n_rules - 1 &&
2209 (V_set_disable &
2210 (1 << chain->map[f_pos]->set)); f_pos++)
2211 ;
2212 /* Re-enter the inner loop at the dest rule. */
2213 f = chain->map[f_pos];
2214 l = f->cmd_len;
2215 cmd = f->cmd;
2216 cmdlen = 0;
2217 skip_or = 0;
2218 continue;
2219 break; /* NOTREACHED */
2220 }
2221#undef IS_CALL
2222#undef IS_RETURN
2223
2224 case O_REJECT:
2225 /*
2226 * Drop the packet and send a reject notice
2227 * if the packet is not ICMP (or is an ICMP
2228 * query), and it is not multicast/broadcast.
2229 */
2230 if (hlen > 0 && is_ipv4 && offset == 0 &&
2231 (proto != IPPROTO_ICMP ||
2232 is_icmp_query(ICMP(ulp))) &&
2233 !(m->m_flags & (M_BCAST|M_MCAST)) &&
2234 !IN_MULTICAST(ntohl(dst_ip.s_addr))) {
2235 send_reject(args, cmd->arg1, iplen, ip);
2236 m = args->m;
2237 }
2238 /* FALLTHROUGH */
2239#ifdef INET6
2240 case O_UNREACH6:
2241 if (hlen > 0 && is_ipv6 &&
2242 ((offset & IP6F_OFF_MASK) == 0) &&
2243 (proto != IPPROTO_ICMPV6 ||
2244 (is_icmp6_query(icmp6_type) == 1)) &&
2245 !(m->m_flags & (M_BCAST|M_MCAST)) &&
2246 !IN6_IS_ADDR_MULTICAST(&args->f_id.dst_ip6)) {
2247 send_reject6(
2248 args, cmd->arg1, hlen,
2249 (struct ip6_hdr *)ip);
2250 m = args->m;
2251 }
2252 /* FALLTHROUGH */
2253#endif
2254 case O_DENY:
2255 retval = IP_FW_DENY;
2256 l = 0; /* exit inner loop */
2257 done = 1; /* exit outer loop */
2258 break;
2259
2260 case O_FORWARD_IP:
2261 if (args->eh) /* not valid on layer2 pkts */
2262 break;
2263 if (q == NULL || q->rule != f ||
2264 dyn_dir == MATCH_FORWARD) {
2265 struct sockaddr_in *sa;
2266 sa = &(((ipfw_insn_sa *)cmd)->sa);
2267 if (sa->sin_addr.s_addr == INADDR_ANY) {
2268 bcopy(sa, &args->hopstore,
2269 sizeof(*sa));
2270 args->hopstore.sin_addr.s_addr =
2271 htonl(tablearg);
2272 args->next_hop = &args->hopstore;
2273 } else {
2274 args->next_hop = sa;
2275 }
2276 }
2277 retval = IP_FW_PASS;
2278 l = 0; /* exit inner loop */
2279 done = 1; /* exit outer loop */
2280 break;
2281
2282#ifdef INET6
2283 case O_FORWARD_IP6:
2284 if (args->eh) /* not valid on layer2 pkts */
2285 break;
2286 if (q == NULL || q->rule != f ||
2287 dyn_dir == MATCH_FORWARD) {
2288 struct sockaddr_in6 *sin6;
2289
2290 sin6 = &(((ipfw_insn_sa6 *)cmd)->sa);
2291 args->next_hop6 = sin6;
2292 }
2293 retval = IP_FW_PASS;
2294 l = 0; /* exit inner loop */
2295 done = 1; /* exit outer loop */
2296 break;
2297#endif
2298
2299 case O_NETGRAPH:
2300 case O_NGTEE:
2301 set_match(args, f_pos, chain);
2302 args->rule.info = (cmd->arg1 == IP_FW_TABLEARG) ?
2303 tablearg : cmd->arg1;
2304 if (V_fw_one_pass)
2305 args->rule.info |= IPFW_ONEPASS;
2306 retval = (cmd->opcode == O_NETGRAPH) ?
2307 IP_FW_NETGRAPH : IP_FW_NGTEE;
2308 l = 0; /* exit inner loop */
2309 done = 1; /* exit outer loop */
2310 break;
2311
2312 case O_SETFIB: {
2313 uint32_t fib;
2314
2315 f->pcnt++; /* update stats */
2316 f->bcnt += pktlen;
2317 f->timestamp = time_uptime;
2318 fib = (cmd->arg1 == IP_FW_TABLEARG) ? tablearg:
2319 cmd->arg1;
2320 if (fib >= rt_numfibs)
2321 fib = 0;
2322 M_SETFIB(m, fib);
2323 args->f_id.fib = fib;
2324 l = 0; /* exit inner loop */
2325 break;
2326 }
2327
2328 case O_NAT:
2329 if (!IPFW_NAT_LOADED) {
2330 retval = IP_FW_DENY;
2331 } else {
2332 struct cfg_nat *t;
2333 int nat_id;
2334
2335 set_match(args, f_pos, chain);
2336 /* Check if this is 'global' nat rule */
2337 if (cmd->arg1 == 0) {
2338 retval = ipfw_nat_ptr(args, NULL, m);
2339 l = 0;
2340 done = 1;
2341 break;
2342 }
2343 t = ((ipfw_insn_nat *)cmd)->nat;
2344 if (t == NULL) {
2345 nat_id = (cmd->arg1 == IP_FW_TABLEARG) ?
2346 tablearg : cmd->arg1;
2347 t = (*lookup_nat_ptr)(&chain->nat, nat_id);
2348
2349 if (t == NULL) {
2350 retval = IP_FW_DENY;
2351 l = 0; /* exit inner loop */
2352 done = 1; /* exit outer loop */
2353 break;
2354 }
2355 if (cmd->arg1 != IP_FW_TABLEARG)
2356 ((ipfw_insn_nat *)cmd)->nat = t;
2357 }
2358 retval = ipfw_nat_ptr(args, t, m);
2359 }
2360 l = 0; /* exit inner loop */
2361 done = 1; /* exit outer loop */
2362 break;
2363
2364 case O_REASS: {
2365 int ip_off;
2366
2367 f->pcnt++;
2368 f->bcnt += pktlen;
2369 l = 0; /* in any case exit inner loop */
2370 ip_off = ntohs(ip->ip_off);
2371
2372 /* if not fragmented, go to next rule */
2373 if ((ip_off & (IP_MF | IP_OFFMASK)) == 0)
2374 break;
2375 /*
2376 * ip_reass() expects len & off in host
2377 * byte order.
2378 */
2379 SET_HOST_IPLEN(ip);
2380
2381 args->m = m = ip_reass(m);
2382
2383 /*
2384 * do IP header checksum fixup.
2385 */
2386 if (m == NULL) { /* fragment got swallowed */
2387 retval = IP_FW_DENY;
2388 } else { /* good, packet complete */
2389 int hlen;
2390
2391 ip = mtod(m, struct ip *);
2392 hlen = ip->ip_hl << 2;
2393 SET_NET_IPLEN(ip);
2394 ip->ip_sum = 0;
2395 if (hlen == sizeof(struct ip))
2396 ip->ip_sum = in_cksum_hdr(ip);
2397 else
2398 ip->ip_sum = in_cksum(m, hlen);
2399 retval = IP_FW_REASS;
2400 set_match(args, f_pos, chain);
2401 }
2402 done = 1; /* exit outer loop */
2403 break;
2404 }
2405
2406 default:
2407 panic("-- unknown opcode %d\n", cmd->opcode);
2408 } /* end of switch() on opcodes */
2409 /*
2410 * if we get here with l=0, then match is irrelevant.
2411 */
2412
2413 if (cmd->len & F_NOT)
2414 match = !match;
2415
2416 if (match) {
2417 if (cmd->len & F_OR)
2418 skip_or = 1;
2419 } else {
2420 if (!(cmd->len & F_OR)) /* not an OR block, */
2421 break; /* try next rule */
2422 }
2423
2424 } /* end of inner loop, scan opcodes */
2425#undef PULLUP_LEN
2426
2427 if (done)
2428 break;
2429
2430/* next_rule:; */ /* try next rule */
2431
2432 } /* end of outer for, scan rules */
2433
2434 if (done) {
2435 struct ip_fw *rule = chain->map[f_pos];
2436 /* Update statistics */
2437 rule->pcnt++;
2438 rule->bcnt += pktlen;
2439 rule->timestamp = time_uptime;
2440 } else {
2441 retval = IP_FW_DENY;
2442 printf("ipfw: ouch!, skip past end of rules, denying packet\n");
2443 }
2444 IPFW_RUNLOCK(chain);
2445#ifdef __FreeBSD__
2446 if (ucred_cache != NULL)
2447 crfree(ucred_cache);
2448#endif
2449 return (retval);
2450
2451pullup_failed:
2452 if (V_fw_verbose)
2453 printf("ipfw: pullup failed\n");
2454 return (IP_FW_DENY);
2455}
2456
2457/*
2458 * Module and VNET glue
2459 */
2460
2461/*
2462 * Stuff that must be initialised only on boot or module load
2463 */
2464static int
2465ipfw_init(void)
2466{
2467 int error = 0;
2468
2469 ipfw_dyn_attach();
2470 /*
2471 * Only print out this stuff the first time around,
2472 * when called from the sysinit code.
2473 */
2474 printf("ipfw2 "
2475#ifdef INET6
2476 "(+ipv6) "
2477#endif
2478 "initialized, divert %s, nat %s, "
2479 "rule-based forwarding "
2480#ifdef IPFIREWALL_FORWARD
2481 "enabled, "
2482#else
2483 "disabled, "
2484#endif
2485 "default to %s, logging ",
2486#ifdef IPDIVERT
2487 "enabled",
2488#else
2489 "loadable",
2490#endif
2491#ifdef IPFIREWALL_NAT
2492 "enabled",
2493#else
2494 "loadable",
2495#endif
2496 default_to_accept ? "accept" : "deny");
2497
2498 /*
2499 * Note: V_xxx variables can be accessed here but the vnet specific
2500 * initializer may not have been called yet for the VIMAGE case.
2501 * Tuneables will have been processed. We will print out values for
2502 * the default vnet.
2503 * XXX This should all be rationalized AFTER 8.0
2504 */
2505 if (V_fw_verbose == 0)
2506 printf("disabled\n");
2507 else if (V_verbose_limit == 0)
2508 printf("unlimited\n");
2509 else
2510 printf("limited to %d packets/entry by default\n",
2511 V_verbose_limit);
2512
2513 ipfw_log_bpf(1); /* init */
2514 return (error);
2515}
2516
2517/*
2518 * Called for the removal of the last instance only on module unload.
2519 */
2520static void
2521ipfw_destroy(void)
2522{
2523
2524 ipfw_log_bpf(0); /* uninit */
2525 ipfw_dyn_detach();
2526 printf("IP firewall unloaded\n");
2527}
2528
2529/*
2530 * Stuff that must be initialized for every instance
2531 * (including the first of course).
2532 */
2533static int
2534vnet_ipfw_init(const void *unused)
2535{
2536 int error;
2537 struct ip_fw *rule = NULL;
2538 struct ip_fw_chain *chain;
2539
2540 chain = &V_layer3_chain;
2541
2542 /* First set up some values that are compile time options */
2543 V_autoinc_step = 100; /* bounded to 1..1000 in add_rule() */
2544 V_fw_deny_unknown_exthdrs = 1;
2545#ifdef IPFIREWALL_VERBOSE
2546 V_fw_verbose = 1;
2547#endif
2548#ifdef IPFIREWALL_VERBOSE_LIMIT
2549 V_verbose_limit = IPFIREWALL_VERBOSE_LIMIT;
2550#endif
2551#ifdef IPFIREWALL_NAT
2552 LIST_INIT(&chain->nat);
2553#endif
2554
2555 /* insert the default rule and create the initial map */
2556 chain->n_rules = 1;
2557 chain->static_len = sizeof(struct ip_fw);
2558 chain->map = malloc(sizeof(struct ip_fw *), M_IPFW, M_NOWAIT | M_ZERO);
2559 if (chain->map)
2560 rule = malloc(chain->static_len, M_IPFW, M_NOWAIT | M_ZERO);
2561 if (rule == NULL) {
2562 if (chain->map)
2563 free(chain->map, M_IPFW);
2564 printf("ipfw2: ENOSPC initializing default rule "
2565 "(support disabled)\n");
2566 return (ENOSPC);
2567 }
2568 error = ipfw_init_tables(chain);
2569 if (error) {
2570 panic("init_tables"); /* XXX Marko fix this ! */
2571 }
2572
2573 /* fill and insert the default rule */
2574 rule->act_ofs = 0;
2575 rule->rulenum = IPFW_DEFAULT_RULE;
2576 rule->cmd_len = 1;
2577 rule->set = RESVD_SET;
2578 rule->cmd[0].len = 1;
2579 rule->cmd[0].opcode = default_to_accept ? O_ACCEPT : O_DENY;
2580 chain->rules = chain->default_rule = chain->map[0] = rule;
2581 chain->id = rule->id = 1;
2582
2583 IPFW_LOCK_INIT(chain);
2584 ipfw_dyn_init();
2585
2586 /* First set up some values that are compile time options */
2587 V_ipfw_vnet_ready = 1; /* Open for business */
2588
2589 /*
2590 * Hook the sockopt handler, and the layer2 (V_ip_fw_chk_ptr)
2591 * and pfil hooks for ipv4 and ipv6. Even if the latter two fail
2592 * we still keep the module alive because the sockopt and
2593 * layer2 paths are still useful.
2594 * ipfw[6]_hook return 0 on success, ENOENT on failure,
2595 * so we can ignore the exact return value and just set a flag.
2596 *
2597 * Note that V_fw[6]_enable are manipulated by a SYSCTL_PROC so
2598 * changes in the underlying (per-vnet) variables trigger
2599 * immediate hook()/unhook() calls.
2600 * In layer2 we have the same behaviour, except that V_ether_ipfw
2601 * is checked on each packet because there are no pfil hooks.
2602 */
2603 V_ip_fw_ctl_ptr = ipfw_ctl;
2604 V_ip_fw_chk_ptr = ipfw_chk;
2605 error = ipfw_attach_hooks(1);
2606 return (error);
2607}
2608
2609/*
2610 * Called for the removal of each instance.
2611 */
2612static int
2613vnet_ipfw_uninit(const void *unused)
2614{
2615 struct ip_fw *reap, *rule;
2616 struct ip_fw_chain *chain = &V_layer3_chain;
2617 int i;
2618
2619 V_ipfw_vnet_ready = 0; /* tell new callers to go away */
2620 /*
2621 * disconnect from ipv4, ipv6, layer2 and sockopt.
2622 * Then grab, release and grab again the WLOCK so we make
2623 * sure the update is propagated and nobody will be in.
2624 */
2625 (void)ipfw_attach_hooks(0 /* detach */);
2626 V_ip_fw_chk_ptr = NULL;
2627 V_ip_fw_ctl_ptr = NULL;
2628 IPFW_UH_WLOCK(chain);
2629 IPFW_UH_WUNLOCK(chain);
2630 IPFW_UH_WLOCK(chain);
2631
2632 IPFW_WLOCK(chain);
2633 IPFW_WUNLOCK(chain);
2634 IPFW_WLOCK(chain);
2635
2636 ipfw_dyn_uninit(0); /* run the callout_drain */
2637 ipfw_destroy_tables(chain);
2638 reap = NULL;
2639 for (i = 0; i < chain->n_rules; i++) {
2640 rule = chain->map[i];
2641 rule->x_next = reap;
2642 reap = rule;
2643 }
2644 if (chain->map)
2645 free(chain->map, M_IPFW);
2646 IPFW_WUNLOCK(chain);
2647 IPFW_UH_WUNLOCK(chain);
2648 if (reap != NULL)
2649 ipfw_reap_rules(reap);
2650 IPFW_LOCK_DESTROY(chain);
2651 ipfw_dyn_uninit(1); /* free the remaining parts */
2652 return 0;
2653}
2654
2655/*
2656 * Module event handler.
2657 * In general we have the choice of handling most of these events by the
2658 * event handler or by the (VNET_)SYS(UN)INIT handlers. I have chosen to
2659 * use the SYSINIT handlers as they are more capable of expressing the
2660 * flow of control during module and vnet operations, so this is just
2661 * a skeleton. Note there is no SYSINIT equivalent of the module
2662 * SHUTDOWN handler, but we don't have anything to do in that case anyhow.
2663 */
2664static int
2665ipfw_modevent(module_t mod, int type, void *unused)
2666{
2667 int err = 0;
2668
2669 switch (type) {
2670 case MOD_LOAD:
2671 /* Called once at module load or
2672 * system boot if compiled in. */
2673 break;
2674 case MOD_QUIESCE:
2675 /* Called before unload. May veto unloading. */
2676 break;
2677 case MOD_UNLOAD:
2678 /* Called during unload. */
2679 break;
2680 case MOD_SHUTDOWN:
2681 /* Called during system shutdown. */
2682 break;
2683 default:
2684 err = EOPNOTSUPP;
2685 break;
2686 }
2687 return err;
2688}
2689
2690static moduledata_t ipfwmod = {
2691 "ipfw",
2692 ipfw_modevent,
2693 0
2694};
2695
2696/* Define startup order. */
2697#define IPFW_SI_SUB_FIREWALL SI_SUB_PROTO_IFATTACHDOMAIN
2698#define IPFW_MODEVENT_ORDER (SI_ORDER_ANY - 255) /* On boot slot in here. */
2699#define IPFW_MODULE_ORDER (IPFW_MODEVENT_ORDER + 1) /* A little later. */
2700#define IPFW_VNET_ORDER (IPFW_MODEVENT_ORDER + 2) /* Later still. */
2701
2702DECLARE_MODULE(ipfw, ipfwmod, IPFW_SI_SUB_FIREWALL, IPFW_MODEVENT_ORDER);
2703MODULE_VERSION(ipfw, 2);
2704/* should declare some dependencies here */
2705
2706/*
2707 * Starting up. Done in order after ipfwmod() has been called.
2708 * VNET_SYSINIT is also called for each existing vnet and each new vnet.
2709 */
2710SYSINIT(ipfw_init, IPFW_SI_SUB_FIREWALL, IPFW_MODULE_ORDER,
2711 ipfw_init, NULL);
2712VNET_SYSINIT(vnet_ipfw_init, IPFW_SI_SUB_FIREWALL, IPFW_VNET_ORDER,
2713 vnet_ipfw_init, NULL);
2714
2715/*
2716 * Closing up shop. These are done in REVERSE ORDER, but still
2717 * after ipfwmod() has been called. Not called on reboot.
2718 * VNET_SYSUNINIT is also called for each exiting vnet as it exits.
2719 * or when the module is unloaded.
2720 */
2721SYSUNINIT(ipfw_destroy, IPFW_SI_SUB_FIREWALL, IPFW_MODULE_ORDER,
2722 ipfw_destroy, NULL);
2723VNET_SYSUNINIT(vnet_ipfw_uninit, IPFW_SI_SUB_FIREWALL, IPFW_VNET_ORDER,
2724 vnet_ipfw_uninit, NULL);
2725/* end of file */