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