xref: /freebsd/sbin/pfctl/pfctl.c (revision 0fc3c29fb3dd6ab6436a78c502544ebf2cf63ee2)
1 /*	$OpenBSD: pfctl.c,v 1.278 2008/08/31 20:18:17 jmc Exp $ */
2 
3 /*-
4  * SPDX-License-Identifier: BSD-2-Clause
5  *
6  * Copyright (c) 2001 Daniel Hartmeier
7  * Copyright (c) 2002,2003 Henning Brauer
8  * All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  *
14  *    - Redistributions of source code must retain the above copyright
15  *      notice, this list of conditions and the following disclaimer.
16  *    - Redistributions in binary form must reproduce the above
17  *      copyright notice, this list of conditions and the following
18  *      disclaimer in the documentation and/or other materials provided
19  *      with the distribution.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
25  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
27  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
29  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
31  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32  * POSSIBILITY OF SUCH DAMAGE.
33  *
34  */
35 
36 #include <sys/cdefs.h>
37 #define PFIOC_USE_LATEST
38 
39 #include <sys/types.h>
40 #include <sys/ioctl.h>
41 #include <sys/socket.h>
42 #include <sys/stat.h>
43 #include <sys/endian.h>
44 
45 #include <net/if.h>
46 #include <netinet/in.h>
47 #include <net/pfvar.h>
48 #include <arpa/inet.h>
49 #include <net/altq/altq.h>
50 
51 #include <err.h>
52 #include <errno.h>
53 #include <fcntl.h>
54 #include <libpfctl.h>
55 #include <limits.h>
56 #include <netdb.h>
57 #include <stdint.h>
58 #include <stdio.h>
59 #include <stdlib.h>
60 #include <string.h>
61 #include <unistd.h>
62 
63 #include "pfctl_parser.h"
64 #include "pfctl.h"
65 
66 void	 usage(void);
67 int	 pfctl_enable(int, int);
68 int	 pfctl_disable(int, int);
69 int	 pfctl_clear_stats(struct pfctl_handle *, int);
70 int	 pfctl_get_skip_ifaces(void);
71 int	 pfctl_check_skip_ifaces(char *);
72 int	 pfctl_adjust_skip_ifaces(struct pfctl *);
73 int	 pfctl_clear_interface_flags(int, int);
74 int	 pfctl_flush_eth_rules(int, int, char *);
75 int	 pfctl_flush_rules(int, int, char *);
76 int	 pfctl_flush_nat(int, int, char *);
77 int	 pfctl_clear_altq(int, int);
78 int	 pfctl_clear_src_nodes(int, int);
79 int	 pfctl_clear_iface_states(int, const char *, int);
80 void	 pfctl_addrprefix(char *, struct pf_addr *);
81 int	 pfctl_kill_src_nodes(int, const char *, int);
82 int	 pfctl_net_kill_states(int, const char *, int);
83 int	 pfctl_gateway_kill_states(int, const char *, int);
84 int	 pfctl_label_kill_states(int, const char *, int);
85 int	 pfctl_id_kill_states(int, const char *, int);
86 void	 pfctl_init_options(struct pfctl *);
87 int	 pfctl_load_options(struct pfctl *);
88 int	 pfctl_load_limit(struct pfctl *, unsigned int, unsigned int);
89 int	 pfctl_load_timeout(struct pfctl *, unsigned int, unsigned int);
90 int	 pfctl_load_debug(struct pfctl *, unsigned int);
91 int	 pfctl_load_logif(struct pfctl *, char *);
92 int	 pfctl_load_hostid(struct pfctl *, u_int32_t);
93 int	 pfctl_load_reassembly(struct pfctl *, u_int32_t);
94 int	 pfctl_load_syncookies(struct pfctl *, u_int8_t);
95 int	 pfctl_get_pool(int, struct pfctl_pool *, u_int32_t, u_int32_t, int,
96 	    const char *, int);
97 void	 pfctl_print_eth_rule_counters(struct pfctl_eth_rule *, int);
98 void	 pfctl_print_rule_counters(struct pfctl_rule *, int);
99 int	 pfctl_show_eth_rules(int, char *, int, enum pfctl_show, char *, int, int);
100 int	 pfctl_show_rules(int, char *, int, enum pfctl_show, char *, int, int);
101 int	 pfctl_show_nat(int, const char *, int, char *, int, int);
102 int	 pfctl_show_src_nodes(int, int);
103 int	 pfctl_show_states(int, const char *, int);
104 int	 pfctl_show_status(int, int);
105 int	 pfctl_show_running(int);
106 int	 pfctl_show_timeouts(int, int);
107 int	 pfctl_show_limits(int, int);
108 void	 pfctl_debug(int, u_int32_t, int);
109 int	 pfctl_test_altqsupport(int, int);
110 int	 pfctl_show_anchors(int, int, char *);
111 int	 pfctl_show_eth_anchors(int, int, char *);
112 int	 pfctl_ruleset_trans(struct pfctl *, char *, struct pfctl_anchor *, bool);
113 int	 pfctl_eth_ruleset_trans(struct pfctl *, char *,
114 	    struct pfctl_eth_anchor *);
115 int	 pfctl_load_eth_ruleset(struct pfctl *, char *,
116 	    struct pfctl_eth_ruleset *, int);
117 int	 pfctl_load_eth_rule(struct pfctl *, char *, struct pfctl_eth_rule *,
118 	    int);
119 int	 pfctl_load_ruleset(struct pfctl *, char *,
120 		struct pfctl_ruleset *, int, int);
121 int	 pfctl_load_rule(struct pfctl *, char *, struct pfctl_rule *, int);
122 const char	*pfctl_lookup_option(char *, const char * const *);
123 
124 static struct pfctl_anchor_global	 pf_anchors;
125 struct pfctl_anchor	 pf_main_anchor;
126 struct pfctl_eth_anchor	 pf_eth_main_anchor;
127 static struct pfr_buffer skip_b;
128 
129 static const char	*clearopt;
130 static char		*rulesopt;
131 static const char	*showopt;
132 static const char	*debugopt;
133 static char		*anchoropt;
134 static const char	*optiopt = NULL;
135 static const char	*pf_device = PF_DEVICE;
136 static char		*ifaceopt;
137 static char		*tableopt;
138 static const char	*tblcmdopt;
139 static int		 src_node_killers;
140 static char		*src_node_kill[2];
141 static int		 state_killers;
142 static char		*state_kill[2];
143 int			 loadopt;
144 int			 altqsupport;
145 
146 int			 dev = -1;
147 struct pfctl_handle	*pfh = NULL;
148 static int		 first_title = 1;
149 static int		 labels = 0;
150 
151 #define INDENT(d, o)	do {						\
152 				if (o) {				\
153 					int i;				\
154 					for (i=0; i < d; i++)		\
155 						printf("  ");		\
156 				}					\
157 			} while (0);					\
158 
159 
160 static const struct {
161 	const char	*name;
162 	int		index;
163 } pf_limits[] = {
164 	{ "states",		PF_LIMIT_STATES },
165 	{ "src-nodes",		PF_LIMIT_SRC_NODES },
166 	{ "frags",		PF_LIMIT_FRAGS },
167 	{ "table-entries",	PF_LIMIT_TABLE_ENTRIES },
168 	{ NULL,			0 }
169 };
170 
171 struct pf_hint {
172 	const char	*name;
173 	int		timeout;
174 };
175 static const struct pf_hint pf_hint_normal[] = {
176 	{ "tcp.first",		2 * 60 },
177 	{ "tcp.opening",	30 },
178 	{ "tcp.established",	24 * 60 * 60 },
179 	{ "tcp.closing",	15 * 60 },
180 	{ "tcp.finwait",	45 },
181 	{ "tcp.closed",		90 },
182 	{ "tcp.tsdiff",		30 },
183 	{ NULL,			0 }
184 };
185 static const struct pf_hint pf_hint_satellite[] = {
186 	{ "tcp.first",		3 * 60 },
187 	{ "tcp.opening",	30 + 5 },
188 	{ "tcp.established",	24 * 60 * 60 },
189 	{ "tcp.closing",	15 * 60 + 5 },
190 	{ "tcp.finwait",	45 + 5 },
191 	{ "tcp.closed",		90 + 5 },
192 	{ "tcp.tsdiff",		60 },
193 	{ NULL,			0 }
194 };
195 static const struct pf_hint pf_hint_conservative[] = {
196 	{ "tcp.first",		60 * 60 },
197 	{ "tcp.opening",	15 * 60 },
198 	{ "tcp.established",	5 * 24 * 60 * 60 },
199 	{ "tcp.closing",	60 * 60 },
200 	{ "tcp.finwait",	10 * 60 },
201 	{ "tcp.closed",		3 * 60 },
202 	{ "tcp.tsdiff",		60 },
203 	{ NULL,			0 }
204 };
205 static const struct pf_hint pf_hint_aggressive[] = {
206 	{ "tcp.first",		30 },
207 	{ "tcp.opening",	5 },
208 	{ "tcp.established",	5 * 60 * 60 },
209 	{ "tcp.closing",	60 },
210 	{ "tcp.finwait",	30 },
211 	{ "tcp.closed",		30 },
212 	{ "tcp.tsdiff",		10 },
213 	{ NULL,			0 }
214 };
215 
216 static const struct {
217 	const char *name;
218 	const struct pf_hint *hint;
219 } pf_hints[] = {
220 	{ "normal",		pf_hint_normal },
221 	{ "satellite",		pf_hint_satellite },
222 	{ "high-latency",	pf_hint_satellite },
223 	{ "conservative",	pf_hint_conservative },
224 	{ "aggressive",		pf_hint_aggressive },
225 	{ NULL,			NULL }
226 };
227 
228 static const char * const clearopt_list[] = {
229 	"nat", "queue", "rules", "Sources",
230 	"states", "info", "Tables", "osfp", "all",
231 	"ethernet", NULL
232 };
233 
234 static const char * const showopt_list[] = {
235 	"ether", "nat", "queue", "rules", "Anchors", "Sources", "states",
236 	"info", "Interfaces", "labels", "timeouts", "memory", "Tables",
237 	"osfp", "Running", "all", "creatorids", NULL
238 };
239 
240 static const char * const tblcmdopt_list[] = {
241 	"kill", "flush", "add", "delete", "load", "replace", "show",
242 	"test", "zero", "expire", "reset", NULL
243 };
244 
245 static const char * const debugopt_list[] = {
246 	"none", "urgent", "misc", "loud", NULL
247 };
248 
249 static const char * const optiopt_list[] = {
250 	"none", "basic", "profile", NULL
251 };
252 
253 void
usage(void)254 usage(void)
255 {
256 	extern char *__progname;
257 
258 	fprintf(stderr,
259 "usage: %s [-AdeghMmNnOPqRrvz] [-a anchor] [-D macro=value] [-F modifier]\n"
260 	"\t[-f file] [-i interface] [-K host | network]\n"
261 	"\t[-k host | network | gateway | label | id] [-o level] [-p device]\n"
262 	"\t[-s modifier] [-t table -T command [address ...]] [-x level]\n",
263 	    __progname);
264 
265 	exit(1);
266 }
267 
268 /*
269  * Cache protocol number to name translations.
270  *
271  * Translation is performed a lot e.g., when dumping states and
272  * getprotobynumber is incredibly expensive.
273  *
274  * Note from the getprotobynumber(3) manpage:
275  * <quote>
276  * These functions use a thread-specific data space; if the data is needed
277  * for future use, it should be copied before any subsequent calls overwrite
278  * it.  Only the Internet protocols are currently understood.
279  * </quote>
280  *
281  * Consequently we only cache the name and strdup it for safety.
282  *
283  * At the time of writing this comment the last entry in /etc/protocols is:
284  * divert  258     DIVERT          # Divert pseudo-protocol [non IANA]
285  */
286 const char *
pfctl_proto2name(int proto)287 pfctl_proto2name(int proto)
288 {
289 	static const char *pfctl_proto_cache[259];
290 	struct protoent *p;
291 
292 	if (proto >= nitems(pfctl_proto_cache)) {
293 		p = getprotobynumber(proto);
294 		if (p == NULL) {
295 			return (NULL);
296 		}
297 		return (p->p_name);
298 	}
299 
300 	if (pfctl_proto_cache[proto] == NULL) {
301 		p = getprotobynumber(proto);
302 		if (p == NULL) {
303 			return (NULL);
304 		}
305 		pfctl_proto_cache[proto] = strdup(p->p_name);
306 	}
307 
308 	return (pfctl_proto_cache[proto]);
309 }
310 
311 int
pfctl_enable(int dev,int opts)312 pfctl_enable(int dev, int opts)
313 {
314 	int ret;
315 
316 	if ((ret = pfctl_startstop(pfh, 1)) != 0) {
317 		if (ret == EEXIST)
318 			errx(1, "pf already enabled");
319 		else if (ret == ESRCH)
320 			errx(1, "pfil registeration failed");
321 		else
322 			errc(1, ret, "DIOCSTART");
323 	}
324 	if ((opts & PF_OPT_QUIET) == 0)
325 		fprintf(stderr, "pf enabled\n");
326 
327 	if (altqsupport && ioctl(dev, DIOCSTARTALTQ))
328 		if (errno != EEXIST)
329 			err(1, "DIOCSTARTALTQ");
330 
331 	return (0);
332 }
333 
334 int
pfctl_disable(int dev,int opts)335 pfctl_disable(int dev, int opts)
336 {
337 	int ret;
338 
339 	if ((ret = pfctl_startstop(pfh, 0)) != 0) {
340 		if (ret == ENOENT)
341 			errx(1, "pf not enabled");
342 		else
343 			errc(1, ret, "DIOCSTOP");
344 	}
345 	if ((opts & PF_OPT_QUIET) == 0)
346 		fprintf(stderr, "pf disabled\n");
347 
348 	if (altqsupport && ioctl(dev, DIOCSTOPALTQ))
349 			if (errno != ENOENT)
350 				err(1, "DIOCSTOPALTQ");
351 
352 	return (0);
353 }
354 
355 int
pfctl_clear_stats(struct pfctl_handle * h,int opts)356 pfctl_clear_stats(struct pfctl_handle *h, int opts)
357 {
358 	int ret;
359 	if ((ret = pfctl_clear_status(h)) != 0)
360 		errc(1, ret, "DIOCCLRSTATUS");
361 	if ((opts & PF_OPT_QUIET) == 0)
362 		fprintf(stderr, "pf: statistics cleared\n");
363 	return (0);
364 }
365 
366 int
pfctl_get_skip_ifaces(void)367 pfctl_get_skip_ifaces(void)
368 {
369 	bzero(&skip_b, sizeof(skip_b));
370 	skip_b.pfrb_type = PFRB_IFACES;
371 	for (;;) {
372 		pfr_buf_grow(&skip_b, skip_b.pfrb_size);
373 		skip_b.pfrb_size = skip_b.pfrb_msize;
374 		if (pfi_get_ifaces(NULL, skip_b.pfrb_caddr, &skip_b.pfrb_size))
375 			err(1, "pfi_get_ifaces");
376 		if (skip_b.pfrb_size <= skip_b.pfrb_msize)
377 			break;
378 	}
379 	return (0);
380 }
381 
382 int
pfctl_check_skip_ifaces(char * ifname)383 pfctl_check_skip_ifaces(char *ifname)
384 {
385 	struct pfi_kif		*p;
386 	struct node_host	*h = NULL, *n = NULL;
387 
388 	PFRB_FOREACH(p, &skip_b) {
389 		if (!strcmp(ifname, p->pfik_name) &&
390 		    (p->pfik_flags & PFI_IFLAG_SKIP))
391 			p->pfik_flags &= ~PFI_IFLAG_SKIP;
392 		if (!strcmp(ifname, p->pfik_name) && p->pfik_group != NULL) {
393 			if ((h = ifa_grouplookup(p->pfik_name, 0)) == NULL)
394 				continue;
395 
396 			for (n = h; n != NULL; n = n->next) {
397 				if (strncmp(p->pfik_name, ifname, IFNAMSIZ))
398 					continue;
399 
400 				p->pfik_flags &= ~PFI_IFLAG_SKIP;
401 			}
402 		}
403 	}
404 	return (0);
405 }
406 
407 int
pfctl_adjust_skip_ifaces(struct pfctl * pf)408 pfctl_adjust_skip_ifaces(struct pfctl *pf)
409 {
410 	struct pfi_kif		*p, *pp;
411 	struct node_host	*h = NULL, *n = NULL;
412 
413 	PFRB_FOREACH(p, &skip_b) {
414 		if (p->pfik_group == NULL || !(p->pfik_flags & PFI_IFLAG_SKIP))
415 			continue;
416 
417 		pfctl_set_interface_flags(pf, p->pfik_name, PFI_IFLAG_SKIP, 0);
418 		if ((h = ifa_grouplookup(p->pfik_name, 0)) == NULL)
419 			continue;
420 
421 		for (n = h; n != NULL; n = n->next)
422 			PFRB_FOREACH(pp, &skip_b) {
423 				if (strncmp(pp->pfik_name, n->ifname, IFNAMSIZ))
424 					continue;
425 
426 				if (!(pp->pfik_flags & PFI_IFLAG_SKIP))
427 					pfctl_set_interface_flags(pf,
428 					    pp->pfik_name, PFI_IFLAG_SKIP, 1);
429 				if (pp->pfik_flags & PFI_IFLAG_SKIP)
430 					pp->pfik_flags &= ~PFI_IFLAG_SKIP;
431 			}
432 	}
433 
434 	PFRB_FOREACH(p, &skip_b) {
435 		if (! (p->pfik_flags & PFI_IFLAG_SKIP))
436 			continue;
437 
438 		pfctl_set_interface_flags(pf, p->pfik_name, PFI_IFLAG_SKIP, 0);
439 	}
440 
441 	return (0);
442 }
443 
444 int
pfctl_clear_interface_flags(int dev,int opts)445 pfctl_clear_interface_flags(int dev, int opts)
446 {
447 	struct pfioc_iface	pi;
448 
449 	if ((opts & PF_OPT_NOACTION) == 0) {
450 		bzero(&pi, sizeof(pi));
451 		pi.pfiio_flags = PFI_IFLAG_SKIP;
452 
453 		if (ioctl(dev, DIOCCLRIFFLAG, &pi))
454 			err(1, "DIOCCLRIFFLAG");
455 		if ((opts & PF_OPT_QUIET) == 0)
456 			fprintf(stderr, "pf: interface flags reset\n");
457 	}
458 	return (0);
459 }
460 
461 int
pfctl_flush_eth_rules(int dev,int opts,char * anchorname)462 pfctl_flush_eth_rules(int dev, int opts, char *anchorname)
463 {
464 	int ret;
465 
466 	ret = pfctl_clear_eth_rules(dev, anchorname);
467 	if (ret != 0)
468 		err(1, "pfctl_clear_eth_rules");
469 
470 	if ((opts & PF_OPT_QUIET) == 0)
471 		fprintf(stderr, "Ethernet rules cleared\n");
472 
473 	return (ret);
474 }
475 
476 int
pfctl_flush_rules(int dev,int opts,char * anchorname)477 pfctl_flush_rules(int dev, int opts, char *anchorname)
478 {
479 	int ret;
480 
481 	ret = pfctl_clear_rules(dev, anchorname);
482 	if (ret != 0)
483 		err(1, "pfctl_clear_rules");
484 	if ((opts & PF_OPT_QUIET) == 0)
485 		fprintf(stderr, "rules cleared\n");
486 	return (0);
487 }
488 
489 int
pfctl_flush_nat(int dev,int opts,char * anchorname)490 pfctl_flush_nat(int dev, int opts, char *anchorname)
491 {
492 	int ret;
493 
494 	ret = pfctl_clear_nat(dev, anchorname);
495 	if (ret != 0)
496 		err(1, "pfctl_clear_nat");
497 	if ((opts & PF_OPT_QUIET) == 0)
498 		fprintf(stderr, "nat cleared\n");
499 	return (0);
500 }
501 
502 int
pfctl_clear_altq(int dev,int opts)503 pfctl_clear_altq(int dev, int opts)
504 {
505 	struct pfr_buffer t;
506 
507 	if (!altqsupport)
508 		return (-1);
509 	memset(&t, 0, sizeof(t));
510 	t.pfrb_type = PFRB_TRANS;
511 	if (pfctl_add_trans(&t, PF_RULESET_ALTQ, "") ||
512 	    pfctl_trans(dev, &t, DIOCXBEGIN, 0) ||
513 	    pfctl_trans(dev, &t, DIOCXCOMMIT, 0))
514 		err(1, "pfctl_clear_altq");
515 	if ((opts & PF_OPT_QUIET) == 0)
516 		fprintf(stderr, "altq cleared\n");
517 	return (0);
518 }
519 
520 int
pfctl_clear_src_nodes(int dev,int opts)521 pfctl_clear_src_nodes(int dev, int opts)
522 {
523 	if (ioctl(dev, DIOCCLRSRCNODES))
524 		err(1, "DIOCCLRSRCNODES");
525 	if ((opts & PF_OPT_QUIET) == 0)
526 		fprintf(stderr, "source tracking entries cleared\n");
527 	return (0);
528 }
529 
530 int
pfctl_clear_iface_states(int dev,const char * iface,int opts)531 pfctl_clear_iface_states(int dev, const char *iface, int opts)
532 {
533 	struct pfctl_kill kill;
534 	unsigned int killed;
535 	int ret;
536 
537 	memset(&kill, 0, sizeof(kill));
538 	if (iface != NULL && strlcpy(kill.ifname, iface,
539 	    sizeof(kill.ifname)) >= sizeof(kill.ifname))
540 		errx(1, "invalid interface: %s", iface);
541 
542 	if (opts & PF_OPT_KILLMATCH)
543 		kill.kill_match = true;
544 
545 	if ((ret = pfctl_clear_states_h(pfh, &kill, &killed)) != 0)
546 		errc(1, ret, "DIOCCLRSTATES");
547 	if ((opts & PF_OPT_QUIET) == 0)
548 		fprintf(stderr, "%d states cleared\n", killed);
549 	return (0);
550 }
551 
552 void
pfctl_addrprefix(char * addr,struct pf_addr * mask)553 pfctl_addrprefix(char *addr, struct pf_addr *mask)
554 {
555 	char *p;
556 	const char *errstr;
557 	int prefix, ret_ga, q, r;
558 	struct addrinfo hints, *res;
559 
560 	if ((p = strchr(addr, '/')) == NULL)
561 		return;
562 
563 	*p++ = '\0';
564 	prefix = strtonum(p, 0, 128, &errstr);
565 	if (errstr)
566 		errx(1, "prefix is %s: %s", errstr, p);
567 
568 	bzero(&hints, sizeof(hints));
569 	/* prefix only with numeric addresses */
570 	hints.ai_flags |= AI_NUMERICHOST;
571 
572 	if ((ret_ga = getaddrinfo(addr, NULL, &hints, &res))) {
573 		errx(1, "getaddrinfo: %s", gai_strerror(ret_ga));
574 		/* NOTREACHED */
575 	}
576 
577 	if (res->ai_family == AF_INET && prefix > 32)
578 		errx(1, "prefix too long for AF_INET");
579 	else if (res->ai_family == AF_INET6 && prefix > 128)
580 		errx(1, "prefix too long for AF_INET6");
581 
582 	q = prefix >> 3;
583 	r = prefix & 7;
584 	switch (res->ai_family) {
585 	case AF_INET:
586 		bzero(&mask->v4, sizeof(mask->v4));
587 		mask->v4.s_addr = htonl((u_int32_t)
588 		    (0xffffffffffULL << (32 - prefix)));
589 		break;
590 	case AF_INET6:
591 		bzero(&mask->v6, sizeof(mask->v6));
592 		if (q > 0)
593 			memset((void *)&mask->v6, 0xff, q);
594 		if (r > 0)
595 			*((u_char *)&mask->v6 + q) =
596 			    (0xff00 >> r) & 0xff;
597 		break;
598 	}
599 	freeaddrinfo(res);
600 }
601 
602 int
pfctl_kill_src_nodes(int dev,const char * iface,int opts)603 pfctl_kill_src_nodes(int dev, const char *iface, int opts)
604 {
605 	struct pfioc_src_node_kill psnk;
606 	struct addrinfo *res[2], *resp[2];
607 	struct sockaddr last_src, last_dst;
608 	int killed, sources, dests;
609 	int ret_ga;
610 
611 	killed = sources = dests = 0;
612 
613 	memset(&psnk, 0, sizeof(psnk));
614 	memset(&psnk.psnk_src.addr.v.a.mask, 0xff,
615 	    sizeof(psnk.psnk_src.addr.v.a.mask));
616 	memset(&last_src, 0xff, sizeof(last_src));
617 	memset(&last_dst, 0xff, sizeof(last_dst));
618 
619 	pfctl_addrprefix(src_node_kill[0], &psnk.psnk_src.addr.v.a.mask);
620 
621 	if ((ret_ga = getaddrinfo(src_node_kill[0], NULL, NULL, &res[0]))) {
622 		errx(1, "getaddrinfo: %s", gai_strerror(ret_ga));
623 		/* NOTREACHED */
624 	}
625 	for (resp[0] = res[0]; resp[0]; resp[0] = resp[0]->ai_next) {
626 		if (resp[0]->ai_addr == NULL)
627 			continue;
628 		/* We get lots of duplicates.  Catch the easy ones */
629 		if (memcmp(&last_src, resp[0]->ai_addr, sizeof(last_src)) == 0)
630 			continue;
631 		last_src = *(struct sockaddr *)resp[0]->ai_addr;
632 
633 		psnk.psnk_af = resp[0]->ai_family;
634 		sources++;
635 
636 		if (psnk.psnk_af == AF_INET)
637 			psnk.psnk_src.addr.v.a.addr.v4 =
638 			    ((struct sockaddr_in *)resp[0]->ai_addr)->sin_addr;
639 		else if (psnk.psnk_af == AF_INET6)
640 			psnk.psnk_src.addr.v.a.addr.v6 =
641 			    ((struct sockaddr_in6 *)resp[0]->ai_addr)->
642 			    sin6_addr;
643 		else
644 			errx(1, "Unknown address family %d", psnk.psnk_af);
645 
646 		if (src_node_killers > 1) {
647 			dests = 0;
648 			memset(&psnk.psnk_dst.addr.v.a.mask, 0xff,
649 			    sizeof(psnk.psnk_dst.addr.v.a.mask));
650 			memset(&last_dst, 0xff, sizeof(last_dst));
651 			pfctl_addrprefix(src_node_kill[1],
652 			    &psnk.psnk_dst.addr.v.a.mask);
653 			if ((ret_ga = getaddrinfo(src_node_kill[1], NULL, NULL,
654 			    &res[1]))) {
655 				errx(1, "getaddrinfo: %s",
656 				    gai_strerror(ret_ga));
657 				/* NOTREACHED */
658 			}
659 			for (resp[1] = res[1]; resp[1];
660 			    resp[1] = resp[1]->ai_next) {
661 				if (resp[1]->ai_addr == NULL)
662 					continue;
663 				if (psnk.psnk_af != resp[1]->ai_family)
664 					continue;
665 
666 				if (memcmp(&last_dst, resp[1]->ai_addr,
667 				    sizeof(last_dst)) == 0)
668 					continue;
669 				last_dst = *(struct sockaddr *)resp[1]->ai_addr;
670 
671 				dests++;
672 
673 				if (psnk.psnk_af == AF_INET)
674 					psnk.psnk_dst.addr.v.a.addr.v4 =
675 					    ((struct sockaddr_in *)resp[1]->
676 					    ai_addr)->sin_addr;
677 				else if (psnk.psnk_af == AF_INET6)
678 					psnk.psnk_dst.addr.v.a.addr.v6 =
679 					    ((struct sockaddr_in6 *)resp[1]->
680 					    ai_addr)->sin6_addr;
681 				else
682 					errx(1, "Unknown address family %d",
683 					    psnk.psnk_af);
684 
685 				if (ioctl(dev, DIOCKILLSRCNODES, &psnk))
686 					err(1, "DIOCKILLSRCNODES");
687 				killed += psnk.psnk_killed;
688 			}
689 			freeaddrinfo(res[1]);
690 		} else {
691 			if (ioctl(dev, DIOCKILLSRCNODES, &psnk))
692 				err(1, "DIOCKILLSRCNODES");
693 			killed += psnk.psnk_killed;
694 		}
695 	}
696 
697 	freeaddrinfo(res[0]);
698 
699 	if ((opts & PF_OPT_QUIET) == 0)
700 		fprintf(stderr, "killed %d src nodes from %d sources and %d "
701 		    "destinations\n", killed, sources, dests);
702 	return (0);
703 }
704 
705 int
pfctl_net_kill_states(int dev,const char * iface,int opts)706 pfctl_net_kill_states(int dev, const char *iface, int opts)
707 {
708 	struct pfctl_kill kill;
709 	struct addrinfo *res[2], *resp[2];
710 	struct sockaddr last_src, last_dst;
711 	unsigned int newkilled;
712 	int killed, sources, dests;
713 	int ret_ga, ret;
714 
715 	killed = sources = dests = 0;
716 
717 	memset(&kill, 0, sizeof(kill));
718 	memset(&kill.src.addr.v.a.mask, 0xff,
719 	    sizeof(kill.src.addr.v.a.mask));
720 	memset(&last_src, 0xff, sizeof(last_src));
721 	memset(&last_dst, 0xff, sizeof(last_dst));
722 	if (iface != NULL && strlcpy(kill.ifname, iface,
723 	    sizeof(kill.ifname)) >= sizeof(kill.ifname))
724 		errx(1, "invalid interface: %s", iface);
725 
726 	if (state_killers == 2 && (strcmp(state_kill[0], "nat") == 0)) {
727 		kill.nat = true;
728 		state_kill[0] = state_kill[1];
729 		state_killers = 1;
730 	}
731 
732 	pfctl_addrprefix(state_kill[0], &kill.src.addr.v.a.mask);
733 
734 	if (opts & PF_OPT_KILLMATCH)
735 		kill.kill_match = true;
736 
737 	if ((ret_ga = getaddrinfo(state_kill[0], NULL, NULL, &res[0]))) {
738 		errx(1, "getaddrinfo: %s", gai_strerror(ret_ga));
739 		/* NOTREACHED */
740 	}
741 	for (resp[0] = res[0]; resp[0]; resp[0] = resp[0]->ai_next) {
742 		if (resp[0]->ai_addr == NULL)
743 			continue;
744 		/* We get lots of duplicates.  Catch the easy ones */
745 		if (memcmp(&last_src, resp[0]->ai_addr, sizeof(last_src)) == 0)
746 			continue;
747 		last_src = *(struct sockaddr *)resp[0]->ai_addr;
748 
749 		kill.af = resp[0]->ai_family;
750 		sources++;
751 
752 		if (kill.af == AF_INET)
753 			kill.src.addr.v.a.addr.v4 =
754 			    ((struct sockaddr_in *)resp[0]->ai_addr)->sin_addr;
755 		else if (kill.af == AF_INET6)
756 			kill.src.addr.v.a.addr.v6 =
757 			    ((struct sockaddr_in6 *)resp[0]->ai_addr)->
758 			    sin6_addr;
759 		else
760 			errx(1, "Unknown address family %d", kill.af);
761 
762 		if (state_killers > 1) {
763 			dests = 0;
764 			memset(&kill.dst.addr.v.a.mask, 0xff,
765 			    sizeof(kill.dst.addr.v.a.mask));
766 			memset(&last_dst, 0xff, sizeof(last_dst));
767 			pfctl_addrprefix(state_kill[1],
768 			    &kill.dst.addr.v.a.mask);
769 			if ((ret_ga = getaddrinfo(state_kill[1], NULL, NULL,
770 			    &res[1]))) {
771 				errx(1, "getaddrinfo: %s",
772 				    gai_strerror(ret_ga));
773 				/* NOTREACHED */
774 			}
775 			for (resp[1] = res[1]; resp[1];
776 			    resp[1] = resp[1]->ai_next) {
777 				if (resp[1]->ai_addr == NULL)
778 					continue;
779 				if (kill.af != resp[1]->ai_family)
780 					continue;
781 
782 				if (memcmp(&last_dst, resp[1]->ai_addr,
783 				    sizeof(last_dst)) == 0)
784 					continue;
785 				last_dst = *(struct sockaddr *)resp[1]->ai_addr;
786 
787 				dests++;
788 
789 				if (kill.af == AF_INET)
790 					kill.dst.addr.v.a.addr.v4 =
791 					    ((struct sockaddr_in *)resp[1]->
792 					    ai_addr)->sin_addr;
793 				else if (kill.af == AF_INET6)
794 					kill.dst.addr.v.a.addr.v6 =
795 					    ((struct sockaddr_in6 *)resp[1]->
796 					    ai_addr)->sin6_addr;
797 				else
798 					errx(1, "Unknown address family %d",
799 					    kill.af);
800 
801 				if ((ret = pfctl_kill_states_h(pfh, &kill, &newkilled)) != 0)
802 					errc(1, ret, "DIOCKILLSTATES");
803 				killed += newkilled;
804 			}
805 			freeaddrinfo(res[1]);
806 		} else {
807 			if ((ret = pfctl_kill_states_h(pfh, &kill, &newkilled)) != 0)
808 				errc(1, ret, "DIOCKILLSTATES");
809 			killed += newkilled;
810 		}
811 	}
812 
813 	freeaddrinfo(res[0]);
814 
815 	if ((opts & PF_OPT_QUIET) == 0)
816 		fprintf(stderr, "killed %d states from %d sources and %d "
817 		    "destinations\n", killed, sources, dests);
818 	return (0);
819 }
820 
821 int
pfctl_gateway_kill_states(int dev,const char * iface,int opts)822 pfctl_gateway_kill_states(int dev, const char *iface, int opts)
823 {
824 	struct pfctl_kill kill;
825 	struct addrinfo *res, *resp;
826 	struct sockaddr last_src;
827 	unsigned int newkilled;
828 	int killed = 0;
829 	int ret_ga;
830 
831 	if (state_killers != 2 || (strlen(state_kill[1]) == 0)) {
832 		warnx("no gateway specified");
833 		usage();
834 	}
835 
836 	memset(&kill, 0, sizeof(kill));
837 	memset(&kill.rt_addr.addr.v.a.mask, 0xff,
838 	    sizeof(kill.rt_addr.addr.v.a.mask));
839 	memset(&last_src, 0xff, sizeof(last_src));
840 	if (iface != NULL && strlcpy(kill.ifname, iface,
841 	    sizeof(kill.ifname)) >= sizeof(kill.ifname))
842 		errx(1, "invalid interface: %s", iface);
843 
844 	if (opts & PF_OPT_KILLMATCH)
845 		kill.kill_match = true;
846 
847 	pfctl_addrprefix(state_kill[1], &kill.rt_addr.addr.v.a.mask);
848 
849 	if ((ret_ga = getaddrinfo(state_kill[1], NULL, NULL, &res))) {
850 		errx(1, "getaddrinfo: %s", gai_strerror(ret_ga));
851 		/* NOTREACHED */
852 	}
853 	for (resp = res; resp; resp = resp->ai_next) {
854 		if (resp->ai_addr == NULL)
855 			continue;
856 		/* We get lots of duplicates.  Catch the easy ones */
857 		if (memcmp(&last_src, resp->ai_addr, sizeof(last_src)) == 0)
858 			continue;
859 		last_src = *(struct sockaddr *)resp->ai_addr;
860 
861 		kill.af = resp->ai_family;
862 
863 		if (kill.af == AF_INET)
864 			kill.rt_addr.addr.v.a.addr.v4 =
865 			    ((struct sockaddr_in *)resp->ai_addr)->sin_addr;
866 		else if (kill.af == AF_INET6)
867 			kill.rt_addr.addr.v.a.addr.v6 =
868 			    ((struct sockaddr_in6 *)resp->ai_addr)->
869 			    sin6_addr;
870 		else
871 			errx(1, "Unknown address family %d", kill.af);
872 
873 		if (pfctl_kill_states_h(pfh, &kill, &newkilled))
874 			err(1, "DIOCKILLSTATES");
875 		killed += newkilled;
876 	}
877 
878 	freeaddrinfo(res);
879 
880 	if ((opts & PF_OPT_QUIET) == 0)
881 		fprintf(stderr, "killed %d states\n", killed);
882 	return (0);
883 }
884 
885 int
pfctl_label_kill_states(int dev,const char * iface,int opts)886 pfctl_label_kill_states(int dev, const char *iface, int opts)
887 {
888 	struct pfctl_kill kill;
889 	unsigned int killed;
890 	int ret;
891 
892 	if (state_killers != 2 || (strlen(state_kill[1]) == 0)) {
893 		warnx("no label specified");
894 		usage();
895 	}
896 	memset(&kill, 0, sizeof(kill));
897 	if (iface != NULL && strlcpy(kill.ifname, iface,
898 	    sizeof(kill.ifname)) >= sizeof(kill.ifname))
899 		errx(1, "invalid interface: %s", iface);
900 
901 	if (opts & PF_OPT_KILLMATCH)
902 		kill.kill_match = true;
903 
904 	if (strlcpy(kill.label, state_kill[1], sizeof(kill.label)) >=
905 	    sizeof(kill.label))
906 		errx(1, "label too long: %s", state_kill[1]);
907 
908 	if ((ret = pfctl_kill_states_h(pfh, &kill, &killed)) != 0)
909 		errc(1, ret, "DIOCKILLSTATES");
910 
911 	if ((opts & PF_OPT_QUIET) == 0)
912 		fprintf(stderr, "killed %d states\n", killed);
913 
914 	return (0);
915 }
916 
917 int
pfctl_id_kill_states(int dev,const char * iface,int opts)918 pfctl_id_kill_states(int dev, const char *iface, int opts)
919 {
920 	struct pfctl_kill kill;
921 	unsigned int killed;
922 	int ret;
923 
924 	if (state_killers != 2 || (strlen(state_kill[1]) == 0)) {
925 		warnx("no id specified");
926 		usage();
927 	}
928 
929 	memset(&kill, 0, sizeof(kill));
930 
931 	if (opts & PF_OPT_KILLMATCH)
932 		kill.kill_match = true;
933 
934 	if ((sscanf(state_kill[1], "%jx/%x",
935 	    &kill.cmp.id, &kill.cmp.creatorid)) == 2) {
936 	}
937 	else if ((sscanf(state_kill[1], "%jx", &kill.cmp.id)) == 1) {
938 		kill.cmp.creatorid = 0;
939 	} else {
940 		warnx("wrong id format specified");
941 		usage();
942 	}
943 	if (kill.cmp.id == 0) {
944 		warnx("cannot kill id 0");
945 		usage();
946 	}
947 
948 	if ((ret = pfctl_kill_states_h(pfh, &kill, &killed)) != 0)
949 		errc(1, ret, "DIOCKILLSTATES");
950 
951 	if ((opts & PF_OPT_QUIET) == 0)
952 		fprintf(stderr, "killed %d states\n", killed);
953 
954 	return (0);
955 }
956 
957 int
pfctl_get_pool(int dev,struct pfctl_pool * pool,u_int32_t nr,u_int32_t ticket,int r_action,const char * anchorname,int which)958 pfctl_get_pool(int dev, struct pfctl_pool *pool, u_int32_t nr,
959     u_int32_t ticket, int r_action, const char *anchorname, int which)
960 {
961 	struct pfioc_pooladdr pp;
962 	struct pf_pooladdr *pa;
963 	u_int32_t pnr, mpnr;
964 	int ret;
965 
966 	memset(&pp, 0, sizeof(pp));
967 	if ((ret = pfctl_get_addrs(pfh, ticket, nr, r_action, anchorname, &mpnr, which)) != 0) {
968 		warnc(ret, "DIOCGETADDRS");
969 		return (-1);
970 	}
971 
972 	TAILQ_INIT(&pool->list);
973 	for (pnr = 0; pnr < mpnr; ++pnr) {
974 		if ((ret = pfctl_get_addr(pfh, ticket, nr, r_action, anchorname, pnr, &pp, which)) != 0) {
975 			warnc(ret, "DIOCGETADDR");
976 			return (-1);
977 		}
978 		pa = calloc(1, sizeof(struct pf_pooladdr));
979 		if (pa == NULL)
980 			err(1, "calloc");
981 		bcopy(&pp.addr, pa, sizeof(struct pf_pooladdr));
982 		TAILQ_INSERT_TAIL(&pool->list, pa, entries);
983 	}
984 
985 	return (0);
986 }
987 
988 void
pfctl_move_pool(struct pfctl_pool * src,struct pfctl_pool * dst)989 pfctl_move_pool(struct pfctl_pool *src, struct pfctl_pool *dst)
990 {
991 	struct pf_pooladdr *pa;
992 
993 	while ((pa = TAILQ_FIRST(&src->list)) != NULL) {
994 		TAILQ_REMOVE(&src->list, pa, entries);
995 		TAILQ_INSERT_TAIL(&dst->list, pa, entries);
996 	}
997 }
998 
999 void
pfctl_clear_pool(struct pfctl_pool * pool)1000 pfctl_clear_pool(struct pfctl_pool *pool)
1001 {
1002 	struct pf_pooladdr *pa;
1003 
1004 	while ((pa = TAILQ_FIRST(&pool->list)) != NULL) {
1005 		TAILQ_REMOVE(&pool->list, pa, entries);
1006 		free(pa);
1007 	}
1008 }
1009 
1010 void
pfctl_print_eth_rule_counters(struct pfctl_eth_rule * rule,int opts)1011 pfctl_print_eth_rule_counters(struct pfctl_eth_rule *rule, int opts)
1012 {
1013 	if (opts & PF_OPT_VERBOSE) {
1014 		printf("  [ Evaluations: %-8llu  Packets: %-8llu  "
1015 			    "Bytes: %-10llu]\n",
1016 			    (unsigned long long)rule->evaluations,
1017 			    (unsigned long long)(rule->packets[0] +
1018 			    rule->packets[1]),
1019 			    (unsigned long long)(rule->bytes[0] +
1020 			    rule->bytes[1]));
1021 	}
1022 	if (opts & PF_OPT_VERBOSE2) {
1023 		char timestr[30];
1024 
1025 		if (rule->last_active_timestamp != 0) {
1026 			bcopy(ctime(&rule->last_active_timestamp), timestr,
1027 			    sizeof(timestr));
1028 			*strchr(timestr, '\n') = '\0';
1029 		} else {
1030 			snprintf(timestr, sizeof(timestr), "N/A");
1031 		}
1032 		printf("  [ Last Active Time: %s ]\n", timestr);
1033 	}
1034 }
1035 
1036 void
pfctl_print_rule_counters(struct pfctl_rule * rule,int opts)1037 pfctl_print_rule_counters(struct pfctl_rule *rule, int opts)
1038 {
1039 	if (opts & PF_OPT_DEBUG) {
1040 		const char *t[PF_SKIP_COUNT] = { "i", "d", "f",
1041 		    "p", "sa", "da", "sp", "dp" };
1042 		int i;
1043 
1044 		printf("  [ Skip steps: ");
1045 		for (i = 0; i < PF_SKIP_COUNT; ++i) {
1046 			if (rule->skip[i].nr == rule->nr + 1)
1047 				continue;
1048 			printf("%s=", t[i]);
1049 			if (rule->skip[i].nr == -1)
1050 				printf("end ");
1051 			else
1052 				printf("%u ", rule->skip[i].nr);
1053 		}
1054 		printf("]\n");
1055 
1056 		printf("  [ queue: qname=%s qid=%u pqname=%s pqid=%u ]\n",
1057 		    rule->qname, rule->qid, rule->pqname, rule->pqid);
1058 	}
1059 	if (opts & PF_OPT_VERBOSE) {
1060 		printf("  [ Evaluations: %-8llu  Packets: %-8llu  "
1061 			    "Bytes: %-10llu  States: %-6ju]\n",
1062 			    (unsigned long long)rule->evaluations,
1063 			    (unsigned long long)(rule->packets[0] +
1064 			    rule->packets[1]),
1065 			    (unsigned long long)(rule->bytes[0] +
1066 			    rule->bytes[1]), (uintmax_t)rule->states_cur);
1067 		printf("  [ Source Nodes: %-6ju "
1068 			    "Limit: %-6ju "
1069 			    "NAT/RDR: %-6ju "
1070 			    "Route: %-6ju "
1071 			    "]\n",
1072 			    (uintmax_t)rule->src_nodes,
1073 			    (uintmax_t)rule->src_nodes_type[PF_SN_LIMIT],
1074 			    (uintmax_t)rule->src_nodes_type[PF_SN_NAT],
1075 			    (uintmax_t)rule->src_nodes_type[PF_SN_ROUTE]);
1076 		if (!(opts & PF_OPT_DEBUG))
1077 			printf("  [ Inserted: uid %u pid %u "
1078 			    "State Creations: %-6ju]\n",
1079 			    (unsigned)rule->cuid, (unsigned)rule->cpid,
1080 			    (uintmax_t)rule->states_tot);
1081 	}
1082 	if (opts & PF_OPT_VERBOSE2) {
1083 		char timestr[30];
1084 		if (rule->last_active_timestamp != 0) {
1085 			bcopy(ctime(&rule->last_active_timestamp), timestr,
1086 			    sizeof(timestr));
1087 			*strchr(timestr, '\n') = '\0';
1088 		} else {
1089 			snprintf(timestr, sizeof(timestr), "N/A");
1090 		}
1091 		printf("  [ Last Active Time: %s ]\n", timestr);
1092 	}
1093 }
1094 
1095 void
pfctl_print_title(char * title)1096 pfctl_print_title(char *title)
1097 {
1098 	if (!first_title)
1099 		printf("\n");
1100 	first_title = 0;
1101 	printf("%s\n", title);
1102 }
1103 
1104 int
pfctl_show_eth_rules(int dev,char * path,int opts,enum pfctl_show format,char * anchorname,int depth,int wildcard)1105 pfctl_show_eth_rules(int dev, char *path, int opts, enum pfctl_show format,
1106     char *anchorname, int depth, int wildcard)
1107 {
1108 	char anchor_call[MAXPATHLEN];
1109 	struct pfctl_eth_rules_info info;
1110 	struct pfctl_eth_rule rule;
1111 	int brace;
1112 	int dotitle = opts & PF_OPT_SHOWALL;
1113 	int len = strlen(path);
1114 	int ret;
1115 	char *npath, *p;
1116 
1117 	/*
1118 	 * Truncate a trailing / and * on an anchorname before searching for
1119 	 * the ruleset, this is syntactic sugar that doesn't actually make it
1120 	 * to the kernel.
1121 	 */
1122 	if ((p = strrchr(anchorname, '/')) != NULL &&
1123 			p[1] == '*' && p[2] == '\0') {
1124 		p[0] = '\0';
1125 	}
1126 
1127 	if (anchorname[0] == '/') {
1128 		if ((npath = calloc(1, MAXPATHLEN)) == NULL)
1129 			errx(1, "pfctl_rules: calloc");
1130 		snprintf(npath, MAXPATHLEN, "%s", anchorname);
1131 	} else {
1132 		if (path[0])
1133 			snprintf(&path[len], MAXPATHLEN - len, "/%s", anchorname);
1134 		else
1135 			snprintf(&path[len], MAXPATHLEN - len, "%s", anchorname);
1136 		npath = path;
1137 	}
1138 
1139 	/*
1140 	 * If this anchor was called with a wildcard path, go through
1141 	 * the rulesets in the anchor rather than the rules.
1142 	 */
1143 	if (wildcard && (opts & PF_OPT_RECURSE)) {
1144 		struct pfctl_eth_rulesets_info	ri;
1145 		u_int32_t                mnr, nr;
1146 
1147 		if ((ret = pfctl_get_eth_rulesets_info(dev, &ri, npath)) != 0) {
1148 			if (ret == EINVAL) {
1149 				fprintf(stderr, "Anchor '%s' "
1150 						"not found.\n", anchorname);
1151 			} else {
1152 				warnc(ret, "DIOCGETETHRULESETS");
1153 				return (-1);
1154 			}
1155 		}
1156 		mnr = ri.nr;
1157 
1158 		pfctl_print_eth_rule_counters(&rule, opts);
1159 		for (nr = 0; nr < mnr; ++nr) {
1160 			struct pfctl_eth_ruleset_info	rs;
1161 
1162 			if ((ret = pfctl_get_eth_ruleset(dev, npath, nr, &rs)) != 0)
1163 				errc(1, ret, "DIOCGETETHRULESET");
1164 			INDENT(depth, !(opts & PF_OPT_VERBOSE));
1165 			printf("anchor \"%s\" all {\n", rs.name);
1166 			pfctl_show_eth_rules(dev, npath, opts,
1167 					format, rs.name, depth + 1, 0);
1168 			INDENT(depth, !(opts & PF_OPT_VERBOSE));
1169 			printf("}\n");
1170 		}
1171 		path[len] = '\0';
1172 		return (0);
1173 	}
1174 
1175 	if ((ret = pfctl_get_eth_rules_info(dev, &info, path)) != 0) {
1176 		warnc(ret, "DIOCGETETHRULES");
1177 		return (-1);
1178 	}
1179 	for (int nr = 0; nr < info.nr; nr++) {
1180 		brace = 0;
1181 		INDENT(depth, !(opts & PF_OPT_VERBOSE));
1182 		if ((ret = pfctl_get_eth_rule(dev, nr, info.ticket, path, &rule,
1183 		    opts & PF_OPT_CLRRULECTRS, anchor_call)) != 0) {
1184 			warnc(ret, "DIOCGETETHRULE");
1185 			return (-1);
1186 		}
1187 		if (anchor_call[0] &&
1188 		   ((((p = strrchr(anchor_call, '_')) != NULL) &&
1189 		   (p == anchor_call ||
1190 		   *(--p) == '/')) || (opts & PF_OPT_RECURSE))) {
1191 			brace++;
1192 			int aclen = strlen(anchor_call);
1193 			if (anchor_call[aclen - 1] == '*')
1194 				anchor_call[aclen - 2] = '\0';
1195 		}
1196 		p = &anchor_call[0];
1197 		if (dotitle) {
1198 			pfctl_print_title("ETH RULES:");
1199 			dotitle = 0;
1200 		}
1201 		print_eth_rule(&rule, anchor_call,
1202 		    opts & (PF_OPT_VERBOSE2 | PF_OPT_DEBUG));
1203 		if (brace)
1204 			printf(" {\n");
1205 		else
1206 			printf("\n");
1207 		pfctl_print_eth_rule_counters(&rule, opts);
1208 		if (brace) {
1209 			pfctl_show_eth_rules(dev, path, opts, format,
1210 			    p, depth + 1, rule.anchor_wildcard);
1211 			INDENT(depth, !(opts & PF_OPT_VERBOSE));
1212 			printf("}\n");
1213 		}
1214 	}
1215 
1216 	path[len] = '\0';
1217 	return (0);
1218 }
1219 
1220 int
pfctl_show_rules(int dev,char * path,int opts,enum pfctl_show format,char * anchorname,int depth,int wildcard)1221 pfctl_show_rules(int dev, char *path, int opts, enum pfctl_show format,
1222     char *anchorname, int depth, int wildcard)
1223 {
1224 	struct pfctl_rules_info ri;
1225 	struct pfctl_rule rule;
1226 	char anchor_call[MAXPATHLEN];
1227 	u_int32_t nr, header = 0;
1228 	int rule_numbers = opts & (PF_OPT_VERBOSE2 | PF_OPT_DEBUG);
1229 	int numeric = opts & PF_OPT_NUMERIC;
1230 	int len = strlen(path), ret = 0;
1231 	char *npath, *p;
1232 
1233 	/*
1234 	 * Truncate a trailing / and * on an anchorname before searching for
1235 	 * the ruleset, this is syntactic sugar that doesn't actually make it
1236 	 * to the kernel.
1237 	 */
1238 	if ((p = strrchr(anchorname, '/')) != NULL &&
1239 	    p[1] == '*' && p[2] == '\0') {
1240 		p[0] = '\0';
1241 	}
1242 
1243 	if (anchorname[0] == '/') {
1244 		if ((npath = calloc(1, MAXPATHLEN)) == NULL)
1245 			errx(1, "pfctl_rules: calloc");
1246 		strlcpy(npath, anchorname, MAXPATHLEN);
1247 	} else {
1248 		if (path[0])
1249 			snprintf(&path[len], MAXPATHLEN - len, "/%s", anchorname);
1250 		else
1251 			snprintf(&path[len], MAXPATHLEN - len, "%s", anchorname);
1252 		npath = path;
1253 	}
1254 
1255 	/*
1256 	 * If this anchor was called with a wildcard path, go through
1257 	 * the rulesets in the anchor rather than the rules.
1258 	 */
1259 	if (wildcard && (opts & PF_OPT_RECURSE)) {
1260 		struct pfioc_ruleset     prs;
1261 		u_int32_t                mnr, nr;
1262 
1263 		memset(&prs, 0, sizeof(prs));
1264 		if ((ret = pfctl_get_rulesets(pfh, npath, &mnr)) != 0) {
1265 			if (ret == EINVAL)
1266 				fprintf(stderr, "Anchor '%s' "
1267 				    "not found.\n", anchorname);
1268 			else
1269 				errc(1, ret, "DIOCGETRULESETS");
1270 		}
1271 
1272 		for (nr = 0; nr < mnr; ++nr) {
1273 			if ((ret = pfctl_get_ruleset(pfh, npath, nr, &prs)) != 0)
1274 				errc(1, ret, "DIOCGETRULESET");
1275 			INDENT(depth, !(opts & PF_OPT_VERBOSE));
1276 			printf("anchor \"%s\" all {\n", prs.name);
1277 			pfctl_show_rules(dev, npath, opts,
1278 			    format, prs.name, depth + 1, 0);
1279 			INDENT(depth, !(opts & PF_OPT_VERBOSE));
1280 			printf("}\n");
1281 		}
1282 		path[len] = '\0';
1283 		return (0);
1284 	}
1285 
1286 	if (opts & PF_OPT_SHOWALL) {
1287 		ret = pfctl_get_rules_info_h(pfh, &ri, PF_PASS, path);
1288 		if (ret != 0) {
1289 			warnc(ret, "DIOCGETRULES");
1290 			goto error;
1291 		}
1292 		header++;
1293 	}
1294 	ret = pfctl_get_rules_info_h(pfh, &ri, PF_SCRUB, path);
1295 	if (ret != 0) {
1296 		warnc(ret, "DIOCGETRULES");
1297 		goto error;
1298 	}
1299 	if (opts & PF_OPT_SHOWALL) {
1300 		if (format == PFCTL_SHOW_RULES && (ri.nr > 0 || header))
1301 			pfctl_print_title("FILTER RULES:");
1302 		else if (format == PFCTL_SHOW_LABELS && labels)
1303 			pfctl_print_title("LABEL COUNTERS:");
1304 	}
1305 
1306 	for (nr = 0; nr < ri.nr; ++nr) {
1307 		if ((ret = pfctl_get_clear_rule_h(pfh, nr, ri.ticket, path, PF_SCRUB,
1308 		    &rule, anchor_call, opts & PF_OPT_CLRRULECTRS)) != 0) {
1309 			warnc(ret, "DIOCGETRULENV");
1310 			goto error;
1311 		}
1312 
1313 		if (pfctl_get_pool(dev, &rule.rdr,
1314 		    nr, ri.ticket, PF_SCRUB, path, PF_RDR) != 0)
1315 			goto error;
1316 
1317 		if (pfctl_get_pool(dev, &rule.nat,
1318 		    nr, ri.ticket, PF_SCRUB, path, PF_NAT) != 0)
1319 			goto error;
1320 
1321 		if (pfctl_get_pool(dev, &rule.route,
1322 		    nr, ri.ticket, PF_SCRUB, path, PF_RT) != 0)
1323 			goto error;
1324 
1325 		switch (format) {
1326 		case PFCTL_SHOW_LABELS:
1327 			break;
1328 		case PFCTL_SHOW_RULES:
1329 			if (rule.label[0][0] && (opts & PF_OPT_SHOWALL))
1330 				labels = 1;
1331 			print_rule(&rule, anchor_call, rule_numbers, numeric);
1332 			printf("\n");
1333 			pfctl_print_rule_counters(&rule, opts);
1334 			break;
1335 		case PFCTL_SHOW_NOTHING:
1336 			break;
1337 		}
1338 		pfctl_clear_pool(&rule.rdr);
1339 		pfctl_clear_pool(&rule.nat);
1340 		pfctl_clear_pool(&rule.route);
1341 	}
1342 	ret = pfctl_get_rules_info_h(pfh, &ri, PF_PASS, path);
1343 	if (ret != 0) {
1344 		warnc(ret, "DIOCGETRULES");
1345 		goto error;
1346 	}
1347 	for (nr = 0; nr < ri.nr; ++nr) {
1348 		if ((ret = pfctl_get_clear_rule_h(pfh, nr, ri.ticket, path, PF_PASS,
1349 		    &rule, anchor_call, opts & PF_OPT_CLRRULECTRS)) != 0) {
1350 			warnc(ret, "DIOCGETRULE");
1351 			goto error;
1352 		}
1353 
1354 		if (pfctl_get_pool(dev, &rule.rdr,
1355 		    nr, ri.ticket, PF_PASS, path, PF_RDR) != 0)
1356 			goto error;
1357 
1358 		if (pfctl_get_pool(dev, &rule.nat,
1359 		    nr, ri.ticket, PF_PASS, path, PF_NAT) != 0)
1360 			goto error;
1361 
1362 		if (pfctl_get_pool(dev, &rule.route,
1363 		    nr, ri.ticket, PF_PASS, path, PF_RT) != 0)
1364 			goto error;
1365 
1366 		switch (format) {
1367 		case PFCTL_SHOW_LABELS: {
1368 			bool show = false;
1369 			int i = 0;
1370 
1371 			while (rule.label[i][0]) {
1372 				printf("%s ", rule.label[i++]);
1373 				show = true;
1374 			}
1375 
1376 			if (show) {
1377 				printf("%llu %llu %llu %llu"
1378 				    " %llu %llu %llu %ju\n",
1379 				    (unsigned long long)rule.evaluations,
1380 				    (unsigned long long)(rule.packets[0] +
1381 				    rule.packets[1]),
1382 				    (unsigned long long)(rule.bytes[0] +
1383 				    rule.bytes[1]),
1384 				    (unsigned long long)rule.packets[0],
1385 				    (unsigned long long)rule.bytes[0],
1386 				    (unsigned long long)rule.packets[1],
1387 				    (unsigned long long)rule.bytes[1],
1388 				    (uintmax_t)rule.states_tot);
1389 			}
1390 
1391 			if (anchor_call[0] &&
1392 			    (((p = strrchr(anchor_call, '/')) ?
1393 			      p[1] == '_' : anchor_call[0] == '_') ||
1394 			     opts & PF_OPT_RECURSE)) {
1395 				pfctl_show_rules(dev, npath, opts, format,
1396 				    anchor_call, depth, rule.anchor_wildcard);
1397 			}
1398 			break;
1399 		}
1400 		case PFCTL_SHOW_RULES:
1401 			if (rule.label[0][0] && (opts & PF_OPT_SHOWALL))
1402 				labels = 1;
1403 			INDENT(depth, !(opts & PF_OPT_VERBOSE));
1404 			print_rule(&rule, anchor_call, rule_numbers, numeric);
1405 
1406 			/*
1407 			 * If this is a 'unnamed' brace notation
1408 			 * anchor, OR the user has explicitly requested
1409 			 * recursion, print it recursively.
1410 			 */
1411 			if (anchor_call[0] &&
1412 			    (((p = strrchr(anchor_call, '/')) ?
1413 			      p[1] == '_' : anchor_call[0] == '_') ||
1414 			     opts & PF_OPT_RECURSE)) {
1415 				printf(" {\n");
1416 				pfctl_print_rule_counters(&rule, opts);
1417 				pfctl_show_rules(dev, npath, opts, format,
1418 				    anchor_call, depth + 1,
1419 				    rule.anchor_wildcard);
1420 				INDENT(depth, !(opts & PF_OPT_VERBOSE));
1421 				printf("}\n");
1422 			} else {
1423 				printf("\n");
1424 				pfctl_print_rule_counters(&rule, opts);
1425 			}
1426 			break;
1427 		case PFCTL_SHOW_NOTHING:
1428 			break;
1429 		}
1430 		pfctl_clear_pool(&rule.rdr);
1431 		pfctl_clear_pool(&rule.nat);
1432 	}
1433 
1434  error:
1435 	path[len] = '\0';
1436 	return (ret);
1437 }
1438 
1439 int
pfctl_show_nat(int dev,const char * path,int opts,char * anchorname,int depth,int wildcard)1440 pfctl_show_nat(int dev, const char *path, int opts, char *anchorname, int depth,
1441     int wildcard)
1442 {
1443 	struct pfctl_rules_info ri;
1444 	struct pfctl_rule rule;
1445 	char anchor_call[MAXPATHLEN];
1446 	u_int32_t nr;
1447 	static int nattype[3] = { PF_NAT, PF_RDR, PF_BINAT };
1448 	int i, dotitle = opts & PF_OPT_SHOWALL;
1449 	int ret;
1450 	int len = strlen(path);
1451 	char *npath, *p;
1452 
1453 	/*
1454 	 * Truncate a trailing / and * on an anchorname before searching for
1455 	 * the ruleset, this is syntactic sugar that doesn't actually make it
1456 	 * to the kernel.
1457 	 */
1458 	if ((p = strrchr(anchorname, '/')) != NULL &&
1459 	    p[1] == '*' && p[2] == '\0') {
1460 		p[0] = '\0';
1461 	}
1462 
1463 	if ((npath = calloc(1, MAXPATHLEN)) == NULL)
1464 		errx(1, "pfctl_rules: calloc");
1465 
1466 	if (anchorname[0] == '/') {
1467 		snprintf(npath, MAXPATHLEN, "%s", anchorname);
1468 	} else {
1469 		snprintf(npath, MAXPATHLEN, "%s", path);
1470 		if (npath[0])
1471 			snprintf(&npath[len], MAXPATHLEN - len, "/%s", anchorname);
1472 		else
1473 			snprintf(&npath[len], MAXPATHLEN - len, "%s", anchorname);
1474 	}
1475 
1476 	/*
1477 	 * If this anchor was called with a wildcard path, go through
1478 	 * the rulesets in the anchor rather than the rules.
1479 	 */
1480 	if (wildcard && (opts & PF_OPT_RECURSE)) {
1481 		struct pfioc_ruleset     prs;
1482 		u_int32_t                mnr, nr;
1483 		memset(&prs, 0, sizeof(prs));
1484 		if ((ret = pfctl_get_rulesets(pfh, npath, &mnr)) != 0) {
1485 			if (ret == EINVAL)
1486 				fprintf(stderr, "NAT anchor '%s' "
1487 				    "not found.\n", anchorname);
1488 			else
1489 				errc(1, ret, "DIOCGETRULESETS");
1490 		}
1491 
1492 		for (nr = 0; nr < mnr; ++nr) {
1493 			if ((ret = pfctl_get_ruleset(pfh, npath, nr, &prs)) != 0)
1494 				errc(1, ret, "DIOCGETRULESET");
1495 			INDENT(depth, !(opts & PF_OPT_VERBOSE));
1496 			printf("nat-anchor \"%s\" all {\n", prs.name);
1497 			pfctl_show_nat(dev, npath, opts,
1498 			    prs.name, depth + 1, 0);
1499 			INDENT(depth, !(opts & PF_OPT_VERBOSE));
1500 			printf("}\n");
1501 		}
1502 		npath[len] = '\0';
1503 		return (0);
1504 	}
1505 
1506 	for (i = 0; i < 3; i++) {
1507 		ret = pfctl_get_rules_info_h(pfh, &ri, nattype[i], npath);
1508 		if (ret != 0) {
1509 			warnc(ret, "DIOCGETRULES");
1510 			return (-1);
1511 		}
1512 		for (nr = 0; nr < ri.nr; ++nr) {
1513 			INDENT(depth, !(opts & PF_OPT_VERBOSE));
1514 
1515 			if ((ret = pfctl_get_rule_h(pfh, nr, ri.ticket, npath,
1516 			    nattype[i], &rule, anchor_call)) != 0) {
1517 				warnc(ret, "DIOCGETRULE");
1518 				return (-1);
1519 			}
1520 			if (pfctl_get_pool(dev, &rule.rdr, nr,
1521 			    ri.ticket, nattype[i], npath, PF_RDR) != 0)
1522 				return (-1);
1523 			if (pfctl_get_pool(dev, &rule.nat, nr,
1524 			    ri.ticket, nattype[i], npath, PF_NAT) != 0)
1525 				return (-1);
1526 			if (pfctl_get_pool(dev, &rule.route, nr,
1527 			    ri.ticket, nattype[i], npath, PF_RT) != 0)
1528 				return (-1);
1529 
1530 			if (dotitle) {
1531 				pfctl_print_title("TRANSLATION RULES:");
1532 				dotitle = 0;
1533 			}
1534 			print_rule(&rule, anchor_call,
1535 			    opts & PF_OPT_VERBOSE2, opts & PF_OPT_NUMERIC);
1536 			if (anchor_call[0] &&
1537 			    (((p = strrchr(anchor_call, '/')) ?
1538 			      p[1] == '_' : anchor_call[0] == '_') ||
1539 			     opts & PF_OPT_RECURSE)) {
1540 				printf(" {\n");
1541 				pfctl_print_rule_counters(&rule, opts);
1542 				pfctl_show_nat(dev, npath, opts, anchor_call,
1543 				    depth + 1, rule.anchor_wildcard);
1544 				INDENT(depth, !(opts & PF_OPT_VERBOSE));
1545 				printf("}\n");
1546 			} else {
1547 				printf("\n");
1548 				pfctl_print_rule_counters(&rule, opts);
1549 			}
1550 		}
1551 	}
1552 	return (0);
1553 }
1554 
1555 static int
pfctl_print_src_node(struct pfctl_src_node * sn,void * arg)1556 pfctl_print_src_node(struct pfctl_src_node *sn, void *arg)
1557 {
1558 	int *opts = (int *)arg;
1559 
1560 	if (*opts & PF_OPT_SHOWALL) {
1561 		pfctl_print_title("SOURCE TRACKING NODES:");
1562 		*opts &= ~PF_OPT_SHOWALL;
1563 	}
1564 
1565 	print_src_node(sn, *opts);
1566 
1567 	return (0);
1568 }
1569 
1570 int
pfctl_show_src_nodes(int dev,int opts)1571 pfctl_show_src_nodes(int dev, int opts)
1572 {
1573 	int error;
1574 
1575 	error = pfctl_get_srcnodes(pfh, pfctl_print_src_node, &opts);
1576 
1577 	return (error);
1578 }
1579 
1580 struct pfctl_show_state_arg {
1581 	int opts;
1582 	int dotitle;
1583 	const char *iface;
1584 };
1585 
1586 static int
pfctl_show_state(struct pfctl_state * s,void * arg)1587 pfctl_show_state(struct pfctl_state *s, void *arg)
1588 {
1589 	struct pfctl_show_state_arg *a = (struct pfctl_show_state_arg *)arg;
1590 
1591 	if (a->dotitle) {
1592 		pfctl_print_title("STATES:");
1593 		a->dotitle = 0;
1594 	}
1595 	print_state(s, a->opts);
1596 
1597 	return (0);
1598 }
1599 
1600 int
pfctl_show_states(int dev,const char * iface,int opts)1601 pfctl_show_states(int dev, const char *iface, int opts)
1602 {
1603 	struct pfctl_show_state_arg arg;
1604 	struct pfctl_state_filter filter = {};
1605 
1606 	if (iface != NULL)
1607 		strncpy(filter.ifname, iface, IFNAMSIZ);
1608 
1609 	arg.opts = opts;
1610 	arg.dotitle = opts & PF_OPT_SHOWALL;
1611 	arg.iface = iface;
1612 
1613 	if (pfctl_get_filtered_states_iter(&filter, pfctl_show_state, &arg))
1614 		return (-1);
1615 
1616 	return (0);
1617 }
1618 
1619 int
pfctl_show_status(int dev,int opts)1620 pfctl_show_status(int dev, int opts)
1621 {
1622 	struct pfctl_status	*status;
1623 	struct pfctl_syncookies	cookies;
1624 	int ret;
1625 
1626 	if ((status = pfctl_get_status_h(pfh)) == NULL) {
1627 		warn("DIOCGETSTATUS");
1628 		return (-1);
1629 	}
1630 	if ((ret = pfctl_get_syncookies(dev, &cookies)) != 0) {
1631 		pfctl_free_status(status);
1632 		warnc(ret, "DIOCGETSYNCOOKIES");
1633 		return (-1);
1634 	}
1635 	if (opts & PF_OPT_SHOWALL)
1636 		pfctl_print_title("INFO:");
1637 	print_status(status, &cookies, opts);
1638 	pfctl_free_status(status);
1639 	return (0);
1640 }
1641 
1642 int
pfctl_show_running(int dev)1643 pfctl_show_running(int dev)
1644 {
1645 	struct pfctl_status *status;
1646 	int running;
1647 
1648 	if ((status = pfctl_get_status_h(pfh)) == NULL) {
1649 		warn("DIOCGETSTATUS");
1650 		return (-1);
1651 	}
1652 
1653 	running = status->running;
1654 
1655 	print_running(status);
1656 	pfctl_free_status(status);
1657 	return (!running);
1658 }
1659 
1660 int
pfctl_show_timeouts(int dev,int opts)1661 pfctl_show_timeouts(int dev, int opts)
1662 {
1663 	uint32_t seconds;
1664 	int i;
1665 	int ret;
1666 
1667 	if (opts & PF_OPT_SHOWALL)
1668 		pfctl_print_title("TIMEOUTS:");
1669 	for (i = 0; pf_timeouts[i].name; i++) {
1670 		if ((ret = pfctl_get_timeout(pfh, pf_timeouts[i].timeout, &seconds)) != 0)
1671 			errc(1, ret, "DIOCGETTIMEOUT");
1672 		printf("%-20s %10d", pf_timeouts[i].name, seconds);
1673 		if (pf_timeouts[i].timeout >= PFTM_ADAPTIVE_START &&
1674 		    pf_timeouts[i].timeout <= PFTM_ADAPTIVE_END)
1675 			printf(" states");
1676 		else
1677 			printf("s");
1678 		printf("\n");
1679 	}
1680 	return (0);
1681 
1682 }
1683 
1684 int
pfctl_show_limits(int dev,int opts)1685 pfctl_show_limits(int dev, int opts)
1686 {
1687 	unsigned int limit;
1688 	int i;
1689 	int ret;
1690 
1691 	if (opts & PF_OPT_SHOWALL)
1692 		pfctl_print_title("LIMITS:");
1693 	for (i = 0; pf_limits[i].name; i++) {
1694 		if ((ret = pfctl_get_limit(pfh, pf_limits[i].index, &limit)) != 0)
1695 			errc(1, ret, "DIOCGETLIMIT");
1696 		printf("%-13s ", pf_limits[i].name);
1697 		if (limit == UINT_MAX)
1698 			printf("unlimited\n");
1699 		else
1700 			printf("hard limit %8u\n", limit);
1701 	}
1702 	return (0);
1703 }
1704 
1705 void
pfctl_show_creators(int opts)1706 pfctl_show_creators(int opts)
1707 {
1708 	int ret;
1709 	uint32_t creators[16];
1710 	size_t count = nitems(creators);
1711 
1712 	ret = pfctl_get_creatorids(pfh, creators, &count);
1713 	if (ret != 0)
1714 		errx(ret, "Failed to retrieve creators");
1715 
1716 	printf("Creator IDs:\n");
1717 	for (size_t i = 0; i < count; i++)
1718 		printf("%08x\n", creators[i]);
1719 }
1720 
1721 /* callbacks for rule/nat/rdr/addr */
1722 int
pfctl_add_pool(struct pfctl * pf,struct pfctl_pool * p,sa_family_t af,int which)1723 pfctl_add_pool(struct pfctl *pf, struct pfctl_pool *p, sa_family_t af, int which)
1724 {
1725 	struct pf_pooladdr *pa;
1726 	int ret;
1727 
1728 	pf->paddr.af = af;
1729 	TAILQ_FOREACH(pa, &p->list, entries) {
1730 		memcpy(&pf->paddr.addr, pa, sizeof(struct pf_pooladdr));
1731 		if ((pf->opts & PF_OPT_NOACTION) == 0) {
1732 			if ((ret = pfctl_add_addr(pf->h, &pf->paddr, which)) != 0)
1733 				errc(1, ret, "DIOCADDADDR");
1734 		}
1735 	}
1736 	return (0);
1737 }
1738 
1739 void
pfctl_init_rule(struct pfctl_rule * r)1740 pfctl_init_rule(struct pfctl_rule *r)
1741 {
1742 
1743 	memset(r, 0, sizeof(struct pfctl_rule));
1744 	TAILQ_INIT(&(r->rdr.list));
1745 	TAILQ_INIT(&(r->nat.list));
1746 	TAILQ_INIT(&(r->route.list));
1747 }
1748 
1749 int
pfctl_append_rule(struct pfctl * pf,struct pfctl_rule * r,const char * anchor_call)1750 pfctl_append_rule(struct pfctl *pf, struct pfctl_rule *r,
1751     const char *anchor_call)
1752 {
1753 	u_int8_t		rs_num;
1754 	struct pfctl_rule	*rule;
1755 	struct pfctl_ruleset	*rs;
1756 	char 			*p;
1757 
1758 	rs_num = pf_get_ruleset_number(r->action);
1759 	if (rs_num == PF_RULESET_MAX)
1760 		errx(1, "Invalid rule type %d", r->action);
1761 
1762 	rs = &pf->anchor->ruleset;
1763 
1764 	if (anchor_call[0] && r->anchor == NULL) {
1765 		/*
1766 		 * Don't make non-brace anchors part of the main anchor pool.
1767 		 */
1768 		if ((r->anchor = calloc(1, sizeof(*r->anchor))) == NULL)
1769 			err(1, "pfctl_append_rule: calloc");
1770 
1771 		pf_init_ruleset(&r->anchor->ruleset);
1772 		r->anchor->ruleset.anchor = r->anchor;
1773 		if (strlcpy(r->anchor->path, anchor_call,
1774 		    sizeof(rule->anchor->path)) >= sizeof(rule->anchor->path))
1775 			errx(1, "pfctl_append_rule: strlcpy");
1776 		if ((p = strrchr(anchor_call, '/')) != NULL) {
1777 			if (!strlen(p))
1778 				err(1, "pfctl_append_rule: bad anchor name %s",
1779 				    anchor_call);
1780 		} else
1781 			p = (char *)anchor_call;
1782 		if (strlcpy(r->anchor->name, p,
1783 		    sizeof(rule->anchor->name)) >= sizeof(rule->anchor->name))
1784 			errx(1, "pfctl_append_rule: strlcpy");
1785 	}
1786 
1787 	if ((rule = calloc(1, sizeof(*rule))) == NULL)
1788 		err(1, "calloc");
1789 	bcopy(r, rule, sizeof(*rule));
1790 	TAILQ_INIT(&rule->rdr.list);
1791 	pfctl_move_pool(&r->rdr, &rule->rdr);
1792 	TAILQ_INIT(&rule->nat.list);
1793 	pfctl_move_pool(&r->nat, &rule->nat);
1794 	TAILQ_INIT(&rule->route.list);
1795 	pfctl_move_pool(&r->route, &rule->route);
1796 
1797 	TAILQ_INSERT_TAIL(rs->rules[rs_num].active.ptr, rule, entries);
1798 	return (0);
1799 }
1800 
1801 int
pfctl_append_eth_rule(struct pfctl * pf,struct pfctl_eth_rule * r,const char * anchor_call)1802 pfctl_append_eth_rule(struct pfctl *pf, struct pfctl_eth_rule *r,
1803     const char *anchor_call)
1804 {
1805 	struct pfctl_eth_rule		*rule;
1806 	struct pfctl_eth_ruleset	*rs;
1807 	char 				*p;
1808 
1809 	rs = &pf->eanchor->ruleset;
1810 
1811 	if (anchor_call[0] && r->anchor == NULL) {
1812 		/*
1813 		 * Don't make non-brace anchors part of the main anchor pool.
1814 		 */
1815 		if ((r->anchor = calloc(1, sizeof(*r->anchor))) == NULL)
1816 			err(1, "pfctl_append_rule: calloc");
1817 
1818 		pf_init_eth_ruleset(&r->anchor->ruleset);
1819 		r->anchor->ruleset.anchor = r->anchor;
1820 		if (strlcpy(r->anchor->path, anchor_call,
1821 		    sizeof(rule->anchor->path)) >= sizeof(rule->anchor->path))
1822 			errx(1, "pfctl_append_rule: strlcpy");
1823 		if ((p = strrchr(anchor_call, '/')) != NULL) {
1824 			if (!strlen(p))
1825 				err(1, "pfctl_append_eth_rule: bad anchor name %s",
1826 				    anchor_call);
1827 		} else
1828 			p = (char *)anchor_call;
1829 		if (strlcpy(r->anchor->name, p,
1830 		    sizeof(rule->anchor->name)) >= sizeof(rule->anchor->name))
1831 			errx(1, "pfctl_append_eth_rule: strlcpy");
1832 	}
1833 
1834 	if ((rule = calloc(1, sizeof(*rule))) == NULL)
1835 		err(1, "calloc");
1836 	bcopy(r, rule, sizeof(*rule));
1837 
1838 	TAILQ_INSERT_TAIL(&rs->rules, rule, entries);
1839 	return (0);
1840 }
1841 
1842 int
pfctl_eth_ruleset_trans(struct pfctl * pf,char * path,struct pfctl_eth_anchor * a)1843 pfctl_eth_ruleset_trans(struct pfctl *pf, char *path,
1844     struct pfctl_eth_anchor *a)
1845 {
1846 	int osize = pf->trans->pfrb_size;
1847 
1848 	if ((pf->loadopt & PFCTL_FLAG_ETH) != 0) {
1849 		if (pfctl_add_trans(pf->trans, PF_RULESET_ETH, path))
1850 			return (1);
1851 	}
1852 	if (pfctl_trans(pf->dev, pf->trans, DIOCXBEGIN, osize))
1853 		return (5);
1854 
1855 	return (0);
1856 }
1857 
1858 int
pfctl_ruleset_trans(struct pfctl * pf,char * path,struct pfctl_anchor * a,bool do_eth)1859 pfctl_ruleset_trans(struct pfctl *pf, char *path, struct pfctl_anchor *a, bool do_eth)
1860 {
1861 	int osize = pf->trans->pfrb_size;
1862 
1863 	if ((pf->loadopt & PFCTL_FLAG_ETH) != 0 && do_eth) {
1864 		if (pfctl_add_trans(pf->trans, PF_RULESET_ETH, path))
1865 			return (1);
1866 	}
1867 	if ((pf->loadopt & PFCTL_FLAG_NAT) != 0) {
1868 		if (pfctl_add_trans(pf->trans, PF_RULESET_NAT, path) ||
1869 		    pfctl_add_trans(pf->trans, PF_RULESET_BINAT, path) ||
1870 		    pfctl_add_trans(pf->trans, PF_RULESET_RDR, path))
1871 			return (1);
1872 	}
1873 	if (a == pf->astack[0] && ((altqsupport &&
1874 	    (pf->loadopt & PFCTL_FLAG_ALTQ) != 0))) {
1875 		if (pfctl_add_trans(pf->trans, PF_RULESET_ALTQ, path))
1876 			return (2);
1877 	}
1878 	if ((pf->loadopt & PFCTL_FLAG_FILTER) != 0) {
1879 		if (pfctl_add_trans(pf->trans, PF_RULESET_SCRUB, path) ||
1880 		    pfctl_add_trans(pf->trans, PF_RULESET_FILTER, path))
1881 			return (3);
1882 	}
1883 	if (pf->loadopt & PFCTL_FLAG_TABLE)
1884 		if (pfctl_add_trans(pf->trans, PF_RULESET_TABLE, path))
1885 			return (4);
1886 	if (pfctl_trans(pf->dev, pf->trans, DIOCXBEGIN, osize))
1887 		return (5);
1888 
1889 	return (0);
1890 }
1891 
1892 int
pfctl_load_eth_ruleset(struct pfctl * pf,char * path,struct pfctl_eth_ruleset * rs,int depth)1893 pfctl_load_eth_ruleset(struct pfctl *pf, char *path,
1894     struct pfctl_eth_ruleset *rs, int depth)
1895 {
1896 	struct pfctl_eth_rule	*r;
1897 	int	error, len = strlen(path);
1898 	int	brace = 0;
1899 
1900 	pf->eanchor = rs->anchor;
1901 	if (path[0])
1902 		snprintf(&path[len], MAXPATHLEN - len, "/%s", pf->eanchor->name);
1903 	else
1904 		snprintf(&path[len], MAXPATHLEN - len, "%s", pf->eanchor->name);
1905 
1906 	if (depth) {
1907 		if (TAILQ_FIRST(&rs->rules) != NULL) {
1908 			brace++;
1909 			if (pf->opts & PF_OPT_VERBOSE)
1910 				printf(" {\n");
1911 			if ((pf->opts & PF_OPT_NOACTION) == 0 &&
1912 			    (error = pfctl_eth_ruleset_trans(pf,
1913 			    path, rs->anchor))) {
1914 				printf("pfctl_load_eth_rulesets: "
1915 				    "pfctl_eth_ruleset_trans %d\n", error);
1916 				goto error;
1917 			}
1918 		} else if (pf->opts & PF_OPT_VERBOSE)
1919 			printf("\n");
1920 	}
1921 
1922 	while ((r = TAILQ_FIRST(&rs->rules)) != NULL) {
1923 		TAILQ_REMOVE(&rs->rules, r, entries);
1924 
1925 		error = pfctl_load_eth_rule(pf, path, r, depth);
1926 		if (error)
1927 			return (error);
1928 
1929 		if (r->anchor) {
1930 			if ((error = pfctl_load_eth_ruleset(pf, path,
1931 			    &r->anchor->ruleset, depth + 1)))
1932 				return (error);
1933 		} else if (pf->opts & PF_OPT_VERBOSE)
1934 			printf("\n");
1935 		free(r);
1936 	}
1937 	if (brace && pf->opts & PF_OPT_VERBOSE) {
1938 		INDENT(depth - 1, (pf->opts & PF_OPT_VERBOSE));
1939 		printf("}\n");
1940 	}
1941 	path[len] = '\0';
1942 
1943 	return (0);
1944 error:
1945 	path[len] = '\0';
1946 	return (error);
1947 }
1948 
1949 int
pfctl_load_eth_rule(struct pfctl * pf,char * path,struct pfctl_eth_rule * r,int depth)1950 pfctl_load_eth_rule(struct pfctl *pf, char *path, struct pfctl_eth_rule *r,
1951     int depth)
1952 {
1953 	char			*name;
1954 	char			anchor[PF_ANCHOR_NAME_SIZE];
1955 	int			len = strlen(path);
1956 	int			ret;
1957 
1958 	if (strlcpy(anchor, path, sizeof(anchor)) >= sizeof(anchor))
1959 		errx(1, "pfctl_load_eth_rule: strlcpy");
1960 
1961 	if (r->anchor) {
1962 		if (r->anchor->match) {
1963 			if (path[0])
1964 				snprintf(&path[len], MAXPATHLEN - len,
1965 				    "/%s", r->anchor->name);
1966 			else
1967 				snprintf(&path[len], MAXPATHLEN - len,
1968 				    "%s", r->anchor->name);
1969 			name = r->anchor->name;
1970 		} else
1971 			name = r->anchor->path;
1972 	} else
1973 		name = "";
1974 
1975 	if ((pf->opts & PF_OPT_NOACTION) == 0)
1976 		if ((ret = pfctl_add_eth_rule(pf->dev, r, anchor, name,
1977 		    pf->eth_ticket)) != 0)
1978 			errc(1, ret, "DIOCADDETHRULENV");
1979 
1980 	if (pf->opts & PF_OPT_VERBOSE) {
1981 		INDENT(depth, !(pf->opts & PF_OPT_VERBOSE2));
1982 		print_eth_rule(r, r->anchor ? r->anchor->name : "",
1983 		    pf->opts & (PF_OPT_VERBOSE2 | PF_OPT_DEBUG));
1984 	}
1985 
1986 	path[len] = '\0';
1987 
1988 	return (0);
1989 }
1990 
1991 int
pfctl_load_ruleset(struct pfctl * pf,char * path,struct pfctl_ruleset * rs,int rs_num,int depth)1992 pfctl_load_ruleset(struct pfctl *pf, char *path, struct pfctl_ruleset *rs,
1993     int rs_num, int depth)
1994 {
1995 	struct pfctl_rule *r;
1996 	int		error, len = strlen(path);
1997 	int		brace = 0;
1998 
1999 	pf->anchor = rs->anchor;
2000 
2001 	if (path[0])
2002 		snprintf(&path[len], MAXPATHLEN - len, "/%s", pf->anchor->name);
2003 	else
2004 		snprintf(&path[len], MAXPATHLEN - len, "%s", pf->anchor->name);
2005 
2006 	if (depth) {
2007 		if (TAILQ_FIRST(rs->rules[rs_num].active.ptr) != NULL) {
2008 			brace++;
2009 			if (pf->opts & PF_OPT_VERBOSE)
2010 				printf(" {\n");
2011 			if ((pf->opts & PF_OPT_NOACTION) == 0 &&
2012 			    (error = pfctl_ruleset_trans(pf,
2013 			    path, rs->anchor, false))) {
2014 				printf("pfctl_load_rulesets: "
2015 				    "pfctl_ruleset_trans %d\n", error);
2016 				goto error;
2017 			}
2018 		} else if (pf->opts & PF_OPT_VERBOSE)
2019 			printf("\n");
2020 
2021 	}
2022 
2023 	if (pf->optimize && rs_num == PF_RULESET_FILTER)
2024 		pfctl_optimize_ruleset(pf, rs);
2025 
2026 	while ((r = TAILQ_FIRST(rs->rules[rs_num].active.ptr)) != NULL) {
2027 		TAILQ_REMOVE(rs->rules[rs_num].active.ptr, r, entries);
2028 
2029 		for (int i = 0; i < PF_RULE_MAX_LABEL_COUNT; i++)
2030 			expand_label(r->label[i], PF_RULE_LABEL_SIZE, r);
2031 		expand_label(r->tagname, PF_TAG_NAME_SIZE, r);
2032 		expand_label(r->match_tagname, PF_TAG_NAME_SIZE, r);
2033 
2034 		if ((error = pfctl_load_rule(pf, path, r, depth)))
2035 			goto error;
2036 		if (r->anchor) {
2037 			if ((error = pfctl_load_ruleset(pf, path,
2038 			    &r->anchor->ruleset, rs_num, depth + 1)))
2039 				goto error;
2040 		} else if (pf->opts & PF_OPT_VERBOSE)
2041 			printf("\n");
2042 		free(r);
2043 	}
2044 	if (brace && pf->opts & PF_OPT_VERBOSE) {
2045 		INDENT(depth - 1, (pf->opts & PF_OPT_VERBOSE));
2046 		printf("}\n");
2047 	}
2048 	path[len] = '\0';
2049 	return (0);
2050 
2051  error:
2052 	path[len] = '\0';
2053 	return (error);
2054 
2055 }
2056 
2057 int
pfctl_load_rule(struct pfctl * pf,char * path,struct pfctl_rule * r,int depth)2058 pfctl_load_rule(struct pfctl *pf, char *path, struct pfctl_rule *r, int depth)
2059 {
2060 	u_int8_t		rs_num = pf_get_ruleset_number(r->action);
2061 	char			*name;
2062 	u_int32_t		ticket;
2063 	char			anchor[PF_ANCHOR_NAME_SIZE];
2064 	int			len = strlen(path);
2065 	int			error;
2066 	bool			was_present;
2067 
2068 	/* set up anchor before adding to path for anchor_call */
2069 	if ((pf->opts & PF_OPT_NOACTION) == 0)
2070 		ticket = pfctl_get_ticket(pf->trans, rs_num, path);
2071 	if (strlcpy(anchor, path, sizeof(anchor)) >= sizeof(anchor))
2072 		errx(1, "pfctl_load_rule: strlcpy");
2073 
2074 	if (r->anchor) {
2075 		if (r->anchor->match) {
2076 			if (path[0])
2077 				snprintf(&path[len], MAXPATHLEN - len,
2078 				    "/%s", r->anchor->name);
2079 			else
2080 				snprintf(&path[len], MAXPATHLEN - len,
2081 				    "%s", r->anchor->name);
2082 			name = r->anchor->name;
2083 		} else
2084 			name = r->anchor->path;
2085 	} else
2086 		name = "";
2087 
2088 	was_present = false;
2089 	if ((pf->opts & PF_OPT_NOACTION) == 0) {
2090 		if ((pf->opts & PF_OPT_NOACTION) == 0) {
2091 			if ((error = pfctl_begin_addrs(pf->h,
2092 			    &pf->paddr.ticket)) != 0)
2093 				errc(1, error, "DIOCBEGINADDRS");
2094 		}
2095 
2096 		if (pfctl_add_pool(pf, &r->rdr, r->af, PF_RDR))
2097 			return (1);
2098 		if (pfctl_add_pool(pf, &r->nat, r->naf ? r->naf : r->af, PF_NAT))
2099 			return (1);
2100 		if (pfctl_add_pool(pf, &r->route, r->af, PF_RT))
2101 			return (1);
2102 		error = pfctl_add_rule_h(pf->h, r, anchor, name, ticket,
2103 		    pf->paddr.ticket);
2104 		switch (error) {
2105 		case 0:
2106 			/* things worked, do nothing */
2107 			break;
2108 		case EEXIST:
2109 			/* an identical rule is already present */
2110 			was_present = true;
2111 			break;
2112 		default:
2113 			errc(1, error, "DIOCADDRULE");
2114 		}
2115 	}
2116 
2117 	if (pf->opts & PF_OPT_VERBOSE) {
2118 		INDENT(depth, !(pf->opts & PF_OPT_VERBOSE2));
2119 		print_rule(r, name,
2120 		    pf->opts & PF_OPT_VERBOSE2,
2121 		    pf->opts & PF_OPT_NUMERIC);
2122 		if (was_present)
2123 			printf(" -- rule was already present");
2124 	}
2125 	path[len] = '\0';
2126 	pfctl_clear_pool(&r->rdr);
2127 	pfctl_clear_pool(&r->nat);
2128 	return (0);
2129 }
2130 
2131 int
pfctl_add_altq(struct pfctl * pf,struct pf_altq * a)2132 pfctl_add_altq(struct pfctl *pf, struct pf_altq *a)
2133 {
2134 	if (altqsupport &&
2135 	    (loadopt & PFCTL_FLAG_ALTQ) != 0) {
2136 		memcpy(&pf->paltq->altq, a, sizeof(struct pf_altq));
2137 		if ((pf->opts & PF_OPT_NOACTION) == 0) {
2138 			if (ioctl(pf->dev, DIOCADDALTQ, pf->paltq)) {
2139 				if (errno == ENXIO)
2140 					errx(1, "qtype not configured");
2141 				else if (errno == ENODEV)
2142 					errx(1, "%s: driver does not support "
2143 					    "altq", a->ifname);
2144 				else
2145 					err(1, "DIOCADDALTQ");
2146 			}
2147 		}
2148 		pfaltq_store(&pf->paltq->altq);
2149 	}
2150 	return (0);
2151 }
2152 
2153 int
pfctl_rules(int dev,char * filename,int opts,int optimize,char * anchorname,struct pfr_buffer * trans)2154 pfctl_rules(int dev, char *filename, int opts, int optimize,
2155     char *anchorname, struct pfr_buffer *trans)
2156 {
2157 #define ERR(x) do { warn(x); goto _error; } while(0)
2158 #define ERRX(x) do { warnx(x); goto _error; } while(0)
2159 
2160 	struct pfr_buffer	*t, buf;
2161 	struct pfioc_altq	 pa;
2162 	struct pfctl		 pf;
2163 	struct pfctl_ruleset	*rs;
2164 	struct pfctl_eth_ruleset	*ethrs;
2165 	struct pfr_table	 trs;
2166 	char			*path;
2167 	int			 osize;
2168 
2169 	RB_INIT(&pf_anchors);
2170 	memset(&pf_main_anchor, 0, sizeof(pf_main_anchor));
2171 	pf_init_ruleset(&pf_main_anchor.ruleset);
2172 	pf_main_anchor.ruleset.anchor = &pf_main_anchor;
2173 
2174 	memset(&pf_eth_main_anchor, 0, sizeof(pf_eth_main_anchor));
2175 	pf_init_eth_ruleset(&pf_eth_main_anchor.ruleset);
2176 	pf_eth_main_anchor.ruleset.anchor = &pf_eth_main_anchor;
2177 
2178 	if (trans == NULL) {
2179 		bzero(&buf, sizeof(buf));
2180 		buf.pfrb_type = PFRB_TRANS;
2181 		t = &buf;
2182 		osize = 0;
2183 	} else {
2184 		t = trans;
2185 		osize = t->pfrb_size;
2186 	}
2187 
2188 	memset(&pa, 0, sizeof(pa));
2189 	pa.version = PFIOC_ALTQ_VERSION;
2190 	memset(&pf, 0, sizeof(pf));
2191 	memset(&trs, 0, sizeof(trs));
2192 	if ((path = calloc(1, MAXPATHLEN)) == NULL)
2193 		ERRX("pfctl_rules: calloc");
2194 	if (strlcpy(trs.pfrt_anchor, anchorname,
2195 	    sizeof(trs.pfrt_anchor)) >= sizeof(trs.pfrt_anchor))
2196 		ERRX("pfctl_rules: strlcpy");
2197 	pf.dev = dev;
2198 	pf.h = pfh;
2199 	pf.opts = opts;
2200 	pf.optimize = optimize;
2201 	pf.loadopt = loadopt;
2202 
2203 	/* non-brace anchor, create without resolving the path */
2204 	if ((pf.anchor = calloc(1, sizeof(*pf.anchor))) == NULL)
2205 		ERRX("pfctl_rules: calloc");
2206 	rs = &pf.anchor->ruleset;
2207 	pf_init_ruleset(rs);
2208 	rs->anchor = pf.anchor;
2209 	if (strlcpy(pf.anchor->path, anchorname,
2210 	    sizeof(pf.anchor->path)) >= sizeof(pf.anchor->path))
2211 		errx(1, "pfctl_rules: strlcpy");
2212 	if (strlcpy(pf.anchor->name, anchorname,
2213 	    sizeof(pf.anchor->name)) >= sizeof(pf.anchor->name))
2214 		errx(1, "pfctl_rules: strlcpy");
2215 
2216 
2217 	pf.astack[0] = pf.anchor;
2218 	pf.asd = 0;
2219 	if (anchorname[0])
2220 		pf.loadopt &= ~PFCTL_FLAG_ALTQ;
2221 	pf.paltq = &pa;
2222 	pf.trans = t;
2223 	pfctl_init_options(&pf);
2224 
2225 	/* Set up ethernet anchor */
2226 	if ((pf.eanchor = calloc(1, sizeof(*pf.eanchor))) == NULL)
2227 		ERRX("pfctl_rules: calloc");
2228 
2229 	if (strlcpy(pf.eanchor->path, anchorname,
2230 	    sizeof(pf.eanchor->path)) >= sizeof(pf.eanchor->path))
2231 		errx(1, "pfctl_rules: strlcpy");
2232 	if (strlcpy(pf.eanchor->name, anchorname,
2233 	    sizeof(pf.eanchor->name)) >= sizeof(pf.eanchor->name))
2234 		errx(1, "pfctl_rules: strlcpy");
2235 
2236 	ethrs = &pf.eanchor->ruleset;
2237 	pf_init_eth_ruleset(ethrs);
2238 	ethrs->anchor = pf.eanchor;
2239 	pf.eastack[0] = pf.eanchor;
2240 
2241 	if ((opts & PF_OPT_NOACTION) == 0) {
2242 		/*
2243 		 * XXX For the time being we need to open transactions for
2244 		 * the main ruleset before parsing, because tables are still
2245 		 * loaded at parse time.
2246 		 */
2247 		if (pfctl_ruleset_trans(&pf, anchorname, pf.anchor, true))
2248 			ERRX("pfctl_rules");
2249 		if (pf.loadopt & PFCTL_FLAG_ETH)
2250 			pf.eth_ticket = pfctl_get_ticket(t, PF_RULESET_ETH, anchorname);
2251 		if (altqsupport && (pf.loadopt & PFCTL_FLAG_ALTQ))
2252 			pa.ticket =
2253 			    pfctl_get_ticket(t, PF_RULESET_ALTQ, anchorname);
2254 		if (pf.loadopt & PFCTL_FLAG_TABLE)
2255 			pf.astack[0]->ruleset.tticket =
2256 			    pfctl_get_ticket(t, PF_RULESET_TABLE, anchorname);
2257 	}
2258 
2259 	if (parse_config(filename, &pf) < 0) {
2260 		if ((opts & PF_OPT_NOACTION) == 0)
2261 			ERRX("Syntax error in config file: "
2262 			    "pf rules not loaded");
2263 		else
2264 			goto _error;
2265 	}
2266 	if (loadopt & PFCTL_FLAG_OPTION)
2267 		pfctl_adjust_skip_ifaces(&pf);
2268 
2269 	if ((pf.loadopt & PFCTL_FLAG_FILTER &&
2270 	    (pfctl_load_ruleset(&pf, path, rs, PF_RULESET_SCRUB, 0))) ||
2271 	    (pf.loadopt & PFCTL_FLAG_ETH &&
2272 	    (pfctl_load_eth_ruleset(&pf, path, ethrs, 0))) ||
2273 	    (pf.loadopt & PFCTL_FLAG_NAT &&
2274 	    (pfctl_load_ruleset(&pf, path, rs, PF_RULESET_NAT, 0) ||
2275 	    pfctl_load_ruleset(&pf, path, rs, PF_RULESET_RDR, 0) ||
2276 	    pfctl_load_ruleset(&pf, path, rs, PF_RULESET_BINAT, 0))) ||
2277 	    (pf.loadopt & PFCTL_FLAG_FILTER &&
2278 	    pfctl_load_ruleset(&pf, path, rs, PF_RULESET_FILTER, 0))) {
2279 		if ((opts & PF_OPT_NOACTION) == 0)
2280 			ERRX("Unable to load rules into kernel");
2281 		else
2282 			goto _error;
2283 	}
2284 
2285 	if ((altqsupport && (pf.loadopt & PFCTL_FLAG_ALTQ) != 0))
2286 		if (check_commit_altq(dev, opts) != 0)
2287 			ERRX("errors in altq config");
2288 
2289 	/* process "load anchor" directives */
2290 	if (!anchorname[0])
2291 		if (pfctl_load_anchors(dev, &pf, t) == -1)
2292 			ERRX("load anchors");
2293 
2294 	if (trans == NULL && (opts & PF_OPT_NOACTION) == 0) {
2295 		if (!anchorname[0])
2296 			if (pfctl_load_options(&pf))
2297 				goto _error;
2298 		if (pfctl_trans(dev, t, DIOCXCOMMIT, osize))
2299 			ERR("DIOCXCOMMIT");
2300 	}
2301 	free(path);
2302 	return (0);
2303 
2304 _error:
2305 	if (trans == NULL) {	/* main ruleset */
2306 		if ((opts & PF_OPT_NOACTION) == 0)
2307 			if (pfctl_trans(dev, t, DIOCXROLLBACK, osize))
2308 				err(1, "DIOCXROLLBACK");
2309 		exit(1);
2310 	} else {		/* sub ruleset */
2311 		free(path);
2312 		return (-1);
2313 	}
2314 
2315 #undef ERR
2316 #undef ERRX
2317 }
2318 
2319 FILE *
pfctl_fopen(const char * name,const char * mode)2320 pfctl_fopen(const char *name, const char *mode)
2321 {
2322 	struct stat	 st;
2323 	FILE		*fp;
2324 
2325 	fp = fopen(name, mode);
2326 	if (fp == NULL)
2327 		return (NULL);
2328 	if (fstat(fileno(fp), &st)) {
2329 		fclose(fp);
2330 		return (NULL);
2331 	}
2332 	if (S_ISDIR(st.st_mode)) {
2333 		fclose(fp);
2334 		errno = EISDIR;
2335 		return (NULL);
2336 	}
2337 	return (fp);
2338 }
2339 
2340 void
pfctl_init_options(struct pfctl * pf)2341 pfctl_init_options(struct pfctl *pf)
2342 {
2343 
2344 	pf->timeout[PFTM_TCP_FIRST_PACKET] = PFTM_TCP_FIRST_PACKET_VAL;
2345 	pf->timeout[PFTM_TCP_OPENING] = PFTM_TCP_OPENING_VAL;
2346 	pf->timeout[PFTM_TCP_ESTABLISHED] = PFTM_TCP_ESTABLISHED_VAL;
2347 	pf->timeout[PFTM_TCP_CLOSING] = PFTM_TCP_CLOSING_VAL;
2348 	pf->timeout[PFTM_TCP_FIN_WAIT] = PFTM_TCP_FIN_WAIT_VAL;
2349 	pf->timeout[PFTM_TCP_CLOSED] = PFTM_TCP_CLOSED_VAL;
2350 	pf->timeout[PFTM_SCTP_FIRST_PACKET] = PFTM_TCP_FIRST_PACKET_VAL;
2351 	pf->timeout[PFTM_SCTP_OPENING] = PFTM_TCP_OPENING_VAL;
2352 	pf->timeout[PFTM_SCTP_ESTABLISHED] = PFTM_TCP_ESTABLISHED_VAL;
2353 	pf->timeout[PFTM_SCTP_CLOSING] = PFTM_TCP_CLOSING_VAL;
2354 	pf->timeout[PFTM_SCTP_CLOSED] = PFTM_TCP_CLOSED_VAL;
2355 	pf->timeout[PFTM_UDP_FIRST_PACKET] = PFTM_UDP_FIRST_PACKET_VAL;
2356 	pf->timeout[PFTM_UDP_SINGLE] = PFTM_UDP_SINGLE_VAL;
2357 	pf->timeout[PFTM_UDP_MULTIPLE] = PFTM_UDP_MULTIPLE_VAL;
2358 	pf->timeout[PFTM_ICMP_FIRST_PACKET] = PFTM_ICMP_FIRST_PACKET_VAL;
2359 	pf->timeout[PFTM_ICMP_ERROR_REPLY] = PFTM_ICMP_ERROR_REPLY_VAL;
2360 	pf->timeout[PFTM_OTHER_FIRST_PACKET] = PFTM_OTHER_FIRST_PACKET_VAL;
2361 	pf->timeout[PFTM_OTHER_SINGLE] = PFTM_OTHER_SINGLE_VAL;
2362 	pf->timeout[PFTM_OTHER_MULTIPLE] = PFTM_OTHER_MULTIPLE_VAL;
2363 	pf->timeout[PFTM_FRAG] = PFTM_FRAG_VAL;
2364 	pf->timeout[PFTM_INTERVAL] = PFTM_INTERVAL_VAL;
2365 	pf->timeout[PFTM_SRC_NODE] = PFTM_SRC_NODE_VAL;
2366 	pf->timeout[PFTM_TS_DIFF] = PFTM_TS_DIFF_VAL;
2367 	pf->timeout[PFTM_ADAPTIVE_START] = PFSTATE_ADAPT_START;
2368 	pf->timeout[PFTM_ADAPTIVE_END] = PFSTATE_ADAPT_END;
2369 
2370 	pf->limit[PF_LIMIT_STATES] = PFSTATE_HIWAT;
2371 	pf->limit[PF_LIMIT_FRAGS] = PFFRAG_FRENT_HIWAT;
2372 	pf->limit[PF_LIMIT_SRC_NODES] = PFSNODE_HIWAT;
2373 	pf->limit[PF_LIMIT_TABLE_ENTRIES] = PFR_KENTRY_HIWAT;
2374 
2375 	pf->debug = PF_DEBUG_URGENT;
2376 	pf->reassemble = 0;
2377 
2378 	pf->syncookies = false;
2379 	pf->syncookieswat[0] = PF_SYNCOOKIES_LOWATPCT;
2380 	pf->syncookieswat[1] = PF_SYNCOOKIES_HIWATPCT;
2381 }
2382 
2383 int
pfctl_load_options(struct pfctl * pf)2384 pfctl_load_options(struct pfctl *pf)
2385 {
2386 	int i, error = 0;
2387 
2388 	if ((loadopt & PFCTL_FLAG_OPTION) == 0)
2389 		return (0);
2390 
2391 	/* load limits */
2392 	for (i = 0; i < PF_LIMIT_MAX; i++) {
2393 		if ((pf->opts & PF_OPT_MERGE) && !pf->limit_set[i])
2394 			continue;
2395 		if (pfctl_load_limit(pf, i, pf->limit[i]))
2396 			error = 1;
2397 	}
2398 
2399 	/*
2400 	 * If we've set the limit, but haven't explicitly set adaptive
2401 	 * timeouts, do it now with a start of 60% and end of 120%.
2402 	 */
2403 	if (pf->limit_set[PF_LIMIT_STATES] &&
2404 	    !pf->timeout_set[PFTM_ADAPTIVE_START] &&
2405 	    !pf->timeout_set[PFTM_ADAPTIVE_END]) {
2406 		pf->timeout[PFTM_ADAPTIVE_START] =
2407 			(pf->limit[PF_LIMIT_STATES] / 10) * 6;
2408 		pf->timeout_set[PFTM_ADAPTIVE_START] = 1;
2409 		pf->timeout[PFTM_ADAPTIVE_END] =
2410 			(pf->limit[PF_LIMIT_STATES] / 10) * 12;
2411 		pf->timeout_set[PFTM_ADAPTIVE_END] = 1;
2412 	}
2413 
2414 	/* load timeouts */
2415 	for (i = 0; i < PFTM_MAX; i++) {
2416 		if ((pf->opts & PF_OPT_MERGE) && !pf->timeout_set[i])
2417 			continue;
2418 		if (pfctl_load_timeout(pf, i, pf->timeout[i]))
2419 			error = 1;
2420 	}
2421 
2422 	/* load debug */
2423 	if (!(pf->opts & PF_OPT_MERGE) || pf->debug_set)
2424 		if (pfctl_load_debug(pf, pf->debug))
2425 			error = 1;
2426 
2427 	/* load logif */
2428 	if (!(pf->opts & PF_OPT_MERGE) || pf->ifname_set)
2429 		if (pfctl_load_logif(pf, pf->ifname))
2430 			error = 1;
2431 
2432 	/* load hostid */
2433 	if (!(pf->opts & PF_OPT_MERGE) || pf->hostid_set)
2434 		if (pfctl_load_hostid(pf, pf->hostid))
2435 			error = 1;
2436 
2437 	/* load reassembly settings */
2438 	if (!(pf->opts & PF_OPT_MERGE) || pf->reass_set)
2439 		if (pfctl_load_reassembly(pf, pf->reassemble))
2440 			error = 1;
2441 
2442 	/* load keepcounters */
2443 	if (pfctl_set_keepcounters(pf->dev, pf->keep_counters))
2444 		error = 1;
2445 
2446 	/* load syncookies settings */
2447 	if (pfctl_load_syncookies(pf, pf->syncookies))
2448 		error = 1;
2449 
2450 	return (error);
2451 }
2452 
2453 int
pfctl_apply_limit(struct pfctl * pf,const char * opt,unsigned int limit)2454 pfctl_apply_limit(struct pfctl *pf, const char *opt, unsigned int limit)
2455 {
2456 	int i;
2457 
2458 
2459 	for (i = 0; pf_limits[i].name; i++) {
2460 		if (strcasecmp(opt, pf_limits[i].name) == 0) {
2461 			pf->limit[pf_limits[i].index] = limit;
2462 			pf->limit_set[pf_limits[i].index] = 1;
2463 			break;
2464 		}
2465 	}
2466 	if (pf_limits[i].name == NULL) {
2467 		warnx("Bad pool name.");
2468 		return (1);
2469 	}
2470 
2471 	if (pf->opts & PF_OPT_VERBOSE)
2472 		printf("set limit %s %d\n", opt, limit);
2473 
2474 	return (0);
2475 }
2476 
2477 int
pfctl_load_limit(struct pfctl * pf,unsigned int index,unsigned int limit)2478 pfctl_load_limit(struct pfctl *pf, unsigned int index, unsigned int limit)
2479 {
2480 	if (pfctl_set_limit(pf->h, index, limit)) {
2481 		if (errno == EBUSY)
2482 			warnx("Current pool size exceeds requested %s limit %u",
2483 			    pf_limits[index].name, limit);
2484 		else
2485 			warnx("Cannot set %s limit to %u",
2486 			    pf_limits[index].name, limit);
2487 		return (1);
2488 	}
2489 	return (0);
2490 }
2491 
2492 int
pfctl_apply_timeout(struct pfctl * pf,const char * opt,int seconds,int quiet)2493 pfctl_apply_timeout(struct pfctl *pf, const char *opt, int seconds, int quiet)
2494 {
2495 	int i;
2496 
2497 	if ((loadopt & PFCTL_FLAG_OPTION) == 0)
2498 		return (0);
2499 
2500 	for (i = 0; pf_timeouts[i].name; i++) {
2501 		if (strcasecmp(opt, pf_timeouts[i].name) == 0) {
2502 			pf->timeout[pf_timeouts[i].timeout] = seconds;
2503 			pf->timeout_set[pf_timeouts[i].timeout] = 1;
2504 			break;
2505 		}
2506 	}
2507 
2508 	if (pf_timeouts[i].name == NULL) {
2509 		warnx("Bad timeout name.");
2510 		return (1);
2511 	}
2512 
2513 
2514 	if (pf->opts & PF_OPT_VERBOSE && ! quiet)
2515 		printf("set timeout %s %d\n", opt, seconds);
2516 
2517 	return (0);
2518 }
2519 
2520 int
pfctl_load_timeout(struct pfctl * pf,unsigned int timeout,unsigned int seconds)2521 pfctl_load_timeout(struct pfctl *pf, unsigned int timeout, unsigned int seconds)
2522 {
2523 	if (pfctl_set_timeout(pf->h, timeout, seconds)) {
2524 		warnx("DIOCSETTIMEOUT");
2525 		return (1);
2526 	}
2527 	return (0);
2528 }
2529 
2530 int
pfctl_set_reassembly(struct pfctl * pf,int on,int nodf)2531 pfctl_set_reassembly(struct pfctl *pf, int on, int nodf)
2532 {
2533 	if ((loadopt & PFCTL_FLAG_OPTION) == 0)
2534 		return (0);
2535 
2536 	pf->reass_set = 1;
2537 	if (on) {
2538 		pf->reassemble = PF_REASS_ENABLED;
2539 		if (nodf)
2540 			pf->reassemble |= PF_REASS_NODF;
2541 	} else {
2542 		pf->reassemble = 0;
2543 	}
2544 
2545 	if (pf->opts & PF_OPT_VERBOSE)
2546 		printf("set reassemble %s %s\n", on ? "yes" : "no",
2547 		    nodf ? "no-df" : "");
2548 
2549 	return (0);
2550 }
2551 
2552 int
pfctl_set_optimization(struct pfctl * pf,const char * opt)2553 pfctl_set_optimization(struct pfctl *pf, const char *opt)
2554 {
2555 	const struct pf_hint *hint;
2556 	int i, r;
2557 
2558 	if ((loadopt & PFCTL_FLAG_OPTION) == 0)
2559 		return (0);
2560 
2561 	for (i = 0; pf_hints[i].name; i++)
2562 		if (strcasecmp(opt, pf_hints[i].name) == 0)
2563 			break;
2564 
2565 	hint = pf_hints[i].hint;
2566 	if (hint == NULL) {
2567 		warnx("invalid state timeouts optimization");
2568 		return (1);
2569 	}
2570 
2571 	for (i = 0; hint[i].name; i++)
2572 		if ((r = pfctl_apply_timeout(pf, hint[i].name,
2573 		    hint[i].timeout, 1)))
2574 			return (r);
2575 
2576 	if (pf->opts & PF_OPT_VERBOSE)
2577 		printf("set optimization %s\n", opt);
2578 
2579 	return (0);
2580 }
2581 
2582 int
pfctl_set_logif(struct pfctl * pf,char * ifname)2583 pfctl_set_logif(struct pfctl *pf, char *ifname)
2584 {
2585 
2586 	if ((loadopt & PFCTL_FLAG_OPTION) == 0)
2587 		return (0);
2588 
2589 	if (!strcmp(ifname, "none")) {
2590 		free(pf->ifname);
2591 		pf->ifname = NULL;
2592 	} else {
2593 		pf->ifname = strdup(ifname);
2594 		if (!pf->ifname)
2595 			errx(1, "pfctl_set_logif: strdup");
2596 	}
2597 	pf->ifname_set = 1;
2598 
2599 	if (pf->opts & PF_OPT_VERBOSE)
2600 		printf("set loginterface %s\n", ifname);
2601 
2602 	return (0);
2603 }
2604 
2605 int
pfctl_load_logif(struct pfctl * pf,char * ifname)2606 pfctl_load_logif(struct pfctl *pf, char *ifname)
2607 {
2608 	if (ifname != NULL && strlen(ifname) >= IFNAMSIZ) {
2609 		warnx("pfctl_load_logif: strlcpy");
2610 		return (1);
2611 	}
2612 	return (pfctl_set_statusif(pfh, ifname ? ifname : ""));
2613 }
2614 
2615 void
pfctl_set_hostid(struct pfctl * pf,u_int32_t hostid)2616 pfctl_set_hostid(struct pfctl *pf, u_int32_t hostid)
2617 {
2618 	if ((loadopt & PFCTL_FLAG_OPTION) == 0)
2619 		return;
2620 
2621 	HTONL(hostid);
2622 
2623 	pf->hostid = hostid;
2624 	pf->hostid_set = 1;
2625 
2626 	if (pf->opts & PF_OPT_VERBOSE)
2627 		printf("set hostid 0x%08x\n", ntohl(hostid));
2628 }
2629 
2630 int
pfctl_load_hostid(struct pfctl * pf,u_int32_t hostid)2631 pfctl_load_hostid(struct pfctl *pf, u_int32_t hostid)
2632 {
2633 	if (ioctl(dev, DIOCSETHOSTID, &hostid)) {
2634 		warnx("DIOCSETHOSTID");
2635 		return (1);
2636 	}
2637 	return (0);
2638 }
2639 
2640 int
pfctl_load_reassembly(struct pfctl * pf,u_int32_t reassembly)2641 pfctl_load_reassembly(struct pfctl *pf, u_int32_t reassembly)
2642 {
2643 	if (ioctl(dev, DIOCSETREASS, &reassembly)) {
2644 		warnx("DIOCSETREASS");
2645 		return (1);
2646 	}
2647 	return (0);
2648 }
2649 
2650 int
pfctl_load_syncookies(struct pfctl * pf,u_int8_t val)2651 pfctl_load_syncookies(struct pfctl *pf, u_int8_t val)
2652 {
2653 	struct pfctl_syncookies	cookies;
2654 
2655 	bzero(&cookies, sizeof(cookies));
2656 
2657 	cookies.mode = val;
2658 	cookies.lowwater = pf->syncookieswat[0];
2659 	cookies.highwater = pf->syncookieswat[1];
2660 
2661 	if (pfctl_set_syncookies(dev, &cookies)) {
2662 		warnx("DIOCSETSYNCOOKIES");
2663 		return (1);
2664 	}
2665 	return (0);
2666 }
2667 
2668 int
pfctl_cfg_syncookies(struct pfctl * pf,uint8_t val,struct pfctl_watermarks * w)2669 pfctl_cfg_syncookies(struct pfctl *pf, uint8_t val, struct pfctl_watermarks *w)
2670 {
2671 	if (val != PF_SYNCOOKIES_ADAPTIVE && w != NULL) {
2672 		warnx("syncookies start/end only apply to adaptive");
2673 		return (1);
2674 	}
2675 	if (val == PF_SYNCOOKIES_ADAPTIVE && w != NULL) {
2676 		if (!w->hi)
2677 			w->hi = PF_SYNCOOKIES_HIWATPCT;
2678 		if (!w->lo)
2679 			w->lo = w->hi / 2;
2680 		if (w->lo >= w->hi) {
2681 			warnx("start must be higher than end");
2682 			return (1);
2683 		}
2684 		pf->syncookieswat[0] = w->lo;
2685 		pf->syncookieswat[1] = w->hi;
2686 		pf->syncookieswat_set = 1;
2687 	}
2688 
2689 	if (pf->opts & PF_OPT_VERBOSE) {
2690 		if (val == PF_SYNCOOKIES_NEVER)
2691 			printf("set syncookies never\n");
2692 		else if (val == PF_SYNCOOKIES_ALWAYS)
2693 			printf("set syncookies always\n");
2694 		else if (val == PF_SYNCOOKIES_ADAPTIVE) {
2695 			if (pf->syncookieswat_set)
2696 				printf("set syncookies adaptive (start %u%%, "
2697 				    "end %u%%)\n", pf->syncookieswat[1],
2698 				    pf->syncookieswat[0]);
2699 			else
2700 				printf("set syncookies adaptive\n");
2701 		} else {        /* cannot happen */
2702 			warnx("king bula ate all syncookies");
2703 			return (1);
2704 		}
2705 	}
2706 
2707 	pf->syncookies = val;
2708 	return (0);
2709 }
2710 
2711 int
pfctl_do_set_debug(struct pfctl * pf,char * d)2712 pfctl_do_set_debug(struct pfctl *pf, char *d)
2713 {
2714 	u_int32_t	level;
2715 	int		ret;
2716 
2717 	if ((loadopt & PFCTL_FLAG_OPTION) == 0)
2718 		return (0);
2719 
2720 	if (!strcmp(d, "none"))
2721 		pf->debug = PF_DEBUG_NONE;
2722 	else if (!strcmp(d, "urgent"))
2723 		pf->debug = PF_DEBUG_URGENT;
2724 	else if (!strcmp(d, "misc"))
2725 		pf->debug = PF_DEBUG_MISC;
2726 	else if (!strcmp(d, "loud"))
2727 		pf->debug = PF_DEBUG_NOISY;
2728 	else {
2729 		warnx("unknown debug level \"%s\"", d);
2730 		return (-1);
2731 	}
2732 
2733 	pf->debug_set = 1;
2734 	level = pf->debug;
2735 
2736 	if ((pf->opts & PF_OPT_NOACTION) == 0)
2737 		if ((ret = pfctl_set_debug(pfh, level)) != 0)
2738 			errc(1, ret, "DIOCSETDEBUG");
2739 
2740 	if (pf->opts & PF_OPT_VERBOSE)
2741 		printf("set debug %s\n", d);
2742 
2743 	return (0);
2744 }
2745 
2746 int
pfctl_load_debug(struct pfctl * pf,unsigned int level)2747 pfctl_load_debug(struct pfctl *pf, unsigned int level)
2748 {
2749 	if (pfctl_set_debug(pf->h, level)) {
2750 		warnx("DIOCSETDEBUG");
2751 		return (1);
2752 	}
2753 	return (0);
2754 }
2755 
2756 int
pfctl_set_interface_flags(struct pfctl * pf,char * ifname,int flags,int how)2757 pfctl_set_interface_flags(struct pfctl *pf, char *ifname, int flags, int how)
2758 {
2759 	struct pfioc_iface	pi;
2760 	struct node_host	*h = NULL, *n = NULL;
2761 
2762 	if ((loadopt & PFCTL_FLAG_OPTION) == 0)
2763 		return (0);
2764 
2765 	bzero(&pi, sizeof(pi));
2766 
2767 	pi.pfiio_flags = flags;
2768 
2769 	/* Make sure our cache matches the kernel. If we set or clear the flag
2770 	 * for a group this applies to all members. */
2771 	h = ifa_grouplookup(ifname, 0);
2772 	for (n = h; n != NULL; n = n->next)
2773 		pfctl_set_interface_flags(pf, n->ifname, flags, how);
2774 
2775 	if (strlcpy(pi.pfiio_name, ifname, sizeof(pi.pfiio_name)) >=
2776 	    sizeof(pi.pfiio_name))
2777 		errx(1, "pfctl_set_interface_flags: strlcpy");
2778 
2779 	if ((pf->opts & PF_OPT_NOACTION) == 0) {
2780 		if (how == 0) {
2781 			if (ioctl(pf->dev, DIOCCLRIFFLAG, &pi))
2782 				err(1, "DIOCCLRIFFLAG");
2783 		} else {
2784 			if (ioctl(pf->dev, DIOCSETIFFLAG, &pi))
2785 				err(1, "DIOCSETIFFLAG");
2786 			pfctl_check_skip_ifaces(ifname);
2787 		}
2788 	}
2789 	return (0);
2790 }
2791 
2792 void
pfctl_debug(int dev,u_int32_t level,int opts)2793 pfctl_debug(int dev, u_int32_t level, int opts)
2794 {
2795 	int ret;
2796 
2797 	if ((ret = pfctl_set_debug(pfh, level)) != 0)
2798 		errc(1, ret, "DIOCSETDEBUG");
2799 	if ((opts & PF_OPT_QUIET) == 0) {
2800 		fprintf(stderr, "debug level set to '");
2801 		switch (level) {
2802 		case PF_DEBUG_NONE:
2803 			fprintf(stderr, "none");
2804 			break;
2805 		case PF_DEBUG_URGENT:
2806 			fprintf(stderr, "urgent");
2807 			break;
2808 		case PF_DEBUG_MISC:
2809 			fprintf(stderr, "misc");
2810 			break;
2811 		case PF_DEBUG_NOISY:
2812 			fprintf(stderr, "loud");
2813 			break;
2814 		default:
2815 			fprintf(stderr, "<invalid>");
2816 			break;
2817 		}
2818 		fprintf(stderr, "'\n");
2819 	}
2820 }
2821 
2822 int
pfctl_test_altqsupport(int dev,int opts)2823 pfctl_test_altqsupport(int dev, int opts)
2824 {
2825 	struct pfioc_altq pa;
2826 
2827 	pa.version = PFIOC_ALTQ_VERSION;
2828 	if (ioctl(dev, DIOCGETALTQS, &pa)) {
2829 		if (errno == ENODEV) {
2830 			if (opts & PF_OPT_VERBOSE)
2831 				fprintf(stderr, "No ALTQ support in kernel\n"
2832 				    "ALTQ related functions disabled\n");
2833 			return (0);
2834 		} else
2835 			err(1, "DIOCGETALTQS");
2836 	}
2837 	return (1);
2838 }
2839 
2840 int
pfctl_show_anchors(int dev,int opts,char * anchorname)2841 pfctl_show_anchors(int dev, int opts, char *anchorname)
2842 {
2843 	struct pfioc_ruleset	 pr;
2844 	u_int32_t		 mnr, nr;
2845 	int			 ret;
2846 
2847 	memset(&pr, 0, sizeof(pr));
2848 	if ((ret = pfctl_get_rulesets(pfh, anchorname, &mnr)) != 0) {
2849 		if (ret == EINVAL)
2850 			fprintf(stderr, "Anchor '%s' not found.\n",
2851 			    anchorname);
2852 		else
2853 			errc(1, ret, "DIOCGETRULESETS");
2854 		return (-1);
2855 	}
2856 	for (nr = 0; nr < mnr; ++nr) {
2857 		char sub[MAXPATHLEN];
2858 
2859 		if ((ret = pfctl_get_ruleset(pfh, anchorname, nr, &pr)) != 0)
2860 			errc(1, ret, "DIOCGETRULESET");
2861 		if (!strcmp(pr.name, PF_RESERVED_ANCHOR))
2862 			continue;
2863 		sub[0] = 0;
2864 		if (pr.path[0]) {
2865 			strlcat(sub, pr.path, sizeof(sub));
2866 			strlcat(sub, "/", sizeof(sub));
2867 		}
2868 		strlcat(sub, pr.name, sizeof(sub));
2869 		if (sub[0] != '_' || (opts & PF_OPT_VERBOSE))
2870 			printf("  %s\n", sub);
2871 		if ((opts & PF_OPT_VERBOSE) && pfctl_show_anchors(dev, opts, sub))
2872 			return (-1);
2873 	}
2874 	return (0);
2875 }
2876 
2877 int
pfctl_show_eth_anchors(int dev,int opts,char * anchorname)2878 pfctl_show_eth_anchors(int dev, int opts, char *anchorname)
2879 {
2880 	struct pfctl_eth_rulesets_info ri;
2881 	struct pfctl_eth_ruleset_info rs;
2882 	int ret;
2883 
2884 	if ((ret = pfctl_get_eth_rulesets_info(dev, &ri, anchorname)) != 0) {
2885 		if (ret == ENOENT)
2886 			fprintf(stderr, "Anchor '%s' not found.\n",
2887 			    anchorname);
2888 		else
2889 			errc(1, ret, "DIOCGETETHRULESETS");
2890 		return (-1);
2891 	}
2892 
2893 	for (int nr = 0; nr < ri.nr; nr++) {
2894 		char sub[MAXPATHLEN];
2895 
2896 		if ((ret = pfctl_get_eth_ruleset(dev, anchorname, nr, &rs)) != 0)
2897 			errc(1, ret, "DIOCGETETHRULESET");
2898 
2899 		if (!strcmp(rs.name, PF_RESERVED_ANCHOR))
2900 			continue;
2901 		sub[0] = 0;
2902 		if (rs.path[0]) {
2903 			strlcat(sub, rs.path, sizeof(sub));
2904 			strlcat(sub, "/", sizeof(sub));
2905 		}
2906 		strlcat(sub, rs.name, sizeof(sub));
2907 		if (sub[0] != '_' || (opts & PF_OPT_VERBOSE))
2908 			printf("  %s\n", sub);
2909 		if ((opts & PF_OPT_VERBOSE) && pfctl_show_eth_anchors(dev, opts, sub))
2910 			return (-1);
2911 	}
2912 	return (0);
2913 }
2914 
2915 const char *
pfctl_lookup_option(char * cmd,const char * const * list)2916 pfctl_lookup_option(char *cmd, const char * const *list)
2917 {
2918 	if (cmd != NULL && *cmd)
2919 		for (; *list; list++)
2920 			if (!strncmp(cmd, *list, strlen(cmd)))
2921 				return (*list);
2922 	return (NULL);
2923 }
2924 
2925 int
main(int argc,char * argv[])2926 main(int argc, char *argv[])
2927 {
2928 	int	 error = 0;
2929 	int	 ch;
2930 	int	 mode = O_RDONLY;
2931 	int	 opts = 0;
2932 	int	 optimize = PF_OPTIMIZE_BASIC;
2933 	char	 anchorname[MAXPATHLEN];
2934 	char	*path;
2935 
2936 	if (argc < 2)
2937 		usage();
2938 
2939 	while ((ch = getopt(argc, argv,
2940 	    "a:AdD:eqf:F:ghi:k:K:mMnNOo:Pp:rRs:t:T:vx:z")) != -1) {
2941 		switch (ch) {
2942 		case 'a':
2943 			anchoropt = optarg;
2944 			break;
2945 		case 'd':
2946 			opts |= PF_OPT_DISABLE;
2947 			mode = O_RDWR;
2948 			break;
2949 		case 'D':
2950 			if (pfctl_cmdline_symset(optarg) < 0)
2951 				warnx("could not parse macro definition %s",
2952 				    optarg);
2953 			break;
2954 		case 'e':
2955 			opts |= PF_OPT_ENABLE;
2956 			mode = O_RDWR;
2957 			break;
2958 		case 'q':
2959 			opts |= PF_OPT_QUIET;
2960 			break;
2961 		case 'F':
2962 			clearopt = pfctl_lookup_option(optarg, clearopt_list);
2963 			if (clearopt == NULL) {
2964 				warnx("Unknown flush modifier '%s'", optarg);
2965 				usage();
2966 			}
2967 			mode = O_RDWR;
2968 			break;
2969 		case 'i':
2970 			ifaceopt = optarg;
2971 			break;
2972 		case 'k':
2973 			if (state_killers >= 2) {
2974 				warnx("can only specify -k twice");
2975 				usage();
2976 				/* NOTREACHED */
2977 			}
2978 			state_kill[state_killers++] = optarg;
2979 			mode = O_RDWR;
2980 			break;
2981 		case 'K':
2982 			if (src_node_killers >= 2) {
2983 				warnx("can only specify -K twice");
2984 				usage();
2985 				/* NOTREACHED */
2986 			}
2987 			src_node_kill[src_node_killers++] = optarg;
2988 			mode = O_RDWR;
2989 			break;
2990 		case 'm':
2991 			opts |= PF_OPT_MERGE;
2992 			break;
2993 		case 'M':
2994 			opts |= PF_OPT_KILLMATCH;
2995 			break;
2996 		case 'n':
2997 			opts |= PF_OPT_NOACTION;
2998 			break;
2999 		case 'N':
3000 			loadopt |= PFCTL_FLAG_NAT;
3001 			break;
3002 		case 'r':
3003 			opts |= PF_OPT_USEDNS;
3004 			break;
3005 		case 'f':
3006 			rulesopt = optarg;
3007 			mode = O_RDWR;
3008 			break;
3009 		case 'g':
3010 			opts |= PF_OPT_DEBUG;
3011 			break;
3012 		case 'A':
3013 			loadopt |= PFCTL_FLAG_ALTQ;
3014 			break;
3015 		case 'R':
3016 			loadopt |= PFCTL_FLAG_FILTER;
3017 			break;
3018 		case 'o':
3019 			optiopt = pfctl_lookup_option(optarg, optiopt_list);
3020 			if (optiopt == NULL) {
3021 				warnx("Unknown optimization '%s'", optarg);
3022 				usage();
3023 			}
3024 			opts |= PF_OPT_OPTIMIZE;
3025 			break;
3026 		case 'O':
3027 			loadopt |= PFCTL_FLAG_OPTION;
3028 			break;
3029 		case 'p':
3030 			pf_device = optarg;
3031 			break;
3032 		case 'P':
3033 			opts |= PF_OPT_NUMERIC;
3034 			break;
3035 		case 's':
3036 			showopt = pfctl_lookup_option(optarg, showopt_list);
3037 			if (showopt == NULL) {
3038 				warnx("Unknown show modifier '%s'", optarg);
3039 				usage();
3040 			}
3041 			break;
3042 		case 't':
3043 			tableopt = optarg;
3044 			break;
3045 		case 'T':
3046 			tblcmdopt = pfctl_lookup_option(optarg, tblcmdopt_list);
3047 			if (tblcmdopt == NULL) {
3048 				warnx("Unknown table command '%s'", optarg);
3049 				usage();
3050 			}
3051 			break;
3052 		case 'v':
3053 			if (opts & PF_OPT_VERBOSE)
3054 				opts |= PF_OPT_VERBOSE2;
3055 			opts |= PF_OPT_VERBOSE;
3056 			break;
3057 		case 'x':
3058 			debugopt = pfctl_lookup_option(optarg, debugopt_list);
3059 			if (debugopt == NULL) {
3060 				warnx("Unknown debug level '%s'", optarg);
3061 				usage();
3062 			}
3063 			mode = O_RDWR;
3064 			break;
3065 		case 'z':
3066 			opts |= PF_OPT_CLRRULECTRS;
3067 			mode = O_RDWR;
3068 			break;
3069 		case 'h':
3070 			/* FALLTHROUGH */
3071 		default:
3072 			usage();
3073 			/* NOTREACHED */
3074 		}
3075 	}
3076 
3077 	if (tblcmdopt != NULL) {
3078 		argc -= optind;
3079 		argv += optind;
3080 		ch = *tblcmdopt;
3081 		if (ch == 'l') {
3082 			loadopt |= PFCTL_FLAG_TABLE;
3083 			tblcmdopt = NULL;
3084 		} else
3085 			mode = strchr("acdefkrz", ch) ? O_RDWR : O_RDONLY;
3086 	} else if (argc != optind) {
3087 		warnx("unknown command line argument: %s ...", argv[optind]);
3088 		usage();
3089 		/* NOTREACHED */
3090 	}
3091 	if (loadopt == 0)
3092 		loadopt = ~0;
3093 
3094 	if ((path = calloc(1, MAXPATHLEN)) == NULL)
3095 		errx(1, "pfctl: calloc");
3096 	memset(anchorname, 0, sizeof(anchorname));
3097 	if (anchoropt != NULL) {
3098 		int len = strlen(anchoropt);
3099 
3100 		if (len >= 1 && anchoropt[len - 1] == '*') {
3101 			if (len >= 2 && anchoropt[len - 2] == '/')
3102 				anchoropt[len - 2] = '\0';
3103 			else
3104 				anchoropt[len - 1] = '\0';
3105 			opts |= PF_OPT_RECURSE;
3106 		}
3107 		if (strlcpy(anchorname, anchoropt,
3108 		    sizeof(anchorname)) >= sizeof(anchorname))
3109 			errx(1, "anchor name '%s' too long",
3110 			    anchoropt);
3111 		loadopt &= PFCTL_FLAG_FILTER|PFCTL_FLAG_NAT|PFCTL_FLAG_TABLE|PFCTL_FLAG_ETH;
3112 	}
3113 
3114 	if ((opts & PF_OPT_NOACTION) == 0) {
3115 		dev = open(pf_device, mode);
3116 		if (dev == -1)
3117 			err(1, "%s", pf_device);
3118 		altqsupport = pfctl_test_altqsupport(dev, opts);
3119 	} else {
3120 		dev = open(pf_device, O_RDONLY);
3121 		if (dev >= 0)
3122 			opts |= PF_OPT_DUMMYACTION;
3123 		/* turn off options */
3124 		opts &= ~ (PF_OPT_DISABLE | PF_OPT_ENABLE);
3125 		clearopt = showopt = debugopt = NULL;
3126 #if !defined(ENABLE_ALTQ)
3127 		altqsupport = 0;
3128 #else
3129 		altqsupport = 1;
3130 #endif
3131 	}
3132 	pfh = pfctl_open(pf_device);
3133 	if (pfh == NULL)
3134 		err(1, "Failed to open netlink");
3135 
3136 	if (opts & PF_OPT_DISABLE)
3137 		if (pfctl_disable(dev, opts))
3138 			error = 1;
3139 
3140 	if (showopt != NULL) {
3141 		switch (*showopt) {
3142 		case 'A':
3143 			pfctl_show_anchors(dev, opts, anchorname);
3144 			if (opts & PF_OPT_VERBOSE2)
3145 				printf("Ethernet:\n");
3146 			pfctl_show_eth_anchors(dev, opts, anchorname);
3147 			break;
3148 		case 'r':
3149 			pfctl_load_fingerprints(dev, opts);
3150 			pfctl_show_rules(dev, path, opts, PFCTL_SHOW_RULES,
3151 			    anchorname, 0, 0);
3152 			break;
3153 		case 'l':
3154 			pfctl_load_fingerprints(dev, opts);
3155 			pfctl_show_rules(dev, path, opts, PFCTL_SHOW_LABELS,
3156 			    anchorname, 0, 0);
3157 			break;
3158 		case 'n':
3159 			pfctl_load_fingerprints(dev, opts);
3160 			pfctl_show_nat(dev, path, opts, anchorname, 0, 0);
3161 			break;
3162 		case 'q':
3163 			pfctl_show_altq(dev, ifaceopt, opts,
3164 			    opts & PF_OPT_VERBOSE2);
3165 			break;
3166 		case 's':
3167 			pfctl_show_states(dev, ifaceopt, opts);
3168 			break;
3169 		case 'S':
3170 			pfctl_show_src_nodes(dev, opts);
3171 			break;
3172 		case 'i':
3173 			pfctl_show_status(dev, opts);
3174 			break;
3175 		case 'R':
3176 			error = pfctl_show_running(dev);
3177 			break;
3178 		case 't':
3179 			pfctl_show_timeouts(dev, opts);
3180 			break;
3181 		case 'm':
3182 			pfctl_show_limits(dev, opts);
3183 			break;
3184 		case 'e':
3185 			pfctl_show_eth_rules(dev, path, opts, 0, anchorname, 0,
3186 			    0);
3187 			break;
3188 		case 'a':
3189 			opts |= PF_OPT_SHOWALL;
3190 			pfctl_load_fingerprints(dev, opts);
3191 
3192 			pfctl_show_eth_rules(dev, path, opts, 0, anchorname, 0,
3193 			    0);
3194 
3195 			pfctl_show_nat(dev, path, opts, anchorname, 0, 0);
3196 			pfctl_show_rules(dev, path, opts, 0, anchorname, 0, 0);
3197 			pfctl_show_altq(dev, ifaceopt, opts, 0);
3198 			pfctl_show_states(dev, ifaceopt, opts);
3199 			pfctl_show_src_nodes(dev, opts);
3200 			pfctl_show_status(dev, opts);
3201 			pfctl_show_rules(dev, path, opts, 1, anchorname, 0, 0);
3202 			pfctl_show_timeouts(dev, opts);
3203 			pfctl_show_limits(dev, opts);
3204 			pfctl_show_tables(anchorname, opts);
3205 			pfctl_show_fingerprints(opts);
3206 			break;
3207 		case 'T':
3208 			pfctl_show_tables(anchorname, opts);
3209 			break;
3210 		case 'o':
3211 			pfctl_load_fingerprints(dev, opts);
3212 			pfctl_show_fingerprints(opts);
3213 			break;
3214 		case 'I':
3215 			pfctl_show_ifaces(ifaceopt, opts);
3216 			break;
3217 		case 'c':
3218 			pfctl_show_creators(opts);
3219 			break;
3220 		}
3221 	}
3222 
3223 	if ((opts & PF_OPT_CLRRULECTRS) && showopt == NULL) {
3224 		pfctl_show_eth_rules(dev, path, opts, PFCTL_SHOW_NOTHING,
3225 		    anchorname, 0, 0);
3226 		pfctl_show_rules(dev, path, opts, PFCTL_SHOW_NOTHING,
3227 		    anchorname, 0, 0);
3228 	}
3229 
3230 	if (clearopt != NULL) {
3231 		if (anchorname[0] == '_' || strstr(anchorname, "/_") != NULL)
3232 			errx(1, "anchor names beginning with '_' cannot "
3233 			    "be modified from the command line");
3234 
3235 		switch (*clearopt) {
3236 		case 'e':
3237 			pfctl_flush_eth_rules(dev, opts, anchorname);
3238 			break;
3239 		case 'r':
3240 			pfctl_flush_rules(dev, opts, anchorname);
3241 			break;
3242 		case 'n':
3243 			pfctl_flush_nat(dev, opts, anchorname);
3244 			break;
3245 		case 'q':
3246 			pfctl_clear_altq(dev, opts);
3247 			break;
3248 		case 's':
3249 			pfctl_clear_iface_states(dev, ifaceopt, opts);
3250 			break;
3251 		case 'S':
3252 			pfctl_clear_src_nodes(dev, opts);
3253 			break;
3254 		case 'i':
3255 			pfctl_clear_stats(pfh, opts);
3256 			break;
3257 		case 'a':
3258 			pfctl_flush_eth_rules(dev, opts, anchorname);
3259 			pfctl_flush_rules(dev, opts, anchorname);
3260 			pfctl_flush_nat(dev, opts, anchorname);
3261 			pfctl_do_clear_tables(anchorname, opts);
3262 			if (!*anchorname) {
3263 				pfctl_clear_altq(dev, opts);
3264 				pfctl_clear_iface_states(dev, ifaceopt, opts);
3265 				pfctl_clear_src_nodes(dev, opts);
3266 				pfctl_clear_stats(pfh, opts);
3267 				pfctl_clear_fingerprints(dev, opts);
3268 				pfctl_clear_interface_flags(dev, opts);
3269 			}
3270 			break;
3271 		case 'o':
3272 			pfctl_clear_fingerprints(dev, opts);
3273 			break;
3274 		case 'T':
3275 			pfctl_do_clear_tables(anchorname, opts);
3276 			break;
3277 		}
3278 	}
3279 	if (state_killers) {
3280 		if (!strcmp(state_kill[0], "label"))
3281 			pfctl_label_kill_states(dev, ifaceopt, opts);
3282 		else if (!strcmp(state_kill[0], "id"))
3283 			pfctl_id_kill_states(dev, ifaceopt, opts);
3284 		else if (!strcmp(state_kill[0], "gateway"))
3285 			pfctl_gateway_kill_states(dev, ifaceopt, opts);
3286 		else
3287 			pfctl_net_kill_states(dev, ifaceopt, opts);
3288 	}
3289 
3290 	if (src_node_killers)
3291 		pfctl_kill_src_nodes(dev, ifaceopt, opts);
3292 
3293 	if (tblcmdopt != NULL) {
3294 		error = pfctl_command_tables(argc, argv, tableopt,
3295 		    tblcmdopt, rulesopt, anchorname, opts);
3296 		rulesopt = NULL;
3297 	}
3298 	if (optiopt != NULL) {
3299 		switch (*optiopt) {
3300 		case 'n':
3301 			optimize = 0;
3302 			break;
3303 		case 'b':
3304 			optimize |= PF_OPTIMIZE_BASIC;
3305 			break;
3306 		case 'o':
3307 		case 'p':
3308 			optimize |= PF_OPTIMIZE_PROFILE;
3309 			break;
3310 		}
3311 	}
3312 
3313 	if ((rulesopt != NULL) && (loadopt & PFCTL_FLAG_OPTION) &&
3314 	    !anchorname[0] && !(opts & PF_OPT_NOACTION))
3315 		if (pfctl_get_skip_ifaces())
3316 			error = 1;
3317 
3318 	if (rulesopt != NULL && !(opts & PF_OPT_MERGE) &&
3319 	    !anchorname[0] && (loadopt & PFCTL_FLAG_OPTION))
3320 		if (pfctl_file_fingerprints(dev, opts, PF_OSFP_FILE))
3321 			error = 1;
3322 
3323 	if (rulesopt != NULL) {
3324 		if (anchorname[0] == '_' || strstr(anchorname, "/_") != NULL)
3325 			errx(1, "anchor names beginning with '_' cannot "
3326 			    "be modified from the command line");
3327 		if (pfctl_rules(dev, rulesopt, opts, optimize,
3328 		    anchorname, NULL))
3329 			error = 1;
3330 		else if (!(opts & PF_OPT_NOACTION) &&
3331 		    (loadopt & PFCTL_FLAG_TABLE))
3332 			warn_namespace_collision(NULL);
3333 	}
3334 
3335 	if (opts & PF_OPT_ENABLE)
3336 		if (pfctl_enable(dev, opts))
3337 			error = 1;
3338 
3339 	if (debugopt != NULL) {
3340 		switch (*debugopt) {
3341 		case 'n':
3342 			pfctl_debug(dev, PF_DEBUG_NONE, opts);
3343 			break;
3344 		case 'u':
3345 			pfctl_debug(dev, PF_DEBUG_URGENT, opts);
3346 			break;
3347 		case 'm':
3348 			pfctl_debug(dev, PF_DEBUG_MISC, opts);
3349 			break;
3350 		case 'l':
3351 			pfctl_debug(dev, PF_DEBUG_NOISY, opts);
3352 			break;
3353 		}
3354 	}
3355 
3356 	exit(error);
3357 }
3358