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