Home | History | Annotate | Line # | Download | only in npfctl
npf_build.c revision 1.42
      1 /*	$NetBSD: npf_build.c,v 1.42 2016/12/27 22:35:33 rmind 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.42 2016/12/27 22:35:33 rmind 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, (opts & MATCH_INVERT) != 0);
    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 	unsigned opts;
    325 	size_t len;
    326 
    327 	/* If none specified, then no byte-code. */
    328 	noproto = family == AF_UNSPEC && proto == -1 && !op->op_opts;
    329 	noaddrs = !apfrom->ap_netaddr && !apto->ap_netaddr;
    330 	noports = !apfrom->ap_portrange && !apto->ap_portrange;
    331 	if (noproto && noaddrs && noports) {
    332 		return false;
    333 	}
    334 
    335 	/*
    336 	 * Sanity check: ports can only be used with TCP or UDP protocol.
    337 	 * No filter options are supported for other protocols, only the
    338 	 * IP addresses are allowed.
    339 	 */
    340 	if (!noports) {
    341 		switch (proto) {
    342 		case IPPROTO_TCP:
    343 		case IPPROTO_UDP:
    344 			break;
    345 		case -1:
    346 			need_tcpudp = true;
    347 			break;
    348 		default:
    349 			yyerror("invalid filter options for protocol %d", proto);
    350 		}
    351 	}
    352 
    353 	bc = npfctl_bpf_create();
    354 
    355 	/* Build layer 4 protocol blocks. */
    356 	npfctl_build_proto(bc, family, op);
    357 
    358 	/*
    359 	 * If this is a stateful rule and TCP flags are not specified,
    360 	 * then add "flags S/SAFR" filter for TCP protocol case.
    361 	 */
    362 	if ((npf_rule_getattr(rl) & NPF_RULE_STATEFUL) != 0 &&
    363 	    (proto == -1 || (proto == IPPROTO_TCP && !op->op_opts))) {
    364 		npfctl_bpf_tcpfl(bc, TH_SYN,
    365 		    TH_SYN | TH_ACK | TH_FIN | TH_RST, proto == -1);
    366 	}
    367 
    368 	/* Build IP address blocks. */
    369 	opts = MATCH_SRC | (fopts->fo_finvert ? MATCH_INVERT : 0);
    370 	npfctl_build_vars(bc, family, apfrom->ap_netaddr, opts);
    371 	opts = MATCH_DST | (fopts->fo_tinvert ? MATCH_INVERT : 0);
    372 	npfctl_build_vars(bc, family, apto->ap_netaddr, opts);
    373 
    374 	/* Build port-range blocks. */
    375 	if (need_tcpudp) {
    376 		/* TCP/UDP check for the ports. */
    377 		npfctl_bpf_group(bc);
    378 		npfctl_bpf_proto(bc, AF_UNSPEC, IPPROTO_TCP);
    379 		npfctl_bpf_proto(bc, AF_UNSPEC, IPPROTO_UDP);
    380 		npfctl_bpf_endgroup(bc, false);
    381 	}
    382 	npfctl_build_vars(bc, family, apfrom->ap_portrange, MATCH_SRC);
    383 	npfctl_build_vars(bc, family, apto->ap_portrange, MATCH_DST);
    384 
    385 	/* Set the byte-code marks, if any. */
    386 	const void *bmarks = npfctl_bpf_bmarks(bc, &len);
    387 	if (npf_rule_setinfo(rl, bmarks, len) == -1) {
    388 		errx(EXIT_FAILURE, "npf_rule_setinfo failed");
    389 	}
    390 
    391 	/* Complete BPF byte-code and pass to the rule. */
    392 	struct bpf_program *bf = npfctl_bpf_complete(bc);
    393 	if (bf == NULL) {
    394 		npfctl_bpf_destroy(bc);
    395 		return true;
    396 	}
    397 	len = bf->bf_len * sizeof(struct bpf_insn);
    398 
    399 	if (npf_rule_setcode(rl, NPF_CODE_BPF, bf->bf_insns, len) == -1) {
    400 		errx(EXIT_FAILURE, "npf_rule_setcode failed");
    401 	}
    402 	npfctl_dump_bpf(bf);
    403 	npfctl_bpf_destroy(bc);
    404 
    405 	return true;
    406 }
    407 
    408 static void
    409 npfctl_build_pcap(nl_rule_t *rl, const char *filter)
    410 {
    411 	const size_t maxsnaplen = 64 * 1024;
    412 	struct bpf_program bf;
    413 	size_t len;
    414 
    415 	if (pcap_compile_nopcap(maxsnaplen, DLT_RAW, &bf,
    416 	    filter, 1, PCAP_NETMASK_UNKNOWN) == -1) {
    417 		yyerror("invalid pcap-filter(7) syntax");
    418 	}
    419 	len = bf.bf_len * sizeof(struct bpf_insn);
    420 
    421 	if (npf_rule_setcode(rl, NPF_CODE_BPF, bf.bf_insns, len) == -1) {
    422 		errx(EXIT_FAILURE, "npf_rule_setcode failed");
    423 	}
    424 	npfctl_dump_bpf(&bf);
    425 	pcap_freecode(&bf);
    426 }
    427 
    428 static void
    429 npfctl_build_rpcall(nl_rproc_t *rp, const char *name, npfvar_t *args)
    430 {
    431 	npf_extmod_t *extmod;
    432 	nl_ext_t *extcall;
    433 	int error;
    434 
    435 	extmod = npf_extmod_get(name, &extcall);
    436 	if (extmod == NULL) {
    437 		yyerror("unknown rule procedure '%s'", name);
    438 	}
    439 
    440 	for (size_t i = 0; i < npfvar_get_count(args); i++) {
    441 		const char *param, *value;
    442 		proc_param_t *p;
    443 
    444 		p = npfvar_get_data(args, NPFVAR_PROC_PARAM, i);
    445 		param = p->pp_param;
    446 		value = p->pp_value;
    447 
    448 		error = npf_extmod_param(extmod, extcall, param, value);
    449 		switch (error) {
    450 		case EINVAL:
    451 			yyerror("invalid parameter '%s'", param);
    452 		default:
    453 			break;
    454 		}
    455 	}
    456 	error = npf_rproc_extcall(rp, extcall);
    457 	if (error) {
    458 		yyerror(error == EEXIST ?
    459 		    "duplicate procedure call" : "unexpected error");
    460 	}
    461 }
    462 
    463 /*
    464  * npfctl_build_rproc: create and insert a rule procedure.
    465  */
    466 void
    467 npfctl_build_rproc(const char *name, npfvar_t *procs)
    468 {
    469 	nl_rproc_t *rp;
    470 	size_t i;
    471 
    472 	rp = npf_rproc_create(name);
    473 	if (rp == NULL) {
    474 		errx(EXIT_FAILURE, "%s failed", __func__);
    475 	}
    476 	npf_rproc_insert(npf_conf, rp);
    477 
    478 	for (i = 0; i < npfvar_get_count(procs); i++) {
    479 		proc_call_t *pc = npfvar_get_data(procs, NPFVAR_PROC, i);
    480 		npfctl_build_rpcall(rp, pc->pc_name, pc->pc_opts);
    481 	}
    482 }
    483 
    484 void
    485 npfctl_build_maprset(const char *name, int attr, const char *ifname)
    486 {
    487 	const int attr_di = (NPF_RULE_IN | NPF_RULE_OUT);
    488 	nl_rule_t *rl;
    489 
    490 	/* If no direction is not specified, then both. */
    491 	if ((attr & attr_di) == 0) {
    492 		attr |= attr_di;
    493 	}
    494 	/* Allow only "in/out" attributes. */
    495 	attr = NPF_RULE_GROUP | NPF_RULE_GROUP | (attr & attr_di);
    496 	rl = npf_rule_create(name, attr, ifname);
    497 	npf_nat_insert(npf_conf, rl, NPF_PRI_LAST);
    498 }
    499 
    500 /*
    501  * npfctl_build_group: create a group, insert into the global ruleset,
    502  * update the current group pointer and increase the nesting level.
    503  */
    504 void
    505 npfctl_build_group(const char *name, int attr, const char *ifname, bool def)
    506 {
    507 	const int attr_di = (NPF_RULE_IN | NPF_RULE_OUT);
    508 	nl_rule_t *rl;
    509 
    510 	if (def || (attr & attr_di) == 0) {
    511 		attr |= attr_di;
    512 	}
    513 
    514 	rl = npf_rule_create(name, attr | NPF_RULE_GROUP, ifname);
    515 	npf_rule_setprio(rl, NPF_PRI_LAST);
    516 	if (def) {
    517 		if (defgroup) {
    518 			yyerror("multiple default groups are not valid");
    519 		}
    520 		if (rule_nesting_level) {
    521 			yyerror("default group can only be at the top level");
    522 		}
    523 		defgroup = rl;
    524 	} else {
    525 		nl_rule_t *cg = current_group[rule_nesting_level];
    526 		npf_rule_insert(npf_conf, cg, rl);
    527 	}
    528 
    529 	/* Set the current group and increase the nesting level. */
    530 	if (rule_nesting_level >= MAX_RULE_NESTING) {
    531 		yyerror("rule nesting limit reached");
    532 	}
    533 	current_group[++rule_nesting_level] = rl;
    534 }
    535 
    536 void
    537 npfctl_build_group_end(void)
    538 {
    539 	assert(rule_nesting_level > 0);
    540 	current_group[rule_nesting_level--] = NULL;
    541 }
    542 
    543 /*
    544  * npfctl_build_rule: create a rule, build byte-code from filter options,
    545  * if any, and insert into the ruleset of current group, or set the rule.
    546  */
    547 void
    548 npfctl_build_rule(uint32_t attr, const char *ifname, sa_family_t family,
    549     const opt_proto_t *op, const filt_opts_t *fopts,
    550     const char *pcap_filter, const char *rproc)
    551 {
    552 	nl_rule_t *rl;
    553 
    554 	attr |= (npf_conf ? 0 : NPF_RULE_DYNAMIC);
    555 
    556 	rl = npf_rule_create(NULL, attr, ifname);
    557 	if (pcap_filter) {
    558 		npfctl_build_pcap(rl, pcap_filter);
    559 	} else {
    560 		npfctl_build_code(rl, family, op, fopts);
    561 	}
    562 
    563 	if (rproc) {
    564 		npf_rule_setproc(rl, rproc);
    565 	}
    566 
    567 	if (npf_conf) {
    568 		nl_rule_t *cg = current_group[rule_nesting_level];
    569 
    570 		if (rproc && !npf_rproc_exists_p(npf_conf, rproc)) {
    571 			yyerror("rule procedure '%s' is not defined", rproc);
    572 		}
    573 		assert(cg != NULL);
    574 		npf_rule_setprio(rl, NPF_PRI_LAST);
    575 		npf_rule_insert(npf_conf, cg, rl);
    576 	} else {
    577 		/* We have parsed a single rule - set it. */
    578 		the_rule = rl;
    579 	}
    580 }
    581 
    582 /*
    583  * npfctl_build_nat: create a single NAT policy of a specified
    584  * type with a given filter options.
    585  */
    586 static nl_nat_t *
    587 npfctl_build_nat(int type, const char *ifname, const addr_port_t *ap,
    588     const filt_opts_t *fopts, u_int flags)
    589 {
    590 	const opt_proto_t op = { .op_proto = -1, .op_opts = NULL };
    591 	fam_addr_mask_t *am = npfctl_get_singlefam(ap->ap_netaddr);
    592 	in_port_t port;
    593 	nl_nat_t *nat;
    594 
    595 	if (ap->ap_portrange) {
    596 		port = npfctl_get_singleport(ap->ap_portrange);
    597 		flags &= ~NPF_NAT_PORTMAP;
    598 		flags |= NPF_NAT_PORTS;
    599 	} else {
    600 		port = 0;
    601 	}
    602 
    603 	nat = npf_nat_create(type, flags, ifname, am->fam_family,
    604 	    &am->fam_addr, am->fam_mask, port);
    605 	npfctl_build_code(nat, am->fam_family, &op, fopts);
    606 	npf_nat_insert(npf_conf, nat, NPF_PRI_LAST);
    607 	return nat;
    608 }
    609 
    610 /*
    611  * npfctl_build_natseg: validate and create NAT policies.
    612  */
    613 void
    614 npfctl_build_natseg(int sd, int type, const char *ifname,
    615     const addr_port_t *ap1, const addr_port_t *ap2,
    616     const filt_opts_t *fopts, u_int algo)
    617 {
    618 	fam_addr_mask_t *am1 = NULL, *am2 = NULL;
    619 	nl_nat_t *nt1 = NULL, *nt2 = NULL;
    620 	filt_opts_t imfopts;
    621 	uint16_t adj = 0;
    622 	u_int flags;
    623 	bool binat;
    624 
    625 	assert(ifname != NULL);
    626 
    627 	/*
    628 	 * Bi-directional NAT is a combination of inbound NAT and outbound
    629 	 * NAT policies with the translation segments inverted respectively.
    630 	 */
    631 	binat = (NPF_NATIN | NPF_NATOUT) == type;
    632 
    633 	switch (sd) {
    634 	case NPFCTL_NAT_DYNAMIC:
    635 		/*
    636 		 * Dynamic NAT: traditional NAPT is expected.  Unless it
    637 		 * is bi-directional NAT, perform port mapping.
    638 		 */
    639 		flags = !binat ? (NPF_NAT_PORTS | NPF_NAT_PORTMAP) : 0;
    640 		break;
    641 	case NPFCTL_NAT_STATIC:
    642 		/* Static NAT: mechanic translation. */
    643 		flags = NPF_NAT_STATIC;
    644 		break;
    645 	default:
    646 		abort();
    647 	}
    648 
    649 	/*
    650 	 * Validate the mappings and their configuration.
    651 	 */
    652 
    653 	if ((type & NPF_NATIN) != 0) {
    654 		if (!ap1->ap_netaddr)
    655 			yyerror("inbound network segment is not specified");
    656 		am1 = npfctl_get_singlefam(ap1->ap_netaddr);
    657 	}
    658 	if ((type & NPF_NATOUT) != 0) {
    659 		if (!ap2->ap_netaddr)
    660 			yyerror("outbound network segment is not specified");
    661 		am2 = npfctl_get_singlefam(ap2->ap_netaddr);
    662 	}
    663 
    664 	switch (algo) {
    665 	case NPF_ALGO_NPT66:
    666 		if (am1 == NULL || am2 == NULL)
    667 			yyerror("1:1 mapping of two segments must be "
    668 			    "used for NPTv6");
    669 		if (am1->fam_mask != am2->fam_mask)
    670 			yyerror("asymmetric translation is not supported");
    671 		adj = npfctl_npt66_calcadj(am1->fam_mask,
    672 		    &am1->fam_addr, &am2->fam_addr);
    673 		break;
    674 	default:
    675 		if ((am1 && am1->fam_mask != NPF_NO_NETMASK) ||
    676 		    (am2 && am2->fam_mask != NPF_NO_NETMASK))
    677 			yyerror("net-to-net translation is not supported");
    678 		break;
    679 	}
    680 
    681 	/*
    682 	 * If the filter criteria is not specified explicitly, apply implicit
    683 	 * filtering according to the given network segments.
    684 	 *
    685 	 * Note: filled below, depending on the type.
    686 	 */
    687 	if (__predict_true(!fopts)) {
    688 		fopts = &imfopts;
    689 	}
    690 
    691 	if (type & NPF_NATIN) {
    692 		memset(&imfopts, 0, sizeof(filt_opts_t));
    693 		memcpy(&imfopts.fo_to, ap2, sizeof(addr_port_t));
    694 		nt1 = npfctl_build_nat(NPF_NATIN, ifname, ap1, fopts, flags);
    695 	}
    696 	if (type & NPF_NATOUT) {
    697 		memset(&imfopts, 0, sizeof(filt_opts_t));
    698 		memcpy(&imfopts.fo_from, ap1, sizeof(addr_port_t));
    699 		nt2 = npfctl_build_nat(NPF_NATOUT, ifname, ap2, fopts, flags);
    700 	}
    701 
    702 	if (algo == NPF_ALGO_NPT66) {
    703 		npf_nat_setnpt66(nt1, ~adj);
    704 		npf_nat_setnpt66(nt2, adj);
    705 	}
    706 }
    707 
    708 /*
    709  * npfctl_fill_table: fill NPF table with entries from a specified file.
    710  */
    711 static void
    712 npfctl_fill_table(nl_table_t *tl, u_int type, const char *fname)
    713 {
    714 	struct cdbw *cdbw = NULL;	/* XXX: gcc */
    715 	char *buf = NULL;
    716 	int l = 0;
    717 	FILE *fp;
    718 	size_t n;
    719 
    720 	if (type == NPF_TABLE_CDB && (cdbw = cdbw_open()) == NULL) {
    721 		err(EXIT_FAILURE, "cdbw_open");
    722 	}
    723 	fp = fopen(fname, "r");
    724 	if (fp == NULL) {
    725 		err(EXIT_FAILURE, "open '%s'", fname);
    726 	}
    727 	while (l++, getline(&buf, &n, fp) != -1) {
    728 		fam_addr_mask_t fam;
    729 		int alen;
    730 
    731 		if (*buf == '\n' || *buf == '#') {
    732 			continue;
    733 		}
    734 
    735 		if (!npfctl_parse_cidr(buf, &fam, &alen)) {
    736 			errx(EXIT_FAILURE,
    737 			    "%s:%d: invalid table entry", fname, l);
    738 		}
    739 		if (type != NPF_TABLE_TREE && fam.fam_mask != NPF_NO_NETMASK) {
    740 			errx(EXIT_FAILURE, "%s:%d: mask used with the "
    741 			    "non-tree table", fname, l);
    742 		}
    743 
    744 		/*
    745 		 * Create and add a table entry.
    746 		 */
    747 		if (type == NPF_TABLE_CDB) {
    748 			const npf_addr_t *addr = &fam.fam_addr;
    749 			if (cdbw_put(cdbw, addr, alen, addr, alen) == -1) {
    750 				err(EXIT_FAILURE, "cdbw_put");
    751 			}
    752 		} else {
    753 			npf_table_add_entry(tl, fam.fam_family,
    754 			    &fam.fam_addr, fam.fam_mask);
    755 		}
    756 	}
    757 	if (buf != NULL) {
    758 		free(buf);
    759 	}
    760 
    761 	if (type == NPF_TABLE_CDB) {
    762 		struct stat sb;
    763 		char sfn[32];
    764 		void *cdb;
    765 		int fd;
    766 
    767 		strncpy(sfn, "/tmp/npfcdb.XXXXXX", sizeof(sfn));
    768 		sfn[sizeof(sfn) - 1] = '\0';
    769 
    770 		if ((fd = mkstemp(sfn)) == -1) {
    771 			err(EXIT_FAILURE, "mkstemp");
    772 		}
    773 		unlink(sfn);
    774 
    775 		if (cdbw_output(cdbw, fd, "npf-table-cdb", NULL) == -1) {
    776 			err(EXIT_FAILURE, "cdbw_output");
    777 		}
    778 		cdbw_close(cdbw);
    779 
    780 		if (fstat(fd, &sb) == -1) {
    781 			err(EXIT_FAILURE, "fstat");
    782 		}
    783 		if ((cdb = mmap(NULL, sb.st_size, PROT_READ,
    784 		    MAP_FILE | MAP_PRIVATE, fd, 0)) == MAP_FAILED) {
    785 			err(EXIT_FAILURE, "mmap");
    786 		}
    787 		npf_table_setdata(tl, cdb, sb.st_size);
    788 
    789 		close(fd);
    790 	}
    791 }
    792 
    793 /*
    794  * npfctl_build_table: create an NPF table, add to the configuration and,
    795  * if required, fill with contents from a file.
    796  */
    797 void
    798 npfctl_build_table(const char *tname, u_int type, const char *fname)
    799 {
    800 	static unsigned tid = 0;
    801 	nl_table_t *tl;
    802 
    803 	tl = npf_table_create(tname, tid++, type);
    804 	assert(tl != NULL);
    805 
    806 	if (npf_table_insert(npf_conf, tl)) {
    807 		yyerror("table '%s' is already defined", tname);
    808 	}
    809 
    810 	if (fname) {
    811 		npfctl_fill_table(tl, type, fname);
    812 	} else if (type == NPF_TABLE_CDB) {
    813 		errx(EXIT_FAILURE, "tables of cdb type must be static");
    814 	}
    815 }
    816 
    817 /*
    818  * npfctl_build_alg: create an NPF application level gateway and add it
    819  * to the configuration.
    820  */
    821 void
    822 npfctl_build_alg(const char *al_name)
    823 {
    824 	if (_npf_alg_load(npf_conf, al_name) != 0) {
    825 		errx(EXIT_FAILURE, "ALG '%s' already loaded", al_name);
    826 	}
    827 }
    828 
    829 static void
    830 npfctl_dump_bpf(struct bpf_program *bf)
    831 {
    832 	if (npf_debug) {
    833 		extern char *yytext;
    834 		extern int yylineno;
    835 
    836 		int rule_line = yylineno - (int)(*yytext == '\n');
    837 		printf("\nRULE AT LINE %d\n", rule_line);
    838 		bpf_dump(bf, 0);
    839 	}
    840 }
    841