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