diff options
Diffstat (limited to 'contrib/blocklist/bin')
23 files changed, 1928 insertions, 133 deletions
diff --git a/contrib/blocklist/bin/Makefile b/contrib/blocklist/bin/Makefile index 280c72fd3af1..1856e2524f3c 100644 --- a/contrib/blocklist/bin/Makefile +++ b/contrib/blocklist/bin/Makefile @@ -1,12 +1,12 @@ -# $NetBSD: Makefile,v 1.11 2015/01/27 19:40:36 christos Exp $ +# $NetBSD: Makefile,v 1.1.1.1 2020/06/15 01:52:52 christos Exp $  BINDIR=/sbin -PROGS=blacklistd blacklistctl -MAN.blacklistd=blacklistd.8 blacklistd.conf.5 -MAN.blacklistctl=blacklistctl.8 -SRCS.blacklistd = blacklistd.c conf.c run.c state.c support.c internal.c -SRCS.blacklistctl = blacklistctl.c conf.c state.c support.c internal.c +PROGS=blocklistd blocklistctl +MAN.blocklistd=blocklistd.8 blocklistd.conf.5 +MAN.blocklistctl=blocklistctl.8 +SRCS.blocklistd = blocklistd.c conf.c run.c state.c support.c internal.c +SRCS.blocklistctl = blocklistctl.c conf.c state.c support.c internal.c  DBG=-g  LDADD+=-lutil diff --git a/contrib/blocklist/bin/blacklistctl.8 b/contrib/blocklist/bin/blacklistctl.8 index 7c6521117745..08f1d1b9e5af 100644 --- a/contrib/blocklist/bin/blacklistctl.8 +++ b/contrib/blocklist/bin/blacklistctl.8 @@ -1,4 +1,4 @@ -.\" $NetBSD: blacklistctl.8,v 1.9 2016/06/08 12:48:37 wiz Exp $ +.\" $NetBSD: blocklistctl.8,v 1.4 2025/02/07 01:35:38 kre Exp $  .\"  .\" Copyright (c) 2015 The NetBSD Foundation, Inc.  .\" All rights reserved. @@ -27,27 +27,42 @@  .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE  .\" POSSIBILITY OF SUCH DAMAGE.  .\" -.Dd June 7, 2016 +.Dd January 27, 2025  .Dt BLACKLISTCTL 8  .Os  .Sh NAME  .Nm blacklistctl -.Nd display and change the state of blacklistd +.Nd display and change the state of the blacklistd database  .Sh SYNOPSIS  .Nm  .Cm dump  .Op Fl abdnrw +.Op Fl D Ar dbname  .Sh DESCRIPTION  .Nm -is a program used to display the state of +is a program used to display and change the state of the  .Xr blacklistd 8 -.Pp -The following options are available: +database. +The following sub-commands are supported: +.Ss dump +The following options are available for the +.Cm dump +sub-command:  .Bl -tag -width indent  .It Fl a -Show all database entries, by default it shows only the embryonic ones. +Show all database entries, by default it shows only the active ones. +Inactive entries will be shown with a last-access (or, with +.Fl r , +the remaining) time of +.Ql never .  .It Fl b  Show only the blocked entries. +.It Fl D Ar dbname +Specify the location of the +.Ic blacklistd +database file to use. +The default is +.Pa /var/db/blocklistd.db .  .It Fl d  Increase debugging level.  .It Fl n @@ -59,9 +74,43 @@ Normally the width of addresses is good for IPv4, the  .Fl w  flag, makes the display wide enough for IPv6 addresses.  .El +.Pp +The output of the +.Cm dump +sub-command consists of a header (unless +.Fl n +was given) and one line for each record in the database, where each line +has the following columns: +.Bl -tag -width indent +.It Ql address/ma:port +The remote address, mask, and local port number of the client connection +associated with the database entry. +.It Ql id +column will show the identifier for the packet filter rule associated +with the database entry, though this may only be the word +.Ql OK +for packet filters which do not create a unique identifier for each rule. +.It Ql nfail +The number of +.Em failures +reported for the client on the noted port, as well as the number of +failures allowed before blocking (or, with +.Fl a , +an asterisk +.Aq * ) +.It So last access Sc | So remaining time Sc +The last time a the client was reported as attempting access, or, with +.Fl r , +the time remaining before the rule blocking the client will be removed. +.El  .Sh SEE ALSO  .Xr blacklistd 8  .Sh NOTES +The +.Nm +program has been renamed to +.Xr blocklistctl 8 . +.Pp  Sometimes the reported number of failed attempts can exceed the number  of attempts that  .Xr blacklistd 8 diff --git a/contrib/blocklist/bin/blacklistctl.c b/contrib/blocklist/bin/blacklistctl.c index 89b72921caf5..6298a08b10b4 100644 --- a/contrib/blocklist/bin/blacklistctl.c +++ b/contrib/blocklist/bin/blacklistctl.c @@ -1,4 +1,4 @@ -/*	$NetBSD: blacklistctl.c,v 1.23 2018/05/24 19:21:01 christos Exp $	*/ +/*	$NetBSD: blocklistctl.c,v 1.4 2025/02/11 17:48:30 christos Exp $	*/  /*-   * Copyright (c) 2015 The NetBSD Foundation, Inc. @@ -32,8 +32,10 @@  #include "config.h"  #endif +#ifdef HAVE_SYS_CDEFS_H  #include <sys/cdefs.h> -__RCSID("$NetBSD: blacklistctl.c,v 1.23 2018/05/24 19:21:01 christos Exp $"); +#endif +__RCSID("$NetBSD: blocklistctl.c,v 1.4 2025/02/11 17:48:30 christos Exp $");  #include <stdio.h>  #include <time.h> @@ -53,7 +55,7 @@ __RCSID("$NetBSD: blacklistctl.c,v 1.23 2018/05/24 19:21:01 christos Exp $");  #include "conf.h"  #include "state.h" -#include "internal.h" +#include "old_internal.h"  #include "support.h"  static __dead void @@ -63,7 +65,8 @@ usage(int c)  		warnx("Missing/unknown command");  	else if (c != '?')  		warnx("Unknown option `%c'", (char)c); -	fprintf(stderr, "Usage: %s dump [-abdnrw]\n", getprogname()); +	fprintf(stderr, +	    "Usage: %s dump [-abdnrw] [-D dbname]\n", getprogname());  	exit(EXIT_FAILURE);  } diff --git a/contrib/blocklist/bin/blacklistd.8 b/contrib/blocklist/bin/blacklistd.8 index 82e1f15f61c9..9ca886e9c4d3 100644 --- a/contrib/blocklist/bin/blacklistd.8 +++ b/contrib/blocklist/bin/blacklistd.8 @@ -1,4 +1,4 @@ -.\" $NetBSD: blacklistd.8,v 1.23 2020/04/21 13:57:12 christos Exp $ +.\" $NetBSD: blocklistd.8,v 1.8 2025/02/25 22:13:34 christos Exp $  .\"  .\" Copyright (c) 2015 The NetBSD Foundation, Inc.  .\" All rights reserved. @@ -27,7 +27,7 @@  .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE  .\" POSSIBILITY OF SUCH DAMAGE.  .\" -.Dd April 21, 2020 +.Dd February 25, 2025  .Dt BLACKLISTD 8  .Os  .Sh NAME @@ -53,18 +53,31 @@ for notifications from other daemons about successful or failed connection  attempts.  If no such file is specified, then it only listens to the socket path  specified by -.Ar sockspath +.Ar sockpath  or if that is not specified to -.Pa /var/run/blacklistd.sock . +.Pa /var/run/blocklistd.sock .  Each notification contains an (action, port, protocol, address, owner) tuple  that identifies the remote connection and the action. -This tuple is consulted against entries in -.Ar configfile -with syntax specified in +This tuple is consulted against entries from the +.Ar configfile , +with the syntax specified in  .Xr blacklistd.conf 5 .  If an entry is matched, a state entry is created for that tuple.  Each entry contains a number of tries limit and a duration.  .Pp +If +.Ar configfile +is a directory, or a directory exists with the same name as +.Ar configfile +with +.Qq .d +appended to it, each file in the directory will be read as configuration file. +If +.Ar configfile +exists as a file it will be processed before the contents of the +.Ar configfile Ns .d +directory if that also exists. +.Pp  The way  .Nm  does configuration entry matching is by having the client side pass the @@ -152,7 +165,7 @@ The following options are available:  .It Fl C Ar controlprog  Use  .Ar controlprog -to communicate with the packet filter, usually +to communicate with the packet filter, instead of the default, which is  .Pa /usr/libexec/blacklistd-helper .  The following arguments are passed to the control program:  .Bl -tag -width protocol @@ -161,7 +174,7 @@ The action to perform:  .Dv add ,  .Dv rem ,  or -.Dv flush +.Dv flush ;  to add, remove or flush a firewall rule.  .It name  The rule name. @@ -183,13 +196,17 @@ identifier of the rule to be removed.  The add command is expected to return the rule identifier string to stdout.  .El  .It Fl c Ar configuration -The name of the configuration file to read, usually +The name of the configuration file to read. +The default when +.Fl c +is not given is  .Pa /etc/blacklistd.conf .  .It Fl D Ar dbfile  The Berkeley DB file where  .Nm -stores its state, usually -.Pa /var/db/blacklistd.db . +stores its state. +It defaults to +.Pa /var/db/blocklistd.db .  .It Fl d  Normally,  .Nm @@ -203,7 +220,7 @@ are deleted by invoking the control script as:  .Bd -literal -offset indent  control flush <rulename>  .Ed -.It Fl P Ar sockspathsfile +.It Fl P Ar sockpathsfile  A file containing a list of pathnames, one per line that  .Nm  will create sockets to listen to. @@ -261,16 +278,23 @@ to decrease the internal debugging level by 1.  Shell script invoked to interface with the packet filter.  .It Pa /etc/blacklistd.conf  Configuration file. -.It Pa /var/db/blacklistd.db +.It Pa /var/db/blocklistd.db  Database of current connection entries. -.It Pa /var/run/blacklistd.sock +.It Pa /var/run/blocklistd.sock  Socket to receive connection notifications.  .El  .Sh SEE ALSO  .Xr blacklistd.conf 5 ,  .Xr blacklistctl 8 , +.Xr ipf 8 , +.Xr ipfw 8 ,  .Xr pfctl 8 ,  .Xr syslogd 8 +.Sh NOTES +The +.Nm +daemon has been renamed to +.Xr blocklistd 8 .  .Sh HISTORY  .Nm  first appeared in diff --git a/contrib/blocklist/bin/blacklistd.c b/contrib/blocklist/bin/blacklistd.c index 714abcbcaf0e..cb6ce6578d9c 100644 --- a/contrib/blocklist/bin/blacklistd.c +++ b/contrib/blocklist/bin/blacklistd.c @@ -1,4 +1,4 @@ -/*	$NetBSD: blacklistd.c,v 1.38 2019/02/27 02:20:18 christos Exp $	*/ +/*	$NetBSD: blocklistd.c,v 1.12 2025/10/25 18:43:51 christos Exp $	*/  /*-   * Copyright (c) 2015 The NetBSD Foundation, Inc. @@ -31,8 +31,11 @@  #ifdef HAVE_CONFIG_H  #include "config.h"  #endif + +#ifdef HAVE_SYS_CDEFS_H  #include <sys/cdefs.h> -__RCSID("$NetBSD: blacklistd.c,v 1.38 2019/02/27 02:20:18 christos Exp $"); +#endif +__RCSID("$NetBSD: blocklistd.c,v 1.12 2025/10/25 18:43:51 christos Exp $");  #include <sys/types.h>  #include <sys/socket.h> @@ -64,8 +67,8 @@ __RCSID("$NetBSD: blacklistd.c,v 1.38 2019/02/27 02:20:18 christos Exp $");  #include <ifaddrs.h>  #include <netinet/in.h> -#include "bl.h" -#include "internal.h" +#include "old_bl.h" +#include "old_internal.h"  #include "conf.h"  #include "run.h"  #include "state.h" @@ -175,6 +178,8 @@ process(bl_t bl)  	struct dbinfo dbi;  	struct timespec ts; +	memset(&dbi, 0, sizeof(dbi)); +	memset(&c, 0, sizeof(c));  	if (clock_gettime(CLOCK_REALTIME, &ts) == -1) {  		(*lfun)(LOG_ERR, "clock_gettime failed (%m)");  		return; @@ -186,24 +191,25 @@ process(bl_t bl)  	}  	if (getremoteaddress(bi, &rss, &rsl) == -1) -		goto out; +		return; -	if (debug) { +	if (debug || bi->bi_msg[0]) {  		sockaddr_snprintf(rbuf, sizeof(rbuf), "%a:%p", (void *)&rss); -		(*lfun)(LOG_DEBUG, "processing type=%d fd=%d remote=%s msg=%s" -		    " uid=%lu gid=%lu", bi->bi_type, bi->bi_fd, rbuf, +		(*lfun)(bi->bi_msg[0] ? LOG_INFO : LOG_DEBUG, +		    "processing type=%d fd=%d remote=%s msg=\"%s\" uid=%lu gid=%lu", +		    bi->bi_type, bi->bi_fd, rbuf,  		    bi->bi_msg, (unsigned long)bi->bi_uid,  		    (unsigned long)bi->bi_gid);  	}  	if (conf_find(bi->bi_fd, bi->bi_uid, &rss, &c) == NULL) {  		(*lfun)(LOG_DEBUG, "no rule matched"); -		goto out; +		return;  	}  	if (state_get(state, &c, &dbi) == -1) -		goto out; +		return;  	if (debug) {  		char b1[128], b2[128]; @@ -220,7 +226,7 @@ process(bl_t bl)  		 * set the number of fails to be one less than the  		 * configured limit.  Fallthrough to the normal BL_ADD  		 * processing, which will increment the failure count -		 * to the threshhold, and block the abusive address. +		 * to the threshold, and block the abusive address.  		 */  		if (c.c_nfail != -1)  			dbi.count = c.c_nfail - 1; @@ -263,8 +269,6 @@ process(bl_t bl)  	state_put(state, &c, &dbi);  out: -	close(bi->bi_fd); -  	if (debug) {  		char b1[128], b2[128];  		(*lfun)(LOG_DEBUG, "%s: final db state for %s: count=%d/%d " @@ -325,8 +329,8 @@ again:  			(*lfun)(LOG_INFO, "released %s/%d:%d after %d seconds",  			    buf, c.c_lmask, c.c_port, c.c_duration);  		} -		state_del(state, &c); -		goto again; +		if (state_del(state, &c) == 0) +			goto again;  	}  } @@ -334,7 +338,7 @@ static void  addfd(struct pollfd **pfdp, bl_t **blp, size_t *nfd, size_t *maxfd,      const char *path)  { -	bl_t bl = bl_create(true, path, vflag ? vdlog : vsyslog); +	bl_t bl = bl_create(true, path, vflag ? vdlog : vsyslog_r);  	if (bl == NULL || !bl_isconnected(bl))  		exit(EXIT_FAILURE);  	if (*nfd >= *maxfd) { @@ -395,15 +399,25 @@ rules_flush(void)  static void  rules_restore(void)  { +	DB *db;  	struct conf c;  	struct dbinfo dbi;  	unsigned int f; -	for (f = 1; state_iterate(state, &c, &dbi, f) == 1; f = 0) { +	db = state_open(dbfile, O_RDONLY, 0); +	if (db == NULL) { +		(*lfun)(LOG_ERR, "Can't open `%s' to restore state (%m)", +			dbfile); +		return; +	} +	for (f = 1; state_iterate(db, &c, &dbi, f) == 1; f = 0) {  		if (dbi.id[0] == '\0')  			continue;  		(void)run_change("add", &c, dbi.id, sizeof(dbi.id)); +		state_put(state, &c, &dbi);  	} +	state_close(db); +	state_sync(state);  }  int @@ -549,7 +563,7 @@ main(int argc, char *argv[])  			conf_parse(configfile);  		}  		ret = poll(pfd, (nfds_t)nfd, tout); -		if (debug) +		if (debug && ret != 0)  			(*lfun)(LOG_DEBUG, "received %d from poll()", ret);  		switch (ret) {  		case -1: diff --git a/contrib/blocklist/bin/blacklistd.conf.5 b/contrib/blocklist/bin/blacklistd.conf.5 index 70036441eb4b..e775d30e7e8e 100644 --- a/contrib/blocklist/bin/blacklistd.conf.5 +++ b/contrib/blocklist/bin/blacklistd.conf.5 @@ -1,6 +1,6 @@ -.\" $NetBSD: blacklistd.conf.5,v 1.9 2019/11/06 20:33:30 para Exp $ +.\" $NetBSD: blocklistd.conf.5,v 1.7 2025/02/11 17:47:05 christos Exp $  .\" -.\" Copyright (c) 2015 The NetBSD Foundation, Inc. +.\" Copyright (c) 2015, 2025 The NetBSD Foundation, Inc.  .\" All rights reserved.  .\"  .\" This code is derived from software contributed to The NetBSD Foundation @@ -27,7 +27,7 @@  .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE  .\" POSSIBILITY OF SUCH DAMAGE.  .\" -.Dd May 18, 2020 +.Dd February 5, 2025  .Dt BLACKLISTD.CONF 5  .Os  .Sh NAME @@ -48,34 +48,34 @@ Comments are denoted by a  at the beginning of a line.  .Pp  There are two kinds of configuration lines, -.Va local +.Va [local]  and -.Va remote . +.Va [remote] .  By default, configuration lines are -.Va local , +.Va [local] ,  i.e. the address specified refers to the addresses on the local machine.  To switch to between -.Va local +.Va [local]  and -.Va remote +.Va [remote]  configuration lines you can specify the stanzas:  .Dq [local]  and  .Dq [remote] .  .Pp  On -.Va local +.Va [local]  and -.Va remote +.Va [remote]  lines  .Dq *  means use the default, or wildcard match.  In addition, for -.Va remote +.Va [remote]  lines  .Dq =  means use the values from the matched -.Va local +.Va [local]  configuration line.  .Pp  The first four fields, @@ -85,9 +85,9 @@ The first four fields,  and  .Va owner  are used to match the -.Va local +.Va [local]  or -.Va remote +.Va [remote]  addresses, whereas the last 3 fields  .Va name ,  .Va nfail , @@ -110,8 +110,8 @@ The  can be an IPv4 address in numeric format, an IPv6 address  in numeric format and enclosed by square brackets, or an interface name.  Mask modifiers are not allowed on interfaces because interfaces -can have multiple addresses in different protocols where the mask has a different -size. +can have multiple addresses in different protocols where the mask has a +different size.  .Pp  The  .Dv mask @@ -143,8 +143,8 @@ The  field, is the name of the packet filter rule to be used.  If the  .Va name -starts with a -.Dq - , +starts with a hyphen +.Pq Dq - ,  then the default rulename is prepended to the given name.  If the  .Dv name @@ -160,13 +160,13 @@ field contains the number of failed attempts before access is blocked,  defaulting to  .Dq *  meaning never, and the last field -.Va disable +.Va duration  specifies the amount of time since the last access that the blocking  rule should be active, defaulting to  .Dq *  meaning forever.  The default unit for -.Va disable +.Va duration  is seconds, but one can specify suffixes for different units, such as  .Dq m  for minutes @@ -176,25 +176,31 @@ for hours and  for days.  .Pp  Matching is done first by checking the -.Va local +.Va [local]  rules individually, in the order of the most specific to the least specific. -If a match is found, then the -.Va remote +If a match is found, then the matching +.Va [remote]  rules are applied.  The  .Va name ,  .Va nfail ,  and -.Va disable +.Va duration  fields can be altered by the -.Va remote +.Va [remote]  rule that matched.  .Pp  The -.Va remote +.Va [remote]  rules can be used for allowing specific addresses, changing the mask -size, the rule that the packet filter uses, the number of failed attempts, -or the block duration. +size (via +.Va name ) , +the rule that the packet filter uses (also via +.Va name ) , +the number of failed attempts (via +.Va nfail ) , +or the duration to block (via +.Va duration ) .  .Sh FILES  .Bl -tag -width /etc/blacklistd.conf -compact  .It Pa /etc/blacklistd.conf @@ -209,13 +215,20 @@ bnx0:ssh	*	*	*	*	3	6h  [remote]  # Never block 1.2.3.4  1.2.3.4:ssh	*	*	*	*	*	* -# For addresses coming from 8.8.0.0/16 block whole /24 networks instead of +# Never block the example IPv6 subnet either +[2001:db8::]/32:ssh	*	*	*	*	*	* +# For addresses coming from 8.8.0.0/16 block whole /24 networks instead  # individual hosts, but keep the rest of the blocking parameters the same.  8.8.0.0/16:ssh	*	*	*	/24	=	=  .Ed  .Sh SEE ALSO  .Xr blacklistctl 8 ,  .Xr blacklistd 8 +.Sh NOTES +The +.Nm +file has been renamed to +.Xr blocklistd.conf 8 .  .Sh HISTORY  .Nm  first appeared in diff --git a/contrib/blocklist/bin/blocklistctl.8 b/contrib/blocklist/bin/blocklistctl.8 new file mode 100644 index 000000000000..d241f2844471 --- /dev/null +++ b/contrib/blocklist/bin/blocklistctl.8 @@ -0,0 +1,134 @@ +.\" $NetBSD: blocklistctl.8,v 1.6 2025/10/26 13:49:22 christos Exp $ +.\" +.\" Copyright (c) 2015 The NetBSD Foundation, Inc. +.\" All rights reserved. +.\" +.\" This code is derived from software contributed to The NetBSD Foundation +.\" by Christos Zoulas. +.\" +.\" Redistribution and use in source and binary forms, with or without +.\" modification, are permitted provided that the following conditions +.\" are met: +.\" 1. Redistributions of source code must retain the above copyright +.\"    notice, this list of conditions and the following disclaimer. +.\" 2. Redistributions in binary form must reproduce the above copyright +.\"    notice, this list of conditions and the following disclaimer in the +.\"    documentation and/or other materials provided with the distribution. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS +.\" ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +.\" TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +.\" PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS +.\" BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +.\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +.\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +.\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +.\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +.\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +.\" POSSIBILITY OF SUCH DAMAGE. +.\" +.Dd October 25, 2025 +.Dt BLOCKLISTCTL 8 +.Os +.Sh NAME +.Nm blocklistctl +.Nd display and change the state of the blocklistd database +.Sh SYNOPSIS +.Nm +.Cm dump +.Op Fl abdnrw +.Op Fl D Ar dbname +.Sh DESCRIPTION +.Nm +is a program used to display and change the state of the +.Xr blocklistd 8 +database. +The following sub-commands are supported: +.Ss dump +The following options are available for the +.Cm dump +sub-command: +.Bl -tag -width indent +.It Fl a +Show all database entries, by default it shows only the active ones. +Inactive entries will be shown with a last-access (or, with +.Fl r , +the remaining) time of +.Ql never . +.It Fl b +Show only the blocked entries. +.It Fl D Ar dbname +Specify the location of the +.Ic blocklistd +database file to use. +The default is +.Pa /var/db/blocklistd.db . +.It Fl d +Increase debugging level. +.It Fl n +Don't display a header. +.It Fl r +Show the remaining blocked time instead of the last activity time. +.It Fl w +Normally the width of addresses is good for IPv4, the +.Fl w +flag, makes the display wide enough for IPv6 addresses. +.El +.Pp +The output of the +.Cm dump +sub-command consists of a header (unless +.Fl n +was given) and one line for each record in the database, where each line +has the following columns: +.Bl -tag -width indent +.It Ql rulename +The packet filter rule name associated with the database entry, +usually +.Dv blocklistd . +.It Ql address/ma:port +The remote address, mask, and local port number of the client connection +associated with the database entry. +.It Ql id +column will show the identifier for the packet filter rule associated +with the database entry, though this may only be the word +.Ql OK +for packet filters which do not create a unique identifier for each rule. +.It Ql nfail +The number of +.Em failures +reported for the client on the noted port, as well as the number of +failures allowed before blocking (or, with +.Fl a , +an asterisk +.Aq * ) +.It So last access Sc | So remaining time Sc +The last time a the client was reported as attempting access, or, with +.Fl r , +the time remaining before the rule blocking the client will be removed. +.El +.Sh SEE ALSO +.Xr blocklistd 8 +.Sh NOTES +Sometimes the reported number of failed attempts can exceed the number +of attempts that +.Xr blocklistd 8 +is configured to block. +This can happen either because the rule has been removed manually, or +because there were more attempts in flight while the rule block was being +added. +This condition is normal; in that case +.Xr blocklistd 8 +will first attempt to remove the existing rule, and then it will re-add +it to make sure that there is only one rule active. +.Sh HISTORY +.Nm +first appeared in +.Nx 7 . +.Fx +support for +.Nm +was implemented in +.Fx 11 . +.Sh AUTHORS +.An Christos Zoulas diff --git a/contrib/blocklist/bin/blocklistctl.c b/contrib/blocklist/bin/blocklistctl.c new file mode 100644 index 000000000000..b43d8b8aaab3 --- /dev/null +++ b/contrib/blocklist/bin/blocklistctl.c @@ -0,0 +1,170 @@ +/*	$NetBSD: blocklistctl.c,v 1.5 2025/10/25 16:56:10 christos Exp $	*/ + +/*- + * Copyright (c) 2015 The NetBSD Foundation, Inc. + * All rights reserved. + * + * This code is derived from software contributed to The NetBSD Foundation + * by Christos Zoulas. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + *    notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + *    notice, this list of conditions and the following disclaimer in the + *    documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS + * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#ifdef HAVE_SYS_CDEFS_H +#include <sys/cdefs.h> +#endif +__RCSID("$NetBSD: blocklistctl.c,v 1.5 2025/10/25 16:56:10 christos Exp $"); + +#include <stdio.h> +#include <time.h> +#ifdef HAVE_LIBUTIL_H +#include <libutil.h> +#endif +#ifdef HAVE_UTIL_H +#include <util.h> +#endif +#include <fcntl.h> +#include <string.h> +#include <syslog.h> +#include <err.h> +#include <stdlib.h> +#include <unistd.h> +#include <sys/socket.h> + +#include "conf.h" +#include "state.h" +#include "internal.h" +#include "support.h" + +static __dead void +usage(int c) +{ +	if (c == 0) +		warnx("Missing/unknown command"); +	else if (c != '?') +		warnx("Unknown option `%c'", (char)c); +	fprintf(stderr, +	    "Usage: %s dump [-abdnrw] [-D dbname]\n", getprogname()); +	exit(EXIT_FAILURE); +} + +static const char * +star(char *buf, size_t len, int val) +{ +	if (val == -1) +		return "*"; +	snprintf(buf, len, "%d", val); +	return buf; +} + +int +main(int argc, char *argv[]) +{ +	const char *dbname = _PATH_BLSTATE; +	DB *db; +	struct conf c; +	struct dbinfo dbi; +	unsigned int i; +	struct timespec ts; +	int all, blocked, remain, wide, noheader; +	int o; + +	noheader = wide = blocked = all = remain = 0; +	lfun = dlog; + +	if (argc == 1 || strcmp(argv[1], "dump") != 0) +		usage(0); + +	argc--; +	argv++; + +	while ((o = getopt(argc, argv, "abD:dnrw")) != -1) +		switch (o) { +		case 'a': +			all = 1; +			blocked = 0; +			break; +		case 'b': +			blocked = 1; +			break; +		case 'D': +			dbname = optarg; +			break; +		case 'd': +			debug++; +			break; +		case 'n': +			noheader = 1; +			break; +		case 'r': +			remain = 1; +			break; +		case 'w': +			wide = 1; +			break; +		default: +			usage(o); +		} + +	db = state_open(dbname, O_RDONLY, 0); +	if (db == NULL) +		err(EXIT_FAILURE, "Can't open `%s'", dbname); + +	clock_gettime(CLOCK_REALTIME, &ts); +	wide = wide ? 8 * 4 + 7 : 4 * 3 + 3; +	if (!noheader) +		printf("rulename\t%*.*s/ma:port\tid\tnfail\t%s\n", wide, wide, +		    "address", remain ? "remaining time" : "last access"); +	for (i = 1; state_iterate(db, &c, &dbi, i) != 0; i = 0) { +		char buf[BUFSIZ]; +		char mbuf[64], pbuf[64]; +		if (!all) { +			if (blocked) { +				if (c.c_nfail == -1 || dbi.count < c.c_nfail) +					continue; +			} else { +				if (dbi.count >= c.c_nfail) +					continue; +			} +		} +		sockaddr_snprintf(buf, sizeof(buf), "%a", (void *)&c.c_ss); +		printf("%s\t%*.*s/%s:%s\t", c.c_name, wide, wide, buf, +		    star(mbuf, sizeof(mbuf), c.c_lmask), +		    star(pbuf, sizeof(pbuf), c.c_port)); +		if (c.c_duration == -1) { +			strlcpy(buf, "never", sizeof(buf)); +		} else { +			if (remain) +				fmtydhms(buf, sizeof(buf), +				    c.c_duration - (ts.tv_sec - dbi.last)); +			else +				fmttime(buf, sizeof(buf), dbi.last); +		} +		printf("%s\t%d/%s\t%-s\n", dbi.id, dbi.count, +		    star(mbuf, sizeof(mbuf), c.c_nfail), buf); +	} +	state_close(db); +	return EXIT_SUCCESS; +} diff --git a/contrib/blocklist/bin/blocklistd.8 b/contrib/blocklist/bin/blocklistd.8 new file mode 100644 index 000000000000..e0b9fb482cbd --- /dev/null +++ b/contrib/blocklist/bin/blocklistd.8 @@ -0,0 +1,303 @@ +.\" $NetBSD: blocklistd.8,v 1.8 2025/02/25 22:13:34 christos Exp $ +.\" +.\" Copyright (c) 2015 The NetBSD Foundation, Inc. +.\" All rights reserved. +.\" +.\" This code is derived from software contributed to The NetBSD Foundation +.\" by Christos Zoulas. +.\" +.\" Redistribution and use in source and binary forms, with or without +.\" modification, are permitted provided that the following conditions +.\" are met: +.\" 1. Redistributions of source code must retain the above copyright +.\"    notice, this list of conditions and the following disclaimer. +.\" 2. Redistributions in binary form must reproduce the above copyright +.\"    notice, this list of conditions and the following disclaimer in the +.\"    documentation and/or other materials provided with the distribution. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS +.\" ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +.\" TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +.\" PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS +.\" BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +.\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +.\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +.\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +.\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +.\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +.\" POSSIBILITY OF SUCH DAMAGE. +.\" +.Dd February 25, 2025 +.Dt BLOCKLISTD 8 +.Os +.Sh NAME +.Nm blocklistd +.Nd block and release ports on demand to avoid DoS abuse +.Sh SYNOPSIS +.Nm +.Op Fl dfrv +.Op Fl C Ar controlprog +.Op Fl c Ar configfile +.Op Fl D Ar dbfile +.Op Fl P Ar sockpathsfile +.Op Fl R Ar rulename +.Op Fl s Ar sockpath +.Op Fl t Ar timeout +.Sh DESCRIPTION +.Nm +is a daemon similar to +.Xr syslogd 8 +that listens to sockets at paths specified in the +.Ar sockpathsfile +for notifications from other daemons about successful or failed connection +attempts. +If no such file is specified, then it only listens to the socket path +specified by +.Ar sockpath +or if that is not specified to +.Pa /var/run/blocklistd.sock . +Each notification contains an (action, port, protocol, address, owner) tuple +that identifies the remote connection and the action. +This tuple is consulted against entries from the +.Ar configfile , +with the syntax specified in +.Xr blocklistd.conf 5 . +If an entry is matched, a state entry is created for that tuple. +Each entry contains a number of tries limit and a duration. +.Pp +If +.Ar configfile +is a directory, or a directory exists with the same name as +.Ar configfile +with +.Qq .d +appended to it, each file in the directory will be read as configuration file. +If +.Ar configfile +exists as a file it will be processed before the contents of the +.Ar configfile Ns .d +directory if that also exists. +.Pp +The way +.Nm +does configuration entry matching is by having the client side pass the +file descriptor associated with the connection the client wants to blocklist +as well as passing socket credentials. +.Pp +The file descriptor is used to retrieve information (address and port) +about the remote side with +.Xr getpeername 2 +and the local side with +.Xr getsockname 2 . +.Pp +By examining the port of the local side, +.Nm +can determine if the client program +.Dq owns +the port. +By examining the optional address portion on the local side, it can match +interfaces. +By examining the remote address, it can match specific allow or deny rules. +.Pp +Finally +.Nm +can examine the socket credentials to match the user in the configuration file. +.Pp +While this works well for TCP sockets, it cannot be relied on for unbound +UDP sockets. +It is also less meaningful when it comes to connections using non-privileged +ports. +On the other hand, if we receive a request that has a local endpoint indicating +a UDP privileged port, we can presume that the client was privileged to be +able to acquire that port. +.Pp +Once an entry is matched +.Nm +can perform various actions. +If the action is +.Dq add +and the number of tries limit is reached, then a +control script +.Ar controlprog +is invoked with arguments: +.Bd -literal -offset indent +control add <rulename> <proto> <address> <mask> <port> +.Ed +.Pp +and should invoke a packet filter command to block the connection +specified by the arguments. +The +.Ar rulename +argument can be set from the command line (default +.Dv blocklistd ) . +The script could print a numerical id to stdout as a handle for +the rule that can be used later to remove that connection, but +that is not required as all information to remove the rule is +kept. +.Pp +If the action is +.Dq rem +Then the same control script is invoked as: +.Bd -literal -offset indent +control rem <rulename> <proto> <address> <mask> <port> <id> +.Ed +.Pp +where +.Ar id +is the number returned from the +.Dq add +action. +.Pp +.Nm +maintains a database of known connections in +.Ar dbfile . +On startup it reads entries from that file, and updates its internal state. +.Pp +.Nm +checks the list of active entries every +.Ar timeout +seconds (default +.Dv 15 ) +and removes entries and block rules using the control program as necessary. +.Pp +The following options are available: +.Bl -tag -width indent +.It Fl C Ar controlprog +Use +.Ar controlprog +to communicate with the packet filter, instead of the default, which is +.Pa /usr/libexec/blocklistd-helper . +The following arguments are passed to the control program: +.Bl -tag -width protocol +.It action +The action to perform: +.Dv add , +.Dv rem , +or +.Dv flush ; +to add, remove or flush a firewall rule. +.It name +The rule name. +.It protocol +The optional protocol name (can be empty): +.Dv tcp , +.Dv tcp6 , +.Dv udp , +.Dv udp6 . +.It address +The IPv4 or IPv6 numeric address to be blocked or released. +.It mask +The numeric mask to be applied to the blocked or released address +.It port +The optional numeric port to be blocked (can be empty). +.It id +For packet filters that support removal of rules by rule identifier, the +identifier of the rule to be removed. +The add command is expected to return the rule identifier string to stdout. +.El +.It Fl c Ar configuration +The name of the configuration file to read. +The default when +.Fl c +is not given is +.Pa /etc/blocklistd.conf . +.It Fl D Ar dbfile +The Berkeley DB file where +.Nm +stores its state. +It defaults to +.Pa /var/db/blocklistd.db . +.It Fl d +Normally, +.Nm +disassociates itself from the terminal unless the +.Fl d +flag is specified, in which case it stays in the foreground. +.It Fl f +Truncate the state database and flush all the rules named +.Ar rulename +are deleted by invoking the control script as: +.Bd -literal -offset indent +control flush <rulename> +.Ed +.It Fl P Ar sockpathsfile +A file containing a list of pathnames, one per line that +.Nm +will create sockets to listen to. +This is useful for chrooted environments. +.It Fl R Ar rulename +Specify the default rule name for the packet filter rules, usually +.Dv blocklistd . +.It Fl r +Re-read the firewall rules from the internal database, then +remove and re-add them. +This helps for packet filters that do not retain state across reboots. +.It Fl s Ar sockpath +Add +.Ar sockpath +to the list of Unix sockets +.Nm +listens to. +.It Fl t Ar timeout +The interval in seconds +.Nm +polls the state file to update the rules. +.It Fl v +Cause +.Nm +to print +diagnostic messages to +.Dv stdout +instead of +.Xr syslogd 8 . +.El +.Sh SIGNAL HANDLING +.Nm +deals with the following signals: +.Bl -tag -width "USR2" +.It Dv HUP +Receipt of this signal causes +.Nm +to re-read the configuration file. +.It Dv INT , Dv TERM & Dv QUIT +These signals tell +.Nm +to exit in an orderly fashion. +.It Dv USR1 +This signal tells +.Nm +to increase the internal debugging level by 1. +.It Dv USR2 +This signal tells +.Nm +to decrease the internal debugging level by 1. +.El +.Sh FILES +.Bl -tag -width /usr/libexec/blocklistd-helper -compact +.It Pa /usr/libexec/blocklistd-helper +Shell script invoked to interface with the packet filter. +.It Pa /etc/blocklistd.conf +Configuration file. +.It Pa /var/db/blocklistd.db +Database of current connection entries. +.It Pa /var/run/blocklistd.sock +Socket to receive connection notifications. +.El +.Sh SEE ALSO +.Xr blocklistd.conf 5 , +.Xr blocklistctl 8 , +.Xr ipf 8 , +.Xr ipfw 8 , +.Xr pfctl 8 , +.Xr syslogd 8 +.Sh HISTORY +.Nm +first appeared in +.Nx 7 . +.Fx +support for +.Nm +was implemented in +.Fx 11 . +.Sh AUTHORS +.An Christos Zoulas diff --git a/contrib/blocklist/bin/blocklistd.c b/contrib/blocklist/bin/blocklistd.c new file mode 100644 index 000000000000..47c145c7aae1 --- /dev/null +++ b/contrib/blocklist/bin/blocklistd.c @@ -0,0 +1,590 @@ +/*	$NetBSD: blocklistd.c,v 1.12 2025/10/25 18:43:51 christos Exp $	*/ + +/*- + * Copyright (c) 2015 The NetBSD Foundation, Inc. + * All rights reserved. + * + * This code is derived from software contributed to The NetBSD Foundation + * by Christos Zoulas. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + *    notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + *    notice, this list of conditions and the following disclaimer in the + *    documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS + * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#ifdef HAVE_SYS_CDEFS_H +#include <sys/cdefs.h> +#endif +__RCSID("$NetBSD: blocklistd.c,v 1.12 2025/10/25 18:43:51 christos Exp $"); + +#include <sys/types.h> +#include <sys/socket.h> +#include <sys/queue.h> + +#ifdef HAVE_LIBUTIL_H +#include <libutil.h> +#endif +#ifdef HAVE_UTIL_H +#include <util.h> +#endif +#include <string.h> +#include <signal.h> +#include <netdb.h> +#include <stdio.h> +#include <stdbool.h> +#include <string.h> +#include <inttypes.h> +#include <syslog.h> +#include <ctype.h> +#include <limits.h> +#include <errno.h> +#include <poll.h> +#include <fcntl.h> +#include <err.h> +#include <stdlib.h> +#include <unistd.h> +#include <time.h> +#include <ifaddrs.h> +#include <netinet/in.h> + +#include "bl.h" +#include "internal.h" +#include "conf.h" +#include "run.h" +#include "state.h" +#include "support.h" + +static const char *configfile = _PATH_BLCONF; +static DB *state; +static const char *dbfile = _PATH_BLSTATE; +static sig_atomic_t readconf; +static sig_atomic_t done; +static int vflag; + +static void +sigusr1(int n __unused) +{ +	debug++; +} + +static void +sigusr2(int n __unused) +{ +	debug--; +} + +static void +sighup(int n __unused) +{ +	readconf++; +} + +static void +sigdone(int n __unused) +{ +	done++; +} + +static __dead void +usage(int c) +{ +	if (c != '?') +		warnx("Unknown option `%c'", (char)c); +	fprintf(stderr, "Usage: %s [-vdfr] [-c <config>] [-R <rulename>] " +	    "[-P <sockpathsfile>] [-C <controlprog>] [-D <dbfile>] " +	    "[-s <sockpath>] [-t <timeout>]\n", getprogname()); +	exit(EXIT_FAILURE); +} + +static int +getremoteaddress(bl_info_t *bi, struct sockaddr_storage *rss, socklen_t *rsl) +{ +	*rsl = sizeof(*rss); +	memset(rss, 0, *rsl); + +	if (getpeername(bi->bi_fd, (void *)rss, rsl) != -1) +		return 0; + +	if (errno != ENOTCONN) { +		(*lfun)(LOG_ERR, "getpeername failed (%m)"); +		return -1; +	} + +	if (bi->bi_slen == 0) { +		(*lfun)(LOG_ERR, "unconnected socket with no peer in message"); +		return -1; +	} + +	switch (bi->bi_ss.ss_family) { +	case AF_INET: +		*rsl = sizeof(struct sockaddr_in); +		break; +	case AF_INET6: +		*rsl = sizeof(struct sockaddr_in6); +		break; +	default: +		(*lfun)(LOG_ERR, "bad client passed socket family %u", +		    (unsigned)bi->bi_ss.ss_family); +		return -1; +	} + +	if (*rsl != bi->bi_slen) { +		(*lfun)(LOG_ERR, "bad client passed socket length %u != %u", +		    (unsigned)*rsl, (unsigned)bi->bi_slen); +		return -1; +	} + +	memcpy(rss, &bi->bi_ss, *rsl); + +#ifdef HAVE_STRUCT_SOCKADDR_SA_LEN +	if (*rsl != rss->ss_len) { +		(*lfun)(LOG_ERR, +		    "bad client passed socket internal length %u != %u", +		    (unsigned)*rsl, (unsigned)rss->ss_len); +		return -1; +	} +#endif +	return 0; +} + +static void +process(bl_t bl) +{ +	struct sockaddr_storage rss; +	socklen_t rsl; +	char rbuf[BUFSIZ]; +	bl_info_t *bi; +	struct conf c; +	struct dbinfo dbi; +	struct timespec ts; + +	memset(&dbi, 0, sizeof(dbi)); +	memset(&c, 0, sizeof(c)); +	if (clock_gettime(CLOCK_REALTIME, &ts) == -1) { +		(*lfun)(LOG_ERR, "clock_gettime failed (%m)"); +		return; +	} + +	if ((bi = bl_recv(bl)) == NULL) { +		(*lfun)(LOG_ERR, "no message (%m)"); +		return; +	} + +	if (getremoteaddress(bi, &rss, &rsl) == -1) +		return; + +	if (debug || bi->bi_msg[0]) { +		sockaddr_snprintf(rbuf, sizeof(rbuf), "%a:%p", (void *)&rss); +		(*lfun)(bi->bi_msg[0] ? LOG_INFO : LOG_DEBUG, +		    "processing type=%d fd=%d remote=%s msg=\"%s\" uid=%lu gid=%lu", +		    bi->bi_type, bi->bi_fd, rbuf, +		    bi->bi_msg, (unsigned long)bi->bi_uid, +		    (unsigned long)bi->bi_gid); +	} + +	if (conf_find(bi->bi_fd, bi->bi_uid, &rss, &c) == NULL) { +		(*lfun)(LOG_DEBUG, "no rule matched"); +		return; +	} + + +	if (state_get(state, &c, &dbi) == -1) +		return; + +	if (debug) { +		char b1[128], b2[128]; +		(*lfun)(LOG_DEBUG, "%s: initial db state for %s: count=%d/%d " +		    "last=%s now=%s", __func__, rbuf, dbi.count, c.c_nfail, +		    fmttime(b1, sizeof(b1), dbi.last), +		    fmttime(b2, sizeof(b2), ts.tv_sec)); +	} + +	switch (bi->bi_type) { +	case BL_ABUSE: +		/* +		 * If the application has signaled abusive behavior, +		 * set the number of fails to be one less than the +		 * configured limit.  Fallthrough to the normal BL_ADD +		 * processing, which will increment the failure count +		 * to the threshold, and block the abusive address. +		 */ +		if (c.c_nfail != -1) +			dbi.count = c.c_nfail - 1; +		/*FALLTHROUGH*/ +	case BL_ADD: +		dbi.count++; +		dbi.last = ts.tv_sec; +		if (c.c_nfail != -1 && dbi.count >= c.c_nfail) { +			/* +			 * No point in re-adding the rule. +			 * It might exist already due to latency in processing +			 * and removing the rule is the wrong thing to do as +			 * it allows a window to attack again. +			 */ +			if (dbi.id[0] == '\0') { +				int res = run_change("add", &c, +				    dbi.id, sizeof(dbi.id)); +				if (res == -1) +					goto out; +			} +			sockaddr_snprintf(rbuf, sizeof(rbuf), "%a", +			    (void *)&rss); +			(*lfun)(LOG_INFO, +			    "blocked %s/%d:%d for %d seconds", +			    rbuf, c.c_lmask, c.c_port, c.c_duration); +		} +		break; +	case BL_DELETE: +		if (dbi.last == 0) +			goto out; +		dbi.count = 0; +		dbi.last = 0; +		break; +	case BL_BADUSER: +		/* ignore for now */ +		break; +	default: +		(*lfun)(LOG_ERR, "unknown message %d", bi->bi_type); +	} +	state_put(state, &c, &dbi); + +out: +	if (debug) { +		char b1[128], b2[128]; +		(*lfun)(LOG_DEBUG, "%s: final db state for %s: count=%d/%d " +		    "last=%s now=%s", __func__, rbuf, dbi.count, c.c_nfail, +		    fmttime(b1, sizeof(b1), dbi.last), +		    fmttime(b2, sizeof(b2), ts.tv_sec)); +	} +} + +static void +update_interfaces(void) +{ +	struct ifaddrs *oifas, *nifas; + +	if (getifaddrs(&nifas) == -1) +		return; + +	oifas = ifas; +	ifas = nifas; + +	if (oifas) +		freeifaddrs(oifas); +} + +static void +update(void) +{ +	struct timespec ts; +	struct conf c; +	struct dbinfo dbi; +	unsigned int f, n; +	char buf[128]; +	void *ss = &c.c_ss; + +	if (clock_gettime(CLOCK_REALTIME, &ts) == -1) { +		(*lfun)(LOG_ERR, "clock_gettime failed (%m)"); +		return; +	} + +again: +	for (n = 0, f = 1; state_iterate(state, &c, &dbi, f) == 1; +	    f = 0, n++) +	{ +		time_t when = c.c_duration + dbi.last; +		if (debug > 1) { +			char b1[64], b2[64]; +			sockaddr_snprintf(buf, sizeof(buf), "%a:%p", ss); +			(*lfun)(LOG_DEBUG, "%s:[%u] %s count=%d duration=%d " +			    "last=%s " "now=%s", __func__, n, buf, dbi.count, +			    c.c_duration, fmttime(b1, sizeof(b1), dbi.last), +			    fmttime(b2, sizeof(b2), ts.tv_sec)); +		} +		if (c.c_duration == -1 || when >= ts.tv_sec) +			continue; +		if (dbi.id[0]) { +			run_change("rem", &c, dbi.id, 0); +			sockaddr_snprintf(buf, sizeof(buf), "%a", ss); +			(*lfun)(LOG_INFO, "released %s/%d:%d after %d seconds", +			    buf, c.c_lmask, c.c_port, c.c_duration); +		} +		if (state_del(state, &c) == 0) +			goto again; +	} +} + +static void +addfd(struct pollfd **pfdp, bl_t **blp, size_t *nfd, size_t *maxfd, +    const char *path) +{ +	bl_t bl = bl_create(true, path, vflag ? vdlog : vsyslog_r); +	if (bl == NULL || !bl_isconnected(bl)) +		exit(EXIT_FAILURE); +	if (*nfd >= *maxfd) { +		*maxfd += 10; +		*blp = realloc(*blp, sizeof(**blp) * *maxfd); +		if (*blp == NULL) +			err(EXIT_FAILURE, "malloc"); +		*pfdp = realloc(*pfdp, sizeof(**pfdp) * *maxfd); +		if (*pfdp == NULL) +			err(EXIT_FAILURE, "malloc"); +	} + +	(*pfdp)[*nfd].fd = bl_getfd(bl); +	(*pfdp)[*nfd].events = POLLIN; +	(*blp)[*nfd] = bl; +	*nfd += 1; +} + +static void +uniqueadd(struct conf ***listp, size_t *nlist, size_t *mlist, struct conf *c) +{ +	struct conf **list = *listp; + +	if (c->c_name[0] == '\0') +		return; +	for (size_t i = 0; i < *nlist; i++) { +		if (strcmp(list[i]->c_name, c->c_name) == 0) +			return; +	} +	if (*nlist == *mlist) { +		*mlist += 10; +		void *p = realloc(*listp, *mlist * sizeof(*list)); +		if (p == NULL) +			err(EXIT_FAILURE, "Can't allocate for rule list"); +		list = *listp = p; +	} +	list[(*nlist)++] = c; +} + +static void +rules_flush(void) +{ +	struct conf **list; +	size_t nlist, mlist; + +	list = NULL; +	mlist = nlist = 0; +	for (size_t i = 0; i < rconf.cs_n; i++) +		uniqueadd(&list, &nlist, &mlist, &rconf.cs_c[i]); +	for (size_t i = 0; i < lconf.cs_n; i++) +		uniqueadd(&list, &nlist, &mlist, &lconf.cs_c[i]); + +	for (size_t i = 0; i < nlist; i++) +		run_flush(list[i]); +	free(list); +} + +static void +rules_restore(void) +{ +	DB *db; +	struct conf c; +	struct dbinfo dbi; +	unsigned int f; + +	db = state_open(dbfile, O_RDONLY, 0); +	if (db == NULL) { +		(*lfun)(LOG_ERR, "Can't open `%s' to restore state (%m)", +			dbfile); +		return; +	} +	for (f = 1; state_iterate(db, &c, &dbi, f) == 1; f = 0) { +		if (dbi.id[0] == '\0') +			continue; +		(void)run_change("add", &c, dbi.id, sizeof(dbi.id)); +		state_put(state, &c, &dbi); +	} +	state_close(db); +	state_sync(state); +} + +int +main(int argc, char *argv[]) +{ +	int c, tout, flags, flush, restore, ret; +	const char *spath, **blsock; +	size_t nblsock, maxblsock; + +	setprogname(argv[0]); + +	spath = NULL; +	blsock = NULL; +	maxblsock = nblsock = 0; +	flush = 0; +	restore = 0; +	tout = 0; +	flags = O_RDWR|O_EXCL|O_CLOEXEC; +	while ((c = getopt(argc, argv, "C:c:D:dfP:rR:s:t:v")) != -1) { +		switch (c) { +		case 'C': +			controlprog = optarg; +			break; +		case 'c': +			configfile = optarg; +			break; +		case 'D': +			dbfile = optarg; +			break; +		case 'd': +			debug++; +			break; +		case 'f': +			flush++; +			break; +		case 'P': +			spath = optarg; +			break; +		case 'R': +			rulename = optarg; +			break; +		case 'r': +			restore++; +			break; +		case 's': +			if (nblsock >= maxblsock) { +				maxblsock += 10; +				void *p = realloc(blsock, +				    sizeof(*blsock) * maxblsock); +				if (p == NULL) +				    err(EXIT_FAILURE, +					"Can't allocate memory for %zu sockets", +					maxblsock); +				blsock = p; +			} +			blsock[nblsock++] = optarg; +			break; +		case 't': +			tout = atoi(optarg) * 1000; +			break; +		case 'v': +			vflag++; +			break; +		default: +			usage(c); +		} +	} + +	argc -= optind; +	if (argc) +		usage('?'); + +	signal(SIGHUP, sighup); +	signal(SIGINT, sigdone); +	signal(SIGQUIT, sigdone); +	signal(SIGTERM, sigdone); +	signal(SIGUSR1, sigusr1); +	signal(SIGUSR2, sigusr2); + +	openlog(getprogname(), LOG_PID, LOG_DAEMON); + +	if (debug) { +		lfun = dlog; +		if (tout == 0) +			tout = 5000; +	} else { +		if (tout == 0) +			tout = 15000; +	} + +	update_interfaces(); +	conf_parse(configfile); +	if (flush) { +		rules_flush(); +		if (!restore) +			flags |= O_TRUNC; +	} + +	struct pollfd *pfd = NULL; +	bl_t *bl = NULL; +	size_t nfd = 0; +	size_t maxfd = 0; + +	for (size_t i = 0; i < nblsock; i++) +		addfd(&pfd, &bl, &nfd, &maxfd, blsock[i]); +	free(blsock); + +	if (spath) { +		FILE *fp = fopen(spath, "r"); +		char *line; +		if (fp == NULL) +			err(EXIT_FAILURE, "Can't open `%s'", spath); +		for (; (line = fparseln(fp, NULL, NULL, NULL, 0)) != NULL; +		    free(line)) +			addfd(&pfd, &bl, &nfd, &maxfd, line); +		fclose(fp); +	} +	if (nfd == 0) +		addfd(&pfd, &bl, &nfd, &maxfd, _PATH_BLSOCK); + +	state = state_open(dbfile, flags, 0600); +	if (state == NULL) +		state = state_open(dbfile,  flags | O_CREAT, 0600); +	if (state == NULL) +		return EXIT_FAILURE; + +	if (restore) { +		if (!flush) +			rules_flush(); +		rules_restore(); +	} + +	if (!debug) { +		if (daemon(0, 0) == -1) +			err(EXIT_FAILURE, "daemon failed"); +		if (pidfile(NULL) == -1) +			err(EXIT_FAILURE, "Can't create pidfile"); +	} + +	for (size_t t = 0; !done; t++) { +		if (readconf) { +			readconf = 0; +			conf_parse(configfile); +		} +		ret = poll(pfd, (nfds_t)nfd, tout); +		if (debug && ret != 0) +			(*lfun)(LOG_DEBUG, "received %d from poll()", ret); +		switch (ret) { +		case -1: +			if (errno == EINTR) +				continue; +			(*lfun)(LOG_ERR, "poll (%m)"); +			return EXIT_FAILURE; +		case 0: +			state_sync(state); +			break; +		default: +			for (size_t i = 0; i < nfd; i++) +				if (pfd[i].revents & POLLIN) +					process(bl[i]); +		} +		if (t % 100 == 0) +			state_sync(state); +		if (t % 10000 == 0) +			update_interfaces(); +		update(); +	} +	state_close(state); +	return 0; +} diff --git a/contrib/blocklist/bin/blocklistd.conf.5 b/contrib/blocklist/bin/blocklistd.conf.5 new file mode 100644 index 000000000000..3a7dbfc07f58 --- /dev/null +++ b/contrib/blocklist/bin/blocklistd.conf.5 @@ -0,0 +1,237 @@ +.\" $NetBSD: blocklistd.conf.5,v 1.7 2025/02/11 17:47:05 christos Exp $ +.\" +.\" Copyright (c) 2015, 2025 The NetBSD Foundation, Inc. +.\" All rights reserved. +.\" +.\" This code is derived from software contributed to The NetBSD Foundation +.\" by Christos Zoulas. +.\" +.\" Redistribution and use in source and binary forms, with or without +.\" modification, are permitted provided that the following conditions +.\" are met: +.\" 1. Redistributions of source code must retain the above copyright +.\"    notice, this list of conditions and the following disclaimer. +.\" 2. Redistributions in binary form must reproduce the above copyright +.\"    notice, this list of conditions and the following disclaimer in the +.\"    documentation and/or other materials provided with the distribution. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS +.\" ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +.\" TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +.\" PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS +.\" BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +.\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +.\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +.\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +.\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +.\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +.\" POSSIBILITY OF SUCH DAMAGE. +.\" +.Dd February 5, 2025 +.Dt BLOCKLISTD.CONF 5 +.Os +.Sh NAME +.Nm blocklistd.conf +.Nd configuration file format for blocklistd +.Sh DESCRIPTION +The +.Nm +file contains configuration entries for +.Xr blocklistd 8 +in a fashion similar to +.Xr inetd.conf 5 . +Only one entry per line is permitted. +Every entry must have all fields populated. +Each field can be separated by a tab or a space. +Comments are denoted by a +.Dq # +at the beginning of a line. +.Pp +There are two kinds of configuration lines, +.Va [local] +and +.Va [remote] . +By default, configuration lines are +.Va [local] , +i.e. the address specified refers to the addresses on the local machine. +To switch to between +.Va [local] +and +.Va [remote] +configuration lines you can specify the stanzas: +.Dq [local] +and +.Dq [remote] . +.Pp +On +.Va [local] +and +.Va [remote] +lines +.Dq * +means use the default, or wildcard match. +In addition, for +.Va [remote] +lines +.Dq = +means use the values from the matched +.Va [local] +configuration line. +.Pp +The first four fields, +.Va location , +.Va type , +.Va proto , +and +.Va owner +are used to match the +.Va [local] +or +.Va [remote] +addresses, whereas the last 3 fields +.Va name , +.Va nfail , +and +.Va disable +are used to modify the filtering action. +.Pp +The first field denotes the +.Va location +as an address, mask, and port. +The syntax for the +.Va location +is: +.Bd -literal -offset indent +	[<address>|<interface>][/<mask>][:<port>] +.Ed +.Pp +The +.Dv address +can be an IPv4 address in numeric format, an IPv6 address +in numeric format and enclosed by square brackets, or an interface name. +Mask modifiers are not allowed on interfaces because interfaces +can have multiple addresses in different protocols where the mask has a +different size. +.Pp +The +.Dv mask +is always numeric, but the +.Dv port +can be either numeric or symbolic. +.Pp +The second field is the socket +.Va type : +.Dv stream , +.Dv dgram , +or numeric. +The third field is the +.Va protocol : +.Dv tcp , +.Dv udp , +.Dv tcp6 , +.Dv udp6 , +or numeric. +The fourth field is the effective user +.Va ( owner ) +of the daemon process reporting the event, +either as a username or a userid. +.Pp +The rest of the fields control the behavior of the filter. +.Pp +The +.Va name +field, is the name of the packet filter rule to be used. +If the +.Va name +starts with a hyphen +.Pq Dq - , +then the default rulename is prepended to the given name. +If the +.Dv name +contains a +.Dq / , +the remaining portion of the name is interpreted as the mask to be +applied to the address specified in the rule, causing a single rule violation to +block the entire subnet for the configured prefix. +.Pp +The +.Va nfail +field contains the number of failed attempts before access is blocked, +defaulting to +.Dq * +meaning never, and the last field +.Va duration +specifies the amount of time since the last access that the blocking +rule should be active, defaulting to +.Dq * +meaning forever. +The default unit for +.Va duration +is seconds, but one can specify suffixes for different units, such as +.Dq m +for minutes +.Dq h +for hours and +.Dq d +for days. +.Pp +Matching is done first by checking the +.Va [local] +rules individually, in the order of the most specific to the least specific. +If a match is found, then the matching +.Va [remote] +rules are applied. +The +.Va name , +.Va nfail , +and +.Va duration +fields can be altered by the +.Va [remote] +rule that matched. +.Pp +The +.Va [remote] +rules can be used for allowing specific addresses, changing the mask +size (via +.Va name ) , +the rule that the packet filter uses (also via +.Va name ) , +the number of failed attempts (via +.Va nfail ) , +or the duration to block (via +.Va duration ) . +.Sh FILES +.Bl -tag -width /etc/blocklistd.conf -compact +.It Pa /etc/blocklistd.conf +Configuration file. +.El +.Sh EXAMPLES +.Bd -literal -offset 8n +# Block ssh, after 3 attempts for 6 hours on the bnx0 interface +[local] +# location	type	proto	owner	name	nfail	duration +bnx0:ssh	*	*	*	*	3	6h +[remote] +# Never block 1.2.3.4 +1.2.3.4:ssh	*	*	*	*	*	* +# Never block the example IPv6 subnet either +[2001:db8::]/32:ssh	*	*	*	*	*	* +# For addresses coming from 8.8.0.0/16 block whole /24 networks instead +# individual hosts, but keep the rest of the blocking parameters the same. +8.8.0.0/16:ssh	*	*	*	/24	=	= +.Ed +.Sh SEE ALSO +.Xr blocklistctl 8 , +.Xr blocklistd 8 +.Sh HISTORY +.Nm +first appeared in +.Nx 7 . +.Fx +support for +.Nm +was implemented in +.Fx 11 . +.Sh AUTHORS +.An Christos Zoulas diff --git a/contrib/blocklist/bin/conf.c b/contrib/blocklist/bin/conf.c index 8f7e75a56be1..f469e28235cd 100644 --- a/contrib/blocklist/bin/conf.c +++ b/contrib/blocklist/bin/conf.c @@ -1,4 +1,4 @@ -/*	$NetBSD: conf.c,v 1.24 2016/04/04 15:52:56 christos Exp $	*/ +/*	$NetBSD: conf.c,v 1.10 2025/02/11 17:48:30 christos Exp $	*/  /*-   * Copyright (c) 2015 The NetBSD Foundation, Inc. @@ -32,8 +32,10 @@  #include "config.h"  #endif +#ifdef HAVE_SYS_CDEFS_H  #include <sys/cdefs.h> -__RCSID("$NetBSD: conf.c,v 1.24 2016/04/04 15:52:56 christos Exp $"); +#endif +__RCSID("$NetBSD: conf.c,v 1.10 2025/02/11 17:48:30 christos Exp $");  #include <stdio.h>  #ifdef HAVE_LIBUTIL_H @@ -58,6 +60,7 @@ __RCSID("$NetBSD: conf.c,v 1.24 2016/04/04 15:52:56 christos Exp $");  #include <net/if.h>  #include <net/route.h>  #include <sys/socket.h> +#include <dirent.h>  #include "bl.h"  #include "internal.h" @@ -261,7 +264,7 @@ conf_gethostport(const char *f, size_t l, bool local, struct conf *c,  		if (debug)  			(*lfun)(LOG_DEBUG, "%s: host6 %s", __func__, p);  		if (strcmp(p, "*") != 0) { -			if (inet_pton(AF_INET6, p, &sin6->sin6_addr) == -1) +			if (inet_pton(AF_INET6, p, &sin6->sin6_addr) != 1)  				goto out;  			sin6->sin6_family = AF_INET6;  #ifdef HAVE_STRUCT_SOCKADDR_SA_LEN @@ -269,6 +272,8 @@ conf_gethostport(const char *f, size_t l, bool local, struct conf *c,  #endif  			port = &sin6->sin6_port;  		} +		if (!*pstr) +			pstr = "*";  	} else if (pstr != p || strchr(p, '.') || conf_is_interface(p)) {  		if (pstr == p)  			pstr = "*"; @@ -311,7 +316,7 @@ conf_gethostport(const char *f, size_t l, bool local, struct conf *c,  		*port = htons((in_port_t)c->c_port);  	return 0;  out: -	(*lfun)(LOG_ERR, "%s: %s, %zu: Bad address [%s]", __func__, f, l, pstr); +	(*lfun)(LOG_ERR, "%s: %s, %zu: Bad address [%s]", __func__, f, l, p);  	return -1;  out1:  	(*lfun)(LOG_ERR, "%s: %s, %zu: Can't specify mask %d with " @@ -407,6 +412,8 @@ conf_parseline(const char *f, size_t l, char *p, struct conf *c, bool local)  {  	int e; +	c->c_lineno = l; +  	while (*p && isspace((unsigned char)*p))  		p++; @@ -471,7 +478,6 @@ conf_amask_eq(const void *v1, const void *v2, size_t len, int mask)  	uint32_t m;  	int omask = mask; -	len >>= 2;  	switch (mask) {  	case FSTAR:  		if (memcmp(v1, v2, len) == 0) @@ -485,7 +491,7 @@ conf_amask_eq(const void *v1, const void *v2, size_t len, int mask)  		break;  	} -	for (size_t i = 0; i < len; i++) { +	for (size_t i = 0; i < (len >> 2); i++) {  		if (mask > 32) {  			m = htonl((uint32_t)~0);  			mask -= 32; @@ -501,7 +507,6 @@ conf_amask_eq(const void *v1, const void *v2, size_t len, int mask)  out:  	if (debug > 1) {  		char b1[256], b2[256]; -		len <<= 2;  		blhexdump(b1, sizeof(b1), "a1", v1, len);  		blhexdump(b2, sizeof(b2), "a2", v2, len);  		(*lfun)(LOG_DEBUG, "%s: %s != %s [0x%x]", __func__, @@ -691,6 +696,25 @@ conf_addr_eq(const struct sockaddr_storage *s1,  static int  conf_eq(const struct conf *c1, const struct conf *c2)  { +	if (!conf_addr_eq(&c1->c_ss, &c2->c_ss, FSTAR)) +		return 0; + +#define	CMP(a, b, f) \ +	if ((a)->f != (b)->f) \ +		return 0; + +	CMP(c1, c2, c_port); +	CMP(c1, c2, c_proto); +	CMP(c1, c2, c_family); +	CMP(c1, c2, c_uid); +#undef CMP + +	return 1; +} + +static int +conf_match(const struct conf *c1, const struct conf *c2) +{  	if (!conf_addr_eq(&c1->c_ss, &c2->c_ss, c2->c_lmask))  		return 0; @@ -953,13 +977,54 @@ confset_free(struct confset *cs)  }  static void -confset_replace(struct confset *dc, struct confset *sc) +confset_merge(struct confset *dc, struct confset *sc)  { -	struct confset tc; -	tc = *dc; -	*dc = *sc; -	confset_init(sc); -	confset_free(&tc); +	size_t i, j; +	char buf[BUFSIZ]; + +	/* Check each rule of the src confset (sc) */ +	for (i = 0; i < sc->cs_n; i++) { +		/* Compare to each rule in the dest confset (dc) */ +		for (j = 0; j < dc->cs_n; j++) { +			if (conf_eq(&dc->cs_c[j], &sc->cs_c[i])) { +				break; +			} +		} + +		if (j == dc->cs_n) { +			/* This is a new rule to add to the dest confset. */ +			if (confset_full(dc) && confset_grow(dc) == -1) +				return; + +			*confset_get(dc) = sc->cs_c[i]; +			confset_add(dc); +			continue; +		} + +		/* We had a match above. */ +		/* +		 * Check whether the rule from the src confset is more +		 * restrictive than the existing one. Adjust the +		 * existing rule if necessary. +		 */ +		if (sc->cs_c[i].c_nfail == dc->cs_c[j].c_nfail && +		    sc->cs_c[i].c_duration && dc->cs_c[j].c_duration) { +			(*lfun)(LOG_DEBUG, "skipping existing rule: %s", +			conf_print(buf, sizeof (buf), "", "\t", &sc->cs_c[i])); +			continue; +		} + +		if (sc->cs_c[i].c_nfail < dc->cs_c[j].c_nfail) +			dc->cs_c[j].c_nfail = sc->cs_c[i].c_nfail; + +		if (sc->cs_c[i].c_duration > dc->cs_c[j].c_duration) +			dc->cs_c[j].c_duration = sc->cs_c[i].c_duration; + +		(*lfun)(LOG_DEBUG, "adjusted existing rule: %s", +		    conf_print(buf, sizeof (buf), "", "\t", &dc->cs_c[j])); +	} + +	confset_free(sc);  }  static void @@ -990,7 +1055,7 @@ confset_match(const struct confset *cs, struct conf *c,  		if (debug)  			(*lfun)(LOG_DEBUG, "%s", conf_print(buf, sizeof(buf),  			    "check:\t", "", &cs->cs_c[i])); -		if (conf_eq(c, &cs->cs_c[i])) { +		if (conf_match(c, &cs->cs_c[i])) {  			if (debug)  				(*lfun)(LOG_DEBUG, "%s",  				    conf_print(buf, sizeof(buf), @@ -1160,21 +1225,14 @@ conf_find(int fd, uid_t uid, const struct sockaddr_storage *rss,  	return cr;  } - -void -conf_parse(const char *f) +static void +conf_parsefile(FILE *fp, const char *config_file)  { -	FILE *fp;  	char *line;  	size_t lineno, len;  	struct confset lc, rc, *cs; -	if ((fp = fopen(f, "r")) == NULL) { -		(*lfun)(LOG_ERR, "%s: Cannot open `%s' (%m)", __func__, f); -		return; -	} - -	lineno = 1; +	lineno = 0;  	confset_init(&rc);  	confset_init(&lc); @@ -1197,23 +1255,103 @@ conf_parse(const char *f)  			if (confset_grow(cs) == -1) {  				confset_free(&lc);  				confset_free(&rc); -				fclose(fp);  				free(line);  				return;  			}  		} -		if (conf_parseline(f, lineno, line, confset_get(cs), +		if (conf_parseline(config_file, lineno, line, confset_get(cs),  		    cs == &lc) == -1)  			continue;  		confset_add(cs);  	} -	fclose(fp); -	confset_sort(&lc); -	confset_sort(&rc); +	confset_merge(&rconf, &rc); +	confset_merge(&lconf, &lc); +} + + +static void +conf_parsedir(DIR *dir, const char *config_path) +{ +	long path_max; +	struct dirent *dent; +	char *path; +	FILE *fp; + +	if ((path_max = pathconf(config_path, _PC_PATH_MAX)) == -1) +		path_max = 2048; + +	if ((path = malloc((size_t)path_max)) == NULL) { +		(*lfun)(LOG_ERR, "%s: Failed to allocate memory for path (%m)", +		    __func__); +		return; +	} + +	while ((dent = readdir(dir)) != NULL) { +		if (strcmp(dent->d_name, ".") == 0 || +		    strcmp(dent->d_name, "..") == 0) +			continue; + +		(void) snprintf(path, (size_t)path_max, "%s/%s", config_path, +		    dent->d_name); +		if ((fp = fopen(path, "r")) == NULL) { +			(*lfun)(LOG_ERR, "%s: Cannot open `%s' (%m)", __func__, +			    path); +			continue; +		} +		conf_parsefile(fp, path); +		fclose(fp); +	} + +	free(path); +} + +void +conf_parse(const char *config_path) +{ +	char *path; +	DIR *dir; +	FILE *fp; + +	if ((dir = opendir(config_path)) != NULL) { +		/* +		 * If config_path is a directory, parse the configuration files +		 * in the directory. Then we're done here. +		 */ +		conf_parsedir(dir, config_path); +		closedir(dir); +		goto out; +	} else if ((fp = fopen(config_path, "r")) != NULL) { +		/* If config_path is a file, parse it. */ +		conf_parsefile(fp, config_path); +		fclose(fp); +	} + +	/* +	 * Append ".d" to config_path, and if that is a directory, parse the +	 * configuration files in the directory. +	 */ +	if (asprintf(&path, "%s.d", config_path) < 0) { +		(*lfun)(LOG_ERR, "%s: Failed to allocate memory for path (%m)", +		    __func__); +		goto out; +	} + +	if ((dir = opendir(path)) != NULL) { +		conf_parsedir(dir, path); +		closedir(dir); +	} +	free(path); + +out: +	if (dir == NULL && fp == NULL) { +		(*lfun)(LOG_ERR, "%s: Cannot open `%s' (%m)", __func__, +		    config_path); +		return; +	} -	confset_replace(&rconf, &rc); -	confset_replace(&lconf, &lc); +	confset_sort(&lconf); +	confset_sort(&rconf);  	if (debug) {  		confset_list(&lconf, "local", "target"); diff --git a/contrib/blocklist/bin/conf.h b/contrib/blocklist/bin/conf.h index 03f1942e3e32..8e4cd3a41fae 100644 --- a/contrib/blocklist/bin/conf.h +++ b/contrib/blocklist/bin/conf.h @@ -1,4 +1,4 @@ -/*	$NetBSD: conf.h,v 1.6 2015/01/27 19:40:36 christos Exp $	*/ +/*	$NetBSD: conf.h,v 1.2 2025/02/05 20:09:33 christos Exp $	*/  /*-   * Copyright (c) 2015 The NetBSD Foundation, Inc. @@ -34,6 +34,7 @@  #include <sys/socket.h>  struct conf { +	size_t			c_lineno;  	struct sockaddr_storage	c_ss;  	int			c_lmask;  	int			c_port; diff --git a/contrib/blocklist/bin/internal.c b/contrib/blocklist/bin/internal.c index 5c039e4dc5d2..625de55928d8 100644 --- a/contrib/blocklist/bin/internal.c +++ b/contrib/blocklist/bin/internal.c @@ -1,4 +1,4 @@ -/*	$NetBSD: internal.c,v 1.5 2015/01/27 19:40:37 christos Exp $	*/ +/*	$NetBSD: internal.c,v 1.2 2025/02/11 17:48:30 christos Exp $	*/  /*-   * Copyright (c) 2015 The NetBSD Foundation, Inc. @@ -32,8 +32,10 @@  #include "config.h"  #endif +#ifdef HAVE_SYS_CDEFS_H  #include <sys/cdefs.h> -__RCSID("$NetBSD: internal.c,v 1.5 2015/01/27 19:40:37 christos Exp $"); +#endif +__RCSID("$NetBSD: internal.c,v 1.2 2025/02/11 17:48:30 christos Exp $");  #include <stdio.h>  #include <syslog.h> @@ -41,7 +43,7 @@ __RCSID("$NetBSD: internal.c,v 1.5 2015/01/27 19:40:37 christos Exp $");  #include "internal.h"  int debug; -const char *rulename = "blacklistd"; +const char *rulename = "blocklistd";  const char *controlprog = _PATH_BLCONTROL;  struct confset lconf, rconf;  struct ifaddrs *ifas; diff --git a/contrib/blocklist/bin/internal.h b/contrib/blocklist/bin/internal.h index 5a40e49fbbd5..553320e7afd5 100644 --- a/contrib/blocklist/bin/internal.h +++ b/contrib/blocklist/bin/internal.h @@ -1,4 +1,4 @@ -/*	$NetBSD: internal.h,v 1.14 2016/04/04 15:52:56 christos Exp $	*/ +/*	$NetBSD: internal.h,v 1.1.1.1 2020/06/15 01:52:53 christos Exp $	*/  /*-   * Copyright (c) 2015 The NetBSD Foundation, Inc. @@ -32,13 +32,13 @@  #define _INTERNAL_H  #ifndef _PATH_BLCONF -#define	_PATH_BLCONF	"/etc/blacklistd.conf" +#define	_PATH_BLCONF	"/etc/blocklistd.conf"  #endif  #ifndef _PATH_BLCONTROL -#define	_PATH_BLCONTROL	"/libexec/blacklistd-helper" +#define	_PATH_BLCONTROL	"/usr/libexec/blocklistd-helper"  #endif  #ifndef _PATH_BLSTATE -#define	_PATH_BLSTATE	"/var/db/blacklistd.db" +#define	_PATH_BLSTATE	"/var/db/blocklistd.db"  #endif  extern struct confset rconf, lconf; diff --git a/contrib/blocklist/bin/old_internal.c b/contrib/blocklist/bin/old_internal.c new file mode 100644 index 000000000000..79093cc8b8ab --- /dev/null +++ b/contrib/blocklist/bin/old_internal.c @@ -0,0 +1,50 @@ +/*	$NetBSD: internal.c,v 1.2 2025/02/11 17:48:30 christos Exp $	*/ + +/*- + * Copyright (c) 2015 The NetBSD Foundation, Inc. + * All rights reserved. + * + * This code is derived from software contributed to The NetBSD Foundation + * by Christos Zoulas. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + *    notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + *    notice, this list of conditions and the following disclaimer in the + *    documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS + * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#ifdef HAVE_SYS_CDEFS_H +#include <sys/cdefs.h> +#endif +__RCSID("$NetBSD: internal.c,v 1.2 2025/02/11 17:48:30 christos Exp $"); + +#include <stdio.h> +#include <syslog.h> +#include "conf.h" +#include "old_internal.h" + +int debug; +const char *rulename = "blacklistd"; +const char *controlprog = _PATH_BLCONTROL; +struct confset lconf, rconf; +struct ifaddrs *ifas; +void (*lfun)(int, const char *, ...) = syslog; diff --git a/contrib/blocklist/bin/old_internal.h b/contrib/blocklist/bin/old_internal.h new file mode 100644 index 000000000000..becee563e81d --- /dev/null +++ b/contrib/blocklist/bin/old_internal.h @@ -0,0 +1,58 @@ +/*	$NetBSD: internal.h,v 1.1.1.1 2020/06/15 01:52:53 christos Exp $	*/ + +/*- + * Copyright (c) 2015 The NetBSD Foundation, Inc. + * All rights reserved. + * + * This code is derived from software contributed to The NetBSD Foundation + * by Christos Zoulas. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + *    notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + *    notice, this list of conditions and the following disclaimer in the + *    documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS + * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +#ifndef _OLD_INTERNAL_H +#define _OLD_INTERNAL_H + +#ifndef _PATH_BLCONF +#define	_PATH_BLCONF	"/etc/blacklistd.conf" +#endif +#ifndef _PATH_BLCONTROL +#define	_PATH_BLCONTROL	"/usr/libexec/blacklistd-helper" +#endif +#ifndef _PATH_BLSTATE +/* We want the new name, the old one would be incompatible after 24932b6 */ +#define	_PATH_BLSTATE	"/var/db/blocklistd.db" +#endif + +extern struct confset rconf, lconf; +extern int debug; +extern const char *rulename; +extern const char *controlprog; +extern struct ifaddrs *ifas; + +#if !defined(__syslog_attribute__) && !defined(__syslog__) +#define __syslog__ __printf__ +#endif + +extern void (*lfun)(int, const char *, ...) +    __attribute__((__format__(__syslog__, 2, 3))); + +#endif /* _OLD_INTERNAL_H */ diff --git a/contrib/blocklist/bin/run.c b/contrib/blocklist/bin/run.c index 5588f0198c04..adcc407e65c6 100644 --- a/contrib/blocklist/bin/run.c +++ b/contrib/blocklist/bin/run.c @@ -1,4 +1,4 @@ -/*	$NetBSD: run.c,v 1.14 2016/04/04 15:52:56 christos Exp $	*/ +/*	$NetBSD: run.c,v 1.3 2025/02/11 17:48:30 christos Exp $	*/  /*-   * Copyright (c) 2015 The NetBSD Foundation, Inc. @@ -32,8 +32,10 @@  #include "config.h"  #endif +#ifdef HAVE_SYS_CDEFS_H  #include <sys/cdefs.h> -__RCSID("$NetBSD: run.c,v 1.14 2016/04/04 15:52:56 christos Exp $"); +#endif +__RCSID("$NetBSD: run.c,v 1.3 2025/02/11 17:48:30 christos Exp $");  #include <stdio.h>  #ifdef HAVE_LIBUTIL_H @@ -131,7 +133,8 @@ run_change(const char *how, const struct conf *c, char *id, size_t len)  		prname = "udp";  		break;  	default: -		(*lfun)(LOG_ERR, "%s: bad protocol %d", __func__, c->c_proto); +		(*lfun)(LOG_ERR, "%s: bad protocol %d (line %zu)", __func__, +		     c->c_proto, c->c_lineno);  		return -1;  	} diff --git a/contrib/blocklist/bin/run.h b/contrib/blocklist/bin/run.h index bafc3e554690..da21906e0db6 100644 --- a/contrib/blocklist/bin/run.h +++ b/contrib/blocklist/bin/run.h @@ -1,4 +1,4 @@ -/*	$NetBSD: run.h,v 1.5 2015/01/27 19:40:37 christos Exp $	*/ +/*	$NetBSD: run.h,v 1.1.1.1 2020/06/15 01:52:53 christos Exp $	*/  /*-   * Copyright (c) 2015 The NetBSD Foundation, Inc. diff --git a/contrib/blocklist/bin/state.c b/contrib/blocklist/bin/state.c index f2622c82c251..bb93904f3489 100644 --- a/contrib/blocklist/bin/state.c +++ b/contrib/blocklist/bin/state.c @@ -1,4 +1,4 @@ -/*	$NetBSD: state.c,v 1.19 2016/09/26 19:43:43 christos Exp $	*/ +/*	$NetBSD: state.c,v 1.3 2025/10/25 18:43:51 christos Exp $	*/  /*-   * Copyright (c) 2015 The NetBSD Foundation, Inc. @@ -32,8 +32,10 @@  #include "config.h"  #endif +#ifdef HAVE_SYS_CDEFS_H  #include <sys/cdefs.h> -__RCSID("$NetBSD: state.c,v 1.19 2016/09/26 19:43:43 christos Exp $"); +#endif +__RCSID("$NetBSD: state.c,v 1.3 2025/10/25 18:43:51 christos Exp $");  #include <sys/types.h>  #include <sys/socket.h> @@ -129,7 +131,7 @@ state_del(DB *db, const struct conf *c)  			(*lfun)(LOG_DEBUG, "%s: returns %d", __func__, rv);  			(*db->sync)(db, 0);  		} -		return 0; +		return rv;  	default:  		(*lfun)(LOG_ERR, "%s: failed (%m)", __func__);  		return -1; diff --git a/contrib/blocklist/bin/state.h b/contrib/blocklist/bin/state.h index 2e9257006e80..48f63a41ef33 100644 --- a/contrib/blocklist/bin/state.h +++ b/contrib/blocklist/bin/state.h @@ -1,4 +1,4 @@ -/*	$NetBSD: state.h,v 1.5 2015/01/27 19:40:37 christos Exp $	*/ +/*	$NetBSD: state.h,v 1.1.1.1 2020/06/15 01:52:53 christos Exp $	*/  /*-   * Copyright (c) 2015 The NetBSD Foundation, Inc. diff --git a/contrib/blocklist/bin/support.c b/contrib/blocklist/bin/support.c index d560d2303223..91e40812611e 100644 --- a/contrib/blocklist/bin/support.c +++ b/contrib/blocklist/bin/support.c @@ -1,4 +1,4 @@ -/*	$NetBSD: support.c,v 1.9 2018/09/18 22:12:19 christos Exp $	*/ +/*	$NetBSD: support.c,v 1.3 2025/02/11 17:48:30 christos Exp $	*/  /*-   * Copyright (c) 2015 The NetBSD Foundation, Inc. @@ -32,8 +32,10 @@  #include "config.h"  #endif +#ifdef HAVE_SYS_CDEFS_H  #include <sys/cdefs.h> -__RCSID("$NetBSD: support.c,v 1.9 2018/09/18 22:12:19 christos Exp $"); +#endif +__RCSID("$NetBSD: support.c,v 1.3 2025/02/11 17:48:30 christos Exp $");  #include <time.h>  #include <string.h> @@ -66,7 +68,8 @@ expandm(char *buf, size_t len, const char *fmt)  }  void -vdlog(int level __unused, const char *fmt, va_list ap) +vdlog(int level __unused, struct syslog_data *sd __unused, +    const char *fmt, va_list ap)  {  	char buf[BUFSIZ]; @@ -81,7 +84,7 @@ dlog(int level, const char *fmt, ...)  	va_list ap;  	va_start(ap, fmt); -	vdlog(level, fmt, ap); +	vdlog(level, NULL, fmt, ap);  	va_end(ap);  } diff --git a/contrib/blocklist/bin/support.h b/contrib/blocklist/bin/support.h index 899649ce8319..bb865cb8fe68 100644 --- a/contrib/blocklist/bin/support.h +++ b/contrib/blocklist/bin/support.h @@ -1,4 +1,4 @@ -/*	$NetBSD: support.h,v 1.7 2016/04/04 15:52:56 christos Exp $	*/ +/*	$NetBSD: support.h,v 1.2 2024/08/02 17:11:55 christos Exp $	*/  /*-   * Copyright (c) 2015 The NetBSD Foundation, Inc. @@ -34,8 +34,9 @@  __BEGIN_DECLS  const char *fmttime(char *, size_t, time_t);  const char *fmtydhms(char *, size_t, time_t); -void vdlog(int, const char *, va_list) -    __attribute__((__format__(__printf__, 2, 0))); +struct syslog_data; +void vdlog(int, struct syslog_data *, const char *, va_list) +    __attribute__((__format__(__printf__, 3, 0)));  void dlog(int, const char *, ...)      __attribute__((__format__(__printf__, 2, 3)));  ssize_t blhexdump(char *, size_t, const char *, const void *, size_t);  | 
