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