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