npf_build.c revision 1.4.2.4 1 /* $NetBSD: npf_build.c,v 1.4.2.4 2012/07/16 22:13:28 riz 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.4.2.4 2012/07/16 22:13:28 riz 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 -1:
250 pflag = NC_MATCH_TCP | NC_MATCH_UDP;
251 nop = false;
252 break;
253 default:
254 /*
255 * No filter options are supported for other protcols.
256 */
257 if (nof && nop) {
258 break;
259 }
260 invop:
261 yyerror("invalid filter options for protocol %d", proto);
262 }
263
264 /*
265 * Build the protocol block, unless other blocks will implicitly
266 * perform the family/protocol checks for us.
267 */
268 if ((family != AF_UNSPEC && nof) || (proto != -1 && nop)) {
269 uint8_t addrlen;
270
271 switch (family) {
272 case AF_INET:
273 addrlen = sizeof(struct in_addr);
274 break;
275 case AF_INET6:
276 addrlen = sizeof(struct in6_addr);
277 break;
278 default:
279 addrlen = 0;
280 }
281 npfctl_gennc_proto(nc, nof ? addrlen : 0, nop ? proto : 0xff);
282 }
283 return pflag;
284 }
285
286 static bool
287 npfctl_build_ncode(nl_rule_t *rl, sa_family_t family, const opt_proto_t *op,
288 const filt_opts_t *fopts, bool invert)
289 {
290 const addr_port_t *apfrom = &fopts->fo_from;
291 const addr_port_t *apto = &fopts->fo_to;
292 const int proto = op->op_proto;
293 bool nof, nop;
294 nc_ctx_t *nc;
295 void *code;
296 size_t len;
297
298 /*
299 * If none specified, no n-code.
300 */
301 nof = !apfrom->ap_netaddr && !apto->ap_netaddr;
302 nop = !apfrom->ap_portrange && !apto->ap_portrange;
303 if (family == AF_UNSPEC && proto == -1 && !op->op_opts && nof && nop)
304 return false;
305
306 int srcflag = NC_MATCH_SRC;
307 int dstflag = NC_MATCH_DST;
308
309 if (invert) {
310 srcflag = NC_MATCH_DST;
311 dstflag = NC_MATCH_SRC;
312 }
313
314 nc = npfctl_ncgen_create();
315
316 /* Build layer 4 protocol blocks. */
317 int pflag = npfctl_build_proto(nc, family, op, nof, nop);
318
319 /* Build IP address blocks. */
320 npfctl_build_vars(nc, family, apfrom->ap_netaddr, srcflag);
321 npfctl_build_vars(nc, family, apto->ap_netaddr, dstflag);
322
323 /* Build port-range blocks. */
324 npfctl_build_vars(nc, family, apfrom->ap_portrange, srcflag | pflag);
325 npfctl_build_vars(nc, family, apto->ap_portrange, dstflag | pflag);
326
327 /*
328 * Complete n-code (destroys the context) and pass to the rule.
329 */
330 code = npfctl_ncgen_complete(nc, &len);
331 if (npf_debug) {
332 extern int yylineno;
333 printf("RULE AT LINE %d\n", yylineno);
334 npfctl_ncgen_print(code, len);
335 }
336 assert(code && len > 0);
337
338 if (npf_rule_setcode(rl, NPF_CODE_NCODE, code, len) == -1) {
339 errx(EXIT_FAILURE, "npf_rule_setcode failed");
340 }
341 free(code);
342 return true;
343 }
344
345 static void
346 npfctl_build_rpcall(nl_rproc_t *rp, const char *name, npfvar_t *args)
347 {
348 /*
349 * XXX/TODO: Hardcoded for the first release. However,
350 * rule procedures will become fully dynamic modules.
351 */
352
353 bool log = false, norm = false;
354 bool rnd = false, no_df = false;
355 int minttl = 0, maxmss = 0;
356
357 if (strcmp(name, "log") == 0) {
358 log = true;
359 } else if (strcmp(name, "normalise") == 0) {
360 norm = true;
361 } else {
362 yyerror("unknown rule procedure '%s'", name);
363 }
364
365 for (size_t i = 0; i < npfvar_get_count(args); i++) {
366 module_arg_t *arg;
367 const char *aval;
368
369 arg = npfvar_get_data(args, NPFVAR_MODULE_ARG, i);
370 aval = arg->ma_name;
371
372 if (log) {
373 u_int if_idx = npfctl_find_ifindex(aval);
374 if (!if_idx) {
375 yyerror("unknown interface '%s'", aval);
376 }
377 _npf_rproc_setlog(rp, if_idx);
378 return;
379 }
380
381 const int type = npfvar_get_type(arg->ma_opts, 0);
382 if (type != -1 && type != NPFVAR_NUM) {
383 yyerror("option '%s' is not numeric", aval);
384 }
385 unsigned long *opt;
386
387 if (strcmp(aval, "random-id") == 0) {
388 rnd = true;
389 } else if (strcmp(aval, "min-ttl") == 0) {
390 opt = npfvar_get_data(arg->ma_opts, NPFVAR_NUM, 0);
391 minttl = *opt;
392 } else if (strcmp(aval, "max-mss") == 0) {
393 opt = npfvar_get_data(arg->ma_opts, NPFVAR_NUM, 0);
394 maxmss = *opt;
395 } else if (strcmp(aval, "no-df") == 0) {
396 no_df = true;
397 } else {
398 yyerror("unknown argument '%s'", aval);
399 }
400 }
401 assert(norm == true);
402 _npf_rproc_setnorm(rp, rnd, no_df, minttl, maxmss);
403 }
404
405 /*
406 * npfctl_build_rproc: create and insert a rule procedure.
407 */
408 void
409 npfctl_build_rproc(const char *name, npfvar_t *procs)
410 {
411 nl_rproc_t *rp;
412 size_t i;
413
414 rp = npf_rproc_create(name);
415 if (rp == NULL) {
416 errx(EXIT_FAILURE, "npf_rproc_create failed");
417 }
418 npf_rproc_insert(npf_conf, rp);
419
420 for (i = 0; i < npfvar_get_count(procs); i++) {
421 proc_op_t *po = npfvar_get_data(procs, NPFVAR_PROC_OP, i);
422 npfctl_build_rpcall(rp, po->po_name, po->po_opts);
423 }
424 }
425
426 /*
427 * npfctl_build_group: create a group, insert into the global ruleset
428 * and update the current group pointer.
429 */
430 void
431 npfctl_build_group(const char *name, int attr, u_int if_idx)
432 {
433 const int attr_di = (NPF_RULE_IN | NPF_RULE_OUT);
434 nl_rule_t *rl;
435
436 if (attr & NPF_RULE_DEFAULT) {
437 if (defgroup_set) {
438 yyerror("multiple default groups are not valid");
439 }
440 defgroup_set = true;
441 attr |= attr_di;
442
443 } else if ((attr & attr_di) == 0) {
444 attr |= attr_di;
445 }
446
447 rl = npf_rule_create(name, attr | NPF_RULE_FINAL, if_idx);
448 npf_rule_insert(npf_conf, NULL, rl, NPF_PRI_NEXT);
449 current_group = rl;
450 }
451
452 /*
453 * npfctl_build_rule: create a rule, build n-code from filter options,
454 * if any, and insert into the ruleset of current group.
455 */
456 void
457 npfctl_build_rule(int attr, u_int if_idx, sa_family_t family,
458 const opt_proto_t *op, const filt_opts_t *fopts, const char *rproc)
459 {
460 nl_rule_t *rl;
461
462 rl = npf_rule_create(NULL, attr, if_idx);
463 npfctl_build_ncode(rl, family, op, fopts, false);
464 if (rproc && npf_rule_setproc(npf_conf, rl, rproc) != 0) {
465 yyerror("rule procedure '%s' is not defined", rproc);
466 }
467 assert(current_group != NULL);
468 npf_rule_insert(npf_conf, current_group, rl, NPF_PRI_NEXT);
469 }
470
471 /*
472 * npfctl_build_nat: create a NAT policy of a specified type with a
473 * given filter options.
474 */
475 void
476 npfctl_build_nat(int sd, int type, u_int if_idx, const addr_port_t *ap1,
477 const addr_port_t *ap2, const filt_opts_t *fopts)
478 {
479 const opt_proto_t op = { .op_proto = -1, .op_opts = NULL };
480 fam_addr_mask_t *am1 = NULL, *am2 = NULL;
481 filt_opts_t imfopts;
482 sa_family_t family;
483 nl_nat_t *nat;
484
485 if (sd == NPFCTL_NAT_STATIC) {
486 yyerror("static NAT is not yet supported");
487 }
488 assert(sd == NPFCTL_NAT_DYNAMIC);
489 assert(if_idx != 0);
490
491 family = AF_INET;
492
493 if (type & NPF_NATIN) {
494 if (!ap1->ap_netaddr) {
495 yyerror("inbound network segment is not specified");
496 }
497 am1 = npfctl_get_singlefam(ap1->ap_netaddr);
498 if (am1->fam_family != family) {
499 yyerror("IPv6 NAT is not supported");
500 }
501 assert(am1 != NULL);
502 }
503
504 if (type & NPF_NATOUT) {
505 if (!ap2->ap_netaddr) {
506 yyerror("outbound network segment is not specified");
507 }
508 am2 = npfctl_get_singlefam(ap2->ap_netaddr);
509 if (am2->fam_family != family) {
510 yyerror("IPv6 NAT is not supported");
511 }
512 assert(am2 != NULL);
513 }
514
515 /*
516 * If filter criteria is not specified explicitly, apply implicit
517 * filtering according to the given network segements.
518 */
519 if (!fopts) {
520 memset(&imfopts, 0, sizeof(filt_opts_t));
521 if (type & NPF_NATOUT) {
522 memcpy(&imfopts.fo_from, ap1, sizeof(addr_port_t));
523 }
524 if (type & NPF_NATIN) {
525 memcpy(&imfopts.fo_to, ap2, sizeof(addr_port_t));
526 }
527 fopts = &imfopts;
528 }
529
530 switch (type) {
531 case NPF_NATIN:
532 assert(am1 != NULL);
533 /*
534 * Redirection: an inbound NAT with a specific port.
535 */
536 if (!ap1->ap_portrange) {
537 yyerror("inbound port is not specified");
538 }
539 in_port_t port = npfctl_get_singleport(ap1->ap_portrange);
540 nat = npf_nat_create(NPF_NATIN, NPF_NAT_PORTS,
541 if_idx, &am1->fam_addr, am1->fam_family, port);
542 break;
543
544 case (NPF_NATIN | NPF_NATOUT):
545 assert(am1 != NULL);
546 /*
547 * Bi-directional NAT: a combination of inbound NAT and
548 * outbound NAT policies. Note that the translation address
549 * is local IP and filter criteria is inverted accordingly.
550 */
551 nat = npf_nat_create(NPF_NATIN, 0, if_idx,
552 &am1->fam_addr, am1->fam_family, 0);
553 npfctl_build_ncode(nat, family, &op, fopts, true);
554 npf_nat_insert(npf_conf, nat, NPF_PRI_NEXT);
555 /* FALLTHROUGH */
556
557 case NPF_NATOUT:
558 assert(am2 != NULL);
559 /*
560 * Traditional NAPT: an outbound NAT policy with port.
561 * If this is another half for bi-directional NAT, then
562 * no port translation with mapping.
563 */
564 nat = npf_nat_create(NPF_NATOUT, type == NPF_NATOUT ?
565 (NPF_NAT_PORTS | NPF_NAT_PORTMAP) : 0,
566 if_idx, &am2->fam_addr, am2->fam_family, 0);
567 break;
568
569 default:
570 assert(false);
571 }
572 npfctl_build_ncode(nat, family, &op, fopts, false);
573 npf_nat_insert(npf_conf, nat, NPF_PRI_NEXT);
574 }
575
576 /*
577 * npfctl_fill_table: fill NPF table with entries from a specified file.
578 */
579 static void
580 npfctl_fill_table(nl_table_t *tl, u_int type, const char *fname)
581 {
582 char *buf = NULL;
583 int l = 0;
584 FILE *fp;
585 size_t n;
586
587 fp = fopen(fname, "r");
588 if (fp == NULL) {
589 err(EXIT_FAILURE, "open '%s'", fname);
590 }
591 while (l++, getline(&buf, &n, fp) != -1) {
592 fam_addr_mask_t fam;
593 int alen;
594
595 if (*buf == '\n' || *buf == '#') {
596 continue;
597 }
598
599 if (!npfctl_parse_cidr(buf, &fam, &alen)) {
600 errx(EXIT_FAILURE,
601 "%s:%d: invalid table entry", fname, l);
602 }
603 if (type == NPF_TABLE_HASH && fam.fam_mask != NPF_NO_NETMASK) {
604 errx(EXIT_FAILURE,
605 "%s:%d: mask used with the hash table", fname, l);
606 }
607
608 /* Create and add a table entry. */
609 npf_table_add_entry(tl, alen, &fam.fam_addr, fam.fam_mask);
610 }
611 if (buf != NULL) {
612 free(buf);
613 }
614 }
615
616 /*
617 * npfctl_build_table: create an NPF table, add to the configuration and,
618 * if required, fill with contents from a file.
619 */
620 void
621 npfctl_build_table(const char *tid, u_int type, const char *fname)
622 {
623 nl_table_t *tl;
624 u_int id;
625
626 id = atoi(tid);
627 tl = npf_table_create(id, type);
628 assert(tl != NULL);
629
630 if (npf_table_insert(npf_conf, tl)) {
631 errx(EXIT_FAILURE, "table '%d' is already defined\n", id);
632 }
633
634 if (fname) {
635 npfctl_fill_table(tl, type, fname);
636 }
637 }
638