Home | History | Annotate | Line # | Download | only in npfctl
npfctl.c revision 1.25
      1 /*	$NetBSD: npfctl.c,v 1.25 2012/12/10 02:26:04 rmind 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.25 2012/12/10 02:26:04 rmind 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, "Invalid packet state cases"			},
    151 		{ NPF_STAT_INVALID_STATE,	"cases in total"	},
    152 		{ NPF_STAT_INVALID_STATE_TCP1,	"TCP case I"		},
    153 		{ NPF_STAT_INVALID_STATE_TCP2,	"TCP case II"		},
    154 		{ NPF_STAT_INVALID_STATE_TCP3,	"TCP case III"		},
    155 
    156 		{ -1, "Packet race cases"				},
    157 		{ NPF_STAT_RACE_NAT,		"NAT association race"	},
    158 		{ NPF_STAT_RACE_SESSION,	"duplicate session race"},
    159 
    160 		{ -1, "Fragmentation"					},
    161 		{ NPF_STAT_FRAGMENTS,		"fragments"		},
    162 		{ NPF_STAT_REASSEMBLY,		"reassembled"		},
    163 		{ NPF_STAT_REASSFAIL,		"failed reassembly"	},
    164 
    165 		{ -1, "Other"						},
    166 		{ NPF_STAT_ERROR,		"unexpected errors"	},
    167 	};
    168 	uint64_t *st = ecalloc(1, NPF_STATS_SIZE);
    169 
    170 	if (ioctl(fd, IOC_NPF_STATS, &st) != 0) {
    171 		err(EXIT_FAILURE, "ioctl(IOC_NPF_STATS)");
    172 	}
    173 
    174 	for (unsigned i = 0; i < __arraycount(stats); i++) {
    175 		const char *sname = stats[i].name;
    176 		int sidx = stats[i].index;
    177 
    178 		if (sidx == -1) {
    179 			printf("%s:\n", sname);
    180 		} else {
    181 			printf("\t%"PRIu64" %s\n", st[sidx], sname);
    182 		}
    183 	}
    184 
    185 	free(st);
    186 	return 0;
    187 }
    188 
    189 void
    190 npfctl_print_error(const nl_error_t *ne)
    191 {
    192 	static const char *ncode_errors[] = {
    193 		[-NPF_ERR_OPCODE]	= "invalid instruction",
    194 		[-NPF_ERR_JUMP]		= "invalid jump",
    195 		[-NPF_ERR_REG]		= "invalid register",
    196 		[-NPF_ERR_INVAL]	= "invalid argument value",
    197 		[-NPF_ERR_RANGE]	= "processing out of range"
    198 	};
    199 	const int nc_err = ne->ne_ncode_error;
    200 	const char *srcfile = ne->ne_source_file;
    201 
    202 	if (srcfile) {
    203 		warnx("source %s line %d", srcfile, ne->ne_source_line);
    204 	}
    205 	if (nc_err) {
    206 		warnx("n-code error (%d): %s at offset 0x%x",
    207 		    nc_err, ncode_errors[-nc_err], ne->ne_ncode_errat);
    208 	}
    209 	if (ne->ne_id) {
    210 		warnx("object: %d", ne->ne_id);
    211 	}
    212 }
    213 
    214 char *
    215 npfctl_print_addrmask(int alen, npf_addr_t *addr, npf_netmask_t mask)
    216 {
    217 	struct sockaddr_storage ss;
    218 	char *buf = ecalloc(1, 64);
    219 	int len;
    220 
    221 	switch (alen) {
    222 	case 4: {
    223 		struct sockaddr_in *sin = (void *)&ss;
    224 		sin->sin_len = sizeof(*sin);
    225 		sin->sin_family = AF_INET;
    226 		sin->sin_port = 0;
    227 		memcpy(&sin->sin_addr, addr, sizeof(sin->sin_addr));
    228 		break;
    229 	}
    230 	case 16: {
    231 		struct sockaddr_in6 *sin6 = (void *)&ss;
    232 		sin6->sin6_len = sizeof(*sin6);
    233 		sin6->sin6_family = AF_INET6;
    234 		sin6->sin6_port = 0;
    235 		memcpy(&sin6->sin6_addr, addr, sizeof(sin6->sin6_addr));
    236 		break;
    237 	}
    238 	default:
    239 		assert(false);
    240 	}
    241 	len = sockaddr_snprintf(buf, 64, "%a", (struct sockaddr *)&ss);
    242 	if (mask) {
    243 		snprintf(&buf[len], 64 - len, "/%u", mask);
    244 	}
    245 	return buf;
    246 }
    247 
    248 __dead static void
    249 npfctl_table(int fd, int argc, char **argv)
    250 {
    251 	static const struct tblops_s {
    252 		const char *	cmd;
    253 		int		action;
    254 	} tblops[] = {
    255 		{ "add",	NPF_IOCTL_TBLENT_ADD		},
    256 		{ "rem",	NPF_IOCTL_TBLENT_REM		},
    257 		{ "test",	NPF_IOCTL_TBLENT_LOOKUP		},
    258 		{ "list",	NPF_IOCTL_TBLENT_LIST		},
    259 		{ NULL,		0				}
    260 	};
    261 	npf_ioctl_table_t nct;
    262 	fam_addr_mask_t fam;
    263 	size_t buflen = 512;
    264 	char *cmd, *arg = NULL; /* XXX gcc */
    265 	int n, alen;
    266 
    267 	/* Default action is list. */
    268 	memset(&nct, 0, sizeof(npf_ioctl_table_t));
    269 	nct.nct_tid = atoi(argv[0]);
    270 	cmd = argv[1];
    271 
    272 	for (n = 0; tblops[n].cmd != NULL; n++) {
    273 		if (strcmp(cmd, tblops[n].cmd) != 0) {
    274 			continue;
    275 		}
    276 		nct.nct_action = tblops[n].action;
    277 		break;
    278 	}
    279 	if (tblops[n].cmd == NULL) {
    280 		errx(EXIT_FAILURE, "invalid command '%s'", cmd);
    281 	}
    282 	if (nct.nct_action != NPF_IOCTL_TBLENT_LIST) {
    283 		if (argc < 3) {
    284 			usage();
    285 		}
    286 		arg = argv[2];
    287 	}
    288 again:
    289 	if (nct.nct_action == NPF_IOCTL_TBLENT_LIST) {
    290 		nct.nct_data.buf.buf = ecalloc(1, buflen);
    291 		nct.nct_data.buf.len = buflen;
    292 	} else {
    293 		if (!npfctl_parse_cidr(arg, &fam, &alen)) {
    294 			errx(EXIT_FAILURE, "invalid CIDR '%s'", arg);
    295 		}
    296 		nct.nct_data.ent.alen = alen;
    297 		memcpy(&nct.nct_data.ent.addr, &fam.fam_addr, sizeof(npf_addr_t));
    298 		nct.nct_data.ent.mask = fam.fam_mask;
    299 	}
    300 
    301 	if (ioctl(fd, IOC_NPF_TABLE, &nct) != -1) {
    302 		errno = 0;
    303 	}
    304 	switch (errno) {
    305 	case 0:
    306 		break;
    307 	case EEXIST:
    308 		errx(EXIT_FAILURE, "entry already exists or is conflicting");
    309 	case ENOENT:
    310 		errx(EXIT_FAILURE, "no matching entry was not found");
    311 	case EINVAL:
    312 		errx(EXIT_FAILURE, "invalid address, mask or table ID");
    313 	case ENOMEM:
    314 		if (nct.nct_action == NPF_IOCTL_TBLENT_LIST) {
    315 			/* XXX */
    316 			free(nct.nct_data.buf.buf);
    317 			buflen <<= 1;
    318 			goto again;
    319 		}
    320 		/* FALLTHROUGH */
    321 	default:
    322 		err(EXIT_FAILURE, "ioctl");
    323 	}
    324 
    325 	if (nct.nct_action == NPF_IOCTL_TBLENT_LIST) {
    326 		npf_ioctl_ent_t *ent = nct.nct_data.buf.buf;
    327 		char *buf;
    328 
    329 		while (nct.nct_data.buf.len--) {
    330 			if (!ent->alen)
    331 				break;
    332 			buf = npfctl_print_addrmask(ent->alen,
    333 			    &ent->addr, ent->mask);
    334 			puts(buf);
    335 			ent++;
    336 		}
    337 		free(nct.nct_data.buf.buf);
    338 	} else {
    339 		printf("%s: %s\n", getprogname(),
    340 		    nct.nct_action == NPF_IOCTL_TBLENT_LOOKUP ?
    341 		    "matching entry found" : "success");
    342 	}
    343 	exit(EXIT_SUCCESS);
    344 }
    345 
    346 static void
    347 npfctl(int action, int argc, char **argv)
    348 {
    349 	int fd, ret, ver, boolval;
    350 
    351 	fd = open(NPF_DEV_PATH, O_RDONLY);
    352 	if (fd == -1) {
    353 		err(EXIT_FAILURE, "cannot open '%s'", NPF_DEV_PATH);
    354 	}
    355 	ret = ioctl(fd, IOC_NPF_VERSION, &ver);
    356 	if (ret == -1) {
    357 		err(EXIT_FAILURE, "ioctl");
    358 	}
    359 	if (ver != NPF_VERSION) {
    360 		errx(EXIT_FAILURE,
    361 		    "incompatible NPF interface version (%d, kernel %d)\n"
    362 		    "Hint: update userland?", NPF_VERSION, ver);
    363 	}
    364 	switch (action) {
    365 	case NPFCTL_START:
    366 		boolval = true;
    367 		ret = ioctl(fd, IOC_NPF_SWITCH, &boolval);
    368 		break;
    369 	case NPFCTL_STOP:
    370 		boolval = false;
    371 		ret = ioctl(fd, IOC_NPF_SWITCH, &boolval);
    372 		break;
    373 	case NPFCTL_RELOAD:
    374 		npfctl_config_init(false);
    375 		npfctl_parsecfg(argc < 3 ? NPF_CONF_PATH : argv[2]);
    376 		ret = npfctl_config_send(fd, NULL);
    377 		if (ret) {
    378 			errx(EXIT_FAILURE, "ioctl: %s", strerror(ret));
    379 		}
    380 		break;
    381 	case NPFCTL_SHOWCONF:
    382 		ret = npfctl_config_show(fd);
    383 		break;
    384 	case NPFCTL_FLUSH:
    385 		ret = npf_config_flush(fd);
    386 		break;
    387 	case NPFCTL_VALIDATE:
    388 		npfctl_config_init(false);
    389 		npfctl_parsecfg(argc < 3 ? NPF_CONF_PATH : argv[2]);
    390 		ret = npfctl_config_show(0);
    391 		break;
    392 	case NPFCTL_TABLE:
    393 		if ((argc -= 2) < 2) {
    394 			usage();
    395 		}
    396 		argv += 2;
    397 		npfctl_table(fd, argc, argv);
    398 		break;
    399 	case NPFCTL_STATS:
    400 		ret = npfctl_print_stats(fd);
    401 		break;
    402 	case NPFCTL_SESSIONS_SAVE:
    403 		if (npf_sessions_recv(fd, NPF_SESSDB_PATH) != 0) {
    404 			errx(EXIT_FAILURE, "could not save sessions to '%s'",
    405 			    NPF_SESSDB_PATH);
    406 		}
    407 		break;
    408 	case NPFCTL_SESSIONS_LOAD:
    409 		if (npf_sessions_send(fd, NPF_SESSDB_PATH) != 0) {
    410 			errx(EXIT_FAILURE, "no sessions loaded from '%s'",
    411 			    NPF_SESSDB_PATH);
    412 		}
    413 		break;
    414 	}
    415 	if (ret) {
    416 		err(EXIT_FAILURE, "ioctl");
    417 	}
    418 	close(fd);
    419 }
    420 
    421 int
    422 main(int argc, char **argv)
    423 {
    424 	char *cmd;
    425 
    426 	if (argc < 2) {
    427 		usage();
    428 	}
    429 	cmd = argv[1];
    430 
    431 	if (strcmp(cmd, "debug") == 0) {
    432 		const char *cfg = argc > 2 ? argv[2] : "/etc/npf.conf";
    433 		const char *out = argc > 3 ? argv[3] : "/tmp/npf.plist";
    434 
    435 		npfctl_config_init(true);
    436 		npfctl_parsecfg(cfg);
    437 		npfctl_config_send(0, out);
    438 		return EXIT_SUCCESS;
    439 	}
    440 
    441 	/* Find and call the subroutine. */
    442 	for (int n = 0; operations[n].cmd != NULL; n++) {
    443 		const char *opcmd = operations[n].cmd;
    444 		if (strncmp(cmd, opcmd, strlen(opcmd)) != 0)
    445 			continue;
    446 		npfctl(operations[n].action, argc, argv);
    447 		return EXIT_SUCCESS;
    448 	}
    449 	usage();
    450 }
    451