Home | History | Annotate | Line # | Download | only in npfctl
npfctl.c revision 1.10.2.11
      1 /*	$NetBSD: npfctl.c,v 1.10.2.11 2013/01/07 16:51:07 riz Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2009-2012 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 #include <sys/cdefs.h>
     33 __RCSID("$NetBSD: npfctl.c,v 1.10.2.11 2013/01/07 16:51:07 riz Exp $");
     34 
     35 #include <sys/ioctl.h>
     36 #include <sys/stat.h>
     37 #include <sys/types.h>
     38 
     39 #include <stdio.h>
     40 #include <stdlib.h>
     41 #include <string.h>
     42 #include <err.h>
     43 #include <fcntl.h>
     44 #include <unistd.h>
     45 #include <errno.h>
     46 
     47 #include "npfctl.h"
     48 
     49 extern int		yylineno, yycolumn;
     50 extern const char *	yyfilename;
     51 extern int		yyparse(void);
     52 extern void		yyrestart(FILE *);
     53 
     54 enum {
     55 	NPFCTL_START,
     56 	NPFCTL_STOP,
     57 	NPFCTL_RELOAD,
     58 	NPFCTL_SHOWCONF,
     59 	NPFCTL_FLUSH,
     60 	NPFCTL_VALIDATE,
     61 	NPFCTL_TABLE,
     62 	NPFCTL_STATS,
     63 	NPFCTL_SESSIONS_SAVE,
     64 	NPFCTL_SESSIONS_LOAD,
     65 };
     66 
     67 static const struct operations_s {
     68 	const char *		cmd;
     69 	int			action;
     70 } operations[] = {
     71 	/* Start, stop, reload */
     72 	{	"start",		NPFCTL_START		},
     73 	{	"stop",			NPFCTL_STOP		},
     74 	{	"reload",		NPFCTL_RELOAD		},
     75 	{	"show",			NPFCTL_SHOWCONF,	},
     76 	{	"flush",		NPFCTL_FLUSH		},
     77 	{	"valid",		NPFCTL_VALIDATE		},
     78 	/* Table */
     79 	{	"table",		NPFCTL_TABLE		},
     80 	/* Stats */
     81 	{	"stats",		NPFCTL_STATS		},
     82 	/* Sessions */
     83 	{	"sess-save",		NPFCTL_SESSIONS_SAVE	},
     84 	{	"sess-load",		NPFCTL_SESSIONS_LOAD	},
     85 	/* --- */
     86 	{	NULL,			0			}
     87 };
     88 
     89 __dead static void
     90 usage(void)
     91 {
     92 	const char *progname = getprogname();
     93 
     94 	fprintf(stderr,
     95 	    "usage:\t%s [ start | stop | reload | flush | show | stats ]\n",
     96 	    progname);
     97 	fprintf(stderr,
     98 	    "\t%s ( sess-save | sess-load )\n",
     99 	    progname);
    100 	fprintf(stderr,
    101 	    "\t%s table <tid> { add | rem | test } <address/mask>\n",
    102 	    progname);
    103 	fprintf(stderr,
    104 	    "\t%s table <tid> { list | flush }\n",
    105 	    progname);
    106 
    107 	exit(EXIT_FAILURE);
    108 }
    109 
    110 static void
    111 npfctl_parsecfg(const char *cfg)
    112 {
    113 	FILE *fp;
    114 
    115 	fp = fopen(cfg, "r");
    116 	if (fp == NULL) {
    117 		err(EXIT_FAILURE, "open '%s'", cfg);
    118 	}
    119 	yyrestart(fp);
    120 	yylineno = 1;
    121 	yycolumn = 0;
    122 	yyfilename = cfg;
    123 	yyparse();
    124 	fclose(fp);
    125 }
    126 
    127 static int
    128 npfctl_print_stats(int fd)
    129 {
    130 	static const struct stats_s {
    131 		/* Note: -1 indicates a new section. */
    132 		int		index;
    133 		const char *	name;
    134 	} stats[] = {
    135 		{ -1, "Packets passed"					},
    136 		{ NPF_STAT_PASS_DEFAULT,	"default pass"		},
    137 		{ NPF_STAT_PASS_RULESET,	"ruleset pass"		},
    138 		{ NPF_STAT_PASS_SESSION,	"session pass"		},
    139 
    140 		{ -1, "Packets blocked"					},
    141 		{ NPF_STAT_BLOCK_DEFAULT,	"default block"		},
    142 		{ NPF_STAT_BLOCK_RULESET,	"ruleset block"		},
    143 
    144 		{ -1, "Session and NAT entries"				},
    145 		{ NPF_STAT_SESSION_CREATE,	"session allocations"	},
    146 		{ NPF_STAT_SESSION_DESTROY,	"session destructions"	},
    147 		{ NPF_STAT_NAT_CREATE,		"NAT entry allocations"	},
    148 		{ NPF_STAT_NAT_DESTROY,		"NAT entry destructions"},
    149 
    150 		{ -1, "Network buffers"					},
    151 		{ NPF_STAT_NBUF_NONCONTIG,	"non-contiguous cases"	},
    152 		{ NPF_STAT_NBUF_CONTIG_FAIL,	"contig alloc failures"	},
    153 
    154 		{ -1, "Invalid packet state cases"			},
    155 		{ NPF_STAT_INVALID_STATE,	"cases in total"	},
    156 		{ NPF_STAT_INVALID_STATE_TCP1,	"TCP case I"		},
    157 		{ NPF_STAT_INVALID_STATE_TCP2,	"TCP case II"		},
    158 		{ NPF_STAT_INVALID_STATE_TCP3,	"TCP case III"		},
    159 
    160 		{ -1, "Packet race cases"				},
    161 		{ NPF_STAT_RACE_NAT,		"NAT association race"	},
    162 		{ NPF_STAT_RACE_SESSION,	"duplicate session race"},
    163 
    164 		{ -1, "Fragmentation"					},
    165 		{ NPF_STAT_FRAGMENTS,		"fragments"		},
    166 		{ NPF_STAT_REASSEMBLY,		"reassembled"		},
    167 		{ NPF_STAT_REASSFAIL,		"failed reassembly"	},
    168 
    169 		{ -1, "Other"						},
    170 		{ NPF_STAT_ERROR,		"unexpected errors"	},
    171 	};
    172 	uint64_t *st = ecalloc(1, NPF_STATS_SIZE);
    173 
    174 	if (ioctl(fd, IOC_NPF_STATS, &st) != 0) {
    175 		err(EXIT_FAILURE, "ioctl(IOC_NPF_STATS)");
    176 	}
    177 
    178 	for (unsigned i = 0; i < __arraycount(stats); i++) {
    179 		const char *sname = stats[i].name;
    180 		int sidx = stats[i].index;
    181 
    182 		if (sidx == -1) {
    183 			printf("%s:\n", sname);
    184 		} else {
    185 			printf("\t%"PRIu64" %s\n", st[sidx], sname);
    186 		}
    187 	}
    188 
    189 	free(st);
    190 	return 0;
    191 }
    192 
    193 void
    194 npfctl_print_error(const nl_error_t *ne)
    195 {
    196 	static const char *ncode_errors[] = {
    197 		[-NPF_ERR_OPCODE]	= "invalid instruction",
    198 		[-NPF_ERR_JUMP]		= "invalid jump",
    199 		[-NPF_ERR_REG]		= "invalid register",
    200 		[-NPF_ERR_INVAL]	= "invalid argument value",
    201 		[-NPF_ERR_RANGE]	= "processing out of range"
    202 	};
    203 	const int nc_err = ne->ne_ncode_error;
    204 	const char *srcfile = ne->ne_source_file;
    205 
    206 	if (srcfile) {
    207 		warnx("source %s line %d", srcfile, ne->ne_source_line);
    208 	}
    209 	if (nc_err) {
    210 		warnx("n-code error (%d): %s at offset 0x%x",
    211 		    nc_err, ncode_errors[-nc_err], ne->ne_ncode_errat);
    212 	}
    213 	if (ne->ne_id) {
    214 		warnx("object: %d", ne->ne_id);
    215 	}
    216 }
    217 
    218 char *
    219 npfctl_print_addrmask(int alen, npf_addr_t *addr, npf_netmask_t mask)
    220 {
    221 	struct sockaddr_storage ss;
    222 	char *buf = ecalloc(1, 64);
    223 	int len;
    224 
    225 	switch (alen) {
    226 	case 4: {
    227 		struct sockaddr_in *sin = (void *)&ss;
    228 		sin->sin_len = sizeof(*sin);
    229 		sin->sin_family = AF_INET;
    230 		sin->sin_port = 0;
    231 		memcpy(&sin->sin_addr, addr, sizeof(sin->sin_addr));
    232 		break;
    233 	}
    234 	case 16: {
    235 		struct sockaddr_in6 *sin6 = (void *)&ss;
    236 		sin6->sin6_len = sizeof(*sin6);
    237 		sin6->sin6_family = AF_INET6;
    238 		sin6->sin6_port = 0;
    239 		memcpy(&sin6->sin6_addr, addr, sizeof(sin6->sin6_addr));
    240 		break;
    241 	}
    242 	default:
    243 		assert(false);
    244 	}
    245 	len = sockaddr_snprintf(buf, 64, "%a", (struct sockaddr *)&ss);
    246 	if (mask) {
    247 		snprintf(&buf[len], 64 - len, "/%u", mask);
    248 	}
    249 	return buf;
    250 }
    251 
    252 __dead static void
    253 npfctl_table(int fd, int argc, char **argv)
    254 {
    255 	static const struct tblops_s {
    256 		const char *	cmd;
    257 		int		action;
    258 	} tblops[] = {
    259 		{ "add",	NPF_IOCTL_TBLENT_ADD		},
    260 		{ "rem",	NPF_IOCTL_TBLENT_REM		},
    261 		{ "test",	NPF_IOCTL_TBLENT_LOOKUP		},
    262 		{ "list",	NPF_IOCTL_TBLENT_LIST		},
    263 		{ NULL,		0				}
    264 	};
    265 	npf_ioctl_table_t nct;
    266 	fam_addr_mask_t fam;
    267 	size_t buflen = 512;
    268 	char *cmd, *arg = NULL; /* XXX gcc */
    269 	int n, alen;
    270 
    271 	/* Default action is list. */
    272 	memset(&nct, 0, sizeof(npf_ioctl_table_t));
    273 	nct.nct_tid = atoi(argv[0]);
    274 	cmd = argv[1];
    275 
    276 	for (n = 0; tblops[n].cmd != NULL; n++) {
    277 		if (strcmp(cmd, tblops[n].cmd) != 0) {
    278 			continue;
    279 		}
    280 		nct.nct_action = tblops[n].action;
    281 		break;
    282 	}
    283 	if (tblops[n].cmd == NULL) {
    284 		errx(EXIT_FAILURE, "invalid command '%s'", cmd);
    285 	}
    286 	if (nct.nct_action != NPF_IOCTL_TBLENT_LIST) {
    287 		if (argc < 3) {
    288 			usage();
    289 		}
    290 		arg = argv[2];
    291 	}
    292 again:
    293 	if (nct.nct_action == NPF_IOCTL_TBLENT_LIST) {
    294 		nct.nct_data.buf.buf = ecalloc(1, buflen);
    295 		nct.nct_data.buf.len = buflen;
    296 	} else {
    297 		if (!npfctl_parse_cidr(arg, &fam, &alen)) {
    298 			errx(EXIT_FAILURE, "invalid CIDR '%s'", arg);
    299 		}
    300 		nct.nct_data.ent.alen = alen;
    301 		memcpy(&nct.nct_data.ent.addr, &fam.fam_addr, alen);
    302 		nct.nct_data.ent.mask = fam.fam_mask;
    303 	}
    304 
    305 	if (ioctl(fd, IOC_NPF_TABLE, &nct) != -1) {
    306 		errno = 0;
    307 	}
    308 	switch (errno) {
    309 	case 0:
    310 		break;
    311 	case EEXIST:
    312 		errx(EXIT_FAILURE, "entry already exists or is conflicting");
    313 	case ENOENT:
    314 		errx(EXIT_FAILURE, "no matching entry was not found");
    315 	case EINVAL:
    316 		errx(EXIT_FAILURE, "invalid address, mask or table ID");
    317 	case ENOMEM:
    318 		if (nct.nct_action == NPF_IOCTL_TBLENT_LIST) {
    319 			/* XXX */
    320 			free(nct.nct_data.buf.buf);
    321 			buflen <<= 1;
    322 			goto again;
    323 		}
    324 		/* FALLTHROUGH */
    325 	default:
    326 		err(EXIT_FAILURE, "ioctl");
    327 	}
    328 
    329 	if (nct.nct_action == NPF_IOCTL_TBLENT_LIST) {
    330 		npf_ioctl_ent_t *ent = nct.nct_data.buf.buf;
    331 		char *buf;
    332 
    333 		while (nct.nct_data.buf.len--) {
    334 			if (!ent->alen)
    335 				break;
    336 			buf = npfctl_print_addrmask(ent->alen,
    337 			    &ent->addr, ent->mask);
    338 			puts(buf);
    339 			ent++;
    340 		}
    341 		free(nct.nct_data.buf.buf);
    342 	} else {
    343 		printf("%s: %s\n", getprogname(),
    344 		    nct.nct_action == NPF_IOCTL_TBLENT_LOOKUP ?
    345 		    "matching entry found" : "success");
    346 	}
    347 	exit(EXIT_SUCCESS);
    348 }
    349 
    350 static void
    351 npfctl(int action, int argc, char **argv)
    352 {
    353 	int fd, ret, ver, boolval;
    354 
    355 	fd = open(NPF_DEV_PATH, O_RDONLY);
    356 	if (fd == -1) {
    357 		err(EXIT_FAILURE, "cannot open '%s'", NPF_DEV_PATH);
    358 	}
    359 	ret = ioctl(fd, IOC_NPF_VERSION, &ver);
    360 	if (ret == -1) {
    361 		err(EXIT_FAILURE, "ioctl");
    362 	}
    363 	if (ver != NPF_VERSION) {
    364 		errx(EXIT_FAILURE,
    365 		    "incompatible NPF interface version (%d, kernel %d)\n"
    366 		    "Hint: update userland?", NPF_VERSION, ver);
    367 	}
    368 	switch (action) {
    369 	case NPFCTL_START:
    370 		boolval = true;
    371 		ret = ioctl(fd, IOC_NPF_SWITCH, &boolval);
    372 		break;
    373 	case NPFCTL_STOP:
    374 		boolval = false;
    375 		ret = ioctl(fd, IOC_NPF_SWITCH, &boolval);
    376 		break;
    377 	case NPFCTL_RELOAD:
    378 		npfctl_config_init(false);
    379 		npfctl_parsecfg(argc < 3 ? NPF_CONF_PATH : argv[2]);
    380 		ret = npfctl_config_send(fd, NULL);
    381 		if (ret) {
    382 			errx(EXIT_FAILURE, "ioctl: %s", strerror(ret));
    383 		}
    384 		break;
    385 	case NPFCTL_SHOWCONF:
    386 		ret = npfctl_config_show(fd);
    387 		break;
    388 	case NPFCTL_FLUSH:
    389 		ret = npf_config_flush(fd);
    390 		break;
    391 	case NPFCTL_VALIDATE:
    392 		npfctl_config_init(false);
    393 		npfctl_parsecfg(argc < 3 ? NPF_CONF_PATH : argv[2]);
    394 		ret = npfctl_config_show(0);
    395 		break;
    396 	case NPFCTL_TABLE:
    397 		if ((argc -= 2) < 2) {
    398 			usage();
    399 		}
    400 		argv += 2;
    401 		npfctl_table(fd, argc, argv);
    402 		break;
    403 	case NPFCTL_STATS:
    404 		ret = npfctl_print_stats(fd);
    405 		break;
    406 	case NPFCTL_SESSIONS_SAVE:
    407 		if (npf_sessions_recv(fd, NPF_SESSDB_PATH) != 0) {
    408 			errx(EXIT_FAILURE, "could not save sessions to '%s'",
    409 			    NPF_SESSDB_PATH);
    410 		}
    411 		break;
    412 	case NPFCTL_SESSIONS_LOAD:
    413 		if (npf_sessions_send(fd, NPF_SESSDB_PATH) != 0) {
    414 			errx(EXIT_FAILURE, "no sessions loaded from '%s'",
    415 			    NPF_SESSDB_PATH);
    416 		}
    417 		break;
    418 	}
    419 	if (ret) {
    420 		err(EXIT_FAILURE, "ioctl");
    421 	}
    422 	close(fd);
    423 }
    424 
    425 int
    426 main(int argc, char **argv)
    427 {
    428 	char *cmd;
    429 
    430 	if (argc < 2) {
    431 		usage();
    432 	}
    433 	cmd = argv[1];
    434 
    435 	if (strcmp(cmd, "debug") == 0) {
    436 		const char *cfg = argc > 2 ? argv[2] : "/etc/npf.conf";
    437 		const char *out = argc > 3 ? argv[3] : "/tmp/npf.plist";
    438 
    439 		npfctl_config_init(true);
    440 		npfctl_parsecfg(cfg);
    441 		npfctl_config_send(0, out);
    442 		return EXIT_SUCCESS;
    443 	}
    444 
    445 	/* Find and call the subroutine. */
    446 	for (int n = 0; operations[n].cmd != NULL; n++) {
    447 		const char *opcmd = operations[n].cmd;
    448 		if (strncmp(cmd, opcmd, strlen(opcmd)) != 0)
    449 			continue;
    450 		npfctl(operations[n].action, argc, argv);
    451 		return EXIT_SUCCESS;
    452 	}
    453 	usage();
    454 }
    455