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