npf_build.c revision 1.15 1 /* $NetBSD: npf_build.c,v 1.15 2012/11/26 20:34:28 rmind 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.15 2012/11/26 20:34:28 rmind 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 <errno.h>
46 #include <err.h>
47
48 #include "npfctl.h"
49
50 static nl_config_t * npf_conf = NULL;
51 static nl_rule_t * current_group = NULL;
52 static bool npf_debug = false;
53 static bool defgroup_set = false;
54
55 void
56 npfctl_config_init(bool debug)
57 {
58
59 npf_conf = npf_config_create();
60 if (npf_conf == NULL) {
61 errx(EXIT_FAILURE, "npf_config_create failed");
62 }
63 npf_debug = debug;
64 }
65
66 int
67 npfctl_config_send(int fd, const char *out)
68 {
69 int error;
70
71 if (out) {
72 _npf_config_setsubmit(npf_conf, out);
73 printf("\nSaving to %s\n", out);
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 unsigned long
89 npfctl_debug_addif(const char *ifname)
90 {
91 char tname[] = "npftest";
92 const size_t tnamelen = sizeof(tname) - 1;
93
94 if (!npf_debug || strncmp(ifname, tname, tnamelen) != 0) {
95 return 0;
96 }
97 struct ifaddrs ifa = {
98 .ifa_name = __UNCONST(ifname),
99 .ifa_flags = 0
100 };
101 unsigned long if_idx = atol(ifname + tnamelen) + 1;
102 _npf_debug_addif(npf_conf, &ifa, if_idx);
103 return if_idx;
104 }
105
106 bool
107 npfctl_table_exists_p(const char *id)
108 {
109 return npf_table_exists_p(npf_conf, atoi(id));
110 }
111
112 static in_port_t
113 npfctl_get_singleport(const npfvar_t *vp)
114 {
115 port_range_t *pr;
116 in_port_t *port;
117
118 if (npfvar_get_count(vp) > 1) {
119 yyerror("multiple ports are not valid");
120 }
121 pr = npfvar_get_data(vp, NPFVAR_PORT_RANGE, 0);
122 if (pr->pr_start != pr->pr_end) {
123 yyerror("port range is not valid");
124 }
125 port = &pr->pr_start;
126 return *port;
127 }
128
129 static fam_addr_mask_t *
130 npfctl_get_singlefam(const npfvar_t *vp)
131 {
132 if (npfvar_get_count(vp) > 1) {
133 yyerror("multiple addresses are not valid");
134 }
135 return npfvar_get_data(vp, NPFVAR_FAM, 0);
136 }
137
138 static bool
139 npfctl_build_fam(nc_ctx_t *nc, sa_family_t family,
140 fam_addr_mask_t *fam, int opts)
141 {
142 /*
143 * If family is specified, address does not match it and the
144 * address is extracted from the interface, then simply ignore.
145 * Otherwise, address of invalid family was passed manually.
146 */
147 if (family != AF_UNSPEC && family != fam->fam_family) {
148 if (!fam->fam_ifindex) {
149 yyerror("specified address is not of the required "
150 "family %d", family);
151 }
152 return false;
153 }
154
155 /*
156 * Optimise 0.0.0.0/0 case to be NOP. Otherwise, address with
157 * zero mask would never match and therefore is not valid.
158 */
159 if (fam->fam_mask == 0) {
160 npf_addr_t zero;
161
162 memset(&zero, 0, sizeof(npf_addr_t));
163 if (memcmp(&fam->fam_addr, &zero, sizeof(npf_addr_t))) {
164 yyerror("filter criterion would never match");
165 }
166 return false;
167 }
168
169 switch (fam->fam_family) {
170 case AF_INET:
171 npfctl_gennc_v4cidr(nc, opts,
172 &fam->fam_addr, fam->fam_mask);
173 break;
174 case AF_INET6:
175 npfctl_gennc_v6cidr(nc, opts,
176 &fam->fam_addr, fam->fam_mask);
177 break;
178 default:
179 yyerror("family %d is not supported", fam->fam_family);
180 }
181 return true;
182 }
183
184 static void
185 npfctl_build_vars(nc_ctx_t *nc, sa_family_t family, npfvar_t *vars, int opts)
186 {
187 const int type = npfvar_get_type(vars, 0);
188 size_t i;
189
190 npfctl_ncgen_group(nc);
191 for (i = 0; i < npfvar_get_count(vars); i++) {
192 void *data = npfvar_get_data(vars, type, i);
193 assert(data != NULL);
194
195 switch (type) {
196 case NPFVAR_FAM: {
197 fam_addr_mask_t *fam = data;
198 npfctl_build_fam(nc, family, fam, opts);
199 break;
200 }
201 case NPFVAR_PORT_RANGE: {
202 port_range_t *pr = data;
203 if (opts & NC_MATCH_TCP) {
204 npfctl_gennc_ports(nc, opts & ~NC_MATCH_UDP,
205 pr->pr_start, pr->pr_end);
206 }
207 if (opts & NC_MATCH_UDP) {
208 npfctl_gennc_ports(nc, opts & ~NC_MATCH_TCP,
209 pr->pr_start, pr->pr_end);
210 }
211 break;
212 }
213 case NPFVAR_TABLE: {
214 u_int tid = atoi(data);
215 npfctl_gennc_tbl(nc, opts, tid);
216 break;
217 }
218 default:
219 assert(false);
220 }
221 }
222 npfctl_ncgen_endgroup(nc);
223 }
224
225 static int
226 npfctl_build_proto(nc_ctx_t *nc, sa_family_t family,
227 const opt_proto_t *op, bool nof, bool nop)
228 {
229 const npfvar_t *popts = op->op_opts;
230 const int proto = op->op_proto;
231 int pflag = 0;
232
233 switch (proto) {
234 case IPPROTO_TCP:
235 pflag = NC_MATCH_TCP;
236 if (!popts) {
237 break;
238 }
239 assert(npfvar_get_count(popts) == 2);
240
241 /* Build TCP flags block (optional). */
242 uint8_t *tf, *tf_mask;
243
244 tf = npfvar_get_data(popts, NPFVAR_TCPFLAG, 0);
245 tf_mask = npfvar_get_data(popts, NPFVAR_TCPFLAG, 1);
246 npfctl_gennc_tcpfl(nc, *tf, *tf_mask);
247 nop = false;
248 break;
249 case IPPROTO_UDP:
250 pflag = NC_MATCH_UDP;
251 break;
252 case IPPROTO_ICMP:
253 /*
254 * Build ICMP block.
255 */
256 if (!nop) {
257 goto invop;
258 }
259 assert(npfvar_get_count(popts) == 2);
260
261 int *icmp_type, *icmp_code;
262 icmp_type = npfvar_get_data(popts, NPFVAR_ICMP, 0);
263 icmp_code = npfvar_get_data(popts, NPFVAR_ICMP, 1);
264 npfctl_gennc_icmp(nc, *icmp_type, *icmp_code);
265 nop = false;
266 break;
267 case IPPROTO_ICMPV6:
268 /*
269 * Build ICMP block.
270 */
271 if (!nop) {
272 goto invop;
273 }
274 assert(npfvar_get_count(popts) == 2);
275
276 int *icmp6_type, *icmp6_code;
277 icmp6_type = npfvar_get_data(popts, NPFVAR_ICMP6, 0);
278 icmp6_code = npfvar_get_data(popts, NPFVAR_ICMP6, 1);
279 npfctl_gennc_icmp6(nc, *icmp6_type, *icmp6_code);
280 nop = false;
281 break;
282 case -1:
283 pflag = NC_MATCH_TCP | NC_MATCH_UDP;
284 nop = false;
285 break;
286 default:
287 /*
288 * No filter options are supported for other protcols.
289 */
290 if (nof && nop) {
291 break;
292 }
293 invop:
294 yyerror("invalid filter options for protocol %d", proto);
295 }
296
297 /*
298 * Build the protocol block, unless other blocks will implicitly
299 * perform the family/protocol checks for us.
300 */
301 if ((family != AF_UNSPEC && nof) || (proto != -1 && nop)) {
302 uint8_t addrlen;
303
304 switch (family) {
305 case AF_INET:
306 addrlen = sizeof(struct in_addr);
307 break;
308 case AF_INET6:
309 addrlen = sizeof(struct in6_addr);
310 break;
311 default:
312 addrlen = 0;
313 }
314 npfctl_gennc_proto(nc, nof ? addrlen : 0, nop ? proto : 0xff);
315 }
316 return pflag;
317 }
318
319 static bool
320 npfctl_build_ncode(nl_rule_t *rl, sa_family_t family, const opt_proto_t *op,
321 const filt_opts_t *fopts, bool invert)
322 {
323 const addr_port_t *apfrom = &fopts->fo_from;
324 const addr_port_t *apto = &fopts->fo_to;
325 const int proto = op->op_proto;
326 bool nof, nop;
327 nc_ctx_t *nc;
328 void *code;
329 size_t len;
330
331 /*
332 * If none specified, no n-code.
333 */
334 nof = !apfrom->ap_netaddr && !apto->ap_netaddr;
335 nop = !apfrom->ap_portrange && !apto->ap_portrange;
336 if (family == AF_UNSPEC && proto == -1 && !op->op_opts && nof && nop)
337 return false;
338
339 int srcflag = NC_MATCH_SRC;
340 int dstflag = NC_MATCH_DST;
341
342 if (invert) {
343 srcflag = NC_MATCH_DST;
344 dstflag = NC_MATCH_SRC;
345 }
346
347 nc = npfctl_ncgen_create();
348
349 /* Build layer 4 protocol blocks. */
350 int pflag = npfctl_build_proto(nc, family, op, nof, nop);
351
352 /* Build IP address blocks. */
353 npfctl_build_vars(nc, family, apfrom->ap_netaddr, srcflag);
354 npfctl_build_vars(nc, family, apto->ap_netaddr, dstflag);
355
356 /* Build port-range blocks. */
357 npfctl_build_vars(nc, family, apfrom->ap_portrange, srcflag | pflag);
358 npfctl_build_vars(nc, family, apto->ap_portrange, dstflag | pflag);
359
360 /*
361 * Complete n-code (destroys the context) and pass to the rule.
362 */
363 code = npfctl_ncgen_complete(nc, &len);
364 if (npf_debug) {
365 extern int yylineno;
366 printf("RULE AT LINE %d\n", yylineno);
367 npfctl_ncgen_print(code, len);
368 }
369 assert(code && len > 0);
370
371 if (npf_rule_setcode(rl, NPF_CODE_NCODE, code, len) == -1) {
372 errx(EXIT_FAILURE, "npf_rule_setcode failed");
373 }
374 free(code);
375 return true;
376 }
377
378 static void
379 npfctl_build_rpcall(nl_rproc_t *rp, const char *name, npfvar_t *args)
380 {
381 npf_extmod_t *extmod;
382 nl_ext_t *extcall;
383 int error;
384
385 extmod = npf_extmod_get(name, &extcall);
386 if (extmod == NULL) {
387 yyerror("unknown rule procedure '%s'", name);
388 }
389
390 for (size_t i = 0; i < npfvar_get_count(args); i++) {
391 const char *param, *value;
392 proc_param_t *p;
393
394 p = npfvar_get_data(args, NPFVAR_PROC_PARAM, i);
395 param = p->pp_param;
396 value = p->pp_value;
397
398 error = npf_extmod_param(extmod, extcall, param, value);
399 switch (error) {
400 case EINVAL:
401 yyerror("invalid parameter '%s'", param);
402 default:
403 break;
404 }
405 }
406 error = npf_rproc_extcall(rp, extcall);
407 if (error) {
408 yyerror(error == EEXIST ?
409 "duplicate procedure call" : "unexpected error");
410 }
411 }
412
413 /*
414 * npfctl_build_rproc: create and insert a rule procedure.
415 */
416 void
417 npfctl_build_rproc(const char *name, npfvar_t *procs)
418 {
419 nl_rproc_t *rp;
420 size_t i;
421
422 rp = npf_rproc_create(name);
423 if (rp == NULL) {
424 errx(EXIT_FAILURE, "npf_rproc_create failed");
425 }
426 npf_rproc_insert(npf_conf, rp);
427
428 for (i = 0; i < npfvar_get_count(procs); i++) {
429 proc_call_t *pc = npfvar_get_data(procs, NPFVAR_PROC, i);
430 npfctl_build_rpcall(rp, pc->pc_name, pc->pc_opts);
431 }
432 }
433
434 /*
435 * npfctl_build_group: create a group, insert into the global ruleset
436 * and update the current group pointer.
437 */
438 void
439 npfctl_build_group(const char *name, int attr, u_int if_idx)
440 {
441 const int attr_di = (NPF_RULE_IN | NPF_RULE_OUT);
442 nl_rule_t *rl;
443
444 if (attr & NPF_RULE_DEFAULT) {
445 if (defgroup_set) {
446 yyerror("multiple default groups are not valid");
447 }
448 defgroup_set = true;
449 attr |= attr_di;
450
451 } else if ((attr & attr_di) == 0) {
452 attr |= attr_di;
453 }
454
455 rl = npf_rule_create(name, attr | NPF_RULE_FINAL, if_idx);
456 npf_rule_insert(npf_conf, NULL, rl, NPF_PRI_NEXT);
457 current_group = rl;
458 }
459
460 /*
461 * npfctl_build_rule: create a rule, build n-code from filter options,
462 * if any, and insert into the ruleset of current group.
463 */
464 void
465 npfctl_build_rule(int attr, u_int if_idx, sa_family_t family,
466 const opt_proto_t *op, const filt_opts_t *fopts, const char *rproc)
467 {
468 nl_rule_t *rl;
469
470 rl = npf_rule_create(NULL, attr, if_idx);
471 npfctl_build_ncode(rl, family, op, fopts, false);
472 if (rproc && npf_rule_setproc(npf_conf, rl, rproc) != 0) {
473 yyerror("rule procedure '%s' is not defined", rproc);
474 }
475 assert(current_group != NULL);
476 npf_rule_insert(npf_conf, current_group, rl, NPF_PRI_NEXT);
477 }
478
479 /*
480 * npfctl_build_nat: create a single NAT policy of a specified
481 * type with a given filter options.
482 */
483 static void
484 npfctl_build_nat(int type, u_int if_idx, sa_family_t family,
485 const addr_port_t *ap, const filt_opts_t *fopts, bool binat)
486 {
487 const opt_proto_t op = { .op_proto = -1, .op_opts = NULL };
488 fam_addr_mask_t *am;
489 in_port_t port;
490 nl_nat_t *nat;
491
492 if (!ap->ap_netaddr) {
493 yyerror("%s network segment is not specified",
494 type == NPF_NATIN ? "inbound" : "outbound");
495 }
496 am = npfctl_get_singlefam(ap->ap_netaddr);
497 if (am->fam_family != family) {
498 yyerror("IPv6 NAT is not supported");
499 }
500
501 switch (type) {
502 case NPF_NATOUT:
503 /*
504 * Outbound NAT (or source NAT) policy, usually used for the
505 * traditional NAPT. If it is a half for bi-directional NAT,
506 * then no port translation with mapping.
507 */
508 nat = npf_nat_create(NPF_NATOUT, !binat ?
509 (NPF_NAT_PORTS | NPF_NAT_PORTMAP) : 0,
510 if_idx, &am->fam_addr, am->fam_family, 0);
511 break;
512 case NPF_NATIN:
513 /*
514 * Inbound NAT (or destination NAT). Unless bi-NAT, a port
515 * must be specified, since it has to be redirection.
516 */
517 port = 0;
518 if (!binat) {
519 if (!ap->ap_portrange) {
520 yyerror("inbound port is not specified");
521 }
522 port = npfctl_get_singleport(ap->ap_portrange);
523 }
524 nat = npf_nat_create(NPF_NATIN, !binat ? NPF_NAT_PORTS : 0,
525 if_idx, &am->fam_addr, am->fam_family, port);
526 break;
527 default:
528 assert(false);
529 }
530
531 npfctl_build_ncode(nat, family, &op, fopts, false);
532 npf_nat_insert(npf_conf, nat, NPF_PRI_NEXT);
533 }
534
535 /*
536 * npfctl_build_natseg: validate and create NAT policies.
537 */
538 void
539 npfctl_build_natseg(int sd, int type, u_int if_idx, const addr_port_t *ap1,
540 const addr_port_t *ap2, const filt_opts_t *fopts)
541 {
542 sa_family_t af = AF_INET;
543 filt_opts_t imfopts;
544 bool binat;
545
546 if (sd == NPFCTL_NAT_STATIC) {
547 yyerror("static NAT is not yet supported");
548 }
549 assert(sd == NPFCTL_NAT_DYNAMIC);
550 assert(if_idx != 0);
551
552 /*
553 * Bi-directional NAT is a combination of inbound NAT and outbound
554 * NAT policies. Note that the translation address is local IP and
555 * the filter criteria is inverted accordingly.
556 */
557 binat = (NPF_NATIN | NPF_NATOUT) == type;
558
559 /*
560 * If the filter criteria is not specified explicitly, apply implicit
561 * filtering according to the given network segments.
562 *
563 * Note: filled below, depending on the type.
564 */
565 if (__predict_true(!fopts)) {
566 fopts = &imfopts;
567 }
568
569 if (type & NPF_NATIN) {
570 memset(&imfopts, 0, sizeof(filt_opts_t));
571 memcpy(&imfopts.fo_to, ap2, sizeof(addr_port_t));
572 npfctl_build_nat(NPF_NATIN, if_idx, af, ap1, fopts, binat);
573 }
574 if (type & NPF_NATOUT) {
575 memset(&imfopts, 0, sizeof(filt_opts_t));
576 memcpy(&imfopts.fo_from, ap1, sizeof(addr_port_t));
577 npfctl_build_nat(NPF_NATOUT, if_idx, af, ap2, fopts, binat);
578 }
579 }
580
581 /*
582 * npfctl_fill_table: fill NPF table with entries from a specified file.
583 */
584 static void
585 npfctl_fill_table(nl_table_t *tl, u_int type, const char *fname)
586 {
587 char *buf = NULL;
588 int l = 0;
589 FILE *fp;
590 size_t n;
591
592 fp = fopen(fname, "r");
593 if (fp == NULL) {
594 err(EXIT_FAILURE, "open '%s'", fname);
595 }
596 while (l++, getline(&buf, &n, fp) != -1) {
597 fam_addr_mask_t fam;
598 int alen;
599
600 if (*buf == '\n' || *buf == '#') {
601 continue;
602 }
603
604 if (!npfctl_parse_cidr(buf, &fam, &alen)) {
605 errx(EXIT_FAILURE,
606 "%s:%d: invalid table entry", fname, l);
607 }
608 if (type == NPF_TABLE_HASH && fam.fam_mask != NPF_NO_NETMASK) {
609 errx(EXIT_FAILURE,
610 "%s:%d: mask used with the hash table", fname, l);
611 }
612
613 /* Create and add a table entry. */
614 npf_table_add_entry(tl, alen, &fam.fam_addr, fam.fam_mask);
615 }
616 if (buf != NULL) {
617 free(buf);
618 }
619 }
620
621 /*
622 * npfctl_build_table: create an NPF table, add to the configuration and,
623 * if required, fill with contents from a file.
624 */
625 void
626 npfctl_build_table(const char *tid, u_int type, const char *fname)
627 {
628 nl_table_t *tl;
629 u_int id;
630
631 id = atoi(tid);
632 tl = npf_table_create(id, type);
633 assert(tl != NULL);
634
635 if (npf_table_insert(npf_conf, tl)) {
636 errx(EXIT_FAILURE, "table '%d' is already defined\n", id);
637 }
638
639 if (fname) {
640 npfctl_fill_table(tl, type, fname);
641 }
642 }
643