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