npf_data.c revision 1.29 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.29 2018/09/29 14:41:36 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
58 static struct ifaddrs * ifs_list = NULL;
59
60 void
61 npfctl_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 invalid;
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 invalid: yyerror("illegitimate interface name '%s'", ifname);
84 }
85 p++;
86 }
87
88 /* Throw a warning, so that the user could double check. */
89 warnx("warning - unknown interface '%s'", ifname);
90 }
91
92 static unsigned long
93 npfctl_find_ifindex(const char *ifname)
94 {
95 unsigned long if_idx = if_nametoindex(ifname);
96 bool testif = npfctl_debug_addif(ifname);
97
98 if (!if_idx) {
99 if (testif) {
100 static u_int dummy_if_idx = (1 << 15);
101 return ++dummy_if_idx;
102 }
103 yyerror("unknown interface '%s'", ifname);
104 }
105 return if_idx;
106 }
107
108 static bool
109 npfctl_copy_address(sa_family_t fam, npf_addr_t *addr, const void *ptr)
110 {
111 memset(addr, 0, sizeof(npf_addr_t));
112
113 switch (fam) {
114 case AF_INET: {
115 const struct sockaddr_in *sin = ptr;
116 memcpy(addr, &sin->sin_addr, sizeof(sin->sin_addr));
117 return true;
118 }
119 case AF_INET6: {
120 const struct sockaddr_in6 *sin6 = ptr;
121 memcpy(addr, &sin6->sin6_addr, sizeof(sin6->sin6_addr));
122 return true;
123 }
124 default:
125 yyerror("unknown address family %u", fam);
126 return false;
127 }
128 }
129
130 /*
131 * npfctl_parse_fam_addr: parse a given a string and return the address
132 * family with the actual address as npf_addr_t.
133 *
134 * => Return true on success; false otherwise.
135 */
136 static bool
137 npfctl_parse_fam_addr(const char *name, sa_family_t *fam, npf_addr_t *addr)
138 {
139 static const struct addrinfo hint = {
140 .ai_family = AF_UNSPEC,
141 .ai_flags = AI_NUMERICHOST
142 };
143 struct addrinfo *ai;
144 int ret;
145
146 ret = getaddrinfo(name, NULL, &hint, &ai);
147 if (ret) {
148 yyerror("cannot parse '%s' (%s)", name, gai_strerror(ret));
149 return false;
150 }
151 if (fam) {
152 *fam = ai->ai_family;
153 }
154 if (!npfctl_copy_address(*fam, addr, ai->ai_addr)) {
155 return false;
156 }
157 freeaddrinfo(ai);
158 return true;
159 }
160
161 /*
162 * npfctl_parse_mask: parse a given string which represents a mask and
163 * can either be in quad-dot or CIDR block notation; validates the mask
164 * given the family.
165 *
166 * => Returns true if mask is valid (or is NULL); false otherwise.
167 */
168 static bool
169 npfctl_parse_mask(const char *s, sa_family_t fam, npf_netmask_t *mask)
170 {
171 unsigned max_mask = NPF_MAX_NETMASK;
172 char *ep = NULL;
173 npf_addr_t addr;
174 uint8_t *ap;
175
176 assert(fam == AF_INET || fam == AF_INET6);
177 if (!s) {
178 /* No mask. */
179 *mask = NPF_NO_NETMASK;
180 return true;
181 }
182
183 errno = 0;
184 *mask = (npf_netmask_t)strtol(s, &ep, 0);
185 if (*ep == '\0' && s != ep && errno != ERANGE) {
186 /* Just a number -- CIDR notation. */
187 goto check;
188 }
189
190 /* Other characters: try to parse a full address. */
191 if (!npfctl_parse_fam_addr(s, &fam, &addr)) {
192 return false;
193 }
194
195 /* Convert the address to CIDR block number. */
196 ap = addr.word8 + (*mask / 8) - 1;
197 while (ap >= addr.word8) {
198 for (int j = 8; j > 0; j--) {
199 if (*ap & 1)
200 goto check;
201 *ap >>= 1;
202 (*mask)--;
203 if (*mask == 0)
204 goto check;
205 }
206 ap--;
207 }
208 *mask = NPF_NO_NETMASK;
209 return true;
210 check:
211 switch (fam) {
212 case AF_INET:
213 max_mask = 32;
214 break;
215 case AF_INET6:
216 max_mask = 128;
217 break;
218 }
219 return *mask <= max_mask;
220 }
221
222 /*
223 * npfctl_parse_fam_addr_mask: return address family, address and mask.
224 *
225 * => Mask is optional and can be NULL.
226 * => Returns true on success or false if unable to parse.
227 */
228 npfvar_t *
229 npfctl_parse_fam_addr_mask(const char *addr, const char *mask,
230 unsigned long *nummask)
231 {
232 fam_addr_mask_t fam;
233 char buf[32];
234
235 memset(&fam, 0, sizeof(fam));
236
237 if (!npfctl_parse_fam_addr(addr, &fam.fam_family, &fam.fam_addr))
238 return NULL;
239
240 /*
241 * Mask may be NULL. In such case, "no mask" value will be set.
242 */
243 if (nummask) {
244 /* Let npfctl_parse_mask() validate the number. */
245 snprintf(buf, sizeof(buf), "%lu", *nummask);
246 mask = buf;
247 }
248 if (!npfctl_parse_mask(mask, fam.fam_family, &fam.fam_mask)) {
249 return NULL;
250 }
251 return npfvar_create_element(NPFVAR_FAM, &fam, sizeof(fam));
252 }
253
254 npfvar_t *
255 npfctl_parse_table_id(const char *name)
256 {
257 u_int tid;
258
259 tid = npfctl_table_getid(name);
260 if (tid == (unsigned)-1) {
261 yyerror("table '%s' is not defined", name);
262 return NULL;
263 }
264 return npfvar_create_element(NPFVAR_TABLE, &tid, sizeof(u_int));
265 }
266
267 /*
268 * npfctl_parse_port_range: create a port-range variable. Note that the
269 * passed port numbers should be in host byte order.
270 */
271 npfvar_t *
272 npfctl_parse_port_range(in_port_t s, in_port_t e)
273 {
274 port_range_t pr;
275
276 pr.pr_start = htons(s);
277 pr.pr_end = htons(e);
278
279 return npfvar_create_element(NPFVAR_PORT_RANGE, &pr, sizeof(pr));
280 }
281
282 npfvar_t *
283 npfctl_parse_port_range_variable(const char *v, npfvar_t *vp)
284 {
285 size_t count = npfvar_get_count(vp);
286 npfvar_t *pvp = npfvar_create();
287 port_range_t *pr;
288
289 for (size_t i = 0; i < count; i++) {
290 int type = npfvar_get_type(vp, i);
291 void *data = npfvar_get_data(vp, type, i);
292 in_port_t p;
293
294 switch (type) {
295 case NPFVAR_IDENTIFIER:
296 case NPFVAR_STRING:
297 p = npfctl_portno(data);
298 npfvar_add_elements(pvp, npfctl_parse_port_range(p, p));
299 break;
300 case NPFVAR_PORT_RANGE:
301 pr = data;
302 npfvar_add_element(pvp, NPFVAR_PORT_RANGE, pr,
303 sizeof(*pr));
304 break;
305 case NPFVAR_NUM:
306 p = *(unsigned long *)data;
307 npfvar_add_elements(pvp, npfctl_parse_port_range(p, p));
308 break;
309 default:
310 if (v) {
311 yyerror("wrong variable '%s' type '%s' "
312 "for port range", v, npfvar_type(type));
313 } else {
314 yyerror("wrong element '%s' in the "
315 "inline list", npfvar_type(type));
316 }
317 npfvar_destroy(pvp);
318 return NULL;
319 }
320 }
321 return pvp;
322 }
323
324 npfvar_t *
325 npfctl_parse_ifnet(const char *ifname, const int family)
326 {
327 struct ifaddrs *ifa;
328 ifnet_addr_t ifna;
329 npfvar_t *vpa;
330
331 if (ifs_list == NULL && getifaddrs(&ifs_list) == -1) {
332 err(EXIT_FAILURE, "getifaddrs");
333 }
334
335 vpa = npfvar_create();
336 ifna.ifna_name = estrdup(ifname);
337 ifna.ifna_addrs = vpa;
338 ifna.ifna_index = npfctl_find_ifindex(ifname);
339 assert(ifna.ifna_index != 0);
340
341 for (ifa = ifs_list; ifa != NULL; ifa = ifa->ifa_next) {
342 fam_addr_mask_t fam;
343 struct sockaddr *sa;
344
345 if (strcmp(ifa->ifa_name, ifname) != 0)
346 continue;
347
348 if ((ifa->ifa_flags & IFF_UP) == 0)
349 warnx("interface '%s' is down", ifname);
350
351 sa = ifa->ifa_addr;
352 if (sa->sa_family != AF_INET && sa->sa_family != AF_INET6)
353 continue;
354 if (family != AF_UNSPEC && sa->sa_family != family)
355 continue;
356
357 memset(&fam, 0, sizeof(fam));
358 fam.fam_family = sa->sa_family;
359 fam.fam_ifindex = ifna.ifna_index;
360 fam.fam_mask = NPF_NO_NETMASK;
361
362 if (!npfctl_copy_address(sa->sa_family, &fam.fam_addr, sa))
363 goto out;
364
365 if (!npfvar_add_element(vpa, NPFVAR_FAM, &fam, sizeof(fam)))
366 goto out;
367 }
368 if (npfvar_get_count(vpa) == 0) {
369 yyerror("no addresses matched for interface '%s'", ifname);
370 goto out;
371 }
372
373 return npfvar_create_element(NPFVAR_INTERFACE, &ifna, sizeof(ifna));
374 out:
375 npfvar_destroy(ifna.ifna_addrs);
376 return NULL;
377 }
378
379 bool
380 npfctl_parse_cidr(char *cidr, fam_addr_mask_t *fam, int *alen)
381 {
382 char *mask, *p;
383
384 p = strchr(cidr, '\n');
385 if (p) {
386 *p = '\0';
387 }
388 mask = strchr(cidr, '/');
389 if (mask) {
390 *mask++ = '\0';
391 }
392
393 memset(fam, 0, sizeof(*fam));
394 if (!npfctl_parse_fam_addr(cidr, &fam->fam_family, &fam->fam_addr)) {
395 return false;
396 }
397 if (!npfctl_parse_mask(mask, fam->fam_family, &fam->fam_mask)) {
398 return false;
399 }
400 switch (fam->fam_family) {
401 case AF_INET:
402 *alen = sizeof(struct in_addr);
403 break;
404 case AF_INET6:
405 *alen = sizeof(struct in6_addr);
406 break;
407 default:
408 return false;
409 }
410 return true;
411 }
412
413 int
414 npfctl_protono(const char *proto)
415 {
416 struct protoent *pe;
417
418 pe = getprotobyname(proto);
419 if (pe == NULL) {
420 yyerror("unknown protocol '%s'", proto);
421 return -1;
422 }
423 return pe->p_proto;
424 }
425
426 /*
427 * npfctl_portno: convert port identifier (string) to a number.
428 *
429 * => Returns port number in host byte order.
430 */
431 in_port_t
432 npfctl_portno(const char *port)
433 {
434 struct addrinfo *ai, *rai;
435 in_port_t p = 0;
436 int e;
437
438 e = getaddrinfo(NULL, port, NULL, &rai);
439 if (e != 0) {
440 yyerror("invalid port name '%s' (%s)", port, gai_strerror(e));
441 return 0;
442 }
443
444 for (ai = rai; ai; ai = ai->ai_next) {
445 switch (ai->ai_family) {
446 case AF_INET: {
447 struct sockaddr_in *sin = (void *)ai->ai_addr;
448 p = sin->sin_port;
449 goto out;
450 }
451 case AF_INET6: {
452 struct sockaddr_in6 *sin6 = (void *)ai->ai_addr;
453 p = sin6->sin6_port;
454 goto out;
455 }
456 default:
457 break;
458 }
459 }
460 out:
461 freeaddrinfo(rai);
462 return ntohs(p);
463 }
464
465 npfvar_t *
466 npfctl_parse_tcpflag(const char *s)
467 {
468 uint8_t tfl = 0;
469
470 while (*s) {
471 switch (*s) {
472 case 'F': tfl |= TH_FIN; break;
473 case 'S': tfl |= TH_SYN; break;
474 case 'R': tfl |= TH_RST; break;
475 case 'P': tfl |= TH_PUSH; break;
476 case 'A': tfl |= TH_ACK; break;
477 case 'U': tfl |= TH_URG; break;
478 case 'E': tfl |= TH_ECE; break;
479 case 'W': tfl |= TH_CWR; break;
480 default:
481 yyerror("invalid flag '%c'", *s);
482 return NULL;
483 }
484 s++;
485 }
486 return npfvar_create_element(NPFVAR_TCPFLAG, &tfl, sizeof(tfl));
487 }
488
489 uint8_t
490 npfctl_icmptype(int proto, const char *type)
491 {
492 #ifdef __NetBSD__
493 uint8_t ul;
494
495 switch (proto) {
496 case IPPROTO_ICMP:
497 for (ul = 0; icmp_type[ul]; ul++)
498 if (strcmp(icmp_type[ul], type) == 0)
499 return ul;
500 break;
501 case IPPROTO_ICMPV6:
502 for (ul = 0; icmp6_type_err[ul]; ul++)
503 if (strcmp(icmp6_type_err[ul], type) == 0)
504 return ul;
505 for (ul = 0; icmp6_type_info[ul]; ul++)
506 if (strcmp(icmp6_type_info[ul], type) == 0)
507 return ul + 128;
508 break;
509 default:
510 assert(false);
511 }
512 #else
513 (void)proto;
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 #else
606 (void)proto;
607 #endif
608 yyerror("unknown code %s for icmp-type %d", code, type);
609 return ~0;
610 }
611
612 npfvar_t *
613 npfctl_parse_icmp(int proto __unused, int type, int code)
614 {
615 npfvar_t *vp = npfvar_create();
616
617 if (!npfvar_add_element(vp, NPFVAR_ICMP, &type, sizeof(type)))
618 goto out;
619
620 if (!npfvar_add_element(vp, NPFVAR_ICMP, &code, sizeof(code)))
621 goto out;
622
623 return vp;
624 out:
625 npfvar_destroy(vp);
626 return NULL;
627 }
628
629 /*
630 * npfctl_npt66_calcadj: calculate the adjustment for NPTv6 as per RFC 6296.
631 */
632 uint16_t
633 npfctl_npt66_calcadj(npf_netmask_t len, const npf_addr_t *pref_in,
634 const npf_addr_t *pref_out)
635 {
636 const uint16_t *addr6_in = (const uint16_t *)pref_in;
637 const uint16_t *addr6_out = (const uint16_t *)pref_out;
638 unsigned i, remnant, wordmask, preflen = len >> 4;
639 uint32_t adj, isum = 0, osum = 0;
640
641 /*
642 * Extract the bits within a 16-bit word (when prefix length is
643 * not dividable by 16) and include them into the sum.
644 */
645 remnant = len - (preflen << 4);
646 wordmask = (1U << remnant) - 1;
647 assert(wordmask == 0 || (len % 16) != 0);
648
649 /* Inner prefix - sum and fold. */
650 for (i = 0; i < preflen; i++) {
651 isum += addr6_in[i];
652 }
653 isum += addr6_in[i] & wordmask;
654 while (isum >> 16) {
655 isum = (isum >> 16) + (isum & 0xffff);
656 }
657
658 /* Outer prefix - sum and fold. */
659 for (i = 0; i < preflen; i++) {
660 osum += addr6_out[i];
661 }
662 osum += addr6_out[i] & wordmask;
663 while (osum >> 16) {
664 osum = (osum >> 16) + (osum & 0xffff);
665 }
666
667 /* Calculate 1's complement difference. */
668 adj = isum + ~osum;
669 while (adj >> 16) {
670 adj = (adj >> 16) + (adj & 0xffff);
671 }
672 return (uint16_t)adj;
673 }
674