xref: /netbsd-src/usr.sbin/npf/npfctl/npf_data.c (revision 479d8f7d843cc1b22d497efdf1f27a50ee8418d4)
1 /*	$NetBSD: npf_data.c,v 1.27 2016/12/27 22:35:33 rmind Exp $	*/
2 
3 /*-
4  * Copyright (c) 2009-2014 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
17  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
18  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
20  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26  * POSSIBILITY OF SUCH DAMAGE.
27  */
28 
29 /*
30  * npfctl(8) data manipulation and helper routines.
31  */
32 
33 #include <sys/cdefs.h>
34 __RCSID("$NetBSD: npf_data.c,v 1.27 2016/12/27 22:35:33 rmind Exp $");
35 
36 #include <stdlib.h>
37 #include <stddef.h>
38 
39 #include <sys/types.h>
40 #include <netinet/in.h>
41 #include <netinet/in_systm.h>
42 #include <netinet/ip.h>
43 #define ICMP_STRINGS
44 #include <netinet/ip_icmp.h>
45 #define ICMP6_STRINGS
46 #include <netinet/icmp6.h>
47 #define	__FAVOR_BSD
48 #include <netinet/tcp.h>
49 #include <net/if.h>
50 
51 #include <string.h>
52 #include <ctype.h>
53 #include <err.h>
54 #include <errno.h>
55 #include <ifaddrs.h>
56 #include <netdb.h>
57 
58 #include "npfctl.h"
59 
60 static struct ifaddrs *		ifs_list = NULL;
61 
62 void
63 npfctl_note_interface(const char *ifname)
64 {
65 	unsigned long if_idx = if_nametoindex(ifname);
66 	bool testif = npfctl_debug_addif(ifname);
67 	const char *p = ifname;
68 
69 	/* If such interface exists or if it is a test interface - done. */
70 	if (if_idx || testif) {
71 		return;
72 	}
73 
74 	/*
75 	 * Minimum sanity check.  The interface name shall be non-empty
76 	 * string shorter than IFNAMSIZ and alphanumeric only.
77 	 */
78 	if (*p == '\0') {
79 		goto invalid;
80 	}
81 	while (*p) {
82 		const size_t len = (ptrdiff_t)p - (ptrdiff_t)ifname;
83 
84 		if (!isalnum((unsigned char)*p) || len > IFNAMSIZ) {
85 invalid:		yyerror("illegitimate interface name '%s'", ifname);
86 		}
87 		p++;
88 	}
89 
90 	/* Throw a warning, so that the user could double check. */
91 	warnx("warning - unknown interface '%s'", ifname);
92 }
93 
94 static unsigned long
95 npfctl_find_ifindex(const char *ifname)
96 {
97 	unsigned long if_idx = if_nametoindex(ifname);
98 	bool testif = npfctl_debug_addif(ifname);
99 
100 	if (!if_idx) {
101 		if (testif) {
102 			static u_int dummy_if_idx = (1 << 15);
103 			return ++dummy_if_idx;
104 		}
105 		yyerror("unknown interface '%s'", ifname);
106 	}
107 	return if_idx;
108 }
109 
110 static bool
111 npfctl_copy_address(sa_family_t fam, npf_addr_t *addr, const void *ptr)
112 {
113 	memset(addr, 0, sizeof(npf_addr_t));
114 
115 	switch (fam) {
116 	case AF_INET: {
117 		const struct sockaddr_in *sin = ptr;
118 		memcpy(addr, &sin->sin_addr, sizeof(sin->sin_addr));
119 		return true;
120 	}
121 	case AF_INET6: {
122 		const struct sockaddr_in6 *sin6 = ptr;
123 		memcpy(addr, &sin6->sin6_addr, sizeof(sin6->sin6_addr));
124 		return true;
125 	}
126 	default:
127 		yyerror("unknown address family %u", fam);
128 		return false;
129 	}
130 }
131 
132 static bool
133 npfctl_parse_fam_addr(const char *name, sa_family_t *fam, npf_addr_t *addr)
134 {
135 	static const struct addrinfo hint = {
136 		.ai_family = AF_UNSPEC,
137 		.ai_flags = AI_NUMERICHOST
138 	};
139 	struct addrinfo *ai;
140 	int ret;
141 
142 	ret = getaddrinfo(name, NULL, &hint, &ai);
143 	if (ret) {
144 		yyerror("cannot parse '%s' (%s)", name, gai_strerror(ret));
145 		return false;
146 	}
147 	if (fam) {
148 		*fam = ai->ai_family;
149 	}
150 	if (!npfctl_copy_address(*fam, addr, ai->ai_addr)) {
151 		return false;
152 	}
153 	freeaddrinfo(ai);
154 	return true;
155 }
156 
157 static bool
158 npfctl_parse_mask(const char *s, sa_family_t fam, npf_netmask_t *mask)
159 {
160 	char *ep = NULL;
161 	npf_addr_t addr;
162 	uint8_t *ap;
163 
164 	if (s) {
165 		errno = 0;
166 		*mask = (npf_netmask_t)strtol(s, &ep, 0);
167 		if (*ep == '\0' && s != ep && errno != ERANGE)
168 			return true;
169 		if (!npfctl_parse_fam_addr(s, &fam, &addr))
170 			return false;
171 	}
172 
173 	assert(fam == AF_INET || fam == AF_INET6);
174 	*mask = NPF_NO_NETMASK;
175 	if (ep == NULL) {
176 		return true;
177 	}
178 
179 	ap = addr.word8 + (*mask / 8) - 1;
180 	while (ap >= addr.word8) {
181 		for (int j = 8; j > 0; j--) {
182 			if (*ap & 1)
183 				return true;
184 			*ap >>= 1;
185 			(*mask)--;
186 			if (*mask == 0)
187 				return true;
188 		}
189 		ap--;
190 	}
191 	return true;
192 }
193 
194 /*
195  * npfctl_parse_fam_addr_mask: return address family, address and mask.
196  *
197  * => Mask is optional and can be NULL.
198  * => Returns true on success or false if unable to parse.
199  */
200 npfvar_t *
201 npfctl_parse_fam_addr_mask(const char *addr, const char *mask,
202     unsigned long *nummask)
203 {
204 	fam_addr_mask_t fam;
205 
206 	memset(&fam, 0, sizeof(fam));
207 
208 	if (!npfctl_parse_fam_addr(addr, &fam.fam_family, &fam.fam_addr))
209 		return NULL;
210 
211 	/*
212 	 * Note: both mask and nummask may be NULL.  In such case,
213 	 * npfctl_parse_mask() will handle and will set full mask.
214 	 */
215 	if (nummask) {
216 		fam.fam_mask = *nummask;
217 	} else if (!npfctl_parse_mask(mask, fam.fam_family, &fam.fam_mask)) {
218 		return NULL;
219 	}
220 	return npfvar_create_element(NPFVAR_FAM, &fam, sizeof(fam));
221 }
222 
223 npfvar_t *
224 npfctl_parse_table_id(const char *name)
225 {
226 	u_int tid;
227 
228 	tid = npfctl_table_getid(name);
229 	if (tid == (unsigned)-1) {
230 		yyerror("table '%s' is not defined", name);
231 		return NULL;
232 	}
233 	return npfvar_create_element(NPFVAR_TABLE, &tid, sizeof(u_int));
234 }
235 
236 /*
237  * npfctl_parse_port_range: create a port-range variable.  Note that the
238  * passed port numbers should be in host byte order.
239  */
240 npfvar_t *
241 npfctl_parse_port_range(in_port_t s, in_port_t e)
242 {
243 	port_range_t pr;
244 
245 	pr.pr_start = htons(s);
246 	pr.pr_end = htons(e);
247 
248 	return npfvar_create_element(NPFVAR_PORT_RANGE, &pr, sizeof(pr));
249 }
250 
251 npfvar_t *
252 npfctl_parse_port_range_variable(const char *v)
253 {
254 	npfvar_t *vp = npfvar_lookup(v);
255 	size_t count = npfvar_get_count(vp);
256 	npfvar_t *pvp = npfvar_create();
257 	port_range_t *pr;
258 	in_port_t p;
259 
260 	for (size_t i = 0; i < count; i++) {
261 		int type = npfvar_get_type(vp, i);
262 		void *data = npfvar_get_data(vp, type, i);
263 
264 		switch (type) {
265 		case NPFVAR_IDENTIFIER:
266 		case NPFVAR_STRING:
267 			p = npfctl_portno(data);
268 			npfvar_add_elements(pvp, npfctl_parse_port_range(p, p));
269 			break;
270 		case NPFVAR_PORT_RANGE:
271 			pr = data;
272 			npfvar_add_element(pvp, NPFVAR_PORT_RANGE, pr,
273 			    sizeof(*pr));
274 			break;
275 		case NPFVAR_NUM:
276 			p = *(unsigned long *)data;
277 			npfvar_add_elements(pvp, npfctl_parse_port_range(p, p));
278 			break;
279 		default:
280 			yyerror("wrong variable '%s' type '%s' for port range",
281 			    v, npfvar_type(type));
282 			npfvar_destroy(pvp);
283 			return NULL;
284 		}
285 	}
286 	return pvp;
287 }
288 
289 npfvar_t *
290 npfctl_parse_ifnet(const char *ifname, const int family)
291 {
292 	struct ifaddrs *ifa;
293 	ifnet_addr_t ifna;
294 	npfvar_t *vpa;
295 
296 	if (ifs_list == NULL && getifaddrs(&ifs_list) == -1) {
297 		err(EXIT_FAILURE, "getifaddrs");
298 	}
299 
300 	vpa = npfvar_create();
301 	ifna.ifna_name = estrdup(ifname);
302 	ifna.ifna_addrs = vpa;
303 	ifna.ifna_index = npfctl_find_ifindex(ifname);
304 	assert(ifna.ifna_index != 0);
305 
306 	for (ifa = ifs_list; ifa != NULL; ifa = ifa->ifa_next) {
307 		fam_addr_mask_t fam;
308 		struct sockaddr *sa;
309 
310 		if (strcmp(ifa->ifa_name, ifname) != 0)
311 			continue;
312 
313 		if ((ifa->ifa_flags & IFF_UP) == 0)
314 			warnx("interface '%s' is down", ifname);
315 
316 		sa = ifa->ifa_addr;
317 		if (sa->sa_family != AF_INET && sa->sa_family != AF_INET6)
318 			continue;
319 		if (family != AF_UNSPEC && sa->sa_family != family)
320 			continue;
321 
322 		memset(&fam, 0, sizeof(fam));
323 		fam.fam_family = sa->sa_family;
324 		fam.fam_ifindex = ifna.ifna_index;
325 
326 		if (!npfctl_copy_address(sa->sa_family, &fam.fam_addr, sa))
327 			goto out;
328 
329 		if (!npfctl_parse_mask(NULL, fam.fam_family, &fam.fam_mask))
330 			goto out;
331 
332 		if (!npfvar_add_element(vpa, NPFVAR_FAM, &fam, sizeof(fam)))
333 			goto out;
334 	}
335 	if (npfvar_get_count(vpa) == 0) {
336 		yyerror("no addresses matched for interface '%s'", ifname);
337 		goto out;
338 	}
339 
340 	return npfvar_create_element(NPFVAR_INTERFACE, &ifna, sizeof(ifna));
341 out:
342 	npfvar_destroy(ifna.ifna_addrs);
343 	return NULL;
344 }
345 
346 bool
347 npfctl_parse_cidr(char *cidr, fam_addr_mask_t *fam, int *alen)
348 {
349 	char *mask, *p;
350 
351 	p = strchr(cidr, '\n');
352 	if (p) {
353 		*p = '\0';
354 	}
355 	mask = strchr(cidr, '/');
356 	if (mask) {
357 		*mask++ = '\0';
358 	}
359 
360 	memset(fam, 0, sizeof(*fam));
361 	if (!npfctl_parse_fam_addr(cidr, &fam->fam_family, &fam->fam_addr)) {
362 		return false;
363 	}
364 	if (!npfctl_parse_mask(mask, fam->fam_family, &fam->fam_mask)) {
365 		return false;
366 	}
367 	switch (fam->fam_family) {
368 	case AF_INET:
369 		*alen = sizeof(struct in_addr);
370 		break;
371 	case AF_INET6:
372 		*alen = sizeof(struct in6_addr);
373 		break;
374 	default:
375 		return false;
376 	}
377 	return true;
378 }
379 
380 int
381 npfctl_protono(const char *proto)
382 {
383 	struct protoent *pe;
384 
385 	pe = getprotobyname(proto);
386 	if (pe == NULL) {
387 		yyerror("unknown protocol '%s'", proto);
388 		return -1;
389 	}
390 	return pe->p_proto;
391 }
392 
393 /*
394  * npfctl_portno: convert port identifier (string) to a number.
395  *
396  * => Returns port number in host byte order.
397  */
398 in_port_t
399 npfctl_portno(const char *port)
400 {
401 	struct addrinfo *ai, *rai;
402 	in_port_t p = 0;
403 	int e;
404 
405 	e = getaddrinfo(NULL, port, NULL, &rai);
406 	if (e != 0) {
407 		yyerror("invalid port name '%s' (%s)", port, gai_strerror(e));
408 		return 0;
409 	}
410 
411 	for (ai = rai; ai; ai = ai->ai_next) {
412 		switch (ai->ai_family) {
413 		case AF_INET: {
414 			struct sockaddr_in *sin = (void *)ai->ai_addr;
415 			p = sin->sin_port;
416 			goto out;
417 		}
418 		case AF_INET6: {
419 			struct sockaddr_in6 *sin6 = (void *)ai->ai_addr;
420 			p = sin6->sin6_port;
421 			goto out;
422 		}
423 		default:
424 			break;
425 		}
426 	}
427 out:
428 	freeaddrinfo(rai);
429 	return ntohs(p);
430 }
431 
432 npfvar_t *
433 npfctl_parse_tcpflag(const char *s)
434 {
435 	uint8_t tfl = 0;
436 
437 	while (*s) {
438 		switch (*s) {
439 		case 'F': tfl |= TH_FIN; break;
440 		case 'S': tfl |= TH_SYN; break;
441 		case 'R': tfl |= TH_RST; break;
442 		case 'P': tfl |= TH_PUSH; break;
443 		case 'A': tfl |= TH_ACK; break;
444 		case 'U': tfl |= TH_URG; break;
445 		case 'E': tfl |= TH_ECE; break;
446 		case 'W': tfl |= TH_CWR; break;
447 		default:
448 			yyerror("invalid flag '%c'", *s);
449 			return NULL;
450 		}
451 		s++;
452 	}
453 	return npfvar_create_element(NPFVAR_TCPFLAG, &tfl, sizeof(tfl));
454 }
455 
456 uint8_t
457 npfctl_icmptype(int proto, const char *type)
458 {
459 #ifdef __NetBSD__
460 	uint8_t ul;
461 
462 	switch (proto) {
463 	case IPPROTO_ICMP:
464 		for (ul = 0; icmp_type[ul]; ul++)
465 			if (strcmp(icmp_type[ul], type) == 0)
466 				return ul;
467 		break;
468 	case IPPROTO_ICMPV6:
469 		for (ul = 0; icmp6_type_err[ul]; ul++)
470 			if (strcmp(icmp6_type_err[ul], type) == 0)
471 				return ul;
472 		for (ul = 0; icmp6_type_info[ul]; ul++)
473 			if (strcmp(icmp6_type_info[ul], type) == 0)
474 				return ul + 128;
475 		break;
476 	default:
477 		assert(false);
478 	}
479 #endif
480 	yyerror("unknown icmp-type %s", type);
481 	return ~0;
482 }
483 
484 uint8_t
485 npfctl_icmpcode(int proto, uint8_t type, const char *code)
486 {
487 #ifdef __NetBSD__
488 	const char * const *arr;
489 
490 	switch (proto) {
491 	case IPPROTO_ICMP:
492 		switch (type) {
493 		case ICMP_ECHOREPLY:
494 		case ICMP_SOURCEQUENCH:
495 		case ICMP_ALTHOSTADDR:
496 		case ICMP_ECHO:
497 		case ICMP_ROUTERSOLICIT:
498 		case ICMP_TSTAMP:
499 		case ICMP_TSTAMPREPLY:
500 		case ICMP_IREQ:
501 		case ICMP_IREQREPLY:
502 		case ICMP_MASKREQ:
503 		case ICMP_MASKREPLY:
504 			arr = icmp_code_none;
505 			break;
506 		case ICMP_ROUTERADVERT:
507 			arr = icmp_code_routeradvert;
508 			break;
509 		case ICMP_UNREACH:
510 			arr = icmp_code_unreach;
511 			break;
512 		case ICMP_REDIRECT:
513 			arr = icmp_code_redirect;
514 			break;
515 		case ICMP_TIMXCEED:
516 			arr = icmp_code_timxceed;
517 			break;
518 		case ICMP_PARAMPROB:
519 			arr = icmp_code_paramprob;
520 			break;
521 		case ICMP_PHOTURIS:
522 			arr = icmp_code_photuris;
523 			break;
524 		default:
525 			yyerror("unknown icmp-type %d while parsing code %s",
526 				type, code);
527 			return ~0;
528 		}
529 		break;
530 	case IPPROTO_ICMPV6:
531 		switch (type) {
532 		case ICMP6_DST_UNREACH:
533 			arr = icmp6_code_unreach;
534 			break;
535 		case ICMP6_TIME_EXCEEDED:
536 			arr = icmp6_code_timxceed;
537 			break;
538 		case ICMP6_PARAM_PROB:
539 			arr = icmp6_code_paramprob;
540 			break;
541 		case ICMP6_PACKET_TOO_BIG:
542 		/* code-less info ICMPs */
543 		case ICMP6_ECHO_REQUEST:
544 		case ICMP6_ECHO_REPLY:
545 		case MLD_LISTENER_QUERY:
546 		case MLD_LISTENER_REPORT:
547 		case MLD_LISTENER_DONE:
548 		case ND_ROUTER_SOLICIT:
549 		case ND_ROUTER_ADVERT:
550 		case ND_NEIGHBOR_SOLICIT:
551 		case ND_NEIGHBOR_ADVERT:
552 		case ND_REDIRECT:
553 			arr = icmp6_code_none;
554 			break;
555 		/* XXX TODO: info ICMPs with code values */
556 		default:
557 			yyerror("unknown icmp-type %d while parsing code %s",
558 				type, code);
559 			return ~0;
560 		}
561 		break;
562 	default:
563 		assert(false);
564 	}
565 
566 	for (uint8_t ul = 0; arr[ul]; ul++) {
567 		if (strcmp(arr[ul], code) == 0)
568 			return ul;
569 	}
570 #endif
571 	yyerror("unknown code %s for icmp-type %d", code, type);
572 	return ~0;
573 }
574 
575 npfvar_t *
576 npfctl_parse_icmp(int proto, int type, int code)
577 {
578 	npfvar_t *vp = npfvar_create();
579 
580 	if (!npfvar_add_element(vp, NPFVAR_ICMP, &type, sizeof(type)))
581 		goto out;
582 
583 	if (!npfvar_add_element(vp, NPFVAR_ICMP, &code, sizeof(code)))
584 		goto out;
585 
586 	return vp;
587 out:
588 	npfvar_destroy(vp);
589 	return NULL;
590 }
591 
592 /*
593  * npfctl_npt66_calcadj: calculate the adjustment for NPTv6 as per RFC 6296.
594  */
595 uint16_t
596 npfctl_npt66_calcadj(npf_netmask_t len, const npf_addr_t *pref_in,
597     const npf_addr_t *pref_out)
598 {
599 	const uint16_t *addr6_in = (const uint16_t *)pref_in;
600 	const uint16_t *addr6_out = (const uint16_t *)pref_out;
601 	unsigned i, remnant, wordmask, preflen = len >> 4;
602 	uint32_t adj, isum = 0, osum = 0;
603 
604 	/*
605 	 * Extract the bits within a 16-bit word (when prefix length is
606 	 * not dividable by 16) and include them into the sum.
607 	 */
608 	remnant = len - (preflen << 4);
609 	wordmask = (1U << remnant) - 1;
610 	assert(wordmask == 0 || (len % 16) != 0);
611 
612 	/* Inner prefix - sum and fold. */
613 	for (i = 0; i < preflen; i++) {
614 		isum += addr6_in[i];
615 	}
616 	isum += addr6_in[i] & wordmask;
617 	while (isum >> 16) {
618 		isum = (isum >> 16) + (isum & 0xffff);
619 	}
620 
621 	/* Outer prefix - sum and fold. */
622 	for (i = 0; i < preflen; i++) {
623 		osum += addr6_out[i];
624 	}
625 	osum += addr6_out[i] & wordmask;
626 	while (osum >> 16) {
627 		osum = (osum >> 16) + (osum & 0xffff);
628 	}
629 
630 	/* Calculate 1's complement difference. */
631 	adj = isum + ~osum;
632 	while (adj >> 16) {
633 		adj = (adj >> 16) + (adj & 0xffff);
634 	}
635 	return (uint16_t)adj;
636 }
637