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