npf_build.c revision 1.12 1 /* $NetBSD: npf_build.c,v 1.12 2012/07/19 21:52:29 spz Exp $ */
2
3 /*-
4 * Copyright (c) 2011-2012 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * This material is based upon work partially supported by The
8 * NetBSD Foundation under a contract with Mindaugas Rasiukevicius.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 * POSSIBILITY OF SUCH DAMAGE.
30 */
31
32 /*
33 * npfctl(8) building of the configuration.
34 */
35
36 #include <sys/cdefs.h>
37 __RCSID("$NetBSD: npf_build.c,v 1.12 2012/07/19 21:52:29 spz Exp $");
38
39 #include <sys/types.h>
40 #include <sys/ioctl.h>
41
42 #include <stdlib.h>
43 #include <inttypes.h>
44 #include <string.h>
45 #include <err.h>
46
47 #include "npfctl.h"
48
49 static nl_config_t * npf_conf = NULL;
50 static nl_rule_t * current_group = NULL;
51 static bool npf_debug = false;
52 static bool defgroup_set = false;
53
54 void
55 npfctl_config_init(bool debug)
56 {
57
58 npf_conf = npf_config_create();
59 if (npf_conf == NULL) {
60 errx(EXIT_FAILURE, "npf_config_create failed");
61 }
62 npf_debug = debug;
63 }
64
65 int
66 npfctl_config_send(int fd)
67 {
68 int error;
69
70 if (!fd) {
71 const char *outconf = "/tmp/npf.plist";
72 _npf_config_setsubmit(npf_conf, outconf);
73 printf("\nSaving to %s\n", outconf);
74 }
75 if (!defgroup_set) {
76 errx(EXIT_FAILURE, "default group was not defined");
77 }
78 error = npf_config_submit(npf_conf, fd);
79 if (error) {
80 nl_error_t ne;
81 _npf_config_error(npf_conf, &ne);
82 npfctl_print_error(&ne);
83 }
84 npf_config_destroy(npf_conf);
85 return error;
86 }
87
88 bool
89 npfctl_table_exists_p(const char *id)
90 {
91 return npf_table_exists_p(npf_conf, atoi(id));
92 }
93
94 static in_port_t
95 npfctl_get_singleport(const npfvar_t *vp)
96 {
97 port_range_t *pr;
98 in_port_t *port;
99
100 if (npfvar_get_count(vp) > 1) {
101 yyerror("multiple ports are not valid");
102 }
103 pr = npfvar_get_data(vp, NPFVAR_PORT_RANGE, 0);
104 if (pr->pr_start != pr->pr_end) {
105 yyerror("port range is not valid");
106 }
107 port = &pr->pr_start;
108 return *port;
109 }
110
111 static fam_addr_mask_t *
112 npfctl_get_singlefam(const npfvar_t *vp)
113 {
114 if (npfvar_get_count(vp) > 1) {
115 yyerror("multiple addresses are not valid");
116 }
117 return npfvar_get_data(vp, NPFVAR_FAM, 0);
118 }
119
120 static bool
121 npfctl_build_fam(nc_ctx_t *nc, sa_family_t family,
122 fam_addr_mask_t *fam, int opts)
123 {
124 /*
125 * If family is specified, address does not match it and the
126 * address is extracted from the interface, then simply ignore.
127 * Otherwise, address of invalid family was passed manually.
128 */
129 if (family != AF_UNSPEC && family != fam->fam_family) {
130 if (!fam->fam_interface) {
131 yyerror("specified address is not of the required "
132 "family %d", family);
133 }
134 return false;
135 }
136
137 /*
138 * Optimise 0.0.0.0/0 case to be NOP. Otherwise, address with
139 * zero mask would never match and therefore is not valid.
140 */
141 if (fam->fam_mask == 0) {
142 npf_addr_t zero;
143
144 memset(&zero, 0, sizeof(npf_addr_t));
145 if (memcmp(&fam->fam_addr, &zero, sizeof(npf_addr_t))) {
146 yyerror("filter criterion would never match");
147 }
148 return false;
149 }
150
151 switch (fam->fam_family) {
152 case AF_INET:
153 npfctl_gennc_v4cidr(nc, opts,
154 &fam->fam_addr, fam->fam_mask);
155 break;
156 case AF_INET6:
157 npfctl_gennc_v6cidr(nc, opts,
158 &fam->fam_addr, fam->fam_mask);
159 break;
160 default:
161 yyerror("family %d is not supported", fam->fam_family);
162 }
163 return true;
164 }
165
166 static void
167 npfctl_build_vars(nc_ctx_t *nc, sa_family_t family, npfvar_t *vars, int opts)
168 {
169 const int type = npfvar_get_type(vars, 0);
170 size_t i;
171
172 npfctl_ncgen_group(nc);
173 for (i = 0; i < npfvar_get_count(vars); i++) {
174 void *data = npfvar_get_data(vars, type, i);
175 assert(data != NULL);
176
177 switch (type) {
178 case NPFVAR_FAM: {
179 fam_addr_mask_t *fam = data;
180 npfctl_build_fam(nc, family, fam, opts);
181 break;
182 }
183 case NPFVAR_PORT_RANGE: {
184 port_range_t *pr = data;
185 if (opts & NC_MATCH_TCP) {
186 npfctl_gennc_ports(nc, opts & ~NC_MATCH_UDP,
187 pr->pr_start, pr->pr_end);
188 }
189 if (opts & NC_MATCH_UDP) {
190 npfctl_gennc_ports(nc, opts & ~NC_MATCH_TCP,
191 pr->pr_start, pr->pr_end);
192 }
193 break;
194 }
195 case NPFVAR_TABLE: {
196 u_int tid = atoi(data);
197 npfctl_gennc_tbl(nc, opts, tid);
198 break;
199 }
200 default:
201 assert(false);
202 }
203 }
204 npfctl_ncgen_endgroup(nc);
205 }
206
207 static int
208 npfctl_build_proto(nc_ctx_t *nc, sa_family_t family,
209 const opt_proto_t *op, bool nof, bool nop)
210 {
211 const npfvar_t *popts = op->op_opts;
212 const int proto = op->op_proto;
213 int pflag = 0;
214
215 switch (proto) {
216 case IPPROTO_TCP:
217 pflag = NC_MATCH_TCP;
218 if (!popts) {
219 break;
220 }
221 assert(npfvar_get_count(popts) == 2);
222
223 /* Build TCP flags block (optional). */
224 uint8_t *tf, *tf_mask;
225
226 tf = npfvar_get_data(popts, NPFVAR_TCPFLAG, 0);
227 tf_mask = npfvar_get_data(popts, NPFVAR_TCPFLAG, 1);
228 npfctl_gennc_tcpfl(nc, *tf, *tf_mask);
229 nop = false;
230 break;
231 case IPPROTO_UDP:
232 pflag = NC_MATCH_UDP;
233 break;
234 case IPPROTO_ICMP:
235 /*
236 * Build ICMP block.
237 */
238 if (!nop) {
239 goto invop;
240 }
241 assert(npfvar_get_count(popts) == 2);
242
243 int *icmp_type, *icmp_code;
244 icmp_type = npfvar_get_data(popts, NPFVAR_ICMP, 0);
245 icmp_code = npfvar_get_data(popts, NPFVAR_ICMP, 1);
246 npfctl_gennc_icmp(nc, *icmp_type, *icmp_code);
247 nop = false;
248 break;
249 case IPPROTO_ICMPV6:
250 /*
251 * Build ICMP block.
252 */
253 if (!nop) {
254 goto invop;
255 }
256 assert(npfvar_get_count(popts) == 2);
257
258 int *icmp6_type, *icmp6_code;
259 icmp6_type = npfvar_get_data(popts, NPFVAR_ICMP6, 0);
260 icmp6_code = npfvar_get_data(popts, NPFVAR_ICMP6, 1);
261 npfctl_gennc_icmp6(nc, *icmp6_type, *icmp6_code);
262 nop = false;
263 break;
264 case -1:
265 pflag = NC_MATCH_TCP | NC_MATCH_UDP;
266 nop = false;
267 break;
268 default:
269 /*
270 * No filter options are supported for other protcols.
271 */
272 if (nof && nop) {
273 break;
274 }
275 invop:
276 yyerror("invalid filter options for protocol %d", proto);
277 }
278
279 /*
280 * Build the protocol block, unless other blocks will implicitly
281 * perform the family/protocol checks for us.
282 */
283 if ((family != AF_UNSPEC && nof) || (proto != -1 && nop)) {
284 uint8_t addrlen;
285
286 switch (family) {
287 case AF_INET:
288 addrlen = sizeof(struct in_addr);
289 break;
290 case AF_INET6:
291 addrlen = sizeof(struct in6_addr);
292 break;
293 default:
294 addrlen = 0;
295 }
296 npfctl_gennc_proto(nc, nof ? addrlen : 0, nop ? proto : 0xff);
297 }
298 return pflag;
299 }
300
301 static bool
302 npfctl_build_ncode(nl_rule_t *rl, sa_family_t family, const opt_proto_t *op,
303 const filt_opts_t *fopts, bool invert)
304 {
305 const addr_port_t *apfrom = &fopts->fo_from;
306 const addr_port_t *apto = &fopts->fo_to;
307 const int proto = op->op_proto;
308 bool nof, nop;
309 nc_ctx_t *nc;
310 void *code;
311 size_t len;
312
313 /*
314 * If none specified, no n-code.
315 */
316 nof = !apfrom->ap_netaddr && !apto->ap_netaddr;
317 nop = !apfrom->ap_portrange && !apto->ap_portrange;
318 if (family == AF_UNSPEC && proto == -1 && !op->op_opts && nof && nop)
319 return false;
320
321 int srcflag = NC_MATCH_SRC;
322 int dstflag = NC_MATCH_DST;
323
324 if (invert) {
325 srcflag = NC_MATCH_DST;
326 dstflag = NC_MATCH_SRC;
327 }
328
329 nc = npfctl_ncgen_create();
330
331 /* Build layer 4 protocol blocks. */
332 int pflag = npfctl_build_proto(nc, family, op, nof, nop);
333
334 /* Build IP address blocks. */
335 npfctl_build_vars(nc, family, apfrom->ap_netaddr, srcflag);
336 npfctl_build_vars(nc, family, apto->ap_netaddr, dstflag);
337
338 /* Build port-range blocks. */
339 npfctl_build_vars(nc, family, apfrom->ap_portrange, srcflag | pflag);
340 npfctl_build_vars(nc, family, apto->ap_portrange, dstflag | pflag);
341
342 /*
343 * Complete n-code (destroys the context) and pass to the rule.
344 */
345 code = npfctl_ncgen_complete(nc, &len);
346 if (npf_debug) {
347 extern int yylineno;
348 printf("RULE AT LINE %d\n", yylineno);
349 npfctl_ncgen_print(code, len);
350 }
351 assert(code && len > 0);
352
353 if (npf_rule_setcode(rl, NPF_CODE_NCODE, code, len) == -1) {
354 errx(EXIT_FAILURE, "npf_rule_setcode failed");
355 }
356 free(code);
357 return true;
358 }
359
360 static void
361 npfctl_build_rpcall(nl_rproc_t *rp, const char *name, npfvar_t *args)
362 {
363 /*
364 * XXX/TODO: Hardcoded for the first release. However,
365 * rule procedures will become fully dynamic modules.
366 */
367
368 bool log = false, norm = false;
369 bool rnd = false, no_df = false;
370 int minttl = 0, maxmss = 0;
371
372 if (strcmp(name, "log") == 0) {
373 log = true;
374 } else if (strcmp(name, "normalise") == 0) {
375 norm = true;
376 } else {
377 yyerror("unknown rule procedure '%s'", name);
378 }
379
380 for (size_t i = 0; i < npfvar_get_count(args); i++) {
381 module_arg_t *arg;
382 const char *aval;
383
384 arg = npfvar_get_data(args, NPFVAR_MODULE_ARG, i);
385 aval = arg->ma_name;
386
387 if (log) {
388 u_int if_idx = npfctl_find_ifindex(aval);
389 if (!if_idx) {
390 yyerror("unknown interface '%s'", aval);
391 }
392 _npf_rproc_setlog(rp, if_idx);
393 return;
394 }
395
396 const int type = npfvar_get_type(arg->ma_opts, 0);
397 if (type != -1 && type != NPFVAR_NUM) {
398 yyerror("option '%s' is not numeric", aval);
399 }
400 unsigned long *opt;
401
402 if (strcmp(aval, "random-id") == 0) {
403 rnd = true;
404 } else if (strcmp(aval, "min-ttl") == 0) {
405 opt = npfvar_get_data(arg->ma_opts, NPFVAR_NUM, 0);
406 minttl = *opt;
407 } else if (strcmp(aval, "max-mss") == 0) {
408 opt = npfvar_get_data(arg->ma_opts, NPFVAR_NUM, 0);
409 maxmss = *opt;
410 } else if (strcmp(aval, "no-df") == 0) {
411 no_df = true;
412 } else {
413 yyerror("unknown argument '%s'", aval);
414 }
415 }
416 assert(norm == true);
417 _npf_rproc_setnorm(rp, rnd, no_df, minttl, maxmss);
418 }
419
420 /*
421 * npfctl_build_rproc: create and insert a rule procedure.
422 */
423 void
424 npfctl_build_rproc(const char *name, npfvar_t *procs)
425 {
426 nl_rproc_t *rp;
427 size_t i;
428
429 rp = npf_rproc_create(name);
430 if (rp == NULL) {
431 errx(EXIT_FAILURE, "npf_rproc_create failed");
432 }
433 npf_rproc_insert(npf_conf, rp);
434
435 for (i = 0; i < npfvar_get_count(procs); i++) {
436 proc_op_t *po = npfvar_get_data(procs, NPFVAR_PROC_OP, i);
437 npfctl_build_rpcall(rp, po->po_name, po->po_opts);
438 }
439 }
440
441 /*
442 * npfctl_build_group: create a group, insert into the global ruleset
443 * and update the current group pointer.
444 */
445 void
446 npfctl_build_group(const char *name, int attr, u_int if_idx)
447 {
448 const int attr_di = (NPF_RULE_IN | NPF_RULE_OUT);
449 nl_rule_t *rl;
450
451 if (attr & NPF_RULE_DEFAULT) {
452 if (defgroup_set) {
453 yyerror("multiple default groups are not valid");
454 }
455 defgroup_set = true;
456 attr |= attr_di;
457
458 } else if ((attr & attr_di) == 0) {
459 attr |= attr_di;
460 }
461
462 rl = npf_rule_create(name, attr | NPF_RULE_FINAL, if_idx);
463 npf_rule_insert(npf_conf, NULL, rl, NPF_PRI_NEXT);
464 current_group = rl;
465 }
466
467 /*
468 * npfctl_build_rule: create a rule, build n-code from filter options,
469 * if any, and insert into the ruleset of current group.
470 */
471 void
472 npfctl_build_rule(int attr, u_int if_idx, sa_family_t family,
473 const opt_proto_t *op, const filt_opts_t *fopts, const char *rproc)
474 {
475 nl_rule_t *rl;
476
477 rl = npf_rule_create(NULL, attr, if_idx);
478 npfctl_build_ncode(rl, family, op, fopts, false);
479 if (rproc && npf_rule_setproc(npf_conf, rl, rproc) != 0) {
480 yyerror("rule procedure '%s' is not defined", rproc);
481 }
482 assert(current_group != NULL);
483 npf_rule_insert(npf_conf, current_group, rl, NPF_PRI_NEXT);
484 }
485
486 /*
487 * npfctl_build_nat: create a NAT policy of a specified type with a
488 * given filter options.
489 */
490 void
491 npfctl_build_nat(int sd, int type, u_int if_idx, const addr_port_t *ap1,
492 const addr_port_t *ap2, const filt_opts_t *fopts)
493 {
494 const opt_proto_t op = { .op_proto = -1, .op_opts = NULL };
495 fam_addr_mask_t *am1 = NULL, *am2 = NULL;
496 filt_opts_t imfopts;
497 sa_family_t family;
498 nl_nat_t *nat;
499
500 if (sd == NPFCTL_NAT_STATIC) {
501 yyerror("static NAT is not yet supported");
502 }
503 assert(sd == NPFCTL_NAT_DYNAMIC);
504 assert(if_idx != 0);
505
506 family = AF_INET;
507
508 if (type & NPF_NATIN) {
509 if (!ap1->ap_netaddr) {
510 yyerror("inbound network segment is not specified");
511 }
512 am1 = npfctl_get_singlefam(ap1->ap_netaddr);
513 if (am1->fam_family != family) {
514 yyerror("IPv6 NAT is not supported");
515 }
516 assert(am1 != NULL);
517 }
518
519 if (type & NPF_NATOUT) {
520 if (!ap2->ap_netaddr) {
521 yyerror("outbound network segment is not specified");
522 }
523 am2 = npfctl_get_singlefam(ap2->ap_netaddr);
524 if (am2->fam_family != family) {
525 yyerror("IPv6 NAT is not supported");
526 }
527 assert(am2 != NULL);
528 }
529
530 /*
531 * If filter criteria is not specified explicitly, apply implicit
532 * filtering according to the given network segements.
533 */
534 if (!fopts) {
535 memset(&imfopts, 0, sizeof(filt_opts_t));
536 if (type & NPF_NATOUT) {
537 memcpy(&imfopts.fo_from, ap1, sizeof(addr_port_t));
538 }
539 if (type & NPF_NATIN) {
540 memcpy(&imfopts.fo_to, ap2, sizeof(addr_port_t));
541 }
542 fopts = &imfopts;
543 }
544
545 switch (type) {
546 case NPF_NATIN:
547 assert(am1 != NULL);
548 /*
549 * Redirection: an inbound NAT with a specific port.
550 */
551 if (!ap1->ap_portrange) {
552 yyerror("inbound port is not specified");
553 }
554 in_port_t port = npfctl_get_singleport(ap1->ap_portrange);
555 nat = npf_nat_create(NPF_NATIN, NPF_NAT_PORTS,
556 if_idx, &am1->fam_addr, am1->fam_family, port);
557 break;
558
559 case (NPF_NATIN | NPF_NATOUT):
560 assert(am1 != NULL);
561 /*
562 * Bi-directional NAT: a combination of inbound NAT and
563 * outbound NAT policies. Note that the translation address
564 * is local IP and filter criteria is inverted accordingly.
565 */
566 nat = npf_nat_create(NPF_NATIN, 0, if_idx,
567 &am1->fam_addr, am1->fam_family, 0);
568 npfctl_build_ncode(nat, family, &op, fopts, true);
569 npf_nat_insert(npf_conf, nat, NPF_PRI_NEXT);
570 /* FALLTHROUGH */
571
572 case NPF_NATOUT:
573 assert(am2 != NULL);
574 /*
575 * Traditional NAPT: an outbound NAT policy with port.
576 * If this is another half for bi-directional NAT, then
577 * no port translation with mapping.
578 */
579 nat = npf_nat_create(NPF_NATOUT, type == NPF_NATOUT ?
580 (NPF_NAT_PORTS | NPF_NAT_PORTMAP) : 0,
581 if_idx, &am2->fam_addr, am2->fam_family, 0);
582 break;
583
584 default:
585 assert(false);
586 }
587 npfctl_build_ncode(nat, family, &op, fopts, false);
588 npf_nat_insert(npf_conf, nat, NPF_PRI_NEXT);
589 }
590
591 /*
592 * npfctl_fill_table: fill NPF table with entries from a specified file.
593 */
594 static void
595 npfctl_fill_table(nl_table_t *tl, u_int type, const char *fname)
596 {
597 char *buf = NULL;
598 int l = 0;
599 FILE *fp;
600 size_t n;
601
602 fp = fopen(fname, "r");
603 if (fp == NULL) {
604 err(EXIT_FAILURE, "open '%s'", fname);
605 }
606 while (l++, getline(&buf, &n, fp) != -1) {
607 fam_addr_mask_t fam;
608 int alen;
609
610 if (*buf == '\n' || *buf == '#') {
611 continue;
612 }
613
614 if (!npfctl_parse_cidr(buf, &fam, &alen)) {
615 errx(EXIT_FAILURE,
616 "%s:%d: invalid table entry", fname, l);
617 }
618 if (type == NPF_TABLE_HASH && fam.fam_mask != NPF_NO_NETMASK) {
619 errx(EXIT_FAILURE,
620 "%s:%d: mask used with the hash table", fname, l);
621 }
622
623 /* Create and add a table entry. */
624 npf_table_add_entry(tl, alen, &fam.fam_addr, fam.fam_mask);
625 }
626 if (buf != NULL) {
627 free(buf);
628 }
629 }
630
631 /*
632 * npfctl_build_table: create an NPF table, add to the configuration and,
633 * if required, fill with contents from a file.
634 */
635 void
636 npfctl_build_table(const char *tid, u_int type, const char *fname)
637 {
638 nl_table_t *tl;
639 u_int id;
640
641 id = atoi(tid);
642 tl = npf_table_create(id, type);
643 assert(tl != NULL);
644
645 if (npf_table_insert(npf_conf, tl)) {
646 errx(EXIT_FAILURE, "table '%d' is already defined\n", id);
647 }
648
649 if (fname) {
650 npfctl_fill_table(tl, type, fname);
651 }
652 }
653