Home | History | Annotate | Line # | Download | only in npfctl
npf_show.c revision 1.4
      1 /*	$NetBSD: npf_show.c,v 1.4 2013/11/12 00:46:34 rmind Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2013 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by 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  * NPF configuration printing.
     34  *
     35  * Each rule having BPF byte-code has a binary description.
     36  */
     37 
     38 #include <sys/cdefs.h>
     39 __RCSID("$NetBSD: npf_show.c,v 1.4 2013/11/12 00:46:34 rmind Exp $");
     40 
     41 #include <sys/socket.h>
     42 #include <netinet/in.h>
     43 #include <netinet/tcp.h>
     44 #include <net/if.h>
     45 
     46 #include <stdio.h>
     47 #include <stdlib.h>
     48 #include <string.h>
     49 #include <stdbool.h>
     50 #include <inttypes.h>
     51 #include <errno.h>
     52 #include <err.h>
     53 
     54 #include "npfctl.h"
     55 
     56 typedef struct {
     57 	nl_config_t *	conf;
     58 	FILE *		fp;
     59 	long		fpos;
     60 } npf_conf_info_t;
     61 
     62 static npf_conf_info_t	stdout_ctx = { .fp = stdout, .fpos = 0 };
     63 
     64 static void	print_indent(npf_conf_info_t *, u_int);
     65 static void	print_linesep(npf_conf_info_t *);
     66 
     67 /*
     68  * Helper routines to print various pieces of information.
     69  */
     70 
     71 static void
     72 print_indent(npf_conf_info_t *ctx, u_int level)
     73 {
     74 	if (level == 0) { /* XXX */
     75 		print_linesep(ctx);
     76 	}
     77 	while (level--)
     78 		fprintf(ctx->fp, "\t");
     79 }
     80 
     81 static void
     82 print_linesep(npf_conf_info_t *ctx)
     83 {
     84 	if (ftell(ctx->fp) != ctx->fpos) {
     85 		fputs("\n", ctx->fp);
     86 		ctx->fpos = ftell(ctx->fp);
     87 	}
     88 }
     89 
     90 static size_t
     91 tcpflags2string(char *buf, u_int tfl)
     92 {
     93 	u_int i = 0;
     94 
     95 	if (tfl & TH_FIN)	buf[i++] = 'F';
     96 	if (tfl & TH_SYN)	buf[i++] = 'S';
     97 	if (tfl & TH_RST)	buf[i++] = 'R';
     98 	if (tfl & TH_PUSH)	buf[i++] = 'P';
     99 	if (tfl & TH_ACK)	buf[i++] = 'A';
    100 	if (tfl & TH_URG)	buf[i++] = 'U';
    101 	if (tfl & TH_ECE)	buf[i++] = 'E';
    102 	if (tfl & TH_CWR)	buf[i++] = 'C';
    103 	buf[i] = '\0';
    104 	return i;
    105 }
    106 
    107 static char *
    108 print_family(npf_conf_info_t *ctx, const uint32_t *words)
    109 {
    110 	const int af = words[0];
    111 
    112 	switch (af) {
    113 	case AF_INET:
    114 		return estrdup("inet");
    115 	case AF_INET6:
    116 		return estrdup("inet6");
    117 	default:
    118 		errx(EXIT_FAILURE, "invalid byte-code mark (family)");
    119 	}
    120 	return NULL;
    121 }
    122 
    123 static char *
    124 print_address(npf_conf_info_t *ctx, const uint32_t *words)
    125 {
    126 	const int af = *words++;
    127 	const u_int mask = *words++;
    128 	const npf_addr_t *addr;
    129 	int alen = 0;
    130 
    131 	switch (af) {
    132 	case AF_INET:
    133 		alen = 4;
    134 		break;
    135 	case AF_INET6:
    136 		alen = 16;
    137 		break;
    138 	default:
    139 		errx(EXIT_FAILURE, "invalid byte-code mark (address)");
    140 	}
    141 	addr = (const npf_addr_t *)words;
    142 	return npfctl_print_addrmask(alen, addr, mask);
    143 }
    144 
    145 static char *
    146 print_number(npf_conf_info_t *ctx, const uint32_t *words)
    147 {
    148 	char *p;
    149 	easprintf(&p, "%u", words[0]);
    150 	return p;
    151 }
    152 
    153 static char *
    154 print_table(npf_conf_info_t *ctx, const uint32_t *words)
    155 {
    156 	unsigned tid = words[0];
    157 	nl_table_t *tl;
    158 	char *p;
    159 
    160 	while ((tl = npf_table_iterate(ctx->conf)) != NULL) {
    161 		if (npf_table_getid(tl) == tid)
    162 			break;
    163 	}
    164 	easprintf(&p, "%s", npf_table_getname(tl));
    165 	return p;
    166 }
    167 
    168 static char *
    169 print_proto(npf_conf_info_t *ctx, const uint32_t *words)
    170 {
    171 	switch (words[0]) {
    172 	case IPPROTO_TCP:
    173 		return estrdup("tcp");
    174 	case IPPROTO_UDP:
    175 		return estrdup("udp");
    176 	case IPPROTO_ICMP:
    177 		return estrdup("icmp");
    178 	case IPPROTO_ICMPV6:
    179 		return estrdup("ipv6-icmp");
    180 	}
    181 	return print_number(ctx, words);
    182 }
    183 
    184 static char *
    185 print_tcpflags(npf_conf_info_t *ctx, const uint32_t *words)
    186 {
    187 	const u_int tf = words[0], tf_mask = words[1];
    188 	char buf[16];
    189 
    190 	size_t n = tcpflags2string(buf, tf);
    191 	if (tf != tf_mask) {
    192 		buf[n++] = '/';
    193 		tcpflags2string(buf + n, tf_mask);
    194 	}
    195 	return estrdup(buf);
    196 }
    197 
    198 static char *
    199 print_portrange(npf_conf_info_t *ctx, const uint32_t *words)
    200 {
    201 	u_int fport = words[0], tport = words[1];
    202 	char *p;
    203 
    204 	if (fport != tport) {
    205 		easprintf(&p, "%u:%u", fport, tport);
    206 	} else {
    207 		easprintf(&p, "%u", fport);
    208 	}
    209 	return p;
    210 }
    211 
    212 /*
    213  * The main keyword mapping tables defining the syntax:
    214  * - Mapping of rule attributes (flags) to the keywords.
    215  * - Mapping of the byte-code marks to the keywords.
    216  */
    217 
    218 #define	F(name)		__CONCAT(NPF_RULE_, name)
    219 #define	NAME_AT		2
    220 
    221 static const struct attr_keyword_mapent {
    222 	uint32_t	mask;
    223 	uint32_t	flags;
    224 	const char *	val;
    225 } attr_keyword_map[] = {
    226 	{ F(GROUP)|F(DYNAMIC),	F(GROUP),		"group"		},
    227 	{ F(DYNAMIC),		F(DYNAMIC),		"ruleset"	},
    228 	{ F(GROUP)|F(PASS),	0,			"block"		},
    229 	{ F(GROUP)|F(PASS),	F(PASS),		"pass"		},
    230 	{ F(RETRST)|F(RETICMP),	F(RETRST)|F(RETICMP),	"return"	},
    231 	{ F(RETRST)|F(RETICMP),	F(RETRST),		"return-rst"	},
    232 	{ F(RETRST)|F(RETICMP),	F(RETICMP),		"return-icmp"	},
    233 	{ F(STATEFUL),		F(STATEFUL),		"stateful"	},
    234 	{ F(DIMASK),		F(IN),			"in"		},
    235 	{ F(DIMASK),		F(OUT),			"out"		},
    236 	{ F(FINAL),		F(FINAL),		"final"		},
    237 };
    238 
    239 static const struct mark_keyword_mapent {
    240 	u_int		mark;
    241 	const char *	token;
    242 	const char *	sep;
    243 	char *		(*printfn)(npf_conf_info_t *, const uint32_t *);
    244 	u_int		fwords;
    245 } mark_keyword_map[] = {
    246 	{ BM_IPVER,	"family %s",	NULL,		print_family,	1 },
    247 	{ BM_PROTO,	"proto %s",	NULL,		print_proto,	1 },
    248 	{ BM_TCPFL,	"flags %s",	NULL,		print_tcpflags,	2 },
    249 	{ BM_ICMP_TYPE,	"icmp-type %s",	NULL,		print_number,	1 },
    250 	{ BM_ICMP_CODE,	"code %s",	NULL,		print_number,	1 },
    251 
    252 	{ BM_SRC_CIDR,	"from %s",	", ",		print_address,	6 },
    253 	{ BM_SRC_TABLE,	"from <%s>",	NULL,		print_table,	1 },
    254 	{ BM_SRC_PORTS,	"port %s",	", ",		print_portrange,2 },
    255 
    256 	{ BM_DST_CIDR,	"to %s",	", ",		print_address,	6 },
    257 	{ BM_DST_TABLE,	"to <%s>",	NULL,		print_table,	1 },
    258 	{ BM_DST_PORTS,	"port %s",	", ",		print_portrange,2 },
    259 };
    260 
    261 static const char * __attribute__((format_arg(2)))
    262 verified_fmt(const char *fmt, const char *t __unused)
    263 {
    264 	return fmt;
    265 }
    266 
    267 static char *
    268 scan_marks(npf_conf_info_t *ctx, const struct mark_keyword_mapent *mk,
    269     const uint32_t *marks, size_t mlen)
    270 {
    271 	char buf[2048], *vals[256], *p;
    272 	size_t nvals = 0;
    273 
    274 	/* Scan for the marks and extract the values. */
    275 	mlen /= sizeof(uint32_t);
    276 	while (mlen > 2) {
    277 		const uint32_t m = *marks++;
    278 		const u_int nwords = *marks++;
    279 
    280 		if ((mlen -= 2) < nwords) {
    281 			errx(EXIT_FAILURE, "byte-code marking inconsistency");
    282 		}
    283 		if (m == mk->mark) {
    284 			/* Value is processed by the print function. */
    285 			assert(mk->fwords == nwords);
    286 			vals[nvals++] = mk->printfn(ctx, marks);
    287 		}
    288 		marks += nwords;
    289 		mlen -= nwords;
    290 	}
    291 	if (nvals == 0) {
    292 		return NULL;
    293 	}
    294 	assert(nvals == 1 || mk->sep != NULL);
    295 
    296 	/*
    297 	 * Join all the values and print.  Add curly brackets if there
    298 	 * is more than value and it can be a set.
    299 	 */
    300 	if (!join(buf, sizeof(buf), nvals, vals, mk->sep ? mk->sep : "")) {
    301 		errx(EXIT_FAILURE, "out of memory while parsing the rule");
    302 	}
    303 	easprintf(&p, nvals > 1 ? "{ %s }" : "%s", buf);
    304 
    305 	for (u_int i = 0; i < nvals; i++) {
    306 		free(vals[i]);
    307 	}
    308 	return p;
    309 }
    310 
    311 static void
    312 npfctl_print_filter(npf_conf_info_t *ctx, nl_rule_t *rl)
    313 {
    314 	const void *marks;
    315 	size_t mlen;
    316 
    317 	/* BPF filter criteria described by the byte-code marks. */
    318 	marks = npf_rule_getinfo(rl, &mlen);
    319 	for (u_int i = 0; i < __arraycount(mark_keyword_map); i++) {
    320 		const struct mark_keyword_mapent *mk = &mark_keyword_map[i];
    321 		char *val;
    322 
    323 		if ((val = scan_marks(ctx, mk, marks, mlen)) != NULL) {
    324 			fprintf(ctx->fp, verified_fmt(mk->token, "%s"), val);
    325 			fputs(" ", ctx->fp);
    326 			free(val);
    327 		}
    328 	}
    329 	if (!mlen) {
    330 		fputs("all ", ctx->fp);
    331 	}
    332 }
    333 
    334 static void
    335 npfctl_print_rule(npf_conf_info_t *ctx, nl_rule_t *rl)
    336 {
    337 	const uint32_t attr = npf_rule_getattr(rl);
    338 	const char *rproc, *ifname, *name;
    339 
    340 	/* Rule attributes/flags. */
    341 	for (u_int i = 0; i < __arraycount(attr_keyword_map); i++) {
    342 		const struct attr_keyword_mapent *ak = &attr_keyword_map[i];
    343 
    344 		if (i == NAME_AT && (name = npf_rule_getname(rl)) != NULL) {
    345 			fprintf(ctx->fp, "\"%s\" ", name);
    346 		}
    347 		if ((attr & ak->mask) == ak->flags) {
    348 			fprintf(ctx->fp, "%s ", ak->val);
    349 		}
    350 	}
    351 	if ((ifname = npf_rule_getinterface(rl)) != NULL) {
    352 		fprintf(ctx->fp, "on %s ", ifname);
    353 	}
    354 
    355 	if ((attr & (NPF_RULE_GROUP | NPF_RULE_DYNAMIC)) == NPF_RULE_GROUP) {
    356 		/* Group; done. */
    357 		fputs("\n", ctx->fp);
    358 		return;
    359 	}
    360 
    361 	/* Print filter criteria. */
    362 	npfctl_print_filter(ctx, rl);
    363 
    364 	/* Rule procedure. */
    365 	if ((rproc = npf_rule_getproc(rl)) != NULL) {
    366 		fprintf(ctx->fp, "apply \"%s\"", rproc);
    367 	}
    368 	fputs("\n", ctx->fp);
    369 }
    370 
    371 static void
    372 npfctl_print_nat(npf_conf_info_t *ctx, nl_nat_t *nt)
    373 {
    374 	nl_rule_t *rl = (nl_nat_t *)nt;
    375 	const char *ifname, *seg1, *seg2, *arrow;
    376 	npf_addr_t addr;
    377 	in_port_t port;
    378 	size_t alen;
    379 	char *seg;
    380 
    381 	/* Get the interface. */
    382 	ifname = npf_rule_getinterface(rl);
    383 	assert(ifname != NULL);
    384 
    385 	/* Get the translation address (and port, if used). */
    386 	npf_nat_getmap(nt, &addr, &alen, &port);
    387 	seg = npfctl_print_addrmask(alen, &addr, NPF_NO_NETMASK);
    388 	if (port) {
    389 		char *p;
    390 		easprintf(&p, "%s port %u", seg, port);
    391 		free(seg), seg = p;
    392 	}
    393 	seg1 = seg2 = "any";
    394 
    395 	/* Get the NAT type and determine the translation segment. */
    396 	switch (npf_nat_gettype(nt)) {
    397 	case NPF_NATIN:
    398 		arrow = "<-";
    399 		seg1 = seg;
    400 		break;
    401 	case NPF_NATOUT:
    402 		arrow = "->";
    403 		seg2 = seg;
    404 		break;
    405 	default:
    406 		assert(false);
    407 	}
    408 
    409 	/* Print out the NAT policy with the filter criteria. */
    410 	fprintf(ctx->fp, "map %s dynamic %s %s %s pass ",
    411 	    ifname, seg1, arrow, seg2);
    412 	npfctl_print_filter(ctx, rl);
    413 	fputs("\n", ctx->fp);
    414 	free(seg);
    415 }
    416 
    417 static void
    418 npfctl_print_table(npf_conf_info_t *ctx, nl_table_t *tl)
    419 {
    420 	const char *name = npf_table_getname(tl);
    421 	const int type = npf_table_gettype(tl);
    422 
    423 	fprintf(ctx->fp, "table <%s> type %s\n", name,
    424 	    (type == NPF_TABLE_HASH) ? "hash" :
    425 	    (type == NPF_TABLE_TREE) ? "tree" :
    426 	    "unknown");
    427 }
    428 
    429 int
    430 npfctl_config_show(int fd)
    431 {
    432 	npf_conf_info_t *ctx = &stdout_ctx;
    433 	nl_config_t *ncf;
    434 	bool active, loaded;
    435 
    436 	if (fd) {
    437 		ncf = npf_config_retrieve(fd, &active, &loaded);
    438 		if (ncf == NULL) {
    439 			return errno;
    440 		}
    441 		fprintf(ctx->fp, "Filtering:\t%s\nConfiguration:\t%s\n",
    442 		    active ? "active" : "inactive",
    443 		    loaded ? "loaded" : "empty");
    444 		print_linesep(ctx);
    445 	} else {
    446 		npfctl_config_send(0, NULL);
    447 		ncf = npfctl_config_ref();
    448 		loaded = true;
    449 	}
    450 	ctx->conf = ncf;
    451 
    452 	if (loaded) {
    453 		nl_rule_t *rl;
    454 		nl_rproc_t *rp;
    455 		nl_nat_t *nt;
    456 		nl_table_t *tl;
    457 		u_int level;
    458 
    459 		while ((tl = npf_table_iterate(ncf)) != NULL) {
    460 			npfctl_print_table(ctx, tl);
    461 		}
    462 		print_linesep(ctx);
    463 
    464 		while ((rp = npf_rproc_iterate(ncf)) != NULL) {
    465 			const char *rpname = npf_rproc_getname(rp);
    466 			fprintf(ctx->fp, "procedure \"%s\"\n", rpname);
    467 		}
    468 		print_linesep(ctx);
    469 
    470 		while ((nt = npf_nat_iterate(ncf)) != NULL) {
    471 			npfctl_print_nat(ctx, nt);
    472 		}
    473 		print_linesep(ctx);
    474 
    475 		while ((rl = npf_rule_iterate(ncf, &level)) != NULL) {
    476 			print_indent(ctx, level);
    477 			npfctl_print_rule(ctx, rl);
    478 		}
    479 		print_linesep(ctx);
    480 	}
    481 	npf_config_destroy(ncf);
    482 	return 0;
    483 }
    484 
    485 int
    486 npfctl_ruleset_show(int fd, const char *ruleset_name)
    487 {
    488 	npf_conf_info_t *ctx = &stdout_ctx;
    489 	nl_config_t *ncf;
    490 	nl_rule_t *rl;
    491 	u_int level;
    492 	int error;
    493 
    494 	ncf = npf_config_create();
    495 	ctx->conf = ncf;
    496 
    497 	if ((error = _npf_ruleset_list(fd, ruleset_name, ncf)) != 0) {
    498 		return error;
    499 	}
    500 	while ((rl = npf_rule_iterate(ncf, &level)) != NULL) {
    501 		npfctl_print_rule(ctx, rl);
    502 	}
    503 	npf_config_destroy(ncf);
    504 	return error;
    505 }
    506