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