npf_data.c revision 1.3 1 /* $NetBSD: npf_data.c,v 1.3 2010/09/16 04:53:27 rmind Exp $ */
2
3 /*-
4 * Copyright (c) 2009-2010 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 * NPF proplib(9) dictionary producer.
31 *
32 * XXX: Needs some clean-up.
33 */
34
35 #include <sys/types.h>
36 #include <sys/socket.h>
37 #include <sys/ioctl.h>
38 #include <net/if.h>
39 #include <netinet/tcp.h>
40
41 #include <arpa/inet.h>
42 #include <prop/proplib.h>
43
44 #include <stdlib.h>
45 #include <string.h>
46 #include <unistd.h>
47 #include <ctype.h>
48 #include <err.h>
49 #include <ifaddrs.h>
50 #include <netdb.h>
51 #include <assert.h>
52
53 #include "npfctl.h"
54
55 static struct ifaddrs * ifs_list = NULL;
56
57 static prop_dictionary_t npf_dict, settings_dict;
58 static prop_array_t nat_arr, tables_arr, rules_arr;
59
60 static pri_t gr_prio_counter = 1;
61 static pri_t rl_prio_counter = 1;
62 static pri_t nat_prio_counter = 1;
63
64 void
65 npfctl_init_data(void)
66 {
67 prop_number_t ver;
68
69 if (getifaddrs(&ifs_list) == -1)
70 err(EXIT_FAILURE, "getifaddrs");
71
72 npf_dict = prop_dictionary_create();
73
74 ver = prop_number_create_integer(NPF_VERSION);
75 prop_dictionary_set(npf_dict, "version", ver);
76
77 nat_arr = prop_array_create();
78 prop_dictionary_set(npf_dict, "translation", nat_arr);
79
80 settings_dict = prop_dictionary_create();
81 prop_dictionary_set(npf_dict, "settings", settings_dict);
82
83 tables_arr = prop_array_create();
84 prop_dictionary_set(npf_dict, "tables", tables_arr);
85
86 rules_arr = prop_array_create();
87 prop_dictionary_set(npf_dict, "rules", rules_arr);
88 }
89
90 int
91 npfctl_ioctl_send(int fd)
92 {
93 int ret = 0, errval;
94
95 #ifdef DEBUG
96 prop_dictionary_externalize_to_file(npf_dict, "./npf.plist");
97 #else
98 errval = prop_dictionary_send_ioctl(npf_dict, fd, IOC_NPF_RELOAD);
99 if (errval) {
100 errx(EXIT_FAILURE, "npf_ioctl_send: %s\n", strerror(errval));
101 ret = -1;
102 }
103 #endif
104 prop_object_release(npf_dict);
105 return ret;
106 }
107
108 /*
109 * Helper routines:
110 *
111 * npfctl_getif() - get interface addresses and index number from name.
112 * npfctl_parse_v4mask() - parse address/mask integers from CIDR block.
113 * npfctl_parse_port() - parse port number (which may be a service name).
114 * npfctl_parse_tcpfl() - parse TCP flags.
115 */
116
117 static struct ifaddrs *
118 npfctl_getif(char *ifname, unsigned int *if_idx)
119 {
120 struct ifaddrs *ifent;
121 struct sockaddr_in *sin;
122
123 for (ifent = ifs_list; ifent != NULL; ifent = ifent->ifa_next) {
124 sin = (struct sockaddr_in *)ifent->ifa_addr;
125
126 if (sin->sin_family != AF_INET)
127 continue;
128 if (strcmp(ifent->ifa_name, ifname) == 0)
129 break;
130 }
131 if (ifent) {
132 *if_idx = if_nametoindex(ifname);
133 }
134 return ifent;
135 }
136
137 bool
138 npfctl_parse_v4mask(char *ostr, in_addr_t *addr, in_addr_t *mask)
139 {
140 char *str = xstrdup(ostr);
141 char *p = strchr(str, '/');
142 u_int bits;
143 bool ret;
144
145 /* In network byte order. */
146 if (p) {
147 *p++ = '\0';
148 bits = (u_int)atoi(p);
149 *mask = bits ? htonl(0xffffffff << (32 - bits)) : 0;
150 } else {
151 *mask = 0xffffffff;
152 }
153 ret = inet_aton(str, (struct in_addr *)addr) != 0;
154 free(str);
155 return ret;
156 }
157
158 static bool
159 npfctl_parse_port(char *ostr, bool *range, in_port_t *fport, in_port_t *tport)
160 {
161 char *str = xstrdup(ostr), *sep;
162
163 *range = false;
164 if ((sep = strchr(str, ':')) != NULL) {
165 /* Port range (only numeric). */
166 *range = true;
167 *sep = '\0';
168
169 } else if (isalpha((unsigned char)*str)) {
170 struct servent *se;
171
172 se = getservbyname(str, NULL);
173 if (se == NULL) {
174 free(str);
175 return false;
176 }
177 *fport = se->s_port;
178 } else {
179 *fport = htons(atoi(str));
180 }
181 *tport = sep ? htons(atoi(sep + 1)) : *fport;
182 free(str);
183 return true;
184 }
185
186 static void
187 npfctl_parse_cidr(char *str, in_addr_t *addr, in_addr_t *mask)
188 {
189
190 if (isalpha((unsigned char)*str)) {
191 struct ifaddrs *ifa;
192 struct sockaddr_in *sin;
193 u_int idx;
194
195 if ((ifa = npfctl_getif(str, &idx)) == NULL) {
196 errx(EXIT_FAILURE, "invalid interface '%s'", str);
197 }
198 /* Interface address. */
199 sin = (struct sockaddr_in *)ifa->ifa_addr;
200 *addr = sin->sin_addr.s_addr;
201 *mask = 0xffffffff;
202
203 } else if (!npfctl_parse_v4mask(str, addr, mask)) {
204 errx(EXIT_FAILURE, "invalid CIDR '%s'\n", str);
205 }
206 }
207
208 static bool
209 npfctl_parse_tcpfl(char *s, uint8_t *tfl, uint8_t *tfl_mask)
210 {
211 uint8_t tcpfl = 0;
212 bool mask = false;
213
214 while (*s) {
215 switch (*s) {
216 case 'F': tcpfl |= TH_FIN; break;
217 case 'S': tcpfl |= TH_SYN; break;
218 case 'R': tcpfl |= TH_RST; break;
219 case 'P': tcpfl |= TH_PUSH; break;
220 case 'A': tcpfl |= TH_ACK; break;
221 case 'U': tcpfl |= TH_URG; break;
222 case 'E': tcpfl |= TH_ECE; break;
223 case 'W': tcpfl |= TH_CWR; break;
224 case '/':
225 *s = '\0';
226 *tfl = tcpfl;
227 tcpfl = 0;
228 mask = true;
229 break;
230 default:
231 return false;
232 }
233 s++;
234 }
235 if (!mask) {
236 *tfl = tcpfl;
237 }
238 *tfl_mask = tcpfl;
239 return true;
240 }
241
242 /*
243 * NPF table creation and construction routines.
244 */
245
246 prop_dictionary_t
247 npfctl_lookup_table(char *tidstr)
248 {
249 prop_dictionary_t tl;
250 prop_object_iterator_t it;
251 prop_object_t obj;
252 u_int tid;
253
254 if ((it = prop_array_iterator(tables_arr)) == NULL)
255 err(EXIT_FAILURE, "prop_array_iterator");
256
257 tid = atoi(tidstr);
258 while ((tl = prop_object_iterator_next(it)) != NULL) {
259 obj = prop_dictionary_get(tl, "id");
260 if (tid == prop_number_integer_value(obj))
261 break;
262 }
263 return tl;
264 }
265
266 prop_dictionary_t
267 npfctl_mk_table(void)
268 {
269 prop_dictionary_t tl;
270 prop_array_t tlist;
271
272 tl = prop_dictionary_create();
273 tlist = prop_array_create();
274 prop_dictionary_set(tl, "entries", tlist);
275
276 return tl;
277 }
278
279 void
280 npfctl_table_setup(prop_dictionary_t tl, char *idstr, char *typestr)
281 {
282 prop_number_t typenum;
283 unsigned int id;
284
285 id = atoi(idstr);
286 /* TODO: 1. check ID range 2. check if not a duplicate */
287 prop_dictionary_set(tl, "id", prop_number_create_integer(id));
288
289 if (strcmp(typestr, "hash")) {
290 typenum = prop_number_create_integer(NPF_TABLE_HASH);
291 } else if (strcmp(typestr, "tree")) {
292 typenum = prop_number_create_integer(NPF_TABLE_RBTREE);
293 } else {
294 errx(EXIT_FAILURE, "invalid table type '%s'\n", typestr);
295 }
296 prop_dictionary_set(tl, "type", typenum);
297 }
298
299 void
300 npfctl_construct_table(prop_dictionary_t tl, char *fname)
301 {
302 prop_dictionary_t entdict;
303 prop_array_t tblents;
304 char *buf;
305 FILE *fp;
306 size_t n;
307 int l;
308
309 tblents = prop_dictionary_get(tl, "entries");
310 assert(tblents != NULL);
311
312 fp = fopen(fname, "r");
313 if (fp == NULL) {
314 err(EXIT_FAILURE, "fopen");
315 }
316 l = 1;
317 buf = NULL;
318 while (getline(&buf, &n, fp) != -1) {
319 in_addr_t addr, mask;
320
321 if (*buf == '\n' || *buf == '#')
322 continue;
323
324 /* IPv4 CIDR: a.b.c.d/mask */
325 if (!npfctl_parse_v4mask(buf, &addr, &mask))
326 errx(EXIT_FAILURE, "invalid table entry at line %d", l);
327
328 /* Create and add table entry. */
329 entdict = prop_dictionary_create();
330 prop_dictionary_set(entdict, "addr",
331 prop_number_create_integer(addr));
332 prop_dictionary_set(entdict, "mask",
333 prop_number_create_integer(mask));
334 prop_array_add(tblents, entdict);
335 l++;
336 }
337 if (buf != NULL) {
338 free(buf);
339 }
340 }
341
342 void
343 npfctl_add_table(prop_dictionary_t tl)
344 {
345
346 prop_array_add(tables_arr, tl);
347 }
348
349 /*
350 * npfctl_mk_rule: create a rule (or group) dictionary.
351 *
352 * Note: group is a rule containing subrules. It has no n-code, however.
353 */
354 prop_dictionary_t
355 npfctl_mk_rule(bool group)
356 {
357 prop_dictionary_t rl;
358 prop_array_t subrl;
359 pri_t pri;
360
361 rl = prop_dictionary_create();
362 if (group) {
363 subrl = prop_array_create();
364 prop_dictionary_set(rl, "subrules", subrl);
365 /* Give new priority, reset rule priority counter. */
366 pri = gr_prio_counter++;
367 rl_prio_counter = 1;
368 } else {
369 pri = rl_prio_counter++;
370 }
371 prop_dictionary_set(rl, "priority",
372 prop_number_create_integer(pri));
373
374 return rl;
375 }
376
377 void
378 npfctl_add_rule(prop_dictionary_t rl, prop_dictionary_t parent)
379 {
380 prop_array_t rlset;
381
382 if (parent) {
383 rlset = prop_dictionary_get(parent, "subrules");
384 assert(rlset != NULL);
385 } else {
386 rlset = rules_arr;
387 }
388 prop_array_add(rlset, rl);
389 }
390
391 void
392 npfctl_rule_setattr(prop_dictionary_t rl, int attr, char *iface)
393 {
394 prop_number_t attrnum;
395
396 attrnum = prop_number_create_integer(attr);
397 prop_dictionary_set(rl, "attributes", attrnum);
398 if (iface) {
399 prop_number_t ifnum;
400 unsigned int if_idx;
401
402 if (npfctl_getif(iface, &if_idx) == NULL) {
403 errx(EXIT_FAILURE, "invalid interface '%s'", iface);
404 }
405 ifnum = prop_number_create_integer(if_idx);
406 prop_dictionary_set(rl, "interface", ifnum);
407 }
408 }
409
410 /*
411 * Main rule generation routines.
412 */
413
414 static void
415 npfctl_rulenc_v4cidr(void **nc, int nblocks[], var_t *dat, bool sd)
416 {
417 element_t *el = dat->v_elements;
418 int foff;
419
420 /* If table, generate a single table matching block. */
421 if (dat->v_type == VAR_TABLE) {
422 u_int tid = atoi(el->e_data);
423
424 nblocks[0]--;
425 foff = npfctl_failure_offset(nblocks);
426 npfctl_gennc_tbl(nc, foff, tid, sd);
427 return;
428 }
429
430 /* Generate v4 CIDR matching blocks. */
431 for (el = dat->v_elements; el != NULL; el = el->e_next) {
432 in_addr_t addr, mask;
433
434 npfctl_parse_cidr(el->e_data, &addr, &mask);
435
436 nblocks[1]--;
437 foff = npfctl_failure_offset(nblocks);
438 npfctl_gennc_v4cidr(nc, foff, addr, mask, sd);
439 }
440 }
441
442 static void
443 npfctl_rulenc_ports(void **nc, int nblocks[], var_t *dat, bool tcpudp, bool sd)
444 {
445 element_t *el = dat->v_elements;
446 int foff;
447
448 assert(dat->v_type != VAR_TABLE);
449
450 /* Generate TCP/UDP port matching blocks. */
451 for (el = dat->v_elements; el != NULL; el = el->e_next) {
452 in_port_t fport, tport;
453 bool range;
454
455 if (!npfctl_parse_port(el->e_data, &range, &fport, &tport)) {
456 errx(EXIT_FAILURE, "invalid service '%s'", el->e_data);
457 }
458 nblocks[0]--;
459 foff = npfctl_failure_offset(nblocks);
460 npfctl_gennc_ports(nc, foff, fport, tport, tcpudp, sd);
461 }
462 }
463
464 static void
465 npfctl_rulenc_block(void **nc, int nblocks[], var_t *cidr, var_t *ports,
466 bool both, bool tcpudp, bool sd)
467 {
468
469 npfctl_rulenc_v4cidr(nc, nblocks, cidr, sd);
470 if (ports == NULL) {
471 return;
472 }
473 npfctl_rulenc_ports(nc, nblocks, ports, tcpudp, sd);
474 if (!both) {
475 return;
476 }
477 npfctl_rulenc_ports(nc, nblocks, ports, !tcpudp, sd);
478 }
479
480 void
481 npfctl_rule_protodata(prop_dictionary_t rl, char *proto, char *tcp_flags,
482 int icmp_type, int icmp_code,
483 var_t *from, var_t *fports, var_t *to, var_t *tports)
484 {
485 prop_data_t ncdata;
486 bool icmp, tcpudp, both;
487 int foff, nblocks[3] = { 0, 0, 0 };
488 void *ncptr, *nc;
489 size_t sz;
490
491 /*
492 * Default: both TCP and UDP.
493 */
494 icmp = false;
495 tcpudp = true;
496 both = false;
497 if (proto == NULL) {
498 goto skip_proto;
499 }
500
501 if (strcmp(proto, "icmp") == 0) {
502 /* ICMP case. */
503 fports = NULL;
504 tports = NULL;
505 icmp = true;
506
507 } else if (strcmp(proto, "tcp") == 0) {
508 /* Just TCP. */
509 tcpudp = true;
510
511 } else if (strcmp(proto, "udp") == 0) {
512 /* Just UDP. */
513 tcpudp = false;
514
515 } else {
516 /* Default. */
517 }
518 skip_proto:
519 if (icmp_type != -1) {
520 assert(tcp_flags == NULL);
521 icmp = true;
522 nblocks[2] += 1;
523 }
524 if (tcpudp && tcp_flags) {
525 assert(icmp_type == -1 && icmp_code == -1);
526 nblocks[2] += 1;
527 }
528
529 /* Calculate how blocks to determince n-code. */
530 if (from && from->v_count) {
531 if (from->v_type == VAR_TABLE)
532 nblocks[0] += 1;
533 else
534 nblocks[1] += from->v_count;
535 if (fports && fports->v_count)
536 nblocks[0] += fports->v_count * (both ? 2 : 1);
537 }
538 if (to && to->v_count) {
539 if (to->v_type == VAR_TABLE)
540 nblocks[0] += 1;
541 else
542 nblocks[1] += to->v_count;
543 if (tports && tports->v_count)
544 nblocks[0] += tports->v_count * (both ? 2 : 1);
545 }
546
547 /* Any n-code to generate? */
548 if ((nblocks[0] + nblocks[1] + nblocks[2]) == 0) {
549 /* Done, if none. */
550 return;
551 }
552
553 /* Allocate memory for the n-code. */
554 sz = npfctl_calc_ncsize(nblocks);
555 ncptr = malloc(sz);
556 if (ncptr == NULL) {
557 perror("malloc");
558 exit(EXIT_FAILURE);
559 }
560 nc = ncptr;
561
562 /*
563 * Generate v4 CIDR matching blocks and TCP/UDP port matching.
564 */
565 if (from) {
566 npfctl_rulenc_block(&nc, nblocks, from, fports,
567 both, tcpudp, true);
568 }
569 if (to) {
570 npfctl_rulenc_block(&nc, nblocks, to, tports,
571 both, tcpudp, false);
572 }
573
574 if (icmp) {
575 /*
576 * ICMP case.
577 */
578 nblocks[2]--;
579 foff = npfctl_failure_offset(nblocks);
580 npfctl_gennc_icmp(&nc, foff, icmp_type, icmp_code);
581
582 } else if (tcpudp && tcp_flags) {
583 /*
584 * TCP case, flags.
585 */
586 uint8_t tfl = 0, tfl_mask;
587
588 nblocks[2]--;
589 foff = npfctl_failure_offset(nblocks);
590 if (!npfctl_parse_tcpfl(tcp_flags, &tfl, &tfl_mask)) {
591 errx(EXIT_FAILURE, "invalid TCP flags '%s'", tcp_flags);
592 }
593 npfctl_gennc_tcpfl(&nc, foff, tfl, tfl_mask);
594 }
595 npfctl_gennc_complete(&nc);
596
597 if ((uintptr_t)nc - (uintptr_t)ncptr != sz) {
598 errx(EXIT_FAILURE, "n-code size got wrong (%tu != %zu)",
599 (uintptr_t)nc - (uintptr_t)ncptr, sz);
600 }
601
602 #ifdef DEBUG
603 uint32_t *op = ncptr;
604 size_t n = sz;
605 do {
606 DPRINTF(("\t> |0x%02x|\n", (u_int)*op));
607 op++;
608 n -= sizeof(*op);
609 } while (n);
610 #endif
611
612 /* Create a final memory block of data, ready to send. */
613 ncdata = prop_data_create_data(ncptr, sz);
614 if (ncdata == NULL) {
615 perror("prop_data_create_data");
616 exit(EXIT_FAILURE);
617 }
618 prop_dictionary_set(rl, "ncode", ncdata);
619 free(ncptr);
620 }
621
622 /*
623 * NAT policy construction routines.
624 */
625
626 prop_dictionary_t
627 npfctl_mk_nat(void)
628 {
629 prop_dictionary_t rl;
630 pri_t pri;
631
632 /* NAT policy is rule with extra info. */
633 rl = prop_dictionary_create();
634 pri = nat_prio_counter++;
635 prop_dictionary_set(rl, "priority",
636 prop_number_create_integer(pri));
637 return rl;
638 }
639
640 void
641 npfctl_add_nat(prop_dictionary_t nat)
642 {
643 prop_array_add(nat_arr, nat);
644 }
645
646 void
647 npfctl_nat_setup(prop_dictionary_t rl, int type, int flags,
648 char *iface, char *taddr, char *rport)
649 {
650 int attr = NPF_RULE_PASS | NPF_RULE_FINAL;
651 in_addr_t addr, mask;
652
653 /* Translation type and flags. */
654 prop_dictionary_set(rl, "type",
655 prop_number_create_integer(type));
656 prop_dictionary_set(rl, "flags",
657 prop_number_create_integer(flags));
658
659 /* Interface and attributes. */
660 attr |= (type == NPF_NATOUT) ? NPF_RULE_OUT : NPF_RULE_IN;
661 npfctl_rule_setattr(rl, attr, iface);
662
663 /* Translation IP, XXX should be no mask. */
664 npfctl_parse_cidr(taddr, &addr, &mask);
665 prop_dictionary_set(rl, "translation_ip",
666 prop_number_create_integer(addr));
667
668 /* Translation port (for redirect case). */
669 if (rport) {
670 in_port_t port;
671 bool range;
672
673 if (!npfctl_parse_port(rport, &range, &port, &port)) {
674 errx(EXIT_FAILURE, "invalid service '%s'", rport);
675 }
676 if (range) {
677 errx(EXIT_FAILURE, "range is not supported for 'rdr'");
678 }
679 prop_dictionary_set(rl, "translation_port",
680 prop_number_create_integer(port));
681 }
682 }
683