# HG changeset patch # User Arkadiusz Juszczyk # Date 1793010550 -3600 # Node ID 9f8d79c98fd282e8b3099a3fdbae02eb37d89138 initial public release diff -r 000000000000 -r 9f8d79c98fd2 .hgignore --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/.hgignore Mon Oct 26 11:29:10 2026 +0100 @@ -0,0 +1,4 @@ +syntax=regex +\.DS_Store +\.orig$ +^VERSION$ diff -r 000000000000 -r 9f8d79c98fd2 CHANGES --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/CHANGES Mon Oct 26 11:29:10 2026 +0100 @@ -0,0 +1,4 @@ + +Changes with botblockd 0.4.0 25 Oct 2026 + + *) First public release. diff -r 000000000000 -r 9f8d79c98fd2 LICENSE --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/LICENSE Mon Oct 26 11:29:10 2026 +0100 @@ -0,0 +1,22 @@ +Copyright (c) 2026 Arkadiusz Juszczyk . + +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 COPYRIGHT HOLDERS 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 COPYRIGHT HOLDER 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. diff -r 000000000000 -r 9f8d79c98fd2 README.md --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/README.md Mon Oct 26 11:29:10 2026 +0100 @@ -0,0 +1,100 @@ +# botblockd + +A small FreeBSD daemon that blocks abusive web clients at the firewall. + +botblockd tails an nginx access log, counts HTTP error responses per +source IP, and adds persistent offenders to a `pf` table so they are +dropped at the host edge. It reinforces application-level decisions +(rate limits, web application firewall rules) at the network layer, +where they are cheap to enforce. + +IPv4 only. No external dependencies: it uses the FreeBSD base system +toolchain, headers and `pfctl`. + +## How it works + +Every source address that receives an error response becomes a suspect. A +periodic sweep evaluates suspects through a small state machine: + +- An inspection window (a number of seconds or requests, whichever comes + first) decides whether a suspect's error balance warrants a block. +- A blocked address is released after a configurable interval into a + probation period, during which renewed bad behaviour re-blocks it. +- Suspects that stop causing errors are forgotten after a cooldown. + +Successful requests count against errors. A client is blocked only when +its errors reach a minimum count and outnumber its successful requests. +An occasional error among normal requests does not block a client, and a +client can clear itself by behaving. + +Which status codes count as errors is configurable; anything else counts +as success. + +## Safety + +A whitelist file of addresses that are never blocked keeps operators +from being locked out. + +The daemon treats the `pf` table as its own and flushes it at startup +and on shutdown. When it blocks an address, it also kills that +address's existing `pf` states, so open connections are cut off. + +## Requirements + +- FreeBSD. Tested on FreeBSD 15. +- `pf` enabled, with a `botblock` table and a matching block rule. + +## Install + +Source releases and install notes are on the project page, +. + +To build and install from an unpacked source release: + + make -C src + make -C src install + +## pf setup + +botblockd manages a `pf` table named `botblock`; you provide the table +and the rule. A sample is installed at +`share/examples/botblockd/pf.conf.sample`: + + table persist + block in quick from + +Splice it into your ruleset and reload with `pfctl -f /etc/pf.conf`. + +## Run + + sysrc botblockd_enable=YES + service botblockd start + +The configuration is read from `/usr/local/etc/botblockd/conf`; copy +`conf.sample` from the same directory and edit it. Send `SIGHUP` (or +`service botblockd reload`) to re-read it. If the new configuration or +whitelist has an error, the reload is rejected and the daemon keeps +running with the previous one; the error goes to the system log. Run +`botblockd check` as root to see errors before reloading. + +## Commands + + botblockd run [-f] run the daemon (-f: foreground) + botblockd check validate configuration and exit + botblockd list list currently blocked addresses + botblockd unblock remove an address from the block table + botblockd unblock -a clear the whole table + +The daemon logs to syslog under the `daemon` facility. + +See `botblockd(8)` for the full configuration reference. + +## Bugs + +Report bugs by email to ark@wobblyhead.net. Include the version, which +`botblockd help` prints on its first line, and the relevant lines from +the system log. + +## Licence + +BSD 2-Clause. See [LICENSE](LICENSE). diff -r 000000000000 -r 9f8d79c98fd2 conf/conf.sample --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/conf/conf.sample Mon Oct 26 11:29:10 2026 +0100 @@ -0,0 +1,41 @@ +# botblockd configuration example. +# +# Every setting below is shown commented out at its compiled-in default, +# which is what botblockd uses when the setting is absent or no config +# file exists. Uncomment a line and change the value to override it. A +# setting that is present must have a valid value: on a malformed value +# botblockd refuses to start, or rejects the reload, rather than silently +# falling back to the default. Unknown settings and lines that are not +# KEY=VALUE are errors too. Numbers must be positive integers, paths +# must be absolute. + +# Inspection window: time or request count, whichever triggers first. +#INSPECT_SECONDS=30 +#INSPECT_REQUEST_COUNT=20 + +# Minimum number of errors a suspect must have caused before it is first +# blocked. A floor against one-shot 404/499 false positives -- a real +# bot reliably causes more than one error. +#MIN_ERROR_COUNT=2 + +# Which HTTP status codes count as errors. Comma-separated list of +# single codes and lo-hi ranges, e.g. 401,403,404,444 or 400-599. +# Anything not listed counts as a successful request. +#ERROR_STATUSES=400-599 + +# Cooldown: forget a suspect after this many seconds without errors; +# successful requests do not keep it. An address on probation is +# forgotten this many seconds after its block was lifted. +#COOLDOWN_SECONDS=600 + +# Block duration in seconds: how long an IP stays in the pf table before +# the block is lifted and the IP enters probation. +#BLOCK_SECONDS=600 + +# Input: nginx access log in combined format, raw or syslog-aggregated. +# Followed across rotation. A reload that changes it is rejected; a +# change takes effect on restart. +#INPUT_LOG=/var/log/nginx/access.log + +# Whitelist: one IPv4 address or CIDR subnet per line. +#WHITELIST_FILE=/usr/local/etc/botblockd/whitelist diff -r 000000000000 -r 9f8d79c98fd2 conf/pf.conf.sample --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/conf/pf.conf.sample Mon Oct 26 11:29:10 2026 +0100 @@ -0,0 +1,12 @@ +# botblockd uses this pf table. Include the table definition and a +# matching block rule in the pf configuration, /etc/pf.conf by +# default. +# +# `persist` keeps the table across `pfctl -f` reloads. The table is +# not file-backed; botblockd flushes it at startup and on exit. + +table persist + +# Drop blocked sources early. Place ahead of any pass rules that +# would otherwise let them through. +block in quick from diff -r 000000000000 -r 9f8d79c98fd2 conf/rc.d/botblockd --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/conf/rc.d/botblockd Mon Oct 26 11:29:10 2026 +0100 @@ -0,0 +1,27 @@ +#!/bin/sh + +# PROVIDE: botblockd +# REQUIRE: LOGIN pf +# KEYWORD: shutdown + +. /etc/rc.subr + +name="botblockd" +rcvar=${name}_enable + +load_rc_config "$name" + +: ${botblockd_enable:=NO} +: ${botblockd_pidfile:=/var/run/${name}.pid} +: ${botblockd_configfile:=%%PREFIX%%/etc/${name}/conf} + +# botblockd detaches itself via daemon(3) and writes its own pidfile; +# the "run" verb starts the daemon. +pidfile="${botblockd_pidfile}" +command="%%PREFIX%%/sbin/${name}" +command_args="run -c ${botblockd_configfile} -p ${pidfile}" + +# reload sends SIGHUP via the pidfile; botblockd re-reads config/whitelist +extra_commands="reload" + +run_rc_command "$1" diff -r 000000000000 -r 9f8d79c98fd2 conf/whitelist.sample --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/conf/whitelist.sample Mon Oct 26 11:29:10 2026 +0100 @@ -0,0 +1,7 @@ +# botblockd whitelist. One IPv4 address or CIDR subnet per line. +# Comments start with '#'. +# +# Example: +# 192.0.2.10 +# 198.51.100.7 +# 203.0.113.0/24 diff -r 000000000000 -r 9f8d79c98fd2 man/botblockd.8 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/man/botblockd.8 Mon Oct 26 11:29:10 2026 +0100 @@ -0,0 +1,268 @@ +.\" SPDX-License-Identifier: BSD-2-Clause +.\" Copyright (c) 2026 Arkadiusz Juszczyk +.\" +.Dd October 25, 2026 +.Dt BOTBLOCKD 8 +.Os +.Sh NAME +.Nm botblockd +.Nd nginx-to-pf bot blocker +.Sh SYNOPSIS +.Nm +.Cm run +.Op Fl f +.Op Fl c Ar config +.Op Fl p Ar pidfile +.Nm +.Cm check +.Op Fl c Ar config +.Nm +.Cm list +.Nm +.Cm unblock +.Ar address ... +.Nm +.Cm unblock Fl a +.Nm +.Cm help +.Sh DESCRIPTION +.Nm +tails an nginx access log via +.Xr kqueue 2 , +counts HTTP error responses per source IP, and blocks persistently +abusive clients at the host +.Xr pf 4 +firewall by adding them to the +.Sy botblock +table. +It reads the standard combined log format, accepting both the raw form +and the form produced when +.Xr syslogd 8 +aggregates the log with a prepended syslog header. +The log is followed across rotation and truncation. +Only IPv4 is handled. +.Pp +Each source that produces an error response becomes a suspect. +A periodic sweep evaluates suspects and moves them through a small state +machine. +An inspection window of +.Va INSPECT_SECONDS +seconds or +.Va INSPECT_REQUEST_COUNT +requests, whichever comes first, decides whether the error balance +warrants a block. +A blocked IP is released after +.Va BLOCK_SECONDS +seconds into a probation period, during which renewed bad behaviour +re-blocks it. +Suspects that cause no further errors are dropped after +.Va COOLDOWN_SECONDS +seconds. +Successful requests count against errors. +A client is blocked only when its errors reach +.Va MIN_ERROR_COUNT +and outnumber its successful requests. +An occasional error among normal requests does not block a client, and a +client can clear itself by behaving. +.Pp +A whitelist file protects operators. +It lists addresses that are never blocked. +.Pp +.Nm +logs to +.Xr syslog 3 +under the +.Dv LOG_DAEMON +facility. +The +.Xr pf 4 +.Sy botblock +table must exist and be referenced by a block rule in the host ruleset; +a sample is installed under +.Pa share/examples/botblockd . +.Nm +treats the table as its own and flushes it at startup and on exit. +When an address is blocked, its existing +.Xr pf 4 +states are killed as well, so connections it has already established +are cut off. +.Sh COMMANDS +.Bl -tag -width "unblock" +.It Cm run +Run the daemon. +It detaches into the background unless +.Fl f +is given, and writes a pidfile. +The configuration, the whitelist, the input log and the +.Sy botblock +table are checked before detaching, so a problem with any of them is +reported in the exit status. +.It Cm check +Parse the configuration and whitelist, open the input log, verify that +the +.Sy botblock +table is loaded in +.Xr pf 4 , +report the result, and exit. +The table is only read, never modified. +Run this as root before sending +.Dv SIGHUP : +a failed reload is reported only in the system log. +.It Cm list +Print the addresses currently in the +.Sy botblock +table. +.It Cm unblock Ar address ... +Remove one or more addresses from the +.Sy botblock +table. +.It Cm unblock Fl a +Remove all addresses from the table. +.It Cm help +Print the version and a usage summary. +.El +.Sh OPTIONS +.Bl -tag -width Fl +.It Fl c Ar config +Read configuration from +.Ar config +instead of the default. +With +.Cm run , +the path must be absolute, so that a reload finds the file after the +daemon has changed to the root directory. +.It Fl f +Run in the foreground without detaching, mirroring log output to +standard error. +.It Fl p Ar pidfile +Write the pidfile to +.Ar pidfile +instead of the default. +.El +.Sh CONFIGURATION +The configuration file holds +.Sy KEY=VALUE +lines. +Blank lines and lines whose first non-blank character is +.Ql # +are ignored. +Unset keys keep their compiled-in defaults, and if the file does not +exist, all defaults apply. +A key that is present must have a valid value. +Numbers must be positive integers, and paths must be absolute. +A malformed value, an unknown key or a line that is not +.Sy KEY=VALUE +is an error rather than ignored: at startup +.Nm +exits, and a reload is rejected. +.Bl -tag -width "INSPECT_REQUEST_COUNT" +.It Va INSPECT_SECONDS +Length of the inspection window in seconds. +The default is 30. +.It Va INSPECT_REQUEST_COUNT +Request count that also closes the inspection window. +The default is 20. +.It Va MIN_ERROR_COUNT +Minimum number of errors a suspect must have caused before it is +first blocked. +Errors are counted from the first one and are not reset when the +inspection window closes. +The default is 2. +.It Va ERROR_STATUSES +Which HTTP status codes count as errors, as a comma-separated list of +single codes and +.Ar lo Ns - Ns Ar hi +ranges, for example +.Ql 401,403,404,444 +or +.Ql 400-599 . +Any status not listed counts as a successful request. +The default is +.Ql 400-599 . +.It Va COOLDOWN_SECONDS +A suspect that has caused no error for this many seconds is +forgotten; successful requests do not keep it. +An address on probation is forgotten this many seconds after its +block was lifted. +The default is 600. +.It Va BLOCK_SECONDS +How long, in seconds, an address stays blocked before entering probation. +The default is 600. +.It Va INPUT_LOG +Path of the nginx access log to tail. +A reload that changes it is rejected; the change takes effect when +the daemon is restarted. +The default is +.Pa /var/log/nginx/access.log . +.It Va WHITELIST_FILE +Path of the whitelist, one IPv4 address or CIDR subnet per line. +A bare address is treated as a single host +.Pq Li /32 ; +a prefix length must be between 1 and 32, as +.Li /0 +would whitelist every address. +Host bits below the prefix are accepted and masked off, so +.Li 10.0.0.5/24 +is the same as +.Li 10.0.0.0/24 . +Blanks around an entry, blank lines and lines whose first non-blank +character is +.Ql # +are ignored; any other line that does not parse fails startup or +reload, just like a malformed configuration value. +A missing file leaves the whitelist empty; a file that exists but +cannot be read is an error. +The default is +.Pa /usr/local/etc/botblockd/whitelist . +.El +.Sh FILES +.Bl -tag -width "/usr/local/etc/botblockd/whitelist" +.It Pa /usr/local/etc/botblockd/conf +Configuration file +.It Pa /usr/local/etc/botblockd/whitelist +IP whitelist +.It Pa /usr/local/etc/rc.d/botblockd +.Xr rc 8 +Startup script +.It Pa /var/run/botblockd.pid +Default pidfile +.El +.Sh SIGNALS +.Bl -tag -width SIGTERM +.It Dv SIGTERM , SIGINT +Graceful shutdown; flush the +.Xr pf 4 +table before exiting. +.It Dv SIGHUP +Reload the configuration file and whitelist. +If either has an error, or +.Va INPUT_LOG +has changed, the reload is rejected: the error is logged and the +previous configuration and whitelist stay in effect. +.El +.Sh EXIT STATUS +.Cm run +exits 0 when stopped by a signal and 1 on any error, at startup or +while running. +The other commands exit 0 on success and 1 on failure. +.Sh SEE ALSO +.Xr kqueue 2 , +.Xr syslog 3 , +.Xr pf 4 , +.Xr pfctl 8 , +.Xr rc 8 , +.Xr syslogd 8 +.Sh AUTHORS +.An Arkadiusz Juszczyk Aq Mt ark@wobblyhead.net +.Sh CAVEATS +Only IPv4 is handled. +Log lines from IPv6 clients are skipped, so these clients are never +blocked. +.Pp +.Cm unblock +works on the +.Xr pf 4 +table only and does not inform a running daemon. +The daemon still counts a manually unblocked address as blocked until +its block interval ends, so the address is not blocked again before +then, whatever errors it causes. diff -r 000000000000 -r 9f8d79c98fd2 src/Makefile --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/Makefile Mon Oct 26 11:29:10 2026 +0100 @@ -0,0 +1,44 @@ +# vim:ts=8: +PROG= botblockd +SRCS= main.c config.c ip.c whitelist.c pf.c suspect.c logtail.c +MAN= ${PROG}.8 +WARNS= 6 + +# pidfile(3) lives in libutil +LDADD= -lutil + +# man page and packaging payload live outside src/ +.PATH: ${.CURDIR}/../man + +# Default to /usr/local-style layout; the port can override PREFIX if needed. +PREFIX?= /usr/local +BINDIR= ${PREFIX}/sbin +MANDIR= ${PREFIX}/share/man/man +CFLAGS+= -DPREFIX=\"${PREFIX}\" + +# release tarballs carry a one-line VERSION file at the top level +BOTBLOCKD_VERSION!= cat ${.CURDIR}/../VERSION 2>/dev/null || echo unknown +CFLAGS+= -DBOTBLOCKD_VERSION=\"${BOTBLOCKD_VERSION}\" + +# Where the extras go +ETCDIR= ${PREFIX}/etc/botblockd +RCDIR= ${PREFIX}/etc/rc.d +EXAMPLESDIR= ${PREFIX}/share/examples/${PROG} +CONFDIR= ${.CURDIR}/../conf +CONF_FILES= conf.sample whitelist.sample +EXAMPLE_FILES= pf.conf.sample + +afterinstall: + ${INSTALL} -d ${DESTDIR}${ETCDIR} + ${INSTALL} -d ${DESTDIR}${RCDIR} + ${INSTALL} -d ${DESTDIR}${EXAMPLESDIR} +.for f in ${CONF_FILES} + ${INSTALL} -m 644 ${CONFDIR}/${f} ${DESTDIR}${ETCDIR}/${f} +.endfor + ${INSTALL} -m 555 ${CONFDIR}/rc.d/botblockd ${DESTDIR}${RCDIR}/botblockd + sed -i '' "s|%%PREFIX%%|${PREFIX}|g" ${DESTDIR}${RCDIR}/botblockd +.for f in ${EXAMPLE_FILES} + ${INSTALL} -m 644 ${CONFDIR}/${f} ${DESTDIR}${EXAMPLESDIR}/${f} +.endfor + +.include diff -r 000000000000 -r 9f8d79c98fd2 src/botblockd.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/botblockd.h Mon Oct 26 11:29:10 2026 +0100 @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2026 Arkadiusz Juszczyk + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#ifndef BOTBLOCKD_H +#define BOTBLOCKD_H + +#include +#include +#include +#include +#include +#include + +/* ---- compile-time paths and constants (PREFIX from the Makefile) ---- */ + +#define DEF_CONF PREFIX "/etc/botblockd/conf" +#define DEF_PIDFILE "/var/run/botblockd.pid" +#define PF_TABLE "botblock" +#define NSTATUS 1000 /* HTTP status codes are 0..999 */ + +/* ---- shared configuration ---- */ + +struct config { + int inspect_secs; + int inspect_count; + int min_errors; + int cooldown_secs; + int block_secs; + char input_log[512]; + char whitelist[512]; + bool status_is_err[NSTATUS]; /* true if the code counts as error */ +}; + +extern struct config cfg; + +/* ---- config.c ---- */ + +int parse_config(const char *path, struct config *out); +char *read_entry(FILE *fp, char **line, size_t *cap, int *lineno); +bool status_is_error(int code); + +/* ---- ip.c ---- */ + +int parse_ipv4(const char *s, uint32_t *out); +int parse_cidr(const char *s, uint32_t *net, uint32_t *mask); +const char *ip_str(uint32_t ip); + +/* ---- whitelist.c ---- */ + +int load_whitelist(const char *path); +bool is_whitelisted(uint32_t ip); + +/* ---- pf.c ---- */ + +int pf_block(uint32_t ip); +int pf_unblock(uint32_t ip); +int pf_show(bool quiet); +int pf_flush(void); + +/* ---- suspect.c ---- */ + +void process_request(uint32_t ip, int status); +void sweep(void); + +/* ---- logtail.c ---- */ + +int tail_open(void); +int tail_log(void); + +/* ---- main.c ---- */ + +extern volatile sig_atomic_t running; +extern volatile sig_atomic_t reload_pending; +void config_reload(void); +time_t monotime(void); + +#endif /* BOTBLOCKD_H */ diff -r 000000000000 -r 9f8d79c98fd2 src/config.c --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/config.c Mon Oct 26 11:29:10 2026 +0100 @@ -0,0 +1,402 @@ +/* + * Copyright (c) 2026 Arkadiusz Juszczyk + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "botblockd.h" + +struct config cfg; + +/* + * config_invalid - report a malformed setting value + * + * A value present in the config file must be usable. Rather than + * silently falling back to a default and masking an operator typo, + * the caller fails the whole parse. + * + * Parameters: + * key - setting name + * val - offending value text + * + * Returns: -1, for the caller to pass on + */ +static int +config_invalid(const char *key, const char *val) +{ + syslog(LOG_ERR, "config: invalid value '%s' for %s", val, key); + return (-1); +} + +/* + * copy_path_setting - copy an absolute path config value + * + * Rejects an empty value, a relative path (the daemon changes to / when + * it detaches, so a relative path would resolve differently on reload), + * and a value that does not fit dst. + * + * Parameters: + * key - setting name, used only in the error message + * val - value text + * dst - destination buffer + * size - size of dst + * + * Returns: 0 on success, -1 on an invalid value + */ +static int +copy_path_setting(const char *key, const char *val, char *dst, + size_t size) +{ + if (*val != '/' || strlcpy(dst, val, size) >= size) + return (config_invalid(key, val)); + return (0); +} + +/* + * parse_int_setting - parse a positive integer config value + * + * Uses strtol with full error checking: rejects empty input, trailing + * non-digit junk, overflow, and values outside 1..INT_MAX. + * + * Parameters: + * key - setting name, used only in the error message + * val - value text (already stripped of surrounding whitespace) + * out - output: parsed value + * + * Returns: 0 on success, -1 on an invalid value + */ +static int +parse_int_setting(const char *key, const char *val, int *out) +{ + char *endp; + long lv; + + errno = 0; + lv = strtol(val, &endp, 10); + if (endp == val || *endp != '\0' || errno != 0 || + lv < 1 || lv > INT_MAX) + return (config_invalid(key, val)); + *out = (int)lv; + return (0); +} + +/* + * parse_status_token - parse one "N" or "lo-hi" item of an error spec + * + * Parameters: + * tok - single comma-delimited token, surrounding spaces tolerated + * lo - output: low bound + * hi - output: high bound (equals lo for a single code) + * + * Returns: 0 on success, -1 on malformed token or out-of-range value + */ +static int +parse_status_token(const char *tok, int *lo, int *hi) +{ + char *endp; + long a, b; + + while (*tok == ' ' || *tok == '\t') + tok++; + errno = 0; + a = strtol(tok, &endp, 10); + if (endp == tok || a < 0 || a >= NSTATUS || errno != 0) + return (-1); + if (*endp == '-') { + const char *p = endp + 1; + b = strtol(p, &endp, 10); + if (endp == p || b < 0 || b >= NSTATUS || errno != 0) + return (-1); + } else { + b = a; + } + while (*endp == ' ' || *endp == '\t') + endp++; + if (*endp != '\0' || a > b) + return (-1); + *lo = (int)a; + *hi = (int)b; + return (0); +} + +/* + * set_error_statuses - parse an error-status spec into a status bitmap + * + * Parses the comma-separated spec of individual codes and lo-hi ranges + * (e.g. "401,403,404,444" or "400-599") straight into the bitmap, so no + * raw copy is retained. An empty spec, an empty item (two commas in a + * row, or a leading or trailing comma) or a malformed item fails the + * parse. + * + * Parameters: + * key - setting name, used only in the error message + * spec - the ERROR_STATUSES value + * err - output: bitmap indexed by status code + * nbytes - size of err in bytes + * + * Returns: 0 on success, -1 on an invalid spec + */ +static int +set_error_statuses(const char *key, const char *spec, bool *err, + size_t nbytes) +{ + char buf[512]; + char *tok, *rest; + int c, lo, hi; + + if (*spec == '\0' || strlcpy(buf, spec, sizeof(buf)) >= sizeof(buf)) + return (config_invalid(key, spec)); + + memset(err, 0, nbytes); + rest = buf; + while ((tok = strsep(&rest, ",")) != NULL) { + if (parse_status_token(tok, &lo, &hi) != 0) + return (config_invalid(key, spec)); + for (c = lo; c <= hi; c++) + err[c] = true; + } + return (0); +} + +/* + * status_is_error - report whether an HTTP status counts as an error + * + * Parameters: + * code - HTTP status code + * + * Returns: true if the code is in the configured error set, else false + */ +bool +status_is_error(int code) +{ + if (code < 0 || code >= NSTATUS) + return (false); + return (cfg.status_is_err[code]); +} + +/* + * Settings, with their compiled-in defaults as text. Each load parses + * every default with the same code as a value from the file, then + * applies the file on top. + */ +enum setting_type { + SET_NUMBER, + SET_PATH, + SET_STATUSES, +}; + +struct setting { + const char *key; + const char *def; + enum setting_type type; + size_t off; /* field offset in struct config */ + size_t size; /* field size */ +}; + +#define FIELD(f) \ + offsetof(struct config, f), sizeof(((struct config *)0)->f) + +static const struct setting settings[] = { + { "INSPECT_SECONDS", "30", SET_NUMBER, FIELD(inspect_secs) }, + { "INSPECT_REQUEST_COUNT", "20", SET_NUMBER, FIELD(inspect_count) }, + { "MIN_ERROR_COUNT", "2", SET_NUMBER, FIELD(min_errors) }, + { "COOLDOWN_SECONDS", "600", SET_NUMBER, FIELD(cooldown_secs) }, + { "BLOCK_SECONDS", "600", SET_NUMBER, FIELD(block_secs) }, + { "ERROR_STATUSES", "400-599", + SET_STATUSES, FIELD(status_is_err) }, + { "INPUT_LOG", "/var/log/nginx/access.log", + SET_PATH, FIELD(input_log) }, + { "WHITELIST_FILE", PREFIX "/etc/botblockd/whitelist", + SET_PATH, FIELD(whitelist) }, +}; + +/* + * apply_setting - validate one value and store it in a config + * + * Parameters: + * c - config to store into + * s - setting the value is for + * val - value text, stripped of surrounding whitespace + * + * Returns: 0 on success, -1 on an invalid value + */ +static int +apply_setting(struct config *c, const struct setting *s, const char *val) +{ + void *dst = (char *)c + s->off; + + switch (s->type) { + case SET_NUMBER: + return (parse_int_setting(s->key, val, dst)); + case SET_PATH: + return (copy_path_setting(s->key, val, dst, s->size)); + case SET_STATUSES: + return (set_error_statuses(s->key, val, dst, s->size)); + } + return (-1); +} + +/* + * find_setting - look up a setting by key + * + * Parameters: + * key - setting name from the config file + * + * Returns: the setting, or NULL for an unknown key + */ +static const struct setting * +find_setting(const char *key) +{ + size_t i; + + for (i = 0; i < nitems(settings); i++) { + if (strcmp(settings[i].key, key) == 0) + return (&settings[i]); + } + return (NULL); +} + +/* + * apply_defaults - fill a config with the compiled-in defaults + * + * A default that does not parse is a program bug: it is logged with + * the setting name and the program exits. + * + * Parameters: + * c - config to fill + */ +static void +apply_defaults(struct config *c) +{ + size_t i; + + memset(c, 0, sizeof(*c)); + for (i = 0; i < nitems(settings); i++) { + if (apply_setting(c, &settings[i], settings[i].def) != 0) { + syslog(LOG_ERR, "config: bad compiled-in default for %s", + settings[i].key); + exit(1); + } + } +} + +/* + * read_entry - read the next entry of a config or whitelist file + * + * Skips blank lines and lines whose first non-blank character is '#', + * and strips the blanks and the newline around the entry. + * + * Parameters: + * fp - file to read + * line - in/out: getline(3) buffer, NULL before the first call + * cap - in/out: size of *line, 0 before the first call + * lineno - in/out: line number, 0 before the first call; on return + * the number of the line holding the entry + * + * Returns: the entry, inside *line, or NULL at end of file or on a + * read error (see ferror(3)) + */ +char * +read_entry(FILE *fp, char **line, size_t *cap, int *lineno) +{ + char *end, *p; + ssize_t n; + + while ((n = getline(line, cap, fp)) != -1) { + (*lineno)++; + p = *line; + end = p + n; + while (end > p && isspace((unsigned char)end[-1])) + end--; + *end = '\0'; + while (isspace((unsigned char)*p)) + p++; + if (*p != '\0' && *p != '#') + return (p); + } + return (NULL); +} + +/* + * parse_config - read a KEY=VALUE config file into a config + * + * The config is first set to the compiled-in defaults, so a key absent + * from the file has its default. Blank lines and lines whose first + * non-blank character is '#' are skipped. Any other line must be + * KEY=VALUE with a known key and a valid value; anything else fails + * the parse. A missing file is not an error: all settings keep their + * defaults. The global cfg is not touched. + * + * Parameters: + * path - path to config file + * out - output: the parsed config, undefined on failure + * + * Returns: 0 on success, -1 on an unreadable file or invalid content + */ +int +parse_config(const char *path, struct config *out) +{ + const struct setting *set; + FILE *fp; + size_t cap = 0; + char *eq, *key, *line = NULL, *val; + int lineno = 0, rc = 0; + + apply_defaults(out); + fp = fopen(path, "r"); + if (fp == NULL) { + if (errno != ENOENT) { + syslog(LOG_ERR, "cannot open config %s: %s", + path, strerror(errno)); + return (-1); + } + syslog(LOG_NOTICE, "no config at %s, using compiled-in " + "defaults", path); + return (0); + } + + while ((key = read_entry(fp, &line, &cap, &lineno)) != NULL) { + eq = strchr(key, '='); + if (eq == NULL) { + syslog(LOG_ERR, "config: line %d is not KEY=VALUE", lineno); + rc = -1; + break; + } + + /* trim blanks around '=' so "KEY = val" still matches */ + val = eq + 1; + while (eq > key && isspace((unsigned char)eq[-1])) + eq--; + *eq = '\0'; + while (isspace((unsigned char)*val)) + val++; + + set = find_setting(key); + if (set == NULL) { + syslog(LOG_ERR, "config: unknown setting '%s'", key); + rc = -1; + break; + } + rc = apply_setting(out, set, val); + if (rc != 0) + break; + } + if (rc == 0 && ferror(fp)) { + syslog(LOG_ERR, "cannot read config %s", path); + rc = -1; + } + free(line); + fclose(fp); + return (rc); +} diff -r 000000000000 -r 9f8d79c98fd2 src/ip.c --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/ip.c Mon Oct 26 11:29:10 2026 +0100 @@ -0,0 +1,115 @@ +/* + * Copyright (c) 2026 Arkadiusz Juszczyk + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#include +#include + +#include +#include + +#include +#include +#include +#include + +#include "botblockd.h" + +/* + * parse_ipv4 - parse the first whitespace-delimited token as IPv4 + * + * The token ends at end of string or at the first space, tab or + * newline. Output is in network byte order, as inet_pton(3) gives it. + * + * Parameters: + * s - start of string (not modified) + * out - output for parsed IP (network byte order) + * + * Returns: 0 on success, -1 if token is empty, too long, or invalid + */ +int +parse_ipv4(const char *s, uint32_t *out) +{ + struct in_addr ia; + char buf[INET_ADDRSTRLEN]; + size_t n; + + n = strcspn(s, " \t\n"); + if (n == 0 || n >= sizeof(buf)) + return (-1); + memcpy(buf, s, n); + buf[n] = '\0'; + if (inet_pton(AF_INET, buf, &ia) != 1) + return (-1); + *out = ia.s_addr; + return (0); +} + +/* + * parse_cidr - parse "A.B.C.D" or "A.B.C.D/N" into network and mask + * + * A bare address is treated as a single host (/32). A prefix length N + * must be 1..32: /0 would whitelist every address and is rejected as + * too wide to be intentional. Host bits below the prefix are accepted + * and masked off, so a non-canonical entry such as 10.0.0.5/24 is + * stored as the 10.0.0.0/24 network. Outputs are network byte order. + * + * Parameters: + * s - entry text (a whole whitelist line, no surrounding space) + * net - output: network address with host bits cleared + * mask - output: netmask + * + * Returns: 0 on success, -1 on a malformed address or prefix + */ +int +parse_cidr(const char *s, uint32_t *net, uint32_t *mask) +{ + struct in_addr ia; + char buf[INET_ADDRSTRLEN + 3]; /* address, "/" and 2 digits */ + char *endp, *slash; + long prefix; + + if (strlcpy(buf, s, sizeof(buf)) >= sizeof(buf)) + return (-1); + prefix = 32; + slash = strchr(buf, '/'); + if (slash != NULL) { + *slash = '\0'; + errno = 0; + prefix = strtol(slash + 1, &endp, 10); + if (endp == slash + 1 || *endp != '\0' || errno != 0 || + prefix < 1 || prefix > 32) + return (-1); + } + if (inet_pton(AF_INET, buf, &ia) != 1) + return (-1); + + /* prefix is 1..32, so the shift is 0..31 and defined */ + *mask = htonl(0xffffffffu << (32 - prefix)); + *net = ia.s_addr & *mask; + return (0); +} + +/* + * ip_str - format an IP (network byte order) as dotted-quad text + * + * The text is kept in a static buffer that the next call overwrites. + * + * Parameters: + * ip - IPv4 address (network byte order) + * + * Returns: the text, or "?" if the address cannot be formatted + */ +const char * +ip_str(uint32_t ip) +{ + static char buf[INET_ADDRSTRLEN]; + struct in_addr ia; + + ia.s_addr = ip; + if (inet_ntop(AF_INET, &ia, buf, sizeof(buf)) == NULL) + return ("?"); + return (buf); +} diff -r 000000000000 -r 9f8d79c98fd2 src/logtail.c --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/logtail.c Mon Oct 26 11:29:10 2026 +0100 @@ -0,0 +1,369 @@ +/* + * Copyright (c) 2026 Arkadiusz Juszczyk + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "botblockd.h" + +/* + * Two arrangements of the standard nginx combined log are accepted on + * the same input file: + * + * raw combined, IP at offset 0: + * - [