npfctl.c revision 1.20       1 /*	$NetBSD: npfctl.c,v 1.20 2012/09/16 13:47:41 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.20 2012/09/16 13:47:41 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_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 	    "\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 	static const struct stats_s {
    175 		/* Note: -1 indicates a new section. */
    176 		int		index;
    177 		const char *	name;
    178 	} stats[] = {
    179 		{ -1, "Packets passed"					},
    180 		{ NPF_STAT_PASS_DEFAULT,	"default pass"		},
    181 		{ NPF_STAT_PASS_RULESET,	"ruleset pass"		},
    182 		{ NPF_STAT_PASS_SESSION,	"session pass"		},
    183 
    184 		{ -1, "Packets blocked"					},
    185 		{ NPF_STAT_BLOCK_DEFAULT,	"default block"		},
    186 		{ NPF_STAT_BLOCK_RULESET,	"ruleset block"		},
    187 
    188 		{ -1, "Session and NAT entries"				},
    189 		{ NPF_STAT_SESSION_CREATE,	"session allocations"	},
    190 		{ NPF_STAT_SESSION_DESTROY,	"session destructions"	},
    191 		{ NPF_STAT_NAT_CREATE,		"NAT entry allocations"	},
    192 		{ NPF_STAT_NAT_DESTROY,		"NAT entry destructions"},
    193 
    194 		{ -1, "Invalid packet state cases"			},
    195 		{ NPF_STAT_INVALID_STATE,	"cases in total"	},
    196 		{ NPF_STAT_INVALID_STATE_TCP1,	"TCP case I"		},
    197 		{ NPF_STAT_INVALID_STATE_TCP2,	"TCP case II"		},
    198 		{ NPF_STAT_INVALID_STATE_TCP3,	"TCP case III"		},
    199 
    200 		{ -1, "Packet race cases"				},
    201 		{ NPF_STAT_RACE_NAT,		"NAT association race"	},
    202 		{ NPF_STAT_RACE_SESSION,	"duplicate session race"},
    203 
    204 		{ -1, "Fragmentation"					},
    205 		{ NPF_STAT_FRAGMENTS,		"fragments"		},
    206 		{ NPF_STAT_REASSEMBLY,		"reassembled"		},
    207 		{ NPF_STAT_REASSFAIL,		"failed reassembly"	},
    208 
    209 		{ -1, "Other"						},
    210 		{ NPF_STAT_ERROR,		"unexpected errors"	},
    211 	};
    212 	uint64_t *st = zalloc(NPF_STATS_SIZE);
    213 
    214 	if (ioctl(fd, IOC_NPF_STATS, &st) != 0) {
    215 		err(EXIT_FAILURE, "ioctl(IOC_NPF_STATS)");
    216 	}
    217 
    218 	for (unsigned i = 0; i < __arraycount(stats); i++) {
    219 		const char *sname = stats[i].name;
    220 		int sidx = stats[i].index;
    221 
    222 		if (sidx == -1) {
    223 			printf("%s:\n", sname);
    224 		} else {
    225 			printf("\t%"PRIu64" %s\n", st[sidx], sname);
    226 		}
    227 	}
    228 
    229 	free(st);
    230 	return 0;
    231 }
    232 
    233 void
    234 npfctl_print_error(const nl_error_t *ne)
    235 {
    236 	static const char *ncode_errors[] = {
    237 		[-NPF_ERR_OPCODE]	= "invalid instruction",
    238 		[-NPF_ERR_JUMP]		= "invalid jump",
    239 		[-NPF_ERR_REG]		= "invalid register",
    240 		[-NPF_ERR_INVAL]	= "invalid argument value",
    241 		[-NPF_ERR_RANGE]	= "processing out of range"
    242 	};
    243 	const int nc_err = ne->ne_ncode_error;
    244 	const char *srcfile = ne->ne_source_file;
    245 
    246 	if (srcfile) {
    247 		warnx("source %s line %d", srcfile, ne->ne_source_line);
    248 	}
    249 	if (nc_err) {
    250 		warnx("n-code error (%d): %s at offset 0x%x",
    251 		    nc_err, ncode_errors[-nc_err], ne->ne_ncode_errat);
    252 	}
    253 	if (ne->ne_id) {
    254 		warnx("object: %d", ne->ne_id);
    255 	}
    256 }
    257 
    258 __dead static void
    259 npfctl_table(int fd, char **argv)
    260 {
    261 	static const struct tblops_s {
    262 		const char *	cmd;
    263 		int		action;
    264 	} tblops[] = {
    265 		{ "add",	NPF_IOCTL_TBLENT_ADD },
    266 		{ "rem",	NPF_IOCTL_TBLENT_REM },
    267 		{ "test",	0 },
    268 		{ NULL,		0 }
    269 	};
    270 	npf_ioctl_table_t nct;
    271 	fam_addr_mask_t fam;
    272 	char *cmd = argv[3];
    273 	char *arg = argv[3];
    274 	int n, alen;
    275 
    276 	memset(&nct, 0, sizeof(npf_ioctl_table_t));
    277 	nct.nct_tid = atoi(argv[2]);
    278 
    279 	for (n = 0; tblops[n].cmd != NULL; n++) {
    280 		if (strcmp(cmd, tblops[n].cmd) == 0) {
    281 			nct.nct_action = tblops[n].action;
    282 			arg = argv[4];
    283 			break;
    284 		}
    285 	}
    286 	if (!npfctl_parse_cidr(arg, &fam, &alen)) {
    287 		errx(EXIT_FAILURE, "invalid CIDR '%s'", arg);
    288 	}
    289 	memcpy(&nct.nct_addr, &fam.fam_addr, sizeof(npf_addr_t));
    290 	nct.nct_mask = fam.fam_mask;
    291 	nct.nct_alen = alen;
    292 
    293 	if (ioctl(fd, IOC_NPF_TABLE, &nct) != -1) {
    294 		errno = 0;
    295 	}
    296 	switch (errno) {
    297 	case EEXIST:
    298 		warnx("entry already exists or is conflicting");
    299 		break;
    300 	case ENOENT:
    301 		warnx("no matching entry was not found");
    302 		break;
    303 	case EINVAL:
    304 		warnx("invalid address, mask or table ID");
    305 		break;
    306 	case 0:
    307 		printf("%s: %s\n", getprogname(), nct.nct_action == 0 ?
    308 		    "matching entry found" : "success");
    309 		break;
    310 	default:
    311 		warn("error");
    312 	}
    313 	exit(errno ? EXIT_FAILURE : EXIT_SUCCESS);
    314 }
    315 
    316 static void
    317 npfctl(int action, int argc, char **argv)
    318 {
    319 	int fd, ret, ver, boolval;
    320 
    321 	fd = open(NPF_DEV_PATH, O_RDONLY);
    322 	if (fd == -1) {
    323 		err(EXIT_FAILURE, "cannot open '%s'", NPF_DEV_PATH);
    324 	}
    325 	ret = ioctl(fd, IOC_NPF_VERSION, &ver);
    326 	if (ret == -1) {
    327 		err(EXIT_FAILURE, "ioctl");
    328 	}
    329 	if (ver != NPF_VERSION) {
    330 		errx(EXIT_FAILURE,
    331 		    "incompatible NPF interface version (%d, kernel %d)\n"
    332 		    "Hint: update userland?", NPF_VERSION, ver);
    333 	}
    334 	switch (action) {
    335 	case NPFCTL_START:
    336 		boolval = true;
    337 		ret = ioctl(fd, IOC_NPF_SWITCH, &boolval);
    338 		break;
    339 	case NPFCTL_STOP:
    340 		boolval = false;
    341 		ret = ioctl(fd, IOC_NPF_SWITCH, &boolval);
    342 		break;
    343 	case NPFCTL_RELOAD:
    344 		npfctl_config_init(false);
    345 		npfctl_parsecfg(argc < 3 ? NPF_CONF_PATH : argv[2]);
    346 		ret = npfctl_config_send(fd, NULL);
    347 		if (ret) {
    348 			errx(EXIT_FAILURE, "ioctl: %s", strerror(ret));
    349 		}
    350 		break;
    351 	case NPFCTL_SHOWCONF:
    352 		ret = npfctl_config_show(fd);
    353 		break;
    354 	case NPFCTL_FLUSH:
    355 		ret = npf_config_flush(fd);
    356 		break;
    357 	case NPFCTL_TABLE:
    358 		if (argc < 5) {
    359 			usage();
    360 		}
    361 		npfctl_table(fd, argv);
    362 		break;
    363 	case NPFCTL_STATS:
    364 		ret = npfctl_print_stats(fd);
    365 		break;
    366 	case NPFCTL_SESSIONS_SAVE:
    367 		if (npf_sessions_recv(fd, NPF_SESSDB_PATH) != 0) {
    368 			errx(EXIT_FAILURE, "could not save sessions to '%s'",
    369 			    NPF_SESSDB_PATH);
    370 		}
    371 		break;
    372 	case NPFCTL_SESSIONS_LOAD:
    373 		if (npf_sessions_send(fd, NPF_SESSDB_PATH) != 0) {
    374 			errx(EXIT_FAILURE, "no sessions loaded from '%s'",
    375 			    NPF_SESSDB_PATH);
    376 		}
    377 		break;
    378 	}
    379 	if (ret) {
    380 		err(EXIT_FAILURE, "ioctl");
    381 	}
    382 	close(fd);
    383 }
    384 
    385 int
    386 main(int argc, char **argv)
    387 {
    388 	char *cmd;
    389 
    390 	if (argc < 2) {
    391 		usage();
    392 	}
    393 	cmd = argv[1];
    394 
    395 	if (strcmp(cmd, "debug") == 0) {
    396 		const char *cfg = argc > 2 ? argv[2] : "/etc/npf.conf";
    397 		const char *out = argc > 3 ? argv[3] : "/tmp/npf.plist";
    398 
    399 		npfctl_config_init(true);
    400 		npfctl_parsecfg(cfg);
    401 		npfctl_config_send(0, out);
    402 		return EXIT_SUCCESS;
    403 	}
    404 
    405 	/* Find and call the subroutine. */
    406 	for (int n = 0; operations[n].cmd != NULL; n++) {
    407 		if (strcmp(cmd, operations[n].cmd) != 0)
    408 			continue;
    409 		npfctl(operations[n].action, argc, argv);
    410 		return EXIT_SUCCESS;
    411 	}
    412 	usage();
    413 }
    414