npfctl.c revision 1.10.2.3       1 /*	$NetBSD: npfctl.c,v 1.10.2.3 2012/07/16 22:13:28 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.3 2012/07/16 22:13:28 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_TABLE,
     61 	NPFCTL_STATS,
     62 	NPFCTL_SESSIONS_SAVE,
     63 	NPFCTL_SESSIONS_LOAD,
     64 };
     65 
     66 static const struct operations_s {
     67 	const char *		cmd;
     68 	int			action;
     69 } operations[] = {
     70 	/* Start, stop, reload */
     71 	{	"start",		NPFCTL_START		},
     72 	{	"stop",			NPFCTL_STOP		},
     73 	{	"reload",		NPFCTL_RELOAD		},
     74 	{	"show",			NPFCTL_SHOWCONF,	},
     75 	{	"flush",		NPFCTL_FLUSH		},
     76 	/* Table */
     77 	{	"table",		NPFCTL_TABLE		},
     78 	/* Stats */
     79 	{	"stats",		NPFCTL_STATS		},
     80 	/* Sessions */
     81 	{	"sess-save",		NPFCTL_SESSIONS_SAVE	},
     82 	{	"sess-load",		NPFCTL_SESSIONS_LOAD	},
     83 	/* --- */
     84 	{	NULL,			0			}
     85 };
     86 
     87 void *
     88 zalloc(size_t sz)
     89 {
     90 	void *p = malloc(sz);
     91 
     92 	if (p == NULL) {
     93 		err(EXIT_FAILURE, "zalloc");
     94 	}
     95 	memset(p, 0, sz);
     96 	return p;
     97 }
     98 
     99 void *
    100 xrealloc(void *ptr, size_t size)
    101 {
    102 	void *p = realloc(ptr, size);
    103 
    104 	if (p == NULL) {
    105 		err(EXIT_FAILURE, "xrealloc");
    106 	}
    107 	return p;
    108 }
    109 
    110 char *
    111 xstrdup(const char *s)
    112 {
    113 	char *p = strdup(s);
    114 
    115 	if (p == NULL) {
    116 		err(EXIT_FAILURE, "xstrdup");
    117 	}
    118 	return p;
    119 }
    120 
    121 char *
    122 xstrndup(const char *s, size_t len)
    123 {
    124 	char *p;
    125 
    126 	p = strndup(s, len);
    127 	if (p == NULL) {
    128 		err(EXIT_FAILURE, "xstrndup");
    129 	}
    130 	return p;
    131 }
    132 
    133 __dead static void
    134 usage(void)
    135 {
    136 	const char *progname = getprogname();
    137 
    138 	fprintf(stderr,
    139 	    "usage:\t%s [ start | stop | reload | flush | show | stats ]\n",
    140 	    progname);
    141 	fprintf(stderr,
    142 	    "usage:\t%s [ sess-save | sess-load ]\n",
    143 	    progname);
    144 	fprintf(stderr,
    145 	    "\t%s table <tid> [ flush ]\n",
    146 	    progname);
    147 	fprintf(stderr,
    148 	    "\t%s table <tid> { add | rem | test } <address/mask>\n",
    149 	    progname);
    150 
    151 	exit(EXIT_FAILURE);
    152 }
    153 
    154 static void
    155 npfctl_parsecfg(const char *cfg)
    156 {
    157 	FILE *fp;
    158 
    159 	fp = fopen(cfg, "r");
    160 	if (fp == NULL) {
    161 		err(EXIT_FAILURE, "open '%s'", cfg);
    162 	}
    163 	yyrestart(fp);
    164 	yylineno = 1;
    165 	yycolumn = 0;
    166 	yyfilename = cfg;
    167 	yyparse();
    168 	fclose(fp);
    169 }
    170 
    171 static int
    172 npfctl_print_stats(int fd)
    173 {
    174 	uint64_t *st = zalloc(NPF_STATS_SIZE);
    175 
    176 	if (ioctl(fd, IOC_NPF_STATS, &st) != 0) {
    177 		err(EXIT_FAILURE, "ioctl(IOC_NPF_STATS)");
    178 	}
    179 
    180 	printf("Packets passed:\n\t%"PRIu64" default pass\n\t"
    181 	    "%"PRIu64 " ruleset pass\n\t%"PRIu64" session pass\n\n",
    182 	    st[NPF_STAT_PASS_DEFAULT], st[NPF_STAT_PASS_RULESET],
    183 	    st[NPF_STAT_PASS_SESSION]);
    184 
    185 	printf("Packets blocked:\n\t%"PRIu64" default block\n\t"
    186 	    "%"PRIu64 " ruleset block\n\n", st[NPF_STAT_BLOCK_DEFAULT],
    187 	    st[NPF_STAT_BLOCK_RULESET]);
    188 
    189 	printf("Session and NAT entries:\n\t%"PRIu64" session allocations\n\t"
    190 	    "%"PRIu64" session destructions\n\t%"PRIu64" NAT entry allocations\n\t"
    191 	    "%"PRIu64" NAT entry destructions\n\n", st[NPF_STAT_SESSION_CREATE],
    192 	    st[NPF_STAT_SESSION_DESTROY], st[NPF_STAT_NAT_CREATE],
    193 	    st[NPF_STAT_NAT_DESTROY]);
    194 
    195 	printf("Invalid packet state cases:\n\t%"PRIu64" cases in total\n\t"
    196 	    "%"PRIu64" TCP case I\n\t%"PRIu64" TCP case II\n\t%"PRIu64
    197 	    " TCP case III\n\n", st[NPF_STAT_INVALID_STATE],
    198 	    st[NPF_STAT_INVALID_STATE_TCP1], st[NPF_STAT_INVALID_STATE_TCP2],
    199 	    st[NPF_STAT_INVALID_STATE_TCP3]);
    200 
    201 	printf("Packet race cases:\n\t%"PRIu64" NAT association race\n\t"
    202 	    "%"PRIu64" duplicate session race\n\n", st[NPF_STAT_RACE_NAT],
    203 	    st[NPF_STAT_RACE_SESSION]);
    204 
    205 	printf("Rule processing procedure cases:\n"
    206 	    "\t%"PRIu64" packets logged\n\t%"PRIu64" packets normalized\n\n",
    207 	    st[NPF_STAT_RPROC_LOG], st[NPF_STAT_RPROC_NORM]);
    208 
    209 	printf("Fragmentation:\n"
    210 	    "\t%"PRIu64" fragments\n\t%"PRIu64" reassembled\n"
    211 	    "\t%"PRIu64" failed reassembly\n\n",
    212 	    st[NPF_STAT_FRAGMENTS], st[NPF_STAT_REASSEMBLY],
    213 	    st[NPF_STAT_REASSFAIL]);
    214 
    215 	printf("Unexpected error cases:\n\t%"PRIu64"\n", st[NPF_STAT_ERROR]);
    216 
    217 	free(st);
    218 	return 0;
    219 }
    220 
    221 void
    222 npfctl_print_error(const nl_error_t *ne)
    223 {
    224 	static const char *ncode_errors[] = {
    225 		[-NPF_ERR_OPCODE]	= "invalid instruction",
    226 		[-NPF_ERR_JUMP]		= "invalid jump",
    227 		[-NPF_ERR_REG]		= "invalid register",
    228 		[-NPF_ERR_INVAL]	= "invalid argument value",
    229 		[-NPF_ERR_RANGE]	= "processing out of range"
    230 	};
    231 	const int nc_err = ne->ne_ncode_error;
    232 	const char *srcfile = ne->ne_source_file;
    233 
    234 	if (srcfile) {
    235 		warnx("source %s line %d", srcfile, ne->ne_source_line);
    236 	}
    237 	if (nc_err) {
    238 		warnx("n-code error (%d): %s at offset 0x%x",
    239 		    nc_err, ncode_errors[-nc_err], ne->ne_ncode_errat);
    240 	}
    241 	if (ne->ne_id) {
    242 		warnx("object: %d", ne->ne_id);
    243 	}
    244 }
    245 
    246 static void
    247 npfctl_table(int fd, char **argv)
    248 {
    249 	static const struct tblops_s {
    250 		const char *	cmd;
    251 		int		action;
    252 	} tblops[] = {
    253 		{ "add",	NPF_IOCTL_TBLENT_ADD },
    254 		{ "rem",	NPF_IOCTL_TBLENT_REM },
    255 		{ "test",	0 },
    256 		{ NULL,		0 }
    257 	};
    258 	npf_ioctl_table_t nct;
    259 	fam_addr_mask_t fam;
    260 	char *cmd = argv[3];
    261 	char *arg = argv[3];
    262 	int n, alen;
    263 
    264 	memset(&nct, 0, sizeof(npf_ioctl_table_t));
    265 	nct.nct_tid = atoi(argv[2]);
    266 
    267 	for (n = 0; tblops[n].cmd != NULL; n++) {
    268 		if (strcmp(cmd, tblops[n].cmd) == 0) {
    269 			nct.nct_action = tblops[n].action;
    270 			arg = argv[4];
    271 			break;
    272 		}
    273 	}
    274 	if (!npfctl_parse_cidr(arg, &fam, &alen)) {
    275 		errx(EXIT_FAILURE, "invalid CIDR '%s'", arg);
    276 	}
    277 	memcpy(&nct.nct_addr, &fam.fam_addr, sizeof(npf_addr_t));
    278 	nct.nct_mask = fam.fam_mask;
    279 	nct.nct_alen = alen;
    280 
    281 	if (ioctl(fd, IOC_NPF_TABLE, &nct) != -1) {
    282 		errno = 0;
    283 	}
    284 	switch (errno) {
    285 	case EEXIST:
    286 		warnx("entry already exists or is conflicting");
    287 		break;
    288 	case ENOENT:
    289 		warnx("no matching entry was not found");
    290 		break;
    291 	case EINVAL:
    292 		warnx("invalid address, mask or table ID");
    293 		break;
    294 	case 0:
    295 		printf("%s: %s\n", getprogname(), nct.nct_action == 0 ?
    296 		    "matching entry found" : "success");
    297 		break;
    298 	default:
    299 		warn("error");
    300 	}
    301 	exit(errno ? EXIT_FAILURE : EXIT_SUCCESS);
    302 }
    303 
    304 static void
    305 npfctl(int action, int argc, char **argv)
    306 {
    307 	int fd, ret, ver, boolval;
    308 
    309 	fd = open(NPF_DEV_PATH, O_RDONLY);
    310 	if (fd == -1) {
    311 		err(EXIT_FAILURE, "cannot open '%s'", NPF_DEV_PATH);
    312 	}
    313 	ret = ioctl(fd, IOC_NPF_VERSION, &ver);
    314 	if (ret == -1) {
    315 		err(EXIT_FAILURE, "ioctl");
    316 	}
    317 	if (ver != NPF_VERSION) {
    318 		errx(EXIT_FAILURE,
    319 		    "incompatible NPF interface version (%d, kernel %d)\n"
    320 		    "Hint: update userland?", NPF_VERSION, ver);
    321 	}
    322 	switch (action) {
    323 	case NPFCTL_START:
    324 		boolval = true;
    325 		ret = ioctl(fd, IOC_NPF_SWITCH, &boolval);
    326 		break;
    327 	case NPFCTL_STOP:
    328 		boolval = false;
    329 		ret = ioctl(fd, IOC_NPF_SWITCH, &boolval);
    330 		break;
    331 	case NPFCTL_RELOAD:
    332 		npfctl_config_init(false);
    333 		npfctl_parsecfg(argc < 3 ? NPF_CONF_PATH : argv[2]);
    334 		ret = npfctl_config_send(fd);
    335 		if (ret) {
    336 			errx(EXIT_FAILURE, "ioctl: %s", strerror(ret));
    337 		}
    338 		break;
    339 	case NPFCTL_SHOWCONF:
    340 		ret = npfctl_config_show(fd);
    341 		break;
    342 	case NPFCTL_FLUSH:
    343 		ret = npf_config_flush(fd);
    344 		break;
    345 	case NPFCTL_TABLE:
    346 		if (argc < 5) {
    347 			usage();
    348 		}
    349 		npfctl_table(fd, argv);
    350 		break;
    351 	case NPFCTL_STATS:
    352 		ret = npfctl_print_stats(fd);
    353 		break;
    354 	case NPFCTL_SESSIONS_SAVE:
    355 		if (npf_sessions_recv(fd, NPF_SESSDB_PATH) != 0) {
    356 			errx(EXIT_FAILURE, "could not save sessions to '%s'",
    357 			    NPF_SESSDB_PATH);
    358 		}
    359 		break;
    360 	case NPFCTL_SESSIONS_LOAD:
    361 		if (npf_sessions_send(fd, NPF_SESSDB_PATH) != 0) {
    362 			errx(EXIT_FAILURE, "no sessions loaded from '%s'",
    363 			    NPF_SESSDB_PATH);
    364 		}
    365 		break;
    366 	}
    367 	if (ret) {
    368 		err(EXIT_FAILURE, "ioctl");
    369 	}
    370 	close(fd);
    371 }
    372 
    373 int
    374 main(int argc, char **argv)
    375 {
    376 	char *cmd;
    377 
    378 	if (argc < 2) {
    379 		usage();
    380 	}
    381 	cmd = argv[1];
    382 
    383 	if (strcmp(cmd, "debug") == 0) {
    384 		const char *cfg = argc > 2 ? argv[2] : "/etc/npf.conf";
    385 		npfctl_config_init(true);
    386 		npfctl_parsecfg(cfg);
    387 		npfctl_config_send(0);
    388 		return EXIT_SUCCESS;
    389 	}
    390 
    391 	/* Find and call the subroutine. */
    392 	for (int n = 0; operations[n].cmd != NULL; n++) {
    393 		if (strcmp(cmd, operations[n].cmd) != 0)
    394 			continue;
    395 		npfctl(operations[n].action, argc, argv);
    396 		return EXIT_SUCCESS;
    397 	}
    398 	usage();
    399 }
    400