xref: /netbsd-src/usr.sbin/npf/npfctl/npf_data.c (revision e89934bbf778a6d6d6894877c4da59d0c7835b0f)
1 /*	$NetBSD: npf_data.c,v 1.28 2017/01/19 20:18:17 rmind Exp $	*/
2 
3 /*-
4  * Copyright (c) 2009-2017 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.28 2017/01/19 20:18:17 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 /*
133  * npfctl_parse_fam_addr: parse a given a string and return the address
134  * family with the actual address as npf_addr_t.
135  *
136  * => Return true on success; false otherwise.
137  */
138 static bool
139 npfctl_parse_fam_addr(const char *name, sa_family_t *fam, npf_addr_t *addr)
140 {
141 	static const struct addrinfo hint = {
142 		.ai_family = AF_UNSPEC,
143 		.ai_flags = AI_NUMERICHOST
144 	};
145 	struct addrinfo *ai;
146 	int ret;
147 
148 	ret = getaddrinfo(name, NULL, &hint, &ai);
149 	if (ret) {
150 		yyerror("cannot parse '%s' (%s)", name, gai_strerror(ret));
151 		return false;
152 	}
153 	if (fam) {
154 		*fam = ai->ai_family;
155 	}
156 	if (!npfctl_copy_address(*fam, addr, ai->ai_addr)) {
157 		return false;
158 	}
159 	freeaddrinfo(ai);
160 	return true;
161 }
162 
163 /*
164  * npfctl_parse_mask: parse a given string which represents a mask and
165  * can either be in quad-dot or CIDR block notation; validates the mask
166  * given the family.
167  *
168  * => Returns true if mask is valid (or is NULL); false otherwise.
169  */
170 static bool
171 npfctl_parse_mask(const char *s, sa_family_t fam, npf_netmask_t *mask)
172 {
173 	unsigned max_mask = NPF_MAX_NETMASK;
174 	char *ep = NULL;
175 	npf_addr_t addr;
176 	uint8_t *ap;
177 
178 	assert(fam == AF_INET || fam == AF_INET6);
179 	if (!s) {
180 		/* No mask. */
181 		*mask = NPF_NO_NETMASK;
182 		return true;
183 	}
184 
185 	errno = 0;
186 	*mask = (npf_netmask_t)strtol(s, &ep, 0);
187 	if (*ep == '\0' && s != ep && errno != ERANGE) {
188 		/* Just a number -- CIDR notation. */
189 		goto check;
190 	}
191 
192 	/* Other characters: try to parse a full address. */
193 	if (!npfctl_parse_fam_addr(s, &fam, &addr)) {
194 		return false;
195 	}
196 
197 	/* Convert the address to CIDR block number. */
198 	ap = addr.word8 + (*mask / 8) - 1;
199 	while (ap >= addr.word8) {
200 		for (int j = 8; j > 0; j--) {
201 			if (*ap & 1)
202 				goto check;
203 			*ap >>= 1;
204 			(*mask)--;
205 			if (*mask == 0)
206 				goto check;
207 		}
208 		ap--;
209 	}
210 	*mask = NPF_NO_NETMASK;
211 	return true;
212 check:
213 	switch (fam) {
214 	case AF_INET:
215 		max_mask = 32;
216 		break;
217 	case AF_INET6:
218 		max_mask = 128;
219 		break;
220 	}
221 	return *mask <= max_mask;
222 }
223 
224 /*
225  * npfctl_parse_fam_addr_mask: return address family, address and mask.
226  *
227  * => Mask is optional and can be NULL.
228  * => Returns true on success or false if unable to parse.
229  */
230 npfvar_t *
231 npfctl_parse_fam_addr_mask(const char *addr, const char *mask,
232     unsigned long *nummask)
233 {
234 	fam_addr_mask_t fam;
235 	char buf[32];
236 
237 	memset(&fam, 0, sizeof(fam));
238 
239 	if (!npfctl_parse_fam_addr(addr, &fam.fam_family, &fam.fam_addr))
240 		return NULL;
241 
242 	/*
243 	 * Mask may be NULL.  In such case, "no mask" value will be set.
244 	 */
245 	if (nummask) {
246 		/* Let npfctl_parse_mask() validate the number. */
247 		snprintf(buf, sizeof(buf), "%lu", *nummask);
248 		mask = buf;
249 	}
250 	if (!npfctl_parse_mask(mask, fam.fam_family, &fam.fam_mask)) {
251 		return NULL;
252 	}
253 	return npfvar_create_element(NPFVAR_FAM, &fam, sizeof(fam));
254 }
255 
256 npfvar_t *
257 npfctl_parse_table_id(const char *name)
258 {
259 	u_int tid;
260 
261 	tid = npfctl_table_getid(name);
262 	if (tid == (unsigned)-1) {
263 		yyerror("table '%s' is not defined", name);
264 		return NULL;
265 	}
266 	return npfvar_create_element(NPFVAR_TABLE, &tid, sizeof(u_int));
267 }
268 
269 /*
270  * npfctl_parse_port_range: create a port-range variable.  Note that the
271  * passed port numbers should be in host byte order.
272  */
273 npfvar_t *
274 npfctl_parse_port_range(in_port_t s, in_port_t e)
275 {
276 	port_range_t pr;
277 
278 	pr.pr_start = htons(s);
279 	pr.pr_end = htons(e);
280 
281 	return npfvar_create_element(NPFVAR_PORT_RANGE, &pr, sizeof(pr));
282 }
283 
284 npfvar_t *
285 npfctl_parse_port_range_variable(const char *v, npfvar_t *vp)
286 {
287 	size_t count = npfvar_get_count(vp);
288 	npfvar_t *pvp = npfvar_create();
289 	port_range_t *pr;
290 
291 	for (size_t i = 0; i < count; i++) {
292 		int type = npfvar_get_type(vp, i);
293 		void *data = npfvar_get_data(vp, type, i);
294 		in_port_t p;
295 
296 		switch (type) {
297 		case NPFVAR_IDENTIFIER:
298 		case NPFVAR_STRING:
299 			p = npfctl_portno(data);
300 			npfvar_add_elements(pvp, npfctl_parse_port_range(p, p));
301 			break;
302 		case NPFVAR_PORT_RANGE:
303 			pr = data;
304 			npfvar_add_element(pvp, NPFVAR_PORT_RANGE, pr,
305 			    sizeof(*pr));
306 			break;
307 		case NPFVAR_NUM:
308 			p = *(unsigned long *)data;
309 			npfvar_add_elements(pvp, npfctl_parse_port_range(p, p));
310 			break;
311 		default:
312 			if (v) {
313 				yyerror("wrong variable '%s' type '%s' "
314 				    "for port range", v, npfvar_type(type));
315 			} else {
316 				yyerror("wrong element '%s' in the "
317 				    "inline list", npfvar_type(type));
318 			}
319 			npfvar_destroy(pvp);
320 			return NULL;
321 		}
322 	}
323 	return pvp;
324 }
325 
326 npfvar_t *
327 npfctl_parse_ifnet(const char *ifname, const int family)
328 {
329 	struct ifaddrs *ifa;
330 	ifnet_addr_t ifna;
331 	npfvar_t *vpa;
332 
333 	if (ifs_list == NULL && getifaddrs(&ifs_list) == -1) {
334 		err(EXIT_FAILURE, "getifaddrs");
335 	}
336 
337 	vpa = npfvar_create();
338 	ifna.ifna_name = estrdup(ifname);
339 	ifna.ifna_addrs = vpa;
340 	ifna.ifna_index = npfctl_find_ifindex(ifname);
341 	assert(ifna.ifna_index != 0);
342 
343 	for (ifa = ifs_list; ifa != NULL; ifa = ifa->ifa_next) {
344 		fam_addr_mask_t fam;
345 		struct sockaddr *sa;
346 
347 		if (strcmp(ifa->ifa_name, ifname) != 0)
348 			continue;
349 
350 		if ((ifa->ifa_flags & IFF_UP) == 0)
351 			warnx("interface '%s' is down", ifname);
352 
353 		sa = ifa->ifa_addr;
354 		if (sa->sa_family != AF_INET && sa->sa_family != AF_INET6)
355 			continue;
356 		if (family != AF_UNSPEC && sa->sa_family != family)
357 			continue;
358 
359 		memset(&fam, 0, sizeof(fam));
360 		fam.fam_family = sa->sa_family;
361 		fam.fam_ifindex = ifna.ifna_index;
362 		fam.fam_mask = NPF_NO_NETMASK;
363 
364 		if (!npfctl_copy_address(sa->sa_family, &fam.fam_addr, sa))
365 			goto out;
366 
367 		if (!npfvar_add_element(vpa, NPFVAR_FAM, &fam, sizeof(fam)))
368 			goto out;
369 	}
370 	if (npfvar_get_count(vpa) == 0) {
371 		yyerror("no addresses matched for interface '%s'", ifname);
372 		goto out;
373 	}
374 
375 	return npfvar_create_element(NPFVAR_INTERFACE, &ifna, sizeof(ifna));
376 out:
377 	npfvar_destroy(ifna.ifna_addrs);
378 	return NULL;
379 }
380 
381 bool
382 npfctl_parse_cidr(char *cidr, fam_addr_mask_t *fam, int *alen)
383 {
384 	char *mask, *p;
385 
386 	p = strchr(cidr, '\n');
387 	if (p) {
388 		*p = '\0';
389 	}
390 	mask = strchr(cidr, '/');
391 	if (mask) {
392 		*mask++ = '\0';
393 	}
394 
395 	memset(fam, 0, sizeof(*fam));
396 	if (!npfctl_parse_fam_addr(cidr, &fam->fam_family, &fam->fam_addr)) {
397 		return false;
398 	}
399 	if (!npfctl_parse_mask(mask, fam->fam_family, &fam->fam_mask)) {
400 		return false;
401 	}
402 	switch (fam->fam_family) {
403 	case AF_INET:
404 		*alen = sizeof(struct in_addr);
405 		break;
406 	case AF_INET6:
407 		*alen = sizeof(struct in6_addr);
408 		break;
409 	default:
410 		return false;
411 	}
412 	return true;
413 }
414 
415 int
416 npfctl_protono(const char *proto)
417 {
418 	struct protoent *pe;
419 
420 	pe = getprotobyname(proto);
421 	if (pe == NULL) {
422 		yyerror("unknown protocol '%s'", proto);
423 		return -1;
424 	}
425 	return pe->p_proto;
426 }
427 
428 /*
429  * npfctl_portno: convert port identifier (string) to a number.
430  *
431  * => Returns port number in host byte order.
432  */
433 in_port_t
434 npfctl_portno(const char *port)
435 {
436 	struct addrinfo *ai, *rai;
437 	in_port_t p = 0;
438 	int e;
439 
440 	e = getaddrinfo(NULL, port, NULL, &rai);
441 	if (e != 0) {
442 		yyerror("invalid port name '%s' (%s)", port, gai_strerror(e));
443 		return 0;
444 	}
445 
446 	for (ai = rai; ai; ai = ai->ai_next) {
447 		switch (ai->ai_family) {
448 		case AF_INET: {
449 			struct sockaddr_in *sin = (void *)ai->ai_addr;
450 			p = sin->sin_port;
451 			goto out;
452 		}
453 		case AF_INET6: {
454 			struct sockaddr_in6 *sin6 = (void *)ai->ai_addr;
455 			p = sin6->sin6_port;
456 			goto out;
457 		}
458 		default:
459 			break;
460 		}
461 	}
462 out:
463 	freeaddrinfo(rai);
464 	return ntohs(p);
465 }
466 
467 npfvar_t *
468 npfctl_parse_tcpflag(const char *s)
469 {
470 	uint8_t tfl = 0;
471 
472 	while (*s) {
473 		switch (*s) {
474 		case 'F': tfl |= TH_FIN; break;
475 		case 'S': tfl |= TH_SYN; break;
476 		case 'R': tfl |= TH_RST; break;
477 		case 'P': tfl |= TH_PUSH; break;
478 		case 'A': tfl |= TH_ACK; break;
479 		case 'U': tfl |= TH_URG; break;
480 		case 'E': tfl |= TH_ECE; break;
481 		case 'W': tfl |= TH_CWR; break;
482 		default:
483 			yyerror("invalid flag '%c'", *s);
484 			return NULL;
485 		}
486 		s++;
487 	}
488 	return npfvar_create_element(NPFVAR_TCPFLAG, &tfl, sizeof(tfl));
489 }
490 
491 uint8_t
492 npfctl_icmptype(int proto, const char *type)
493 {
494 #ifdef __NetBSD__
495 	uint8_t ul;
496 
497 	switch (proto) {
498 	case IPPROTO_ICMP:
499 		for (ul = 0; icmp_type[ul]; ul++)
500 			if (strcmp(icmp_type[ul], type) == 0)
501 				return ul;
502 		break;
503 	case IPPROTO_ICMPV6:
504 		for (ul = 0; icmp6_type_err[ul]; ul++)
505 			if (strcmp(icmp6_type_err[ul], type) == 0)
506 				return ul;
507 		for (ul = 0; icmp6_type_info[ul]; ul++)
508 			if (strcmp(icmp6_type_info[ul], type) == 0)
509 				return ul + 128;
510 		break;
511 	default:
512 		assert(false);
513 	}
514 #endif
515 	yyerror("unknown icmp-type %s", type);
516 	return ~0;
517 }
518 
519 uint8_t
520 npfctl_icmpcode(int proto, uint8_t type, const char *code)
521 {
522 #ifdef __NetBSD__
523 	const char * const *arr;
524 
525 	switch (proto) {
526 	case IPPROTO_ICMP:
527 		switch (type) {
528 		case ICMP_ECHOREPLY:
529 		case ICMP_SOURCEQUENCH:
530 		case ICMP_ALTHOSTADDR:
531 		case ICMP_ECHO:
532 		case ICMP_ROUTERSOLICIT:
533 		case ICMP_TSTAMP:
534 		case ICMP_TSTAMPREPLY:
535 		case ICMP_IREQ:
536 		case ICMP_IREQREPLY:
537 		case ICMP_MASKREQ:
538 		case ICMP_MASKREPLY:
539 			arr = icmp_code_none;
540 			break;
541 		case ICMP_ROUTERADVERT:
542 			arr = icmp_code_routeradvert;
543 			break;
544 		case ICMP_UNREACH:
545 			arr = icmp_code_unreach;
546 			break;
547 		case ICMP_REDIRECT:
548 			arr = icmp_code_redirect;
549 			break;
550 		case ICMP_TIMXCEED:
551 			arr = icmp_code_timxceed;
552 			break;
553 		case ICMP_PARAMPROB:
554 			arr = icmp_code_paramprob;
555 			break;
556 		case ICMP_PHOTURIS:
557 			arr = icmp_code_photuris;
558 			break;
559 		default:
560 			yyerror("unknown icmp-type %d while parsing code %s",
561 				type, code);
562 			return ~0;
563 		}
564 		break;
565 	case IPPROTO_ICMPV6:
566 		switch (type) {
567 		case ICMP6_DST_UNREACH:
568 			arr = icmp6_code_unreach;
569 			break;
570 		case ICMP6_TIME_EXCEEDED:
571 			arr = icmp6_code_timxceed;
572 			break;
573 		case ICMP6_PARAM_PROB:
574 			arr = icmp6_code_paramprob;
575 			break;
576 		case ICMP6_PACKET_TOO_BIG:
577 		/* code-less info ICMPs */
578 		case ICMP6_ECHO_REQUEST:
579 		case ICMP6_ECHO_REPLY:
580 		case MLD_LISTENER_QUERY:
581 		case MLD_LISTENER_REPORT:
582 		case MLD_LISTENER_DONE:
583 		case ND_ROUTER_SOLICIT:
584 		case ND_ROUTER_ADVERT:
585 		case ND_NEIGHBOR_SOLICIT:
586 		case ND_NEIGHBOR_ADVERT:
587 		case ND_REDIRECT:
588 			arr = icmp6_code_none;
589 			break;
590 		/* XXX TODO: info ICMPs with code values */
591 		default:
592 			yyerror("unknown icmp-type %d while parsing code %s",
593 				type, code);
594 			return ~0;
595 		}
596 		break;
597 	default:
598 		assert(false);
599 	}
600 
601 	for (uint8_t ul = 0; arr[ul]; ul++) {
602 		if (strcmp(arr[ul], code) == 0)
603 			return ul;
604 	}
605 #endif
606 	yyerror("unknown code %s for icmp-type %d", code, type);
607 	return ~0;
608 }
609 
610 npfvar_t *
611 npfctl_parse_icmp(int proto, int type, int code)
612 {
613 	npfvar_t *vp = npfvar_create();
614 
615 	if (!npfvar_add_element(vp, NPFVAR_ICMP, &type, sizeof(type)))
616 		goto out;
617 
618 	if (!npfvar_add_element(vp, NPFVAR_ICMP, &code, sizeof(code)))
619 		goto out;
620 
621 	return vp;
622 out:
623 	npfvar_destroy(vp);
624 	return NULL;
625 }
626 
627 /*
628  * npfctl_npt66_calcadj: calculate the adjustment for NPTv6 as per RFC 6296.
629  */
630 uint16_t
631 npfctl_npt66_calcadj(npf_netmask_t len, const npf_addr_t *pref_in,
632     const npf_addr_t *pref_out)
633 {
634 	const uint16_t *addr6_in = (const uint16_t *)pref_in;
635 	const uint16_t *addr6_out = (const uint16_t *)pref_out;
636 	unsigned i, remnant, wordmask, preflen = len >> 4;
637 	uint32_t adj, isum = 0, osum = 0;
638 
639 	/*
640 	 * Extract the bits within a 16-bit word (when prefix length is
641 	 * not dividable by 16) and include them into the sum.
642 	 */
643 	remnant = len - (preflen << 4);
644 	wordmask = (1U << remnant) - 1;
645 	assert(wordmask == 0 || (len % 16) != 0);
646 
647 	/* Inner prefix - sum and fold. */
648 	for (i = 0; i < preflen; i++) {
649 		isum += addr6_in[i];
650 	}
651 	isum += addr6_in[i] & wordmask;
652 	while (isum >> 16) {
653 		isum = (isum >> 16) + (isum & 0xffff);
654 	}
655 
656 	/* Outer prefix - sum and fold. */
657 	for (i = 0; i < preflen; i++) {
658 		osum += addr6_out[i];
659 	}
660 	osum += addr6_out[i] & wordmask;
661 	while (osum >> 16) {
662 		osum = (osum >> 16) + (osum & 0xffff);
663 	}
664 
665 	/* Calculate 1's complement difference. */
666 	adj = isum + ~osum;
667 	while (adj >> 16) {
668 		adj = (adj >> 16) + (adj & 0xffff);
669 	}
670 	return (uint16_t)adj;
671 }
672