Home | History | Annotate | Line # | Download | only in npfctl
npf_build.c revision 1.41
      1 /*	$NetBSD: npf_build.c,v 1.41 2016/12/26 23:05:05 christos Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2011-2014 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This material is based upon work partially supported by The
      8  * NetBSD Foundation under a contract with Mindaugas Rasiukevicius.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     29  * POSSIBILITY OF SUCH DAMAGE.
     30  */
     31 
     32 /*
     33  * npfctl(8) building of the configuration.
     34  */
     35 
     36 #include <sys/cdefs.h>
     37 __RCSID("$NetBSD: npf_build.c,v 1.41 2016/12/26 23:05:05 christos Exp $");
     38 
     39 #include <sys/types.h>
     40 #include <sys/mman.h>
     41 #include <sys/stat.h>
     42 #define	__FAVOR_BSD
     43 #include <netinet/tcp.h>
     44 
     45 #include <stdlib.h>
     46 #include <inttypes.h>
     47 #include <string.h>
     48 #include <ctype.h>
     49 #include <unistd.h>
     50 #include <fcntl.h>
     51 #include <errno.h>
     52 #include <err.h>
     53 
     54 #include <pcap/pcap.h>
     55 #include <cdbw.h>
     56 
     57 #include "npfctl.h"
     58 
     59 #define	MAX_RULE_NESTING	16
     60 
     61 static nl_config_t *		npf_conf = NULL;
     62 static bool			npf_debug = false;
     63 static nl_rule_t *		the_rule = NULL;
     64 
     65 static nl_rule_t *		current_group[MAX_RULE_NESTING];
     66 static unsigned			rule_nesting_level = 0;
     67 static nl_rule_t *		defgroup = NULL;
     68 
     69 static void			npfctl_dump_bpf(struct bpf_program *);
     70 
     71 void
     72 npfctl_config_init(bool debug)
     73 {
     74 	npf_conf = npf_config_create();
     75 	if (npf_conf == NULL) {
     76 		errx(EXIT_FAILURE, "npf_config_create failed");
     77 	}
     78 	npf_debug = debug;
     79 	memset(current_group, 0, sizeof(current_group));
     80 }
     81 
     82 int
     83 npfctl_config_send(int fd, const char *out)
     84 {
     85 	npf_error_t errinfo;
     86 	int error = 0;
     87 
     88 	if (!defgroup) {
     89 		errx(EXIT_FAILURE, "default group was not defined");
     90 	}
     91 	npf_rule_insert(npf_conf, NULL, defgroup);
     92 	if (out) {
     93 		printf("\nSaving to %s\n", out);
     94 		npfctl_config_save(npf_conf, out);
     95 	} else {
     96 		error = npf_config_submit(npf_conf, fd, &errinfo);
     97 	}
     98 	if (error == EEXIST) { /* XXX */
     99 		errx(EXIT_FAILURE, "(re)load failed: "
    100 		    "some table has a duplicate entry?");
    101 	}
    102 	if (error) {
    103 		npfctl_print_error(&errinfo);
    104 	}
    105 	npf_config_destroy(npf_conf);
    106 	return error;
    107 }
    108 
    109 void
    110 npfctl_config_save(nl_config_t *ncf, const char *outfile)
    111 {
    112 	void *blob;
    113 	size_t len;
    114 	int fd;
    115 
    116 	blob = npf_config_export(ncf, &len);
    117 	if (!blob)
    118 		err(EXIT_FAILURE, "npf_config_export");
    119 	if ((fd = open(outfile, O_CREAT | O_TRUNC | O_WRONLY, 0644)) == -1)
    120 		err(EXIT_FAILURE, "could not open %s", outfile);
    121 	if (write(fd, blob, len) != (ssize_t)len) {
    122 		err(EXIT_FAILURE, "write to %s failed", outfile);
    123 	}
    124 	free(blob);
    125 	close(fd);
    126 }
    127 
    128 nl_config_t *
    129 npfctl_config_ref(void)
    130 {
    131 	return npf_conf;
    132 }
    133 
    134 nl_rule_t *
    135 npfctl_rule_ref(void)
    136 {
    137 	return the_rule;
    138 }
    139 
    140 bool
    141 npfctl_debug_addif(const char *ifname)
    142 {
    143 	const char tname[] = "npftest";
    144 	const size_t tnamelen = sizeof(tname) - 1;
    145 
    146 	if (npf_debug) {
    147 		_npf_debug_addif(npf_conf, ifname);
    148 		return strncmp(ifname, tname, tnamelen) == 0;
    149 	}
    150 	return 0;
    151 }
    152 
    153 unsigned
    154 npfctl_table_getid(const char *name)
    155 {
    156 	unsigned tid = (unsigned)-1;
    157 	nl_table_t *tl;
    158 
    159 	/* XXX dynamic ruleset */
    160 	if (!npf_conf) {
    161 		return (unsigned)-1;
    162 	}
    163 
    164 	/* XXX: Iterating all as we need to rewind for the next call. */
    165 	while ((tl = npf_table_iterate(npf_conf)) != NULL) {
    166 		const char *tname = npf_table_getname(tl);
    167 		if (strcmp(tname, name) == 0) {
    168 			tid = npf_table_getid(tl);
    169 		}
    170 	}
    171 	return tid;
    172 }
    173 
    174 static in_port_t
    175 npfctl_get_singleport(const npfvar_t *vp)
    176 {
    177 	port_range_t *pr;
    178 	in_port_t *port;
    179 
    180 	if (npfvar_get_count(vp) > 1) {
    181 		yyerror("multiple ports are not valid");
    182 	}
    183 	pr = npfvar_get_data(vp, NPFVAR_PORT_RANGE, 0);
    184 	if (pr->pr_start != pr->pr_end) {
    185 		yyerror("port range is not valid");
    186 	}
    187 	port = &pr->pr_start;
    188 	return *port;
    189 }
    190 
    191 static fam_addr_mask_t *
    192 npfctl_get_singlefam(const npfvar_t *vp)
    193 {
    194 	if (npfvar_get_count(vp) > 1) {
    195 		yyerror("multiple addresses are not valid");
    196 	}
    197 	return npfvar_get_data(vp, NPFVAR_FAM, 0);
    198 }
    199 
    200 static bool
    201 npfctl_build_fam(npf_bpf_t *ctx, sa_family_t family,
    202     fam_addr_mask_t *fam, int opts)
    203 {
    204 	/*
    205 	 * If family is specified, address does not match it and the
    206 	 * address is extracted from the interface, then simply ignore.
    207 	 * Otherwise, address of invalid family was passed manually.
    208 	 */
    209 	if (family != AF_UNSPEC && family != fam->fam_family) {
    210 		if (!fam->fam_ifindex) {
    211 			yyerror("specified address is not of the required "
    212 			    "family %d", family);
    213 		}
    214 		return false;
    215 	}
    216 
    217 	family = fam->fam_family;
    218 	if (family != AF_INET && family != AF_INET6) {
    219 		yyerror("family %d is not supported", family);
    220 	}
    221 
    222 	/*
    223 	 * Optimise 0.0.0.0/0 case to be NOP.  Otherwise, address with
    224 	 * zero mask would never match and therefore is not valid.
    225 	 */
    226 	if (fam->fam_mask == 0) {
    227 		static const npf_addr_t zero; /* must be static */
    228 
    229 		if (memcmp(&fam->fam_addr, &zero, sizeof(npf_addr_t))) {
    230 			yyerror("filter criterion would never match");
    231 		}
    232 		return false;
    233 	}
    234 
    235 	npfctl_bpf_cidr(ctx, opts, family, &fam->fam_addr, fam->fam_mask);
    236 	return true;
    237 }
    238 
    239 static void
    240 npfctl_build_vars(npf_bpf_t *ctx, sa_family_t family, npfvar_t *vars, int opts)
    241 {
    242 	const int type = npfvar_get_type(vars, 0);
    243 	size_t i;
    244 
    245 	npfctl_bpf_group(ctx);
    246 	for (i = 0; i < npfvar_get_count(vars); i++) {
    247 		void *data = npfvar_get_data(vars, type, i);
    248 		assert(data != NULL);
    249 
    250 		switch (type) {
    251 		case NPFVAR_FAM: {
    252 			fam_addr_mask_t *fam = data;
    253 			npfctl_build_fam(ctx, family, fam, opts);
    254 			break;
    255 		}
    256 		case NPFVAR_PORT_RANGE: {
    257 			port_range_t *pr = data;
    258 			npfctl_bpf_ports(ctx, opts, pr->pr_start, pr->pr_end);
    259 			break;
    260 		}
    261 		case NPFVAR_TABLE: {
    262 			u_int tid;
    263 			memcpy(&tid, data, sizeof(u_int));
    264 			npfctl_bpf_table(ctx, opts, tid);
    265 			break;
    266 		}
    267 		default:
    268 			assert(false);
    269 		}
    270 	}
    271 	npfctl_bpf_endgroup(ctx);
    272 }
    273 
    274 static void
    275 npfctl_build_proto(npf_bpf_t *ctx, sa_family_t family, const opt_proto_t *op)
    276 {
    277 	const npfvar_t *popts = op->op_opts;
    278 	const int proto = op->op_proto;
    279 
    280 	/* IP version and/or L4 protocol matching. */
    281 	if (family != AF_UNSPEC || proto != -1) {
    282 		npfctl_bpf_proto(ctx, family, proto);
    283 	}
    284 
    285 	switch (proto) {
    286 	case IPPROTO_TCP:
    287 		/* Build TCP flags matching (optional). */
    288 		if (popts) {
    289 			uint8_t *tf, *tf_mask;
    290 
    291 			assert(npfvar_get_count(popts) == 2);
    292 			tf = npfvar_get_data(popts, NPFVAR_TCPFLAG, 0);
    293 			tf_mask = npfvar_get_data(popts, NPFVAR_TCPFLAG, 1);
    294 			npfctl_bpf_tcpfl(ctx, *tf, *tf_mask, false);
    295 		}
    296 		break;
    297 	case IPPROTO_ICMP:
    298 	case IPPROTO_ICMPV6:
    299 		/* Build ICMP/ICMPv6 type and/or code matching. */
    300 		if (popts) {
    301 			int *icmp_type, *icmp_code;
    302 
    303 			assert(npfvar_get_count(popts) == 2);
    304 			icmp_type = npfvar_get_data(popts, NPFVAR_ICMP, 0);
    305 			icmp_code = npfvar_get_data(popts, NPFVAR_ICMP, 1);
    306 			npfctl_bpf_icmp(ctx, *icmp_type, *icmp_code);
    307 		}
    308 		break;
    309 	default:
    310 		/* No options for other protocols. */
    311 		break;
    312 	}
    313 }
    314 
    315 static bool
    316 npfctl_build_code(nl_rule_t *rl, sa_family_t family, const opt_proto_t *op,
    317     const filt_opts_t *fopts)
    318 {
    319 	bool noproto, noaddrs, noports, need_tcpudp = false;
    320 	const addr_port_t *apfrom = &fopts->fo_from;
    321 	const addr_port_t *apto = &fopts->fo_to;
    322 	const int proto = op->op_proto;
    323 	npf_bpf_t *bc;
    324 	size_t len;
    325 
    326 	/* If none specified, then no byte-code. */
    327 	noproto = family == AF_UNSPEC && proto == -1 && !op->op_opts;
    328 	noaddrs = !apfrom->ap_netaddr && !apto->ap_netaddr;
    329 	noports = !apfrom->ap_portrange && !apto->ap_portrange;
    330 	if (noproto && noaddrs && noports) {
    331 		return false;
    332 	}
    333 
    334 	/*
    335 	 * Sanity check: ports can only be used with TCP or UDP protocol.
    336 	 * No filter options are supported for other protocols, only the
    337 	 * IP addresses are allowed.
    338 	 */
    339 	if (!noports) {
    340 		switch (proto) {
    341 		case IPPROTO_TCP:
    342 		case IPPROTO_UDP:
    343 			break;
    344 		case -1:
    345 			need_tcpudp = true;
    346 			break;
    347 		default:
    348 			yyerror("invalid filter options for protocol %d", proto);
    349 		}
    350 	}
    351 
    352 	bc = npfctl_bpf_create();
    353 
    354 	/* Build layer 4 protocol blocks. */
    355 	npfctl_build_proto(bc, family, op);
    356 
    357 	/*
    358 	 * If this is a stateful rule and TCP flags are not specified,
    359 	 * then add "flags S/SAFR" filter for TCP protocol case.
    360 	 */
    361 	if ((npf_rule_getattr(rl) & NPF_RULE_STATEFUL) != 0 &&
    362 	    (proto == -1 || (proto == IPPROTO_TCP && !op->op_opts))) {
    363 		npfctl_bpf_tcpfl(bc, TH_SYN,
    364 		    TH_SYN | TH_ACK | TH_FIN | TH_RST, proto == -1);
    365 	}
    366 
    367 	/* Build IP address blocks. */
    368 	npfctl_build_vars(bc, family, apfrom->ap_netaddr, MATCH_SRC);
    369 	npfctl_build_vars(bc, family, apto->ap_netaddr, MATCH_DST);
    370 
    371 	/* Build port-range blocks. */
    372 	if (need_tcpudp) {
    373 		/* TCP/UDP check for the ports. */
    374 		npfctl_bpf_group(bc);
    375 		npfctl_bpf_proto(bc, AF_UNSPEC, IPPROTO_TCP);
    376 		npfctl_bpf_proto(bc, AF_UNSPEC, IPPROTO_UDP);
    377 		npfctl_bpf_endgroup(bc);
    378 	}
    379 	npfctl_build_vars(bc, family, apfrom->ap_portrange, MATCH_SRC);
    380 	npfctl_build_vars(bc, family, apto->ap_portrange, MATCH_DST);
    381 
    382 	/* Set the byte-code marks, if any. */
    383 	const void *bmarks = npfctl_bpf_bmarks(bc, &len);
    384 	if (npf_rule_setinfo(rl, bmarks, len) == -1) {
    385 		errx(EXIT_FAILURE, "npf_rule_setinfo failed");
    386 	}
    387 
    388 	/* Complete BPF byte-code and pass to the rule. */
    389 	struct bpf_program *bf = npfctl_bpf_complete(bc);
    390 	if (bf == NULL) {
    391 		npfctl_bpf_destroy(bc);
    392 		return true;
    393 	}
    394 	len = bf->bf_len * sizeof(struct bpf_insn);
    395 
    396 	if (npf_rule_setcode(rl, NPF_CODE_BPF, bf->bf_insns, len) == -1) {
    397 		errx(EXIT_FAILURE, "npf_rule_setcode failed");
    398 	}
    399 	npfctl_dump_bpf(bf);
    400 	npfctl_bpf_destroy(bc);
    401 
    402 	return true;
    403 }
    404 
    405 static void
    406 npfctl_build_pcap(nl_rule_t *rl, const char *filter)
    407 {
    408 	const size_t maxsnaplen = 64 * 1024;
    409 	struct bpf_program bf;
    410 	size_t len;
    411 
    412 	if (pcap_compile_nopcap(maxsnaplen, DLT_RAW, &bf,
    413 	    filter, 1, PCAP_NETMASK_UNKNOWN) == -1) {
    414 		yyerror("invalid pcap-filter(7) syntax");
    415 	}
    416 	len = bf.bf_len * sizeof(struct bpf_insn);
    417 
    418 	if (npf_rule_setcode(rl, NPF_CODE_BPF, bf.bf_insns, len) == -1) {
    419 		errx(EXIT_FAILURE, "npf_rule_setcode failed");
    420 	}
    421 	npfctl_dump_bpf(&bf);
    422 	pcap_freecode(&bf);
    423 }
    424 
    425 static void
    426 npfctl_build_rpcall(nl_rproc_t *rp, const char *name, npfvar_t *args)
    427 {
    428 	npf_extmod_t *extmod;
    429 	nl_ext_t *extcall;
    430 	int error;
    431 
    432 	extmod = npf_extmod_get(name, &extcall);
    433 	if (extmod == NULL) {
    434 		yyerror("unknown rule procedure '%s'", name);
    435 	}
    436 
    437 	for (size_t i = 0; i < npfvar_get_count(args); i++) {
    438 		const char *param, *value;
    439 		proc_param_t *p;
    440 
    441 		p = npfvar_get_data(args, NPFVAR_PROC_PARAM, i);
    442 		param = p->pp_param;
    443 		value = p->pp_value;
    444 
    445 		error = npf_extmod_param(extmod, extcall, param, value);
    446 		switch (error) {
    447 		case EINVAL:
    448 			yyerror("invalid parameter '%s'", param);
    449 		default:
    450 			break;
    451 		}
    452 	}
    453 	error = npf_rproc_extcall(rp, extcall);
    454 	if (error) {
    455 		yyerror(error == EEXIST ?
    456 		    "duplicate procedure call" : "unexpected error");
    457 	}
    458 }
    459 
    460 /*
    461  * npfctl_build_rproc: create and insert a rule procedure.
    462  */
    463 void
    464 npfctl_build_rproc(const char *name, npfvar_t *procs)
    465 {
    466 	nl_rproc_t *rp;
    467 	size_t i;
    468 
    469 	rp = npf_rproc_create(name);
    470 	if (rp == NULL) {
    471 		errx(EXIT_FAILURE, "%s failed", __func__);
    472 	}
    473 	npf_rproc_insert(npf_conf, rp);
    474 
    475 	for (i = 0; i < npfvar_get_count(procs); i++) {
    476 		proc_call_t *pc = npfvar_get_data(procs, NPFVAR_PROC, i);
    477 		npfctl_build_rpcall(rp, pc->pc_name, pc->pc_opts);
    478 	}
    479 }
    480 
    481 void
    482 npfctl_build_maprset(const char *name, int attr, const char *ifname)
    483 {
    484 	const int attr_di = (NPF_RULE_IN | NPF_RULE_OUT);
    485 	nl_rule_t *rl;
    486 
    487 	/* If no direction is not specified, then both. */
    488 	if ((attr & attr_di) == 0) {
    489 		attr |= attr_di;
    490 	}
    491 	/* Allow only "in/out" attributes. */
    492 	attr = NPF_RULE_GROUP | NPF_RULE_GROUP | (attr & attr_di);
    493 	rl = npf_rule_create(name, attr, ifname);
    494 	npf_nat_insert(npf_conf, rl, NPF_PRI_LAST);
    495 }
    496 
    497 /*
    498  * npfctl_build_group: create a group, insert into the global ruleset,
    499  * update the current group pointer and increase the nesting level.
    500  */
    501 void
    502 npfctl_build_group(const char *name, int attr, const char *ifname, bool def)
    503 {
    504 	const int attr_di = (NPF_RULE_IN | NPF_RULE_OUT);
    505 	nl_rule_t *rl;
    506 
    507 	if (def || (attr & attr_di) == 0) {
    508 		attr |= attr_di;
    509 	}
    510 
    511 	rl = npf_rule_create(name, attr | NPF_RULE_GROUP, ifname);
    512 	npf_rule_setprio(rl, NPF_PRI_LAST);
    513 	if (def) {
    514 		if (defgroup) {
    515 			yyerror("multiple default groups are not valid");
    516 		}
    517 		if (rule_nesting_level) {
    518 			yyerror("default group can only be at the top level");
    519 		}
    520 		defgroup = rl;
    521 	} else {
    522 		nl_rule_t *cg = current_group[rule_nesting_level];
    523 		npf_rule_insert(npf_conf, cg, rl);
    524 	}
    525 
    526 	/* Set the current group and increase the nesting level. */
    527 	if (rule_nesting_level >= MAX_RULE_NESTING) {
    528 		yyerror("rule nesting limit reached");
    529 	}
    530 	current_group[++rule_nesting_level] = rl;
    531 }
    532 
    533 void
    534 npfctl_build_group_end(void)
    535 {
    536 	assert(rule_nesting_level > 0);
    537 	current_group[rule_nesting_level--] = NULL;
    538 }
    539 
    540 /*
    541  * npfctl_build_rule: create a rule, build byte-code from filter options,
    542  * if any, and insert into the ruleset of current group, or set the rule.
    543  */
    544 void
    545 npfctl_build_rule(uint32_t attr, const char *ifname, sa_family_t family,
    546     const opt_proto_t *op, const filt_opts_t *fopts,
    547     const char *pcap_filter, const char *rproc)
    548 {
    549 	nl_rule_t *rl;
    550 
    551 	attr |= (npf_conf ? 0 : NPF_RULE_DYNAMIC);
    552 
    553 	rl = npf_rule_create(NULL, attr, ifname);
    554 	if (pcap_filter) {
    555 		npfctl_build_pcap(rl, pcap_filter);
    556 	} else {
    557 		npfctl_build_code(rl, family, op, fopts);
    558 	}
    559 
    560 	if (rproc) {
    561 		npf_rule_setproc(rl, rproc);
    562 	}
    563 
    564 	if (npf_conf) {
    565 		nl_rule_t *cg = current_group[rule_nesting_level];
    566 
    567 		if (rproc && !npf_rproc_exists_p(npf_conf, rproc)) {
    568 			yyerror("rule procedure '%s' is not defined", rproc);
    569 		}
    570 		assert(cg != NULL);
    571 		npf_rule_setprio(rl, NPF_PRI_LAST);
    572 		npf_rule_insert(npf_conf, cg, rl);
    573 	} else {
    574 		/* We have parsed a single rule - set it. */
    575 		the_rule = rl;
    576 	}
    577 }
    578 
    579 /*
    580  * npfctl_build_nat: create a single NAT policy of a specified
    581  * type with a given filter options.
    582  */
    583 static nl_nat_t *
    584 npfctl_build_nat(int type, const char *ifname, const addr_port_t *ap,
    585     const filt_opts_t *fopts, u_int flags)
    586 {
    587 	const opt_proto_t op = { .op_proto = -1, .op_opts = NULL };
    588 	fam_addr_mask_t *am = npfctl_get_singlefam(ap->ap_netaddr);
    589 	in_port_t port;
    590 	nl_nat_t *nat;
    591 
    592 	if (ap->ap_portrange) {
    593 		port = npfctl_get_singleport(ap->ap_portrange);
    594 		flags &= ~NPF_NAT_PORTMAP;
    595 		flags |= NPF_NAT_PORTS;
    596 	} else {
    597 		port = 0;
    598 	}
    599 
    600 	nat = npf_nat_create(type, flags, ifname, am->fam_family,
    601 	    &am->fam_addr, am->fam_mask, port);
    602 	npfctl_build_code(nat, am->fam_family, &op, fopts);
    603 	npf_nat_insert(npf_conf, nat, NPF_PRI_LAST);
    604 	return nat;
    605 }
    606 
    607 /*
    608  * npfctl_build_natseg: validate and create NAT policies.
    609  */
    610 void
    611 npfctl_build_natseg(int sd, int type, const char *ifname,
    612     const addr_port_t *ap1, const addr_port_t *ap2,
    613     const filt_opts_t *fopts, u_int algo)
    614 {
    615 	fam_addr_mask_t *am1 = NULL, *am2 = NULL;
    616 	nl_nat_t *nt1 = NULL, *nt2 = NULL;
    617 	filt_opts_t imfopts;
    618 	uint16_t adj = 0;
    619 	u_int flags;
    620 	bool binat;
    621 
    622 	assert(ifname != NULL);
    623 
    624 	/*
    625 	 * Bi-directional NAT is a combination of inbound NAT and outbound
    626 	 * NAT policies with the translation segments inverted respectively.
    627 	 */
    628 	binat = (NPF_NATIN | NPF_NATOUT) == type;
    629 
    630 	switch (sd) {
    631 	case NPFCTL_NAT_DYNAMIC:
    632 		/*
    633 		 * Dynamic NAT: traditional NAPT is expected.  Unless it
    634 		 * is bi-directional NAT, perform port mapping.
    635 		 */
    636 		flags = !binat ? (NPF_NAT_PORTS | NPF_NAT_PORTMAP) : 0;
    637 		break;
    638 	case NPFCTL_NAT_STATIC:
    639 		/* Static NAT: mechanic translation. */
    640 		flags = NPF_NAT_STATIC;
    641 		break;
    642 	default:
    643 		abort();
    644 	}
    645 
    646 	/*
    647 	 * Validate the mappings and their configuration.
    648 	 */
    649 
    650 	if ((type & NPF_NATIN) != 0) {
    651 		if (!ap1->ap_netaddr)
    652 			yyerror("inbound network segment is not specified");
    653 		am1 = npfctl_get_singlefam(ap1->ap_netaddr);
    654 	}
    655 	if ((type & NPF_NATOUT) != 0) {
    656 		if (!ap2->ap_netaddr)
    657 			yyerror("outbound network segment is not specified");
    658 		am2 = npfctl_get_singlefam(ap2->ap_netaddr);
    659 	}
    660 
    661 	switch (algo) {
    662 	case NPF_ALGO_NPT66:
    663 		if (am1 == NULL || am2 == NULL)
    664 			yyerror("1:1 mapping of two segments must be "
    665 			    "used for NPTv6");
    666 		if (am1->fam_mask != am2->fam_mask)
    667 			yyerror("asymmetric translation is not supported");
    668 		adj = npfctl_npt66_calcadj(am1->fam_mask,
    669 		    &am1->fam_addr, &am2->fam_addr);
    670 		break;
    671 	default:
    672 		if ((am1 && am1->fam_mask != NPF_NO_NETMASK) ||
    673 		    (am2 && am2->fam_mask != NPF_NO_NETMASK))
    674 			yyerror("net-to-net translation is not supported");
    675 		break;
    676 	}
    677 
    678 	/*
    679 	 * If the filter criteria is not specified explicitly, apply implicit
    680 	 * filtering according to the given network segments.
    681 	 *
    682 	 * Note: filled below, depending on the type.
    683 	 */
    684 	if (__predict_true(!fopts)) {
    685 		fopts = &imfopts;
    686 	}
    687 
    688 	if (type & NPF_NATIN) {
    689 		memset(&imfopts, 0, sizeof(filt_opts_t));
    690 		memcpy(&imfopts.fo_to, ap2, sizeof(addr_port_t));
    691 		nt1 = npfctl_build_nat(NPF_NATIN, ifname, ap1, fopts, flags);
    692 	}
    693 	if (type & NPF_NATOUT) {
    694 		memset(&imfopts, 0, sizeof(filt_opts_t));
    695 		memcpy(&imfopts.fo_from, ap1, sizeof(addr_port_t));
    696 		nt2 = npfctl_build_nat(NPF_NATOUT, ifname, ap2, fopts, flags);
    697 	}
    698 
    699 	if (algo == NPF_ALGO_NPT66) {
    700 		npf_nat_setnpt66(nt1, ~adj);
    701 		npf_nat_setnpt66(nt2, adj);
    702 	}
    703 }
    704 
    705 /*
    706  * npfctl_fill_table: fill NPF table with entries from a specified file.
    707  */
    708 static void
    709 npfctl_fill_table(nl_table_t *tl, u_int type, const char *fname)
    710 {
    711 	struct cdbw *cdbw = NULL;	/* XXX: gcc */
    712 	char *buf = NULL;
    713 	int l = 0;
    714 	FILE *fp;
    715 	size_t n;
    716 
    717 	if (type == NPF_TABLE_CDB && (cdbw = cdbw_open()) == NULL) {
    718 		err(EXIT_FAILURE, "cdbw_open");
    719 	}
    720 	fp = fopen(fname, "r");
    721 	if (fp == NULL) {
    722 		err(EXIT_FAILURE, "open '%s'", fname);
    723 	}
    724 	while (l++, getline(&buf, &n, fp) != -1) {
    725 		fam_addr_mask_t fam;
    726 		int alen;
    727 
    728 		if (*buf == '\n' || *buf == '#') {
    729 			continue;
    730 		}
    731 
    732 		if (!npfctl_parse_cidr(buf, &fam, &alen)) {
    733 			errx(EXIT_FAILURE,
    734 			    "%s:%d: invalid table entry", fname, l);
    735 		}
    736 		if (type != NPF_TABLE_TREE && fam.fam_mask != NPF_NO_NETMASK) {
    737 			errx(EXIT_FAILURE, "%s:%d: mask used with the "
    738 			    "non-tree table", fname, l);
    739 		}
    740 
    741 		/*
    742 		 * Create and add a table entry.
    743 		 */
    744 		if (type == NPF_TABLE_CDB) {
    745 			const npf_addr_t *addr = &fam.fam_addr;
    746 			if (cdbw_put(cdbw, addr, alen, addr, alen) == -1) {
    747 				err(EXIT_FAILURE, "cdbw_put");
    748 			}
    749 		} else {
    750 			npf_table_add_entry(tl, fam.fam_family,
    751 			    &fam.fam_addr, fam.fam_mask);
    752 		}
    753 	}
    754 	if (buf != NULL) {
    755 		free(buf);
    756 	}
    757 
    758 	if (type == NPF_TABLE_CDB) {
    759 		struct stat sb;
    760 		char sfn[32];
    761 		void *cdb;
    762 		int fd;
    763 
    764 		strncpy(sfn, "/tmp/npfcdb.XXXXXX", sizeof(sfn));
    765 		sfn[sizeof(sfn) - 1] = '\0';
    766 
    767 		if ((fd = mkstemp(sfn)) == -1) {
    768 			err(EXIT_FAILURE, "mkstemp");
    769 		}
    770 		unlink(sfn);
    771 
    772 		if (cdbw_output(cdbw, fd, "npf-table-cdb", NULL) == -1) {
    773 			err(EXIT_FAILURE, "cdbw_output");
    774 		}
    775 		cdbw_close(cdbw);
    776 
    777 		if (fstat(fd, &sb) == -1) {
    778 			err(EXIT_FAILURE, "fstat");
    779 		}
    780 		if ((cdb = mmap(NULL, sb.st_size, PROT_READ,
    781 		    MAP_FILE | MAP_PRIVATE, fd, 0)) == MAP_FAILED) {
    782 			err(EXIT_FAILURE, "mmap");
    783 		}
    784 		npf_table_setdata(tl, cdb, sb.st_size);
    785 
    786 		close(fd);
    787 	}
    788 }
    789 
    790 /*
    791  * npfctl_build_table: create an NPF table, add to the configuration and,
    792  * if required, fill with contents from a file.
    793  */
    794 void
    795 npfctl_build_table(const char *tname, u_int type, const char *fname)
    796 {
    797 	static unsigned tid = 0;
    798 	nl_table_t *tl;
    799 
    800 	tl = npf_table_create(tname, tid++, type);
    801 	assert(tl != NULL);
    802 
    803 	if (npf_table_insert(npf_conf, tl)) {
    804 		yyerror("table '%s' is already defined", tname);
    805 	}
    806 
    807 	if (fname) {
    808 		npfctl_fill_table(tl, type, fname);
    809 	} else if (type == NPF_TABLE_CDB) {
    810 		errx(EXIT_FAILURE, "tables of cdb type must be static");
    811 	}
    812 }
    813 
    814 /*
    815  * npfctl_build_alg: create an NPF application level gateway and add it
    816  * to the configuration.
    817  */
    818 void
    819 npfctl_build_alg(const char *al_name)
    820 {
    821 	if (_npf_alg_load(npf_conf, al_name) != 0) {
    822 		errx(EXIT_FAILURE, "ALG '%s' already loaded", al_name);
    823 	}
    824 }
    825 
    826 static void
    827 npfctl_dump_bpf(struct bpf_program *bf)
    828 {
    829 	if (npf_debug) {
    830 		extern char *yytext;
    831 		extern int yylineno;
    832 
    833 		int rule_line = yylineno - (int)(*yytext == '\n');
    834 		printf("\nRULE AT LINE %d\n", rule_line);
    835 		bpf_dump(bf, 0);
    836 	}
    837 }
    838