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