xref: /openbsd/sbin/pfctl/pfctl_parser.c (revision 19e99d06)
1 /*	$OpenBSD: pfctl_parser.c,v 1.351 2024/04/22 13:30:22 bluhm Exp $ */
2 
3 /*
4  * Copyright (c) 2001 Daniel Hartmeier
5  * Copyright (c) 2002 - 2013 Henning Brauer <henning@openbsd.org>
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  *    - Redistributions of source code must retain the above copyright
13  *      notice, this list of conditions and the following disclaimer.
14  *    - Redistributions in binary form must reproduce the above
15  *      copyright notice, this list of conditions and the following
16  *      disclaimer in the documentation and/or other materials provided
17  *      with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
22  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
23  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
24  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
25  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
26  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
27  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
29  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30  * POSSIBILITY OF SUCH DAMAGE.
31  *
32  */
33 
34 #include <sys/types.h>
35 #include <sys/ioctl.h>
36 #include <sys/socket.h>
37 #include <net/if_dl.h>
38 #include <net/if.h>
39 #include <netinet/in.h>
40 #include <netinet/ip.h>
41 #include <netinet/ip_icmp.h>
42 #include <netinet/icmp6.h>
43 #include <net/pfvar.h>
44 #include <arpa/inet.h>
45 
46 #include <ctype.h>
47 #include <err.h>
48 #include <errno.h>
49 #include <ifaddrs.h>
50 #include <limits.h>
51 #include <netdb.h>
52 #include <stdarg.h>
53 #include <stdio.h>
54 #include <stdlib.h>
55 #include <string.h>
56 #include <time.h>
57 #include <unistd.h>
58 
59 #define SYSLOG_NAMES
60 #include <syslog.h>
61 
62 #include "pfctl_parser.h"
63 #include "pfctl.h"
64 
65 #ifndef nitems
66 #define nitems(_a)	(sizeof((_a)) / sizeof((_a)[0]))
67 #endif
68 
69 void		 print_op (u_int8_t, const char *, const char *);
70 void		 print_port (u_int8_t, u_int16_t, u_int16_t, const char *, int);
71 void		 print_ugid (u_int8_t, id_t, id_t, const char *);
72 void		 print_flags (u_int8_t);
73 void		 print_fromto(struct pf_rule_addr *, pf_osfp_t,
74 		    struct pf_rule_addr *, u_int8_t, u_int8_t, int);
75 void		 print_bwspec(const char *index, struct pf_queue_bwspec *);
76 void		 print_scspec(const char *, struct pf_queue_scspec *);
77 int		 ifa_skip_if(const char *filter, struct node_host *p);
78 
79 struct node_host	*ifa_grouplookup(const char *, int);
80 struct node_host	*host_if(const char *, int);
81 struct node_host	*host_ip(const char *, int);
82 struct node_host	*host_dns(const char *, int, int);
83 
84 const char *tcpflags = "FSRPAUEW";
85 
86 static const struct icmptypeent icmp_type[] = {
87 	{ "echoreq",	ICMP_ECHO },
88 	{ "echorep",	ICMP_ECHOREPLY },
89 	{ "unreach",	ICMP_UNREACH },
90 	{ "squench",	ICMP_SOURCEQUENCH },
91 	{ "redir",	ICMP_REDIRECT },
92 	{ "althost",	ICMP_ALTHOSTADDR },
93 	{ "routeradv",	ICMP_ROUTERADVERT },
94 	{ "routersol",	ICMP_ROUTERSOLICIT },
95 	{ "timex",	ICMP_TIMXCEED },
96 	{ "paramprob",	ICMP_PARAMPROB },
97 	{ "timereq",	ICMP_TSTAMP },
98 	{ "timerep",	ICMP_TSTAMPREPLY },
99 	{ "inforeq",	ICMP_IREQ },
100 	{ "inforep",	ICMP_IREQREPLY },
101 	{ "maskreq",	ICMP_MASKREQ },
102 	{ "maskrep",	ICMP_MASKREPLY },
103 	{ "trace",	ICMP_TRACEROUTE },
104 	{ "dataconv",	ICMP_DATACONVERR },
105 	{ "mobredir",	ICMP_MOBILE_REDIRECT },
106 	{ "ipv6-where",	ICMP_IPV6_WHEREAREYOU },
107 	{ "ipv6-here",	ICMP_IPV6_IAMHERE },
108 	{ "mobregreq",	ICMP_MOBILE_REGREQUEST },
109 	{ "mobregrep",	ICMP_MOBILE_REGREPLY },
110 	{ "skip",	ICMP_SKIP },
111 	{ "photuris",	ICMP_PHOTURIS }
112 };
113 
114 static const struct icmptypeent icmp6_type[] = {
115 	{ "unreach",	ICMP6_DST_UNREACH },
116 	{ "toobig",	ICMP6_PACKET_TOO_BIG },
117 	{ "timex",	ICMP6_TIME_EXCEEDED },
118 	{ "paramprob",	ICMP6_PARAM_PROB },
119 	{ "echoreq",	ICMP6_ECHO_REQUEST },
120 	{ "echorep",	ICMP6_ECHO_REPLY },
121 	{ "groupqry",	ICMP6_MEMBERSHIP_QUERY },
122 	{ "listqry",	MLD_LISTENER_QUERY },
123 	{ "grouprep",	ICMP6_MEMBERSHIP_REPORT },
124 	{ "listenrep",	MLD_LISTENER_REPORT },
125 	{ "groupterm",	ICMP6_MEMBERSHIP_REDUCTION },
126 	{ "listendone", MLD_LISTENER_DONE },
127 	{ "routersol",	ND_ROUTER_SOLICIT },
128 	{ "routeradv",	ND_ROUTER_ADVERT },
129 	{ "neighbrsol", ND_NEIGHBOR_SOLICIT },
130 	{ "neighbradv", ND_NEIGHBOR_ADVERT },
131 	{ "redir",	ND_REDIRECT },
132 	{ "routrrenum", ICMP6_ROUTER_RENUMBERING },
133 	{ "wrureq",	ICMP6_WRUREQUEST },
134 	{ "wrurep",	ICMP6_WRUREPLY },
135 	{ "fqdnreq",	ICMP6_FQDN_QUERY },
136 	{ "fqdnrep",	ICMP6_FQDN_REPLY },
137 	{ "niqry",	ICMP6_NI_QUERY },
138 	{ "nirep",	ICMP6_NI_REPLY },
139 	{ "mtraceresp",	MLD_MTRACE_RESP },
140 	{ "mtrace",	MLD_MTRACE },
141 	{ "listenrepv2", MLDV2_LISTENER_REPORT },
142 };
143 
144 static const struct icmpcodeent icmp_code[] = {
145 	{ "net-unr",		ICMP_UNREACH,	ICMP_UNREACH_NET },
146 	{ "host-unr",		ICMP_UNREACH,	ICMP_UNREACH_HOST },
147 	{ "proto-unr",		ICMP_UNREACH,	ICMP_UNREACH_PROTOCOL },
148 	{ "port-unr",		ICMP_UNREACH,	ICMP_UNREACH_PORT },
149 	{ "needfrag",		ICMP_UNREACH,	ICMP_UNREACH_NEEDFRAG },
150 	{ "srcfail",		ICMP_UNREACH,	ICMP_UNREACH_SRCFAIL },
151 	{ "net-unk",		ICMP_UNREACH,	ICMP_UNREACH_NET_UNKNOWN },
152 	{ "host-unk",		ICMP_UNREACH,	ICMP_UNREACH_HOST_UNKNOWN },
153 	{ "isolate",		ICMP_UNREACH,	ICMP_UNREACH_ISOLATED },
154 	{ "net-prohib",		ICMP_UNREACH,	ICMP_UNREACH_NET_PROHIB },
155 	{ "host-prohib",	ICMP_UNREACH,	ICMP_UNREACH_HOST_PROHIB },
156 	{ "net-tos",		ICMP_UNREACH,	ICMP_UNREACH_TOSNET },
157 	{ "host-tos",		ICMP_UNREACH,	ICMP_UNREACH_TOSHOST },
158 	{ "filter-prohib",	ICMP_UNREACH,	ICMP_UNREACH_FILTER_PROHIB },
159 	{ "host-preced",	ICMP_UNREACH,	ICMP_UNREACH_HOST_PRECEDENCE },
160 	{ "cutoff-preced",	ICMP_UNREACH,	ICMP_UNREACH_PRECEDENCE_CUTOFF },
161 	{ "redir-net",		ICMP_REDIRECT,	ICMP_REDIRECT_NET },
162 	{ "redir-host",		ICMP_REDIRECT,	ICMP_REDIRECT_HOST },
163 	{ "redir-tos-net",	ICMP_REDIRECT,	ICMP_REDIRECT_TOSNET },
164 	{ "redir-tos-host",	ICMP_REDIRECT,	ICMP_REDIRECT_TOSHOST },
165 	{ "normal-adv",		ICMP_ROUTERADVERT, ICMP_ROUTERADVERT_NORMAL },
166 	{ "common-adv",		ICMP_ROUTERADVERT, ICMP_ROUTERADVERT_NOROUTE_COMMON },
167 	{ "transit",		ICMP_TIMXCEED,	ICMP_TIMXCEED_INTRANS },
168 	{ "reassemb",		ICMP_TIMXCEED,	ICMP_TIMXCEED_REASS },
169 	{ "badhead",		ICMP_PARAMPROB,	ICMP_PARAMPROB_ERRATPTR },
170 	{ "optmiss",		ICMP_PARAMPROB,	ICMP_PARAMPROB_OPTABSENT },
171 	{ "badlen",		ICMP_PARAMPROB,	ICMP_PARAMPROB_LENGTH },
172 	{ "unknown-ind",	ICMP_PHOTURIS,	ICMP_PHOTURIS_UNKNOWN_INDEX },
173 	{ "auth-fail",		ICMP_PHOTURIS,	ICMP_PHOTURIS_AUTH_FAILED },
174 	{ "decrypt-fail",	ICMP_PHOTURIS,	ICMP_PHOTURIS_DECRYPT_FAILED }
175 };
176 
177 static const struct icmpcodeent icmp6_code[] = {
178 	{ "admin-unr", ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADMIN },
179 	{ "noroute-unr", ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_NOROUTE },
180 	{ "beyond-unr", ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_BEYONDSCOPE },
181 	{ "addr-unr", ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR },
182 	{ "port-unr", ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_NOPORT },
183 	{ "transit", ICMP6_TIME_EXCEEDED, ICMP6_TIME_EXCEED_TRANSIT },
184 	{ "reassemb", ICMP6_TIME_EXCEEDED, ICMP6_TIME_EXCEED_REASSEMBLY },
185 	{ "badhead", ICMP6_PARAM_PROB, ICMP6_PARAMPROB_HEADER },
186 	{ "nxthdr", ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER },
187 	{ "redironlink", ND_REDIRECT, ND_REDIRECT_ONLINK },
188 	{ "redirrouter", ND_REDIRECT, ND_REDIRECT_ROUTER }
189 };
190 
191 const struct pf_timeout pf_timeouts[] = {
192 	{ "tcp.first",		PFTM_TCP_FIRST_PACKET },
193 	{ "tcp.opening",	PFTM_TCP_OPENING },
194 	{ "tcp.established",	PFTM_TCP_ESTABLISHED },
195 	{ "tcp.closing",	PFTM_TCP_CLOSING },
196 	{ "tcp.finwait",	PFTM_TCP_FIN_WAIT },
197 	{ "tcp.closed",		PFTM_TCP_CLOSED },
198 	{ "tcp.tsdiff",		PFTM_TS_DIFF },
199 	{ "udp.first",		PFTM_UDP_FIRST_PACKET },
200 	{ "udp.single",		PFTM_UDP_SINGLE },
201 	{ "udp.multiple",	PFTM_UDP_MULTIPLE },
202 	{ "icmp.first",		PFTM_ICMP_FIRST_PACKET },
203 	{ "icmp.error",		PFTM_ICMP_ERROR_REPLY },
204 	{ "other.first",	PFTM_OTHER_FIRST_PACKET },
205 	{ "other.single",	PFTM_OTHER_SINGLE },
206 	{ "other.multiple",	PFTM_OTHER_MULTIPLE },
207 	{ "frag",		PFTM_FRAG },
208 	{ "interval",		PFTM_INTERVAL },
209 	{ "adaptive.start",	PFTM_ADAPTIVE_START },
210 	{ "adaptive.end",	PFTM_ADAPTIVE_END },
211 	{ "src.track",		PFTM_SRC_NODE },
212 	{ NULL,			0 }
213 };
214 
215 enum { PF_POOL_ROUTE, PF_POOL_NAT, PF_POOL_RDR };
216 
217 void
copy_satopfaddr(struct pf_addr * pfa,struct sockaddr * sa)218 copy_satopfaddr(struct pf_addr *pfa, struct sockaddr *sa)
219 {
220 	if (sa->sa_family == AF_INET6)
221 		pfa->v6 = ((struct sockaddr_in6 *)sa)->sin6_addr;
222 	else if (sa->sa_family == AF_INET)
223 		pfa->v4 = ((struct sockaddr_in *)sa)->sin_addr;
224 	else
225 		warnx("unhandled af %d", sa->sa_family);
226 }
227 
228 const struct icmptypeent *
geticmptypebynumber(u_int8_t type,sa_family_t af)229 geticmptypebynumber(u_int8_t type, sa_family_t af)
230 {
231 	size_t	i;
232 
233 	if (af != AF_INET6) {
234 		for (i = 0; i < nitems(icmp_type); i++) {
235 			if (type == icmp_type[i].type)
236 				return (&icmp_type[i]);
237 		}
238 	} else {
239 		for (i = 0; i < nitems(icmp6_type); i++) {
240 			if (type == icmp6_type[i].type)
241 				 return (&icmp6_type[i]);
242 		}
243 	}
244 	return (NULL);
245 }
246 
247 const struct icmptypeent *
geticmptypebyname(char * w,sa_family_t af)248 geticmptypebyname(char *w, sa_family_t af)
249 {
250 	size_t	i;
251 
252 	if (af != AF_INET6) {
253 		for (i = 0; i < nitems(icmp_type); i++) {
254 			if (!strcmp(w, icmp_type[i].name))
255 				return (&icmp_type[i]);
256 		}
257 	} else {
258 		for (i = 0; i < nitems(icmp6_type); i++) {
259 			if (!strcmp(w, icmp6_type[i].name))
260 				return (&icmp6_type[i]);
261 		}
262 	}
263 	return (NULL);
264 }
265 
266 const struct icmpcodeent *
geticmpcodebynumber(u_int8_t type,u_int8_t code,sa_family_t af)267 geticmpcodebynumber(u_int8_t type, u_int8_t code, sa_family_t af)
268 {
269 	size_t	i;
270 
271 	if (af != AF_INET6) {
272 		for (i = 0; i < nitems(icmp_code); i++) {
273 			if (type == icmp_code[i].type &&
274 			    code == icmp_code[i].code)
275 				return (&icmp_code[i]);
276 		}
277 	} else {
278 		for (i = 0; i < nitems(icmp6_code); i++) {
279 			if (type == icmp6_code[i].type &&
280 			    code == icmp6_code[i].code)
281 				return (&icmp6_code[i]);
282 		}
283 	}
284 	return (NULL);
285 }
286 
287 const struct icmpcodeent *
geticmpcodebyname(u_long type,char * w,sa_family_t af)288 geticmpcodebyname(u_long type, char *w, sa_family_t af)
289 {
290 	size_t	i;
291 
292 	if (af != AF_INET6) {
293 		for (i = 0; i < nitems(icmp_code); i++) {
294 			if (type == icmp_code[i].type &&
295 			    !strcmp(w, icmp_code[i].name))
296 				return (&icmp_code[i]);
297 		}
298 	} else {
299 		for (i = 0; i < nitems(icmp6_code); i++) {
300 			if (type == icmp6_code[i].type &&
301 			    !strcmp(w, icmp6_code[i].name))
302 				return (&icmp6_code[i]);
303 		}
304 	}
305 	return (NULL);
306 }
307 
308 /*
309  *  Decode a symbolic name to a numeric value.
310  *  From syslogd.
311  */
312 int
string_to_loglevel(const char * name)313 string_to_loglevel(const char *name)
314 {
315 	CODE *c;
316 	char *p, buf[40];
317 
318 	if (isdigit((unsigned char)*name)) {
319 		const char *errstr;
320 		int val;
321 
322 		val = strtonum(name, 0, LOG_DEBUG, &errstr);
323 		if (errstr)
324 			return -1;
325 		return val;
326 	}
327 
328 	for (p = buf; *name && p < &buf[sizeof(buf) - 1]; p++, name++) {
329 		if (isupper((unsigned char)*name))
330 			*p = tolower((unsigned char)*name);
331 		else
332 			*p = *name;
333 	}
334 	*p = '\0';
335 	for (c = prioritynames; c->c_name; c++)
336 		if (!strcmp(buf, c->c_name) && c->c_val != INTERNAL_NOPRI)
337 			return (c->c_val);
338 
339 	return (-1);
340 }
341 
342 const char *
loglevel_to_string(int level)343 loglevel_to_string(int level)
344 {
345 	CODE *c;
346 
347 	for (c = prioritynames; c->c_name; c++)
348 		if (c->c_val == level)
349 			return (c->c_name);
350 
351 	return ("unknown");
352 }
353 
354 void
print_op(u_int8_t op,const char * a1,const char * a2)355 print_op(u_int8_t op, const char *a1, const char *a2)
356 {
357 	if (op == PF_OP_IRG)
358 		printf(" %s >< %s", a1, a2);
359 	else if (op == PF_OP_XRG)
360 		printf(" %s <> %s", a1, a2);
361 	else if (op == PF_OP_EQ)
362 		printf(" = %s", a1);
363 	else if (op == PF_OP_NE)
364 		printf(" != %s", a1);
365 	else if (op == PF_OP_LT)
366 		printf(" < %s", a1);
367 	else if (op == PF_OP_LE)
368 		printf(" <= %s", a1);
369 	else if (op == PF_OP_GT)
370 		printf(" > %s", a1);
371 	else if (op == PF_OP_GE)
372 		printf(" >= %s", a1);
373 	else if (op == PF_OP_RRG)
374 		printf(" %s:%s", a1, a2);
375 }
376 
377 void
print_port(u_int8_t op,u_int16_t p1,u_int16_t p2,const char * proto,int opts)378 print_port(u_int8_t op, u_int16_t p1, u_int16_t p2, const char *proto, int opts)
379 {
380 	char		 a1[6], a2[6];
381 	struct servent	*s = NULL;
382 
383 	if (opts & PF_OPT_PORTNAMES)
384 		s = getservbyport(p1, proto);
385 	p1 = ntohs(p1);
386 	p2 = ntohs(p2);
387 	snprintf(a1, sizeof(a1), "%u", p1);
388 	snprintf(a2, sizeof(a2), "%u", p2);
389 	printf(" port");
390 	if (s != NULL && (op == PF_OP_EQ || op == PF_OP_NE))
391 		print_op(op, s->s_name, a2);
392 	else
393 		print_op(op, a1, a2);
394 }
395 
396 void
print_ugid(u_int8_t op,id_t i1,id_t i2,const char * t)397 print_ugid(u_int8_t op, id_t i1, id_t i2, const char *t)
398 {
399 	char	a1[11], a2[11];
400 
401 	snprintf(a1, sizeof(a1), "%u", i1);
402 	snprintf(a2, sizeof(a2), "%u", i2);
403 	printf(" %s", t);
404 	if (i1 == -1 && (op == PF_OP_EQ || op == PF_OP_NE))
405 		print_op(op, "unknown", a2);
406 	else
407 		print_op(op, a1, a2);
408 }
409 
410 void
print_flags(u_int8_t f)411 print_flags(u_int8_t f)
412 {
413 	int	i;
414 
415 	for (i = 0; tcpflags[i]; ++i)
416 		if (f & (1 << i))
417 			printf("%c", tcpflags[i]);
418 }
419 
420 void
print_fromto(struct pf_rule_addr * src,pf_osfp_t osfp,struct pf_rule_addr * dst,sa_family_t af,u_int8_t proto,int opts)421 print_fromto(struct pf_rule_addr *src, pf_osfp_t osfp, struct pf_rule_addr *dst,
422     sa_family_t af, u_int8_t proto, int opts)
423 {
424 	char buf[PF_OSFP_LEN*3];
425 	int verbose = opts & (PF_OPT_VERBOSE2 | PF_OPT_DEBUG);
426 	if (src->addr.type == PF_ADDR_ADDRMASK &&
427 	    dst->addr.type == PF_ADDR_ADDRMASK &&
428 	    PF_AZERO(&src->addr.v.a.addr, AF_INET6) &&
429 	    PF_AZERO(&src->addr.v.a.mask, AF_INET6) &&
430 	    PF_AZERO(&dst->addr.v.a.addr, AF_INET6) &&
431 	    PF_AZERO(&dst->addr.v.a.mask, AF_INET6) &&
432 	    !src->neg && !dst->neg &&
433 	    !src->port_op && !dst->port_op &&
434 	    osfp == PF_OSFP_ANY)
435 		printf(" all");
436 	else {
437 		printf(" from ");
438 		if (src->neg)
439 			printf("! ");
440 		print_addr(&src->addr, af, verbose);
441 		if (src->port_op)
442 			print_port(src->port_op, src->port[0],
443 			    src->port[1],
444 			    proto == IPPROTO_TCP ? "tcp" : "udp", opts);
445 		if (osfp != PF_OSFP_ANY)
446 			printf(" os \"%s\"", pfctl_lookup_fingerprint(osfp, buf,
447 			    sizeof(buf)));
448 
449 		printf(" to ");
450 		if (dst->neg)
451 			printf("! ");
452 		print_addr(&dst->addr, af, verbose);
453 		if (dst->port_op)
454 			print_port(dst->port_op, dst->port[0],
455 			    dst->port[1],
456 			    proto == IPPROTO_TCP ? "tcp" : "udp", opts);
457 	}
458 }
459 
460 void
print_pool(struct pf_pool * pool,u_int16_t p1,u_int16_t p2,sa_family_t af,int id,int verbose)461 print_pool(struct pf_pool *pool, u_int16_t p1, u_int16_t p2,
462     sa_family_t af, int id, int verbose)
463 {
464 	if (pool->ifname[0]) {
465 		if (!PF_AZERO(&pool->addr.v.a.addr, af)) {
466 			print_addr(&pool->addr, af, verbose);
467 			printf("@");
468 		}
469 		printf("%s", pool->ifname);
470 	} else
471 		print_addr(&pool->addr, af, verbose);
472 	switch (id) {
473 	case PF_POOL_NAT:
474 		if ((p1 != PF_NAT_PROXY_PORT_LOW ||
475 		    p2 != PF_NAT_PROXY_PORT_HIGH) && (p1 != 0 || p2 != 0)) {
476 			if (p1 == p2)
477 				printf(" port %u", p1);
478 			else
479 				printf(" port %u:%u", p1, p2);
480 		}
481 		break;
482 	case PF_POOL_RDR:
483 		if (p1) {
484 			printf(" port %u", p1);
485 			if (p2 && (p2 != p1))
486 				printf(":%u", p2);
487 		}
488 		break;
489 	default:
490 		break;
491 	}
492 	switch (pool->opts & PF_POOL_TYPEMASK) {
493 	case PF_POOL_NONE:
494 		break;
495 	case PF_POOL_BITMASK:
496 		printf(" bitmask");
497 		break;
498 	case PF_POOL_RANDOM:
499 		printf(" random");
500 		break;
501 	case PF_POOL_SRCHASH:
502 		printf(" source-hash 0x%08x%08x%08x%08x",
503 		    pool->key.key32[0], pool->key.key32[1],
504 		    pool->key.key32[2], pool->key.key32[3]);
505 		break;
506 	case PF_POOL_ROUNDROBIN:
507 		printf(" round-robin");
508 		break;
509 	case PF_POOL_LEASTSTATES:
510 		printf(" least-states");
511 		break;
512 	}
513 	if (pool->opts & PF_POOL_STICKYADDR)
514 		printf(" sticky-address");
515 	if (id == PF_POOL_NAT && p1 == 0 && p2 == 0)
516 		printf(" static-port");
517 }
518 
519 const char	*pf_reasons[PFRES_MAX+1] = PFRES_NAMES;
520 const char	*pf_lcounters[LCNT_MAX+1] = LCNT_NAMES;
521 const char	*pf_fcounters[FCNT_MAX+1] = FCNT_NAMES;
522 const char	*pf_scounters[SCNT_MAX+1] = FCNT_NAMES;
523 const char	*pf_ncounters[NCNT_MAX+1] = FCNT_NAMES;
524 
525 void
print_status(struct pf_status * s,struct pfctl_watermarks * synflwats,int opts)526 print_status(struct pf_status *s, struct pfctl_watermarks *synflwats, int opts)
527 {
528 	char			statline[80], *running, *debug;
529 	time_t			runtime = 0;
530 	struct timespec		uptime;
531 	int			i;
532 	char			buf[PF_MD5_DIGEST_LENGTH * 2 + 1];
533 	static const char	hex[] = "0123456789abcdef";
534 
535 	if (!clock_gettime(CLOCK_BOOTTIME, &uptime))
536 		runtime = uptime.tv_sec - s->since;
537 	running = s->running ? "Enabled" : "Disabled";
538 
539 	if (runtime) {
540 		unsigned int	sec, min, hrs;
541 		time_t		day = runtime;
542 
543 		sec = day % 60;
544 		day /= 60;
545 		min = day % 60;
546 		day /= 60;
547 		hrs = day % 24;
548 		day /= 24;
549 		snprintf(statline, sizeof(statline),
550 		    "Status: %s for %lld days %.2u:%.2u:%.2u",
551 		    running, (long long)day, hrs, min, sec);
552 	} else
553 		snprintf(statline, sizeof(statline), "Status: %s", running);
554 	printf("%-44s", statline);
555 	if (asprintf(&debug, "Debug: %s", loglevel_to_string(s->debug)) != -1) {
556 		printf("%15s\n\n", debug);
557 		free(debug);
558 	}
559 
560 	if (opts & PF_OPT_VERBOSE) {
561 		printf("Hostid:   0x%08x\n", ntohl(s->hostid));
562 
563 		for (i = 0; i < PF_MD5_DIGEST_LENGTH; i++) {
564 			buf[i + i] = hex[s->pf_chksum[i] >> 4];
565 			buf[i + i + 1] = hex[s->pf_chksum[i] & 0x0f];
566 		}
567 		buf[i + i] = '\0';
568 		printf("Checksum: 0x%s\n\n", buf);
569 	}
570 
571 	if (s->ifname[0] != 0) {
572 		printf("Interface Stats for %-16s %5s %16s\n",
573 		    s->ifname, "IPv4", "IPv6");
574 		printf("  %-25s %14llu %16llu\n", "Bytes In",
575 		    (unsigned long long)s->bcounters[0][0],
576 		    (unsigned long long)s->bcounters[1][0]);
577 		printf("  %-25s %14llu %16llu\n", "Bytes Out",
578 		    (unsigned long long)s->bcounters[0][1],
579 		    (unsigned long long)s->bcounters[1][1]);
580 		printf("  Packets In\n");
581 		printf("    %-23s %14llu %16llu\n", "Passed",
582 		    (unsigned long long)s->pcounters[0][0][PF_PASS],
583 		    (unsigned long long)s->pcounters[1][0][PF_PASS]);
584 		printf("    %-23s %14llu %16llu\n", "Blocked",
585 		    (unsigned long long)s->pcounters[0][0][PF_DROP],
586 		    (unsigned long long)s->pcounters[1][0][PF_DROP]);
587 		printf("  Packets Out\n");
588 		printf("    %-23s %14llu %16llu\n", "Passed",
589 		    (unsigned long long)s->pcounters[0][1][PF_PASS],
590 		    (unsigned long long)s->pcounters[1][1][PF_PASS]);
591 		printf("    %-23s %14llu %16llu\n\n", "Blocked",
592 		    (unsigned long long)s->pcounters[0][1][PF_DROP],
593 		    (unsigned long long)s->pcounters[1][1][PF_DROP]);
594 	}
595 	printf("%-27s %14s %16s\n", "State Table", "Total", "Rate");
596 	printf("  %-25s %14u %14s\n", "current entries", s->states, "");
597 	printf("  %-25s %14u %14s\n", "half-open tcp", s->states_halfopen, "");
598 	for (i = 0; i < FCNT_MAX; i++) {
599 		printf("  %-25s %14llu ", pf_fcounters[i],
600 			    (unsigned long long)s->fcounters[i]);
601 		if (runtime > 0)
602 			printf("%14.1f/s\n",
603 			    (double)s->fcounters[i] / (double)runtime);
604 		else
605 			printf("%14s\n", "");
606 	}
607 	if (opts & PF_OPT_VERBOSE) {
608 		printf("Source Tracking Table\n");
609 		printf("  %-25s %14u %14s\n", "current entries",
610 		    s->src_nodes, "");
611 		for (i = 0; i < SCNT_MAX; i++) {
612 			printf("  %-25s %14lld ", pf_scounters[i],
613 				    s->scounters[i]);
614 			if (runtime > 0)
615 				printf("%14.1f/s\n",
616 				    (double)s->scounters[i] / (double)runtime);
617 			else
618 				printf("%14s\n", "");
619 		}
620 	}
621 	if (opts & PF_OPT_VERBOSE) {
622 		printf("Fragments\n");
623 		printf("  %-25s %14u %14s\n", "current entries",
624 		    s->fragments, "");
625 		for (i = 0; i < NCNT_MAX; i++) {
626 			printf("  %-25s %14lld ", pf_ncounters[i],
627 				    s->ncounters[i]);
628 			if (runtime > 0)
629 				printf("%14.1f/s\n",
630 				    (double)s->ncounters[i] / (double)runtime);
631 			else
632 				printf("%14s\n", "");
633 		}
634 	}
635 	printf("Counters\n");
636 	for (i = 0; i < PFRES_MAX; i++) {
637 		printf("  %-25s %14llu ", pf_reasons[i],
638 		    (unsigned long long)s->counters[i]);
639 		if (runtime > 0)
640 			printf("%14.1f/s\n",
641 			    (double)s->counters[i] / (double)runtime);
642 		else
643 			printf("%14s\n", "");
644 	}
645 	if (opts & PF_OPT_VERBOSE) {
646 		printf("Limit Counters\n");
647 		for (i = 0; i < LCNT_MAX; i++) {
648 			printf("  %-25s %14lld ", pf_lcounters[i],
649 				    s->lcounters[i]);
650 			if (runtime > 0)
651 				printf("%14.1f/s\n",
652 				    (double)s->lcounters[i] / (double)runtime);
653 			else
654 				printf("%14s\n", "");
655 		}
656 	}
657 	if (opts & PF_OPT_VERBOSE) {
658 		printf("Adaptive Syncookies Watermarks\n");
659 		printf("  %-25s %14d states\n", "start", synflwats->hi);
660 		printf("  %-25s %14d states\n", "end", synflwats->lo);
661 	}
662 }
663 
664 void
print_src_node(struct pf_src_node * sn,int opts)665 print_src_node(struct pf_src_node *sn, int opts)
666 {
667 	struct pf_addr_wrap aw;
668 	int min, sec;
669 
670 	memset(&aw, 0, sizeof(aw));
671 	if (sn->af == AF_INET)
672 		aw.v.a.mask.addr32[0] = 0xffffffff;
673 	else
674 		memset(&aw.v.a.mask, 0xff, sizeof(aw.v.a.mask));
675 
676 	aw.v.a.addr = sn->addr;
677 	print_addr(&aw, sn->af, opts & PF_OPT_VERBOSE2);
678 
679 	if (!PF_AZERO(&sn->raddr, sn->af)) {
680 		if (sn->type == PF_SN_NAT)
681 			printf(" nat-to ");
682 		else if (sn->type == PF_SN_RDR)
683 			printf(" rdr-to ");
684 		else if (sn->type == PF_SN_ROUTE)
685 			printf(" route-to ");
686 		else
687 			printf(" ??? (%u) ", sn->type);
688 		aw.v.a.addr = sn->raddr;
689 		print_addr(&aw, sn->naf ? sn->naf : sn->af,
690 		    opts & PF_OPT_VERBOSE2);
691 	}
692 
693 	printf(" ( states %u, connections %u, rate %u.%u/%us )\n", sn->states,
694 	    sn->conn, sn->conn_rate.count / 1000,
695 	    (sn->conn_rate.count % 1000) / 100, sn->conn_rate.seconds);
696 	if (opts & PF_OPT_VERBOSE) {
697 		sec = sn->creation % 60;
698 		sn->creation /= 60;
699 		min = sn->creation % 60;
700 		sn->creation /= 60;
701 		printf("   age %.2u:%.2u:%.2u", sn->creation, min, sec);
702 		if (sn->states == 0) {
703 			sec = sn->expire % 60;
704 			sn->expire /= 60;
705 			min = sn->expire % 60;
706 			sn->expire /= 60;
707 			printf(", expires in %.2u:%.2u:%.2u",
708 			    sn->expire, min, sec);
709 		}
710 		printf(", %llu pkts, %llu bytes",
711 		    sn->packets[0] + sn->packets[1],
712 		    sn->bytes[0] + sn->bytes[1]);
713 		if (sn->rule.nr != -1)
714 			printf(", rule %u", sn->rule.nr);
715 		printf("\n");
716 	}
717 }
718 
719 void
print_rule(struct pf_rule * r,const char * anchor_call,int opts)720 print_rule(struct pf_rule *r, const char *anchor_call, int opts)
721 {
722 	static const char *actiontypes[] = { "pass", "block", "scrub",
723 	    "no scrub", "nat", "no nat", "binat", "no binat", "rdr", "no rdr",
724 	    "", "", "match"};
725 	static const char *anchortypes[] = { "anchor", "anchor", "anchor",
726 	    "anchor", "nat-anchor", "nat-anchor", "binat-anchor",
727 	    "binat-anchor", "rdr-anchor", "rdr-anchor" };
728 	int	i, ropts;
729 	int	verbose = opts & (PF_OPT_VERBOSE2 | PF_OPT_DEBUG);
730 	char	*p;
731 
732 	if ((r->rule_flag & PFRULE_EXPIRED) && (!verbose))
733 		return;
734 
735 	if (verbose)
736 		printf("@%d ", r->nr);
737 
738 	if (anchor_call[0]) {
739 		if (r->action >= nitems(anchortypes)) {
740 			printf("anchor(%d)", r->action);
741 		} else {
742 			p = strrchr(anchor_call, '/');
743 			if (p ? p[1] == '_' : anchor_call[0] == '_')
744 				printf("%s", anchortypes[r->action]);
745 			else
746 				printf("%s \"%s\"", anchortypes[r->action],
747 				    anchor_call);
748 		}
749 	} else {
750 		if (r->action >= nitems(actiontypes))
751 			printf("action(%d)", r->action);
752 		else
753 			printf("%s", actiontypes[r->action]);
754 	}
755 	if (r->action == PF_DROP) {
756 		if (r->rule_flag & PFRULE_RETURN)
757 			printf(" return");
758 		else if (r->rule_flag & PFRULE_RETURNRST) {
759 			if (!r->return_ttl)
760 				printf(" return-rst");
761 			else
762 				printf(" return-rst(ttl %d)", r->return_ttl);
763 		} else if (r->rule_flag & PFRULE_RETURNICMP) {
764 			const struct icmpcodeent	*ic, *ic6;
765 
766 			ic = geticmpcodebynumber(r->return_icmp >> 8,
767 			    r->return_icmp & 255, AF_INET);
768 			ic6 = geticmpcodebynumber(r->return_icmp6 >> 8,
769 			    r->return_icmp6 & 255, AF_INET6);
770 
771 			switch (r->af) {
772 			case AF_INET:
773 				printf(" return-icmp");
774 				if (ic == NULL)
775 					printf("(%u)", r->return_icmp & 255);
776 				else
777 					printf("(%s)", ic->name);
778 				break;
779 			case AF_INET6:
780 				printf(" return-icmp6");
781 				if (ic6 == NULL)
782 					printf("(%u)", r->return_icmp6 & 255);
783 				else
784 					printf("(%s)", ic6->name);
785 				break;
786 			default:
787 				printf(" return-icmp");
788 				if (ic == NULL)
789 					printf("(%u, ", r->return_icmp & 255);
790 				else
791 					printf("(%s, ", ic->name);
792 				if (ic6 == NULL)
793 					printf("%u)", r->return_icmp6 & 255);
794 				else
795 					printf("%s)", ic6->name);
796 				break;
797 			}
798 		} else
799 			printf(" drop");
800 	}
801 	if (r->direction == PF_IN)
802 		printf(" in");
803 	else if (r->direction == PF_OUT)
804 		printf(" out");
805 	if (r->log) {
806 		printf(" log");
807 		if (r->log & ~PF_LOG || r->logif) {
808 			int count = 0;
809 
810 			printf(" (");
811 			if (r->log & PF_LOG_ALL)
812 				printf("%sall", count++ ? ", " : "");
813 			if (r->log & PF_LOG_MATCHES)
814 				printf("%smatches", count++ ? ", " : "");
815 			if (r->log & PF_LOG_USER)
816 				printf("%suser", count++ ? ", " : "");
817 			if (r->logif)
818 				printf("%sto pflog%u", count++ ? ", " : "",
819 				    r->logif);
820 			printf(")");
821 		}
822 	}
823 	if (r->quick)
824 		printf(" quick");
825 	if (r->ifname[0]) {
826 		if (r->ifnot)
827 			printf(" on ! %s", r->ifname);
828 		else
829 			printf(" on %s", r->ifname);
830 	}
831 	if (r->onrdomain >= 0) {
832 		if (r->ifnot)
833 			printf(" on ! rdomain %d", r->onrdomain);
834 		else
835 			printf(" on rdomain %d", r->onrdomain);
836 	}
837 	if (r->af) {
838 		if (r->af == AF_INET)
839 			printf(" inet");
840 		else
841 			printf(" inet6");
842 	}
843 	if (r->proto) {
844 		struct protoent	*p;
845 
846 		if ((p = getprotobynumber(r->proto)) != NULL)
847 			printf(" proto %s", p->p_name);
848 		else
849 			printf(" proto %u", r->proto);
850 	}
851 	print_fromto(&r->src, r->os_fingerprint, &r->dst, r->af, r->proto,
852 	    opts);
853 	if (r->rcv_ifname[0])
854 		printf(" %sreceived-on %s", r->rcvifnot ? "!" : "",
855 		    r->rcv_ifname);
856 	if (r->uid.op)
857 		print_ugid(r->uid.op, r->uid.uid[0], r->uid.uid[1], "user");
858 	if (r->gid.op)
859 		print_ugid(r->gid.op, r->gid.gid[0], r->gid.gid[1], "group");
860 	if (r->flags || r->flagset) {
861 		printf(" flags ");
862 		print_flags(r->flags);
863 		printf("/");
864 		print_flags(r->flagset);
865 	} else if ((r->action == PF_PASS || r->action == PF_MATCH) &&
866 	    (!r->proto || r->proto == IPPROTO_TCP) &&
867 	    !(r->rule_flag & PFRULE_FRAGMENT) &&
868 	    !anchor_call[0] && r->keep_state)
869 		printf(" flags any");
870 	if (r->type) {
871 		const struct icmptypeent	*it;
872 
873 		it = geticmptypebynumber(r->type-1, r->af);
874 		if (r->af != AF_INET6)
875 			printf(" icmp-type");
876 		else
877 			printf(" icmp6-type");
878 		if (it != NULL)
879 			printf(" %s", it->name);
880 		else
881 			printf(" %u", r->type-1);
882 		if (r->code) {
883 			const struct icmpcodeent	*ic;
884 
885 			ic = geticmpcodebynumber(r->type-1, r->code-1, r->af);
886 			if (ic != NULL)
887 				printf(" code %s", ic->name);
888 			else
889 				printf(" code %u", r->code-1);
890 		}
891 	}
892 	if (r->tos)
893 		printf(" tos 0x%2.2x", r->tos);
894 	if (r->prio)
895 		printf(" prio %u", r->prio == PF_PRIO_ZERO ? 0 : r->prio);
896 	if (r->pktrate.limit)
897 		printf(" max-pkt-rate %u/%u", r->pktrate.limit,
898 		    r->pktrate.seconds);
899 
900 	if (r->scrub_flags & PFSTATE_SETMASK || r->qname[0] ||
901 	    r->rule_flag & PFRULE_SETDELAY) {
902 		char *comma = "";
903 		printf(" set (");
904 		if (r->scrub_flags & PFSTATE_SETPRIO) {
905 			if (r->set_prio[0] == r->set_prio[1])
906 				printf("%sprio %u", comma, r->set_prio[0]);
907 			else
908 				printf("%sprio(%u, %u)", comma, r->set_prio[0],
909 				    r->set_prio[1]);
910 			comma = ", ";
911 		}
912 		if (r->qname[0]) {
913 			if (r->pqname[0])
914 				printf("%squeue(%s, %s)", comma, r->qname,
915 				    r->pqname);
916 			else
917 				printf("%squeue %s", comma, r->qname);
918 			comma = ", ";
919 		}
920 		if (r->scrub_flags & PFSTATE_SETTOS) {
921 			printf("%stos 0x%2.2x", comma, r->set_tos);
922 			comma = ", ";
923 		}
924 		if (r->rule_flag & PFRULE_SETDELAY) {
925 			printf("%sdelay %u", comma, r->delay);
926 			comma = ", ";
927 		}
928 		printf(")");
929 	}
930 
931 	ropts = 0;
932 	if (r->max_states || r->max_src_nodes || r->max_src_states)
933 		ropts = 1;
934 	if (r->rule_flag & PFRULE_NOSYNC)
935 		ropts = 1;
936 	if (r->rule_flag & PFRULE_SRCTRACK)
937 		ropts = 1;
938 	if (r->rule_flag & PFRULE_IFBOUND)
939 		ropts = 1;
940 	if (r->rule_flag & PFRULE_STATESLOPPY)
941 		ropts = 1;
942 	if (r->rule_flag & PFRULE_PFLOW)
943 		ropts = 1;
944 	for (i = 0; !ropts && i < PFTM_MAX; ++i)
945 		if (r->timeout[i])
946 			ropts = 1;
947 
948 	if (!r->keep_state && r->action == PF_PASS && !anchor_call[0])
949 		printf(" no state");
950 	else if (r->keep_state == PF_STATE_NORMAL && ropts)
951 		printf(" keep state");
952 	else if (r->keep_state == PF_STATE_MODULATE)
953 		printf(" modulate state");
954 	else if (r->keep_state == PF_STATE_SYNPROXY)
955 		printf(" synproxy state");
956 	if (r->prob) {
957 		char	buf[20];
958 
959 		snprintf(buf, sizeof(buf), "%f", r->prob*100.0/(UINT_MAX+1.0));
960 		for (i = strlen(buf)-1; i > 0; i--) {
961 			if (buf[i] == '0')
962 				buf[i] = '\0';
963 			else {
964 				if (buf[i] == '.')
965 					buf[i] = '\0';
966 				break;
967 			}
968 		}
969 		printf(" probability %s%%", buf);
970 	}
971 	if (ropts) {
972 		printf(" (");
973 		if (r->max_states) {
974 			printf("max %u", r->max_states);
975 			ropts = 0;
976 		}
977 		if (r->rule_flag & PFRULE_NOSYNC) {
978 			if (!ropts)
979 				printf(", ");
980 			printf("no-sync");
981 			ropts = 0;
982 		}
983 		if (r->rule_flag & PFRULE_SRCTRACK) {
984 			if (!ropts)
985 				printf(", ");
986 			printf("source-track");
987 			if (r->rule_flag & PFRULE_RULESRCTRACK)
988 				printf(" rule");
989 			else
990 				printf(" global");
991 			ropts = 0;
992 		}
993 		if (r->max_src_states) {
994 			if (!ropts)
995 				printf(", ");
996 			printf("max-src-states %u", r->max_src_states);
997 			ropts = 0;
998 		}
999 		if (r->max_src_conn) {
1000 			if (!ropts)
1001 				printf(", ");
1002 			printf("max-src-conn %u", r->max_src_conn);
1003 			ropts = 0;
1004 		}
1005 		if (r->max_src_conn_rate.limit) {
1006 			if (!ropts)
1007 				printf(", ");
1008 			printf("max-src-conn-rate %u/%u",
1009 			    r->max_src_conn_rate.limit,
1010 			    r->max_src_conn_rate.seconds);
1011 			ropts = 0;
1012 		}
1013 		if (r->max_src_nodes) {
1014 			if (!ropts)
1015 				printf(", ");
1016 			printf("max-src-nodes %u", r->max_src_nodes);
1017 			ropts = 0;
1018 		}
1019 		if (r->overload_tblname[0]) {
1020 			if (!ropts)
1021 				printf(", ");
1022 			printf("overload <%s>", r->overload_tblname);
1023 			if (r->flush)
1024 				printf(" flush");
1025 			if (r->flush & PF_FLUSH_GLOBAL)
1026 				printf(" global");
1027 		}
1028 		if (r->rule_flag & PFRULE_IFBOUND) {
1029 			if (!ropts)
1030 				printf(", ");
1031 			printf("if-bound");
1032 			ropts = 0;
1033 		}
1034 		if (r->rule_flag & PFRULE_STATESLOPPY) {
1035 			if (!ropts)
1036 				printf(", ");
1037 			printf("sloppy");
1038 			ropts = 0;
1039 		}
1040 		if (r->rule_flag & PFRULE_PFLOW) {
1041 			if (!ropts)
1042 				printf(", ");
1043 			printf("pflow");
1044 			ropts = 0;
1045 		}
1046 		for (i = 0; i < PFTM_MAX; ++i)
1047 			if (r->timeout[i]) {
1048 				int j;
1049 
1050 				if (!ropts)
1051 					printf(", ");
1052 				ropts = 0;
1053 				for (j = 0; pf_timeouts[j].name != NULL;
1054 				    ++j)
1055 					if (pf_timeouts[j].timeout == i)
1056 						break;
1057 				printf("%s %u", pf_timeouts[j].name == NULL ?
1058 				    "inv.timeout" : pf_timeouts[j].name,
1059 				    r->timeout[i]);
1060 			}
1061 		printf(")");
1062 	}
1063 
1064 	if (r->rule_flag & PFRULE_FRAGMENT)
1065 		printf(" fragment");
1066 
1067 	if (r->scrub_flags & PFSTATE_SCRUBMASK || r->min_ttl || r->max_mss) {
1068 		printf(" scrub (");
1069 		ropts = 1;
1070 		if (r->scrub_flags & PFSTATE_NODF) {
1071 			printf("no-df");
1072 			ropts = 0;
1073 		}
1074 		if (r->scrub_flags & PFSTATE_RANDOMID) {
1075 			if (!ropts)
1076 				printf(" ");
1077 			printf("random-id");
1078 			ropts = 0;
1079 		}
1080 		if (r->min_ttl) {
1081 			if (!ropts)
1082 				printf(" ");
1083 			printf("min-ttl %d", r->min_ttl);
1084 			ropts = 0;
1085 		}
1086 		if (r->scrub_flags & PFSTATE_SCRUB_TCP) {
1087 			if (!ropts)
1088 				printf(" ");
1089 			printf("reassemble tcp");
1090 			ropts = 0;
1091 		}
1092 		if (r->max_mss) {
1093 			if (!ropts)
1094 				printf(" ");
1095 			printf("max-mss %d", r->max_mss);
1096 			ropts = 0;
1097 		}
1098 		printf(")");
1099 	}
1100 
1101 	if (r->allow_opts)
1102 		printf(" allow-opts");
1103 	if (r->label[0])
1104 		printf(" label \"%s\"", r->label);
1105 	if (r->rule_flag & PFRULE_ONCE)
1106 		printf(" once");
1107 	if (r->tagname[0])
1108 		printf(" tag %s", r->tagname);
1109 	if (r->match_tagname[0]) {
1110 		if (r->match_tag_not)
1111 			printf(" !");
1112 		printf(" tagged %s", r->match_tagname);
1113 	}
1114 	if (r->rtableid != -1)
1115 		printf(" rtable %u", r->rtableid);
1116 	switch (r->divert.type) {
1117 	case PF_DIVERT_NONE:
1118 		break;
1119 	case PF_DIVERT_TO: {
1120 		printf(" divert-to ");
1121 		print_addr_str(r->af, &r->divert.addr);
1122 		printf(" port %u", ntohs(r->divert.port));
1123 		break;
1124 	}
1125 	case PF_DIVERT_REPLY:
1126 		printf(" divert-reply");
1127 		break;
1128 	case PF_DIVERT_PACKET:
1129 		printf(" divert-packet port %u", ntohs(r->divert.port));
1130 		break;
1131 	default:
1132 		printf(" divert ???");
1133 		break;
1134 	}
1135 
1136 	if (!anchor_call[0] && r->nat.addr.type != PF_ADDR_NONE &&
1137 	    r->rule_flag & PFRULE_AFTO) {
1138 		printf(" af-to %s from ", r->naf == AF_INET ? "inet" : "inet6");
1139 		print_pool(&r->nat, r->nat.proxy_port[0],
1140 		    r->nat.proxy_port[1], r->naf ? r->naf : r->af,
1141 		    PF_POOL_NAT, verbose);
1142 		if (r->rdr.addr.type != PF_ADDR_NONE) {
1143 			printf(" to ");
1144 			print_pool(&r->rdr, r->rdr.proxy_port[0],
1145 			    r->rdr.proxy_port[1], r->naf ? r->naf : r->af,
1146 			    PF_POOL_RDR, verbose);
1147 		}
1148 	} else if (!anchor_call[0] && r->nat.addr.type != PF_ADDR_NONE) {
1149 		printf (" nat-to ");
1150 		print_pool(&r->nat, r->nat.proxy_port[0],
1151 		    r->nat.proxy_port[1], r->naf ? r->naf : r->af,
1152 		    PF_POOL_NAT, verbose);
1153 	} else if (!anchor_call[0] && r->rdr.addr.type != PF_ADDR_NONE) {
1154 		printf (" rdr-to ");
1155 		print_pool(&r->rdr, r->rdr.proxy_port[0],
1156 		    r->rdr.proxy_port[1], r->af, PF_POOL_RDR, verbose);
1157 	}
1158 	if (r->rt) {
1159 		if (r->rt == PF_ROUTETO)
1160 			printf(" route-to");
1161 		else if (r->rt == PF_REPLYTO)
1162 			printf(" reply-to");
1163 		else if (r->rt == PF_DUPTO)
1164 			printf(" dup-to");
1165 		printf(" ");
1166 		print_pool(&r->route, 0, 0, r->af, PF_POOL_ROUTE, verbose);
1167 	}
1168 
1169 	if (r->rule_flag & PFRULE_EXPIRED)
1170 		printf(" # expired");
1171 }
1172 
1173 void
print_tabledef(const char * name,int flags,int addrs,struct node_tinithead * nodes)1174 print_tabledef(const char *name, int flags, int addrs,
1175     struct node_tinithead *nodes)
1176 {
1177 	struct node_tinit	*ti, *nti;
1178 	struct node_host	*h;
1179 
1180 	printf("table <%s>", name);
1181 	if (flags & PFR_TFLAG_CONST)
1182 		printf(" const");
1183 	if (flags & PFR_TFLAG_PERSIST)
1184 		printf(" persist");
1185 	if (flags & PFR_TFLAG_COUNTERS)
1186 		printf(" counters");
1187 	SIMPLEQ_FOREACH(ti, nodes, entries) {
1188 		if (ti->file) {
1189 			printf(" file \"%s\"", ti->file);
1190 			continue;
1191 		}
1192 		printf(" {");
1193 		for (;;) {
1194 			for (h = ti->host; h != NULL; h = h->next) {
1195 				printf(h->not ? " !" : " ");
1196 				print_addr(&h->addr, h->af, 0);
1197 				if (h->ifname)
1198 					printf("@%s", h->ifname);
1199 			}
1200 			nti = SIMPLEQ_NEXT(ti, entries);
1201 			if (nti != NULL && nti->file == NULL)
1202 				ti = nti;	/* merge lists */
1203 			else
1204 				break;
1205 		}
1206 		printf(" }");
1207 	}
1208 	if (addrs && SIMPLEQ_EMPTY(nodes))
1209 		printf(" { }");
1210 	printf("\n");
1211 }
1212 
1213 void
print_bwspec(const char * prefix,struct pf_queue_bwspec * bw)1214 print_bwspec(const char *prefix, struct pf_queue_bwspec *bw)
1215 {
1216 	u_int	rate;
1217 	int	i;
1218 	static const char unit[] = " KMG";
1219 
1220 	if (bw->percent)
1221 		printf("%s%u%%", prefix, bw->percent);
1222 	else if (bw->absolute) {
1223 		rate = bw->absolute;
1224 		for (i = 0; rate >= 1000 && i <= 3 && (rate % 1000 == 0); i++)
1225 			rate /= 1000;
1226 		printf("%s%u%c", prefix, rate, unit[i]);
1227 	}
1228 }
1229 
1230 void
print_scspec(const char * prefix,struct pf_queue_scspec * sc)1231 print_scspec(const char *prefix, struct pf_queue_scspec *sc)
1232 {
1233 	print_bwspec(prefix, &sc->m2);
1234 	if (sc->d) {
1235 		printf(" burst ");
1236 		print_bwspec("", &sc->m1);
1237 		printf(" for %ums", sc->d);
1238 	}
1239 }
1240 
1241 void
print_queuespec(struct pf_queuespec * q)1242 print_queuespec(struct pf_queuespec *q)
1243 {
1244 	printf("queue %s", q->qname);
1245 	if (q->parent[0])
1246 		printf(" parent %s", q->parent);
1247 	else if (q->ifname[0])
1248 		printf(" on %s", q->ifname);
1249 	if (q->flags & PFQS_FLOWQUEUE) {
1250 		printf(" flows %u", q->flowqueue.flows);
1251 		if (q->flowqueue.quantum > 0)
1252 			printf(" quantum %u", q->flowqueue.quantum);
1253 		if (q->flowqueue.interval > 0)
1254 			printf(" interval %ums",
1255 			    q->flowqueue.interval / 1000000);
1256 		if (q->flowqueue.target > 0)
1257 			printf(" target %ums",
1258 			    q->flowqueue.target / 1000000);
1259 	}
1260 	if (q->linkshare.m1.absolute || q->linkshare.m2.absolute) {
1261 		print_scspec(" bandwidth ", &q->linkshare);
1262 		print_scspec(", min ", &q->realtime);
1263 		print_scspec(", max ", &q->upperlimit);
1264 	}
1265 	if (q->flags & PFQS_DEFAULT)
1266 		printf(" default");
1267 	if (q->qlimit)
1268 		printf(" qlimit %u", q->qlimit);
1269 	printf("\n");
1270 }
1271 
1272 int
parse_flags(char * s)1273 parse_flags(char *s)
1274 {
1275 	char		*p, *q;
1276 	u_int8_t	 f = 0;
1277 
1278 	for (p = s; *p; p++) {
1279 		if ((q = strchr(tcpflags, *p)) == NULL)
1280 			return -1;
1281 		else
1282 			f |= 1 << (q - tcpflags);
1283 	}
1284 	return (f ? f : PF_TH_ALL);
1285 }
1286 
1287 void
set_ipmask(struct node_host * h,int bb)1288 set_ipmask(struct node_host *h, int bb)
1289 {
1290 	struct pf_addr	*m, *n;
1291 	int		 i, j = 0;
1292 	u_int8_t	 b;
1293 
1294 	m = &h->addr.v.a.mask;
1295 	memset(m, 0, sizeof(*m));
1296 
1297 	if (bb == -1)
1298 		b = h->af == AF_INET ? 32 : 128;
1299 	else
1300 		b = bb;
1301 
1302 	while (b >= 32) {
1303 		m->addr32[j++] = 0xffffffff;
1304 		b -= 32;
1305 	}
1306 	for (i = 31; i > 31-b; --i)
1307 		m->addr32[j] |= (1 << i);
1308 	if (b)
1309 		m->addr32[j] = htonl(m->addr32[j]);
1310 
1311 	/* Mask off bits of the address that will never be used. */
1312 	n = &h->addr.v.a.addr;
1313 	if (h->addr.type == PF_ADDR_ADDRMASK)
1314 		for (i = 0; i < 4; i++)
1315 			n->addr32[i] = n->addr32[i] & m->addr32[i];
1316 }
1317 
1318 int
check_netmask(struct node_host * h,sa_family_t af)1319 check_netmask(struct node_host *h, sa_family_t af)
1320 {
1321 	struct node_host	*n = NULL;
1322 	struct pf_addr		*m;
1323 
1324 	for (n = h; n != NULL; n = n->next) {
1325 		if (h->addr.type == PF_ADDR_TABLE)
1326 			continue;
1327 		m = &h->addr.v.a.mask;
1328 		/* netmasks > 32 bit are invalid on v4 */
1329 		if (af == AF_INET &&
1330 		    (m->addr32[1] || m->addr32[2] || m->addr32[3])) {
1331 			fprintf(stderr, "netmask %u invalid for IPv4 address\n",
1332 			    unmask(m));
1333 			return (1);
1334 		}
1335 	}
1336 	return (0);
1337 }
1338 
1339 struct node_host *
gen_dynnode(struct node_host * h,sa_family_t af)1340 gen_dynnode(struct node_host *h, sa_family_t af)
1341 {
1342 	struct node_host	*n;
1343 
1344 	if (h->addr.type != PF_ADDR_DYNIFTL)
1345 		return (NULL);
1346 
1347 	if ((n = calloc(1, sizeof(*n))) == NULL)
1348 		return (NULL);
1349 	bcopy(h, n, sizeof(*n));
1350 	n->ifname = NULL;
1351 	n->next = NULL;
1352 	n->tail = NULL;
1353 
1354 	/* fix up netmask */
1355 	if (af == AF_INET && unmask(&n->addr.v.a.mask) > 32)
1356 		set_ipmask(n, 32);
1357 
1358 	return (n);
1359 }
1360 
1361 /* interface lookup routines */
1362 
1363 struct node_host	*iftab;
1364 
1365 void
ifa_load(void)1366 ifa_load(void)
1367 {
1368 	struct ifaddrs		*ifap, *ifa;
1369 	struct node_host	*n = NULL, *h = NULL;
1370 
1371 	if (getifaddrs(&ifap) == -1)
1372 		err(1, "getifaddrs");
1373 
1374 	for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
1375 		if (ifa->ifa_addr == NULL ||
1376 		    !(ifa->ifa_addr->sa_family == AF_INET ||
1377 		    ifa->ifa_addr->sa_family == AF_INET6 ||
1378 		    ifa->ifa_addr->sa_family == AF_LINK))
1379 				continue;
1380 		n = calloc(1, sizeof(struct node_host));
1381 		if (n == NULL)
1382 			err(1, "%s: calloc", __func__);
1383 		n->af = ifa->ifa_addr->sa_family;
1384 		n->ifa_flags = ifa->ifa_flags;
1385 #ifdef __KAME__
1386 		if (n->af == AF_INET6 &&
1387 		    IN6_IS_ADDR_LINKLOCAL(&((struct sockaddr_in6 *)
1388 		    ifa->ifa_addr)->sin6_addr) &&
1389 		    ((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_scope_id ==
1390 		    0) {
1391 			struct sockaddr_in6	*sin6;
1392 
1393 			sin6 = (struct sockaddr_in6 *)ifa->ifa_addr;
1394 			sin6->sin6_scope_id = sin6->sin6_addr.s6_addr[2] << 8 |
1395 			    sin6->sin6_addr.s6_addr[3];
1396 			sin6->sin6_addr.s6_addr[2] = 0;
1397 			sin6->sin6_addr.s6_addr[3] = 0;
1398 		}
1399 #endif
1400 		n->ifindex = 0;
1401 		if (n->af == AF_LINK)
1402 			n->ifindex = ((struct sockaddr_dl *)
1403 			    ifa->ifa_addr)->sdl_index;
1404 		else {
1405 			copy_satopfaddr(&n->addr.v.a.addr, ifa->ifa_addr);
1406 			ifa->ifa_netmask->sa_family = ifa->ifa_addr->sa_family;
1407 			copy_satopfaddr(&n->addr.v.a.mask, ifa->ifa_netmask);
1408 			if (ifa->ifa_broadaddr != NULL) {
1409 				ifa->ifa_broadaddr->sa_family = ifa->ifa_addr->sa_family;
1410 				copy_satopfaddr(&n->bcast, ifa->ifa_broadaddr);
1411 			}
1412 			if (ifa->ifa_dstaddr != NULL) {
1413 				ifa->ifa_dstaddr->sa_family = ifa->ifa_addr->sa_family;
1414 				copy_satopfaddr(&n->peer, ifa->ifa_dstaddr);
1415 			}
1416 			if (n->af == AF_INET6)
1417 				n->ifindex = ((struct sockaddr_in6 *)
1418 				    ifa->ifa_addr)->sin6_scope_id;
1419 		}
1420 		if ((n->ifname = strdup(ifa->ifa_name)) == NULL)
1421 			err(1, "%s: strdup", __func__);
1422 		n->next = NULL;
1423 		n->tail = n;
1424 		if (h == NULL)
1425 			h = n;
1426 		else {
1427 			h->tail->next = n;
1428 			h->tail = n;
1429 		}
1430 	}
1431 
1432 	iftab = h;
1433 	freeifaddrs(ifap);
1434 }
1435 
1436 unsigned int
ifa_nametoindex(const char * ifa_name)1437 ifa_nametoindex(const char *ifa_name)
1438 {
1439 	struct node_host	*p;
1440 
1441 	for (p = iftab; p; p = p->next) {
1442 		if (p->af == AF_LINK && strcmp(p->ifname, ifa_name) == 0)
1443 			return (p->ifindex);
1444 	}
1445 	errno = ENXIO;
1446 	return (0);
1447 }
1448 
1449 char *
ifa_indextoname(unsigned int ifindex,char * ifa_name)1450 ifa_indextoname(unsigned int ifindex, char *ifa_name)
1451 {
1452 	struct node_host	*p;
1453 
1454 	for (p = iftab; p; p = p->next) {
1455 		if (p->af == AF_LINK && ifindex == p->ifindex) {
1456 			strlcpy(ifa_name, p->ifname, IFNAMSIZ);
1457 			return (ifa_name);
1458 		}
1459 	}
1460 	errno = ENXIO;
1461 	return (NULL);
1462 }
1463 
1464 struct node_host *
ifa_exists(const char * ifa_name)1465 ifa_exists(const char *ifa_name)
1466 {
1467 	struct node_host	*n;
1468 	struct ifgroupreq	ifgr;
1469 	int			s;
1470 
1471 	if (iftab == NULL)
1472 		ifa_load();
1473 
1474 	/* check whether this is a group */
1475 	if ((s = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
1476 		err(1, "socket");
1477 	bzero(&ifgr, sizeof(ifgr));
1478 	strlcpy(ifgr.ifgr_name, ifa_name, sizeof(ifgr.ifgr_name));
1479 	if (ioctl(s, SIOCGIFGMEMB, (caddr_t)&ifgr) == 0) {
1480 		/* fake a node_host */
1481 		if ((n = calloc(1, sizeof(*n))) == NULL)
1482 			err(1, "calloc");
1483 		if ((n->ifname = strdup(ifa_name)) == NULL)
1484 			err(1, "strdup");
1485 		close(s);
1486 		return (n);
1487 	}
1488 	close(s);
1489 
1490 	for (n = iftab; n; n = n->next) {
1491 		if (n->af == AF_LINK && !strncmp(n->ifname, ifa_name, IFNAMSIZ))
1492 			return (n);
1493 	}
1494 
1495 	return (NULL);
1496 }
1497 
1498 struct node_host *
ifa_grouplookup(const char * ifa_name,int flags)1499 ifa_grouplookup(const char *ifa_name, int flags)
1500 {
1501 	struct ifg_req		*ifg;
1502 	struct ifgroupreq	 ifgr;
1503 	int			 s, len;
1504 	struct node_host	*n, *h = NULL;
1505 
1506 	if ((s = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
1507 		err(1, "socket");
1508 	bzero(&ifgr, sizeof(ifgr));
1509 	strlcpy(ifgr.ifgr_name, ifa_name, sizeof(ifgr.ifgr_name));
1510 	if (ioctl(s, SIOCGIFGMEMB, (caddr_t)&ifgr) == -1) {
1511 		close(s);
1512 		return (NULL);
1513 	}
1514 
1515 	len = ifgr.ifgr_len;
1516 	if ((ifgr.ifgr_groups = calloc(1, len)) == NULL)
1517 		err(1, "calloc");
1518 	if (ioctl(s, SIOCGIFGMEMB, (caddr_t)&ifgr) == -1)
1519 		err(1, "SIOCGIFGMEMB");
1520 
1521 	for (ifg = ifgr.ifgr_groups; ifg && len >= sizeof(struct ifg_req);
1522 	    ifg++) {
1523 		len -= sizeof(struct ifg_req);
1524 		if ((n = ifa_lookup(ifg->ifgrq_member, flags)) == NULL)
1525 			continue;
1526 		if (h == NULL)
1527 			h = n;
1528 		else {
1529 			h->tail->next = n;
1530 			h->tail = n->tail;
1531 		}
1532 	}
1533 	free(ifgr.ifgr_groups);
1534 	close(s);
1535 
1536 	return (h);
1537 }
1538 
1539 struct node_host *
ifa_lookup(const char * ifa_name,int flags)1540 ifa_lookup(const char *ifa_name, int flags)
1541 {
1542 	struct node_host	*p = NULL, *h = NULL, *n = NULL;
1543 	int			 got4 = 0, got6 = 0;
1544 	const char		 *last_if = NULL;
1545 
1546 	if ((h = ifa_grouplookup(ifa_name, flags)) != NULL)
1547 		return (h);
1548 
1549 	if (!strncmp(ifa_name, "self", IFNAMSIZ))
1550 		ifa_name = NULL;
1551 
1552 	if (iftab == NULL)
1553 		ifa_load();
1554 
1555 	for (p = iftab; p; p = p->next) {
1556 		if (ifa_skip_if(ifa_name, p))
1557 			continue;
1558 		if ((flags & PFI_AFLAG_BROADCAST) && p->af != AF_INET)
1559 			continue;
1560 		if ((flags & PFI_AFLAG_BROADCAST) &&
1561 		    !(p->ifa_flags & IFF_BROADCAST))
1562 			continue;
1563 		if ((flags & PFI_AFLAG_BROADCAST) && p->bcast.v4.s_addr == 0)
1564 			continue;
1565 		if ((flags & PFI_AFLAG_PEER) &&
1566 		    !(p->ifa_flags & IFF_POINTOPOINT))
1567 			continue;
1568 		if ((flags & PFI_AFLAG_NETWORK) && p->ifindex > 0)
1569 			continue;
1570 		if (last_if == NULL || strcmp(last_if, p->ifname))
1571 			got4 = got6 = 0;
1572 		last_if = p->ifname;
1573 		if ((flags & PFI_AFLAG_NOALIAS) && p->af == AF_INET && got4)
1574 			continue;
1575 		if ((flags & PFI_AFLAG_NOALIAS) && p->af == AF_INET6 && got6)
1576 			continue;
1577 		if (p->af == AF_INET)
1578 			got4 = 1;
1579 		else
1580 			got6 = 1;
1581 		n = calloc(1, sizeof(struct node_host));
1582 		if (n == NULL)
1583 			err(1, "%s: calloc", __func__);
1584 		n->af = p->af;
1585 		if (flags & PFI_AFLAG_BROADCAST)
1586 			memcpy(&n->addr.v.a.addr, &p->bcast,
1587 			    sizeof(struct pf_addr));
1588 		else if (flags & PFI_AFLAG_PEER)
1589 			memcpy(&n->addr.v.a.addr, &p->peer,
1590 			    sizeof(struct pf_addr));
1591 		else
1592 			memcpy(&n->addr.v.a.addr, &p->addr.v.a.addr,
1593 			    sizeof(struct pf_addr));
1594 		if (flags & PFI_AFLAG_NETWORK)
1595 			set_ipmask(n, unmask(&p->addr.v.a.mask));
1596 		else
1597 			set_ipmask(n, -1);
1598 		n->ifindex = p->ifindex;
1599 
1600 		n->next = NULL;
1601 		n->tail = n;
1602 		if (h == NULL)
1603 			h = n;
1604 		else {
1605 			h->tail->next = n;
1606 			h->tail = n;
1607 		}
1608 	}
1609 	return (h);
1610 }
1611 
1612 int
ifa_skip_if(const char * filter,struct node_host * p)1613 ifa_skip_if(const char *filter, struct node_host *p)
1614 {
1615 	int	n;
1616 
1617 	if (p->af != AF_INET && p->af != AF_INET6)
1618 		return (1);
1619 	if (filter == NULL || !*filter)
1620 		return (0);
1621 	if (!strcmp(p->ifname, filter))
1622 		return (0);	/* exact match */
1623 	n = strlen(filter);
1624 	if (n < 1 || n >= IFNAMSIZ)
1625 		return (1);	/* sanity check */
1626 	if (filter[n-1] >= '0' && filter[n-1] <= '9')
1627 		return (1);	/* only do exact match in that case */
1628 	if (strncmp(p->ifname, filter, n))
1629 		return (1);	/* prefix doesn't match */
1630 	return (p->ifname[n] < '0' || p->ifname[n] > '9');
1631 }
1632 
1633 struct node_host *
host(const char * s,int opts)1634 host(const char *s, int opts)
1635 {
1636 	struct node_host	*h = NULL, *n;
1637 	int			 mask = -1;
1638 	char			*p, *ps;
1639 	const char		*errstr;
1640 
1641 	if ((ps = strdup(s)) == NULL)
1642 		err(1, "%s: strdup", __func__);
1643 
1644 	if ((p = strchr(ps, '/')) != NULL) {
1645 		mask = strtonum(p+1, 0, 128, &errstr);
1646 		if (errstr) {
1647 			fprintf(stderr, "netmask is %s: %s\n", errstr, p);
1648 			goto error;
1649 		}
1650 		p[0] = '\0';
1651 	}
1652 
1653 	if ((h = host_if(ps, mask)) == NULL &&
1654 	    (h = host_ip(ps, mask)) == NULL &&
1655 	    (h = host_dns(ps, mask, (opts & PF_OPT_NODNS))) == NULL) {
1656 		fprintf(stderr, "no IP address found for %s\n", s);
1657 		goto error;
1658 	}
1659 
1660 	for (n = h; n != NULL; n = n->next) {
1661 		n->addr.type = PF_ADDR_ADDRMASK;
1662 		n->weight = 0;
1663 	}
1664 
1665 error:
1666 	free(ps);
1667 	return (h);
1668 }
1669 
1670 struct node_host *
host_if(const char * s,int mask)1671 host_if(const char *s, int mask)
1672 {
1673 	struct node_host	*n, *h = NULL;
1674 	char			*p, *ps;
1675 	int			 flags = 0;
1676 
1677 	if ((ps = strdup(s)) == NULL)
1678 		err(1, "host_if: strdup");
1679 	while ((p = strrchr(ps, ':')) != NULL) {
1680 		if (!strcmp(p+1, "network"))
1681 			flags |= PFI_AFLAG_NETWORK;
1682 		else if (!strcmp(p+1, "broadcast"))
1683 			flags |= PFI_AFLAG_BROADCAST;
1684 		else if (!strcmp(p+1, "peer"))
1685 			flags |= PFI_AFLAG_PEER;
1686 		else if (!strcmp(p+1, "0"))
1687 			flags |= PFI_AFLAG_NOALIAS;
1688 		else
1689 			goto error;
1690 		*p = '\0';
1691 	}
1692 	if (flags & (flags - 1) & PFI_AFLAG_MODEMASK) { /* Yep! */
1693 		fprintf(stderr, "illegal combination of interface modifiers\n");
1694 		goto error;
1695 	}
1696 	if ((flags & (PFI_AFLAG_NETWORK|PFI_AFLAG_BROADCAST)) && mask > -1) {
1697 		fprintf(stderr, "network or broadcast lookup, but "
1698 		    "extra netmask given\n");
1699 		goto error;
1700 	}
1701 	if (ifa_exists(ps) || !strncmp(ps, "self", IFNAMSIZ)) {
1702 		/* interface with this name exists */
1703 		h = ifa_lookup(ps, flags);
1704 		if (mask > -1)
1705 			for (n = h; n != NULL; n = n->next)
1706 				set_ipmask(n, mask);
1707 	}
1708 
1709 error:
1710 	free(ps);
1711 	return (h);
1712 }
1713 
1714 struct node_host *
host_ip(const char * s,int mask)1715 host_ip(const char *s, int mask)
1716 {
1717 	struct addrinfo		 hints, *res;
1718 	struct node_host	*h = NULL;
1719 
1720 	memset(&hints, 0, sizeof(hints));
1721 	hints.ai_family = AF_UNSPEC;
1722 	hints.ai_socktype = SOCK_DGRAM; /*dummy*/
1723 	hints.ai_flags = AI_NUMERICHOST;
1724 	if (getaddrinfo(s, NULL, &hints, &res) == 0) {
1725 		h = calloc(1, sizeof(*h));
1726 		if (h == NULL)
1727 			err(1, "%s: calloc", __func__);
1728 		h->af = res->ai_family;
1729 		copy_satopfaddr(&h->addr.v.a.addr, res->ai_addr);
1730 		if (h->af == AF_INET6)
1731 			h->ifindex =
1732 			    ((struct sockaddr_in6 *)res->ai_addr)->sin6_scope_id;
1733 		freeaddrinfo(res);
1734 	} else {	/* ie. for 10/8 parsing */
1735 		if (mask == -1)
1736 			return (NULL);
1737 		h = calloc(1, sizeof(*h));
1738 		if (h == NULL)
1739 			err(1, "%s: calloc", __func__);
1740 		h->af = AF_INET;
1741 		if (inet_net_pton(AF_INET, s, &h->addr.v.a.addr.v4,
1742 		    sizeof(h->addr.v.a.addr.v4)) == -1) {
1743 			free(h);
1744 			return (NULL);
1745 		}
1746 	}
1747 	set_ipmask(h, mask);
1748 	h->ifname = NULL;
1749 	h->next = NULL;
1750 	h->tail = h;
1751 
1752 	return (h);
1753 }
1754 
1755 struct node_host *
host_dns(const char * s,int mask,int numeric)1756 host_dns(const char *s, int mask, int numeric)
1757 {
1758 	struct addrinfo		 hints, *res0, *res;
1759 	struct node_host	*n, *h = NULL;
1760 	int			 noalias = 0, got4 = 0, got6 = 0;
1761 	char			*p, *ps;
1762 
1763 	if ((ps = strdup(s)) == NULL)
1764 		err(1, "host_dns: strdup");
1765 	if ((p = strrchr(ps, ':')) != NULL && !strcmp(p, ":0")) {
1766 		noalias = 1;
1767 		*p = '\0';
1768 	}
1769 	memset(&hints, 0, sizeof(hints));
1770 	hints.ai_family = PF_UNSPEC;
1771 	hints.ai_socktype = SOCK_STREAM; /* DUMMY */
1772 	if (numeric)
1773 		hints.ai_flags = AI_NUMERICHOST;
1774 	if (getaddrinfo(ps, NULL, &hints, &res0) != 0)
1775 		goto error;
1776 
1777 	for (res = res0; res; res = res->ai_next) {
1778 		if (res->ai_family != AF_INET &&
1779 		    res->ai_family != AF_INET6)
1780 			continue;
1781 		if (noalias) {
1782 			if (res->ai_family == AF_INET) {
1783 				if (got4)
1784 					continue;
1785 				got4 = 1;
1786 			} else {
1787 				if (got6)
1788 					continue;
1789 				got6 = 1;
1790 			}
1791 		}
1792 		n = calloc(1, sizeof(struct node_host));
1793 		if (n == NULL)
1794 			err(1, "host_dns: calloc");
1795 		n->ifname = NULL;
1796 		n->af = res->ai_family;
1797 		copy_satopfaddr(&n->addr.v.a.addr, res->ai_addr);
1798 		if (res->ai_family == AF_INET6)
1799 			n->ifindex =
1800 			    ((struct sockaddr_in6 *)res->ai_addr)->sin6_scope_id;
1801 		set_ipmask(n, mask);
1802 		n->next = NULL;
1803 		n->tail = n;
1804 		if (h == NULL)
1805 			h = n;
1806 		else {
1807 			h->tail->next = n;
1808 			h->tail = n;
1809 		}
1810 	}
1811 	freeaddrinfo(res0);
1812 error:
1813 	free(ps);
1814 
1815 	return (h);
1816 }
1817 
1818 /*
1819  * convert a hostname to a list of addresses and put them in the given buffer.
1820  * test:
1821  *	if set to 1, only simple addresses are accepted (no netblock, no "!").
1822  */
1823 int
append_addr(struct pfr_buffer * b,char * s,int test,int opts)1824 append_addr(struct pfr_buffer *b, char *s, int test, int opts)
1825 {
1826 	static int		 previous = 0;
1827 	static int		 expect = 0;
1828 	struct pfr_addr		*a;
1829 	struct node_host	*h, *n;
1830 	char			*r;
1831 	const char		*errstr;
1832 	int			 rv, not = 0, i = 0;
1833 	u_int16_t		 weight;
1834 
1835 	/* skip weight if given */
1836 	if (strcmp(s, "weight") == 0) {
1837 		expect = 1;
1838 		return (1); /* expecting further call */
1839 	}
1840 
1841 	/* check if previous host is set */
1842 	if (expect) {
1843 		/* parse and append load balancing weight */
1844 		weight = strtonum(s, 1, USHRT_MAX, &errstr);
1845 		if (errstr) {
1846 			fprintf(stderr, "failed to convert weight %s\n", s);
1847 			return (-1);
1848 		}
1849 		if (previous != -1) {
1850 			PFRB_FOREACH(a, b) {
1851 				if (++i >= previous) {
1852 					a->pfra_weight = weight;
1853 					a->pfra_type = PFRKE_COST;
1854 				}
1855 			}
1856 		}
1857 		expect = 0;
1858 		return (0);
1859 	}
1860 
1861 	for (r = s; *r == '!'; r++)
1862 		not = !not;
1863 	if ((n = host(r, opts)) == NULL) {
1864 		errno = 0;
1865 		return (-1);
1866 	}
1867 	rv = append_addr_host(b, n, test, not);
1868 	previous = b->pfrb_size;
1869 	do {
1870 		h = n;
1871 		n = n->next;
1872 		free(h);
1873 	} while (n != NULL);
1874 	return (rv);
1875 }
1876 
1877 /*
1878  * same as previous function, but with a pre-parsed input and the ability
1879  * to "negate" the result. Does not free the node_host list.
1880  * not:
1881  *      setting it to 1 is equivalent to adding "!" in front of parameter s.
1882  */
1883 int
append_addr_host(struct pfr_buffer * b,struct node_host * n,int test,int not)1884 append_addr_host(struct pfr_buffer *b, struct node_host *n, int test, int not)
1885 {
1886 	int			 bits;
1887 	struct pfr_addr		 addr;
1888 
1889 	do {
1890 		bzero(&addr, sizeof(addr));
1891 		addr.pfra_not = n->not ^ not;
1892 		addr.pfra_af = n->af;
1893 		addr.pfra_net = unmask(&n->addr.v.a.mask);
1894 		if (n->ifname) {
1895 			if (strlcpy(addr.pfra_ifname, n->ifname,
1896 			   sizeof(addr.pfra_ifname)) >= sizeof(addr.pfra_ifname))
1897 				errx(1, "append_addr_host: strlcpy");
1898 			addr.pfra_type = PFRKE_ROUTE;
1899 		}
1900 		if (n->weight > 0) {
1901 			addr.pfra_weight = n->weight;
1902 			addr.pfra_type = PFRKE_COST;
1903 		}
1904 		switch (n->af) {
1905 		case AF_INET:
1906 			addr.pfra_ip4addr.s_addr = n->addr.v.a.addr.addr32[0];
1907 			bits = 32;
1908 			break;
1909 		case AF_INET6:
1910 			memcpy(&addr.pfra_ip6addr, &n->addr.v.a.addr.v6,
1911 			    sizeof(struct in6_addr));
1912 			bits = 128;
1913 			break;
1914 		default:
1915 			errno = EINVAL;
1916 			return (-1);
1917 		}
1918 		if ((test && (not || addr.pfra_net != bits)) ||
1919 		    addr.pfra_net > bits) {
1920 			errno = EINVAL;
1921 			return (-1);
1922 		}
1923 		if (pfr_buf_add(b, &addr))
1924 			return (-1);
1925 	} while ((n = n->next) != NULL);
1926 
1927 	return (0);
1928 }
1929 
1930 int
pfctl_add_trans(struct pfr_buffer * buf,int type,const char * anchor)1931 pfctl_add_trans(struct pfr_buffer *buf, int type, const char *anchor)
1932 {
1933 	struct pfioc_trans_e trans;
1934 
1935 	bzero(&trans, sizeof(trans));
1936 	trans.type = type;
1937 	if (strlcpy(trans.anchor, anchor,
1938 	    sizeof(trans.anchor)) >= sizeof(trans.anchor))
1939 		errx(1, "pfctl_add_trans: strlcpy");
1940 
1941 	return pfr_buf_add(buf, &trans);
1942 }
1943 
1944 u_int32_t
pfctl_get_ticket(struct pfr_buffer * buf,int type,const char * anchor)1945 pfctl_get_ticket(struct pfr_buffer *buf, int type, const char *anchor)
1946 {
1947 	struct pfioc_trans_e *p;
1948 
1949 	PFRB_FOREACH(p, buf)
1950 		if (type == p->type && !strcmp(anchor, p->anchor))
1951 			return (p->ticket);
1952 	errx(1, "pfctl_get_ticket: assertion failed");
1953 }
1954 
1955 int
pfctl_trans(int dev,struct pfr_buffer * buf,u_long cmd,int from)1956 pfctl_trans(int dev, struct pfr_buffer *buf, u_long cmd, int from)
1957 {
1958 	struct pfioc_trans trans;
1959 
1960 	bzero(&trans, sizeof(trans));
1961 	trans.size = buf->pfrb_size - from;
1962 	trans.esize = sizeof(struct pfioc_trans_e);
1963 	trans.array = ((struct pfioc_trans_e *)buf->pfrb_caddr) + from;
1964 	return ioctl(dev, cmd, &trans);
1965 }
1966