xref: /netbsd-src/usr.sbin/npf/npfctl/npf_data.c (revision 946379e7b37692fc43f68eb0d1c10daa0a7f3b6c)
1 /*	$NetBSD: npf_data.c,v 1.25 2014/02/13 03:34:40 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.25 2014/02/13 03:34:40 rmind Exp $");
35 
36 #include <sys/types.h>
37 #include <sys/null.h>
38 
39 #include <netinet/in.h>
40 #include <netinet/in_systm.h>
41 #include <netinet/ip.h>
42 #define ICMP_STRINGS
43 #include <netinet/ip_icmp.h>
44 #define ICMP6_STRINGS
45 #include <netinet/icmp6.h>
46 #include <netinet/tcp.h>
47 #include <net/if.h>
48 
49 #include <stdlib.h>
50 #include <stddef.h>
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.s6_addr + (*mask / 8) - 1;
180 	while (ap >= addr.s6_addr) {
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 	uint8_t ul;
460 
461 	switch (proto) {
462 	case IPPROTO_ICMP:
463 		for (ul = 0; icmp_type[ul]; ul++)
464 			if (strcmp(icmp_type[ul], type) == 0)
465 				return ul;
466 		break;
467 	case IPPROTO_ICMPV6:
468 		for (ul = 0; icmp6_type_err[ul]; ul++)
469 			if (strcmp(icmp6_type_err[ul], type) == 0)
470 				return ul;
471 		for (ul = 0; icmp6_type_info[ul]; ul++)
472 			if (strcmp(icmp6_type_info[ul], type) == 0)
473 				return ul + 128;
474 		break;
475 	default:
476 		assert(false);
477 	}
478 
479 	yyerror("unknown icmp-type %s", type);
480 	return ~0;
481 }
482 
483 uint8_t
484 npfctl_icmpcode(int proto, uint8_t type, const char *code)
485 {
486 	const char * const *arr;
487 
488 	switch (proto) {
489 	case IPPROTO_ICMP:
490 		switch (type) {
491 		case ICMP_ECHOREPLY:
492 		case ICMP_SOURCEQUENCH:
493 		case ICMP_ALTHOSTADDR:
494 		case ICMP_ECHO:
495 		case ICMP_ROUTERSOLICIT:
496 		case ICMP_TSTAMP:
497 		case ICMP_TSTAMPREPLY:
498 		case ICMP_IREQ:
499 		case ICMP_IREQREPLY:
500 		case ICMP_MASKREQ:
501 		case ICMP_MASKREPLY:
502 			arr = icmp_code_none;
503 			break;
504 		case ICMP_ROUTERADVERT:
505 			arr = icmp_code_routeradvert;
506 			break;
507 		case ICMP_UNREACH:
508 			arr = icmp_code_unreach;
509 			break;
510 		case ICMP_REDIRECT:
511 			arr = icmp_code_redirect;
512 			break;
513 		case ICMP_TIMXCEED:
514 			arr = icmp_code_timxceed;
515 			break;
516 		case ICMP_PARAMPROB:
517 			arr = icmp_code_paramprob;
518 			break;
519 		case ICMP_PHOTURIS:
520 			arr = icmp_code_photuris;
521 			break;
522 		default:
523 			yyerror("unknown icmp-type %d while parsing code %s",
524 				type, code);
525 			return ~0;
526 		}
527 		break;
528 	case IPPROTO_ICMPV6:
529 		switch (type) {
530 		case ICMP6_DST_UNREACH:
531 			arr = icmp6_code_unreach;
532 			break;
533 		case ICMP6_TIME_EXCEEDED:
534 			arr = icmp6_code_timxceed;
535 			break;
536 		case ICMP6_PARAM_PROB:
537 			arr = icmp6_code_paramprob;
538 			break;
539 		case ICMP6_PACKET_TOO_BIG:
540 		/* code-less info ICMPs */
541 		case ICMP6_ECHO_REQUEST:
542 		case ICMP6_ECHO_REPLY:
543 		case MLD_LISTENER_QUERY:
544 		case MLD_LISTENER_REPORT:
545 		case MLD_LISTENER_DONE:
546 		case ND_ROUTER_SOLICIT:
547 		case ND_ROUTER_ADVERT:
548 		case ND_NEIGHBOR_SOLICIT:
549 		case ND_NEIGHBOR_ADVERT:
550 		case ND_REDIRECT:
551 			arr = icmp6_code_none;
552 			break;
553 		/* XXX TODO: info ICMPs with code values */
554 		default:
555 			yyerror("unknown icmp-type %d while parsing code %s",
556 				type, code);
557 			return ~0;
558 		}
559 		break;
560 	default:
561 		assert(false);
562 	}
563 
564 	for (uint8_t ul = 0; arr[ul]; ul++) {
565 		if (strcmp(arr[ul], code) == 0)
566 			return ul;
567 	}
568 	yyerror("unknown code %s for icmp-type %d", code, type);
569 	return ~0;
570 }
571 
572 npfvar_t *
573 npfctl_parse_icmp(int proto, int type, int code)
574 {
575 	npfvar_t *vp = npfvar_create();
576 
577 	if (!npfvar_add_element(vp, NPFVAR_ICMP, &type, sizeof(type)))
578 		goto out;
579 
580 	if (!npfvar_add_element(vp, NPFVAR_ICMP, &code, sizeof(code)))
581 		goto out;
582 
583 	return vp;
584 out:
585 	npfvar_destroy(vp);
586 	return NULL;
587 }
588 
589 /*
590  * npfctl_npt66_calcadj: calculate the adjustment for NPTv6 as per RFC 6296.
591  */
592 uint16_t
593 npfctl_npt66_calcadj(npf_netmask_t len, const npf_addr_t *pref_in,
594     const npf_addr_t *pref_out)
595 {
596 	const uint16_t *addr6_in = (const uint16_t *)pref_in;
597 	const uint16_t *addr6_out = (const uint16_t *)pref_out;
598 	unsigned i, remnant, wordmask, preflen = len >> 4;
599 	uint32_t adj, isum = 0, osum = 0;
600 
601 	/*
602 	 * Extract the bits within a 16-bit word (when prefix length is
603 	 * not dividable by 16) and include them into the sum.
604 	 */
605 	remnant = len - (preflen << 4);
606 	wordmask = (1U << remnant) - 1;
607 	assert(wordmask == 0 || (len % 16) != 0);
608 
609 	/* Inner prefix - sum and fold. */
610 	for (i = 0; i < preflen; i++) {
611 		isum += addr6_in[i];
612 	}
613 	isum += addr6_in[i] & wordmask;
614 	while (isum >> 16) {
615 		isum = (isum >> 16) + (isum & 0xffff);
616 	}
617 
618 	/* Outer prefix - sum and fold. */
619 	for (i = 0; i < preflen; i++) {
620 		osum += addr6_out[i];
621 	}
622 	osum += addr6_out[i] & wordmask;
623 	while (osum >> 16) {
624 		osum = (osum >> 16) + (osum & 0xffff);
625 	}
626 
627 	/* Calculate 1's complement difference. */
628 	adj = isum + ~osum;
629 	while (adj >> 16) {
630 		adj = (adj >> 16) + (adj & 0xffff);
631 	}
632 	return (uint16_t)adj;
633 }
634