npf_build.c revision 1.54 1 /*-
2 * Copyright (c) 2011-2019 The NetBSD Foundation, Inc.
3 * All rights reserved.
4 *
5 * This material is based upon work partially supported by The
6 * NetBSD Foundation under a contract with Mindaugas Rasiukevicius.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
18 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
19 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
20 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
21 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27 * POSSIBILITY OF SUCH DAMAGE.
28 */
29
30 /*
31 * npfctl(8) building of the configuration.
32 */
33
34 #include <sys/cdefs.h>
35 __RCSID("$NetBSD: npf_build.c,v 1.54 2020/05/23 19:56:00 rmind Exp $");
36
37 #include <sys/types.h>
38 #define __FAVOR_BSD
39 #include <netinet/tcp.h>
40
41 #include <stdlib.h>
42 #include <inttypes.h>
43 #include <string.h>
44 #include <ctype.h>
45 #include <unistd.h>
46 #include <fcntl.h>
47 #include <errno.h>
48 #include <err.h>
49
50 #include <pcap/pcap.h>
51
52 #include "npfctl.h"
53
54 #define MAX_RULE_NESTING 16
55
56 static nl_config_t * npf_conf = NULL;
57 static bool npf_debug = false;
58 static nl_rule_t * the_rule = NULL;
59 static bool npf_conf_built = false;
60
61 static nl_rule_t * defgroup = NULL;
62 static nl_rule_t * current_group[MAX_RULE_NESTING];
63 static unsigned rule_nesting_level = 0;
64 static unsigned npfctl_tid_counter = 0;
65
66 static void npfctl_dump_bpf(struct bpf_program *);
67
68 void
69 npfctl_config_init(bool debug)
70 {
71 npf_conf = npf_config_create();
72 if (npf_conf == NULL) {
73 errx(EXIT_FAILURE, "npf_config_create failed");
74 }
75 memset(current_group, 0, sizeof(current_group));
76 npf_debug = debug;
77 npf_conf_built = false;
78 }
79
80 void
81 npfctl_config_build(void)
82 {
83 /* Run-once. */
84 if (npf_conf_built) {
85 return;
86 }
87
88 /*
89 * The default group is mandatory. Note: npfctl_build_group_end()
90 * skipped the default rule, since it must be the last one.
91 */
92 if (!defgroup) {
93 errx(EXIT_FAILURE, "default group was not defined");
94 }
95 assert(rule_nesting_level == 0);
96 npf_rule_insert(npf_conf, NULL, defgroup);
97
98 npf_config_build(npf_conf);
99 npf_conf_built = true;
100 }
101
102 int
103 npfctl_config_send(int fd)
104 {
105 npf_error_t errinfo;
106 int error = 0;
107
108 npfctl_config_build();
109 error = npf_config_submit(npf_conf, fd, &errinfo);
110 if (error == EEXIST) { /* XXX */
111 errx(EXIT_FAILURE, "(re)load failed: "
112 "some table has a duplicate entry?");
113 }
114 if (error) {
115 npfctl_print_error(&errinfo);
116 }
117 npf_config_destroy(npf_conf);
118 return error;
119 }
120
121 void
122 npfctl_config_save(nl_config_t *ncf, const char *outfile)
123 {
124 void *blob;
125 size_t len;
126 int fd;
127
128 blob = npf_config_export(ncf, &len);
129 if (!blob)
130 err(EXIT_FAILURE, "npf_config_export");
131 if ((fd = open(outfile, O_CREAT | O_TRUNC | O_WRONLY, 0644)) == -1)
132 err(EXIT_FAILURE, "could not open %s", outfile);
133 if (write(fd, blob, len) != (ssize_t)len) {
134 err(EXIT_FAILURE, "write to %s failed", outfile);
135 }
136 free(blob);
137 close(fd);
138 }
139
140 void
141 npfctl_config_debug(const char *outfile)
142 {
143 npfctl_config_build();
144
145 printf("\nConfiguration:\n\n");
146 _npf_config_dump(npf_conf, STDOUT_FILENO);
147
148 printf("\nSaving binary to %s\n", outfile);
149 npfctl_config_save(npf_conf, outfile);
150 npf_config_destroy(npf_conf);
151 }
152
153 nl_config_t *
154 npfctl_config_ref(void)
155 {
156 return npf_conf;
157 }
158
159 nl_rule_t *
160 npfctl_rule_ref(void)
161 {
162 return the_rule;
163 }
164
165 bool
166 npfctl_debug_addif(const char *ifname)
167 {
168 const char tname[] = "npftest";
169 const size_t tnamelen = sizeof(tname) - 1;
170
171 if (npf_debug) {
172 _npf_debug_addif(npf_conf, ifname);
173 return strncmp(ifname, tname, tnamelen) == 0;
174 }
175 return 0;
176 }
177
178 nl_table_t *
179 npfctl_table_getbyname(nl_config_t *ncf, const char *name)
180 {
181 nl_iter_t i = NPF_ITER_BEGIN;
182 nl_table_t *tl;
183
184 /* XXX dynamic ruleset */
185 if (!ncf) {
186 return NULL;
187 }
188 while ((tl = npf_table_iterate(ncf, &i)) != NULL) {
189 const char *tname = npf_table_getname(tl);
190 if (strcmp(tname, name) == 0) {
191 break;
192 }
193 }
194 return tl;
195 }
196
197 unsigned
198 npfctl_table_getid(const char *name)
199 {
200 nl_table_t *tl;
201
202 tl = npfctl_table_getbyname(npf_conf, name);
203 return tl ? npf_table_getid(tl) : (unsigned)-1;
204 }
205
206 const char *
207 npfctl_table_getname(nl_config_t *ncf, unsigned tid, bool *ifaddr)
208 {
209 const char *name = NULL;
210 nl_iter_t i = NPF_ITER_BEGIN;
211 nl_table_t *tl;
212
213 while ((tl = npf_table_iterate(ncf, &i)) != NULL) {
214 if (npf_table_getid(tl) == tid) {
215 name = npf_table_getname(tl);
216 break;
217 }
218 }
219 if (!name) {
220 return NULL;
221 }
222 if (!strncmp(name, NPF_IFNET_TABLE_PREF, NPF_IFNET_TABLE_PREFLEN)) {
223 name += NPF_IFNET_TABLE_PREFLEN;
224 *ifaddr = true;
225 } else {
226 *ifaddr = false;
227 }
228 return name;
229 }
230
231 static in_port_t
232 npfctl_get_singleport(const npfvar_t *vp)
233 {
234 port_range_t *pr;
235 in_port_t *port;
236
237 if (npfvar_get_count(vp) > 1) {
238 yyerror("multiple ports are not valid");
239 }
240 pr = npfvar_get_data(vp, NPFVAR_PORT_RANGE, 0);
241 if (pr->pr_start != pr->pr_end) {
242 yyerror("port range is not valid");
243 }
244 port = &pr->pr_start;
245 return *port;
246 }
247
248 static fam_addr_mask_t *
249 npfctl_get_singlefam(const npfvar_t *vp)
250 {
251 fam_addr_mask_t *am;
252
253 if (npfvar_get_type(vp, 0) != NPFVAR_FAM) {
254 yyerror("map segment must be an address or network");
255 }
256 if (npfvar_get_count(vp) > 1) {
257 yyerror("map segment cannot have multiple static addresses");
258 }
259 am = npfvar_get_data(vp, NPFVAR_FAM, 0);
260 if (am == NULL) {
261 yyerror("invalid map segment");
262 }
263 return am;
264 }
265
266 static unsigned
267 npfctl_get_singletable(const npfvar_t *vp)
268 {
269 unsigned *tid;
270
271 if (npfvar_get_count(vp) > 1) {
272 yyerror("multiple tables are not valid");
273 }
274 tid = npfvar_get_data(vp, NPFVAR_TABLE, 0);
275 assert(tid != NULL);
276 return *tid;
277 }
278
279 static bool
280 npfctl_build_fam(npf_bpf_t *ctx, sa_family_t family,
281 fam_addr_mask_t *fam, int opts)
282 {
283 /*
284 * If family is specified, address does not match it and the
285 * address is extracted from the interface, then simply ignore.
286 * Otherwise, address of invalid family was passed manually.
287 */
288 if (family != AF_UNSPEC && family != fam->fam_family) {
289 if (!fam->fam_ifindex) {
290 yyerror("specified address is not of the required "
291 "family %d", family);
292 }
293 return false;
294 }
295
296 family = fam->fam_family;
297 if (family != AF_INET && family != AF_INET6) {
298 yyerror("family %d is not supported", family);
299 }
300
301 /*
302 * Optimise 0.0.0.0/0 case to be NOP. Otherwise, address with
303 * zero mask would never match and therefore is not valid.
304 */
305 if (fam->fam_mask == 0) {
306 static const npf_addr_t zero; /* must be static */
307
308 if (memcmp(&fam->fam_addr, &zero, sizeof(npf_addr_t))) {
309 yyerror("filter criterion would never match");
310 }
311 return false;
312 }
313
314 npfctl_bpf_cidr(ctx, opts, family, &fam->fam_addr, fam->fam_mask);
315 return true;
316 }
317
318 static void
319 npfctl_build_vars(npf_bpf_t *ctx, sa_family_t family, npfvar_t *vars, int opts)
320 {
321 const int type = npfvar_get_type(vars, 0);
322 size_t i;
323
324 npfctl_bpf_group_enter(ctx);
325 for (i = 0; i < npfvar_get_count(vars); i++) {
326 void *data = npfvar_get_data(vars, type, i);
327 assert(data != NULL);
328
329 switch (type) {
330 case NPFVAR_FAM: {
331 fam_addr_mask_t *fam = data;
332 npfctl_build_fam(ctx, family, fam, opts);
333 break;
334 }
335 case NPFVAR_PORT_RANGE: {
336 port_range_t *pr = data;
337 npfctl_bpf_ports(ctx, opts, pr->pr_start, pr->pr_end);
338 break;
339 }
340 case NPFVAR_TABLE: {
341 u_int tid;
342 memcpy(&tid, data, sizeof(u_int));
343 npfctl_bpf_table(ctx, opts, tid);
344 break;
345 }
346 default:
347 assert(false);
348 }
349 }
350 npfctl_bpf_group_exit(ctx, (opts & MATCH_INVERT) != 0);
351 }
352
353 static void
354 npfctl_build_proto(npf_bpf_t *ctx, sa_family_t family, const opt_proto_t *op)
355 {
356 const npfvar_t *popts = op->op_opts;
357 const int proto = op->op_proto;
358
359 /* IP version and/or L4 protocol matching. */
360 if (family != AF_UNSPEC || proto != -1) {
361 npfctl_bpf_proto(ctx, family, proto);
362 }
363
364 switch (proto) {
365 case IPPROTO_TCP:
366 /* Build TCP flags matching (optional). */
367 if (popts) {
368 uint8_t *tf, *tf_mask;
369
370 assert(npfvar_get_count(popts) == 2);
371 tf = npfvar_get_data(popts, NPFVAR_TCPFLAG, 0);
372 tf_mask = npfvar_get_data(popts, NPFVAR_TCPFLAG, 1);
373 npfctl_bpf_tcpfl(ctx, *tf, *tf_mask, false);
374 }
375 break;
376 case IPPROTO_ICMP:
377 case IPPROTO_ICMPV6:
378 /* Build ICMP/ICMPv6 type and/or code matching. */
379 if (popts) {
380 int *icmp_type, *icmp_code;
381
382 assert(npfvar_get_count(popts) == 2);
383 icmp_type = npfvar_get_data(popts, NPFVAR_ICMP, 0);
384 icmp_code = npfvar_get_data(popts, NPFVAR_ICMP, 1);
385 npfctl_bpf_icmp(ctx, *icmp_type, *icmp_code);
386 }
387 break;
388 default:
389 /* No options for other protocols. */
390 break;
391 }
392 }
393
394 static bool
395 npfctl_build_code(nl_rule_t *rl, sa_family_t family, const opt_proto_t *op,
396 const filt_opts_t *fopts)
397 {
398 bool noproto, noaddrs, noports, nostate, need_tcpudp = false;
399 const addr_port_t *apfrom = &fopts->fo_from;
400 const addr_port_t *apto = &fopts->fo_to;
401 const int proto = op->op_proto;
402 npf_bpf_t *bc;
403 unsigned opts;
404 size_t len;
405
406 /* If none specified, then no byte-code. */
407 noproto = family == AF_UNSPEC && proto == -1 && !op->op_opts;
408 noaddrs = !apfrom->ap_netaddr && !apto->ap_netaddr;
409 noports = !apfrom->ap_portrange && !apto->ap_portrange;
410 nostate = !(npf_rule_getattr(rl) & NPF_RULE_STATEFUL);
411 if (noproto && noaddrs && noports && nostate) {
412 return false;
413 }
414
415 /*
416 * Sanity check: ports can only be used with TCP or UDP protocol.
417 * No filter options are supported for other protocols, only the
418 * IP addresses are allowed.
419 */
420 if (!noports) {
421 switch (proto) {
422 case IPPROTO_TCP:
423 case IPPROTO_UDP:
424 break;
425 case -1:
426 need_tcpudp = true;
427 break;
428 default:
429 yyerror("invalid filter options for protocol %d", proto);
430 }
431 }
432
433 bc = npfctl_bpf_create();
434
435 /* Build layer 4 protocol blocks. */
436 npfctl_build_proto(bc, family, op);
437
438 /*
439 * If this is a stateful rule and TCP flags are not specified,
440 * then add "flags S/SAFR" filter for TCP protocol case.
441 */
442 if ((npf_rule_getattr(rl) & NPF_RULE_STATEFUL) != 0 &&
443 (proto == -1 || (proto == IPPROTO_TCP && !op->op_opts))) {
444 npfctl_bpf_tcpfl(bc, TH_SYN,
445 TH_SYN | TH_ACK | TH_FIN | TH_RST, proto == -1);
446 }
447
448 /* Build IP address blocks. */
449 opts = MATCH_SRC | (fopts->fo_finvert ? MATCH_INVERT : 0);
450 npfctl_build_vars(bc, family, apfrom->ap_netaddr, opts);
451 opts = MATCH_DST | (fopts->fo_tinvert ? MATCH_INVERT : 0);
452 npfctl_build_vars(bc, family, apto->ap_netaddr, opts);
453
454 /* Build port-range blocks. */
455 if (need_tcpudp) {
456 /* TCP/UDP check for the ports. */
457 npfctl_bpf_group_enter(bc);
458 npfctl_bpf_proto(bc, AF_UNSPEC, IPPROTO_TCP);
459 npfctl_bpf_proto(bc, AF_UNSPEC, IPPROTO_UDP);
460 npfctl_bpf_group_exit(bc, false);
461 }
462 npfctl_build_vars(bc, family, apfrom->ap_portrange, MATCH_SRC);
463 npfctl_build_vars(bc, family, apto->ap_portrange, MATCH_DST);
464
465 /* Set the byte-code marks, if any. */
466 const void *bmarks = npfctl_bpf_bmarks(bc, &len);
467 if (npf_rule_setinfo(rl, bmarks, len) == -1) {
468 errx(EXIT_FAILURE, "npf_rule_setinfo failed");
469 }
470
471 /* Complete BPF byte-code and pass to the rule. */
472 struct bpf_program *bf = npfctl_bpf_complete(bc);
473 if (bf == NULL) {
474 npfctl_bpf_destroy(bc);
475 return true;
476 }
477 len = bf->bf_len * sizeof(struct bpf_insn);
478
479 if (npf_rule_setcode(rl, NPF_CODE_BPF, bf->bf_insns, len) != 0) {
480 errx(EXIT_FAILURE, "npf_rule_setcode failed");
481 }
482 npfctl_dump_bpf(bf);
483 npfctl_bpf_destroy(bc);
484
485 return true;
486 }
487
488 static void
489 npfctl_build_pcap(nl_rule_t *rl, const char *filter)
490 {
491 const size_t maxsnaplen = 64 * 1024;
492 struct bpf_program bf;
493 size_t len;
494
495 if (pcap_compile_nopcap(maxsnaplen, DLT_RAW, &bf,
496 filter, 1, PCAP_NETMASK_UNKNOWN) == -1) {
497 yyerror("invalid pcap-filter(7) syntax");
498 }
499 len = bf.bf_len * sizeof(struct bpf_insn);
500
501 if (npf_rule_setcode(rl, NPF_CODE_BPF, bf.bf_insns, len) != 0) {
502 errx(EXIT_FAILURE, "npf_rule_setcode failed");
503 }
504 npfctl_dump_bpf(&bf);
505 pcap_freecode(&bf);
506 }
507
508 static void
509 npfctl_build_rpcall(nl_rproc_t *rp, const char *name, npfvar_t *args)
510 {
511 npf_extmod_t *extmod;
512 nl_ext_t *extcall;
513 int error;
514
515 extmod = npf_extmod_get(name, &extcall);
516 if (extmod == NULL) {
517 yyerror("unknown rule procedure '%s'", name);
518 }
519
520 for (size_t i = 0; i < npfvar_get_count(args); i++) {
521 const char *param, *value;
522 proc_param_t *p;
523
524 p = npfvar_get_data(args, NPFVAR_PROC_PARAM, i);
525 param = p->pp_param;
526 value = p->pp_value;
527
528 error = npf_extmod_param(extmod, extcall, param, value);
529 switch (error) {
530 case EINVAL:
531 yyerror("invalid parameter '%s'", param);
532 default:
533 break;
534 }
535 }
536 error = npf_rproc_extcall(rp, extcall);
537 if (error) {
538 yyerror(error == EEXIST ?
539 "duplicate procedure call" : "unexpected error");
540 }
541 }
542
543 /*
544 * npfctl_build_rproc: create and insert a rule procedure.
545 */
546 void
547 npfctl_build_rproc(const char *name, npfvar_t *procs)
548 {
549 nl_rproc_t *rp;
550 size_t i;
551
552 rp = npf_rproc_create(name);
553 if (rp == NULL) {
554 errx(EXIT_FAILURE, "%s failed", __func__);
555 }
556
557 for (i = 0; i < npfvar_get_count(procs); i++) {
558 proc_call_t *pc = npfvar_get_data(procs, NPFVAR_PROC, i);
559 npfctl_build_rpcall(rp, pc->pc_name, pc->pc_opts);
560 }
561 npf_rproc_insert(npf_conf, rp);
562 }
563
564 /*
565 * npfctl_build_maprset: create and insert a NAT ruleset.
566 */
567 void
568 npfctl_build_maprset(const char *name, int attr, const char *ifname)
569 {
570 const int attr_di = (NPF_RULE_IN | NPF_RULE_OUT);
571 nl_rule_t *rl;
572 bool natset;
573 int err;
574
575 /* Validate the prefix. */
576 err = npfctl_nat_ruleset_p(name, &natset);
577 if (!natset) {
578 yyerror("NAT ruleset names must be prefixed with `"
579 NPF_RULESET_MAP_PREF "`");
580 }
581 if (err) {
582 yyerror("NAT ruleset is missing a name (only prefix found)");
583 }
584
585 /* If no direction is not specified, then both. */
586 if ((attr & attr_di) == 0) {
587 attr |= attr_di;
588 }
589
590 /* Allow only "in/out" attributes. */
591 attr = NPF_RULE_GROUP | NPF_RULE_DYNAMIC | (attr & attr_di);
592 rl = npf_rule_create(name, attr, ifname);
593 npf_rule_setprio(rl, NPF_PRI_LAST);
594 npf_nat_insert(npf_conf, rl);
595 }
596
597 /*
598 * npfctl_build_group: create a group, update the current group pointer
599 * and increase the nesting level.
600 */
601 void
602 npfctl_build_group(const char *name, int attr, const char *ifname, bool def)
603 {
604 const int attr_di = (NPF_RULE_IN | NPF_RULE_OUT);
605 nl_rule_t *rl;
606
607 if (def || (attr & attr_di) == 0) {
608 attr |= attr_di;
609 }
610
611 rl = npf_rule_create(name, attr | NPF_RULE_GROUP, ifname);
612 npf_rule_setprio(rl, NPF_PRI_LAST);
613 if (def) {
614 if (defgroup) {
615 yyerror("multiple default groups are not valid");
616 }
617 if (rule_nesting_level) {
618 yyerror("default group can only be at the top level");
619 }
620 defgroup = rl;
621 }
622
623 /* Set the current group and increase the nesting level. */
624 if (rule_nesting_level >= MAX_RULE_NESTING) {
625 yyerror("rule nesting limit reached");
626 }
627 current_group[++rule_nesting_level] = rl;
628 }
629
630 void
631 npfctl_build_group_end(void)
632 {
633 nl_rule_t *parent, *group;
634
635 assert(rule_nesting_level > 0);
636 parent = current_group[rule_nesting_level - 1];
637 group = current_group[rule_nesting_level];
638 current_group[rule_nesting_level--] = NULL;
639
640 /*
641 * Note:
642 * - If the parent is NULL, then it is a global rule.
643 * - The default rule must be the last, so it is inserted later.
644 */
645 if (group == defgroup) {
646 assert(parent == NULL);
647 return;
648 }
649 npf_rule_insert(npf_conf, parent, group);
650 }
651
652 /*
653 * npfctl_build_rule: create a rule, build byte-code from filter options,
654 * if any, and insert into the ruleset of current group, or set the rule.
655 */
656 void
657 npfctl_build_rule(uint32_t attr, const char *ifname, sa_family_t family,
658 const opt_proto_t *op, const filt_opts_t *fopts,
659 const char *pcap_filter, const char *rproc)
660 {
661 nl_rule_t *rl;
662
663 attr |= (npf_conf ? 0 : NPF_RULE_DYNAMIC);
664
665 rl = npf_rule_create(NULL, attr, ifname);
666 if (pcap_filter) {
667 npfctl_build_pcap(rl, pcap_filter);
668 } else {
669 npfctl_build_code(rl, family, op, fopts);
670 }
671
672 if (rproc) {
673 npf_rule_setproc(rl, rproc);
674 }
675
676 if (npf_conf) {
677 nl_rule_t *cg = current_group[rule_nesting_level];
678
679 if (rproc && !npf_rproc_exists_p(npf_conf, rproc)) {
680 yyerror("rule procedure '%s' is not defined", rproc);
681 }
682 assert(cg != NULL);
683 npf_rule_setprio(rl, NPF_PRI_LAST);
684 npf_rule_insert(npf_conf, cg, rl);
685 } else {
686 /* We have parsed a single rule - set it. */
687 the_rule = rl;
688 }
689 }
690
691 /*
692 * npfctl_build_nat: create a single NAT policy of a specified
693 * type with a given filter options.
694 */
695 static nl_nat_t *
696 npfctl_build_nat(int type, const char *ifname, const addr_port_t *ap,
697 const opt_proto_t *op, const filt_opts_t *fopts, unsigned flags)
698 {
699 const opt_proto_t def_op = { .op_proto = -1, .op_opts = NULL };
700 fam_addr_mask_t *am;
701 sa_family_t family;
702 in_port_t port;
703 nl_nat_t *nat;
704 unsigned tid;
705
706 if (ap->ap_portrange) {
707 /*
708 * The port forwarding case. In such case, there has to
709 * be a single port used for translation; we keep the port
710 * translation on, but disable the port map.
711 */
712 port = npfctl_get_singleport(ap->ap_portrange);
713 flags = (flags & ~NPF_NAT_PORTMAP) | NPF_NAT_PORTS;
714 } else {
715 port = 0;
716 }
717 if (!op) {
718 op = &def_op;
719 }
720
721 nat = npf_nat_create(type, flags, ifname);
722
723 switch (npfvar_get_type(ap->ap_netaddr, 0)) {
724 case NPFVAR_FAM:
725 /* Translation address. */
726 am = npfctl_get_singlefam(ap->ap_netaddr);
727 family = am->fam_family;
728 npf_nat_setaddr(nat, family, &am->fam_addr, am->fam_mask);
729 break;
730 case NPFVAR_TABLE:
731 /* Translation table. */
732 family = AF_UNSPEC;
733 tid = npfctl_get_singletable(ap->ap_netaddr);
734 npf_nat_settable(nat, tid);
735 break;
736 default:
737 yyerror("map must have a valid translation address");
738 abort();
739 }
740 npf_nat_setport(nat, port);
741 npfctl_build_code(nat, family, op, fopts);
742 return nat;
743 }
744
745 static void
746 npfctl_dnat_check(const addr_port_t *ap, const unsigned algo)
747 {
748 int type = npfvar_get_type(ap->ap_netaddr, 0);
749 fam_addr_mask_t *am;
750
751 switch (algo) {
752 case NPF_ALGO_NETMAP:
753 if (type == NPFVAR_FAM) {
754 break;
755 }
756 yyerror("translation address using NETMAP must be "
757 "a network and not a dynamic pool");
758 break;
759 case NPF_ALGO_IPHASH:
760 case NPF_ALGO_RR:
761 case NPF_ALGO_NONE:
762 if (type != NPFVAR_FAM) {
763 break;
764 }
765 am = npfctl_get_singlefam(ap->ap_netaddr);
766 if (am->fam_mask == NPF_NO_NETMASK) {
767 break;
768 }
769 yyerror("translation address, given the specified algorithm, "
770 "must be a pool or a single address");
771 break;
772 default:
773 yyerror("invalid algorithm specified for dynamic NAT");
774 }
775 }
776
777 /*
778 * npfctl_build_natseg: validate and create NAT policies.
779 */
780 void
781 npfctl_build_natseg(int sd, int type, unsigned mflags, const char *ifname,
782 const addr_port_t *ap1, const addr_port_t *ap2, const opt_proto_t *op,
783 const filt_opts_t *fopts, unsigned algo)
784 {
785 fam_addr_mask_t *am1 = NULL, *am2 = NULL;
786 nl_nat_t *nt1 = NULL, *nt2 = NULL;
787 filt_opts_t imfopts;
788 uint16_t adj = 0;
789 unsigned flags;
790 bool binat;
791
792 assert(ifname != NULL);
793
794 /*
795 * Validate that mapping has the translation address(es) set.
796 */
797 if ((type & NPF_NATIN) != 0 && ap1->ap_netaddr == NULL) {
798 yyerror("inbound network segment is not specified");
799 }
800 if ((type & NPF_NATOUT) != 0 && ap2->ap_netaddr == NULL) {
801 yyerror("outbound network segment is not specified");
802 }
803
804 /*
805 * Bi-directional NAT is a combination of inbound NAT and outbound
806 * NAT policies with the translation segments inverted respectively.
807 */
808 binat = (NPF_NATIN | NPF_NATOUT) == type;
809
810 switch (sd) {
811 case NPFCTL_NAT_DYNAMIC:
812 /*
813 * Dynamic NAT: stateful translation -- traditional NAPT
814 * is expected. Unless it is bi-directional NAT, perform
815 * the port mapping.
816 */
817 flags = !binat ? (NPF_NAT_PORTS | NPF_NAT_PORTMAP) : 0;
818 if (type & NPF_NATIN) {
819 npfctl_dnat_check(ap1, algo);
820 }
821 if (type & NPF_NATOUT) {
822 npfctl_dnat_check(ap2, algo);
823 }
824 break;
825 case NPFCTL_NAT_STATIC:
826 /*
827 * Static NAT: stateless translation.
828 */
829 flags = NPF_NAT_STATIC;
830
831 /* Note: translation address/network cannot be a table. */
832 am1 = npfctl_get_singlefam(ap1->ap_netaddr);
833 am2 = npfctl_get_singlefam(ap2->ap_netaddr);
834
835 /* Validate the algorithm. */
836 switch (algo) {
837 case NPF_ALGO_NPT66:
838 if (am1->fam_mask != am2->fam_mask) {
839 yyerror("asymmetric NPTv6 is not supported");
840 }
841 adj = npfctl_npt66_calcadj(am1->fam_mask,
842 &am1->fam_addr, &am2->fam_addr);
843 break;
844 case NPF_ALGO_NETMAP:
845 if (am1->fam_mask != am2->fam_mask) {
846 yyerror("net-to-net mapping using the "
847 "NETMAP algorithm must be 1:1");
848 }
849 break;
850 case NPF_ALGO_NONE:
851 if (am1->fam_mask != NPF_NO_NETMASK ||
852 am2->fam_mask != NPF_NO_NETMASK) {
853 yyerror("static net-to-net translation "
854 "must have an algorithm specified");
855 }
856 break;
857 default:
858 yyerror("invalid algorithm specified for static NAT");
859 }
860 break;
861 default:
862 abort();
863 }
864
865 /*
866 * Apply the flag modifications.
867 */
868 if (mflags & NPF_NAT_PORTS) {
869 flags &= ~(NPF_NAT_PORTS | NPF_NAT_PORTMAP);
870 }
871
872 /*
873 * If the filter criteria is not specified explicitly, apply implicit
874 * filtering according to the given network segments.
875 *
876 * Note: filled below, depending on the type.
877 */
878 if (__predict_true(!fopts)) {
879 fopts = &imfopts;
880 }
881
882 if (type & NPF_NATIN) {
883 memset(&imfopts, 0, sizeof(filt_opts_t));
884 memcpy(&imfopts.fo_to, ap2, sizeof(addr_port_t));
885 nt1 = npfctl_build_nat(NPF_NATIN, ifname, ap1, op, fopts, flags);
886 }
887 if (type & NPF_NATOUT) {
888 memset(&imfopts, 0, sizeof(filt_opts_t));
889 memcpy(&imfopts.fo_from, ap1, sizeof(addr_port_t));
890 nt2 = npfctl_build_nat(NPF_NATOUT, ifname, ap2, op, fopts, flags);
891 }
892
893 switch (algo) {
894 case NPF_ALGO_NONE:
895 break;
896 case NPF_ALGO_NPT66:
897 /*
898 * NPTv6 is a special case using special adjustment value.
899 * It is always bidirectional NAT.
900 */
901 assert(nt1 && nt2);
902 npf_nat_setnpt66(nt1, ~adj);
903 npf_nat_setnpt66(nt2, adj);
904 break;
905 default:
906 /*
907 * Set the algorithm.
908 */
909 if (nt1) {
910 npf_nat_setalgo(nt1, algo);
911 }
912 if (nt2) {
913 npf_nat_setalgo(nt2, algo);
914 }
915 }
916
917 if (npf_conf) {
918 if (nt1) {
919 npf_rule_setprio(nt1, NPF_PRI_LAST);
920 npf_nat_insert(npf_conf, nt1);
921 }
922 if (nt2) {
923 npf_rule_setprio(nt2, NPF_PRI_LAST);
924 npf_nat_insert(npf_conf, nt2);
925 }
926 } else {
927 // XXX/TODO: need to refactor a bit to enable this..
928 if (nt1 && nt2) {
929 errx(EXIT_FAILURE, "bidirectional NAT is currently "
930 "not yet supported in the dynamic rules");
931 }
932 the_rule = nt1 ? nt1 : nt2;
933 }
934 }
935
936 /*
937 * npfctl_fill_table: fill NPF table with entries from a specified file.
938 */
939 static void
940 npfctl_fill_table(nl_table_t *tl, u_int type, const char *fname, FILE *fp)
941 {
942 char *buf = NULL;
943 int l = 0;
944 size_t n;
945
946 if (fp == NULL && (fp = fopen(fname, "r")) == NULL) {
947 err(EXIT_FAILURE, "open '%s'", fname);
948 }
949 while (l++, getline(&buf, &n, fp) != -1) {
950 fam_addr_mask_t fam;
951 int alen;
952
953 if (*buf == '\n' || *buf == '#') {
954 continue;
955 }
956
957 if (!npfctl_parse_cidr(buf, &fam, &alen)) {
958 errx(EXIT_FAILURE,
959 "%s:%d: invalid table entry", fname, l);
960 }
961 if (type != NPF_TABLE_LPM && fam.fam_mask != NPF_NO_NETMASK) {
962 errx(EXIT_FAILURE, "%s:%d: mask used with the "
963 "table type other than \"lpm\"", fname, l);
964 }
965
966 npf_table_add_entry(tl, fam.fam_family,
967 &fam.fam_addr, fam.fam_mask);
968 }
969 free(buf);
970 }
971
972 /*
973 * npfctl_load_table: create an NPF table and fill with contents from a file.
974 */
975 nl_table_t *
976 npfctl_load_table(const char *tname, int tid, u_int type,
977 const char *fname, FILE *fp)
978 {
979 nl_table_t *tl;
980
981 tl = npf_table_create(tname, tid, type);
982 if (tl && fname) {
983 npfctl_fill_table(tl, type, fname, fp);
984 }
985
986 return tl;
987 }
988
989 /*
990 * npfctl_build_table: create an NPF table, add to the configuration and,
991 * if required, fill with contents from a file.
992 */
993 void
994 npfctl_build_table(const char *tname, u_int type, const char *fname)
995 {
996 nl_table_t *tl;
997
998 if (type == NPF_TABLE_CONST && !fname) {
999 yyerror("table type 'const' must be loaded from a file");
1000 }
1001
1002 tl = npfctl_load_table(tname, npfctl_tid_counter++, type, fname, NULL);
1003 assert(tl != NULL);
1004
1005 if (npf_table_insert(npf_conf, tl)) {
1006 yyerror("table '%s' is already defined", tname);
1007 }
1008 }
1009
1010 /*
1011 * npfctl_ifnet_table: get a variable with ifaddr-table; auto-create
1012 * the table on first reference.
1013 */
1014 npfvar_t *
1015 npfctl_ifnet_table(const char *ifname)
1016 {
1017 char tname[NPF_TABLE_MAXNAMELEN];
1018 nl_table_t *tl;
1019 unsigned tid;
1020
1021 snprintf(tname, sizeof(tname), NPF_IFNET_TABLE_PREF "%s", ifname);
1022 if (!npf_conf) {
1023 errx(EXIT_FAILURE, "expression `ifaddrs(%s)` is currently "
1024 "not yet supported in dynamic rules", ifname);
1025 }
1026
1027 tid = npfctl_table_getid(tname);
1028 if (tid == (unsigned)-1) {
1029 tid = npfctl_tid_counter++;
1030 tl = npf_table_create(tname, tid, NPF_TABLE_IFADDR);
1031 (void)npf_table_insert(npf_conf, tl);
1032 }
1033 return npfvar_create_element(NPFVAR_TABLE, &tid, sizeof(unsigned));
1034 }
1035
1036 /*
1037 * npfctl_build_alg: create an NPF application level gateway and add it
1038 * to the configuration.
1039 */
1040 void
1041 npfctl_build_alg(const char *al_name)
1042 {
1043 if (npf_alg_load(npf_conf, al_name) != 0) {
1044 yyerror("ALG '%s' is already loaded", al_name);
1045 }
1046 }
1047
1048 void
1049 npfctl_setparam(const char *name, int val)
1050 {
1051 if (strcmp(name, "bpf.jit") == 0) {
1052 npfctl_bpfjit(val != 0);
1053 return;
1054 }
1055 if (npf_param_set(npf_conf, name, val) != 0) {
1056 yyerror("invalid parameter `%s` or its value", name);
1057 }
1058 }
1059
1060 static void
1061 npfctl_dump_bpf(struct bpf_program *bf)
1062 {
1063 if (npf_debug) {
1064 extern char *yytext;
1065 extern int yylineno;
1066
1067 int rule_line = yylineno - (int)(*yytext == '\n');
1068 printf("\nRULE AT LINE %d\n", rule_line);
1069 bpf_dump(bf, 0);
1070 }
1071 }
1072