Home | History | Annotate | Line # | Download | only in bin
blocklistd.c revision 1.9
      1 /*	$NetBSD: blocklistd.c,v 1.9 2025/03/26 00:12:49 christos Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2015 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Christos Zoulas.
      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 #ifdef HAVE_CONFIG_H
     32 #include "config.h"
     33 #endif
     34 
     35 #ifdef HAVE_SYS_CDEFS_H
     36 #include <sys/cdefs.h>
     37 #endif
     38 __RCSID("$NetBSD: blocklistd.c,v 1.9 2025/03/26 00:12:49 christos Exp $");
     39 
     40 #include <sys/types.h>
     41 #include <sys/socket.h>
     42 #include <sys/queue.h>
     43 
     44 #ifdef HAVE_LIBUTIL_H
     45 #include <libutil.h>
     46 #endif
     47 #ifdef HAVE_UTIL_H
     48 #include <util.h>
     49 #endif
     50 #include <string.h>
     51 #include <signal.h>
     52 #include <netdb.h>
     53 #include <stdio.h>
     54 #include <stdbool.h>
     55 #include <string.h>
     56 #include <inttypes.h>
     57 #include <syslog.h>
     58 #include <ctype.h>
     59 #include <limits.h>
     60 #include <errno.h>
     61 #include <poll.h>
     62 #include <fcntl.h>
     63 #include <err.h>
     64 #include <stdlib.h>
     65 #include <unistd.h>
     66 #include <time.h>
     67 #include <ifaddrs.h>
     68 #include <netinet/in.h>
     69 
     70 #include "bl.h"
     71 #include "internal.h"
     72 #include "conf.h"
     73 #include "run.h"
     74 #include "state.h"
     75 #include "support.h"
     76 
     77 static const char *configfile = _PATH_BLCONF;
     78 static DB *state;
     79 static const char *dbfile = _PATH_BLSTATE;
     80 static sig_atomic_t readconf;
     81 static sig_atomic_t done;
     82 static int vflag;
     83 
     84 static void
     85 sigusr1(int n __unused)
     86 {
     87 	debug++;
     88 }
     89 
     90 static void
     91 sigusr2(int n __unused)
     92 {
     93 	debug--;
     94 }
     95 
     96 static void
     97 sighup(int n __unused)
     98 {
     99 	readconf++;
    100 }
    101 
    102 static void
    103 sigdone(int n __unused)
    104 {
    105 	done++;
    106 }
    107 
    108 static __dead void
    109 usage(int c)
    110 {
    111 	if (c != '?')
    112 		warnx("Unknown option `%c'", (char)c);
    113 	fprintf(stderr, "Usage: %s [-vdfr] [-c <config>] [-R <rulename>] "
    114 	    "[-P <sockpathsfile>] [-C <controlprog>] [-D <dbfile>] "
    115 	    "[-s <sockpath>] [-t <timeout>]\n", getprogname());
    116 	exit(EXIT_FAILURE);
    117 }
    118 
    119 static int
    120 getremoteaddress(bl_info_t *bi, struct sockaddr_storage *rss, socklen_t *rsl)
    121 {
    122 	*rsl = sizeof(*rss);
    123 	memset(rss, 0, *rsl);
    124 
    125 	if (getpeername(bi->bi_fd, (void *)rss, rsl) != -1)
    126 		return 0;
    127 
    128 	if (errno != ENOTCONN) {
    129 		(*lfun)(LOG_ERR, "getpeername failed (%m)");
    130 		return -1;
    131 	}
    132 
    133 	if (bi->bi_slen == 0) {
    134 		(*lfun)(LOG_ERR, "unconnected socket with no peer in message");
    135 		return -1;
    136 	}
    137 
    138 	switch (bi->bi_ss.ss_family) {
    139 	case AF_INET:
    140 		*rsl = sizeof(struct sockaddr_in);
    141 		break;
    142 	case AF_INET6:
    143 		*rsl = sizeof(struct sockaddr_in6);
    144 		break;
    145 	default:
    146 		(*lfun)(LOG_ERR, "bad client passed socket family %u",
    147 		    (unsigned)bi->bi_ss.ss_family);
    148 		return -1;
    149 	}
    150 
    151 	if (*rsl != bi->bi_slen) {
    152 		(*lfun)(LOG_ERR, "bad client passed socket length %u != %u",
    153 		    (unsigned)*rsl, (unsigned)bi->bi_slen);
    154 		return -1;
    155 	}
    156 
    157 	memcpy(rss, &bi->bi_ss, *rsl);
    158 
    159 #ifdef HAVE_STRUCT_SOCKADDR_SA_LEN
    160 	if (*rsl != rss->ss_len) {
    161 		(*lfun)(LOG_ERR,
    162 		    "bad client passed socket internal length %u != %u",
    163 		    (unsigned)*rsl, (unsigned)rss->ss_len);
    164 		return -1;
    165 	}
    166 #endif
    167 	return 0;
    168 }
    169 
    170 static void
    171 process(bl_t bl)
    172 {
    173 	struct sockaddr_storage rss;
    174 	socklen_t rsl;
    175 	char rbuf[BUFSIZ];
    176 	bl_info_t *bi;
    177 	struct conf c;
    178 	struct dbinfo dbi;
    179 	struct timespec ts;
    180 
    181 	memset(&dbi, 0, sizeof(dbi));
    182 	if (clock_gettime(CLOCK_REALTIME, &ts) == -1) {
    183 		(*lfun)(LOG_ERR, "clock_gettime failed (%m)");
    184 		return;
    185 	}
    186 
    187 	if ((bi = bl_recv(bl)) == NULL) {
    188 		(*lfun)(LOG_ERR, "no message (%m)");
    189 		return;
    190 	}
    191 
    192 	if (getremoteaddress(bi, &rss, &rsl) == -1)
    193 		goto out;
    194 
    195 	if (debug || bi->bi_msg[0]) {
    196 		sockaddr_snprintf(rbuf, sizeof(rbuf), "%a:%p", (void *)&rss);
    197 		(*lfun)(bi->bi_msg[0] ? LOG_INFO : LOG_DEBUG,
    198 		    "processing type=%d fd=%d remote=%s msg=%s uid=%lu gid=%lu",
    199 		    bi->bi_type, bi->bi_fd, rbuf,
    200 		    bi->bi_msg, (unsigned long)bi->bi_uid,
    201 		    (unsigned long)bi->bi_gid);
    202 	}
    203 
    204 	if (conf_find(bi->bi_fd, bi->bi_uid, &rss, &c) == NULL) {
    205 		(*lfun)(LOG_DEBUG, "no rule matched");
    206 		goto out;
    207 	}
    208 
    209 
    210 	if (state_get(state, &c, &dbi) == -1)
    211 		goto out;
    212 
    213 	if (debug) {
    214 		char b1[128], b2[128];
    215 		(*lfun)(LOG_DEBUG, "%s: initial db state for %s: count=%d/%d "
    216 		    "last=%s now=%s", __func__, rbuf, dbi.count, c.c_nfail,
    217 		    fmttime(b1, sizeof(b1), dbi.last),
    218 		    fmttime(b2, sizeof(b2), ts.tv_sec));
    219 	}
    220 
    221 	switch (bi->bi_type) {
    222 	case BL_ABUSE:
    223 		/*
    224 		 * If the application has signaled abusive behavior, set the
    225 		 * number of fails to be two less than the configured limit.
    226 		 * Fall through to the normal BL_ADD and BL_BADUSER processing,
    227 		 * which will increment the failure count to the threshhold, and
    228 		 * block the abusive address.
    229 		 */
    230 		if (c.c_nfail != -1)
    231 			dbi.count = c.c_nfail - 2;
    232 		/*FALLTHROUGH*/
    233 	case BL_ADD:
    234 		dbi.count++;		/* will become += 2 */
    235 		/*FALLTHROUGH*/
    236 	case BL_BADUSER:
    237 		dbi.count++;
    238 		dbi.last = ts.tv_sec;
    239 		if (c.c_nfail != -1 && dbi.count >= c.c_nfail) {
    240 			/*
    241 			 * No point in re-adding the rule.
    242 			 * It might exist already due to latency in processing
    243 			 * and removing the rule is the wrong thing to do as
    244 			 * it allows a window to attack again.
    245 			 */
    246 			if (dbi.id[0] == '\0') {
    247 				int res = run_change("add", &c,
    248 				    dbi.id, sizeof(dbi.id));
    249 				if (res == -1)
    250 					goto out;
    251 			}
    252 			sockaddr_snprintf(rbuf, sizeof(rbuf), "%a",
    253 			    (void *)&rss);
    254 			(*lfun)(LOG_INFO,
    255 			    "blocked %s/%d:%d for %d seconds",
    256 			    rbuf, c.c_lmask, c.c_port, c.c_duration);
    257 		}
    258 		break;
    259 	case BL_DELETE:
    260 		if (dbi.last == 0)
    261 			goto out;
    262 		dbi.count = 0;
    263 		dbi.last = 0;
    264 		break;
    265 	default:
    266 		(*lfun)(LOG_ERR, "unknown message %d", bi->bi_type);
    267 	}
    268 	state_put(state, &c, &dbi);
    269 
    270 out:
    271 	close(bi->bi_fd);
    272 
    273 	if (debug) {
    274 		char b1[128], b2[128];
    275 		(*lfun)(LOG_DEBUG, "%s: final db state for %s: count=%d/%d "
    276 		    "last=%s now=%s", __func__, rbuf, dbi.count, c.c_nfail,
    277 		    fmttime(b1, sizeof(b1), dbi.last),
    278 		    fmttime(b2, sizeof(b2), ts.tv_sec));
    279 	}
    280 }
    281 
    282 static void
    283 update_interfaces(void)
    284 {
    285 	struct ifaddrs *oifas, *nifas;
    286 
    287 	if (getifaddrs(&nifas) == -1)
    288 		return;
    289 
    290 	oifas = ifas;
    291 	ifas = nifas;
    292 
    293 	if (oifas)
    294 		freeifaddrs(oifas);
    295 }
    296 
    297 static void
    298 update(void)
    299 {
    300 	struct timespec ts;
    301 	struct conf c;
    302 	struct dbinfo dbi;
    303 	unsigned int f, n;
    304 	char buf[128];
    305 	void *ss = &c.c_ss;
    306 
    307 	if (clock_gettime(CLOCK_REALTIME, &ts) == -1) {
    308 		(*lfun)(LOG_ERR, "clock_gettime failed (%m)");
    309 		return;
    310 	}
    311 
    312 again:
    313 	for (n = 0, f = 1; state_iterate(state, &c, &dbi, f) == 1;
    314 	    f = 0, n++)
    315 	{
    316 		time_t when = c.c_duration + dbi.last;
    317 		if (debug > 1) {
    318 			char b1[64], b2[64];
    319 			sockaddr_snprintf(buf, sizeof(buf), "%a:%p", ss);
    320 			(*lfun)(LOG_DEBUG, "%s:[%u] %s count=%d duration=%d "
    321 			    "last=%s " "now=%s", __func__, n, buf, dbi.count,
    322 			    c.c_duration, fmttime(b1, sizeof(b1), dbi.last),
    323 			    fmttime(b2, sizeof(b2), ts.tv_sec));
    324 		}
    325 		if (c.c_duration == -1 || when >= ts.tv_sec)
    326 			continue;
    327 		if (dbi.id[0]) {
    328 			run_change("rem", &c, dbi.id, 0);
    329 			sockaddr_snprintf(buf, sizeof(buf), "%a", ss);
    330 			(*lfun)(LOG_INFO, "released %s/%d:%d after %d seconds",
    331 			    buf, c.c_lmask, c.c_port, c.c_duration);
    332 		}
    333 		state_del(state, &c);
    334 		goto again;
    335 	}
    336 }
    337 
    338 static void
    339 addfd(struct pollfd **pfdp, bl_t **blp, size_t *nfd, size_t *maxfd,
    340     const char *path)
    341 {
    342 	bl_t bl = bl_create(true, path, vflag ? vdlog : vsyslog_r);
    343 	if (bl == NULL || !bl_isconnected(bl))
    344 		exit(EXIT_FAILURE);
    345 	if (*nfd >= *maxfd) {
    346 		*maxfd += 10;
    347 		*blp = realloc(*blp, sizeof(**blp) * *maxfd);
    348 		if (*blp == NULL)
    349 			err(EXIT_FAILURE, "malloc");
    350 		*pfdp = realloc(*pfdp, sizeof(**pfdp) * *maxfd);
    351 		if (*pfdp == NULL)
    352 			err(EXIT_FAILURE, "malloc");
    353 	}
    354 
    355 	(*pfdp)[*nfd].fd = bl_getfd(bl);
    356 	(*pfdp)[*nfd].events = POLLIN;
    357 	(*blp)[*nfd] = bl;
    358 	*nfd += 1;
    359 }
    360 
    361 static void
    362 uniqueadd(struct conf ***listp, size_t *nlist, size_t *mlist, struct conf *c)
    363 {
    364 	struct conf **list = *listp;
    365 
    366 	if (c->c_name[0] == '\0')
    367 		return;
    368 	for (size_t i = 0; i < *nlist; i++) {
    369 		if (strcmp(list[i]->c_name, c->c_name) == 0)
    370 			return;
    371 	}
    372 	if (*nlist == *mlist) {
    373 		*mlist += 10;
    374 		void *p = realloc(*listp, *mlist * sizeof(*list));
    375 		if (p == NULL)
    376 			err(EXIT_FAILURE, "Can't allocate for rule list");
    377 		list = *listp = p;
    378 	}
    379 	list[(*nlist)++] = c;
    380 }
    381 
    382 static void
    383 rules_flush(void)
    384 {
    385 	struct conf **list;
    386 	size_t nlist, mlist;
    387 
    388 	list = NULL;
    389 	mlist = nlist = 0;
    390 	for (size_t i = 0; i < rconf.cs_n; i++)
    391 		uniqueadd(&list, &nlist, &mlist, &rconf.cs_c[i]);
    392 	for (size_t i = 0; i < lconf.cs_n; i++)
    393 		uniqueadd(&list, &nlist, &mlist, &lconf.cs_c[i]);
    394 
    395 	for (size_t i = 0; i < nlist; i++)
    396 		run_flush(list[i]);
    397 	free(list);
    398 }
    399 
    400 static void
    401 rules_restore(void)
    402 {
    403 	DB *db;
    404 	struct conf c;
    405 	struct dbinfo dbi;
    406 	unsigned int f;
    407 
    408 	db = state_open(dbfile, O_RDONLY, 0);
    409 	if (db == NULL) {
    410 		(*lfun)(LOG_ERR, "Can't open `%s' to restore state (%m)",
    411 			dbfile);
    412 		return;
    413 	}
    414 	for (f = 1; state_iterate(db, &c, &dbi, f) == 1; f = 0) {
    415 		if (dbi.id[0] == '\0')
    416 			continue;
    417 		(void)run_change("add", &c, dbi.id, sizeof(dbi.id));
    418 		state_put(state, &c, &dbi);
    419 	}
    420 	state_close(db);
    421 	state_sync(state);
    422 }
    423 
    424 int
    425 main(int argc, char *argv[])
    426 {
    427 	int c, tout, flags, flush, restore, ret;
    428 	const char *spath, **blsock;
    429 	size_t nblsock, maxblsock;
    430 
    431 	setprogname(argv[0]);
    432 
    433 	spath = NULL;
    434 	blsock = NULL;
    435 	maxblsock = nblsock = 0;
    436 	flush = 0;
    437 	restore = 0;
    438 	tout = 0;
    439 	flags = O_RDWR|O_EXCL|O_CLOEXEC;
    440 	while ((c = getopt(argc, argv, "C:c:D:dfP:rR:s:t:v")) != -1) {
    441 		switch (c) {
    442 		case 'C':
    443 			controlprog = optarg;
    444 			break;
    445 		case 'c':
    446 			configfile = optarg;
    447 			break;
    448 		case 'D':
    449 			dbfile = optarg;
    450 			break;
    451 		case 'd':
    452 			debug++;
    453 			break;
    454 		case 'f':
    455 			flush++;
    456 			break;
    457 		case 'P':
    458 			spath = optarg;
    459 			break;
    460 		case 'R':
    461 			rulename = optarg;
    462 			break;
    463 		case 'r':
    464 			restore++;
    465 			break;
    466 		case 's':
    467 			if (nblsock >= maxblsock) {
    468 				maxblsock += 10;
    469 				void *p = realloc(blsock,
    470 				    sizeof(*blsock) * maxblsock);
    471 				if (p == NULL)
    472 				    err(EXIT_FAILURE,
    473 					"Can't allocate memory for %zu sockets",
    474 					maxblsock);
    475 				blsock = p;
    476 			}
    477 			blsock[nblsock++] = optarg;
    478 			break;
    479 		case 't':
    480 			tout = atoi(optarg) * 1000;
    481 			break;
    482 		case 'v':
    483 			vflag++;
    484 			break;
    485 		default:
    486 			usage(c);
    487 		}
    488 	}
    489 
    490 	argc -= optind;
    491 	if (argc)
    492 		usage('?');
    493 
    494 	signal(SIGHUP, sighup);
    495 	signal(SIGINT, sigdone);
    496 	signal(SIGQUIT, sigdone);
    497 	signal(SIGTERM, sigdone);
    498 	signal(SIGUSR1, sigusr1);
    499 	signal(SIGUSR2, sigusr2);
    500 
    501 	openlog(getprogname(), LOG_PID, LOG_DAEMON);
    502 
    503 	if (debug) {
    504 		lfun = dlog;
    505 		if (tout == 0)
    506 			tout = 5000;
    507 	} else {
    508 		if (tout == 0)
    509 			tout = 15000;
    510 	}
    511 
    512 	update_interfaces();
    513 	conf_parse(configfile);
    514 	if (flush) {
    515 		rules_flush();
    516 		if (!restore)
    517 			flags |= O_TRUNC;
    518 	}
    519 
    520 	struct pollfd *pfd = NULL;
    521 	bl_t *bl = NULL;
    522 	size_t nfd = 0;
    523 	size_t maxfd = 0;
    524 
    525 	for (size_t i = 0; i < nblsock; i++)
    526 		addfd(&pfd, &bl, &nfd, &maxfd, blsock[i]);
    527 	free(blsock);
    528 
    529 	if (spath) {
    530 		FILE *fp = fopen(spath, "r");
    531 		char *line;
    532 		if (fp == NULL)
    533 			err(EXIT_FAILURE, "Can't open `%s'", spath);
    534 		for (; (line = fparseln(fp, NULL, NULL, NULL, 0)) != NULL;
    535 		    free(line))
    536 			addfd(&pfd, &bl, &nfd, &maxfd, line);
    537 		fclose(fp);
    538 	}
    539 	if (nfd == 0)
    540 		addfd(&pfd, &bl, &nfd, &maxfd, _PATH_BLSOCK);
    541 
    542 	state = state_open(dbfile, flags, 0600);
    543 	if (state == NULL)
    544 		state = state_open(dbfile,  flags | O_CREAT, 0600);
    545 	if (state == NULL)
    546 		return EXIT_FAILURE;
    547 
    548 	if (restore) {
    549 		if (!flush)
    550 			rules_flush();
    551 		rules_restore();
    552 	}
    553 
    554 	if (!debug) {
    555 		if (daemon(0, 0) == -1)
    556 			err(EXIT_FAILURE, "daemon failed");
    557 		if (pidfile(NULL) == -1)
    558 			err(EXIT_FAILURE, "Can't create pidfile");
    559 	}
    560 
    561 	for (size_t t = 0; !done; t++) {
    562 		if (readconf) {
    563 			readconf = 0;
    564 			conf_parse(configfile);
    565 		}
    566 		ret = poll(pfd, (nfds_t)nfd, tout);
    567 		if (debug)
    568 			(*lfun)(LOG_DEBUG, "received %d from poll()", ret);
    569 		switch (ret) {
    570 		case -1:
    571 			if (errno == EINTR)
    572 				continue;
    573 			(*lfun)(LOG_ERR, "poll (%m)");
    574 			return EXIT_FAILURE;
    575 		case 0:
    576 			state_sync(state);
    577 			break;
    578 		default:
    579 			for (size_t i = 0; i < nfd; i++)
    580 				if (pfd[i].revents & POLLIN)
    581 					process(bl[i]);
    582 		}
    583 		if (t % 100 == 0)
    584 			state_sync(state);
    585 		if (t % 10000 == 0)
    586 			update_interfaces();
    587 		update();
    588 	}
    589 	state_close(state);
    590 	return 0;
    591 }
    592