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