From 10a2fc4f47fb290d74fc12a2b21487faceca9669 Mon Sep 17 00:00:00 2001 From: Tommaso Bailetti Date: Mon, 2 Nov 2026 17:01:05 +0100 Subject: [PATCH 01/51] chore: version bump --- build.conf.defaults | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/build.conf.defaults b/build.conf.defaults index 2b7333b31..f23b89d02 100644 --- a/build.conf.defaults +++ b/build.conf.defaults @@ -1,3 +1,3 @@ -OWRT_VERSION=v25.12.5 -NETHSECURITY_VERSION=8.8.1 +OWRT_VERSION=v25.12.6 +NETHSECURITY_VERSION=8.9.0 TARGET=x86_64 From 4fbdd7d69e40c5f401e88b73f8a625e9e450b3f4 Mon Sep 17 00:00:00 2001 From: Tommaso Bailetti Date: Mon, 2 Nov 2026 17:02:43 +0100 Subject: [PATCH 02/51] build: debian update --- builder/Containerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/builder/Containerfile b/builder/Containerfile index 104315506..c6137251c 100644 --- a/builder/Containerfile +++ b/builder/Containerfile @@ -3,7 +3,7 @@ # SPDX-License-Identifier: GPL-2.0-only # -FROM debian:13.4 AS base +FROM debian:13.7 AS base RUN apt-get update \ && apt-get install --yes --no-install-recommends --no-install-suggests \ # openwrt build dependencies https://openwrt.org/docs/guide-developer/toolchain/install-buildsystem#debianubuntumint From 1f8fe33f593246a3693c4bd03150423f588dd712 Mon Sep 17 00:00:00 2001 From: Tommaso Bailetti Date: Mon, 2 Nov 2026 17:11:56 +0100 Subject: [PATCH 03/51] bumped binaries --- packages/telegraf/Makefile | 6 +++--- packages/victoria-logs/Makefile | 6 +++--- packages/victoria-metrics/Makefile | 6 +++--- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/packages/telegraf/Makefile b/packages/telegraf/Makefile index 0cf30299c..4c14287dd 100644 --- a/packages/telegraf/Makefile +++ b/packages/telegraf/Makefile @@ -7,8 +7,8 @@ include $(TOPDIR)/rules.mk PKG_NAME:=telegraf # renovate: datasource=github-tags depName=influxdata/telegraf -PKG_VERSION:=1.39.1 -PKG_RELEASE:=5 +PKG_VERSION:=1.40.2 +PKG_RELEASE:=1 PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.gz PKG_SOURCE_URL:=https://codeload.github.com/influxdata/telegraf/tar.gz/v$(PKG_VERSION)? @@ -19,7 +19,7 @@ PKG_HASH:=skip PKG_MAINTAINER:=Tommaso Bailetti PKG_LICENSE:=MIT -PKG_BUILD_DEPENDS:=golang/host +PKG_BUILD_DEPENDS:=golang1.27/host PKG_BUILD_PARALLEL:=1 PKG_BUILD_FLAGS:=no-mips16 diff --git a/packages/victoria-logs/Makefile b/packages/victoria-logs/Makefile index 1325aea19..89d3b179f 100644 --- a/packages/victoria-logs/Makefile +++ b/packages/victoria-logs/Makefile @@ -7,8 +7,8 @@ include $(TOPDIR)/rules.mk PKG_NAME:=victoria-logs # renovate: datasource=github-tags depName=VictoriaMetrics/VictoriaLogs -PKG_VERSION:=1.51.0 -PKG_RELEASE:=2 +PKG_VERSION:=1.53.0 +PKG_RELEASE:=1 PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.gz PKG_SOURCE_URL:=https://codeload.github.com/VictoriaMetrics/VictoriaLogs/tar.gz/v$(PKG_VERSION)? @@ -19,7 +19,7 @@ PKG_HASH:=skip PKG_MAINTAINER:=Tommaso Bailetti PKG_LICENSE:=Apache-2.0 -PKG_BUILD_DEPENDS:=golang/host +PKG_BUILD_DEPENDS:=golang1.27/host PKG_BUILD_PARALLEL:=1 PKG_BUILD_FLAGS:=no-mips16 diff --git a/packages/victoria-metrics/Makefile b/packages/victoria-metrics/Makefile index ac336dc86..00319cac9 100644 --- a/packages/victoria-metrics/Makefile +++ b/packages/victoria-metrics/Makefile @@ -7,8 +7,8 @@ include $(TOPDIR)/rules.mk PKG_NAME:=victoria-metrics # renovate: datasource=github-tags depName=VictoriaMetrics/VictoriaMetrics -PKG_VERSION:=1.146.0 -PKG_RELEASE:=3 +PKG_VERSION:=1.153.0 +PKG_RELEASE:=1 PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.gz PKG_SOURCE_URL:=https://codeload.github.com/VictoriaMetrics/VictoriaMetrics/tar.gz/v$(PKG_VERSION)? @@ -19,7 +19,7 @@ PKG_HASH:=skip PKG_MAINTAINER:=Tommaso Bailetti PKG_LICENSE:=Apache-2.0 -PKG_BUILD_DEPENDS:=golang/host +PKG_BUILD_DEPENDS:=golang1.27/host PKG_BUILD_PARALLEL:=1 PKG_BUILD_FLAGS:=no-mips16 From 2b8bca26a0a719d816964e510218a9863ca50c50 Mon Sep 17 00:00:00 2001 From: Tommaso Bailetti Date: Tue, 3 Nov 2026 09:20:56 +0100 Subject: [PATCH 04/51] fixed patches --- ...vpn-allow-deprecated-insecure-static-crypto.patch | 12 ------------ .../packages/100-strongswan-dpd-action-restart.patch | 12 ------------ 2 files changed, 24 deletions(-) delete mode 100644 patches/feeds/packages/100-strongswan-dpd-action-restart.patch diff --git a/patches/feeds/packages/100-openvpn-allow-deprecated-insecure-static-crypto.patch b/patches/feeds/packages/100-openvpn-allow-deprecated-insecure-static-crypto.patch index 784c60d3e..94fd0480f 100644 --- a/patches/feeds/packages/100-openvpn-allow-deprecated-insecure-static-crypto.patch +++ b/patches/feeds/packages/100-openvpn-allow-deprecated-insecure-static-crypto.patch @@ -1,15 +1,3 @@ -diff --git a/net/openvpn/Makefile b/net/openvpn/Makefile ---- a/net/openvpn/Makefile -+++ b/net/openvpn/Makefile -@@ -10,7 +10,7 @@ - PKG_NAME:=openvpn - - PKG_VERSION:=2.7.4 --PKG_RELEASE:=2 -+PKG_RELEASE:=3 - - PKG_SOURCE_URL:=\ - https://build.openvpn.net/downloads/releases/ \ diff --git a/net/openvpn/files/openvpn.init b/net/openvpn/files/openvpn.init --- a/net/openvpn/files/openvpn.init +++ b/net/openvpn/files/openvpn.init diff --git a/patches/feeds/packages/100-strongswan-dpd-action-restart.patch b/patches/feeds/packages/100-strongswan-dpd-action-restart.patch deleted file mode 100644 index 8f16df2a3..000000000 --- a/patches/feeds/packages/100-strongswan-dpd-action-restart.patch +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/net/strongswan/files/swanctl.init b/net/strongswan/files/swanctl.init ---- a/net/strongswan/files/swanctl.init -+++ b/net/strongswan/files/swanctl.init -@@ -314,7 +314,7 @@ - hold) - dpdaction="trap" ;; - restart) -- dpdaction="start" ;; -+ dpdaction="restart" ;; - trap|start) - # already using new syntax - ;; From 40454a40a6212bed0e954fed3edc413e732d7226 Mon Sep 17 00:00:00 2001 From: Tommaso Bailetti Date: Tue, 3 Nov 2026 15:49:17 +0100 Subject: [PATCH 05/51] fix: updating telegraf configuration for banip --- packages/banip/Makefile | 5 ++++- .../banip.conf => banip/files/banip.telegraf} | 4 ++-- packages/telegraf/Makefile | 1 - 3 files changed, 6 insertions(+), 4 deletions(-) rename packages/{telegraf/files/telegraf.conf.d/banip.conf => banip/files/banip.telegraf} (89%) diff --git a/packages/banip/Makefile b/packages/banip/Makefile index 78167a97c..c51ced040 100644 --- a/packages/banip/Makefile +++ b/packages/banip/Makefile @@ -16,7 +16,7 @@ define Package/banip SECTION:=net CATEGORY:=Network TITLE:=banIP blocks IPs via named nftables Sets - DEPENDS:=+jshn +jsonfilter +firewall4 +gawk +ca-bundle +rpcd +rpcd-mod-rpcsys + DEPENDS:=+jshn +jsonfilter +firewall4 +gawk +ca-bundle +rpcd +rpcd-mod-rpcsys +telegraf PKGARCH:=all endef @@ -69,6 +69,9 @@ define Package/banip/install $(INSTALL_DIR) $(1)/etc/uci-defaults $(INSTALL_BIN) ./files/95-banip-housekeeping $(1)/etc/uci-defaults + + $(INSTALL_DIR) $(1)/etc/telegraf.conf.d + $(INSTALL_DATA) ./files/banip.telegraf $(1)/etc/telegraf.conf.d/banip.conf endef $(eval $(call BuildPackage,banip)) diff --git a/packages/telegraf/files/telegraf.conf.d/banip.conf b/packages/banip/files/banip.telegraf similarity index 89% rename from packages/telegraf/files/telegraf.conf.d/banip.conf rename to packages/banip/files/banip.telegraf index eec34d159..14eca7a4b 100644 --- a/packages/telegraf/files/telegraf.conf.d/banip.conf +++ b/packages/banip/files/banip.telegraf @@ -4,7 +4,7 @@ [[inputs.tail]] name_override = "banip" files = ["/var/log/messages"] - from_beginning = false + initial_read_offset = "saved-or-end" data_format = "grok" grok_patterns = ['banIP/%{DATA:chain:tag}/%{WORD:verdict:tag}/%{DATA:feed:tag}: %{GREEDYDATA}SRC=%{IP:src:tag}%{GREEDYDATA}DST=%{IP:dst:tag}%{GREEDYDATA}LEN=%{NUMBER:blocked_bytes:int}'] @@ -15,7 +15,7 @@ [[inputs.tail]] name_override = "banip" files = ["/var/log/messages"] - from_beginning = false + initial_read_offset = "saved-or-end" data_format = "grok" grok_patterns = ["banIP%{DATA}\\[%{NUMBER:banned:int}\\]: add IP '%{IP:ip:tag}'"] diff --git a/packages/telegraf/Makefile b/packages/telegraf/Makefile index 4c14287dd..83e67a71c 100644 --- a/packages/telegraf/Makefile +++ b/packages/telegraf/Makefile @@ -91,7 +91,6 @@ define Package/telegraf/install $(INSTALL_DATA) ./files/telegraf.conf.d/services.conf $(1)/etc/telegraf.conf.d/services.conf $(INSTALL_DATA) ./files/telegraf.conf.d/mwan.conf $(1)/etc/telegraf.conf.d/mwan.conf $(INSTALL_DATA) ./files/telegraf.conf.d/ha.conf $(1)/etc/telegraf.conf.d/ha.conf - $(INSTALL_DATA) ./files/telegraf.conf.d/banip.conf $(1)/etc/telegraf.conf.d/banip.conf $(INSTALL_DIR) $(1)/etc/uci-defaults $(INSTALL_BIN) ./files/uci-defaults/99-telegraf-migrate-netdata $(1)/etc/uci-defaults/99-telegraf-migrate-netdata $(INSTALL_DIR) $(1)/usr/sbin From 2d2581fdf1af0c36eabd5355d424cf55aeac9579 Mon Sep 17 00:00:00 2001 From: Tommaso Bailetti Date: Tue, 3 Nov 2026 16:02:58 +0100 Subject: [PATCH 06/51] feat: added storage monitoring --- packages/ns-storage/Makefile | 5 ++++- packages/ns-storage/files/smart.telegraf | 7 +++++++ packages/telegraf/Makefile | 7 +------ 3 files changed, 12 insertions(+), 7 deletions(-) create mode 100644 packages/ns-storage/files/smart.telegraf diff --git a/packages/ns-storage/Makefile b/packages/ns-storage/Makefile index 9c22c9be3..f1caabc5e 100644 --- a/packages/ns-storage/Makefile +++ b/packages/ns-storage/Makefile @@ -21,7 +21,8 @@ define Package/ns-storage CATEGORY:=NethSecurity TITLE:=NethSecurity storage manager URL:=https://github.com/NethServer/nethsecurity/ - DEPENDS:=+parted +block-mount +logrotate +rsync +tune2fs +blockd +rsyslog +dnsmasq-full + DEPENDS:=+parted +block-mount +logrotate +rsync +tune2fs +blockd +rsyslog +dnsmasq-full +nvme-cli +smartmontools +telegraf + EXTRA_DEPENDS:=telegraf (>=1.40.2) PKGARCH:=all endef @@ -75,6 +76,8 @@ define Package/ns-storage/install $(INSTALL_BIN) ./files/storage-status $(1)/usr/sbin $(INSTALL_BIN) ./files/ns-storage-check.init $(1)/etc/init.d/ns-storage-check $(INSTALL_BIN) ./files/30-ns-storage $(1)/etc/hotplug.d/block/ + $(INSTALL_DIR) $(1)/etc/telegraf.conf.d + $(INSTALL_DATA) ./files/smart.telegraf $(1)/etc/telegraf.conf.d/smart.conf endef $(eval $(call BuildPackage,ns-storage)) diff --git a/packages/ns-storage/files/smart.telegraf b/packages/ns-storage/files/smart.telegraf new file mode 100644 index 000000000..b5eb1aacb --- /dev/null +++ b/packages/ns-storage/files/smart.telegraf @@ -0,0 +1,7 @@ +# Disk health monitoring (S.M.A.R.T. via smartctl and nvme-cli) + +[[inputs.smart]] + interval = "5m" + + [inputs.smart.tags] + influxdb_db = "os-metrics" diff --git a/packages/telegraf/Makefile b/packages/telegraf/Makefile index 83e67a71c..5d9a04bb2 100644 --- a/packages/telegraf/Makefile +++ b/packages/telegraf/Makefile @@ -45,6 +45,7 @@ GO_PKG_TAGS:= \ inputs.ping \ inputs.processes \ inputs.sensors \ + inputs.smart \ inputs.system \ inputs.wireguard \ inputs.tail \ @@ -102,11 +103,5 @@ define Package/telegraf/install $(INSTALL_BIN) ./files/telegraf-ha-alert $(1)/usr/libexec/telegraf-ha-alert endef -define Package/telegraf/postinst -#!/bin/sh -[ -z "$${IPKG_INSTROOT}" ] && /etc/init.d/telegraf restart -exit 0 -endef - $(eval $(call GoBinPackage,telegraf)) $(eval $(call BuildPackage,telegraf)) From 8ccbf257da676ffef21bd9d0d02304872b54798b Mon Sep 17 00:00:00 2001 From: Tommaso Bailetti Date: Thu, 5 Nov 2026 17:04:46 +0100 Subject: [PATCH 07/51] refactor: making victoria-logs save persistent data --- config/monitoring.conf | 2 +- packages/ns-storage/Makefile | 24 ++----------------- packages/ns-storage/README.md | 9 +++---- packages/ns-storage/files/30_ns-storage | 2 -- .../33-ns-storage-drop-disk-log.uci-default | 17 +++++++++++++ packages/ns-storage/files/add-storage | 8 ------- packages/ns-storage/files/data.conf | 14 ----------- .../ns-storage/files/ns-storage-check.init | 12 +++------- packages/ns-storage/files/remove-storage | 5 ---- packages/rsyslog/files/rsyslog.init | 7 +++++- packages/victoria-logs/README.md | 7 +----- .../files/rsyslog-victoria-logs.conf | 5 ++++ 12 files changed, 38 insertions(+), 74 deletions(-) create mode 100644 packages/ns-storage/files/33-ns-storage-drop-disk-log.uci-default delete mode 100644 packages/ns-storage/files/data.conf diff --git a/config/monitoring.conf b/config/monitoring.conf index f5e4fa381..3ff10c3b6 100644 --- a/config/monitoring.conf +++ b/config/monitoring.conf @@ -1,3 +1,3 @@ CONFIG_PACKAGE_victoria-metrics=y -CONFIG_PACKAGE_victoria-logs=m +CONFIG_PACKAGE_victoria-logs=y CONFIG_PACKAGE_telegraf=y diff --git a/packages/ns-storage/Makefile b/packages/ns-storage/Makefile index f1caabc5e..4ed8d2673 100644 --- a/packages/ns-storage/Makefile +++ b/packages/ns-storage/Makefile @@ -21,7 +21,7 @@ define Package/ns-storage CATEGORY:=NethSecurity TITLE:=NethSecurity storage manager URL:=https://github.com/NethServer/nethsecurity/ - DEPENDS:=+parted +block-mount +logrotate +rsync +tune2fs +blockd +rsyslog +dnsmasq-full +nvme-cli +smartmontools +telegraf + DEPENDS:=+parted +block-mount +rsync +tune2fs +blockd +rsyslog +dnsmasq-full +nvme-cli +smartmontools +telegraf EXTRA_DEPENDS:=telegraf (>=1.40.2) PKGARCH:=all endef @@ -34,28 +34,9 @@ endef define Build/Compile endef -define Package/ns-storage/postinst -#!/bin/sh -if [ -z "$${IPKG_INSTROOT}" ]; then - crontab -l | grep -q '/usr/sbin/logrotate /etc/logrotate.conf' || echo '5 1 * * * /usr/sbin/logrotate /etc/logrotate.conf' >> /etc/crontabs/root - /etc/init.d/cron restart -fi -exit 0 -endef - -define Package/ns-storage/prerm -#!/bin/sh -if [ -z "$${IPKG_INSTROOT}" ]; then - crontab -l | grep -v "/usr/sbin/logrotate /etc/logrotate.conf" | sort | uniq | crontab - -fi -exit 0 -endef - - define Package/ns-storage/install $(INSTALL_DIR) $(1)/usr/sbin $(INSTALL_DIR) $(1)/etc/uci-defaults - $(INSTALL_DIR) $(1)/etc/logrotate.d $(INSTALL_DIR) $(1)/usr/libexec $(INSTALL_DIR) $(1)/usr/libexec/sync-data $(INSTALL_DIR) $(1)/etc/init.d @@ -71,8 +52,7 @@ define Package/ns-storage/install $(INSTALL_BIN) ./files/30_ns-storage $(1)/etc/uci-defaults $(INSTALL_BIN) ./files/31-ns-storage-default.uci-default $(1)/etc/uci-defaults/31-ns-storage-default $(INSTALL_BIN) ./files/32-ns-storage-convert-uuid.uci-default $(1)/etc/uci-defaults/32-ns-storage-convert-uuid - $(INSTALL_BIN) ./files/33-ns-storage-cleanup-root.uci-default $(1)/etc/uci-defaults/33-ns-storage-cleanup-root - $(INSTALL_CONF) ./files/data.conf $(1)/etc/logrotate.d + $(INSTALL_BIN) ./files/33-ns-storage-drop-disk-log.uci-default $(1)/etc/uci-defaults/33-ns-storage-drop-disk-log $(INSTALL_BIN) ./files/storage-status $(1)/usr/sbin $(INSTALL_BIN) ./files/ns-storage-check.init $(1)/etc/init.d/ns-storage-check $(INSTALL_BIN) ./files/30-ns-storage $(1)/etc/hotplug.d/block/ diff --git a/packages/ns-storage/README.md b/packages/ns-storage/README.md index 3c47d1908..0ec08dae1 100644 --- a/packages/ns-storage/README.md +++ b/packages/ns-storage/README.md @@ -3,15 +3,13 @@ As default, logs are written inside a volatile in-memory directory to prevent errors on the root file system in case of failure. -The `ns-storage` package configures the system to save a copy of the logs inside an extra data local storage, -like a USB stick. +The `ns-storage` package configures an extra data local storage, like a USB stick, where services keep +their persistent data. Persistent logs are stored there by victoria-logs. Features: - device initialization and mounting -- rsyslog configuration - dnsmasq DHCP lease persistence on mounted storage -- logrotate for extra log files - customizable cron job to sync data once a day ## Add a data storage @@ -67,8 +65,7 @@ add-storage /dev/sda The script will mount the storage at `/mnt/data` and configure the system as follow: -- rsyslog will write logs also inside `/mnt/data/log/messages` file -- logrotate will rotate `/mnt/data/log/messages` once a week (see `/etc/logrotate/data.conf` for more info) +- victoria-logs will store logs inside `/mnt/data/victoria-logs-data`, see the victoria-logs README for retention - dnsmasq will store DHCP leases inside `/mnt/data/dnsmasq/dhcp.leases`; `/tmp/dhcp.leases` remains available as a compatibility symlink while the storage is mounted ### Storage status alert diff --git a/packages/ns-storage/files/30_ns-storage b/packages/ns-storage/files/30_ns-storage index e3a6a7e2d..4c4b42d8f 100644 --- a/packages/ns-storage/files/30_ns-storage +++ b/packages/ns-storage/files/30_ns-storage @@ -19,8 +19,6 @@ config selector ns_memory option destination ':omfile:\$log_rotation' EOI -crontab -l | grep -q '/usr/sbin/logrotate /etc/logrotate.conf' || echo '5 1 * * * /usr/sbin/logrotate /etc/logrotate.conf' >> /etc/crontabs/root - # Default log_size in case of error log_size=52428800 diff --git a/packages/ns-storage/files/33-ns-storage-drop-disk-log.uci-default b/packages/ns-storage/files/33-ns-storage-drop-disk-log.uci-default new file mode 100644 index 000000000..8d7c7dbf2 --- /dev/null +++ b/packages/ns-storage/files/33-ns-storage-drop-disk-log.uci-default @@ -0,0 +1,17 @@ +#!/bin/sh + +# +# Copyright (C) 2026 Nethesis S.r.l. +# SPDX-License-Identifier: GPL-2.0-only +# + +# Persistent logs are stored by victoria-logs, rsyslog no longer writes to /mnt/data/log/messages +if [ "$(uci -q get rsyslog.ns_data)" = "selector" ]; then + uci delete rsyslog.ns_data + uci commit rsyslog +fi + +crontab -l 2>/dev/null | grep -q '/usr/sbin/logrotate /etc/logrotate.conf' && \ + crontab -l | grep -v '/usr/sbin/logrotate /etc/logrotate.conf' | crontab - + +exit 0 diff --git a/packages/ns-storage/files/add-storage b/packages/ns-storage/files/add-storage index 9aa15d682..87a14ecb8 100755 --- a/packages/ns-storage/files/add-storage +++ b/packages/ns-storage/files/add-storage @@ -35,14 +35,6 @@ uci set fstab.ns_data.label="$LABEL" uci set fstab.ns_data.enabled=1 uci commit fstab -# setup rsyslog to write log into the device -mkdir -p "$mdir/log" -uci set rsyslog.ns_data=selector -uci set rsyslog.ns_data.source='*.*' -uci set rsyslog.ns_data.destination="$mdir/log/messages" -uci commit rsyslog -/etc/init.d/rsyslog restart - crontab -l | grep -q '/usr/sbin/sync-data' || echo '40 1 * * * /usr/sbin/sync-data' >> /etc/crontabs/root /etc/init.d/cron restart diff --git a/packages/ns-storage/files/data.conf b/packages/ns-storage/files/data.conf deleted file mode 100644 index a99dd0d60..000000000 --- a/packages/ns-storage/files/data.conf +++ /dev/null @@ -1,14 +0,0 @@ -/mnt/data/log/messages { - weekly - rotate 52 - create - notifempty - nomail - missingok - compress - dateext - delaycompress - postrotate - kill -HUP $(cat /var/run/rsyslogd.pid 2> /dev/null) 2> /dev/null || true - endscript -} diff --git a/packages/ns-storage/files/ns-storage-check.init b/packages/ns-storage/files/ns-storage-check.init index 50371bc8f..76c360432 100644 --- a/packages/ns-storage/files/ns-storage-check.init +++ b/packages/ns-storage/files/ns-storage-check.init @@ -15,16 +15,10 @@ storage_check() { if [ "$(storage-status)" = "error" ]; then echo "Storage is in error state, disabling write to disk." - uci -q delete rsyslog.ns_data - uci commit crontab -l | grep -v "/usr/sbin/sync-data" | sort | uniq | crontab - - elif [ "$(storage-status)" = "ok" ] && [ -z "$(uci -q get rsyslog.ns_data)" ]; then - echo "Storage is in ok state, enabling write to disk if not enabled." - crontab -l | grep -q '/usr/sbin/sync-data' || echo '40 1 * * * /usr/sbin/sync-data' >> /etc/crontabs/root - uci set rsyslog.ns_data=selector - uci set rsyslog.ns_data.source='*.*' - uci set rsyslog.ns_data.destination="/mnt/data/log/messages" - uci commit rsyslog + elif [ "$(storage-status)" = "ok" ] && ! crontab -l | grep -q '/usr/sbin/sync-data'; then + echo "Storage is in ok state, enabling write to disk." + echo '40 1 * * * /usr/sbin/sync-data' >> /etc/crontabs/root fi /usr/libexec/ns-storage-dhcp-leases diff --git a/packages/ns-storage/files/remove-storage b/packages/ns-storage/files/remove-storage index 36f6015e7..de6a91f14 100644 --- a/packages/ns-storage/files/remove-storage +++ b/packages/ns-storage/files/remove-storage @@ -19,11 +19,6 @@ data_disk='' uci -q delete fstab.ns_data || : uci commit fstab -# Configuring rsyslog -uci -q delete rsyslog.ns_data || : -uci commit rsyslog -/etc/init.d/rsyslog restart - # Removing sync-data cron job (crontab -l 2>/dev/null || :) | grep -v "/usr/sbin/sync-data" | sort | uniq | crontab - /etc/init.d/cron restart diff --git a/packages/rsyslog/files/rsyslog.init b/packages/rsyslog/files/rsyslog.init index c83d5d612..a74245a5a 100644 --- a/packages/rsyslog/files/rsyslog.init +++ b/packages/rsyslog/files/rsyslog.init @@ -94,7 +94,12 @@ expand_config() { > ${CONFIG_FILE} echo "include(file=\"${BASE_CONFIG_FILE}\" mode=\"optional\")" >> ${CONFIG_FILE} for m in ${modules}; do - echo "module(load=\"${m}\")" >> ${CONFIG_FILE} + if [ "${m}" = "imklog" ]; then + # early userspace (preinit, procd, block, mount_root) logs to kmsg with non-kernel facilities + echo "module(load=\"imklog\" permitNonKernelFacility=\"on\")" >> ${CONFIG_FILE} + else + echo "module(load=\"${m}\")" >> ${CONFIG_FILE} + fi done echo "${input_t}" >> ${CONFIG_FILE} echo "${input_u}" >> ${CONFIG_FILE} diff --git a/packages/victoria-logs/README.md b/packages/victoria-logs/README.md index 1425696a6..9e6733260 100644 --- a/packages/victoria-logs/README.md +++ b/packages/victoria-logs/README.md @@ -12,12 +12,7 @@ This package provides **Victoria Logs** for centralized log storage and aggregat ## Installation -This package is **not installed by default**. To enable Victoria Logs: - -```bash -# Install the package -apk add victoria-logs -``` +This package is installed by default and it's where persistent logs are kept when a data storage is mounted. The package depends on rsyslog. This service will automatically start on installation. diff --git a/packages/victoria-logs/files/rsyslog-victoria-logs.conf b/packages/victoria-logs/files/rsyslog-victoria-logs.conf index c2a66de3b..8972195d6 100644 --- a/packages/victoria-logs/files/rsyslog-victoria-logs.conf +++ b/packages/victoria-logs/files/rsyslog-victoria-logs.conf @@ -12,6 +12,11 @@ ruleset(name="victoria-logs") { action.resumeRetryCount="-1" queue.type="linkedList" queue.size="10000" + # keep messages queued before victoria-logs starts across rsyslog restarts + queue.spoolDirectory="/var/spool" + queue.filename="victorialogsq" + queue.saveOnShutdown="on" + queue.maxDiskSpace="10m" ) } From 215e85cf011e4a05be60c165e534a4f75e3b8987 Mon Sep 17 00:00:00 2001 From: Filippo Carletti Date: Tue, 3 Nov 2026 15:23:57 +0100 Subject: [PATCH 08/51] feat(setup): add root password action --- packages/ns-api/files/setup | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/packages/ns-api/files/setup b/packages/ns-api/files/setup index fd14547b4..b6137c690 100644 --- a/packages/ns-api/files/setup +++ b/packages/ns-api/files/setup @@ -1138,17 +1138,23 @@ confirm_exit() { whiptail --title "Exit" --yesno "You have unsaved network changes.\nExit without applying?" 10 70 } +change_password() { + passwd +} + main_menu() { while true; do - run_dialog --title "Setup" --cancel-button "Exit" --menu "Choose an action" 14 70 3 \ + run_dialog --title "Setup" --cancel-button "Exit" --menu "Choose an action" 16 70 4 \ network "Configure network" \ keymap "Keyboard layout: ${KEYMAP}" \ + password "Change root password" \ exit "Exit without applying" || { confirm_exit && break; continue; } selection="$WHIPTAIL_RESULT" case "$selection" in keymap) pick_keymap ;; network) network_menu ;; + password) change_password ;; exit) confirm_exit && break ;; esac done From c29ac8868d23722c89d9c3fe5afb920d0bc19330 Mon Sep 17 00:00:00 2001 From: Giacomo Sanchietti Date: Wed, 4 Nov 2026 08:26:24 +0100 Subject: [PATCH 09/51] feat(setup): toggle WAN UI access Add a setup menu entry to open or close access to the web UI port 9090 from the WAN zone. Assisted-by: Claude Code:claude-sonnet-5-5 --- packages/ns-api/files/setup | 31 ++++++++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/packages/ns-api/files/setup b/packages/ns-api/files/setup index b6137c690..51ff8b008 100644 --- a/packages/ns-api/files/setup +++ b/packages/ns-api/files/setup @@ -1142,12 +1142,40 @@ change_password() { passwd } +remote_access_status() { + if [ "$(uci -q get firewall.ns_allow_ui.enabled)" = "0" ]; then + printf '%s' 'closed' + else + printf '%s' 'open' + fi +} + +toggle_remote_access() { + if [ "$(remote_access_status)" = "open" ]; then + state='closed' + value='0' + else + state='open' + value='1' + fi + + uci set "firewall.ns_allow_ui.enabled=$value" && + uci commit firewall && + /etc/init.d/firewall reload || { + whiptail --title "Setup Error" --msgbox "Unable to change remote access." 10 70 + return 1 + } + + whiptail --title "Setup" --msgbox "Remote access to port 9090 from WAN is now $state." 10 70 +} + main_menu() { while true; do - run_dialog --title "Setup" --cancel-button "Exit" --menu "Choose an action" 16 70 4 \ + run_dialog --title "Setup" --cancel-button "Exit" --menu "Choose an action" 18 70 5 \ network "Configure network" \ keymap "Keyboard layout: ${KEYMAP}" \ password "Change root password" \ + remote-access "Toggle access to port 9090 from WAN: $(remote_access_status)" \ exit "Exit without applying" || { confirm_exit && break; continue; } selection="$WHIPTAIL_RESULT" @@ -1155,6 +1183,7 @@ main_menu() { keymap) pick_keymap ;; network) network_menu ;; password) change_password ;; + remote-access) toggle_remote_access ;; exit) confirm_exit && break ;; esac done From 2ddc06cd6b400e604642358d82603886b913ae25 Mon Sep 17 00:00:00 2001 From: Giacomo Sanchietti Date: Wed, 4 Nov 2026 08:26:25 +0100 Subject: [PATCH 10/51] feat(firewall): disable WAN UI access by default New images no longer expose the web UI port 9090 on WAN. Existing installations keep their current rule. Assisted-by: Claude Code:claude-sonnet-5-5 --- files/etc/config/firewall | 1 + 1 file changed, 1 insertion(+) diff --git a/files/etc/config/firewall b/files/etc/config/firewall index 2f1f93313..5f84d5b92 100644 --- a/files/etc/config/firewall +++ b/files/etc/config/firewall @@ -36,6 +36,7 @@ config rule 'ns_allow_ui' option src 'wan' option dest_port '9090' option target 'ACCEPT' + option enabled '0' # We need to accept udp packets on port 68, # see https://dev.openwrt.org/ticket/4108 From f9c0266e0f7b152393614f59cd4df88462cc4143 Mon Sep 17 00:00:00 2001 From: Giacomo Sanchietti Date: Wed, 4 Nov 2026 08:26:42 +0100 Subject: [PATCH 11/51] fix(setup): report root password change result The menu was redrawn right after passwd, hiding its output. Show a dialog telling whether the password was changed. Assisted-by: Claude Code:claude-sonnet-5-5 --- packages/ns-api/files/setup | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/packages/ns-api/files/setup b/packages/ns-api/files/setup index 51ff8b008..f42104318 100644 --- a/packages/ns-api/files/setup +++ b/packages/ns-api/files/setup @@ -1139,7 +1139,12 @@ confirm_exit() { } change_password() { - passwd + clear + if passwd; then + whiptail --title "Setup" --msgbox "Root password changed." 10 70 + else + whiptail --title "Setup Error" --msgbox "Root password not changed." 10 70 + fi } remote_access_status() { From ac1cc1571b8bffd2ac0369b8907c51a86cc45827 Mon Sep 17 00:00:00 2001 From: Giacomo Sanchietti Date: Wed, 4 Nov 2026 08:31:11 +0100 Subject: [PATCH 12/51] fix(setup): use Success and Error dialog titles Make the result of the password change and remote access toggle clear at a glance. Assisted-by: Claude Code:claude-opus-5-5 --- packages/ns-api/files/setup | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/ns-api/files/setup b/packages/ns-api/files/setup index f42104318..0cc9a4ad7 100644 --- a/packages/ns-api/files/setup +++ b/packages/ns-api/files/setup @@ -1141,9 +1141,9 @@ confirm_exit() { change_password() { clear if passwd; then - whiptail --title "Setup" --msgbox "Root password changed." 10 70 + whiptail --title "Success" --msgbox "Root password changed." 10 70 else - whiptail --title "Setup Error" --msgbox "Root password not changed." 10 70 + whiptail --title "Error" --msgbox "Root password not changed." 10 70 fi } @@ -1167,11 +1167,11 @@ toggle_remote_access() { uci set "firewall.ns_allow_ui.enabled=$value" && uci commit firewall && /etc/init.d/firewall reload || { - whiptail --title "Setup Error" --msgbox "Unable to change remote access." 10 70 + whiptail --title "Error" --msgbox "Unable to change remote access." 10 70 return 1 } - whiptail --title "Setup" --msgbox "Remote access to port 9090 from WAN is now $state." 10 70 + whiptail --title "Success" --msgbox "Remote access to port 9090 from WAN is now $state." 10 70 } main_menu() { From 46e62bed3e954384016423cc46fdf0aff05defad Mon Sep 17 00:00:00 2001 From: Tommaso Bailetti Date: Wed, 4 Nov 2026 12:45:01 +0100 Subject: [PATCH 13/51] feat: added proxying of victoria-logs --- packages/ns-api-server/Makefile | 2 +- packages/ns-api-server/files/ns-api-server.initd | 10 +++++++++- .../files/src/configuration/configuration.go | 7 +++++++ packages/ns-api-server/files/src/main.go | 6 ++++++ 4 files changed, 23 insertions(+), 2 deletions(-) diff --git a/packages/ns-api-server/Makefile b/packages/ns-api-server/Makefile index 5c4ba4142..e26c7011c 100644 --- a/packages/ns-api-server/Makefile +++ b/packages/ns-api-server/Makefile @@ -33,7 +33,7 @@ define Package/ns-api-server CATEGORY:=NethSecurity TITLE:=NethSecurity REST API server URL:=https://github.com/NethServer/nethsecurity-api - DEPENDS:=$(GO_ARCH_DEPENDS) +victoria-metrics + DEPENDS:=$(GO_ARCH_DEPENDS) +victoria-metrics +victoria-logs endef define Package/ns-api-server/description diff --git a/packages/ns-api-server/files/ns-api-server.initd b/packages/ns-api-server/files/ns-api-server.initd index 9376dc73a..d00aded6b 100644 --- a/packages/ns-api-server/files/ns-api-server.initd +++ b/packages/ns-api-server/files/ns-api-server.initd @@ -55,6 +55,13 @@ start_service() { :*) vmalert_http_listen_addr="127.0.0.1${vmalert_http_listen_addr}" ;; esac + config_load victoria-logs + local vl_http_listen_addr + config_get vl_http_listen_addr main http_listen_addr "127.0.0.1:9428" + case "$vl_http_listen_addr" in + :*) vl_http_listen_addr="127.0.0.1${vl_http_listen_addr}" ;; + esac + procd_set_param env GIN_MODE=release \ LISTEN_ADDRESS=127.0.0.1:8090 \ SECRET_JWT="${SECRET_JWT}" \ @@ -65,6 +72,7 @@ start_service() { UPLOAD_FILE_MAX_SIZE=${UPLOAD_FILE_MAX_SIZE} \ VICTORIA_METRICS_URL="http://${vm_http_listen_addr}" \ VMALERT_URL="http://${vmalert_http_listen_addr}" \ + VICTORIA_LOGS_URL="http://${vl_http_listen_addr}" \ GLOBAL_RATE_LIMIT_AVERAGE=${GLOBAL_RATE_LIMIT_AVERAGE} \ GLOBAL_RATE_LIMIT_BURST=${GLOBAL_RATE_LIMIT_BURST} @@ -76,7 +84,7 @@ start_service() { } service_triggers() { - procd_add_reload_trigger victoria-metrics vmalert + procd_add_reload_trigger victoria-metrics vmalert victoria-logs } reload_service() { diff --git a/packages/ns-api-server/files/src/configuration/configuration.go b/packages/ns-api-server/files/src/configuration/configuration.go index 8087f366c..71b968785 100644 --- a/packages/ns-api-server/files/src/configuration/configuration.go +++ b/packages/ns-api-server/files/src/configuration/configuration.go @@ -33,6 +33,7 @@ type Configuration struct { VictoriaMetricsURL string `json:"victoria_metrics_url"` VMAlertURL string `json:"vmalert_url"` + VictoriaLogsURL string `json:"victoria_logs_url"` // Generous global per-IP rate limit applied to every API route as a coarse // safety net; 0 disables it @@ -112,6 +113,12 @@ func Init() { Config.VMAlertURL = "http://127.0.0.1:8082" } + if os.Getenv("VICTORIA_LOGS_URL") != "" { + Config.VictoriaLogsURL = os.Getenv("VICTORIA_LOGS_URL") + } else { + Config.VictoriaLogsURL = "http://127.0.0.1:9428" + } + if v, err := strconv.Atoi(os.Getenv("GLOBAL_RATE_LIMIT_AVERAGE")); err == nil { Config.GlobalRateLimitAverage = v } else { diff --git a/packages/ns-api-server/files/src/main.go b/packages/ns-api-server/files/src/main.go index a958614e2..120a3e8dd 100644 --- a/packages/ns-api-server/files/src/main.go +++ b/packages/ns-api-server/files/src/main.go @@ -124,6 +124,12 @@ func main() { authGroup.Any("/metrics/query_range", methods.ProxyTo(victoriaMetricsProxy, "/api/v1/query_range")) authGroup.Any("/alerts/alerts", methods.ProxyTo(methods.NewReverseProxy(configuration.Config.VMAlertURL), "/api/v1/alerts")) + // reverse proxies to VictoriaLogs + victoriaLogsProxy := methods.NewReverseProxy(configuration.Config.VictoriaLogsURL) + authGroup.Any("/logs/query", methods.ProxyTo(victoriaLogsProxy, "/select/logsql/query")) + authGroup.Any("/logs/hits", methods.ProxyTo(victoriaLogsProxy, "/select/logsql/hits")) + authGroup.Any("/logs/field_values", methods.ProxyTo(victoriaLogsProxy, "/select/logsql/field_values")) + // handle missing endpoint router.NoRoute(func(c *gin.Context) { c.JSON(http.StatusNotFound, structs.Map(response.StatusNotFound{ From 5b1bae0c4ab329e1a33ace6a1dde544857fa2035 Mon Sep 17 00:00:00 2001 From: Tommaso Bailetti Date: Wed, 4 Nov 2026 17:31:55 +0100 Subject: [PATCH 14/51] build: added ulogd --- config/ulogd.conf | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 config/ulogd.conf diff --git a/config/ulogd.conf b/config/ulogd.conf new file mode 100644 index 000000000..753eb734f --- /dev/null +++ b/config/ulogd.conf @@ -0,0 +1,6 @@ +# Enable ulogd to receive nft logs over NFLOG +CONFIG_PACKAGE_ulogd=y +CONFIG_PACKAGE_ulogd-mod-nflog=y +CONFIG_PACKAGE_ulogd-mod-syslog=y +CONFIG_PACKAGE_ulogd-mod-extra=y +CONFIG_PACKAGE_kmod-nfnetlink-log=y From ce2db32a8d4cbef7528896174b43c190fd7ea180 Mon Sep 17 00:00:00 2001 From: Tommaso Bailetti Date: Wed, 4 Nov 2026 17:34:13 +0100 Subject: [PATCH 15/51] ui bump --- packages/ns-ui/Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/ns-ui/Makefile b/packages/ns-ui/Makefile index 089492351..e64205c2a 100644 --- a/packages/ns-ui/Makefile +++ b/packages/ns-ui/Makefile @@ -12,7 +12,7 @@ PKG_RELEASE:=1 PKG_SOURCE_PROTO:=git PKG_SOURCE_URL:=https://github.com/NethServer/nethsecurity-ui.git -PKG_SOURCE_VERSION:=$(PKG_VERSION) +PKG_SOURCE_VERSION:=bd8185cd4e0c6824afdcc53b5181a6d50c374e0c PKG_SOURCE_SUBDIR:=nethsecurity-ui-$(PKG_SOURCE_VERSION) PKG_BUILD_DIR:=$(BUILD_DIR)/$(PKG_SOURCE_SUBDIR) PKG_MIRROR_HASH:=skip From 208bfb328bc2c8d92dc5ac7631067a74c6222846 Mon Sep 17 00:00:00 2001 From: Tommaso Bailetti Date: Wed, 4 Nov 2026 17:34:53 +0100 Subject: [PATCH 16/51] build: enabled DCO for openvpn --- config/openvpn.conf | 1 + 1 file changed, 1 insertion(+) diff --git a/config/openvpn.conf b/config/openvpn.conf index 79fd8fbdd..1807286b7 100644 --- a/config/openvpn.conf +++ b/config/openvpn.conf @@ -10,3 +10,4 @@ CONFIG_OPENVPN_openssl_ENABLE_MULTIHOME=y CONFIG_OPENVPN_openssl_ENABLE_PORT_SHARE=y CONFIG_OPENVPN_openssl_ENABLE_DEF_AUTH=y CONFIG_OPENVPN_openssl_ENABLE_SMALL=y +CONFIG_OPENVPN_openssl_ENABLE_DCO=y From 39c88061556798bd1e3ec7de4626c9745759e24e Mon Sep 17 00:00:00 2001 From: Tommaso Bailetti Date: Wed, 4 Nov 2026 17:41:23 +0100 Subject: [PATCH 17/51] fix: adjusted some log levels --- .../etc/uci-defaults/99-nethsec-cron-loglevel | 12 ++++++ .../files/src/configuration/configuration.go | 6 +-- packages/ns-api-server/files/src/logs/logs.go | 42 ++++++++++++++++--- packages/ns-api-server/files/src/main.go | 2 +- .../ns-api-server/files/src/methods/auth.go | 16 +++---- .../ns-api-server/files/src/methods/proxy.go | 4 +- .../files/src/methods/proxy_test.go | 9 ---- .../ns-api-server/files/src/methods/ubus.go | 10 ++--- .../files/src/middleware/middleware.go | 20 ++++----- .../files/src/middleware/middleware_test.go | 3 +- .../files/src/middleware/on_behalf_of_test.go | 3 +- .../files/src/middleware/rate_limit.go | 2 +- .../files/rsyslog-victoria-logs.conf | 14 ++++++- 13 files changed, 93 insertions(+), 50 deletions(-) create mode 100644 files/etc/uci-defaults/99-nethsec-cron-loglevel diff --git a/files/etc/uci-defaults/99-nethsec-cron-loglevel b/files/etc/uci-defaults/99-nethsec-cron-loglevel new file mode 100644 index 000000000..d72df7439 --- /dev/null +++ b/files/etc/uci-defaults/99-nethsec-cron-loglevel @@ -0,0 +1,12 @@ +# +# Copyright (C) 2026 Nethesis S.r.l. +# SPDX-License-Identifier: GPL-2.0-only +# + +# Stop crond from logging every job it runs, errors are still logged +[ "$(uci -q get system.@system[0].cronloglevel)" != "" ] && exit 0 + +uci -q batch << EOI +set system.@system[0].cronloglevel="9" +commit system +EOI diff --git a/packages/ns-api-server/files/src/configuration/configuration.go b/packages/ns-api-server/files/src/configuration/configuration.go index 71b968785..3ffb08e31 100644 --- a/packages/ns-api-server/files/src/configuration/configuration.go +++ b/packages/ns-api-server/files/src/configuration/configuration.go @@ -54,7 +54,7 @@ func Init() { if os.Getenv("SECRET_JWT") != "" { Config.SecretJWT = os.Getenv("SECRET_JWT") } else { - logs.Logs.Println("[CRITICAL][ENV] SECRET_JWT variable is empty") + logs.Crit("[ENV] SECRET_JWT variable is empty") os.Exit(1) } @@ -67,14 +67,14 @@ func Init() { if os.Getenv("SECRETS_DIR") != "" { Config.SecretsDir = os.Getenv("SECRETS_DIR") } else { - logs.Logs.Println("[CRITICAL][ENV] SECRETS_DIR variable is empty") + logs.Crit("[ENV] SECRETS_DIR variable is empty") os.Exit(1) } if os.Getenv("TOKENS_DIR") != "" { Config.TokensDir = os.Getenv("TOKENS_DIR") } else { - logs.Logs.Println("[CRITICAL][ENV] TOKENS_DIR variable is empty") + logs.Crit("[ENV] TOKENS_DIR variable is empty") os.Exit(1) } diff --git a/packages/ns-api-server/files/src/logs/logs.go b/packages/ns-api-server/files/src/logs/logs.go index 9cf14dfec..a3e96a405 100644 --- a/packages/ns-api-server/files/src/logs/logs.go +++ b/packages/ns-api-server/files/src/logs/logs.go @@ -10,16 +10,46 @@ package logs import ( - "log" + "fmt" + "io" + "log/syslog" "os" ) -var Logs *log.Logger +var writer *syslog.Writer + +// Output receives the log lines when syslog isn't available +var Output io.Writer = os.Stderr func Init(name string) { - // init syslog writer - logger := log.New(os.Stderr, name+" ", log.Ldate|log.Ltime|log.Lshortfile) + w, err := syslog.New(syslog.LOG_DAEMON|syslog.LOG_INFO, name) + if err != nil { + fmt.Fprintln(Output, "[ERR][LOGS] cannot connect to syslog: "+err.Error()) + return + } + writer = w +} + +func Info(msg string) { + if writer == nil { + fmt.Fprintln(Output, msg) + return + } + writer.Info(msg) +} + +func Err(msg string) { + if writer == nil { + fmt.Fprintln(Output, msg) + return + } + writer.Err(msg) +} - // assign writer to Logs var - Logs = logger +func Crit(msg string) { + if writer == nil { + fmt.Fprintln(Output, msg) + return + } + writer.Crit(msg) } diff --git a/packages/ns-api-server/files/src/main.go b/packages/ns-api-server/files/src/main.go index 120a3e8dd..aea61f062 100644 --- a/packages/ns-api-server/files/src/main.go +++ b/packages/ns-api-server/files/src/main.go @@ -45,7 +45,7 @@ import ( func main() { // init logs with syslog - logs.Init("nethsecurity_api") + logs.Init("nethsecurity-api") // init configuration configuration.Init() diff --git a/packages/ns-api-server/files/src/methods/auth.go b/packages/ns-api-server/files/src/methods/auth.go index d3ec0896d..73757112a 100644 --- a/packages/ns-api-server/files/src/methods/auth.go +++ b/packages/ns-api-server/files/src/methods/auth.go @@ -216,7 +216,7 @@ func QRCode(c *gin.Context) { secret := make([]byte, 20) _, err := rand.Read(secret) if err != nil { - logs.Logs.Println("[ERR][2FA] Failed to generate random secret for QRCode: " + err.Error()) + logs.Err("[2FA] Failed to generate random secret for QRCode: " + err.Error()) } // convert to string @@ -243,7 +243,7 @@ func QRCode(c *gin.Context) { // define URL URL, err := url.Parse("otpauth://totp") if err != nil { - logs.Logs.Println("[ERR][2FA] Failed to parse URL for QRCode: " + err.Error()) + logs.Err("[2FA] Failed to parse URL for QRCode: " + err.Error()) } // add params @@ -448,7 +448,7 @@ func ValidateAuth(tokenString string, ensureTokenExists bool) bool { }) if err != nil { - logs.Logs.Println("[ERR][JWT] error in JWT token validation: " + err.Error()) + logs.Err("[JWT] error in JWT token validation: " + err.Error()) return false } @@ -458,14 +458,14 @@ func ValidateAuth(tokenString string, ensureTokenExists bool) bool { username := claims["id"].(string) if !CheckTokenValidation(username, tokenString) { - logs.Logs.Println("[ERR][JWT] error JWT token not found") + logs.Err("[JWT] error JWT token not found") return false } } return true } } else { - logs.Logs.Println("[ERR][JWT] error in JWT token claims") + logs.Err("[JWT] error in JWT token claims") return false } } @@ -542,7 +542,7 @@ func DeleteExpiredTokens() { // check read error if err != nil { - logs.Logs.Println("[ERR][JWT] Failed to read tokens dir " + configuration.Config.TokensDir + ". Error: " + err.Error()) + logs.Err("[JWT] Failed to read tokens dir " + configuration.Config.TokensDir + ". Error: " + err.Error()) } // list usernames @@ -552,7 +552,7 @@ func DeleteExpiredTokens() { // check error if err != nil { - logs.Logs.Println("[ERR][JWT] Failed to read tokens file " + configuration.Config.TokensDir + "/" + username.Name() + ". Error: " + err.Error()) + logs.Err("[JWT] Failed to read tokens file " + configuration.Config.TokensDir + "/" + username.Name() + ". Error: " + err.Error()) } // get string file @@ -590,7 +590,7 @@ func DeleteExpiredTokens() { // check error if errWrite != nil { - logs.Logs.Println("[ERR][JWT] Failed to write new tokens file " + configuration.Config.TokensDir + "/" + username.Name() + ". Error: " + errWrite.Error()) + logs.Err("[JWT] Failed to write new tokens file " + configuration.Config.TokensDir + "/" + username.Name() + ". Error: " + errWrite.Error()) } } diff --git a/packages/ns-api-server/files/src/methods/proxy.go b/packages/ns-api-server/files/src/methods/proxy.go index 6f9063933..63e2d4ce6 100644 --- a/packages/ns-api-server/files/src/methods/proxy.go +++ b/packages/ns-api-server/files/src/methods/proxy.go @@ -23,7 +23,7 @@ import ( func NewReverseProxy(rawBaseURL string) *httputil.ReverseProxy { target, err := url.Parse(rawBaseURL) if err != nil { - logs.Logs.Println("[CRITICAL][PROXY] invalid backend URL:", rawBaseURL, err.Error()) + logs.Crit("[PROXY] invalid backend URL: " + rawBaseURL + " " + err.Error()) } proxy := httputil.NewSingleHostReverseProxy(target) @@ -31,7 +31,7 @@ func NewReverseProxy(rawBaseURL string) *httputil.ReverseProxy { ResponseHeaderTimeout: 10 * time.Second, } proxy.ErrorHandler = func(w http.ResponseWriter, r *http.Request, err error) { - logs.Logs.Println("[ERROR][PROXY] backend unreachable:", err.Error()) + logs.Err("[PROXY] backend unreachable: " + err.Error()) w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusBadGateway) json.NewEncoder(w).Encode(structs.Map(response.StatusBadGateway{ diff --git a/packages/ns-api-server/files/src/methods/proxy_test.go b/packages/ns-api-server/files/src/methods/proxy_test.go index 7625f47ca..aced5117e 100644 --- a/packages/ns-api-server/files/src/methods/proxy_test.go +++ b/packages/ns-api-server/files/src/methods/proxy_test.go @@ -9,25 +9,16 @@ import ( "bytes" "compress/gzip" "io" - "log" "net/http" "net/http/httptest" - "os" "strings" "testing" "time" - "github.com/NethServer/nethsecurity-api/logs" gzipmw "github.com/gin-contrib/gzip" "github.com/gin-gonic/gin" ) -// proxy.go logs backend errors; logs.Logs is otherwise only set up in main(). -func TestMain(m *testing.M) { - logs.Logs = log.New(os.Stderr, "test ", 0) - os.Exit(m.Run()) -} - // httputil.ReverseProxy needs a real ResponseWriter (CloseNotifier/Flusher), // which httptest.NewRecorder doesn't implement. func startTestServer(t *testing.T, r *gin.Engine) *httptest.Server { diff --git a/packages/ns-api-server/files/src/methods/ubus.go b/packages/ns-api-server/files/src/methods/ubus.go index fba672e12..1b2df1847 100644 --- a/packages/ns-api-server/files/src/methods/ubus.go +++ b/packages/ns-api-server/files/src/methods/ubus.go @@ -51,7 +51,7 @@ func UBusCallAction(c *gin.Context) { stdin, err := cmd.StdinPipe() if err != nil { // log full response for debugging if ubus call fails - logs.Logs.Println("[ERROR][UBUS][STDIN] ubus stdin pipe error:", err.Error()) + logs.Err("[UBUS][STDIN] ubus stdin pipe error: " + err.Error()) c.JSON(http.StatusInternalServerError, structs.Map(response.StatusBadRequest{ Code: 500, Message: "ubus call action failed", @@ -96,8 +96,8 @@ func UBusCallAction(c *gin.Context) { out, err := cmd.CombinedOutput() if err != nil { // log full response for debugging if ubus call fails - logs.Logs.Println("[ERROR][UBUS][PROCESS] ubus execution error:", err.Error()) - logs.Logs.Println("[ERROR][UBUS][OUTPUT] ubus execution output:", string(out)) + logs.Err("[UBUS][PROCESS] ubus execution error: " + err.Error()) + logs.Err("[UBUS][OUTPUT] ubus execution output: " + string(out)) c.JSON(http.StatusInternalServerError, structs.Map(response.StatusBadRequest{ Code: 500, Message: "ubus call action failed", @@ -113,8 +113,8 @@ func UBusCallAction(c *gin.Context) { errorMessage, errFound := jsonParsed.Path("error").Data().(string) if errFound { // log full response for debugging if we find {"error": ...} in response - logs.Logs.Println(fmt.Sprintf( - "[ERROR][UBUS][RESPONSE] ubus application error: Message='%s', Data='%s'", + logs.Err(fmt.Sprintf( + "[UBUS][RESPONSE] ubus application error: Message='%s', Data='%s'", errorMessage, jsonParsed.String(), )) diff --git a/packages/ns-api-server/files/src/middleware/middleware.go b/packages/ns-api-server/files/src/middleware/middleware.go index 001624ceb..dc7a7e2a6 100644 --- a/packages/ns-api-server/files/src/middleware/middleware.go +++ b/packages/ns-api-server/files/src/middleware/middleware.go @@ -118,7 +118,7 @@ func InitJWT() *jwt.GinJWTMiddleware { err := methods.CheckAuthentication(username, password) if err != nil { // login failed, write also the IP address of the client - logs.Logs.Println("[INFO][AUTH] authentication failed for user " + utils.SanitizeForLog(username) + " from " + c.ClientIP() + ": " + err.Error()) + logs.Info("[AUTH] authentication failed for user " + utils.SanitizeForLog(username) + " from " + c.ClientIP() + ": " + err.Error()) // return JWT error return nil, jwt.ErrFailedAuthentication @@ -127,7 +127,7 @@ func InitJWT() *jwt.GinJWTMiddleware { onBehalfOf := checkOnBehalfOf(loginVals.OnBehalfOf, username) // login ok action - logs.Logs.Println("[INFO][AUTH] authentication success for user " + utils.SanitizeForLog(username) + logSuffixOnBehalfOf(onBehalfOf) + " from " + c.ClientIP()) + logs.Info("[AUTH] authentication success for user " + utils.SanitizeForLog(username) + logSuffixOnBehalfOf(onBehalfOf) + " from " + c.ClientIP()) // return user auth model return &models.UserAuthorizations{ @@ -194,7 +194,7 @@ func InitJWT() *jwt.GinJWTMiddleware { // check if token exists if !methods.CheckTokenValidation(claims["id"].(string), token.Raw) { // write logs - logs.Logs.Println("[INFO][AUTH] authorization failed for user " + utils.SanitizeForLog(claims["id"].(string)) + claimsSuffixOnBehalfOf(claims) + ". " + reqMethod + " " + reqURI) + logs.Info("[AUTH] authorization failed for user " + utils.SanitizeForLog(claims["id"].(string)) + claimsSuffixOnBehalfOf(claims) + ". " + reqMethod + " " + reqURI) // not authorized return false @@ -234,7 +234,7 @@ func InitJWT() *jwt.GinJWTMiddleware { reqBody = jsonB } - logs.Logs.Println("[INFO][AUTH] authorization success for user " + utils.SanitizeForLog(claims["id"].(string)) + claimsSuffixOnBehalfOf(claims) + ". " + reqMethod + " " + reqURI + " " + utils.SanitizeForLog(reqBody)) + logs.Info("[AUTH] authorization success for user " + utils.SanitizeForLog(claims["id"].(string)) + claimsSuffixOnBehalfOf(claims) + ". " + reqMethod + " " + reqURI + " " + utils.SanitizeForLog(reqBody)) // authorized return true @@ -250,7 +250,7 @@ func InitJWT() *jwt.GinJWTMiddleware { } // write logs - logs.Logs.Println("[INFO][AUTH] login response success for user " + utils.SanitizeForLog(claims["id"].(string)) + claimsSuffixOnBehalfOf(claims)) + logs.Info("[AUTH] login response success for user " + utils.SanitizeForLog(claims["id"].(string)) + claimsSuffixOnBehalfOf(claims)) // return 200 OK c.JSON(200, gin.H{"code": 200, "expire": t, "token": token}) @@ -264,7 +264,7 @@ func InitJWT() *jwt.GinJWTMiddleware { methods.SetTokenValidation(claims["id"].(string), token) // write logs - logs.Logs.Println("[INFO][AUTH] refresh response success for user " + utils.SanitizeForLog(claims["id"].(string)) + claimsSuffixOnBehalfOf(claims)) + logs.Info("[AUTH] refresh response success for user " + utils.SanitizeForLog(claims["id"].(string)) + claimsSuffixOnBehalfOf(claims)) // return 200 OK c.JSON(200, gin.H{"code": 200, "expire": t, "token": token}) @@ -278,14 +278,14 @@ func InitJWT() *jwt.GinJWTMiddleware { methods.DelTokenValidation(claims["id"].(string), tokenObj.Raw) // write logs - logs.Logs.Println("[INFO][AUTH] logout response success for user " + utils.SanitizeForLog(claims["id"].(string)) + claimsSuffixOnBehalfOf(claims)) + logs.Info("[AUTH] logout response success for user " + utils.SanitizeForLog(claims["id"].(string)) + claimsSuffixOnBehalfOf(claims)) // reutrn 200 OK c.JSON(200, gin.H{"code": 200}) }, Unauthorized: func(c *gin.Context, code int, message string) { // write logs - logs.Logs.Println("[INFO][AUTH] unauthorized request: " + utils.SanitizeForLog(message)) + logs.Info("[AUTH] unauthorized request: " + utils.SanitizeForLog(message)) // response not authorized c.JSON(code, structs.Map(response.StatusUnauthorized{ @@ -302,7 +302,7 @@ func InitJWT() *jwt.GinJWTMiddleware { // check middleware errors if errDefine != nil { - logs.Logs.Println("[ERR][AUTH] middleware definition error: " + errDefine.Error()) + logs.Err("[AUTH] middleware definition error: " + errDefine.Error()) } // init middleware @@ -310,7 +310,7 @@ func InitJWT() *jwt.GinJWTMiddleware { // check error on initialization if errInit != nil { - logs.Logs.Println("[ERR][AUTH] middleware initialization error: " + errInit.Error()) + logs.Err("[AUTH] middleware initialization error: " + errInit.Error()) } // return object diff --git a/packages/ns-api-server/files/src/middleware/middleware_test.go b/packages/ns-api-server/files/src/middleware/middleware_test.go index 1b08b95fb..655a19d3d 100644 --- a/packages/ns-api-server/files/src/middleware/middleware_test.go +++ b/packages/ns-api-server/files/src/middleware/middleware_test.go @@ -10,7 +10,6 @@ package middleware import ( "bytes" "encoding/json" - "log" "net/http" "net/http/httptest" "regexp" @@ -57,7 +56,7 @@ func TestLoginLogInjection(t *testing.T) { configuration.Config.SecretJWT = "test-secret" var buf bytes.Buffer - logs.Logs = log.New(&buf, "", 0) + logs.Output = &buf gin.SetMode(gin.TestMode) jwtMiddleware = nil diff --git a/packages/ns-api-server/files/src/middleware/on_behalf_of_test.go b/packages/ns-api-server/files/src/middleware/on_behalf_of_test.go index 65624930c..8b8387329 100644 --- a/packages/ns-api-server/files/src/middleware/on_behalf_of_test.go +++ b/packages/ns-api-server/files/src/middleware/on_behalf_of_test.go @@ -9,7 +9,6 @@ package middleware import ( "bytes" - "log" "net/http/httptest" "strings" "testing" @@ -129,7 +128,7 @@ func TestOnBehalfOfLogSuffix(t *testing.T) { jwtMiddleware = nil var buf bytes.Buffer - logs.Logs = log.New(&buf, "", 0) + logs.Output = &buf token, _, err := InstanceJWT().TokenGenerator(&models.UserAuthorizations{ Username: controllerUser, diff --git a/packages/ns-api-server/files/src/middleware/rate_limit.go b/packages/ns-api-server/files/src/middleware/rate_limit.go index 58d848d2b..8fa4d4b19 100644 --- a/packages/ns-api-server/files/src/middleware/rate_limit.go +++ b/packages/ns-api-server/files/src/middleware/rate_limit.go @@ -72,7 +72,7 @@ func RateLimiter(rps rate.Limit, burst int) gin.HandlerFunc { mu.Unlock() if !limiter.Allow() { - logs.Logs.Println("[INFO][AUTH] rate limit exceeded for " + ip + " on " + c.Request.URL.Path) + logs.Info("[AUTH] rate limit exceeded for " + ip + " on " + c.Request.URL.Path) c.JSON(http.StatusTooManyRequests, structs.Map(response.StatusTooManyRequests{ Code: http.StatusTooManyRequests, Message: "too many requests", diff --git a/packages/victoria-logs/files/rsyslog-victoria-logs.conf b/packages/victoria-logs/files/rsyslog-victoria-logs.conf index 8972195d6..febd28191 100644 --- a/packages/victoria-logs/files/rsyslog-victoria-logs.conf +++ b/packages/victoria-logs/files/rsyslog-victoria-logs.conf @@ -1,13 +1,25 @@ # Rsyslog configuration for VictoriaLogs +# RFC 5424 without the trailing newline, using the cleaned up fields set below +template(name="victoria-logs" type="string" + string="<%PRI%>1 %TIMESTAMP:::date-rfc3339% %$.host% %$.app% %PROCID% %MSGID% %STRUCTURED-DATA% %$.msg%") + ruleset(name="victoria-logs") { + # rsyslog uses the FQDN only if DNS answered when it started + set $.host = field($hostname, 46, 1); + # banIP and adblock put their version in the tag + set $.app = re_extract($app-name, "^(banIP|adblock)-", 0, 1, $app-name); + # rsyslog's own messages have no tag + if $.app == "" or $.app == "-" then set $.app = "rsyslogd"; + set $.msg = ltrim($msg); + *.* action( type="omfwd" target="127.0.0.1" port="5514" protocol="tcp" TCP_Framing="octet-counted" - Template="RSYSLOG_SyslogProtocol23Format" + Template="victoria-logs" action.resumeRetryCount="-1" queue.type="linkedList" From 31441ff32c26f30ac1321a11fa2a9ff43e37308c Mon Sep 17 00:00:00 2001 From: Matteo Di Lorenzi <52289654+m-dilorenzi@users.noreply.github.com> Date: Thu, 5 Nov 2026 10:02:58 +0100 Subject: [PATCH 18/51] fix(ns-binding): limit log rate for DROP messages in binding tables (#1995) --- packages/ns-binding/files/ns-binding.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/ns-binding/files/ns-binding.py b/packages/ns-binding/files/ns-binding.py index b12fd441c..638659343 100755 --- a/packages/ns-binding/files/ns-binding.py +++ b/packages/ns-binding/files/ns-binding.py @@ -58,7 +58,7 @@ iifname {{ iface }} jump binding {%- endif %} {%- endfor %} - log flags all prefix "ns-binding DROP: " counter + counter limit rate 1/second log flags all prefix "ns-binding DROP: " } chain forward { @@ -72,7 +72,7 @@ iifname {{ iface }} jump binding {%- endif %} {%- endfor %} - log flags all prefix "ns-binding DROP: " counter + counter limit rate 1/second log flags all prefix "ns-binding DROP: " } chain soft-binding { From bef177c81756bed3ec1f71326a0727785ec1e519 Mon Sep 17 00:00:00 2001 From: Giacomo Sanchietti Date: Thu, 5 Nov 2026 09:47:24 +0100 Subject: [PATCH 19/51] fix(adblock): hide feed credentials in logs When a feed download failed, adblock logged the full feed URL to syslog. Nethesis DNS feeds configured by ns-threat_shield embed the subscription credentials as https://:@bl.nethesis.it, so the secret ended up in /var/log/messages and in VictoriaLogs. Strip the user:password@ part before logging, keeping the host and path for debugging. Other URL outputs (etag debug line, JSON report, fetch parameters) do not include the feed URL. Assisted-by: Claude Code:claude-opus-5-5 --- packages/adblock/files/adblock.sh | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/packages/adblock/files/adblock.sh b/packages/adblock/files/adblock.sh index f1554a889..161035e32 100644 --- a/packages/adblock/files/adblock.sh +++ b/packages/adblock/files/adblock.sh @@ -1076,7 +1076,7 @@ f_nftremove() { # backup/restore/remove blocklists # f_list() { - local file files item array safe_url safe_ips safe_cname safe_domains ip out_rc file_name name + local file files item array safe_url safe_ips safe_cname safe_domains ip out_rc file_name name log_url local mode="${1}" src_name="${2:-"${src_name}"}" in_rc="${src_rc:-0}" use_cname="0" case "${mode}" in @@ -1222,7 +1222,12 @@ f_list() { : >"${src_tmpfile}" fi else - f_log "info" "download of '${src_name}' failed, url: ${src_url}, rule: ${src_rset:-"-"}, categories: ${src_cat:-"-"}, rc: ${src_rc}" + # strip user:password@ to keep feed credentials out of the log + case "${src_url}" in + *://*@*) log_url="${src_url%%://*}://${src_url##*@}" ;; + *) log_url="${src_url}" ;; + esac + f_log "info" "download of '${src_name}' failed, url: ${log_url}, rule: ${src_rset:-"-"}, categories: ${src_cat:-"-"}, rc: ${src_rc}" if [ "${adb_action}" != "boot" ] && [ "${adb_action}" != "start" ]; then f_list restore out_rc="${?}" From 9fdb3ebf5a4a6a08f2f2bd5a7a701f4a0433b3a1 Mon Sep 17 00:00:00 2001 From: Tommaso Bailetti Date: Fri, 6 Nov 2026 14:42:57 +0100 Subject: [PATCH 20/51] fix(dpi): making scripts behave using syslog --- packages/ns-dpi/files/dpi-data-update.py | 4 +++- packages/ns-dpi/files/dpi-license-update.py | 4 +++- packages/ns-dpi/files/dpi-update.py | 4 +++- 3 files changed, 9 insertions(+), 3 deletions(-) diff --git a/packages/ns-dpi/files/dpi-data-update.py b/packages/ns-dpi/files/dpi-data-update.py index 5d8050fef..81493f9d6 100644 --- a/packages/ns-dpi/files/dpi-data-update.py +++ b/packages/ns-dpi/files/dpi-data-update.py @@ -11,6 +11,7 @@ import os.path import json import logging +import logging.handlers from os import environ @@ -81,7 +82,8 @@ def download_data(endpoint: str, filename: str) -> None: if __name__ == "__main__": logger = logging.getLogger() logger.setLevel(environ.get("LOGLEVEL", "INFO").upper()) - handler = logging.StreamHandler() + handler = logging.handlers.SysLogHandler("/dev/log", logging.handlers.SysLogHandler.LOG_DAEMON) + handler.ident = "dpi-data-update: " logger.addHandler(handler) errors = [] diff --git a/packages/ns-dpi/files/dpi-license-update.py b/packages/ns-dpi/files/dpi-license-update.py index 61ae36121..417aa6a5f 100644 --- a/packages/ns-dpi/files/dpi-license-update.py +++ b/packages/ns-dpi/files/dpi-license-update.py @@ -13,6 +13,7 @@ import subprocess import json import logging +import logging.handlers import time from os import environ @@ -82,7 +83,8 @@ def download_license() -> str: if __name__ == "__main__": logger = logging.getLogger() logger.setLevel(environ.get("LOGLEVEL", "INFO").upper()) - handler = logging.StreamHandler() + handler = logging.handlers.SysLogHandler("/dev/log", logging.handlers.SysLogHandler.LOG_DAEMON) + handler.ident = "dpi-license-update: " logger.addHandler(handler) try: diff --git a/packages/ns-dpi/files/dpi-update.py b/packages/ns-dpi/files/dpi-update.py index 5890c8148..932fd0816 100755 --- a/packages/ns-dpi/files/dpi-update.py +++ b/packages/ns-dpi/files/dpi-update.py @@ -12,6 +12,7 @@ import os.path import subprocess import logging +import logging.handlers from os import environ import json @@ -65,7 +66,8 @@ def download_file(session: Session, url: str, filename: str) -> bool: if __name__ == "__main__": logger = logging.getLogger() logger.setLevel(environ.get("LOGLEVEL", "INFO").upper()) - handler = logging.StreamHandler() + handler = logging.handlers.SysLogHandler("/dev/log", logging.handlers.SysLogHandler.LOG_DAEMON) + handler.ident = "dpi-update: " logger.addHandler(handler) e_uci = EUci() From 8425a80164052439d054e931a6f086c2e7397511 Mon Sep 17 00:00:00 2001 From: Tommaso Bailetti Date: Fri, 6 Nov 2026 16:14:54 +0100 Subject: [PATCH 21/51] feat(logs): per-package pre log processor (#2004) --- packages/ns-openvpn/Makefile | 2 ++ .../ns-openvpn/files/rsyslog-victoria-logs.conf | 2 ++ packages/rsyslog/Makefile | 2 ++ packages/rsyslog/files/rsyslog.commit-hook | 10 ++++++++++ packages/rsyslog/files/rsyslog.init | 2 ++ packages/telegraf/Makefile | 2 ++ packages/telegraf/files/rsyslog-victoria-logs.conf | 9 +++++++++ packages/victoria-logs/Makefile | 2 ++ .../victoria-logs/files/rsyslog-victoria-logs.conf | 11 +++++++++-- .../files/rsyslog-victoria-logs.d.conf | 14 ++++++++++++++ packages/victoria-metrics/Makefile | 2 ++ .../files/rsyslog-victoria-logs.conf | 14 ++++++++++++++ 12 files changed, 70 insertions(+), 2 deletions(-) create mode 100644 packages/ns-openvpn/files/rsyslog-victoria-logs.conf create mode 100644 packages/rsyslog/files/rsyslog.commit-hook create mode 100644 packages/telegraf/files/rsyslog-victoria-logs.conf create mode 100644 packages/victoria-logs/files/rsyslog-victoria-logs.d.conf create mode 100644 packages/victoria-metrics/files/rsyslog-victoria-logs.conf diff --git a/packages/ns-openvpn/Makefile b/packages/ns-openvpn/Makefile index 1368bec77..bcf4f92e3 100644 --- a/packages/ns-openvpn/Makefile +++ b/packages/ns-openvpn/Makefile @@ -67,6 +67,8 @@ define Package/ns-openvpn/install $(INSTALL_BIN) ./files/99_ns-openvpn-allow-deprecated-static-crypto $(1)/etc/uci-defaults $(INSTALL_BIN) ./files/openvpn-status $(1)/usr/bin $(INSTALL_BIN) ./files/openvpn-kill $(1)/usr/bin + $(INSTALL_DIR) $(1)/etc/rsyslog.d/victoria-logs.d + $(INSTALL_DATA) ./files/rsyslog-victoria-logs.conf $(1)/etc/rsyslog.d/victoria-logs.d/ns-openvpn.conf endef define Package/ns-openvpn/prerm diff --git a/packages/ns-openvpn/files/rsyslog-victoria-logs.conf b/packages/ns-openvpn/files/rsyslog-victoria-logs.conf new file mode 100644 index 000000000..750396dc6 --- /dev/null +++ b/packages/ns-openvpn/files/rsyslog-victoria-logs.conf @@ -0,0 +1,2 @@ +# openvpn logs every command sent to its management socket +if $.app startswith "openvpn" and $.msg startswith "MANAGEMENT:" then set $.drop = "1"; diff --git a/packages/rsyslog/Makefile b/packages/rsyslog/Makefile index e824e23d6..78c437486 100644 --- a/packages/rsyslog/Makefile +++ b/packages/rsyslog/Makefile @@ -74,6 +74,8 @@ define Package/rsyslog/install $(INSTALL_BIN) ./files/rsyslog.init $(1)/etc/init.d/rsyslog $(INSTALL_DIR) $(1)/etc/uci-defaults $(INSTALL_CONF) ./files/20_rsyslog $(1)/etc/uci-defaults + $(INSTALL_DIR) $(1)/etc/apk/commit_hooks.d + $(INSTALL_BIN) ./files/rsyslog.commit-hook $(1)/etc/apk/commit_hooks.d/rsyslog endef define Package/rsyslog/config diff --git a/packages/rsyslog/files/rsyslog.commit-hook b/packages/rsyslog/files/rsyslog.commit-hook new file mode 100644 index 000000000..f4e26ca38 --- /dev/null +++ b/packages/rsyslog/files/rsyslog.commit-hook @@ -0,0 +1,10 @@ +#!/bin/sh + +# +# Copyright (C) 2026 Nethesis S.r.l. +# SPDX-License-Identifier: GPL-2.0-only +# + +# Run by apk after every transaction: pick up config dropped in /etc/rsyslog.d by other packages +[ "$1" = "post-commit" ] && /etc/init.d/rsyslog reload +exit 0 diff --git a/packages/rsyslog/files/rsyslog.init b/packages/rsyslog/files/rsyslog.init index a74245a5a..bb67ed39a 100644 --- a/packages/rsyslog/files/rsyslog.init +++ b/packages/rsyslog/files/rsyslog.init @@ -119,6 +119,8 @@ start_service() { expand_config procd_open_instance procd_set_param command /usr/sbin/rsyslogd -f ${CONFIG_FILE} -n + # restart on reload only when one of these files changed + procd_set_param file ${CONFIG_FILE} /etc/rsyslog.conf /etc/rsyslog.d/*.conf /etc/rsyslog.d/*/*.conf procd_close_instance } diff --git a/packages/telegraf/Makefile b/packages/telegraf/Makefile index 5d9a04bb2..81d51e044 100644 --- a/packages/telegraf/Makefile +++ b/packages/telegraf/Makefile @@ -92,6 +92,8 @@ define Package/telegraf/install $(INSTALL_DATA) ./files/telegraf.conf.d/services.conf $(1)/etc/telegraf.conf.d/services.conf $(INSTALL_DATA) ./files/telegraf.conf.d/mwan.conf $(1)/etc/telegraf.conf.d/mwan.conf $(INSTALL_DATA) ./files/telegraf.conf.d/ha.conf $(1)/etc/telegraf.conf.d/ha.conf + $(INSTALL_DIR) $(1)/etc/rsyslog.d/victoria-logs.d + $(INSTALL_DATA) ./files/rsyslog-victoria-logs.conf $(1)/etc/rsyslog.d/victoria-logs.d/telegraf.conf $(INSTALL_DIR) $(1)/etc/uci-defaults $(INSTALL_BIN) ./files/uci-defaults/99-telegraf-migrate-netdata $(1)/etc/uci-defaults/99-telegraf-migrate-netdata $(INSTALL_DIR) $(1)/usr/sbin diff --git a/packages/telegraf/files/rsyslog-victoria-logs.conf b/packages/telegraf/files/rsyslog-victoria-logs.conf new file mode 100644 index 000000000..20d1f7388 --- /dev/null +++ b/packages/telegraf/files/rsyslog-victoria-logs.conf @@ -0,0 +1,9 @@ +# telegraf writes everything to stderr: take the level from the message and drop its timestamp +if $.app == "telegraf" then { + set $.lvl = re_extract($.msg, "^[^ ]+ ([DIWE])! ", 0, 1, ""); + set $.msg = re_extract($.msg, "^[^ ]+ [DIWE]! (.*)", 0, 1, $.msg); + if $.lvl == "E" then set $.sev = 3; + if $.lvl == "W" then set $.sev = 4; + if $.lvl == "I" then set $.sev = 6; + if $.lvl == "D" then set $.sev = 7; +} diff --git a/packages/victoria-logs/Makefile b/packages/victoria-logs/Makefile index 89d3b179f..9f448bbdf 100644 --- a/packages/victoria-logs/Makefile +++ b/packages/victoria-logs/Makefile @@ -65,6 +65,8 @@ define Package/victoria-logs/install $(INSTALL_DATA) ./files/victoria-logs.conf $(1)/etc/config/victoria-logs $(INSTALL_DIR) $(1)/etc/rsyslog.d $(INSTALL_CONF) ./files/rsyslog-victoria-logs.conf $(1)/etc/rsyslog.d/victoria-logs.conf + $(INSTALL_DIR) $(1)/etc/rsyslog.d/victoria-logs.d + $(INSTALL_DATA) ./files/rsyslog-victoria-logs.d.conf $(1)/etc/rsyslog.d/victoria-logs.d/victoria-logs.conf $(INSTALL_DIR) $(1)/etc/uci-defaults $(INSTALL_BIN) ./files/35_victoria-logs $(1)/etc/uci-defaults/35_victoria-logs endef diff --git a/packages/victoria-logs/files/rsyslog-victoria-logs.conf b/packages/victoria-logs/files/rsyslog-victoria-logs.conf index febd28191..44985b36f 100644 --- a/packages/victoria-logs/files/rsyslog-victoria-logs.conf +++ b/packages/victoria-logs/files/rsyslog-victoria-logs.conf @@ -2,7 +2,7 @@ # RFC 5424 without the trailing newline, using the cleaned up fields set below template(name="victoria-logs" type="string" - string="<%PRI%>1 %TIMESTAMP:::date-rfc3339% %$.host% %$.app% %PROCID% %MSGID% %STRUCTURED-DATA% %$.msg%") + string="<%$.pri%>1 %TIMESTAMP:::date-rfc3339% %$.host% %$.app% %PROCID% %MSGID% %STRUCTURED-DATA% %$.msg%") ruleset(name="victoria-logs") { # rsyslog uses the FQDN only if DNS answered when it started @@ -12,8 +12,15 @@ ruleset(name="victoria-logs") { # rsyslog's own messages have no tag if $.app == "" or $.app == "-" then set $.app = "rsyslogd"; set $.msg = ltrim($msg); + set $.sev = $syslogseverity; + set $.drop = ""; - *.* action( + # per-application rules shipped by each package, they can change $.msg, $.sev and set $.drop + include(file="/etc/rsyslog.d/victoria-logs.d/*.conf" mode="optional") + + set $.pri = $syslogfacility * 8 + $.sev; + + if $.drop == "" then action( type="omfwd" target="127.0.0.1" port="5514" diff --git a/packages/victoria-logs/files/rsyslog-victoria-logs.d.conf b/packages/victoria-logs/files/rsyslog-victoria-logs.d.conf new file mode 100644 index 000000000..92180addf --- /dev/null +++ b/packages/victoria-logs/files/rsyslog-victoria-logs.d.conf @@ -0,0 +1,14 @@ +# victoria-logs writes everything to stderr: take the level from the message and drop its timestamp +if $.app == "victoria-logs" then { + if re_match($.msg, "^[0-9TZ:.-]+#011") then { + set $.lvl = re_extract($.msg, "^[^#]+#011([a-z]+)#011", 0, 1, ""); + set $.msg = replace(re_extract($.msg, "^[^#]+#011[a-z]+#011(.*)", 0, 1, $.msg), "#011", " "); + } else { + set $.lvl = tolower(re_extract($.msg, "^[0-9/]+ [0-9:]+ ([A-Z]+): ", 0, 1, "")); + set $.msg = re_extract($.msg, "^[0-9/]+ [0-9:]+ [A-Z]+: (.*)", 0, 1, $.msg); + } + if $.lvl == "fatal" or $.lvl == "panic" then set $.sev = 2; + if $.lvl == "error" then set $.sev = 3; + if $.lvl == "warn" then set $.sev = 4; + if $.lvl == "info" then set $.sev = 6; +} diff --git a/packages/victoria-metrics/Makefile b/packages/victoria-metrics/Makefile index 00319cac9..ab2d8c499 100644 --- a/packages/victoria-metrics/Makefile +++ b/packages/victoria-metrics/Makefile @@ -66,6 +66,8 @@ define Package/victoria-metrics/install $(INSTALL_DIR) $(1)/etc/config $(INSTALL_DATA) ./files/victoria-metrics.conf $(1)/etc/config/victoria-metrics $(INSTALL_DATA) ./files/vmalert.conf $(1)/etc/config/vmalert + $(INSTALL_DIR) $(1)/etc/rsyslog.d/victoria-logs.d + $(INSTALL_DATA) ./files/rsyslog-victoria-logs.conf $(1)/etc/rsyslog.d/victoria-logs.d/victoria-metrics.conf endef define Package/victoria-metrics/postinst diff --git a/packages/victoria-metrics/files/rsyslog-victoria-logs.conf b/packages/victoria-metrics/files/rsyslog-victoria-logs.conf new file mode 100644 index 000000000..14db6b2ef --- /dev/null +++ b/packages/victoria-metrics/files/rsyslog-victoria-logs.conf @@ -0,0 +1,14 @@ +# VictoriaMetrics tools write everything to stderr: take the level from the message and drop its timestamp +if $.app == "victoria-metrics" or $.app == "vmalert" then { + if re_match($.msg, "^[0-9TZ:.-]+#011") then { + set $.lvl = re_extract($.msg, "^[^#]+#011([a-z]+)#011", 0, 1, ""); + set $.msg = replace(re_extract($.msg, "^[^#]+#011[a-z]+#011(.*)", 0, 1, $.msg), "#011", " "); + } else { + set $.lvl = tolower(re_extract($.msg, "^[0-9/]+ [0-9:]+ ([A-Z]+): ", 0, 1, "")); + set $.msg = re_extract($.msg, "^[0-9/]+ [0-9:]+ [A-Z]+: (.*)", 0, 1, $.msg); + } + if $.lvl == "fatal" or $.lvl == "panic" then set $.sev = 2; + if $.lvl == "error" then set $.sev = 3; + if $.lvl == "warn" then set $.sev = 4; + if $.lvl == "info" then set $.sev = 6; +} From da1d6221005e1a8d52662bfba46b6400fc42823c Mon Sep 17 00:00:00 2001 From: Giacomo Sanchietti Date: Fri, 6 Nov 2026 17:13:15 +0100 Subject: [PATCH 22/51] feat(threat_shield): fail2ban brute force bans (#1977) --- AGENTS.md | 2 + config/ns-thread_shield.conf | 1 + files/etc/uci-defaults/99-nethsec-nginx | 4 +- packages/banip/Makefile | 5 +- packages/banip/files/README.md | 13 -- packages/banip/files/banip-functions.sh | 7 - packages/banip/files/banip.telegraf | 23 --- .../ns-api-server/files/src/methods/auth.go | 2 +- .../files/src/middleware/rate_limit.go | 3 +- .../files/src/middleware/rate_limit_test.go | 35 ++++ packages/ns-api/README.md | 86 +++++++-- packages/ns-api/files/ns.controller | 44 ++--- packages/ns-api/files/ns.dashboard | 29 ++- packages/ns-api/files/ns.report | 80 ++++---- packages/ns-api/files/ns.threatshield | 179 ++++++++---------- packages/ns-ha/Makefile | 1 + packages/ns-ha/README.md | 4 +- packages/ns-ha/files/810-fail2ban | 15 ++ packages/ns-storage/files/add-storage | 1 + packages/ns-storage/files/remove-storage | 9 + packages/ns-threat_shield/Makefile | 22 ++- packages/ns-threat_shield/README.md | 92 +++++++-- packages/ns-threat_shield/files/30-fail2ban | 17 ++ .../files/99-nethsec-fail2ban | 32 ++++ .../ns-threat_shield/files/adjust-fail2ban.py | 13 ++ .../ns-threat_shield/files/banip-defaults | 8 +- .../files/banip-insights-defaults | 6 +- .../files/fail2ban/action.d/ns-insights.conf | 12 ++ .../files/fail2ban/fail2ban.d/ns.local | 9 + .../files/fail2ban/filter.d/ns-openvpn.conf | 17 ++ .../fail2ban/filter.d/ns-proxy-auth.conf | 21 ++ .../fail2ban/filter.d/ns-proxy-scan.conf | 15 ++ .../files/fail2ban/filter.d/ns-ssh.conf | 19 ++ .../files/fail2ban/filter.d/ns-webui.conf | 15 ++ .../fail2ban/jail.d/10-ns-threat_shield.conf | 52 +++++ .../files/send-insights-blocklist | 144 -------------- packages/ns-threat_shield/files/ts-fail2ban | 128 +++++++++++++ .../files/ts-fail2ban-allowed.py | 50 +++++ .../ns-threat_shield/files/ts-insights-hook | 33 +++- packages/ns-threat_shield/files/ts-ip | 21 +- packages/ns-threat_shield/files/ts-ip.hook | 2 +- packages/ns-ui/Makefile | 2 + packages/ns-ui/files/ns-ui | 2 +- packages/ns-ui/files/ns-ui-log.conf | 10 + .../src/nethsec/inventory/__init__.py | 7 + .../python3-nethsec/tests/test_inventory.py | 11 ++ .../100-fail2ban-no-firewall-include.patch | 22 +++ .../packages/101-fail2ban-data-storage.patch | 17 ++ 48 files changed, 897 insertions(+), 445 deletions(-) delete mode 100644 packages/banip/files/banip.telegraf create mode 100644 packages/ns-ha/files/810-fail2ban create mode 100755 packages/ns-threat_shield/files/30-fail2ban create mode 100644 packages/ns-threat_shield/files/99-nethsec-fail2ban create mode 100755 packages/ns-threat_shield/files/adjust-fail2ban.py create mode 100644 packages/ns-threat_shield/files/fail2ban/action.d/ns-insights.conf create mode 100644 packages/ns-threat_shield/files/fail2ban/fail2ban.d/ns.local create mode 100644 packages/ns-threat_shield/files/fail2ban/filter.d/ns-openvpn.conf create mode 100644 packages/ns-threat_shield/files/fail2ban/filter.d/ns-proxy-auth.conf create mode 100644 packages/ns-threat_shield/files/fail2ban/filter.d/ns-proxy-scan.conf create mode 100644 packages/ns-threat_shield/files/fail2ban/filter.d/ns-ssh.conf create mode 100644 packages/ns-threat_shield/files/fail2ban/filter.d/ns-webui.conf create mode 100644 packages/ns-threat_shield/files/fail2ban/jail.d/10-ns-threat_shield.conf delete mode 100755 packages/ns-threat_shield/files/send-insights-blocklist create mode 100755 packages/ns-threat_shield/files/ts-fail2ban create mode 100755 packages/ns-threat_shield/files/ts-fail2ban-allowed.py create mode 100644 packages/ns-ui/files/ns-ui-log.conf create mode 100644 patches/feeds/packages/100-fail2ban-no-firewall-include.patch create mode 100644 patches/feeds/packages/101-fail2ban-data-storage.patch diff --git a/AGENTS.md b/AGENTS.md index d786d4468..321b0ef44 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -83,10 +83,12 @@ recent host Ruby (4.x), so the site is built in a `ruby:3.3` container and the - Set `CATEGORY:=NethSecurity` and `SECTION:=base` in Makefile. - Use `PKGARCH:=all` for architecture-independent packages (pure Python, shell scripts, etc.). - **Do not set `PKG_SOURCE_URL`** when package code lives in this repo. Set it only when fetching from external GitHub releases. +- Install wrappers and hooks that are not meant to be run by hand in `/usr/libexec`, not in `/usr/sbin` or `/usr/bin`. - To add a package to the image, create a corresponding `config/.conf` fragment that enables it at build time. - Renovate manages external package versions via magic comments in Makefiles: `# renovate: datasource=github-tags depName=Org/Repo` - `packages/netifyd` is download-only: prebuilt per-arch binaries, filenames and hashes in `netify-dist.mk`, regenerated by `tools/netifyd-update/netifyd-update.py`. No compile step. - `packages/python3-nethsec/` (the `nethsec` Python library used by all `ns.*` API scripts) is vendored in this repo, not fetched from an external project — read `packages/python3-nethsec/src/nethsec/` directly rather than looking it up on GitHub. +- fail2ban comes from upstream `net/fail2ban` in the pinned packages feed, patched to skip the fw3-era firewall include that restarts it on every firewall reload (`patches/feeds/packages/100-fail2ban-no-firewall-include.patch`) and to keep its DB on the data storage when mounted, else in `/var/run/fail2ban` (`patches/feeds/packages/101-fail2ban-data-storage.patch`); its jails, filters, `ns-insights` action, `ts-fail2ban` generator and `30-fail2ban` hotplug restart live in `ns-threat_shield`. --- diff --git a/config/ns-thread_shield.conf b/config/ns-thread_shield.conf index 69831401d..16c623b1d 100644 --- a/config/ns-thread_shield.conf +++ b/config/ns-thread_shield.conf @@ -1 +1,2 @@ CONFIG_PACKAGE_ns-threat_shield=y +CONFIG_PACKAGE_fail2ban=y diff --git a/files/etc/uci-defaults/99-nethsec-nginx b/files/etc/uci-defaults/99-nethsec-nginx index 6d8e99f92..353de86f6 100644 --- a/files/etc/uci-defaults/99-nethsec-nginx +++ b/files/etc/uci-defaults/99-nethsec-nginx @@ -1,6 +1,6 @@ -uci -q batch << EOI +uci -q batch << 'EOI' set nginx._lan.error_log=syslog:server=unix:/dev/log,nohostname -set nginx._lan.access_log=off +set nginx._lan.access_log='syslog:server=unix:/dev/log,nohostname combined if=$ns_ui_log' commit nginx EOI diff --git a/packages/banip/Makefile b/packages/banip/Makefile index c51ced040..78167a97c 100644 --- a/packages/banip/Makefile +++ b/packages/banip/Makefile @@ -16,7 +16,7 @@ define Package/banip SECTION:=net CATEGORY:=Network TITLE:=banIP blocks IPs via named nftables Sets - DEPENDS:=+jshn +jsonfilter +firewall4 +gawk +ca-bundle +rpcd +rpcd-mod-rpcsys +telegraf + DEPENDS:=+jshn +jsonfilter +firewall4 +gawk +ca-bundle +rpcd +rpcd-mod-rpcsys PKGARCH:=all endef @@ -69,9 +69,6 @@ define Package/banip/install $(INSTALL_DIR) $(1)/etc/uci-defaults $(INSTALL_BIN) ./files/95-banip-housekeeping $(1)/etc/uci-defaults - - $(INSTALL_DIR) $(1)/etc/telegraf.conf.d - $(INSTALL_DATA) ./files/banip.telegraf $(1)/etc/telegraf.conf.d/banip.conf endef $(eval $(call BuildPackage,banip)) diff --git a/packages/banip/files/README.md b/packages/banip/files/README.md index bbf5df08a..8109069b0 100644 --- a/packages/banip/files/README.md +++ b/packages/banip/files/README.md @@ -255,7 +255,6 @@ The `report` sub-command accepts an output mode: `text` (default, human-readable | ban_resolver | option | - | external resolver used for DNS lookups, by default the local resolver/forwarder will be used | | ban_remotelog | option | 0 | enable the cgi interface to receive remote logging events | | ban_remotetoken | option | - | unique token to communicate with the cgi interface | -| ban_blockhook | option | - | full path of an external script, called once for every IP newly blocked by the log service | ## Examples @@ -546,18 +545,6 @@ Examples to transfer remote logging events from an internal server to banIP via Please note: for security reasons use this cgi interface only internally and only encrypted via https transfer protocol. -**External hook for newly blocked IPs** -banIP can notify an external program whenever the log service adds a new IP to a blocklist Set (disabled by default). Set `ban_blockhook` to the full path of an executable script, e.g. `/usr/libexec/my-block-hook`. The hook is called once per newly blocked IP, right after the nftables element has been added, with four positional arguments: - -``` - $1: the blocked IP address, e.g. '198.51.100.44' - $2: the protocol family, either 'v4' or 'v6' - $3: the log count that triggered the block (ban_logcount) - $4: the Set expiry time (ban_nftexpiry), '0s' if the block is permanent -``` - -Please note: the hook runs synchronously inside the single-threaded log service, so it has to be fast and non-blocking - queue the event and process it elsewhere, never do network I/O in the hook itself. Its exit code and output are ignored. - **Download options** By default banIP uses the following pre-configured download options: diff --git a/packages/banip/files/banip-functions.sh b/packages/banip/files/banip-functions.sh index e4fdb45d6..e8b5b54bd 100755 --- a/packages/banip/files/banip-functions.sh +++ b/packages/banip/files/banip-functions.sh @@ -41,7 +41,6 @@ ban_mailprofile="ban_notify" ban_mailnotification="0" ban_remotelog="0" ban_remotetoken="" -ban_blockhook="" ban_nftloglevel="warn" ban_nftpriority="-100" ban_nftpolicy="memory" @@ -2836,12 +2835,6 @@ f_monitor() { fi block_cache="${block_cache} ${ip} " f_log "info" "add IP '${ip}' (cnt: ${ban_logcount}, expiry: ${ban_nftexpiry:-"0"}) to blocklist${proto} Set" - - # optional external hook, called once for every newly blocked IP - # - if [ -n "${ban_blockhook}" ] && [ -x "${ban_blockhook}" ]; then - "${ban_blockhook}" "${ip}" "${proto#.}" "${ban_logcount}" "${ban_nftexpiry:-0s}" >/dev/null 2>&1 - fi else f_log "info" "failed to add IP '${ip}' to blocklist${proto} Set with rc '${?}'" continue diff --git a/packages/banip/files/banip.telegraf b/packages/banip/files/banip.telegraf deleted file mode 100644 index 14eca7a4b..000000000 --- a/packages/banip/files/banip.telegraf +++ /dev/null @@ -1,23 +0,0 @@ -# banIP monitoring - -# blocked packets (nftables drop/reject) -[[inputs.tail]] - name_override = "banip" - files = ["/var/log/messages"] - initial_read_offset = "saved-or-end" - data_format = "grok" - grok_patterns = ['banIP/%{DATA:chain:tag}/%{WORD:verdict:tag}/%{DATA:feed:tag}: %{GREEDYDATA}SRC=%{IP:src:tag}%{GREEDYDATA}DST=%{IP:dst:tag}%{GREEDYDATA}LEN=%{NUMBER:blocked_bytes:int}'] - - [inputs.tail.tags] - influxdb_db = "os-metrics" - -# dynamically banned IPs (fail2ban-like "add IP") -[[inputs.tail]] - name_override = "banip" - files = ["/var/log/messages"] - initial_read_offset = "saved-or-end" - data_format = "grok" - grok_patterns = ["banIP%{DATA}\\[%{NUMBER:banned:int}\\]: add IP '%{IP:ip:tag}'"] - - [inputs.tail.tags] - influxdb_db = "os-metrics" diff --git a/packages/ns-api-server/files/src/methods/auth.go b/packages/ns-api-server/files/src/methods/auth.go index 73757112a..6814512f9 100644 --- a/packages/ns-api-server/files/src/methods/auth.go +++ b/packages/ns-api-server/files/src/methods/auth.go @@ -448,7 +448,7 @@ func ValidateAuth(tokenString string, ensureTokenExists bool) bool { }) if err != nil { - logs.Err("[JWT] error in JWT token validation: " + err.Error()) + logs.Err("[JWT] error in JWT token validation: " + utils.SanitizeForLog(err.Error())) return false } diff --git a/packages/ns-api-server/files/src/middleware/rate_limit.go b/packages/ns-api-server/files/src/middleware/rate_limit.go index 8fa4d4b19..38b263d8c 100644 --- a/packages/ns-api-server/files/src/middleware/rate_limit.go +++ b/packages/ns-api-server/files/src/middleware/rate_limit.go @@ -16,6 +16,7 @@ import ( "github.com/NethServer/nethsecurity-api/logs" "github.com/NethServer/nethsecurity-api/response" + "github.com/NethServer/nethsecurity-api/utils" ) // BodyLimit rejects requests whose body exceeds maxBytes before any downstream @@ -72,7 +73,7 @@ func RateLimiter(rps rate.Limit, burst int) gin.HandlerFunc { mu.Unlock() if !limiter.Allow() { - logs.Info("[AUTH] rate limit exceeded for " + ip + " on " + c.Request.URL.Path) + logs.Info("[AUTH] rate limit exceeded for " + ip + " on " + utils.SanitizeForLog(c.Request.URL.Path)) c.JSON(http.StatusTooManyRequests, structs.Map(response.StatusTooManyRequests{ Code: http.StatusTooManyRequests, Message: "too many requests", diff --git a/packages/ns-api-server/files/src/middleware/rate_limit_test.go b/packages/ns-api-server/files/src/middleware/rate_limit_test.go index 22000f767..97c773384 100644 --- a/packages/ns-api-server/files/src/middleware/rate_limit_test.go +++ b/packages/ns-api-server/files/src/middleware/rate_limit_test.go @@ -6,6 +6,7 @@ SPDX-License-Identifier: GPL-2.0-only package middleware import ( + "bytes" "io" "net/http" "net/http/httptest" @@ -15,6 +16,8 @@ import ( "github.com/gin-gonic/gin" "golang.org/x/time/rate" + + "github.com/NethServer/nethsecurity-api/logs" ) func TestBodyLimit(t *testing.T) { @@ -97,3 +100,35 @@ func TestRateLimiter(t *testing.T) { t.Fatalf("different IP: status = %d, want %d", w.Code, http.StatusOK) } } + +// TestRateLimiterLogInjection checks that a crafted path (an unknown route is +// enough) cannot forge an extra log line or put a victim IP on the logged line. +func TestRateLimiterLogInjection(t *testing.T) { + var buf bytes.Buffer + logs.Output = &buf + + gin.SetMode(gin.TestMode) + r := gin.New() + r.Use(RateLimiter(rate.Every(time.Minute), 1)) + + target := "/api/x%0D%0Aauthentication%20failed%20for%20user%20x%20from%208.8.8.8:%20exit%20status%20250" + for i := 0; i < 2; i++ { + req := httptest.NewRequest(http.MethodGet, target, nil) + req.RemoteAddr = "1.2.3.4:1111" + r.ServeHTTP(httptest.NewRecorder(), req) + } + + out := buf.String() + if strings.Count(out, "\n") != 1 || !strings.HasSuffix(out, "\n") { + t.Fatalf("expected exactly one log line, got %q", out) + } + if strings.ContainsAny(strings.TrimSuffix(out, "\n"), "\r\n") { + t.Fatalf("control chars in log line %q", out) + } + if strings.Contains(out, "8.8.8.8") { + t.Fatalf("victim IP leaked into log line %q", out) + } + if !strings.Contains(out, "rate limit exceeded for 1.2.3.4 ") { + t.Fatalf("client IP missing from log line %q", out) + } +} diff --git a/packages/ns-api/README.md b/packages/ns-api/README.md index 99e76e043..93a66f023 100644 --- a/packages/ns-api/README.md +++ b/packages/ns-api/README.md @@ -2553,7 +2553,7 @@ api-cli ns.dashboard counter --data '{"service": "hosts"}' Supported services are: - `hosts`: return the number of hosts as seen by ARP protocol -- `threat_shield_ip`: return the number of blocked IPs in the last hour +- `threat_shield_ip`: return the number of banIP blocks logged in Victoria Logs in the last hour - `openvpn_rw`: return the number of clients connected to `ns_roadwarrior1` instance Response example: @@ -6160,9 +6160,11 @@ api-cli ns.threatshield list-settings Response example: ```json -{"data": {"enabled": true}} +{"data": {"ban_icmplimit": 100, "ban_icmplimit_default": 25, "ban_loginbound": true, "ban_loglimit": true, "ban_logoutbound": true, "ban_logprerouting": true, "ban_nftexpiry": "30m", "ban_synlimit": 10, "ban_synlimit_default": 10, "ban_udplimit": 100, "ban_udplimit_default": 100, "enabled": true, "jails": [{"enabled": true, "name": "ns-ssh"}, {"enabled": true, "name": "ns-webui"}, {"enabled": false, "name": "ns-openvpn"}, {"enabled": false, "name": "ns-proxy-auth"}, {"enabled": false, "name": "ns-proxy-scan"}]}} ``` +`jails` lists the fail2ban brute-force jails and whether each one is enabled. + ### edit-settings Configure banip settings: @@ -6171,9 +6173,9 @@ Configure banip settings: - `ban_logprerouting`: Log suspicious packets in the prerouting chain (true or false). - `ban_loginbound`: Log suspicious packets in inbound traffic (WAN-input chain) (true or false). - `ban_logoutbound`: Log suspicious packets in outbound traffic (LAN-forward chain) (true or false). -- `ban_loglimit`: Enable or disable scanning of logfiles (true or false). -- `ban_logcount`: Specify how many times an IP must appear in the log to be considered suspicious (integer). -- `ban_logterm`: List of regex entries for logfile parsing (list of strings). +- `ban_loglimit`: Enable or disable fail2ban brute-force detection (true or false). +- `ban_logcount`: ignored, each fail2ban jail has its own threshold (optional). +- `jails`: fail2ban jails to enable when `ban_loglimit` is true: `ns-ssh`, `ns-webui`, `ns-openvpn`, `ns-proxy-auth`, `ns-proxy-scan` (list of strings, optional: unchanged when omitted). - `ban_icmplimit`: Enable or disable icmp DoS detection (true or false). - `ban_synlimit`: Enable or disable syn DoS detection (true or false). - `ban_udplimit`: Enable or disable udp DoS detection (true or false). @@ -6181,7 +6183,7 @@ Configure banip settings: ```bash -api-cli ns.threatshield edit-settings --data '{"enabled": true, "ban_logprerouting": true, "ban_loginbound": true, "ban_logoutbound": true, "ban_loglimit": false, "ban_logcount": 5, "ban_logterm": ["regex1", "regex2"], "ban_icmplimit": true, "ban_synlimit": true, "ban_udplimit": true, "ban_nftexpiry": "1d"}' +api-cli ns.threatshield edit-settings --data '{"enabled": true, "ban_logprerouting": true, "ban_loginbound": true, "ban_logoutbound": true, "ban_loglimit": true, "jails": ["ns-ssh", "ns-webui"], "ban_icmplimit": true, "ban_synlimit": true, "ban_udplimit": true, "ban_nftexpiry": "1d"}' ``` Response example: @@ -6221,6 +6223,8 @@ Response example: ### add-allowed +Allow list changes also apply to fail2ban: IP and CIDR entries are never banned, and banned ones are freed. + Add an address which is always allowed: ``` api-cli ns.threatshield add-allowed --data '{"address": "1.2.3.4", "description": "my allow1"}' @@ -6331,6 +6335,55 @@ Response example: It can raise the following validation errors: - `address_not_found` if the address is not inside the block list +### list-active-blocks + +List the IP addresses currently banned by fail2ban: +``` +api-cli ns.threatshield list-active-blocks +``` + +Response example: +```json +[{"ip": "198.51.100.9", "timeout": 1800, "expires": 1741, "jails": ["ns-ssh", "ns-webui"]}] +``` + +`timeout` is the ban duration and `expires` the remaining time, in seconds (`-1` for a permanent ban); `jails` lists the jails banning the IP. +The list is empty if fail2ban is not running. + +### list-recent-bans + +List the bans recorded by fail2ban, newest first: +``` +api-cli ns.threatshield list-recent-bans +``` + +Response example: +```json +[{"ip": "198.51.100.9", "jail": "ns-ssh", "time": 1762412310, "timeout": 600, "active": true, "failures": 3, "matches": [""]}] +``` + +`time` is the ban start (unix timestamp), `timeout` the ban duration in seconds (`-1` for a permanent ban), `active` tells if the ban is still in place, `failures` and `matches` are the failures and log lines that triggered the ban. +Bans are kept until fail2ban purges them (`dbpurgeage`, default 1 day); they survive reboot only when the data storage is mounted. + +### remove-active-block + +Unban an IP address from all fail2ban jails: +``` +api-cli ns.threatshield remove-active-block --data '{"ip": "198.51.100.9"}' +``` + +Response example: +```json +{"message": "success"} +``` + +It can raise the following validation errors: +- `required` if `ip` is missing +- `invalid` if `ip` is not a valid IP address or it is not currently banned + +It can raise the following errors: +- `remove_active_block_failed` if fail2ban fails to unban the IP + ### dns-list-blocklist List current dns blocklist: @@ -7424,11 +7477,10 @@ api-cli ns.controller dump-mwan-events } ``` -### dumpt-ts-attacks +### dump-ts-attacks Dump ThreatShield attacks to the controller as a time series. -An attack is an IP blocked due to a temporary ban (fail2ban behavior). -The function reads all data from last 20 minutes. If the firewall has been rebooted, try to read the whole log. +An attack is a new fail2ban ban, read from the fail2ban `Ban` log lines of the last 20 minutes stored in Victoria Logs; `jail` is the fail2ban jail. Returned JSON output can be sent to the controller. Output example: @@ -7437,11 +7489,13 @@ Output example: "data": [ { "timestamp": 1724230611, - "ip": "79.10.245.41" + "ip": "79.10.245.41", + "jail": "ns-ssh" }, { "timestamp": 1724230781, - "ip": "79.10.245.41" + "ip": "79.10.245.41", + "jail": "ns-webui" } ] } @@ -7450,8 +7504,7 @@ Output example: ### dump-ts-malware Dump ThreatShield malware to the controller as a time series. -A malware is an IP blocked due to a blocklist. -The function reads all data from last 20 minutes. If the firewall has been rebooted, try to read the whole log. +A malware is an IP blocked due to a blocklist, read from the banIP block log lines of the last 20 minutes stored in Victoria Logs; `category` is the blocklist feed. Output example: ```json @@ -8044,10 +8097,11 @@ Output example: ### tsip-attack-report -Report the number of blocked IPs by Threat Shield IP using the regexp over the log (like fail2ban). -Data are searched from the last 24 hours, inside `/var/log/messages` and `/var/log/messages.1.gz` so data can be incomplete -if the logs do not contain the full 24 hours. +Report the IPs banned by fail2ban (Threat Shield IP), counting the fail2ban `Ban` log lines stored in Victoria Logs: +one line per new ban (`Restore Ban` after a restart is not counted). +Data cover the current day, from local midnight to now; `attack_by_hour` uses the local hour. Result is cached for 15 minutes. +If Victoria Logs cannot be queried, it returns `{"error": "metrics_query_failed"}` and the error is not cached. Usage example: ``` api-cli ns.report tsip-attack-report diff --git a/packages/ns-api/files/ns.controller b/packages/ns-api/files/ns.controller index c9f3f7534..80adcce5a 100755 --- a/packages/ns-api/files/ns.controller +++ b/packages/ns-api/files/ns.controller @@ -28,23 +28,26 @@ AUTHORIZED_KEYS = "/etc/dropbear/authorized_keys" dns_cache = {} try: - _vm_addr = EUci().get("victoria-metrics", "main", "http_listen_addr", default="127.0.0.1:8428") + _vl_addr = EUci().get("victoria-logs", "main", "http_listen_addr", default="127.0.0.1:9428") except Exception: - _vm_addr = "127.0.0.1:8428" -VM_URL = f"http://{_vm_addr}" - -def vm_export(metric, start, end): - params = urllib.parse.urlencode({"match[]": metric, "start": start, "end": end}) - series = [] + _vl_addr = "127.0.0.1:9428" +VL_URL = f"http://{_vl_addr}" +FAIL2BAN_BAN_QUERY = 'app_name:"fail2ban.actions" "] Ban " | extract "[] Ban " | math floor(_time / 1e9) as ts | fields ts, jail, ip' +# prerouting lines have no feed and are skipped +BANIP_BLOCK_QUERY = 'app_name:kernel "banIP/" | extract "banIP///: " | filter feed:* | extract " SRC= " | extract " DST= " | math floor(_time / 1e9) as ts | fields ts, chain, feed, src, dst' + +def vl_query(query, start, end): + data = urllib.parse.urlencode({"query": query, "start": start, "end": end}).encode() + rows = [] try: - with urllib.request.urlopen(f"{VM_URL}/api/v1/export?{params}", timeout=10) as resp: + with urllib.request.urlopen(f"{VL_URL}/select/logsql/query", data=data, timeout=10) as resp: for line in resp.read().decode().splitlines(): line = line.strip() if line: - series.append(json.loads(line)) + rows.append(json.loads(line)) except Exception: pass - return series + return rows # Utility functions @@ -205,15 +208,8 @@ def dump_ts_malware(): ret = [] end = int(time.time()) start = end - 1200 # last 20 minutes - for serie in vm_export("banip_blocked_bytes", start, end): - labels = serie.get("metric", {}) - src = labels.get("src", "") - dst = labels.get("dst", "") - category = labels.get("feed", "") - chain = labels.get("chain", "") - for ts in serie.get("timestamps", []): - # VM timestamps are in milliseconds - ret.append({"timestamp": int(ts) // 1000, "src": src, "dst": dst, "category": category, "chain": chain}) + for row in vl_query(BANIP_BLOCK_QUERY, start, end): + ret.append({"timestamp": int(row["ts"]), "src": row.get("src", ""), "dst": row.get("dst", ""), "category": row["feed"], "chain": row.get("chain", "")}) return {"data": ret} @@ -221,13 +217,9 @@ def dump_ts_attacks(): ret = [] end = int(time.time()) start = end - 1200 # last 20 minutes - for serie in vm_export("banip_banned", start, end): - ip = serie.get("metric", {}).get("ip", "") - if not ip: - continue - for ts in serie.get("timestamps", []): - # VM timestamps are in milliseconds - ret.append({"timestamp": int(ts) // 1000, "ip": ip}) + for ban in vl_query(FAIL2BAN_BAN_QUERY, start, end): + if ban.get("ip"): + ret.append({"timestamp": int(ban["ts"]), "ip": ban["ip"], "jail": ban.get("jail", "")}) return {"data": ret} def dump_mwan_events(): diff --git a/packages/ns-api/files/ns.dashboard b/packages/ns-api/files/ns.dashboard index 5b15ca332..4a55a5a2f 100644 --- a/packages/ns-api/files/ns.dashboard +++ b/packages/ns-api/files/ns.dashboard @@ -20,12 +20,16 @@ from glob import glob from euci import EUci from nethsec import utils, ovpn -# VictoriaMetrics HTTP API base URL +# VictoriaMetrics and VictoriaLogs HTTP API base URLs try: - _vm_addr = EUci().get("victoria-metrics", "main", "http_listen_addr", default="127.0.0.1:8428") + _uci = EUci() + _vm_addr = _uci.get("victoria-metrics", "main", "http_listen_addr", default="127.0.0.1:8428") + _vl_addr = _uci.get("victoria-logs", "main", "http_listen_addr", default="127.0.0.1:9428") except Exception: _vm_addr = "127.0.0.1:8428" + _vl_addr = "127.0.0.1:9428" VM_URL = f"http://{_vm_addr}" +VL_URL = f"http://{_vl_addr}" def get_uptime(): with open('/proc/uptime', 'r') as f: @@ -141,23 +145,14 @@ def count_openvpn_rw(): return len(ovpn.list_connected_clients('ns_roadwarrior1').keys()) def count_threat_shield_ip(): - ret = 0 - - def vm_query(expr): - params = urllib.parse.urlencode({"query": expr}) - with urllib.request.urlopen(f"{VM_URL}/api/v1/query?{params}", timeout=5) as resp: - data = json.loads(resp.read()) - result = data.get("data", {}).get("result", []) - return result[0].get("value", []) if result else [] - + # banIP blocks logged in the last hour, prerouting lines have no feed + query = 'app_name:kernel "banIP/" | extract "banIP///: " | filter feed:* | stats count() blocked' + data = urllib.parse.urlencode({"query": query, "start": "1h"}).encode() try: - value = vm_query("sum(count_over_time(banip_blocked_bytes[1h]))") - if value: - ret = int(float(value[1])) + with urllib.request.urlopen(f"{VL_URL}/select/logsql/query", data=data, timeout=5) as resp: + return int(json.loads(resp.read()).get("blocked", 0)) except Exception: - pass - - return ret + return 0 def check_ts_dns(): u = EUci() diff --git a/packages/ns-api/files/ns.report b/packages/ns-api/files/ns.report index c6add322c..1b235e901 100755 --- a/packages/ns-api/files/ns.report +++ b/packages/ns-api/files/ns.report @@ -19,12 +19,17 @@ import urllib.parse import urllib.request from euci import EUci -# VictoriaMetrics HTTP API base URL +# VictoriaMetrics and VictoriaLogs HTTP API base URLs try: - _vm_addr = EUci().get("victoria-metrics", "main", "http_listen_addr", default="127.0.0.1:8428") + _uci = EUci() + _vm_addr = _uci.get("victoria-metrics", "main", "http_listen_addr", default="127.0.0.1:8428") + _vl_addr = _uci.get("victoria-logs", "main", "http_listen_addr", default="127.0.0.1:9428") except Exception: _vm_addr = "127.0.0.1:8428" + _vl_addr = "127.0.0.1:9428" VM_URL = f"http://{_vm_addr}" +VL_URL = f"http://{_vl_addr}" +FAIL2BAN_BAN_QUERY = 'app_name:"fail2ban.actions" "] Ban " | extract "[] Ban " | math floor(_time / 1e9) as ts | fields ts, jail, ip' ## Utility functions @@ -45,6 +50,16 @@ def get_cached_report(report_name, cache_timeout=900): return json.load(f) return None +def fail2ban_bans(start, end): + data = urllib.parse.urlencode({"query": FAIL2BAN_BAN_QUERY, "start": start, "end": end}).encode() + bans = [] + with urllib.request.urlopen(f"{VL_URL}/select/logsql/query", data=data, timeout=10) as resp: + for line in resp.read().decode().splitlines(): + line = line.strip() + if line: + bans.append(json.loads(line)) + return bans + def get_ovpnrw_db_path(instance): u = EUci() base_path = u.get('fstab', 'ns_data', 'target', default='') @@ -55,51 +70,29 @@ def get_ovpnrw_db_path(instance): ## API def tsip_attack_report(): - file_paths = ['/var/log/messages.1.gz', '/var/log/messages'] - search_terms = 'banIP.*add IP' - - # Get the current date in the format '%b %e ' (e.g., 'Aug 8 ') - date_str = datetime.now().strftime('%b %e ').rstrip() - # Regex pattern to extract IP addresses - ip_pattern = re.compile(r'\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b') - # Regex pattern to extract hour from timestamp - hour_pattern = re.compile(r'(\d{2}):(\d{2}):(\d{2})') + now = datetime.now() + start = int(now.replace(hour=0, minute=0, second=0, microsecond=0).timestamp()) + try: + bans = fail2ban_bans(start, int(now.timestamp())) + except Exception as e: + print(f"Error querying Victoria Logs: {e}", file=sys.stderr) + return utils.generic_error("metrics_query_failed") - ip_count = defaultdict(int) + ip_count = defaultdict(int) hourly_count = [0] * 24 first_seen = 0 - - for file_path in file_paths: - if file_path.endswith('.gz'): - command = f'zcat {file_path} | grep "{date_str}" | grep "{search_terms}"' - else: - command = f'grep "{date_str}" {file_path} | grep "{search_terms}"' - - process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) - for line in process.stdout: - line = line.decode('utf-8') - # Find all IP addresses in the line - ips = ip_pattern.findall(line) - - # Extract the hour from the timestamp - hour_match = hour_pattern.search(line) - if hour_match: - hour = int(hour_match.group(1)) - hourly_count[hour] += 1 - - # Extract full date and time of the first matching line and convert it to timestamp - if not first_seen: - # Example line: 'Aug 8 00:00:01', but add current year - first_seen = datetime.strptime(f"{datetime.now().year} {line[:15]}", '%Y %b %d %H:%M:%S').timestamp() - - for ip in ips: - ip_count[ip] += 1 - - process.stdout.close() - process.wait() + for ban in bans: + ip = ban.get("ip", "") + if not ip: + continue + ts = int(ban["ts"]) + hourly_count[datetime.fromtimestamp(ts).hour] += 1 + ip_count[ip] += 1 + if not first_seen or ts < first_seen: + first_seen = ts return { - "first_seen": int(first_seen), + "first_seen": first_seen, "attack_count": sum(ip_count.values()), "attack_by_ip": sorted(ip_count.items(), key=lambda item: item[1], reverse=True), "attack_by_hour": format_hourly_data(hourly_count), @@ -439,7 +432,8 @@ elif cmd == 'call': ret = get_cached_report('tsip-attack-report', 900) if ret is None: ret = tsip_attack_report() - save_cached_report('tsip-attack-report', ret) + if 'error' not in ret: + save_cached_report('tsip-attack-report', ret) elif action == "ovpnrw-list-days": data = json.loads(sys.stdin.read()) ret = ovpnrw_list_days(data.get('instance')) diff --git a/packages/ns-api/files/ns.threatshield b/packages/ns-api/files/ns.threatshield index 716613c17..e1dce350d 100644 --- a/packages/ns-api/files/ns.threatshield +++ b/packages/ns-api/files/ns.threatshield @@ -12,15 +12,18 @@ import json import urllib import urllib.request import urllib.error -import logging import ipaddress from euci import EUci from nethsec.utils import ValidationError, validation_error, generic_error from nethsec import utils, firewall import base64 import time +import sqlite3 import subprocess +# NethSecurity jail list, hard-coded in packages/ns-api/files/ns.threatshield and packages/ns-threat_shield/files/{ts-fail2ban,99-nethsec-fail2ban,banip-defaults,fail2ban/jail.d/10-ns-threat_shield.conf}: keep them in sync +JAILS = ['ns-ssh', 'ns-webui', 'ns-openvpn', 'ns-proxy-auth', 'ns-proxy-scan'] + ## continent codes map continent_table = { @@ -343,6 +346,9 @@ def write_allow_list(allow_list, file='/etc/banip/banip.allowlist'): f.write(' #' + x['description']) f.write('\n') subprocess.run(["/etc/init.d/banip", "reload"], capture_output=True) + if file == '/etc/banip/banip.allowlist': + # sync fail2ban ignoreip with the allowlist and unban allowlisted IPs + subprocess.run(["/usr/libexec/ts-fail2ban"], capture_output=True) def dns_get_local_list(e_uci, list_type): values = e_uci.get('adblock', 'ns_lists', list_type, list=True, default=[]) @@ -487,6 +493,7 @@ def list_settings(e_uci): ban_icmplimit_default = 25 ban_synlimit_default = 10 ban_udplimit_default = 100 + ns_jails = e_uci.get('banip', 'global', 'ns_jails', list=True, default=[]) return { 'data': { 'enabled': e_uci.get('banip', 'global', 'ban_enabled') == '1', @@ -494,8 +501,7 @@ def list_settings(e_uci): 'ban_loginbound': e_uci.get('banip', 'global', 'ban_loginbound', default=False) == '1', 'ban_logoutbound': e_uci.get('banip', 'global', 'ban_logoutbound', default=False) == '1', 'ban_loglimit': True if int(e_uci.get('banip', 'global', 'ban_loglimit', default=100)) > 0 else False, - 'ban_logcount': e_uci.get('banip', 'global', 'ban_logcount', default=1), - 'ban_logterm': e_uci.get('banip', 'global', 'ban_logterm', list=True, default=[]), + 'jails': [{'name': j, 'enabled': j in ns_jails} for j in JAILS], 'ban_icmplimit': e_uci.get('banip', 'global', 'ban_icmplimit', default=ban_icmplimit_default, dtype=int), 'ban_synlimit': e_uci.get('banip', 'global', 'ban_synlimit', default=ban_synlimit_default, dtype=int), 'ban_udplimit': e_uci.get('banip', 'global', 'ban_udplimit', default=ban_udplimit_default, dtype=int), @@ -566,14 +572,13 @@ def edit_settings(e_uci, payload): raise ValidationError('ban_loglimit', 'invalid', payload['ban_loglimit']) if payload['ban_loglimit']: - if 'ban_logcount' not in payload: - raise ValidationError('ban_logcount', 'required') - if not isinstance(payload['ban_logcount'], int): - raise ValidationError('ban_logcount', 'invalid', payload['ban_logcount']) - if 'ban_logterm' not in payload: - raise ValidationError('ban_logterm', 'required') - if not isinstance(payload['ban_logterm'], list): - raise ValidationError('ban_logterm', 'invalid', payload['ban_logterm']) + # jails is optional: when omitted, ns_jails is left unchanged + if 'jails' in payload: + if not isinstance(payload['jails'], list): + raise ValidationError('jails', 'invalid', payload['jails']) + for item in payload['jails']: + if item not in JAILS: + raise ValidationError('jails', 'invalid', item) if 'ban_nftexpiry' not in payload: raise ValidationError('ban_nftexpiry', 'required') if not isinstance(payload['ban_nftexpiry'], str): @@ -602,10 +607,14 @@ def edit_settings(e_uci, payload): e_uci.set('banip', 'global', 'ban_udplimit', max(0, payload['ban_udplimit'])) else: e_uci.set('banip', 'global', 'ban_udplimit', 100 if payload['ban_udplimit'] else 0) + try: + e_uci.delete('banip', 'global', 'ban_logterm') + except: + pass if payload['ban_loglimit']: - e_uci.set('banip', 'global', 'ban_logcount', payload['ban_logcount']) - e_uci.set('banip', 'global', 'ban_logterm', payload['ban_logterm']) + if 'jails' in payload: + e_uci.set('banip', 'global', 'ns_jails', payload['jails']) e_uci.set('banip', 'global', 'ban_nftexpiry', payload['ban_nftexpiry']) else: e_uci.set('banip', 'global', 'ban_enabled', '0') @@ -889,87 +898,34 @@ def dns_delete_bypass(e_uci, payload): return {'message': 'success'} -def __parse_expression(expression): - if isinstance(expression, str) or isinstance(expression, int): - return ipaddress.ip_address(expression) - if isinstance(expression, list): - return [__parse_expression(item) for item in expression] - if isinstance(expression, dict): - if "prefix" in expression: - return ipaddress.ip_network(expression["prefix"]["addr"] + "/" + str(expression["prefix"]["len"])) - elif "range" in expression: - return list(ipaddress.summarize_address_range( - __parse_expression(expression["range"][0]), - __parse_expression(expression["range"][1]) - )) - elif "elem" in expression: - if "timeout" not in expression["elem"] or "expires" not in expression["elem"]: - return None - return { - "timeout": expression["elem"]["timeout"], - "expires": expression["elem"]["expires"], - "val": __parse_expression(expression["elem"]["val"]), - } - - logging.warning('Unsupported expression type: {}'.format(type(expression))) - return None - - -def __parse_set(blocklist): - """ - This function parses any set returned by nftables and returns a list of entries - """ - blocked_ips = [] - if ("nftables" in blocklist - and len(blocklist["nftables"]) > 1 - and "set" in blocklist["nftables"][1] - and "elem" in blocklist["nftables"][1]["set"]): - blocked_ips = [ip for ip in __parse_expression(blocklist["nftables"][1]["set"]["elem"]) if ip is not None] - - return blocked_ips +def fail2ban_db(): + # same choice as the fail2ban init script + if os.path.ismount('/mnt/data'): + return '/mnt/data/fail2ban/fail2ban.sqlite3' + return '/var/run/fail2ban/fail2ban.sqlite3' def list_active_blocks(): + # expired bans and bans of stopped jails stay in bips, so filter them out + now = int(time.time()) try: - output_ipv4 = subprocess.run(["nft", "-j", "list", "set", "inet", "banIP", "blocklist.v4"], check=True, - capture_output=True, text=True) - data = json.loads(output_ipv4.stdout) - except subprocess.CalledProcessError: - data = {} - - blocks = __parse_set(data) - - try: - output_ipv6 = subprocess.run(["nft", "-j", "list", "set", "inet", "banIP", "blocklist.v6"], check=True, - capture_output=True, text=True) - data = json.loads(output_ipv6.stdout) - except subprocess.CalledProcessError: - data = {} - - blocks = blocks + __parse_set(data) - blocks = filter(lambda x: isinstance(x, dict) and "val" in x, blocks) - blocks = sorted(blocks, key=lambda x: x["timeout"] - x["expires"]) - response = [] - for block in blocks: - if not isinstance(block["val"], list): - block["val"] = [block["val"]] - for item in block["val"]: - if isinstance(item, ipaddress.IPv4Address) or isinstance(item, ipaddress.IPv6Address): - response.append({ - "ip": str(item), - "timeout": block["timeout"], - "expires": block["expires"], - }) - if isinstance(item, ipaddress.IPv4Network) or isinstance(item, ipaddress.IPv6Network): - for addr in item: - if isinstance(addr, ipaddress.IPv4Address) or isinstance(addr, ipaddress.IPv6Address): - response.append({ - "ip": str(addr), - "timeout": block["timeout"], - "expires": block["expires"], - }) - - return response + db = sqlite3.connect(f'file:{fail2ban_db()}?mode=ro', uri=True) + try: + rows = db.execute( + "SELECT ip, bantime, timeofban + bantime - ?, bips.jail FROM bips JOIN jails ON jails.name = bips.jail " + "WHERE jails.enabled = 1 AND (bantime < 0 OR timeofban + bantime > ?) " + "ORDER BY bantime < 0, timeofban + bantime", (now, now)).fetchall() + finally: + db.close() + except sqlite3.Error: + return [] + # rows are sorted by expiry: the last one per IP is the longest (-1 is permanent) + jails = {} + for ip, _, _, jail in rows: + jails.setdefault(ip, set()).add(jail) + blocks = {ip: {"ip": ip, "timeout": bantime, "expires": -1 if bantime < 0 else left, "jails": sorted(jails[ip])} + for ip, bantime, left, _ in rows} + return sorted(blocks.values(), key=lambda x: x["timeout"] - x["expires"]) def remove_active_block(): @@ -987,19 +943,42 @@ def remove_active_block(): if not found: return validation_error("ip", "invalid", str(ip)) - if isinstance(ip, ipaddress.IPv4Address): - blocklist = "blocklist.v4" - else: - blocklist = "blocklist.v6" - try: - subprocess.run(["nft", "delete", "element", "inet", "banIP", blocklist, "{" + str(ip) + "}"], check=True) - except subprocess.CalledProcessError: + subprocess.run(["fail2ban-client", "unban", str(ip)], capture_output=True, check=True, timeout=30) + except (OSError, subprocess.SubprocessError): return generic_error("remove_active_block_failed") return {'message': 'success'} +def list_recent_bans(): + now = int(time.time()) + try: + db = sqlite3.connect(f'file:{fail2ban_db()}?mode=ro', uri=True) + try: + rows = db.execute( + "SELECT ip, bips.jail, timeofban, bantime, " + "jails.enabled = 1 AND (bantime < 0 OR timeofban + bantime > ?), data " + "FROM bips LEFT JOIN jails ON jails.name = bips.jail ORDER BY timeofban DESC", (now,)).fetchall() + finally: + db.close() + except sqlite3.Error: + return [] + bans = [] + for ip, jail, timeofban, bantime, active, data in rows: + try: + data = json.loads(data) + except (TypeError, ValueError): + data = {} + if not isinstance(data, dict): + data = {} + # fail2ban stores multi-line matches as lists of strings + matches = [''.join(m) if isinstance(m, list) else m for m in data.get('matches') or []] + bans.append({"ip": ip, "jail": jail, "time": int(timeofban), "timeout": int(bantime), "active": bool(active), + "failures": data.get('failures', 0), "matches": matches}) + return bans + + def is_ip_blocked(): data = json.loads(sys.stdin.read()) if "ip" not in data or data["ip"] == "": @@ -1088,8 +1067,7 @@ if cmd == 'list': 'ban_loginbound': True, 'ban_logoutbound': True, 'ban_loglimit': True, - 'ban_logcount': 3, - 'ban_logterm': ['string'], + 'jails': ['ns-ssh'], 'ban_icmplimit': True, 'ban_synlimit': True, 'ban_udplimit': True @@ -1103,6 +1081,7 @@ if cmd == 'list': 'edit-blocked': {'address': '1.2.3.4', 'description': 'optional'}, 'delete-blocked': {'address': '1.2.3.4'}, 'list-active-blocks': {}, + 'list-recent-bans': {}, 'remove-active-block': { 'ip': '' }, 'is-ip-blocked': {'ip': ''}, 'dns-list-blocklist': {}, @@ -1162,6 +1141,8 @@ elif cmd == 'call': ret = delete_blocked(payload) elif action == 'list-active-blocks': ret = list_active_blocks() + elif action == 'list-recent-bans': + ret = list_recent_bans() elif action == 'remove-active-block': ret = remove_active_block() elif action == 'is-ip-blocked': diff --git a/packages/ns-ha/Makefile b/packages/ns-ha/Makefile index c4ec21e81..15dda14f6 100644 --- a/packages/ns-ha/Makefile +++ b/packages/ns-ha/Makefile @@ -73,6 +73,7 @@ define Package/ns-ha/install $(INSTALL_DATA) ./files/700-nginx $(1)/etc/hotplug.d/keepalived $(INSTALL_DATA) ./files/800-adblock $(1)/etc/hotplug.d/keepalived $(INSTALL_DATA) ./files/800-banip $(1)/etc/hotplug.d/keepalived + $(INSTALL_DATA) ./files/810-fail2ban $(1)/etc/hotplug.d/keepalived $(INSTALL_DATA) ./files/800-netifyd $(1)/etc/hotplug.d/keepalived $(INSTALL_DATA) ./files/800-flashstart $(1)/etc/hotplug.d/keepalived $(INSTALL_DATA) ./files/800-ui $(1)/etc/hotplug.d/keepalived diff --git a/packages/ns-ha/README.md b/packages/ns-ha/README.md index 9b87024d9..574bb03c4 100644 --- a/packages/ns-ha/README.md +++ b/packages/ns-ha/README.md @@ -42,7 +42,7 @@ The following features are supported: - Multi-WAN (mwan3) - DPI rules - Netifyd informatics configuration -- Threat shield IP (banip) +- Threat shield IP (banip, fail2ban) - Threat shield DNS (adblock) - Reverse proxy (nginx) - ACME certificates @@ -638,7 +638,7 @@ The backup node maintains synchronized configuration but keeps most services dis **Disabled services on backup:** - DHCP and DNS server (dnsmasq) -- Threat shield (banip, adblock) +- Threat shield (banip, fail2ban, adblock) - OpenVPN server and tunnels - MAC binding - Multi-WAN (mwan3) diff --git a/packages/ns-ha/files/810-fail2ban b/packages/ns-ha/files/810-fail2ban new file mode 100644 index 000000000..63fe58b21 --- /dev/null +++ b/packages/ns-ha/files/810-fail2ban @@ -0,0 +1,15 @@ +#!/bin/sh +# +# Copyright (C) 2026 Nethesis S.r.l. +# SPDX-License-Identifier: GPL-2.0-only +# + +. /lib/functions/keepalived/hotplug.sh + +set_service_name fail2ban + +# start fail2ban on master only when ts-fail2ban enabled it +/etc/init.d/fail2ban enabled && set_restart_if_master +set_stop_if_backup + +keepalived_hotplug diff --git a/packages/ns-storage/files/add-storage b/packages/ns-storage/files/add-storage index 87a14ecb8..8fdfe0a36 100755 --- a/packages/ns-storage/files/add-storage +++ b/packages/ns-storage/files/add-storage @@ -47,4 +47,5 @@ crontab -l | grep -q '/usr/sbin/sync-data' || echo '40 1 * * * /usr/sbin/sync-da # Restart services that will use the storage /etc/init.d/dnsmasq restart /etc/init.d/victoria-metrics restart +/etc/init.d/fail2ban running && /etc/init.d/fail2ban restart /etc/init.d/victoria-logs restart 2>/dev/null || : diff --git a/packages/ns-storage/files/remove-storage b/packages/ns-storage/files/remove-storage index de6a91f14..dc3ee243c 100644 --- a/packages/ns-storage/files/remove-storage +++ b/packages/ns-storage/files/remove-storage @@ -27,6 +27,12 @@ uci commit fstab /etc/init.d/dnsmasq stop /etc/init.d/victoria-metrics stop /etc/init.d/victoria-logs stop 2>/dev/null || : +# fail2ban is stopped on purpose on HA backup nodes, restart it only if it was running +fail2ban_running='' +if /etc/init.d/fail2ban running 2>/dev/null; then + fail2ban_running=1 + /etc/init.d/fail2ban stop +fi # Sync and wait for the disk to be free sync && sleep 5 @@ -57,3 +63,6 @@ fi /etc/init.d/dnsmasq start /etc/init.d/victoria-metrics start /etc/init.d/victoria-logs start 2>/dev/null || : +if [ -n "$fail2ban_running" ]; then + /etc/init.d/fail2ban start +fi diff --git a/packages/ns-threat_shield/Makefile b/packages/ns-threat_shield/Makefile index a98f86223..548388c38 100644 --- a/packages/ns-threat_shield/Makefile +++ b/packages/ns-threat_shield/Makefile @@ -22,7 +22,7 @@ define Package/ns-threat_shield CATEGORY:=NethSecurity TITLE:=Threat shield block list URL:=https://github.com/NethServer/nethsecurity/ - DEPENDS:=+wget-ssl +adblock +jq +ns-api + DEPENDS:=+wget-ssl +adblock +jq +ns-api +fail2ban +curl EXTRA_DEPENDS:=adblock (>=4.5.3), ns-api (>=3.6.2) PKGARCH:=all endef @@ -46,7 +46,8 @@ define Package/ns-threat_shield/install $(INSTALL_DIR) $(1)/usr/libexec $(INSTALL_BIN) ./files/ts-dns $(1)/usr/sbin/ts-dns $(INSTALL_BIN) ./files/ts-ip $(1)/usr/sbin/ts-ip - $(INSTALL_BIN) ./files/send-insights-blocklist $(1)/usr/sbin/send-insights-blocklist + $(INSTALL_BIN) ./files/ts-fail2ban $(1)/usr/libexec/ts-fail2ban + $(INSTALL_BIN) ./files/ts-fail2ban-allowed.py $(1)/usr/libexec/ts-fail2ban-allowed $(INSTALL_BIN) ./files/ts-insights-hook $(1)/usr/libexec/ts-insights-hook $(INSTALL_BIN) ./files/20_threat_shield $(1)/etc/uci-defaults $(INSTALL_BIN) ./files/ts-dns.hook $(1)/usr/share/ns-plug/hooks/register/90ts-dns @@ -58,16 +59,32 @@ define Package/ns-threat_shield/install $(INSTALL_DATA) ./files/community-dns.sources $(1)/usr/share/threat_shield $(INSTALL_DATA) ./files/banip.nethesis.feeds $(1)/etc/banip $(INSTALL_BIN) ./files/adjust-banip.py $(1)/usr/libexec/ns-api/post-commit/ + $(INSTALL_BIN) ./files/adjust-fail2ban.py $(1)/usr/libexec/ns-api/post-commit/ $(INSTALL_BIN) ./files/configure-banip-wans.py $(1)/usr/libexec/ns-api/pre-commit/ $(INSTALL_BIN) ./files/configure-adblock-devices.py $(1)/usr/libexec/ns-api/pre-commit/ $(INSTALL_BIN) ./files/adblock-devices-migrate.py $(1)/usr/libexec/ts-dns-migrate-devices $(INSTALL_DIR) $(1)/etc/uci-defaults $(INSTALL_BIN) ./files/banip-defaults $(1)/etc/uci-defaults/99-nethsec-banip + $(INSTALL_BIN) ./files/99-nethsec-fail2ban $(1)/etc/uci-defaults/99-nethsec-fail2ban $(INSTALL_BIN) ./files/banip-extra-defaults $(1)/etc/uci-defaults/96-nethsec-banip-extra $(INSTALL_BIN) ./files/97-nethsec-banip-feeds $(1)/etc/uci-defaults/97-nethsec-banip-feeds $(INSTALL_BIN) ./files/banip-insights-defaults $(1)/etc/uci-defaults/98-nethsec-banip-insights $(INSTALL_BIN) ./files/35_ns-threat_shield $(1)/etc/uci-defaults/35_ns-threat_shield $(INSTALL_BIN) ./files/96_ns-threat_shield $(1)/etc/uci-defaults/96_ns-threat_shield + $(INSTALL_DIR) $(1)/etc/fail2ban/action.d + $(INSTALL_DIR) $(1)/etc/fail2ban/fail2ban.d + $(INSTALL_DIR) $(1)/etc/fail2ban/filter.d + $(INSTALL_DIR) $(1)/etc/fail2ban/jail.d + $(INSTALL_DATA) ./files/fail2ban/action.d/ns-insights.conf $(1)/etc/fail2ban/action.d/ + $(INSTALL_DATA) ./files/fail2ban/fail2ban.d/ns.local $(1)/etc/fail2ban/fail2ban.d/ + $(INSTALL_DATA) ./files/fail2ban/filter.d/ns-openvpn.conf $(1)/etc/fail2ban/filter.d/ + $(INSTALL_DATA) ./files/fail2ban/filter.d/ns-proxy-auth.conf $(1)/etc/fail2ban/filter.d/ + $(INSTALL_DATA) ./files/fail2ban/filter.d/ns-proxy-scan.conf $(1)/etc/fail2ban/filter.d/ + $(INSTALL_DATA) ./files/fail2ban/filter.d/ns-ssh.conf $(1)/etc/fail2ban/filter.d/ + $(INSTALL_DATA) ./files/fail2ban/filter.d/ns-webui.conf $(1)/etc/fail2ban/filter.d/ + $(INSTALL_DATA) ./files/fail2ban/jail.d/10-ns-threat_shield.conf $(1)/etc/fail2ban/jail.d/ + $(INSTALL_DIR) $(1)/etc/hotplug.d/block + $(INSTALL_BIN) ./files/30-fail2ban $(1)/etc/hotplug.d/block/ gzip -9n $(1)/usr/share/threat_shield/nethesis-dns.sources gzip -9n $(1)/usr/share/threat_shield/community-dns.sources endef @@ -87,7 +104,6 @@ define Package/ns-threat_shield/prerm if [ -z "$${IPKG_INSTROOT}" ]; then crontab -l | grep -v "/etc/init.d/banip reload" | sort | uniq | crontab - crontab -l | grep -v "/etc/init.d/adblock" | sort | uniq | crontab - - crontab -l | grep -v "/usr/sbin/send-insights-blocklist" | sort | uniq | crontab - fi exit 0 endef diff --git a/packages/ns-threat_shield/README.md b/packages/ns-threat_shield/README.md index 2fe48b9a4..5ab5fa987 100644 --- a/packages/ns-threat_shield/README.md +++ b/packages/ns-threat_shield/README.md @@ -27,6 +27,10 @@ After machine registration, above categories will be automatically added to exis A special global allowlist will also be added to banip (`ban_allowurl` option). +Blocks are counted from the banIP kernel log lines in Victoria Logs, not from metrics, as `ns.dashboard counter` and +`ns.controller dump-ts-malware` do; blocks per feed in the last hour: +`app_name:kernel "banIP/" | extract "banIP///: " | filter feed:* | stats by (feed) count() blocked` + ### Examples #### Start the service @@ -51,7 +55,7 @@ ts-ip ### Nethesis Insights On registered machines `ts-ip` joins the [Nethesis Insights](https://github.com/nethesis/nethesis-insights) -threat shield: IPs blocked by the banip log service are reported to the Insights server, and IPs reported by +threat shield: IPs banned by [fail2ban](#fail2ban) are reported to the Insights server, and IPs reported by several firewalls can be blocked locally with the `nethesisinsightslvl2` feed. Authentication uses the subscription `system_id` and `secret`. @@ -63,17 +67,81 @@ Authentication uses the subscription `system_id` and `secret`. Reporting: -- `ts-ip` sets `banip.global.ban_blockhook` to `/usr/libexec/ts-insights-hook`, which appends every blocked IP - to `/var/run/ns-insights/threat-events.jsonl` -- banip supports a single block hook: when `ban_blockhook` already points to a custom script, `ts-ip` leaves it - untouched, Insights reporting stays disabled and a `threat_shield` message is logged to `/var/log/messages`; - on unregistration `ts-ip` removes only its own hook -- `/usr/sbin/send-insights-blocklist` sends the public IPs to `POST /blocklist/v1/events`, in batches of 500; - the full endpoint URL can be overridden with `ns-plug.config.insights_blocklist_url` - (default `https://insights.nethesis.it/blocklist/v1/events`); - `ts-ip` adds its 5-minute cron job on registration and removes it, along with the spool, on unregistration -- fire and forget: events that fail to send are dropped -- only failed pushes are logged to `/var/log/messages`; set `banip.global.ban_debug` to `1` to log every push +- each new fail2ban ban is reported in background; a report that fails is dropped and logged to `/var/log/messages` + (tag `threat_shield`) +- only public addresses are reported: private, CGNAT, link-local, loopback and other non-global IPv4/IPv6 addresses are skipped +- the endpoint URL can be overridden with `ns-plug.config.insights_blocklist_url` + (default `https://insights.nethesis.it/blocklist/v1/events`) +- to stop reporting or to log every report see `ns_insights_report` and `ban_debug` in [fail2ban](#fail2ban) + +## fail2ban + +Brute force detection for `ts-ip` is done by the upstream +[fail2ban](https://github.com/openwrt/packages/tree/openwrt-25.12/net/fail2ban) package: it reads `/var/log/messages` +and bans offending IPs in the nftables table `inet f2b-table`. + +| jail | detects | bans after | +|---|---|---| +| `ns-ssh` | SSH login failures and disconnects before login | 3 in 10m | +| `ns-webui` | web UI and API login failures | 8 in 1h | +| `ns-openvpn` | road warrior authentication and TLS handshake failures | 6 in 10m | +| `ns-proxy-auth` | reverse proxy 403 and Basic auth 401 responses | 6 in 10m | +| `ns-proxy-scan` | reverse proxy and web UI 404 responses, static files excluded | 20 in 2m | + +Never banned: loopback, the static networks of non-WAN interfaces (not DHCP or delegated IPv6 prefixes), the banIP allowlist +(its IP and CIDR entries and its nft sets, downloaded `ban_allowurl` feeds included) and the firewall's own addresses. + +### UCI options + +Options of `banip.global`, applied on `ns.commit` (from the command line run `/usr/libexec/ts-fail2ban`): + +| option | effect | +|---|---| +| `ban_enabled` | `1`: run fail2ban if at least one jail is enabled | +| `ban_loglimit` | `> 0`: enable the jails listed in `ns_jails` | +| `ns_jails` | jails to enable, all five on a fresh install | +| `ban_nftexpiry` | ban duration, e.g. `30m`, `1h`, `3d` (default `30m`) | +| `ns_insights_report` | `0`: do not report bans to [Nethesis Insights](#nethesis-insights), bans still apply | +| `ban_debug` | `1`: log every Insights report | + +### Bans + +Check status: +``` +fail2ban-client status +fail2ban-client status ns-webui +nft list table inet f2b-table +``` + +Unban an IP: +``` +fail2ban-client unban 203.0.113.7 +``` + +- bans are lost on reboot +- bans survive firewall reloads: fw4 never touches `inet f2b-table`, so the upstream firewall include that restarts fail2ban is not installed (`patches/feeds/packages/100-fail2ban-no-firewall-include.patch`) +- fail2ban logs to `/var/log/messages` at `NOTICE` level: bans, unbans and errors only, not every failed attempt +- bans are counted from the `Ban` lines in Victoria Logs, not from metrics, as `ns.controller dump-ts-attacks` and `ns.report tsip-attack-report` do; bans per jail: + `app_name:"fail2ban.actions" "] Ban " | extract "[] Ban " | stats by (jail) count() bans` +- a ban drops all traffic from the IP, also replies to connections opened by the firewall or LAN hosts +- adding a banned IP to the local allowlist frees it (downloaded allowlists only prevent new bans), but the ban can come back if the IP leaves the allowlist before the ban expires +- `ns-proxy-auth` does not cover the web UI and the path rules on the `_lan` server: their access log has only 404 responses +- `ns-proxy-auth` counts 401 responses only for Basic auth + +### Custom jails + +Add the jail in `/etc/fail2ban/jail.d/` and its filter in `/etc/fail2ban/filter.d/`; do not edit +`90-ns-threat_shield.local`, it is generated. Custom jails default to `maxretry = 3` and `findtime = 10m`, +and run only while at least one NethSecurity jail is enabled. +Example `/etc/fail2ban/jail.d/50-custom.local`: +``` +[custom-app] +enabled = true +filter = custom-app +action = %(ns_banaction)s + ns-insights[scenario=custom/app-bruteforce] +``` +Without `action` the jail bans the same way but does not report to Insights. Apply with `fail2ban-client reload`. ## ts-dns diff --git a/packages/ns-threat_shield/files/30-fail2ban b/packages/ns-threat_shield/files/30-fail2ban new file mode 100755 index 000000000..dafe6fe62 --- /dev/null +++ b/packages/ns-threat_shield/files/30-fail2ban @@ -0,0 +1,17 @@ +#!/bin/sh +# +# Copyright (C) 2026 Nethesis S.r.l. +# SPDX-License-Identifier: GPL-2.0-only +# +# Triggered by hotplug when a block device is added, after 10-mount. +# If the data storage got mounted after boot, restart to move the ban database onto it. + +[ "$ACTION" = "add" ] || exit 0 +[ "$DEVTYPE" = "partition" ] || exit 0 + +target=$(uci -q get fstab.ns_data.target) +[ -n "$target" ] || exit 0 +grep -q "^/dev/$DEVNAME $target " /proc/mounts || exit 0 + +/etc/init.d/fail2ban running && /etc/init.d/fail2ban restart +exit 0 diff --git a/packages/ns-threat_shield/files/99-nethsec-fail2ban b/packages/ns-threat_shield/files/99-nethsec-fail2ban new file mode 100644 index 000000000..d70ccc883 --- /dev/null +++ b/packages/ns-threat_shield/files/99-nethsec-fail2ban @@ -0,0 +1,32 @@ +#!/bin/sh + +# +# Copyright (C) 2026 Nethesis S.r.l. +# SPDX-License-Identifier: GPL-2.0-only +# + +# Move the banIP log monitor settings to the fail2ban jails on upgrade + +# fail2ban reports each ban directly: drop the Insights queue sender cron job +crontab -l 2>/dev/null | grep -v /usr/sbin/send-insights-blocklist | crontab - + +# ban_logterm is set only before the migration: an empty ns_jails is a valid admin choice +if [ -n "$(uci -q get banip.global.ban_logterm)" ] && [ -z "$(uci -q get banip.global.ns_jails)" ]; then + # banIP log patterns are not migrated: the fail2ban jails replace them + uci -q delete banip.global.ban_logterm + # the banIP block hook never fires without the log monitor, fail2ban reports to Insights + if [ "$(uci -q get banip.global.ban_blockhook)" = "/usr/libexec/ts-insights-hook" ]; then + uci -q delete banip.global.ban_blockhook + fi + # NethSecurity jail list, hard-coded in packages/ns-api/files/ns.threatshield and packages/ns-threat_shield/files/{ts-fail2ban,99-nethsec-fail2ban,banip-defaults,fail2ban/jail.d/10-ns-threat_shield.conf}: keep them in sync + for jail in ns-ssh ns-webui ns-openvpn ns-proxy-auth ns-proxy-scan; do + uci add_list banip.global.ns_jails="$jail" + done + uci commit banip + /etc/init.d/banip running && /etc/init.d/banip restart +fi + +# rsyslog is not running yet: the boot sequence starts fail2ban later +/usr/libexec/ts-fail2ban --no-start + +exit 0 diff --git a/packages/ns-threat_shield/files/adjust-fail2ban.py b/packages/ns-threat_shield/files/adjust-fail2ban.py new file mode 100755 index 000000000..41b6d9525 --- /dev/null +++ b/packages/ns-threat_shield/files/adjust-fail2ban.py @@ -0,0 +1,13 @@ +#!/usr/bin/python3 +# +# Copyright (C) 2026 Nethesis S.r.l. +# SPDX-License-Identifier: GPL-2.0-only +# + +# Regenerate fail2ban jails and ignore list when related configurations change + +import subprocess + +# `changes` is injected by ns.commit when the hook is exec'd +if changes.keys() & {"banip", "network", "firewall"}: # noqa: F821 + subprocess.run(["/usr/libexec/ts-fail2ban"]) diff --git a/packages/ns-threat_shield/files/banip-defaults b/packages/ns-threat_shield/files/banip-defaults index 52af4f6ae..26bdafed5 100644 --- a/packages/ns-threat_shield/files/banip-defaults +++ b/packages/ns-threat_shield/files/banip-defaults @@ -1,5 +1,6 @@ [ "$(uci -q get banip.global.ban_loginbound)" != "" ] && exit 0 +# NethSecurity jail list, hard-coded in packages/ns-api/files/ns.threatshield and packages/ns-threat_shield/files/{ts-fail2ban,99-nethsec-fail2ban,banip-defaults,fail2ban/jail.d/10-ns-threat_shield.conf}: keep them in sync uci -q batch << EOI set banip.global.ban_loginbound="1" set banip.global.ban_logoutbound="1" @@ -10,8 +11,11 @@ set banip.global.ban_logcount="3" set banip.global.ban_nftexpiry="30m" delete banip.global.ban_logterm -add_list banip.global.ban_logterm="Exit before auth from" -add_list banip.global.ban_logterm="authentication failed for user" +add_list banip.global.ns_jails="ns-ssh" +add_list banip.global.ns_jails="ns-webui" +add_list banip.global.ns_jails="ns-openvpn" +add_list banip.global.ns_jails="ns-proxy-auth" +add_list banip.global.ns_jails="ns-proxy-scan" set banip.global.ban_icmplimit="100" set banip.global.ban_synlimit="10" diff --git a/packages/ns-threat_shield/files/banip-insights-defaults b/packages/ns-threat_shield/files/banip-insights-defaults index 7cd946daa..20331dc65 100755 --- a/packages/ns-threat_shield/files/banip-insights-defaults +++ b/packages/ns-threat_shield/files/banip-insights-defaults @@ -5,10 +5,10 @@ # SPDX-License-Identifier: GPL-2.0-only # -# Registered units: run ts-ip after an update to add the Insights hook and feed definition. -# ts-ip preserves a custom block hook, so it runs unless the Insights hook is already set. +# Registered units: run ts-ip after an update to add the Insights feed definition, +# unless it is already set. [ -n "$(uci -q get ns-plug.config.secret)" ] || exit 0 -[ "$(uci -q get banip.global.ban_blockhook)" = "/usr/libexec/ts-insights-hook" ] && exit 0 +grep -q nethesisinsightslvl2 /etc/banip/banip.custom.feeds 2>/dev/null && exit 0 /usr/sbin/ts-ip diff --git a/packages/ns-threat_shield/files/fail2ban/action.d/ns-insights.conf b/packages/ns-threat_shield/files/fail2ban/action.d/ns-insights.conf new file mode 100644 index 000000000..cedcb5e04 --- /dev/null +++ b/packages/ns-threat_shield/files/fail2ban/action.d/ns-insights.conf @@ -0,0 +1,12 @@ +# +# Copyright (C) 2026 Nethesis S.r.l. +# SPDX-License-Identifier: GPL-2.0-only +# + +# Report a ban to Nethesis Insights +[Definition] +norestored = 1 +actionban = /usr/libexec/ts-insights-hook >/dev/null 2>&1 & + +[Init] +scenario = nethsecurity/fail2ban diff --git a/packages/ns-threat_shield/files/fail2ban/fail2ban.d/ns.local b/packages/ns-threat_shield/files/fail2ban/fail2ban.d/ns.local new file mode 100644 index 000000000..21acdf2b5 --- /dev/null +++ b/packages/ns-threat_shield/files/fail2ban/fail2ban.d/ns.local @@ -0,0 +1,9 @@ +# +# Copyright (C) 2026 Nethesis S.r.l. +# SPDX-License-Identifier: GPL-2.0-only +# + +[Definition] +logtarget = SYSLOG +# NOTICE drops the per-attempt "Found" and start/stop lines, keeps bans, unbans and errors +loglevel = NOTICE diff --git a/packages/ns-threat_shield/files/fail2ban/filter.d/ns-openvpn.conf b/packages/ns-threat_shield/files/fail2ban/filter.d/ns-openvpn.conf new file mode 100644 index 000000000..4083e37c1 --- /dev/null +++ b/packages/ns-threat_shield/files/fail2ban/filter.d/ns-openvpn.conf @@ -0,0 +1,17 @@ +# +# Copyright (C) 2026 Nethesis S.r.l. +# SPDX-License-Identifier: GPL-2.0-only +# + +# Sample: Oct 28 15:44:37 NethSec openvpn(ns_roadwarrior1)[4808]: udp4:192.168.122.1:42475 TLS Auth Error: Auth Username/Password verification failed for peer +# Sample: Oct 28 15:44:45 NethSec openvpn(ns_roadwarrior1)[4808]: udp4:192.168.122.1:58337 TLS Error: TLS handshake failed + +[INCLUDES] +before = common.conf + +[Definition] +_daemon = openvpn\(ns_roadwarrior\d+\) +# spoofed sources cannot trigger "TLS handshake failed": OpenVPN >= 2.6 answers the first reset statelessly +# VERIFY ERROR is not matched: it is always followed by "TLS handshake failed" +failregex = ^%(__prefix_line)s(?:(?:udp|tcp)\d?(?:-server)?:)?:\d+ TLS (?:Auth Error: Auth Username/Password verification failed for peer|Error: TLS handshake failed)$ +ignoreregex = diff --git a/packages/ns-threat_shield/files/fail2ban/filter.d/ns-proxy-auth.conf b/packages/ns-threat_shield/files/fail2ban/filter.d/ns-proxy-auth.conf new file mode 100644 index 000000000..39cfbb76b --- /dev/null +++ b/packages/ns-threat_shield/files/fail2ban/filter.d/ns-proxy-auth.conf @@ -0,0 +1,21 @@ +# +# Copyright (C) 2026 Nethesis S.r.l. +# SPDX-License-Identifier: GPL-2.0-only +# + +# Sample: Oct 30 07:26:32 NethSec nethsec nginx: 203.0.113.7 - bob [30/Oct/2026:07:26:32 +0000] "GET /api/system HTTP/1.1" 401 50 "-" "curl/8.19.0" +# Sample: Oct 30 07:26:32 NethSec nethsec nginx: 203.0.113.7 - - [30/Oct/2026:07:26:32 +0000] "GET /admin HTTP/1.1" 403 153 "-" "curl/8.19.0" + +[INCLUDES] +before = common.conf + +[Definition] +_daemon = nginx +# syslog host, optional nginx host, tag, then the client address of the combined access log +_prefix = ^\s*\S+ (?:[^\s:]+ )?%(_daemon)s: - +# time and "$request": nginx escapes " in every field, so the first quoted string is the request +_request = \[[^\]"]+\] "[^"]*" +# 401 counts only with a Basic auth user ($remote_user not "-"): other auth schemes are not counted +failregex = %(_prefix)s [^"]+ %(_request)s 403\b + %(_prefix)s (?!- %(_request)s)[^"]+ %(_request)s 401\b +ignoreregex = diff --git a/packages/ns-threat_shield/files/fail2ban/filter.d/ns-proxy-scan.conf b/packages/ns-threat_shield/files/fail2ban/filter.d/ns-proxy-scan.conf new file mode 100644 index 000000000..309875e45 --- /dev/null +++ b/packages/ns-threat_shield/files/fail2ban/filter.d/ns-proxy-scan.conf @@ -0,0 +1,15 @@ +# +# Copyright (C) 2026 Nethesis S.r.l. +# SPDX-License-Identifier: GPL-2.0-only +# + +# Sample: Oct 30 07:26:32 NethSec nethsec nginx: 203.0.113.7 - - [30/Oct/2026:07:26:32 +0000] "GET /.env HTTP/1.1" 404 50 "-" "curl/8.19.0" +# Sample: Oct 30 07:26:32 NethSec nethsec nginx: 203.0.113.7 - bob [30/Oct/2026:07:26:32 +0000] "GET /nonexistent/x HTTP/1.1" 404 50 "-" "curl/8.19.0" + +[INCLUDES] +before = ns-proxy-auth.conf + +[Definition] +failregex = %(_prefix)s [^"]+ %(_request)s 404\b +# missing static files are not scans, like CrowdSec http-probing +ignoreregex = "[A-Z]+ [^" ?]+\.(?:ico|png|jpe?g|gif|svg|webp|css|js|map|woff2?|ttf|eot|otf)(?:\?[^" ]*)? HTTP/ diff --git a/packages/ns-threat_shield/files/fail2ban/filter.d/ns-ssh.conf b/packages/ns-threat_shield/files/fail2ban/filter.d/ns-ssh.conf new file mode 100644 index 000000000..ebb2da05f --- /dev/null +++ b/packages/ns-threat_shield/files/fail2ban/filter.d/ns-ssh.conf @@ -0,0 +1,19 @@ +# +# Copyright (C) 2026 Nethesis S.r.l. +# SPDX-License-Identifier: GPL-2.0-only +# + +# Sample: Oct 25 00:08:44 fw dropbear[27326]: Login attempt for nonexistent user from 203.0.113.7:60416 +# Sample: Oct 17 04:13:29 fw dropbear[8198]: Bad password attempt for 'root' from 203.0.113.7:50008 +# Sample: Oct 15 11:24:31 fw dropbear[8251]: Exit before auth from <203.0.113.7:52980>: (user 'root', 1 fails): Exited normally +# Sample: Oct 28 17:21:20 fw dropbear[24160]: Exit before auth from <203.0.113.7:51234>: Exited normally +# Sample: Oct 27 14:12:00 fw dropbear[23840]: Exit before auth from <203.0.113.7:47336>: Timeout before auth + +[INCLUDES] +before = dropbear.conf + +[Definition] +# upstream dropbear patterns, plus exits before auth, except after failed passwords that upstream already counts +failregex = %(known/failregex)s + ^[Ee]xit before auth from \<:\d+\>: (?!\(user '[^']*', [1-9]\d* fails\)).+$ +ignoreregex = diff --git a/packages/ns-threat_shield/files/fail2ban/filter.d/ns-webui.conf b/packages/ns-threat_shield/files/fail2ban/filter.d/ns-webui.conf new file mode 100644 index 000000000..c5898205c --- /dev/null +++ b/packages/ns-threat_shield/files/fail2ban/filter.d/ns-webui.conf @@ -0,0 +1,15 @@ +# +# Copyright (C) 2026 Nethesis S.r.l. +# SPDX-License-Identifier: GPL-2.0-only +# + +# Sample: Nov 4 18:15:49 NethSec nethsecurity-api[6042]: [AUTH] authentication failed for user root from 192.168.100.1: exit status 250 +# Sample: Nov 4 18:16:02 NethSec nethsecurity-api[6042]: [AUTH] authentication failed for user nobody from 192.168.122.1: exit status 250 + +[INCLUDES] +before = common.conf + +[Definition] +_daemon = nethsecurity-api +failregex = ^%(__prefix_line)s\[AUTH\] authentication failed for user \S+ from : exit status \d+$ +ignoreregex = diff --git a/packages/ns-threat_shield/files/fail2ban/jail.d/10-ns-threat_shield.conf b/packages/ns-threat_shield/files/fail2ban/jail.d/10-ns-threat_shield.conf new file mode 100644 index 000000000..6f7ad8ba3 --- /dev/null +++ b/packages/ns-threat_shield/files/fail2ban/jail.d/10-ns-threat_shield.conf @@ -0,0 +1,52 @@ +# +# Copyright (C) 2026 Nethesis S.r.l. +# SPDX-License-Identifier: GPL-2.0-only +# + +[DEFAULT] +# fallback for custom jails, the ns-* jails set their own thresholds +maxretry = 3 +findtime = 10m +logpath = /var/log/messages +backend = polling +# match IP addresses only, never resolve host names from log lines +usedns = no +# also ignore the banIP allowlist sets, downloaded feeds included +ignorecommand = /usr/libexec/ts-fail2ban-allowed +ignorecache = key="", max-count=1000, max-time=5m +# drop all protocols in prerouting: covers the firewall and forwarded traffic, LAN is in ignoreip +ns_banaction = nftables[type=custom, blocktype=drop, chain_hook=prerouting] +banaction = %(ns_banaction)s +banaction_allports = %(ns_banaction)s + +[ns-ssh] +maxretry = 3 +filter = ns-ssh +action = %(ns_banaction)s + ns-insights[scenario=nethsecurity/ssh-bruteforce] + +[ns-webui] +maxretry = 8 +findtime = 1h +filter = ns-webui +action = %(ns_banaction)s + ns-insights[scenario=nethsecurity/webui-bruteforce] + +[ns-openvpn] +maxretry = 6 +filter = ns-openvpn +action = %(ns_banaction)s + ns-insights[scenario=nethsecurity/openvpn-bruteforce] + +[ns-proxy-auth] +maxretry = 6 +filter = ns-proxy-auth +action = %(ns_banaction)s + ns-insights[scenario=nethsecurity/http-auth-bruteforce] + +[ns-proxy-scan] +maxretry = 20 +findtime = 2m +filter = ns-proxy-scan +action = %(ns_banaction)s + ns-insights[scenario=nethsecurity/http-scan] diff --git a/packages/ns-threat_shield/files/send-insights-blocklist b/packages/ns-threat_shield/files/send-insights-blocklist deleted file mode 100755 index 79dbacde2..000000000 --- a/packages/ns-threat_shield/files/send-insights-blocklist +++ /dev/null @@ -1,144 +0,0 @@ -#!/usr/bin/python3 -# -# Copyright (C) 2026 Nethesis S.r.l. -# SPDX-License-Identifier: GPL-2.0-only -# - -# Send the IPs blocked by banip, spooled by ts-insights-hook, to Nethesis Insights. -# Run by cron, does nothing if the unit is not registered. -# Only the errors dropping events are logged, unless banip.global.ban_debug is set. - -import base64 -import http.client -import ipaddress -import json -import os -import syslog -import urllib.request - -from euci import EUci - -SPOOL_DIR = "/var/run/ns-insights" -SPOOL = os.path.join(SPOOL_DIR, "threat-events.jsonl") -SENDING = SPOOL + ".sending" - -DEFAULT_URL = "https://insights.nethesis.it/blocklist/v1/events" -MAX_DECISIONS_PER_REQUEST = 500 -MAX_SPOOLED_EVENTS = 5000 -TIMEOUT = 20 - - -def read_config(uci): - """Return (url, system_id, secret), or None if the unit is not registered.""" - system_id = uci.get("ns-plug", "config", "system_id", default="") - secret = uci.get("ns-plug", "config", "secret", default="") - if not system_id or not secret: - return None - - url = uci.get("ns-plug", "config", "insights_blocklist_url", default=DEFAULT_URL) - - return url, system_id, secret - - -def read_spool(): - """Take the spooled lines and remove the spool file.""" - if not os.path.exists(SPOOL): - return [] - - # move the file first, so the hook can keep writing a new one - os.rename(SPOOL, SENDING) - with open(SENDING) as spool: - lines = spool.readlines() - os.unlink(SENDING) - - return lines - - -def is_reportable(value): - """Only public addresses are sent.""" - try: - return ipaddress.ip_address(value).is_global - except ValueError: - return False - - -def parse_events(lines): - """Return the valid and reportable decisions, the most recent ones if over the cap.""" - decisions = [] - - for line in lines: - line = line.strip() - if not line: - continue - try: - decision = json.loads(line) - value = decision["value"] - except (ValueError, KeyError, TypeError): - continue - - if is_reportable(value): - decisions.append(decision) - - if len(decisions) > MAX_SPOOLED_EVENTS: - syslog.syslog( - syslog.LOG_DEBUG, - f"too many events, dropped the {len(decisions) - MAX_SPOOLED_EVENTS} oldest", - ) - decisions = decisions[-MAX_SPOOLED_EVENTS:] - - return decisions - - -def send_batch(config, decisions): - """Post a batch of decisions, any 2xx response means they are queued.""" - url, system_id, secret = config - payload = json.dumps( - {"schema_version": 1, "system_id": system_id, "decisions": decisions} - ).encode() - credentials = base64.b64encode(f"{system_id}:{secret}".encode()).decode() - request = urllib.request.Request( - url, - data=payload, - method="POST", - headers={ - "Content-Type": "application/json", - "Authorization": f"Basic {credentials}", - }, - ) - - with urllib.request.urlopen(request, timeout=TIMEOUT) as response: - response.read() - - -def main(): - syslog.openlog("send-insights-blocklist") - - uci = EUci() - debug = uci.get("banip", "global", "ban_debug", default="0") == "1" - syslog.setlogmask(syslog.LOG_UPTO(syslog.LOG_DEBUG if debug else syslog.LOG_ERR)) - - config = read_config(uci) - if config is None: - return - - decisions = parse_events(read_spool()) - sent = 0 - for index in range(0, len(decisions), MAX_DECISIONS_PER_REQUEST): - batch = decisions[index : index + MAX_DECISIONS_PER_REQUEST] - try: - send_batch(config, batch) - except (http.client.HTTPException, OSError) as error: - syslog.syslog( - syslog.LOG_ERR, - f"push failed, dropped {len(decisions) - index} events: {error}", - ) - break - - sent += len(batch) - - if sent: - syslog.syslog(syslog.LOG_DEBUG, f"pushed {sent} events") - - -if __name__ == "__main__": - main() diff --git a/packages/ns-threat_shield/files/ts-fail2ban b/packages/ns-threat_shield/files/ts-fail2ban new file mode 100755 index 000000000..d13e41198 --- /dev/null +++ b/packages/ns-threat_shield/files/ts-fail2ban @@ -0,0 +1,128 @@ +#!/usr/bin/python3 +# +# Copyright (C) 2026 Nethesis S.r.l. +# SPDX-License-Identifier: GPL-2.0-only +# + +# Generate the fail2ban jail overrides from banip UCI options, then start or stop fail2ban + +import ipaddress +import json +import os +import re +import subprocess +import sys + +from euci import EUci +from nethsec import utils + +JAIL_FILE = "/etc/fail2ban/jail.d/90-ns-threat_shield.local" +ALLOWLIST = "/etc/banip/banip.allowlist" +# NethSecurity jail list, hard-coded in packages/ns-api/files/ns.threatshield and packages/ns-threat_shield/files/{ts-fail2ban,99-nethsec-fail2ban,banip-defaults,fail2ban/jail.d/10-ns-threat_shield.conf}: keep them in sync +BRUTE_FORCE_JAILS = [ + "ns-ssh", + "ns-webui", + "ns-openvpn", + "ns-proxy-auth", + "ns-proxy-scan", +] + + +def allowlist(): + allowed = [] + try: + with open(ALLOWLIST) as f: + for line in f: + value = (line.split() or [""])[0] + # skip scope ids (fe80::1%eth0): fail2ban interpolates % in its config + if "%" in value: + continue + # comments, MAC addresses and empty lines raise ValueError + try: + allowed.append(str(ipaddress.ip_network(value, strict=False))) + except ValueError: + pass + except FileNotFoundError: + pass + return allowed + + +def ignore_list(uci): + # static LAN addresses only, ignoreself covers the firewall own addresses + wan = [] + for section, zone in utils.get_all_by_type(uci, "firewall", "zone").items(): + if zone.get("name") == "wan": + wan += uci.get("firewall", section, "network", list=True, default=()) + networks = [] + for iface in utils.get_all_by_type(uci, "network", "interface"): + if iface in wan: + continue + addresses = list(uci.get("network", iface, "ip6addr", list=True, default=())) + netmask = uci.get("network", iface, "netmask", default="") + for ipaddr in uci.get("network", iface, "ipaddr", list=True, default=()): + addresses.append(f"{ipaddr}/{netmask}" if netmask else ipaddr) + for address in addresses: + try: + networks.append(str(ipaddress.ip_interface(address).network)) + except ValueError: + pass + # dict keeps the order and drops duplicates + return list(dict.fromkeys(["127.0.0.0/8", "::1"] + networks + allowlist())) + + +def is_ha_backup(): + # same keepalived state check as ns-ha-enable, non-HA units report "unknown" + status = subprocess.run( + ["/usr/libexec/rpcd/ns.ha", "call", "status"], capture_output=True + ) + try: + return json.loads(status.stdout).get("state") == "backup" + except ValueError: + return False + + +def main(): + uci = EUci() + loglimit = uci.get("banip", "global", "ban_loglimit", dtype=int, default=100) > 0 + jails = uci.get("banip", "global", "ns_jails", list=True, default=()) + enabled = {jail: loglimit and jail in jails for jail in BRUTE_FORCE_JAILS} + + if uci.get("banip", "global", "ban_enabled", default="0") != "1" or not any( + enabled.values() + ): + subprocess.run(["/etc/init.d/fail2ban", "disable"]) + subprocess.run(["/etc/init.d/fail2ban", "stop"]) + return + + ignoreip = ignore_list(uci) + # fail2ban reads the same time format as banIP (e.g. 30m, 1h, 3d) + bantime = uci.get("banip", "global", "ban_nftexpiry", default="") + if not re.fullmatch(r"\d+[smhdw]", bantime): + bantime = "30m" + lines = ["[DEFAULT]", f"ignoreip = {' '.join(ignoreip)}", f"bantime = {bantime}"] + for jail, value in enabled.items(): + lines += ["", f"[{jail}]", f"enabled = {'true' if value else 'false'}"] + content = "\n".join(lines) + "\n" + try: + with open(JAIL_FILE) as f: + changed = f.read() != content + except FileNotFoundError: + changed = True + if changed: + # atomic write: the callers can run concurrently + tmp = f"{JAIL_FILE}.{os.getpid()}" + with open(tmp, "w") as f: + f.write(content) + os.replace(tmp, JAIL_FILE) + + # restart only on changes, start is a no-op when already running + subprocess.run(["/etc/init.d/fail2ban", "enable"]) + if "--no-start" in sys.argv: + return + # on the HA backup ns-ha 810-fail2ban starts it when the node becomes master + if not is_ha_backup(): + subprocess.run(["/etc/init.d/fail2ban", "restart" if changed else "start"]) + + +if __name__ == "__main__": + main() diff --git a/packages/ns-threat_shield/files/ts-fail2ban-allowed.py b/packages/ns-threat_shield/files/ts-fail2ban-allowed.py new file mode 100755 index 000000000..779a60fb0 --- /dev/null +++ b/packages/ns-threat_shield/files/ts-fail2ban-allowed.py @@ -0,0 +1,50 @@ +#!/usr/bin/python3 +# +# Copyright (C) 2026 Nethesis S.r.l. +# SPDX-License-Identifier: GPL-2.0-only +# + +# fail2ban ignorecommand: exit 0 if the IP is in a banIP allowlist set, 1 otherwise + +import ipaddress +import json +import subprocess +import sys + + +def allowed(ip): + # list only this set: "nft get element" would load every set, blocklists included + result = subprocess.run( + ["nft", "-j", "list", "set", "inet", "banIP", f"allowlist.v{ip.version}"], + capture_output=True, + timeout=10, + ) + for item in json.loads(result.stdout)["nftables"]: + for elem in item.get("set", {}).get("elem", []): + # elements with counters are wrapped in {"elem": {"val": ...}} + if isinstance(elem, dict) and "elem" in elem: + elem = elem["elem"]["val"] + if isinstance(elem, str): + if ip == ipaddress.ip_address(elem): + return True + elif "prefix" in elem: + prefix = elem["prefix"] + if ip in ipaddress.ip_network(f"{prefix['addr']}/{prefix['len']}"): + return True + elif "range" in elem: + first, last = elem["range"] + if ipaddress.ip_address(first) <= ip <= ipaddress.ip_address(last): + return True + return False + + +def main(): + try: + sys.exit(0 if allowed(ipaddress.ip_address(sys.argv[1])) else 1) + except Exception: + # missing set, bad input or nft error: not allowlisted + sys.exit(1) + + +if __name__ == "__main__": + main() diff --git a/packages/ns-threat_shield/files/ts-insights-hook b/packages/ns-threat_shield/files/ts-insights-hook index d76dad593..d92bfb039 100755 --- a/packages/ns-threat_shield/files/ts-insights-hook +++ b/packages/ns-threat_shield/files/ts-insights-hook @@ -5,15 +5,32 @@ # SPDX-License-Identifier: GPL-2.0-only # -# banip ban_blockhook: append a blocked IP to the spool, send-insights-blocklist sends it. -# Args: $1 IP; the other banip args ($2 family, $3 log count, $4 Set expiry) are not used +# fail2ban ns-insights action: report a banned IP to Nethesis Insights, fire and forget. +# Args: $1 IP, $2 fail2ban scenario +# Only failures are logged, unless banip.global.ban_debug is set. -SPOOL_DIR="/var/run/ns-insights" -SPOOL="${SPOOL_DIR}/threat-events.jsonl" +# opt-out: uci set banip.global.ns_insights_report=0 +[ "$(uci -q get banip.global.ns_insights_report)" = "0" ] && exit 0 +system_id=$(uci -q get ns-plug.config.system_id) +secret=$(uci -q get ns-plug.config.secret) +[ -n "$system_id" ] && [ -n "$secret" ] || exit 0 +url=$(uci -q get ns-plug.config.insights_blocklist_url) +url="${url:-https://insights.nethesis.it/blocklist/v1/events}" -[ -n "$1" ] || exit 0 +ip="$1" +# only public addresses are reported +python3 -c 'import ipaddress, sys; sys.exit(not ipaddress.ip_address(sys.argv[1]).is_global)' "$ip" 2>/dev/null || exit 0 +scenario="$2" +case "$scenario" in + "" | *[!A-Za-z0-9/._-]*) scenario="nethsecurity/fail2ban" ;; +esac -[ -d "${SPOOL_DIR}" ] || mkdir -p "${SPOOL_DIR}" +payload=$(printf '{"schema_version":1,"system_id":"%s","decisions":[{"value":"%s","scope":"Ip","type":"ban","scenario":"%s","origin":"fail2ban","created_at":"%s"}]}' \ + "$system_id" "$ip" "$scenario" "$(date -u '+%Y-%m-%dT%H:%M:%SZ')") -printf '{"value":"%s","scope":"Ip","type":"ban","scenario":"nethsecurity/banip-log","origin":"banip","created_at":"%s"}\n' \ - "$1" "$(date -u '+%Y-%m-%dT%H:%M:%SZ')" >>"${SPOOL}" +if ! error=$(curl -sS --fail --max-time 5 -o /dev/null -u "$system_id:$secret" \ + -H 'Content-Type: application/json' --data "$payload" "$url" 2>&1); then + logger -t threat_shield "Insights report of $ip failed, dropped: $error" +elif [ "$(uci -q get banip.global.ban_debug)" = "1" ]; then + logger -t threat_shield "Insights report of $ip ($scenario) sent" +fi diff --git a/packages/ns-threat_shield/files/ts-ip b/packages/ns-threat_shield/files/ts-ip index 362e6c858..6cac0d05c 100755 --- a/packages/ns-threat_shield/files/ts-ip +++ b/packages/ns-threat_shield/files/ts-ip @@ -28,7 +28,6 @@ function exit_error { INSIGHTS_SENDER=/usr/sbin/send-insights-blocklist INSIGHTS_HOOK=/usr/libexec/ts-insights-hook -INSIGHTS_SPOOL=/var/run/ns-insights/threat-events.jsonl SYSTEM_SECRET=$(uci -q get ns-plug.config.secret) SYSTEM_ID=$(uci -q get ns-plug.config.system_id) @@ -50,19 +49,6 @@ if [ ! -z "$SYSTEM_SECRET" ] && [ ! -z "$SYSTEM_ID" ]; then uci add_list banip.global.ban_allowurl="$allow_current" uci commit banip fi - # Nethesis Insights: every subscription reports the blocked IPs, - # the nethesisinsightslvl2 feed is selectable only with the Threat Shield entitlement. - # banip supports a single block hook: a custom one is preserved and disables the reporting - hook=$(uci -q get banip.global.ban_blockhook) - if [ -z "$hook" ]; then - uci set banip.global.ban_blockhook="$INSIGHTS_HOOK" - uci commit banip - elif [ "$hook" != "$INSIGHTS_HOOK" ]; then - logger -t threat_shield "Nethesis Insights reporting disabled: custom banip block hook $hook is configured" - fi - if ! crontab -l 2>/dev/null | grep -q "$INSIGHTS_SENDER"; then - { crontab -l 2>/dev/null; echo "*/5 * * * * sleep \$(( RANDOM % 60 )); $INSIGHTS_SENDER"; } | crontab - - fi else allow=$(uci -q get banip.global.ban_allowurl | tr " " "\n" | grep bl.nethesis.it) if [ "$allow" != "" ]; then @@ -78,8 +64,8 @@ else uci commit banip fi > /etc/banip/banip.custom.feeds - # stop reporting to Nethesis Insights, the feed is removed with the other enterprise feeds; - # a custom block hook is left untouched + # the Insights feed is removed with the other enterprise feeds, ts-insights-hook stops reporting; + # remove the banip block hook and the sender cron job left by older releases, a custom hook is left untouched if [ "$(uci -q get banip.global.ban_blockhook)" = "$INSIGHTS_HOOK" ]; then uci -q delete banip.global.ban_blockhook uci commit banip @@ -87,5 +73,6 @@ else if crontab -l 2>/dev/null | grep -q "$INSIGHTS_SENDER"; then crontab -l | grep -v "$INSIGHTS_SENDER" | crontab - fi - rm -f "$INSIGHTS_SPOOL" fi + +/usr/libexec/ts-fail2ban diff --git a/packages/ns-threat_shield/files/ts-ip.hook b/packages/ns-threat_shield/files/ts-ip.hook index c26afde24..95b0c60e9 100755 --- a/packages/ns-threat_shield/files/ts-ip.hook +++ b/packages/ns-threat_shield/files/ts-ip.hook @@ -8,6 +8,6 @@ # ns-plug register/unregister hook: ts-ip does not reload banip, since it also runs during upgrades /usr/sbin/ts-ip -# the banip log service reads the hook, the feeds and the allowlist only on start +# banip reads the feeds and the allowlist only on start /etc/init.d/banip reload exit 0 diff --git a/packages/ns-ui/Makefile b/packages/ns-ui/Makefile index e64205c2a..60d76d6f3 100644 --- a/packages/ns-ui/Makefile +++ b/packages/ns-ui/Makefile @@ -60,6 +60,8 @@ define Package/ns-ui/install $(INSTALL_BIN) ./files/ns-ui.init $(1)/etc/init.d/ns-ui $(INSTALL_DIR) $(1)/etc/uci-defaults $(INSTALL_BIN) ./files/ns-ui.uci-defaults $(1)/etc/uci-defaults + $(INSTALL_DIR) $(1)/etc/nginx/conf.d + $(INSTALL_DATA) ./files/ns-ui-log.conf $(1)/etc/nginx/conf.d $(CP) $(PKG_BUILD_DIR)/dist/* $(1)/www-ns endef diff --git a/packages/ns-ui/files/ns-ui b/packages/ns-ui/files/ns-ui index 6e5b00ee3..20fd2fa2f 100755 --- a/packages/ns-ui/files/ns-ui +++ b/packages/ns-ui/files/ns-ui @@ -124,7 +124,7 @@ server { ssl_session_cache shared:SSL:32k; ssl_session_timeout 64m; error_log syslog:server=unix:/dev/log,nohostname; - access_log off; + access_log syslog:server=unix:/dev/log,nohostname combined if=\$ns_ui_log; server_tokens $server_tokens; # enable NS UI diff --git a/packages/ns-ui/files/ns-ui-log.conf b/packages/ns-ui/files/ns-ui-log.conf new file mode 100644 index 000000000..4c3b3ad94 --- /dev/null +++ b/packages/ns-ui/files/ns-ui-log.conf @@ -0,0 +1,10 @@ +# +# Copyright (C) 2026 Nethesis S.r.l. +# SPDX-License-Identifier: GPL-2.0-only +# + +# log only "not found" responses of the UI servers: fail2ban ns-proxy-scan bans scanners +map $status $ns_ui_log { + 404 1; + default 0; +} diff --git a/packages/python3-nethsec/src/nethsec/inventory/__init__.py b/packages/python3-nethsec/src/nethsec/inventory/__init__.py index f2ea43d24..57e85ddd5 100644 --- a/packages/python3-nethsec/src/nethsec/inventory/__init__.py +++ b/packages/python3-nethsec/src/nethsec/inventory/__init__.py @@ -440,6 +440,13 @@ def fact_threat_shield(uci: EUci): pass return ret +def fact_fail2ban(uci: EUci): + # same rules as ts-fail2ban: banIP on, log monitor on (ban_loglimit > 0), at least one jail + jails = [] + if uci.get('banip', 'global', 'ban_enabled', default='0') == '1' and uci.get('banip', 'global', 'ban_loglimit', dtype=int, default=100) > 0: + jails = list(uci.get('banip', 'global', 'ns_jails', list=True, default=[])) + return { 'enabled': len(jails) > 0, 'jails': jails } + def fact_adblock(uci: EUci): ret = { 'enabled': False, 'community': 0, 'enterprise': 0, 'enterprise_feeds': [] } ret['enabled'] = uci.get('adblock', 'global', 'ts_enabled', default='0') == '1' diff --git a/packages/python3-nethsec/tests/test_inventory.py b/packages/python3-nethsec/tests/test_inventory.py index a9618346e..bf6b70f03 100644 --- a/packages/python3-nethsec/tests/test_inventory.py +++ b/packages/python3-nethsec/tests/test_inventory.py @@ -427,6 +427,8 @@ option ban_autoblocklist '1' option ban_allowlistonly '0' option ban_nftexpiry '1d' + list ns_jails 'ns-ssh' + list ns_jails 'ns-webui' option ban_logcount '3' list ban_feed 'nethesislvl3' list ban_feed 'test1' @@ -895,6 +897,15 @@ def test_fact_threat_shield(tmp_path): u = _setup_db(tmp_path) assert inventory.fact_threat_shield(u) == {"enabled": True, "community": 1, "enterprise": 1, "enterprise_feeds": ["nethesislvl3"], "geoblocking": 0} +def test_fact_fail2ban(tmp_path): + u = _setup_db(tmp_path) + assert inventory.fact_fail2ban(u) == {"enabled": True, "jails": ["ns-ssh", "ns-webui"]} + u.set("banip", "global", "ban_loglimit", "0") + assert inventory.fact_fail2ban(u) == {"enabled": False, "jails": []} + u.set("banip", "global", "ban_loglimit", "100") + u.set("banip", "global", "ban_enabled", "0") + assert inventory.fact_fail2ban(u) == {"enabled": False, "jails": []} + def test_fact_ui(tmp_path): u = _setup_db(tmp_path) assert inventory.fact_ui(u) == {"luci": False, "port443": True, "port9090": True} diff --git a/patches/feeds/packages/100-fail2ban-no-firewall-include.patch b/patches/feeds/packages/100-fail2ban-no-firewall-include.patch new file mode 100644 index 000000000..717cc7279 --- /dev/null +++ b/patches/feeds/packages/100-fail2ban-no-firewall-include.patch @@ -0,0 +1,22 @@ +diff --git a/net/fail2ban/Makefile b/net/fail2ban/Makefile +index 2565c52..cb219f5 100644 +--- a/net/fail2ban/Makefile ++++ b/net/fail2ban/Makefile +@@ -67,7 +67,6 @@ define Py3Package/fail2ban/install + + $(INSTALL_DIR) $(1)/etc/config + $(INSTALL_CONF) ./files/fail2ban.config $(1)/etc/config/fail2ban +- $(INSTALL_BIN) ./files/firewall.fail2ban $(1)/etc/firewall.fail2ban + + $(INSTALL_DIR) $(1)/etc/init.d + $(INSTALL_BIN) ./files/fail2ban.init $(1)/etc/init.d/fail2ban +@@ -78,9 +77,6 @@ define Py3Package/fail2ban/install + $(INSTALL_DIR) $(1)/etc/fail2ban/fail2ban.d + $(INSTALL_DATA) ./files/db.conf $(1)/etc/fail2ban/fail2ban.d/db.conf + $(INSTALL_DATA) ./files/uci.conf $(1)/etc/fail2ban/fail2ban.d/uci.conf +- +- $(INSTALL_DIR) $(1)/etc/uci-defaults +- $(INSTALL_BIN) ./files/fail2ban.defaults $(1)/etc/uci-defaults/99_fail2ban + endef + + $(eval $(call Py3Package,fail2ban)) diff --git a/patches/feeds/packages/101-fail2ban-data-storage.patch b/patches/feeds/packages/101-fail2ban-data-storage.patch new file mode 100644 index 000000000..82a35c1bd --- /dev/null +++ b/patches/feeds/packages/101-fail2ban-data-storage.patch @@ -0,0 +1,17 @@ +diff --git a/net/fail2ban/files/fail2ban.init b/net/fail2ban/files/fail2ban.init +--- a/net/fail2ban/files/fail2ban.init ++++ b/net/fail2ban/files/fail2ban.init +@@ -21,6 +21,13 @@ + + config_load fail2ban + config_get dbfile fail2ban dbfile /var/lib/fail2ban/fail2ban.sqlite3 ++ # NethSecurity: keep the DB on the data storage only when it is really mounted ++ if grep -q " /mnt/data " /proc/mounts; then ++ dbfile=/mnt/data/fail2ban/fail2ban.sqlite3 ++ else ++ dbfile=/var/run/fail2ban/fail2ban.sqlite3 ++ fi ++ mkdir -m 0755 -p "$(dirname "$dbfile")" + + echo "[Definition]" > "${RUNCONF}" + echo -n "dbfile = " >> "${RUNCONF}" From 2e671e0c7463a10dcf990fc0f85a33064af24614 Mon Sep 17 00:00:00 2001 From: Tommaso Bailetti Date: Fri, 6 Nov 2026 17:14:32 +0100 Subject: [PATCH 23/51] ui bump --- packages/ns-ui/Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/ns-ui/Makefile b/packages/ns-ui/Makefile index 60d76d6f3..2e75e3252 100644 --- a/packages/ns-ui/Makefile +++ b/packages/ns-ui/Makefile @@ -12,7 +12,7 @@ PKG_RELEASE:=1 PKG_SOURCE_PROTO:=git PKG_SOURCE_URL:=https://github.com/NethServer/nethsecurity-ui.git -PKG_SOURCE_VERSION:=bd8185cd4e0c6824afdcc53b5181a6d50c374e0c +PKG_SOURCE_VERSION:=809aa4cfa08f80463542421df1e8ca37653d96aa PKG_SOURCE_SUBDIR:=nethsecurity-ui-$(PKG_SOURCE_VERSION) PKG_BUILD_DIR:=$(BUILD_DIR)/$(PKG_SOURCE_SUBDIR) PKG_MIRROR_HASH:=skip From a7e4ac1f01f43016149da9868b11f23a51e17288 Mon Sep 17 00:00:00 2001 From: Tommaso Bailetti Date: Fri, 6 Nov 2026 17:39:10 +0100 Subject: [PATCH 24/51] ci: fixed issue with deduping sarif checks --- .github/workflows/govulncheck.yml | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/.github/workflows/govulncheck.yml b/.github/workflows/govulncheck.yml index aa1890e35..26ecc67d4 100644 --- a/.github/workflows/govulncheck.yml +++ b/.github/workflows/govulncheck.yml @@ -38,6 +38,7 @@ jobs: - uses: actions/setup-go@v7 with: go-version-file: ${{ matrix.path }}/go.mod + cache-dependency-path: ${{ matrix.path }}/go.sum - name: Install govulncheck run: go install golang.org/x/vuln/cmd/govulncheck@latest @@ -46,6 +47,12 @@ jobs: run: govulncheck -format sarif ./... > govulncheck.sarif continue-on-error: true + # govulncheck emits one identical stack per matching OSV affected entry, SARIF requires them unique + - name: Deduplicate SARIF stacks + run: | + jq '.runs[].results[] |= if .stacks then .stacks |= unique else . end' govulncheck.sarif > deduped.sarif + mv deduped.sarif govulncheck.sarif + - name: Upload SARIF to code scanning uses: github/codeql-action/upload-sarif@v4 with: From 907fceca48eb5cd6eb84462c74e63f5ac6f16ac3 Mon Sep 17 00:00:00 2001 From: Tommaso Bailetti Date: Mon, 9 Nov 2026 10:01:45 +0100 Subject: [PATCH 25/51] build: removed image builder --- config/image_builder.conf | 2 -- docs/build/custom_images.md | 50 ------------------------------------- 2 files changed, 52 deletions(-) delete mode 100644 config/image_builder.conf delete mode 100644 docs/build/custom_images.md diff --git a/config/image_builder.conf b/config/image_builder.conf deleted file mode 100644 index 5961a41d6..000000000 --- a/config/image_builder.conf +++ /dev/null @@ -1,2 +0,0 @@ -CONFIG_IB=y -CONFIG_IB_STANDALONE=y diff --git a/docs/build/custom_images.md b/docs/build/custom_images.md deleted file mode 100644 index 32a19181d..000000000 --- a/docs/build/custom_images.md +++ /dev/null @@ -1,50 +0,0 @@ ---- -layout: default -title: Custom images -parent: Build system ---- - -# Custom images - -You can create custom images using [Image Builder](https://openwrt.org/docs/guide-user/additional-software/imagebuilder). - -Download the image builder from: -``` -https://updates.nethsecurity.nethserver.org/stable//targets/x86/64/nethsecurity-imagebuilder-8--ns.-x86-64.Linux-x86_64.tar.xz -``` - -Replace `owrt_version` with the latest OpenWrt release, like `23.05.05` and `nsec_version` with lates NethSecurity release like `1.4.1`. - -## Using Image Builder inside CentOS 7 - -Install the dependencies: -``` -yum install perl-Thread-Queue devtoolset-7-make git unzip bzip2 -``` - -Upload the builder inside the system and prepare it: -``` -mkdir builder; tar xvf nethsecurity-imagebuilder-22.03.0-x86-64.Linux-x86_64.tar.xz -C builder -cd builder -sed -i '/logd \\/d' include/target.mk -``` -Note: OpenWrt build system assumes logd is always installed, but NethSecurity image does not ship it. -The `sed` command ensure logd is not bundled inside the image. - -Prepare the files directory: -``` -wget https://github.com/NethServer/nethsecurity/archive/refs/heads/master.tar.gz -tar xvf master.tar.gz nethsecurity-master/files/ -``` - -To include custom files, add them inside `nethsecurity-master/files` directory -with the full path, like: -``` -echo "hello" > file/root/goofy -``` - -Start the build with all included packages: -``` -source /opt/rh/devtoolset-7/enable -make image FILES="nethsecurity-master/files/" PACKAGES="$(grep "Package: " packages/Packages | cut -d ':' -f 2 | tr '\n' ' ')" -``` From bc925a03cf1ed4dc9cc68f07bd0757d0454b9cec Mon Sep 17 00:00:00 2001 From: Giacomo Sanchietti Date: Mon, 9 Nov 2026 15:08:51 +0100 Subject: [PATCH 26/51] fix(api-server): avoid panic on invalid logout (#1999) --- packages/ns-api-server/files/src/middleware/middleware.go | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/packages/ns-api-server/files/src/middleware/middleware.go b/packages/ns-api-server/files/src/middleware/middleware.go index dc7a7e2a6..084fe4bcc 100644 --- a/packages/ns-api-server/files/src/middleware/middleware.go +++ b/packages/ns-api-server/files/src/middleware/middleware.go @@ -271,7 +271,12 @@ func InitJWT() *jwt.GinJWTMiddleware { }, LogoutResponse: func(c *gin.Context, code int) { //get claims - tokenObj, _ := InstanceJWT().ParseToken(c) + tokenObj, err := InstanceJWT().ParseToken(c) + // invalid or missing token: nothing to log out + if err != nil { + c.JSON(200, gin.H{"code": 200}) + return + } claims := jwt.ExtractClaimsFromToken(tokenObj) // set token to invalid From 89a1ff08426bb23152ac2513b17aa99179be6369 Mon Sep 17 00:00:00 2001 From: Giacomo Sanchietti Date: Mon, 9 Nov 2026 15:18:44 +0100 Subject: [PATCH 27/51] fix(restore-extra-packages): stop respawn loop (#1997) --- .../uci-defaults/99-nethsec-restore-extra-packages | 2 ++ files/usr/sbin/ns-restore-extra-packages | 13 +++++++++---- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/files/etc/uci-defaults/99-nethsec-restore-extra-packages b/files/etc/uci-defaults/99-nethsec-restore-extra-packages index 5734052ad..fcfd34a9b 100644 --- a/files/etc/uci-defaults/99-nethsec-restore-extra-packages +++ b/files/etc/uci-defaults/99-nethsec-restore-extra-packages @@ -1 +1,3 @@ +# Re-enable: the backup 10_disable_services may have disabled it +/etc/init.d/ns-restore-extra-packages enable /etc/init.d/ns-restore-extra-packages start diff --git a/files/usr/sbin/ns-restore-extra-packages b/files/usr/sbin/ns-restore-extra-packages index 50748cfae..08d19bcde 100755 --- a/files/usr/sbin/ns-restore-extra-packages +++ b/files/usr/sbin/ns-restore-extra-packages @@ -7,8 +7,15 @@ # Runs via procd init script which handles respawn on failure. # -if ! grep -qE '\w+\s+overlay$' /etc/backup/installed_packages.txt &>/dev/null; then +# Disable before stop: stop makes procd kill this very process +finish() { + /etc/init.d/ns-restore-extra-packages disable + /etc/init.d/ns-restore-extra-packages stop exit 0 +} + +if ! grep -qE '\w+\s+overlay$' /etc/backup/installed_packages.txt &>/dev/null; then + finish fi # Check network connectivity @@ -39,9 +46,7 @@ while IFS= read -r package; do done < <(grep -E '\w+\s+overlay$' /etc/backup/installed_packages.txt | awk '{print $1}') if [ -z "$failed_packages" ]; then - /etc/init.d/ns-restore-extra-packages stop - /etc/init.d/ns-restore-extra-packages disable - exit 0 + finish else echo "Some packages failed to restore, will retry later" exit 1 From 949e89fc03b0a36de66f64baf6fe06dd50fbc4d4 Mon Sep 17 00:00:00 2001 From: Giacomo Sanchietti Date: Mon, 9 Nov 2026 15:46:23 +0100 Subject: [PATCH 28/51] fix(vmalert): start after VictoriaMetrics (#1998) --- packages/victoria-metrics/files/vmalert.initd | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/victoria-metrics/files/vmalert.initd b/packages/victoria-metrics/files/vmalert.initd index 18d9bd382..daf7fe759 100644 --- a/packages/victoria-metrics/files/vmalert.initd +++ b/packages/victoria-metrics/files/vmalert.initd @@ -5,7 +5,7 @@ # SPDX-License-Identifier: GPL-2.0-only # -START=95 +START=99 STOP=5 USE_PROCD=1 From ef4a72d34a9950b98ebfa036e5189b4f14efc1ad Mon Sep 17 00:00:00 2001 From: Giacomo Sanchietti Date: Mon, 9 Nov 2026 15:46:39 +0100 Subject: [PATCH 29/51] fix(ns-plug): show ns-plug as controller in alerts (#1993) --- packages/ns-plug/files/vmalert-rules/services.yaml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/ns-plug/files/vmalert-rules/services.yaml b/packages/ns-plug/files/vmalert-rules/services.yaml index 67381e580..2a0fa994b 100644 --- a/packages/ns-plug/files/vmalert-rules/services.yaml +++ b/packages/ns-plug/files/vmalert-rules/services.yaml @@ -11,7 +11,8 @@ groups: eval_alignment: false rules: - alert: ServiceDown - expr: 'procd_service_running == 0 and procd_service_exit_code != 0' + # Show ns-plug as "controller" in alerts + expr: 'label_replace(procd_service_running == 0 and procd_service_exit_code != 0, "service", "controller", "service", "ns-plug")' for: "5m" labels: severity: "critical" From 05cf038c0215c79554dfd595fd510ef4ffc9fa84 Mon Sep 17 00:00:00 2001 From: Matteo Di Lorenzi <52289654+m-dilorenzi@users.noreply.github.com> Date: Mon, 9 Nov 2026 17:52:37 +0100 Subject: [PATCH 30/51] fix(ovpnrw): list disabled accounts of deleted remote users (#1981) --- packages/ns-api/README.md | 23 ++++++++++++++++++++--- packages/ns-api/files/ns.ovpnrw | 5 ++++- 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/packages/ns-api/README.md b/packages/ns-api/README.md index 93a66f023..6d08738b9 100644 --- a/packages/ns-api/README.md +++ b/packages/ns-api/README.md @@ -1601,9 +1601,10 @@ Response example: "id": "ns_d486faa0", "connected": false, "expiration": "", - "expired": false + "expired": false, "used": false, - "matches": [] + "matches": [], + "valid": true }, { "local": true, @@ -1624,7 +1625,20 @@ Response example: "expiration": 2012741635, "expired": false, "used": true, - "matches": ["firewall/ns_allow_xx"] + "matches": ["firewall/ns_allow_xx"], + "valid": true + }, + { + "id": "ns_91a99e42", + "name": "mario", + "openvpn_enabled": "0", + "openvpn_ipaddr": "", + "expiration": 0, + "expired": false, + "used": false, + "matches": [], + "connected": false, + "valid": false } ] } @@ -1634,6 +1648,9 @@ The following fields may not be present: - `password` - `ipaddr` +The `valid` field is `false` if the user has an OpenVPN account but it no longer exists inside the remote user database, +for example when it has been deleted from the LDAP/AD server. Both enabled and disabled accounts are listed. + If `connected` field is `true`, the user object should contain also: - `real_address`, the remote address - `virtual_address` diff --git a/packages/ns-api/files/ns.ovpnrw b/packages/ns-api/files/ns.ovpnrw index 8a538a4db..8439a62dd 100755 --- a/packages/ns-api/files/ns.ovpnrw +++ b/packages/ns-api/files/ns.ovpnrw @@ -682,7 +682,8 @@ def list_users(ovpninstance): user['valid'] = True ret.append(user) for configured_user in utils.get_all_by_option(u, 'users', 'database', db): - if u.get('users', configured_user, 'openvpn_enabled', default='0') != '1': + # include also disabled accounts, otherwise they can't be deleted from the UI + if u.get('users', configured_user, 'openvpn_enabled', default=None) is None: continue username = u.get('users', configured_user, 'name') # Search for the user inside the ret array @@ -692,6 +693,8 @@ def list_users(ovpninstance): ret.append( { "id": configured_user, "name": username, + "openvpn_enabled": u.get('users', configured_user, 'openvpn_enabled'), + "openvpn_ipaddr": u.get('users', configured_user, 'openvpn_ipaddr', default=''), "expiration": 0, "expired": False, "used": used, From 9683bfc6ede4953d353931c66f29552a19c27659 Mon Sep 17 00:00:00 2001 From: Matteo Di Lorenzi <52289654+m-dilorenzi@users.noreply.github.com> Date: Tue, 10 Nov 2026 09:17:48 +0100 Subject: [PATCH 31/51] fix(wireguard): enable mtu_fix on new tunnel zones (#1994) --- packages/ns-api/files/ns.wireguard | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/packages/ns-api/files/ns.wireguard b/packages/ns-api/files/ns.wireguard index 2bf0903bd..569eaf6f7 100644 --- a/packages/ns-api/files/ns.wireguard +++ b/packages/ns-api/files/ns.wireguard @@ -44,6 +44,16 @@ def __set_list_to_uci(e_uci: EUci, config: str, section: str, option: str, new_v e_uci.set(config, section, option, new_value) +def __add_zone(e_uci: EUci, instance: str): + zone = f"{instance}vpn" + zone_section, _ = firewall.add_trusted_zone(e_uci, zone, link=f"network/{instance}") + if zone_section: + # clamp TCP MSS to the tunnel MTU + e_uci.set('firewall', zone_section, 'mtu_fix', '1') + e_uci.save('firewall') + firewall.add_interface_to_zone(e_uci, instance, zone) + + def generate_wireguard_keys(): private_key = subprocess.run(["wg", "genkey"], capture_output=True, text=True).stdout.strip() public_key = subprocess.run(["wg", "pubkey"], input=private_key, capture_output=True, text=True).stdout.strip() @@ -324,9 +334,7 @@ def add_server(args): ['udp'], link=f"network/{instance}" ) - zone = f"{instance}vpn" - firewall.add_trusted_zone(e_uci, zone, link=f"network/{instance}") - firewall.add_interface_to_zone(e_uci, instance, zone) + __add_zone(e_uci, instance) return {"result": "success"} @@ -671,9 +679,7 @@ def import_configuration(args): e_uci.set('network', peer_instance, 'persistent_keepalive', config_parser["Peer"].get("PersistentKeepalive", "25")) e_uci.set('network', peer_instance, 'ns_link', f'network/{instance}') e_uci.save('network') - zone = f"{instance}vpn" - firewall.add_trusted_zone(e_uci, zone, link=f"network/{instance}") - firewall.add_interface_to_zone(e_uci, instance, zone) + __add_zone(e_uci, instance) except Exception: return utils.validation_error("config", "invalid_file_format") @@ -778,9 +784,7 @@ def add_tunnel(args): if 'dns' in args: e_uci.set('network', instance, 'dns', args['dns']) e_uci.save('network') - zone = f"{instance}vpn" - firewall.add_trusted_zone(e_uci, zone, link=f"network/{instance}") - firewall.add_interface_to_zone(e_uci, instance, zone) + __add_zone(e_uci, instance) return {"result": "success"} From 149242ef0e49afb04e9a05a88d786602db29aca2 Mon Sep 17 00:00:00 2001 From: Matteo Di Lorenzi <52289654+m-dilorenzi@users.noreply.github.com> Date: Tue, 10 Nov 2026 09:18:49 +0100 Subject: [PATCH 32/51] fix(openvpn): refuse connection of users removed from remote database (#1989) --- packages/ns-openvpn/files/01-check-status | 19 +++++-- .../src/nethsec/users/__init__.py | 54 +++++++++++++++++++ packages/python3-nethsec/tests/test_users.py | 28 ++++++++++ 3 files changed, 98 insertions(+), 3 deletions(-) diff --git a/packages/ns-openvpn/files/01-check-status b/packages/ns-openvpn/files/01-check-status index 4d43c8638..4fd917ea1 100755 --- a/packages/ns-openvpn/files/01-check-status +++ b/packages/ns-openvpn/files/01-check-status @@ -12,6 +12,8 @@ import os import sys +import syslog +import subprocess from euci import EUci from nethsec import users @@ -66,8 +68,19 @@ if user is None: # User not found sys.exit(2) -if user.get("openvpn_enabled", "0") == "1": - sys.exit(0) -else: +if user.get("openvpn_enabled", "0") != "1": # User is disabled sys.exit(1) + +# If user DB is remote, check the existence of the user +# in the LDAP server +if users.get_database_type(uci, db) == "ldap": + try: + if not users.remote_user_exists(uci, cn, db): + # User not found in remote database + sys.exit(7) + except subprocess.CalledProcessError as e: + syslog.syslog(syslog.LOG_ERR, f"Connection refused for user '{cn}': can't query remote database '{db}': {e.stderr.strip()}") + sys.exit(6) + +sys.exit(0) diff --git a/packages/python3-nethsec/src/nethsec/users/__init__.py b/packages/python3-nethsec/src/nethsec/users/__init__.py index 7fcd4a61f..a0ee0ba21 100644 --- a/packages/python3-nethsec/src/nethsec/users/__init__.py +++ b/packages/python3-nethsec/src/nethsec/users/__init__.py @@ -731,6 +731,60 @@ def delete_remote_user(uci, name, database): uci.save("users") return True +def remote_user_exists(uci, name, database): + ''' + Check if a user exists inside a remote LDAP database + + Arguments: + - uci -- EUci pointer + - name -- User name + - database -- Database identifier + + Returns: + - True if the user exists, False otherwise + + Raises: + - subprocess.CalledProcessError if the LDAP server can't be queried + ''' + if get_database_type(uci, database) != "ldap": + raise utils.ValidationError('database', 'db_not_ldap', database) + ldap = uci.get_all("users", database) + uri = ldap.get("uri", "") + base_dn = ldap.get("base_dn", "") + user_attr = ldap.get("user_attr", "uid") + tls_reqcert = ldap.get("tls_reqcert", "never") + starttls = int(ldap.get("start_tls", 0)) + bind_dn = ldap.get("bind_dn") + bind_password = ldap.get("bind_password") + + ldapsearch_command = [ + "/usr/bin/ldapsearch", + "-LLL", + "-H", uri, + "-b", base_dn, + ] + + if bind_dn: + ldapsearch_command.append("-D") + ldapsearch_command.append(bind_dn) + ldapsearch_command.append("-w") + ldapsearch_command.append(bind_password) + else: + ldapsearch_command.append("-x") + + if starttls: + ldapsearch_command.append("-Z") + + # static filter to limit the number of returned attributes and entries + ldapsearch_command.append(f"{user_attr}={name}") + + env = os.environ.copy() + env['LDAPTLS_REQCERT'] = tls_reqcert + + proc = subprocess.run(ldapsearch_command, env=env, check=True, capture_output=True, text=True) + # search for a generic field since different LDAP servers have different DN formats + return "objectclass" in proc.stdout.lower() + def shadow_password(password): ''' Generate a shadow password diff --git a/packages/python3-nethsec/tests/test_users.py b/packages/python3-nethsec/tests/test_users.py index 904b5493e..dec4c4d03 100644 --- a/packages/python3-nethsec/tests/test_users.py +++ b/packages/python3-nethsec/tests/test_users.py @@ -1,4 +1,5 @@ import pytest +import subprocess from nethsec import utils, users from euci import EUci, UciExceptionNotFound from unittest.mock import MagicMock, patch @@ -427,6 +428,33 @@ def test_delete_remote_user_with_vpn_account(tmp_path): assert e.value.message == "user_has_vpn_account" assert users.get_user_by_name(u, "jane", "ldap2") +def test_remote_user_exists(tmp_path): + u = _setup_db(tmp_path) + ldif = "dn: uid=jane,ou=People,dc=directory,dc=nh\nobjectClass: posixAccount\nuid: jane\n" + with patch('nethsec.users.subprocess.run') as mock_run: + mock_run.return_value = MagicMock(stdout=ldif) + assert users.remote_user_exists(u, "jane", "ldap2") + assert mock_run.call_args[0][0][-1] == "uid=jane" + +def test_remote_user_not_exists(tmp_path): + u = _setup_db(tmp_path) + with patch('nethsec.users.subprocess.run') as mock_run: + mock_run.return_value = MagicMock(stdout="") + assert not users.remote_user_exists(u, "jane", "ldap2") + +def test_remote_user_exists_ldap_unreachable(tmp_path): + u = _setup_db(tmp_path) + with patch('nethsec.users.subprocess.run') as mock_run: + mock_run.side_effect = subprocess.CalledProcessError(255, "ldapsearch", stderr="Can't contact LDAP server") + with pytest.raises(subprocess.CalledProcessError): + users.remote_user_exists(u, "jane", "ldap2") + +def test_remote_user_exists_local_db(tmp_path): + u = _setup_db(tmp_path) + with pytest.raises(utils.ValidationError) as e: + users.remote_user_exists(u, "jane", "main") + assert e.value.message == "db_not_ldap" + def test_shadow_password(): shadow = users.shadow_password("test") assert(users.check_password("test", shadow)) From 040f915ebf9883c5f1e52833ece74bae104d4a06 Mon Sep 17 00:00:00 2001 From: Matteo Di Lorenzi <52289654+m-dilorenzi@users.noreply.github.com> Date: Tue, 10 Nov 2026 09:22:23 +0100 Subject: [PATCH 33/51] fix(nat): list real devices with bound interfaces in NAT rules device field (#1984) --- packages/ns-api/README.md | 25 +++++ packages/ns-api/files/ns.nat | 11 +- .../src/nethsec/utils/__init__.py | 65 +++++++++++ packages/python3-nethsec/tests/test_utils.py | 103 ++++++++++++++++++ 4 files changed, 198 insertions(+), 6 deletions(-) diff --git a/packages/ns-api/README.md b/packages/ns-api/README.md index 6d08738b9..7a9e05351 100644 --- a/packages/ns-api/README.md +++ b/packages/ns-api/README.md @@ -7211,6 +7211,31 @@ Output example: } ``` +### list-devices + +List the devices associated to firewall zones, usable to limit a NAT rule to a specific device: +``` +api-cli ns.nat list-devices +``` + +The `id` is the device name, the `label` also contains the logical interfaces bound to the device, if any. +Alias interfaces are resolved to the device of their parent interface, PPPoE and bonding interfaces +to the device they create (`pppoe-` and `bond-`). +Aliases of aliases are not supported and are not listed. + +Output example: +```json +{ + "devices": [ + {"id": "br-lan", "label": "br-lan (lan)"}, + {"id": "eth1", "label": "eth1 (f1000, al_f1000)"}, + {"id": "pppoe-wan", "label": "pppoe-wan (wan, wan6)"}, + {"id": "tunrw1", "label": "tunrw1"}, + {"id": "wg1", "label": "wg1"} + ] +} +``` + ### add-rule Add a new NAT rule: diff --git a/packages/ns-api/files/ns.nat b/packages/ns-api/files/ns.nat index 7ea702cd6..d79c12c02 100755 --- a/packages/ns-api/files/ns.nat +++ b/packages/ns-api/files/ns.nat @@ -46,12 +46,11 @@ elif cmd == 'call': print(json.dumps({'rules': firewall.list_nat_rules(e_uci)})) elif action == 'list-devices': devices = [] - for zone in firewall.list_zones(e_uci).values(): - for device in utils.get_all_devices_by_zone(e_uci, zone.get('name')): - devices.append({ - 'id': device, - 'label': utils.get_interface_from_device(e_uci, device) or device - }) + for device, interfaces in sorted(utils.get_all_zone_devices_with_interfaces(e_uci).items()): + devices.append({ + 'id': device, + 'label': f'{device} ({", ".join(interfaces)})' if interfaces else device + }) json.dump({ 'devices': devices, }, sys.stdout) diff --git a/packages/python3-nethsec/src/nethsec/utils/__init__.py b/packages/python3-nethsec/src/nethsec/utils/__init__.py index d95aec797..9d971eba0 100644 --- a/packages/python3-nethsec/src/nethsec/utils/__init__.py +++ b/packages/python3-nethsec/src/nethsec/utils/__init__.py @@ -295,6 +295,71 @@ def get_all_devices_by_zone(uci, zone, exclude_aliases=False): return list(set(devices)) +def get_interface_l3_device(uci, interface): + ''' + Retrieve the network device that carries the IP traffic of the given logical interface. + Alias interfaces are resolved to the device of their parent interface, aliases of aliases are not supported. + + Arguments: + - uci -- EUci pointer + - interface -- Logical interface name + + Returns: + - The device name as a string, None if it can't be resolved + ''' + device = uci.get('network', interface, 'device', default='') + # alias interface: use the parent interface + if device.startswith('@'): + interface = device[1:] + device = uci.get('network', interface, 'device', default='') + if uci.get('network', interface, default='') != 'interface': + return None + proto = uci.get('network', interface, 'proto', default='') + # these protocols create a device named after the interface + if proto in ('wireguard', 'xfrm'): + return interface + if proto == 'pppoe': + return f'pppoe-{interface}' + if proto == 'bonding': + return f'bond-{interface}' + # alias of alias + if device.startswith('@'): + return None + return device or uci.get('network', interface, 'name', default='') or None + + +def get_all_zone_devices_with_interfaces(uci): + ''' + Retrieve all devices associated to firewall zones, along with the logical interfaces bound to them + + Arguments: + - uci -- EUci pointer + + Returns: + - A dictionary with device names as keys and lists of interface names as values, + interfaces named like the device itself are not listed + ''' + bound = {} + for section in uci.get('network', list=True, default=[]): + if uci.get('network', section, default='') == 'interface': + device = get_interface_l3_device(uci, section) + if device and device != section: + bound.setdefault(device, []).append(section) + + devices = {} + for section in uci.get('firewall', list=True, default=[]): + if uci.get('firewall', section, default='') != 'zone': + continue + for device in uci.get('firewall', section, 'device', list=True, default=[]): + devices[device] = bound.get(device, []) + for network in uci.get('firewall', section, 'network', list=True, default=[]): + device = get_interface_l3_device(uci, network) + if device: + devices[device] = bound.get(device, []) + + return devices + + def get_all_wan_devices(uci, exclude_aliases=False): """ Retrieve all devices associated to the wan zone diff --git a/packages/python3-nethsec/tests/test_utils.py b/packages/python3-nethsec/tests/test_utils.py index 283aa5a8e..fd5f209c0 100644 --- a/packages/python3-nethsec/tests/test_utils.py +++ b/packages/python3-nethsec/tests/test_utils.py @@ -190,6 +190,109 @@ def test_get_all_lan_devices(tmp_path): u = _setup_db(tmp_path) assert(set(utils.get_all_lan_devices(u)) == set(['vnet3'])) +zone_devices_network_db = """ +config interface 'lan' + option device 'br-lan' + option proto 'static' + +config interface 'f1000' + option device 'eth1' + option proto 'static' + +config interface 'al_f1000' + option device '@f1000' + option proto 'static' + +config interface 'wan' + option device 'eth2' + option proto 'pppoe' + +config interface 'wan6' + option device '@wan' + option proto 'dhcpv6' + +config interface 'bond1' + option proto 'bonding' + list slaves 'eth3' + +config interface 'wg1' + option proto 'wireguard' + +config interface 'ipsec1' + option proto 'xfrm' + +config interface 'ns_tun1' + option device 'tuntun1' + option proto 'none' + +config interface 'al_al_f1000' + option device '@al_f1000' + +config interface 'al_missing' + option device '@missing' + +config interface 'loop1' + option device '@loop2' + +config interface 'loop2' + option device '@loop1' +""" + +zone_devices_firewall_db = """ +config zone + option name 'lan' + list network 'lan' + list network 'bond1' + +config zone + option name 'wan' + list network 'f1000' + list network 'al_f1000' + list network 'wan' + list network 'wan6' + list network 'loop1' + +config zone + option name 'vpn' + list network 'wg1' + list network 'ipsec1' + list device 'tunrw1' + list device 'tuntun1' +""" + +def test_get_interface_l3_device(tmp_path): + with tmp_path.joinpath('network').open('w') as fp: + fp.write(zone_devices_network_db) + u = EUci(confdir=tmp_path.as_posix()) + assert utils.get_interface_l3_device(u, 'f1000') == 'eth1' + assert utils.get_interface_l3_device(u, 'al_f1000') == 'eth1' + assert utils.get_interface_l3_device(u, 'wan') == 'pppoe-wan' + assert utils.get_interface_l3_device(u, 'wan6') == 'pppoe-wan' + assert utils.get_interface_l3_device(u, 'bond1') == 'bond-bond1' + assert utils.get_interface_l3_device(u, 'wg1') == 'wg1' + assert utils.get_interface_l3_device(u, 'ipsec1') == 'ipsec1' + assert utils.get_interface_l3_device(u, 'al_al_f1000') == None + assert utils.get_interface_l3_device(u, 'al_missing') == None + assert utils.get_interface_l3_device(u, 'loop1') == None + assert utils.get_interface_l3_device(u, 'missing') == None + +def test_get_all_zone_devices_with_interfaces(tmp_path): + with tmp_path.joinpath('network').open('w') as fp: + fp.write(zone_devices_network_db) + with tmp_path.joinpath('firewall').open('w') as fp: + fp.write(zone_devices_firewall_db) + u = EUci(confdir=tmp_path.as_posix()) + assert utils.get_all_zone_devices_with_interfaces(u) == { + 'br-lan': ['lan'], + 'bond-bond1': ['bond1'], + 'eth1': ['f1000', 'al_f1000'], + 'pppoe-wan': ['wan', 'wan6'], + 'wg1': [], + 'ipsec1': [], + 'tunrw1': [], + 'tuntun1': ['ns_tun1'], + } + def test_get_random_id(): id1 = utils.get_random_id() id2 = utils.get_random_id() From b88f9782ff1384df31e1c9949667243f840dc869 Mon Sep 17 00:00:00 2001 From: Tommaso Bailetti Date: Tue, 10 Nov 2026 17:36:11 +0100 Subject: [PATCH 34/51] feat: added monitoring for user-facing or demanding processes --- .../ns-plug/files/ns-controller-push-info | 1 + packages/telegraf/Makefile | 2 + packages/telegraf/README.md | 20 ++++++ .../files/telegraf.conf.d/procstat.conf | 72 +++++++++++++++++++ 4 files changed, 95 insertions(+) create mode 100644 packages/telegraf/files/telegraf.conf.d/procstat.conf diff --git a/packages/ns-plug/files/ns-controller-push-info b/packages/ns-plug/files/ns-controller-push-info index 4b81d1c8c..36f2b8563 100755 --- a/packages/ns-plug/files/ns-controller-push-info +++ b/packages/ns-plug/files/ns-controller-push-info @@ -64,6 +64,7 @@ try: telegraf_config = f"""# Controller prometheus exporter [[outputs.prometheus_client]] listen = \"{ifconfig_local}:9273\" + namedrop = [\"procstat*\"] """ with open('/etc/telegraf.conf.d/controller-prometheus.conf', 'w') as f: f.write(telegraf_config) diff --git a/packages/telegraf/Makefile b/packages/telegraf/Makefile index 81d51e044..5275ac8f4 100644 --- a/packages/telegraf/Makefile +++ b/packages/telegraf/Makefile @@ -44,6 +44,7 @@ GO_PKG_TAGS:= \ inputs.nstat \ inputs.ping \ inputs.processes \ + inputs.procstat \ inputs.sensors \ inputs.smart \ inputs.system \ @@ -92,6 +93,7 @@ define Package/telegraf/install $(INSTALL_DATA) ./files/telegraf.conf.d/services.conf $(1)/etc/telegraf.conf.d/services.conf $(INSTALL_DATA) ./files/telegraf.conf.d/mwan.conf $(1)/etc/telegraf.conf.d/mwan.conf $(INSTALL_DATA) ./files/telegraf.conf.d/ha.conf $(1)/etc/telegraf.conf.d/ha.conf + $(INSTALL_DATA) ./files/telegraf.conf.d/procstat.conf $(1)/etc/telegraf.conf.d/procstat.conf $(INSTALL_DIR) $(1)/etc/rsyslog.d/victoria-logs.d $(INSTALL_DATA) ./files/rsyslog-victoria-logs.conf $(1)/etc/rsyslog.d/victoria-logs.d/telegraf.conf $(INSTALL_DIR) $(1)/etc/uci-defaults diff --git a/packages/telegraf/README.md b/packages/telegraf/README.md index 70284b418..96426cfc3 100644 --- a/packages/telegraf/README.md +++ b/packages/telegraf/README.md @@ -123,6 +123,26 @@ curl -s 'http://127.0.0.1:8428/api/v1/query?query=mwan_interface_online' storage_status_error = 1 (error) or 0 (ok / not configured) ``` +### Process Resource Monitoring (procstat.conf) + +**How it works**: Every 30 seconds, Telegraf `procstat` collects CPU and memory usage of the most resource-intensive daemons and of the user-facing services. Each process group is a filter named after its procd service, so it can be matched with `procd_service`. Services that run more than one process with the same name (`openvpn`, `ns-plug`, `dropbear`, `nginx`, `dnsmasq`) also get a `pid` tag. + +These metrics are kept in the local Victoria Metrics only, the controller exporter drops them. + +**Metric format**: +``` +procstat_cpu_usage{filter="snort", process_name="snort3"} = percent +procstat_memory_rss{filter="nginx", process_name="nginx", pid="9086"} = bytes +procstat_lookup_running{filter="openvpn"} = number of matching processes +``` + +#### Querying Process Usage + +```bash +# Memory of every monitored service, summing multi-process ones +curl -s 'http://127.0.0.1:8428/api/v1/query?query=sum(procstat_memory_rss)by(filter)' +``` + ## Advanced Configuration To add custom metrics or modify collection intervals, edit the `/etc/telegraf.conf.d/` files following [Telegraf documentation](https://docs.influxdata.com/telegraf/). Common customizations: diff --git a/packages/telegraf/files/telegraf.conf.d/procstat.conf b/packages/telegraf/files/telegraf.conf.d/procstat.conf new file mode 100644 index 000000000..8c1e9b430 --- /dev/null +++ b/packages/telegraf/files/telegraf.conf.d/procstat.conf @@ -0,0 +1,72 @@ +# Per-process CPU and memory usage +# Filter names match the procd service names used by procd_service. + +[[inputs.procstat]] + interval = "30s" + properties = ["cpu", "memory"] + + [[inputs.procstat.filter]] + name = "snort" + executables = ["/usr/bin/snort"] + [[inputs.procstat.filter]] + name = "netifyd" + executables = ["/usr/sbin/netifyd"] + [[inputs.procstat.filter]] + name = "victoria-metrics" + executables = ["/usr/bin/victoria-metrics"] + [[inputs.procstat.filter]] + name = "victoria-logs" + executables = ["/usr/bin/victoria-logs"] + [[inputs.procstat.filter]] + name = "vmalert" + executables = ["/usr/bin/vmalert"] + [[inputs.procstat.filter]] + name = "telegraf" + executables = ["/usr/bin/telegraf"] + [[inputs.procstat.filter]] + name = "ns-flows" + executables = ["/usr/sbin/ns-flows"] + [[inputs.procstat.filter]] + name = "ns-stats" + executables = ["/usr/sbin/ns-stats"] + [[inputs.procstat.filter]] + name = "ns-api-server" + executables = ["/usr/bin/nethsecurity-api"] + # fail2ban-server runs under python3 + [[inputs.procstat.filter]] + name = "fail2ban" + patterns = ["fail2ban-server"] + [[inputs.procstat.filter]] + name = "swanctl" + executables = ["/usr/lib/ipsec/charon"] + [[inputs.procstat.filter]] + name = "odhcpd" + executables = ["/usr/sbin/odhcpd"] + + [inputs.procstat.tags] + influxdb_db = "os-metrics" + +# Services running more than one process with the same name +[[inputs.procstat]] + interval = "30s" + properties = ["cpu", "memory"] + tag_with = ["pid"] + + [[inputs.procstat.filter]] + name = "openvpn" + patterns = ["^/usr/sbin/openvpn "] + [[inputs.procstat.filter]] + name = "ns-plug" + patterns = ["^openvpn /usr/share/ns-plug/client.conf"] + [[inputs.procstat.filter]] + name = "dropbear" + executables = ["/usr/sbin/dropbear"] + [[inputs.procstat.filter]] + name = "nginx" + executables = ["/usr/sbin/nginx"] + [[inputs.procstat.filter]] + name = "dnsmasq" + executables = ["/usr/sbin/dnsmasq"] + + [inputs.procstat.tags] + influxdb_db = "os-metrics" From 87c5d295c352860f2c5dc281b470c0dd9d520f2d Mon Sep 17 00:00:00 2001 From: Tommaso Bailetti Date: Wed, 11 Nov 2026 17:29:05 +0100 Subject: [PATCH 35/51] build: adding ice firmware support (#2012) --- config/ice.conf | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 config/ice.conf diff --git a/config/ice.conf b/config/ice.conf new file mode 100644 index 000000000..551cc72d5 --- /dev/null +++ b/config/ice.conf @@ -0,0 +1,3 @@ +CONFIG_PACKAGE_ice-firmware=y +CONFIG_PACKAGE_kmod-ice=y + From 3c4aba1bd95c6ef6884425889aada052108dbc3d Mon Sep 17 00:00:00 2001 From: Giacomo Sanchietti Date: Wed, 11 Nov 2026 08:27:51 +0100 Subject: [PATCH 36/51] feat(python3-nethsec): report custom IP lists The threat_shield inventory fact reports the number of enabled custom allowlist URLs and custom blocklists. Refs #2005 Assisted-by: Claude Code:claude-opus-5-5 --- .../src/nethsec/inventory/__init__.py | 6 ++++++ .../python3-nethsec/tests/test_inventory.py | 19 ++++++++++++++++++- 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/packages/python3-nethsec/src/nethsec/inventory/__init__.py b/packages/python3-nethsec/src/nethsec/inventory/__init__.py index 57e85ddd5..670fee47e 100644 --- a/packages/python3-nethsec/src/nethsec/inventory/__init__.py +++ b/packages/python3-nethsec/src/nethsec/inventory/__init__.py @@ -426,12 +426,18 @@ def fact_rpcd_users(uci: EUci): def fact_threat_shield(uci: EUci): ret = { 'enabled': False, 'community': 0, 'enterprise': 0, 'enterprise_feeds': [], 'geoblocking': 0 } ret['enabled'] = uci.get('banip', 'global', 'ban_enabled', default='0') == '1' + custom = utils.get_all_by_type(uci, 'banip', 'ns_blockfeed') or {} + allow = utils.get_all_by_type(uci, 'banip', 'ns_allowurl') or {} + ret['custom_allowlists'] = len([s for s in allow.values() if s.get('enabled', '1') == '1']) + ret['custom_blocklists'] = 0 try: feeds = uci.get_all("banip", "global", "ban_feed") for feed in feeds: if feed.startswith("nethesis") or feed.startswith("yoroi"): ret['enterprise'] += 1 ret['enterprise_feeds'].append(feed) + elif feed in custom: + ret['custom_blocklists'] += 1 else: ret['community'] += 1 if 'country' in feeds: diff --git a/packages/python3-nethsec/tests/test_inventory.py b/packages/python3-nethsec/tests/test_inventory.py index bf6b70f03..0013a343e 100644 --- a/packages/python3-nethsec/tests/test_inventory.py +++ b/packages/python3-nethsec/tests/test_inventory.py @@ -432,6 +432,23 @@ option ban_logcount '3' list ban_feed 'nethesislvl3' list ban_feed 'test1' + list ban_feed 'mytest' + +config ns_allowurl 'allow1' + option url 'https://example.com/allow.txt' + option enabled '1' + +config ns_allowurl 'alloff' + option url 'https://example.com/off.txt' + option enabled '0' + +config ns_blockfeed 'mytest' + option url_4 'https://example.com/block.txt' + option chain 'in' + +config ns_blockfeed 'myoff' + option url_4 'https://example.com/off.txt' + option chain 'in' """ ns_ui_db = """ @@ -895,7 +912,7 @@ def test_fact_rpcd_users(tmp_path): def test_fact_threat_shield(tmp_path): u = _setup_db(tmp_path) - assert inventory.fact_threat_shield(u) == {"enabled": True, "community": 1, "enterprise": 1, "enterprise_feeds": ["nethesislvl3"], "geoblocking": 0} + assert inventory.fact_threat_shield(u) == {"enabled": True, "community": 1, "enterprise": 1, "enterprise_feeds": ["nethesislvl3"], "geoblocking": 0, "custom_blocklists": 1, "custom_allowlists": 1} def test_fact_fail2ban(tmp_path): u = _setup_db(tmp_path) From c1193c7afdff2e87a1fcab6688ba0400bd881562 Mon Sep 17 00:00:00 2001 From: Giacomo Sanchietti Date: Wed, 11 Nov 2026 08:27:51 +0100 Subject: [PATCH 37/51] feat(ns-api): custom allow and block lists ns.threatshield manages remote allowlist URLs and custom blocklists, and lists the Nethesis global allowlist as a read-only built-in row, enabled only with a subscription. Edits replace the whole entry. Custom list names can't clash with builtin feeds, and a custom list is always listed as custom. Threat Shield IP status no longer depends on the Nethesis allowlist URL. Refs #2005 Assisted-by: Claude Code:claude-opus-5-5 --- packages/ns-api/README.md | 153 ++++++++++++++- packages/ns-api/files/ns.dashboard | 3 +- packages/ns-api/files/ns.threatshield | 199 +++++++++++++++++++- packages/ns-api/openapi.yml | 258 ++++++++++++++++++++++++++ 4 files changed, 607 insertions(+), 6 deletions(-) diff --git a/packages/ns-api/README.md b/packages/ns-api/README.md index 7a9e05351..40004226f 100644 --- a/packages/ns-api/README.md +++ b/packages/ns-api/README.md @@ -6134,9 +6134,23 @@ Response example: ```json { "data": [ + { + "name": "myfeed", + "type": "community", + "custom": true, + "enabled": false, + "confidence": -1, + "description": "my blocklist", + "direction": "in", + "protocols": [], + "ports": [], + "url_4": "https://example.com/v4.txt", + "url_6": "" + }, { "name": "yoroimallvl1", "type": "enterprise", + "custom": false, "enabled": false, "confidence": 10, "description": "Yoroi malware - Level 1", @@ -6147,6 +6161,7 @@ Response example: { "name": "doh", "type": "community", + "custom": false, "enabled": true, "confidence": -1, "description": "public DoH-Server", @@ -6158,8 +6173,11 @@ Response example: } ``` +Custom blocklists are listed first, then the built-in feeds. + Fields: - type can be `enterprise` or `community` +- custom is `true` for custom blocklists (see [add-custom-blocklist](#add-custom-blocklist)), listed from UCI also before commit, with type `community`, confidence `-1` and the extra `url_4` and `url_6` fields - confidence can be `-1` if the value is not available - direction is the default blocking direction of the feed: `in` (inbound, WAN-input and WAN-forward), `out` (outbound, LAN-forward) or `inout` (both) @@ -6210,11 +6228,144 @@ Response example: ### edit-blocklist -Enable or disable a blocklist: +Enable or disable a blocklist, custom blocklists included: ``` api-cli ns.threatshield edit-blocklist --data '{ "blocklist": "blocklist_name", "enabled": True }' ``` +### list-allowlist-urls + +List the remote allowlist URLs downloaded by banip (`ban_allowurl`). +The built-in `nethesis` row is always listed and read-only: `enabled` is true only on units with ns-plug credentials, its URL is never returned. +``` +api-cli ns.threatshield list-allowlist-urls +``` + +Response example: +```json +{ + "data": [ + {"name": "nethesis", "builtin": true, "url": "", "description": "Nethesis global allowlist", "enabled": true}, + {"name": "partners", "builtin": false, "url": "https://example.com/allow.txt", "description": "partner networks", "enabled": true} + ] +} +``` + +### add-allowlist-url + +Add a remote allowlist URL, a plain list with one IP/CIDR per line: +``` +api-cli ns.threatshield add-allowlist-url --data '{"name": "partners", "url": "https://example.com/allow.txt", "description": "partner networks", "enabled": true}' +``` + +The `name` follows the same rules of `add-custom-blocklist`: allowlist and custom blocklist names share the same namespace. +The `url` must be `http` or `https`, max 512 chars, made only of `A-Za-z0-9._~:/?&=%+,@-` characters. +Credentials inside the URL (`https://user:pass@host/...`) are stored in plain text. + +Response example: +```json +{"name": "partners"} +``` + +It can raise the following validation errors: +- `invalid_name` if the name does not match `^[a-z][a-z0-9]{2,15}$` +- `reserved_name` if the name starts with `yoroi` or `nethesis`, or is `allowlist` or `blocklist` +- `name_already_present` if the name is already used by an allowlist or a blocklist +- `invalid_url` if the URL is not valid +- `url_already_present` if the URL is already in the list +- `required` for a missing or empty `url` or a missing `enabled`, `invalid` for a non-string `url` or a wrong `enabled` or `description` + +### edit-allowlist-url + +Edit a remote allowlist URL, the name can't be changed. The edit replaces the entry: `name`, `url` and `enabled` are required, an omitted `description` is removed: +``` +api-cli ns.threatshield edit-allowlist-url --data '{"name": "partners", "url": "https://example.com/allow.txt", "description": "partner networks", "enabled": false}' +``` + +Response example: +```json +{"message": "success"} +``` + +It can raise the same validation errors of `add-allowlist-url` except the `name` ones, plus: +- `allowlist_url_not_found` if the `name` does not exist +- `builtin_allowlist_url_not_editable` if the `name` is `nethesis` + +### delete-allowlist-url + +Delete a remote allowlist URL: +``` +api-cli ns.threatshield delete-allowlist-url --data '{"name": "partners"}' +``` + +Response example: +```json +{"message": "success"} +``` + +It can raise the following validation errors: +- `allowlist_url_not_found` if the `name` does not exist +- `builtin_allowlist_url_not_deletable` if the `name` is `nethesis` + +### add-custom-blocklist + +Add a custom blocklist, a plain list with one IP/CIDR per line: +``` +api-cli ns.threatshield add-custom-blocklist --data '{"name": "myfeed", "url_4": "https://example.com/v4.txt", "url_6": "", "chain": "in", "description": "my blocklist", "enabled": true}' +``` + +Fields: +- `name`: `^[a-z][a-z0-9]{2,15}$`, must not start with `yoroi` or `nethesis`, must not be `allowlist`, `blocklist` or a built-in feed name, shared with allowlist names +- `url_4`, `url_6`: IPv4 and IPv6 list URLs, at least one is required, same rules of `add-allowlist-url` +- `chain`: `in` (inbound), `out` (outbound) or `inout` (both), default `in` +- `description`: optional +- `enabled`: optional boolean, default `true`; adds or removes the feed from `ban_feed` like `edit-blocklist` + +Response example: +```json +{"name": "myfeed"} +``` + +It can raise the following validation errors: +- `invalid_name` if the name does not match `^[a-z][a-z0-9]{2,15}$` +- `reserved_name` if the name starts with `yoroi` or `nethesis`, or is `allowlist` or `blocklist` +- `name_already_present` if the name is already used +- `url_required` if both URLs are empty +- `invalid_url` if a URL is not valid +- `invalid` for a non-string `url_4` or `url_6`, or a wrong `chain`, `description` or `enabled` + +### edit-custom-blocklist + +Edit a custom blocklist, the name can't be changed: +``` +api-cli ns.threatshield edit-custom-blocklist --data '{"name": "myfeed", "url_4": "https://example.com/v4.txt", "url_6": "https://example.com/v6.txt", "chain": "inout", "description": "my blocklist", "enabled": false}' +``` + +The edit replaces the feed: an omitted `url_4`, `url_6` or `description` is removed and an omitted `chain` becomes `in`. If `enabled` is missing, the feed state is not changed. + +Response example: +```json +{"message": "success"} +``` + +It can raise the same validation errors of `add-custom-blocklist` except the `name` ones, plus: +- `custom_blocklist_not_found` if the name does not exist + +### delete-custom-blocklist + +Delete a custom blocklist and remove it from `ban_feed`: +``` +api-cli ns.threatshield delete-custom-blocklist --data '{"name": "myfeed"}' +``` + +Response example: +```json +{"message": "success"} +``` + +It can raise the following validation errors: +- `custom_blocklist_not_found` if the name does not exist + ### list-allowed List addresses always allowed: diff --git a/packages/ns-api/files/ns.dashboard b/packages/ns-api/files/ns.dashboard index 4a55a5a2f..0982c72d4 100644 --- a/packages/ns-api/files/ns.dashboard +++ b/packages/ns-api/files/ns.dashboard @@ -189,7 +189,8 @@ def check_banip(): def check_ts_ip(): u = EUci() bip_status = check_banip() - ts_enabled = "bl.nethesis.it" in u.get("banip", "global", "ban_allowurl", default="") + # threat shield IP is active on units with ns-plug credentials + ts_enabled = u.get("ns-plug", "config", "system_id", default="") != "" and u.get("ns-plug", "config", "secret", default="") != "" if not ts_enabled or bip_status == "disabled": return "disabled" if ts_enabled and bip_status == "ok": diff --git a/packages/ns-api/files/ns.threatshield b/packages/ns-api/files/ns.threatshield index e1dce350d..5219e9e93 100644 --- a/packages/ns-api/files/ns.threatshield +++ b/packages/ns-api/files/ns.threatshield @@ -10,6 +10,7 @@ import re import sys import json import urllib +import urllib.parse import urllib.request import urllib.error import ipaddress @@ -318,6 +319,55 @@ def list_feeds(): with open('/etc/banip/banip.feeds') as f: return json.loads(f.read()) +def get_custom_feeds(e_uci): + ret = {} + for name, s in (utils.get_all_by_type(e_uci, 'banip', 'ns_blockfeed') or {}).items(): + feed = {'rule': 'feed 1', 'chain': s.get('chain', 'in'), 'descr': s.get('description', '')} + for url in ('url_4', 'url_6'): + if s.get(url): + feed[url] = s.get(url) + ret[name] = feed + return ret + +def builtin_feeds(): + return set(read_json('/etc/banip/banip.feeds')) | set(read_json('/etc/banip/banip.nethesis.feeds')) + +def list_all_feeds(e_uci): + # the generated file is updated on commit: take custom feeds from UCI + builtin = builtin_feeds() + feeds = {k: v for k, v in list_feeds().items() if k in builtin} + feeds.update(get_custom_feeds(e_uci)) + return feeds + +def has_credentials(e_uci): + return e_uci.get('ns-plug', 'config', 'system_id', default='') != '' and e_uci.get('ns-plug', 'config', 'secret', default='') != '' + +def validate_url(payload, parameter, required=True): + url = payload.get(parameter, '') + if not isinstance(url, str): + raise ValidationError(parameter, 'invalid', url) + if url == '': + if required: + raise ValidationError(parameter, 'required') + return '' + # banIP expands URLs unquoted in shell: allow only safe characters + if len(url) > 512 or not re.fullmatch(r'https?://[A-Za-z0-9._~:/?&=%+,@-]+', url) or not urllib.parse.urlparse(url).hostname: + raise ValidationError(parameter, 'invalid_url', url) + return url + +def validate_string(payload, parameter): + value = payload.get(parameter, '') + if not isinstance(value, str) or len(value) > 128 or '\n' in value: + raise ValidationError(parameter, 'invalid', value) + return value + +def validate_bool(payload, parameter): + if parameter not in payload: + raise ValidationError(parameter, 'required') + if not isinstance(payload[parameter], bool): + raise ValidationError(parameter, 'invalid', payload[parameter]) + return payload[parameter] + def get_block_list(): return get_allow_list('/etc/banip/banip.blocklist') @@ -460,7 +510,8 @@ def get_countries_from_banip(e_uci): def list_blocklist(e_uci): ret = [] - feeds = list_feeds() + feeds = list_all_feeds(e_uci) + custom_feeds = get_custom_feeds(e_uci) has_bl = has_bl_entitlement(e_uci) try: enabled_feeds = list(e_uci.get_all('banip', 'global', 'ban_feed')) @@ -473,8 +524,10 @@ def list_blocklist(e_uci): continue feed = feeds[f] enabled = f in enabled_feeds + # ts-ip lets a custom list override a builtin feed with the same name + custom = f in custom_feeds - if 'nethesis' in feed.get('url_4'): + if not custom and 'nethesis' in (feed.get('url_4') or ''): type = 'enterprise' else: type = 'community' @@ -486,7 +539,11 @@ def list_blocklist(e_uci): protocols, ports = parse_feed_flag(feed.get('flag')) - ret.append({ 'name': f, 'type': type, 'enabled': enabled, 'confidence': get_confidence(f, type == 'enterprise'), 'description': feed.get('descr'), 'direction': feed.get('chain', 'in'), 'protocols': protocols, 'ports': ports}) + ret.append({ 'name': f, 'type': type, 'custom': custom, 'enabled': enabled, 'confidence': get_confidence(f, type == 'enterprise'), 'description': feed.get('descr'), 'direction': feed.get('chain', 'in'), 'protocols': protocols, 'ports': ports}) + if custom: + ret[-1].update({'url_4': feed.get('url_4', ''), 'url_6': feed.get('url_6', '')}) + # custom lists first, the rest keeps the feeds file order + ret.sort(key=lambda x: not x['custom']) return { "data": ret } def list_settings(e_uci): @@ -513,6 +570,11 @@ def list_settings(e_uci): } def edit_blocklist(e_uci, payload): + for param, ptype in (('blocklist', str), ('enabled', bool)): + if param not in payload: + raise ValidationError(param, 'required') + if not isinstance(payload[param], ptype): + raise ValidationError(param, 'invalid', payload[param]) try: enabled = list(e_uci.get_all('banip', 'global', 'ban_feed')) except: @@ -522,12 +584,109 @@ def edit_blocklist(e_uci, payload): if not payload['enabled'] and payload['blocklist'] in enabled: enabled.remove(payload['blocklist']) # cleanup invalid feeds - feeds = list_feeds() + feeds = list_all_feeds(e_uci) enabled = [feed for feed in enabled if feed in feeds] e_uci.set('banip', 'global', 'ban_feed', enabled) e_uci.save('banip') return {'message': 'success'} +# allowlist and blocklist names share the banip section namespace +def validate_list_name(e_uci, payload): + name = payload.get('name', '') + if not isinstance(name, str) or not re.fullmatch(r'[a-z][a-z0-9]{2,15}', name): + raise ValidationError('name', 'invalid_name', name) + if name.startswith(('yoroi', 'nethesis')) or name in ('allowlist', 'blocklist'): + raise ValidationError('name', 'reserved_name', name) + if name in builtin_feeds() or name in e_uci.get('banip'): + raise ValidationError('name', 'name_already_present', name) + return name + +def list_allowlist_urls(e_uci): + # built-in row: always listed, enabled only with a subscription + ret = [{'name': 'nethesis', 'builtin': True, 'url': '', 'description': 'Nethesis global allowlist', 'enabled': has_credentials(e_uci)}] + for sid, s in (utils.get_all_by_type(e_uci, 'banip', 'ns_allowurl') or {}).items(): + ret.append({'name': sid, 'builtin': False, 'url': s.get('url', ''), 'description': s.get('description', ''), 'enabled': s.get('enabled', '1') == '1'}) + return {'data': ret} + +def set_allowlist_url(e_uci, sid, payload): + url = validate_url(payload, 'url') + description = validate_string(payload, 'description') + enabled = validate_bool(payload, 'enabled') + for cur, s in (utils.get_all_by_type(e_uci, 'banip', 'ns_allowurl') or {}).items(): + if cur != sid and s.get('url') == url: + raise ValidationError('url', 'url_already_present', url) + e_uci.set('banip', sid, 'ns_allowurl') + e_uci.set('banip', sid, 'url', url) + e_uci.set('banip', sid, 'description', description) + e_uci.set('banip', sid, 'enabled', '1' if enabled else '0') + e_uci.save('banip') + +def add_allowlist_url(e_uci, payload): + name = validate_list_name(e_uci, payload) + set_allowlist_url(e_uci, name, payload) + return {'name': name} + +def check_section_exists(e_uci, stype, name, error): + # list/dict names are unhashable: report any non-string as not found + if not isinstance(name, str) or name not in (utils.get_all_by_type(e_uci, 'banip', stype) or {}): + raise ValidationError('name', error, name) + +def edit_allowlist_url(e_uci, payload): + sid = payload.get('name', '') + if sid == 'nethesis': + raise ValidationError('name', 'builtin_allowlist_url_not_editable', sid) + check_section_exists(e_uci, 'ns_allowurl', sid, 'allowlist_url_not_found') + set_allowlist_url(e_uci, sid, payload) + return {'message': 'success'} + +def delete_allowlist_url(e_uci, payload): + sid = payload.get('name', '') + if sid == 'nethesis': + raise ValidationError('name', 'builtin_allowlist_url_not_deletable', sid) + check_section_exists(e_uci, 'ns_allowurl', sid, 'allowlist_url_not_found') + e_uci.delete('banip', sid) + e_uci.save('banip') + return {'message': 'success'} + +def set_custom_blocklist(e_uci, name, payload): + url_4 = validate_url(payload, 'url_4', False) + url_6 = validate_url(payload, 'url_6', False) + if not url_4 and not url_6: + raise ValidationError('url_4', 'url_required') + chain = payload.get('chain', 'in') + if chain not in ('in', 'out', 'inout'): + raise ValidationError('chain', 'invalid', chain) + description = validate_string(payload, 'description') + e_uci.set('banip', name, 'ns_blockfeed') + e_uci.set('banip', name, 'url_4', url_4) + e_uci.set('banip', name, 'url_6', url_6) + e_uci.set('banip', name, 'chain', chain) + e_uci.set('banip', name, 'description', description) + e_uci.save('banip') + +def add_custom_blocklist(e_uci, payload): + name = validate_list_name(e_uci, payload) + enabled = validate_bool(payload, 'enabled') if 'enabled' in payload else True + set_custom_blocklist(e_uci, name, payload) + edit_blocklist(e_uci, {'blocklist': name, 'enabled': enabled}) + return {'name': name} + +def edit_custom_blocklist(e_uci, payload): + name = payload.get('name', '') + check_section_exists(e_uci, 'ns_blockfeed', name, 'custom_blocklist_not_found') + # enabled is optional on edit: keep the current state when missing + enabled = validate_bool(payload, 'enabled') if 'enabled' in payload else None + set_custom_blocklist(e_uci, name, payload) + if enabled is not None: + edit_blocklist(e_uci, {'blocklist': name, 'enabled': enabled}) + return {'message': 'success'} + +def delete_custom_blocklist(e_uci, payload): + name = payload.get('name', '') + check_section_exists(e_uci, 'ns_blockfeed', name, 'custom_blocklist_not_found') + e_uci.delete('banip', name) + return edit_blocklist(e_uci, {'blocklist': name, 'enabled': False}) + def set_default(e_uci, option, value): try: e_uci.get('banip', 'global', option) @@ -724,6 +883,11 @@ def dns_list_blocklist(e_uci): return { "data": ret } def dns_edit_blocklist(e_uci, payload): + for param, ptype in (('blocklist', str), ('enabled', bool)): + if param not in payload: + raise ValidationError(param, 'required') + if not isinstance(payload[param], ptype): + raise ValidationError(param, 'invalid', payload[param]) try: enabled = list(e_uci.get_all('adblock', 'global', 'adb_feed')) except: @@ -1060,6 +1224,13 @@ if cmd == 'list': print(json.dumps({ 'list-blocklist': {}, 'edit-blocklist': { "blocklist": "blocklist_name", "enabled": True }, + 'list-allowlist-urls': {}, + 'add-allowlist-url': {'name': 'myallow', 'url': 'https://example.com/allow.txt', 'description': 'optional', 'enabled': True}, + 'edit-allowlist-url': {'name': 'myallow', 'url': 'https://example.com/allow.txt', 'description': 'optional', 'enabled': True}, + 'delete-allowlist-url': {'name': 'myallow'}, + 'add-custom-blocklist': {'name': 'myfeed', 'url_4': 'https://example.com/v4.txt', 'url_6': '', 'chain': 'in', 'description': 'optional', 'enabled': True}, + 'edit-custom-blocklist': {'name': 'myfeed', 'url_4': 'https://example.com/v4.txt', 'url_6': '', 'chain': 'in', 'description': 'optional', 'enabled': True}, + 'delete-custom-blocklist': {'name': 'myfeed'}, 'list-settings': {}, 'edit-settings': { 'enabled': True, @@ -1112,6 +1283,26 @@ elif cmd == 'call': elif action == 'edit-blocklist': payload = json.loads(sys.stdin.read()) ret = edit_blocklist(e_uci, payload) + elif action == 'list-allowlist-urls': + ret = list_allowlist_urls(e_uci) + elif action == 'add-allowlist-url': + payload = json.loads(sys.stdin.read()) + ret = add_allowlist_url(e_uci, payload) + elif action == 'edit-allowlist-url': + payload = json.loads(sys.stdin.read()) + ret = edit_allowlist_url(e_uci, payload) + elif action == 'delete-allowlist-url': + payload = json.loads(sys.stdin.read()) + ret = delete_allowlist_url(e_uci, payload) + elif action == 'add-custom-blocklist': + payload = json.loads(sys.stdin.read()) + ret = add_custom_blocklist(e_uci, payload) + elif action == 'edit-custom-blocklist': + payload = json.loads(sys.stdin.read()) + ret = edit_custom_blocklist(e_uci, payload) + elif action == 'delete-custom-blocklist': + payload = json.loads(sys.stdin.read()) + ret = delete_custom_blocklist(e_uci, payload) elif action == 'list-settings': ret = list_settings(e_uci) elif action == 'edit-settings': diff --git a/packages/ns-api/openapi.yml b/packages/ns-api/openapi.yml index cef18dc97..245a2b4b4 100644 --- a/packages/ns-api/openapi.yml +++ b/packages/ns-api/openapi.yml @@ -102,6 +102,58 @@ components: description: Optional free-form description associated with the domain example: my allow1 + ThreatShieldAllowlistUrl: + type: object + required: [name, builtin, url, description, enabled] + properties: + name: + type: string + description: UCI section name, `nethesis` for the built-in Nethesis allowlist + example: partners + builtin: + type: boolean + description: True for the Nethesis allowlist, read-only and enabled only on units with ns-plug credentials + example: false + url: + type: string + description: Remote IP list URL, empty for the built-in row + example: https://example.com/allow.txt + description: + type: string + example: partner networks + enabled: + type: boolean + example: true + + ThreatShieldCustomBlocklist: + type: object + required: [name] + properties: + name: + type: string + description: Feed name, `^[a-z][a-z0-9]{2,15}$`, not starting with yoroi or nethesis, not a built-in feed name + example: myfeed + url_4: + type: string + description: IPv4 list URL, one IP/CIDR per line (at least one of url_4 or url_6 is required) + example: https://example.com/v4.txt + url_6: + type: string + description: IPv6 list URL, one IP/CIDR per line + example: "" + chain: + type: string + enum: [in, out, inout] + description: Defaults to `in` when omitted + example: in + description: + type: string + example: my blocklist + enabled: + type: boolean + description: Add the feed to ban_feed; defaults to true on add, unchanged on edit when missing + example: true + securitySchemes: BearerAuth: type: http @@ -747,3 +799,209 @@ paths: example: success - $ref: "#/components/schemas/ValidationError" - $ref: "#/components/schemas/Error" + POST /ubus/ns.threatshield/list-allowlist-urls: + post: + summary: List banIP remote allowlist URLs, including the built-in Nethesis allowlist + operationId: ns.threatshield.list-allowlist-urls + tags: + - threatshield + responses: + "200": + description: Result + content: + application/json: + schema: + oneOf: + - type: object + required: [data] + properties: + data: + type: array + items: + $ref: "#/components/schemas/ThreatShieldAllowlistUrl" + - $ref: "#/components/schemas/ValidationError" + - $ref: "#/components/schemas/Error" + POST /ubus/ns.threatshield/add-allowlist-url: + post: + summary: Add a banIP remote allowlist URL + operationId: ns.threatshield.add-allowlist-url + tags: + - threatshield + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [name, url, enabled] + properties: + name: + type: string + description: Allowlist name, same rules of custom blocklist names, which share the same namespace + example: partners + url: + type: string + description: http(s) URL, max 512 chars, only `A-Za-z0-9._~:/?&=%+,@-` characters + example: https://example.com/allow.txt + description: + type: string + description: Optional, defaults to empty + example: partner networks + enabled: + type: boolean + example: true + responses: + "200": + description: Result + content: + application/json: + schema: + oneOf: + - type: object + required: [name] + properties: + name: + type: string + example: partners + - $ref: "#/components/schemas/ValidationError" + - $ref: "#/components/schemas/Error" + POST /ubus/ns.threatshield/edit-allowlist-url: + post: + summary: Replace a banIP remote allowlist URL (the Nethesis allowlist cannot be edited); omitted description is removed + operationId: ns.threatshield.edit-allowlist-url + tags: + - threatshield + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [name, url, enabled] + properties: + name: + type: string + description: Allowlist name (not editable) + example: partners + url: + type: string + example: https://example.com/allow.txt + description: + type: string + example: partner networks + enabled: + type: boolean + example: true + responses: + "200": + description: Result + content: + application/json: + schema: + oneOf: + - $ref: "#/components/schemas/SuccessResponse" + - $ref: "#/components/schemas/ValidationError" + - $ref: "#/components/schemas/Error" + POST /ubus/ns.threatshield/delete-allowlist-url: + post: + summary: Delete a banIP remote allowlist URL (the Nethesis allowlist cannot be deleted) + operationId: ns.threatshield.delete-allowlist-url + tags: + - threatshield + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [name] + properties: + name: + type: string + example: partners + responses: + "200": + description: Result + content: + application/json: + schema: + oneOf: + - $ref: "#/components/schemas/SuccessResponse" + - $ref: "#/components/schemas/ValidationError" + - $ref: "#/components/schemas/Error" + POST /ubus/ns.threatshield/add-custom-blocklist: + post: + summary: Add a custom banIP blocklist, enabled by default + operationId: ns.threatshield.add-custom-blocklist + tags: + - threatshield + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/ThreatShieldCustomBlocklist" + responses: + "200": + description: Result + content: + application/json: + schema: + oneOf: + - type: object + required: [name] + properties: + name: + type: string + example: myfeed + - $ref: "#/components/schemas/ValidationError" + - $ref: "#/components/schemas/Error" + POST /ubus/ns.threatshield/edit-custom-blocklist: + post: + summary: Replace a custom banIP blocklist (name is not renamable); omitted fields are reset (chain to `in`), omitted enabled keeps the feed state + operationId: ns.threatshield.edit-custom-blocklist + tags: + - threatshield + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/ThreatShieldCustomBlocklist" + responses: + "200": + description: Result + content: + application/json: + schema: + oneOf: + - $ref: "#/components/schemas/SuccessResponse" + - $ref: "#/components/schemas/ValidationError" + - $ref: "#/components/schemas/Error" + POST /ubus/ns.threatshield/delete-custom-blocklist: + post: + summary: Delete a custom banIP blocklist and remove it from ban_feed + operationId: ns.threatshield.delete-custom-blocklist + tags: + - threatshield + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [name] + properties: + name: + type: string + example: myfeed + responses: + "200": + description: Result + content: + application/json: + schema: + oneOf: + - $ref: "#/components/schemas/SuccessResponse" + - $ref: "#/components/schemas/ValidationError" + - $ref: "#/components/schemas/Error" From 0a7160fe34fb2c03f0bf8d0e3d6e494d80a5e49b Mon Sep 17 00:00:00 2001 From: Giacomo Sanchietti Date: Wed, 11 Nov 2026 08:27:51 +0100 Subject: [PATCH 38/51] feat(threat_shield): build banIP lists from UCI ts-ip rebuilds ban_allowurl and banip.custom.feeds from the ns_allowurl and ns_blockfeed sections. Legacy ban_allowurl entries are moved once to ns_allowurl sections, also on upgrade. The post-commit hook runs ts-ip and drops the banIP backups of lists whose URL changed; ts-fail2ban runs once per commit. On upgrade the feed copy is refreshed without starting fail2ban. Refs #2005 Assisted-by: Claude Code:claude-opus-5-5 --- packages/ns-threat_shield/Makefile | 2 + packages/ns-threat_shield/README.md | 26 ++++++ .../files/97-nethsec-banip-feeds | 13 ++- .../ns-threat_shield/files/adjust-banip.py | 28 ++++-- .../ns-threat_shield/files/adjust-fail2ban.py | 3 +- .../files/banip-insights-defaults | 2 +- .../files/ts-allowurl-migrate | 27 ++++++ packages/ns-threat_shield/files/ts-ip | 89 ++++++++++++++----- 8 files changed, 152 insertions(+), 38 deletions(-) create mode 100755 packages/ns-threat_shield/files/ts-allowurl-migrate diff --git a/packages/ns-threat_shield/Makefile b/packages/ns-threat_shield/Makefile index 548388c38..99ad0c05b 100644 --- a/packages/ns-threat_shield/Makefile +++ b/packages/ns-threat_shield/Makefile @@ -67,6 +67,8 @@ define Package/ns-threat_shield/install $(INSTALL_BIN) ./files/banip-defaults $(1)/etc/uci-defaults/99-nethsec-banip $(INSTALL_BIN) ./files/99-nethsec-fail2ban $(1)/etc/uci-defaults/99-nethsec-fail2ban $(INSTALL_BIN) ./files/banip-extra-defaults $(1)/etc/uci-defaults/96-nethsec-banip-extra + $(INSTALL_BIN) ./files/ts-allowurl-migrate $(1)/usr/libexec/ts-allowurl-migrate + $(INSTALL_BIN) ./files/ts-allowurl-migrate $(1)/etc/uci-defaults/97-nethsec-banip-allowurl $(INSTALL_BIN) ./files/97-nethsec-banip-feeds $(1)/etc/uci-defaults/97-nethsec-banip-feeds $(INSTALL_BIN) ./files/banip-insights-defaults $(1)/etc/uci-defaults/98-nethsec-banip-insights $(INSTALL_BIN) ./files/35_ns-threat_shield $(1)/etc/uci-defaults/35_ns-threat_shield diff --git a/packages/ns-threat_shield/README.md b/packages/ns-threat_shield/README.md index 5ab5fa987..e09ff1f9d 100644 --- a/packages/ns-threat_shield/README.md +++ b/packages/ns-threat_shield/README.md @@ -31,6 +31,32 @@ Blocks are counted from the banIP kernel log lines in Victoria Logs, not from me `ns.controller dump-ts-malware` do; blocks per feed in the last hour: `app_name:kernel "banIP/" | extract "banIP///: " | filter feed:* | stats by (feed) count() blocked` +### Custom allowlists and blocklists + +`ts-ip` owns `banip.global.ban_allowurl` and `/etc/banip/banip.custom.feeds` and rebuilds them from UCI. +With ns-plug credentials the Nethesis allowlist URL is always the first `ban_allowurl` entry: it can't be disabled and it is never stored in UCI, because the credentials rotate. + +| UCI (`banip`) | options | effect | +|---|---|---| +| `config ns_allowurl ''` | `url`, `description`, `enabled` | enabled URLs added to `ban_allowurl` | +| `config ns_blockfeed ''` | `url_4`, `url_6`, `chain` (`in`, `out`, `inout`), `description` | feed added to `banip.custom.feeds` with `"rule": "feed 1"` (one IP/CIDR per line); enabled when `` is in `global.ban_feed` | + +`banip.custom.feeds` content: + +| ns-plug credentials | custom feeds | file | +|---|---|---| +| yes | any | `banip.feeds` + `banip.nethesis.feeds` + custom feeds | +| no | yes | `banip.feeds` + custom feeds | +| no | no | empty, banip uses `banip.feeds` | + +- custom feed names must not start with `yoroi` or `nethesis`: those names are removed from `ban_feed` on units without credentials +- allowlist names follow the custom blocklist name rules and share the same namespace (banip section names) +- `banip.custom.feeds` is replaced only by a complete and changed file: banip removes from `ban_feed` the feeds missing from it +- a non-empty `banip.custom.feeds` holds copies of `banip.feeds` (and `banip.nethesis.feeds` when registered), which banip then ignores: uci-defaults `95-banip-housekeeping` (banip upgrade) and `97-nethsec-banip-feeds` (ns-threat_shield upgrade) refresh it with `ts-ip --no-start` (no fail2ban restart) +- the `adjust-banip.py` post-commit hook runs `ts-ip` before restarting banip when `banip` changes, and removes from `/tmp/banIP-backup` the backups of the changed lists (`banIP.allowlist.gz`, `banIP..v4.gz`, `banIP..v6.gz`): banip start restores backups instead of downloading +- when `global.ns_allowurl_migrated` is not `1`, `ts-allowurl-migrate` (run on install/upgrade as uci-defaults `97-nethsec-banip-allowurl`, and by every `ts-ip` run, so a restored old backup is migrated on the next banip commit or register/unregister) moves the non-Nethesis `ban_allowurl` entries into `ns_allowurl` sections named `allow` and sets it +- APIs: `ns.threatshield` `*-allowlist-url(s)`, `*-custom-blocklist` and `list-blocklist`, see [ns-api](../ns-api/README.md#nsthreatshield) + ### Examples #### Start the service diff --git a/packages/ns-threat_shield/files/97-nethsec-banip-feeds b/packages/ns-threat_shield/files/97-nethsec-banip-feeds index 3a68fa012..42c85dcb7 100644 --- a/packages/ns-threat_shield/files/97-nethsec-banip-feeds +++ b/packages/ns-threat_shield/files/97-nethsec-banip-feeds @@ -5,16 +5,13 @@ # SPDX-License-Identifier: GPL-2.0-only # -# Rebuild the enterprise feeds left in the banIP 1.0 format (rule_4) by an upgrade. -# apk can install banip before ns-threat_shield: 95-banip-housekeeping then runs ts-ip -# with the old banip.nethesis.feeds, and banIP skips the enterprise feeds as incomplete. -# If banip.feeds is still in the old format banip is not updated yet, and its own -# housekeeping rebuilds the file later. -# The postinst reloads banIP after all the uci-defaults. +# Rebuild a non-empty banip.custom.feeds after an upgrade: it holds copies of banip.feeds (and banip.nethesis.feeds +# when registered), banIP reads only it. With banip.feeds still in the old format (rule_4) banip is not +# updated yet and its housekeeping rebuilds it later; the postinst reloads banIP after all the uci-defaults. -grep -q '"rule_4"' /etc/banip/banip.custom.feeds 2>/dev/null || exit 0 +[ -s /etc/banip/banip.custom.feeds ] || exit 0 grep -q '"rule_4"' /etc/banip/banip.feeds && exit 0 -/usr/sbin/ts-ip +/usr/sbin/ts-ip --no-start exit 0 diff --git a/packages/ns-threat_shield/files/adjust-banip.py b/packages/ns-threat_shield/files/adjust-banip.py index 8dc17825e..fe7bda953 100755 --- a/packages/ns-threat_shield/files/adjust-banip.py +++ b/packages/ns-threat_shield/files/adjust-banip.py @@ -14,13 +14,31 @@ # The changes variable is already within the scope from the caller if 'banip' in changes or 'network' in changes: + # banIP start restores lists from backups: drop the changed ones to force a download + stale = [] + # if ban_country property was modified, remove stale backup files to prevent old country selections from being restored if 'banip' in changes and any('ban_country' in op for op in changes['banip']): - for backup_file in ['/tmp/banIP-backup/banIP.country.v4.gz', '/tmp/banIP-backup/banIP.country.v6.gz']: - try: - os.remove(backup_file) - except FileNotFoundError: - pass + stale += ['country.v4', 'country.v6'] + + # rebuild custom feeds and ban_allowurl from UCI before banIP (re)starts + if 'banip' in changes: + allow_before = EUci().get('banip', 'global', 'ban_allowurl', list=True, default=[]) + subprocess.run(["/usr/sbin/ts-ip"]) + # new instance: EUci caches loaded configs and would miss what ts-ip committed + uci = EUci() + if allow_before != uci.get('banip', 'global', 'ban_allowurl', list=True, default=[]): + stale.append('allowlist') + for op in changes['banip']: + # ns_blockfeed sections whose url_4/url_6 changed: drop that family's backup + if len(op) > 2 and op[0] == 'set' and op[2] in ('url_4', 'url_6') and str(op[1]).isalnum() and uci.get('banip', op[1], default='') == 'ns_blockfeed': + stale.append(f'{op[1]}.v{op[2][-1]}') + + for name in stale: + try: + os.remove(f'/tmp/banIP-backup/banIP.{name}.gz') + except FileNotFoundError: + pass uci = EUci() enabled = uci.get('banip', 'global', 'ban_enabled', default='0') diff --git a/packages/ns-threat_shield/files/adjust-fail2ban.py b/packages/ns-threat_shield/files/adjust-fail2ban.py index 41b6d9525..04433bb39 100755 --- a/packages/ns-threat_shield/files/adjust-fail2ban.py +++ b/packages/ns-threat_shield/files/adjust-fail2ban.py @@ -9,5 +9,6 @@ import subprocess # `changes` is injected by ns.commit when the hook is exec'd -if changes.keys() & {"banip", "network", "firewall"}: # noqa: F821 +# banip changes are covered by adjust-banip.py, whose ts-ip run ends with ts-fail2ban +if changes.keys() & {"network", "firewall"}: # noqa: F821 subprocess.run(["/usr/libexec/ts-fail2ban"]) diff --git a/packages/ns-threat_shield/files/banip-insights-defaults b/packages/ns-threat_shield/files/banip-insights-defaults index 20331dc65..b6621e4dc 100755 --- a/packages/ns-threat_shield/files/banip-insights-defaults +++ b/packages/ns-threat_shield/files/banip-insights-defaults @@ -11,4 +11,4 @@ [ -n "$(uci -q get ns-plug.config.secret)" ] || exit 0 grep -q nethesisinsightslvl2 /etc/banip/banip.custom.feeds 2>/dev/null && exit 0 -/usr/sbin/ts-ip +/usr/sbin/ts-ip --no-start diff --git a/packages/ns-threat_shield/files/ts-allowurl-migrate b/packages/ns-threat_shield/files/ts-allowurl-migrate new file mode 100755 index 000000000..eadc80987 --- /dev/null +++ b/packages/ns-threat_shield/files/ts-allowurl-migrate @@ -0,0 +1,27 @@ +#!/bin/sh + +# +# Copyright (C) 2026 Nethesis S.r.l. +# SPDX-License-Identifier: GPL-2.0-only +# + +# One-shot: move custom ban_allowurl entries to ns_allowurl sections; run as uci-defaults and by ts-ip (restored old backups) + +# URLs are expanded unquoted: no globbing +set -f + +if [ "$(uci -q get banip.global.ns_allowurl_migrated)" != "1" ]; then + n=1 + for url in $(uci -q get banip.global.ban_allowurl); do + case "$url" in + *bl.nethesis.it*) continue ;; + esac + uci -q show banip | grep -qF ".url='$url'" && continue + while uci -q get banip.allow$n >/dev/null; do n=$((n + 1)); done + uci set banip.allow$n=ns_allowurl + uci set banip.allow$n.url="$url" + uci set banip.allow$n.enabled=1 + done + uci set banip.global.ns_allowurl_migrated=1 + uci commit banip +fi diff --git a/packages/ns-threat_shield/files/ts-ip b/packages/ns-threat_shield/files/ts-ip index 6cac0d05c..a4d54f156 100755 --- a/packages/ns-threat_shield/files/ts-ip +++ b/packages/ns-threat_shield/files/ts-ip @@ -11,7 +11,12 @@ . /lib/functions.sh +# URLs are expanded unquoted: no globbing +set -f + keep='' +custom='{}' +allow='' handle_blocklist() { # preserve only non-enteprise lists @@ -20,6 +25,32 @@ handle_blocklist() { fi } +# custom blocklist: plain IP/CIDR list, one per line +handle_blockfeed() { + local url_4 url_6 chain description + config_get url_4 "$1" url_4 + config_get url_6 "$1" url_6 + config_get chain "$1" chain in + config_get description "$1" description + custom=$(printf '%s' "$custom" | jq -c --arg n "$1" --arg u4 "$url_4" --arg u6 "$url_6" --arg c "$chain" --arg d "$description" \ + '.[$n] = ({rule: "feed 1", chain: $c, descr: $d} + (if $u4 != "" then {url_4: $u4} else {} end) + (if $u6 != "" then {url_6: $u6} else {} end))') +} + +handle_allowurl() { + local url enabled + config_get url "$1" url + config_get_bool enabled "$1" enabled 1 + [ "$enabled" = "1" ] && [ -n "$url" ] && allow="$allow $url" +} + + +# replace the feeds file only with a complete and changed one: banIP drops ban_feed names missing from it +update_feeds() { + if [ "$1" = "0" ] && [ -s "$FEEDS_TMP" ] && ! cmp -s "$FEEDS_TMP" "$FEEDS"; then + mv -f "$FEEDS_TMP" "$FEEDS" + fi + rm -f "$FEEDS_TMP" +} function exit_error { >&2 echo "[ERROR] $@" @@ -28,42 +59,53 @@ function exit_error { INSIGHTS_SENDER=/usr/sbin/send-insights-blocklist INSIGHTS_HOOK=/usr/libexec/ts-insights-hook +FEEDS=/etc/banip/banip.custom.feeds +FEEDS_TMP=/etc/banip/banip.custom.feeds.tmp SYSTEM_SECRET=$(uci -q get ns-plug.config.secret) SYSTEM_ID=$(uci -q get ns-plug.config.system_id) TYPE=$(uci -q get ns-plug.config.type) +# migrate custom ban_allowurl entries first, a restored old backup is migrated again +/usr/libexec/ts-allowurl-migrate + +# ts-ip owns ban_allowurl: the Nethesis allowlist (credentials rotate, never stored) plus enabled custom URLs; +# Nethesis first, banIP stops at the first failed download +if [ ! -z "$SYSTEM_SECRET" ] && [ ! -z "$SYSTEM_ID" ]; then + allow="https://$SYSTEM_ID:$SYSTEM_SECRET@bl.nethesis.it/plain/$TYPE/nethesis-blacklists/whitelist.global" +fi +config_load banip +config_foreach handle_blockfeed ns_blockfeed +config_foreach handle_allowurl ns_allowurl +if [ "$(echo $allow)" != "$(uci -q get banip.global.ban_allowurl)" ]; then + uci -q delete banip.global.ban_allowurl + for url in $allow; do + uci add_list banip.global.ban_allowurl="$url" + done + uci commit banip +fi + if [ ! -z "$SYSTEM_SECRET" ] && [ ! -z "$SYSTEM_ID" ]; then jq -s '.[0] * .[1]' /etc/banip/banip.nethesis.feeds /etc/banip/banip.feeds \ - | sed -e "s/__USER__/$SYSTEM_ID/" -e "s/__PASSWORD__/$SYSTEM_SECRET/" -e "s/__TYPE__/$TYPE/" > /etc/banip/banip.custom.feeds - # The credentials are part of the URL, so an entry written before a key - # rotation keeps fetching as the old pair. Enforce one entry, the current - # one: compare the whole set, and del_list per entry (a multi-line value - # matches nothing). - allow_current="https://$SYSTEM_ID:$SYSTEM_SECRET@bl.nethesis.it/plain/$TYPE/nethesis-blacklists/whitelist.global" - allow_have=$(uci -q get banip.global.ban_allowurl | tr " " "\n" | grep bl.nethesis.it) - if [ "$allow_have" != "$allow_current" ]; then - for allow_stale in $allow_have; do - uci del_list banip.global.ban_allowurl="$allow_stale" - done - uci add_list banip.global.ban_allowurl="$allow_current" - uci commit banip - fi + | sed -e "s/__USER__/$SYSTEM_ID/" -e "s/__PASSWORD__/$SYSTEM_SECRET/" -e "s/__TYPE__/$TYPE/" \ + | jq --argjson c "$custom" '. + $c' > "$FEEDS_TMP" + update_feeds $? else - allow=$(uci -q get banip.global.ban_allowurl | tr " " "\n" | grep bl.nethesis.it) - if [ "$allow" != "" ]; then - # cleanup allowlist - uci del_list banip.global.ban_allowurl="$allow" - # remove premium blocklist - config_load banip - config_list_foreach global ban_feed handle_blocklist + # remove premium blocklist + config_list_foreach global ban_feed handle_blocklist + if [ "$(echo $keep)" != "$(uci -q get banip.global.ban_feed)" ]; then uci -q delete banip.global.ban_feed for k in $keep; do uci add_list banip.global.ban_feed=$k done uci commit banip fi - > /etc/banip/banip.custom.feeds + if [ "$custom" = "{}" ]; then + > /etc/banip/banip.custom.feeds + else + jq --argjson c "$custom" '. + $c' /etc/banip/banip.feeds > "$FEEDS_TMP" + update_feeds $? + fi # the Insights feed is removed with the other enterprise feeds, ts-insights-hook stops reporting; # remove the banip block hook and the sender cron job left by older releases, a custom hook is left untouched if [ "$(uci -q get banip.global.ban_blockhook)" = "$INSIGHTS_HOOK" ]; then @@ -75,4 +117,5 @@ else fi fi -/usr/libexec/ts-fail2ban +# uci-defaults pass --no-start: no fail2ban (re)start during upgrades, rsyslog is down at first boot +/usr/libexec/ts-fail2ban "$@" From f59eebca33953ebdeee8261c0032481c362f0027 Mon Sep 17 00:00:00 2001 From: Giacomo Sanchietti Date: Wed, 11 Nov 2026 08:27:51 +0100 Subject: [PATCH 39/51] fix(banip): refresh custom feeds on upgrade A non-empty banip.custom.feeds holds a copy of banip.feeds and banIP reads only that file, so rerun ts-ip after a banip upgrade to pick up new or changed upstream feeds. Refs #2005 Assisted-by: Claude Code:claude-opus-5-5 --- packages/banip/files/95-banip-housekeeping | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/banip/files/95-banip-housekeeping b/packages/banip/files/95-banip-housekeeping index 8cfc3b7ca..bbfd38d76 100644 --- a/packages/banip/files/95-banip-housekeeping +++ b/packages/banip/files/95-banip-housekeeping @@ -39,6 +39,9 @@ if grep -q '"rule_4"' "${custom_feed}"; then mv -f "${custom_feed}" "${custom_feed}.backup.$(date "+%Y%m%d%H%M%S")" : > "${custom_feed}" # rebuild the Nethesis enterprise feeds before banip is started by postinst - /usr/sbin/ts-ip + /usr/sbin/ts-ip --no-start +elif [ -s "${custom_feed}" ]; then + # ts-ip merges a copy of banip.feeds into the custom feeds: refresh it from the new banip.feeds + /usr/sbin/ts-ip --no-start fi exit 0 From 755af96fe60d442a58e94dd1e0c4aef2fe773bb7 Mon Sep 17 00:00:00 2001 From: Tommaso Bailetti Date: Thu, 12 Nov 2026 10:34:35 +0100 Subject: [PATCH 40/51] refactor(logs): now all logs pass through our transformation layer (#2011) --- AGENTS.md | 1 + packages/ns-openvpn/Makefile | 4 +-- ...-victoria-logs.conf => rsyslog-rules.conf} | 0 packages/ns-plug/files/ns-plug | 2 +- packages/rsyslog/Makefile | 2 ++ packages/rsyslog/files/rsyslog.init | 12 +++++--- packages/rsyslog/files/rules.conf | 30 +++++++++++++++++++ packages/telegraf/Makefile | 4 +-- ...-victoria-logs.conf => rsyslog-rules.conf} | 0 packages/victoria-logs/Makefile | 4 +-- ...ictoria-logs.d.conf => rsyslog-rules.conf} | 0 .../files/rsyslog-victoria-logs.conf | 25 ++-------------- packages/victoria-metrics/Makefile | 4 +-- ...-victoria-logs.conf => rsyslog-rules.conf} | 0 14 files changed, 53 insertions(+), 35 deletions(-) rename packages/ns-openvpn/files/{rsyslog-victoria-logs.conf => rsyslog-rules.conf} (100%) create mode 100644 packages/rsyslog/files/rules.conf rename packages/telegraf/files/{rsyslog-victoria-logs.conf => rsyslog-rules.conf} (100%) rename packages/victoria-logs/files/{rsyslog-victoria-logs.d.conf => rsyslog-rules.conf} (100%) rename packages/victoria-metrics/files/{rsyslog-victoria-logs.conf => rsyslog-rules.conf} (100%) diff --git a/AGENTS.md b/AGENTS.md index 321b0ef44..9fa1a8391 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -59,6 +59,7 @@ recent host Ruby (4.x), so the site is built in a `ruby:3.3` container and the - `files/` is the rootfs overlay for the final image. `files/etc/uci-defaults` holds first-boot defaults. - Runtime web stack: **nginx** serves `ns-ui` from `/www-ns` and proxies `/api/` → **ns-api-server** on `127.0.0.1:8090`; `ns-api-server` handles auth/JWT and forwards calls to ubus/rpcd handlers. - System monitoring alerts, including HA alerts, follow the Telegraf → Victoria Metrics/vmalert -> Mimir. +- Every syslog line is cleaned up once by `/etc/rsyslog.d/rules.conf` (rsyslog package) before any output: app without version, trimmed message, and the hostname fixed to UCI `system.hostname` by `rsyslog.init`, never the DNS-resolved FQDN. Packages ship their own rules in `/etc/rsyslog.d/rules.d/.conf` to change `$.app`, `$.msg`, `$.sev` or set `$.drop`, and every output (log files, forwarders, controller, Victoria Logs) uses the `ns-file`, `ns-rfc3164` or `ns-rfc5424` template built from those fields. The cleanup runs before `/etc/rsyslog.conf` too, and file and forward actions without a template default to `ns-file` and `ns-rfc3164`, so custom rules get clean logs as well. Selectors still filter on the original severity. - Many local packages are thin wrappers around upstream code. When changing behavior in one of those areas, inspect the matching upstream repo first and treat the local package as integration glue. --- diff --git a/packages/ns-openvpn/Makefile b/packages/ns-openvpn/Makefile index bcf4f92e3..ac9ac57f3 100644 --- a/packages/ns-openvpn/Makefile +++ b/packages/ns-openvpn/Makefile @@ -67,8 +67,8 @@ define Package/ns-openvpn/install $(INSTALL_BIN) ./files/99_ns-openvpn-allow-deprecated-static-crypto $(1)/etc/uci-defaults $(INSTALL_BIN) ./files/openvpn-status $(1)/usr/bin $(INSTALL_BIN) ./files/openvpn-kill $(1)/usr/bin - $(INSTALL_DIR) $(1)/etc/rsyslog.d/victoria-logs.d - $(INSTALL_DATA) ./files/rsyslog-victoria-logs.conf $(1)/etc/rsyslog.d/victoria-logs.d/ns-openvpn.conf + $(INSTALL_DIR) $(1)/etc/rsyslog.d/rules.d + $(INSTALL_DATA) ./files/rsyslog-rules.conf $(1)/etc/rsyslog.d/rules.d/ns-openvpn.conf endef define Package/ns-openvpn/prerm diff --git a/packages/ns-openvpn/files/rsyslog-victoria-logs.conf b/packages/ns-openvpn/files/rsyslog-rules.conf similarity index 100% rename from packages/ns-openvpn/files/rsyslog-victoria-logs.conf rename to packages/ns-openvpn/files/rsyslog-rules.conf diff --git a/packages/ns-plug/files/ns-plug b/packages/ns-plug/files/ns-plug index c3c072d9b..e6693cdc8 100755 --- a/packages/ns-plug/files/ns-plug +++ b/packages/ns-plug/files/ns-plug @@ -159,7 +159,7 @@ ruleset(name="forward") { port="$(echo "$response" | jq -r .data.promtail_port)" protocol="tcp" TCP_Framing="octet-counted" - Template="RSYSLOG_SyslogProtocol23Format" + Template="ns-rfc5424" KeepAlive="on" KeepAlive.Probes="3" diff --git a/packages/rsyslog/Makefile b/packages/rsyslog/Makefile index 78c437486..74c4296fc 100644 --- a/packages/rsyslog/Makefile +++ b/packages/rsyslog/Makefile @@ -70,6 +70,8 @@ define Package/rsyslog/install $(CP) $(PKG_INSTALL_DIR)/usr/lib/rsyslog/* $(1)/usr/lib/rsyslog/ $(INSTALL_DIR) $(1)/etc $(INSTALL_CONF) ./files/rsyslog.conf $(1)/etc + $(INSTALL_DIR) $(1)/etc/rsyslog.d/rules.d + $(INSTALL_DATA) ./files/rules.conf $(1)/etc/rsyslog.d/rules.conf $(INSTALL_DIR) $(1)/etc/init.d $(INSTALL_BIN) ./files/rsyslog.init $(1)/etc/init.d/rsyslog $(INSTALL_DIR) $(1)/etc/uci-defaults diff --git a/packages/rsyslog/files/rsyslog.init b/packages/rsyslog/files/rsyslog.init index bb67ed39a..0b5fc8573 100644 --- a/packages/rsyslog/files/rsyslog.init +++ b/packages/rsyslog/files/rsyslog.init @@ -48,7 +48,7 @@ handle_forwarder() { config_get rfc "${config}" rfc "3164" if [ "$rfc" = "5424" ]; then - opts='Template="RSYSLOG_SyslogProtocol23Format" TCP_Framing="octet-counted"' + opts='Template="ns-rfc5424" TCP_Framing="octet-counted"' fi if [ "${src}" != "" ] && [ "${target}" != "" ]; then @@ -85,13 +85,18 @@ expand_config() { input_u="input(type=\"imudp\" port=\"${udp_port}\" address=\"${udp_addr}\")" fi - config_get template syslog default_template config_foreach handle_selector selector config_foreach handle_forwarder forwarder mkdir -p "$(dirname ${CONFIG_FILE})" # shellcheck disable=SC2188 > ${CONFIG_FILE} + # the configured hostname, rsyslog would otherwise use the FQDN only if DNS answered when it started + echo "global(localHostname=\"$(uci -q get system.@system[0].hostname)\")" >> ${CONFIG_FILE} + # cleanup and default templates first, so custom rules in the base config get clean logs too + echo "include(file=\"/etc/rsyslog.d/rules.conf\")" >> ${CONFIG_FILE} + echo "module(load=\"builtin:omfile\" template=\"ns-file\")" >> ${CONFIG_FILE} + echo "module(load=\"builtin:omfwd\" template=\"ns-rfc3164\")" >> ${CONFIG_FILE} echo "include(file=\"${BASE_CONFIG_FILE}\" mode=\"optional\")" >> ${CONFIG_FILE} for m in ${modules}; do if [ "${m}" = "imklog" ]; then @@ -103,7 +108,6 @@ expand_config() { done echo "${input_t}" >> ${CONFIG_FILE} echo "${input_u}" >> ${CONFIG_FILE} - echo "\$ActionFileDefaultTemplate ${template}" >> ${CONFIG_FILE} echo "\$CreateDirs off" >> ${CONFIG_FILE} echo -e "${selectors}" >> ${CONFIG_FILE} echo -e "${forwarders}" >> ${CONFIG_FILE} @@ -127,5 +131,5 @@ start_service() { service_triggers() { - procd_add_reload_trigger ${UCI_CONF} + procd_add_reload_trigger ${UCI_CONF} system } diff --git a/packages/rsyslog/files/rules.conf b/packages/rsyslog/files/rules.conf new file mode 100644 index 000000000..862cf7c32 --- /dev/null +++ b/packages/rsyslog/files/rules.conf @@ -0,0 +1,30 @@ +# +# Copyright (C) 2026 Nethesis S.r.l. +# SPDX-License-Identifier: GPL-2.0-only +# + +# Cleaned up fields shared by every output, included before any selector, forwarder or include + +# files, same layout as RSYSLOG_TraditionalFileFormat +template(name="ns-file" type="string" string="%TIMESTAMP% %HOSTNAME% %$.tag% %$.msg:::drop-last-lf%\n") +# RFC 3164 forwarders +template(name="ns-rfc3164" type="string" string="<%$.pri%>%TIMESTAMP% %HOSTNAME% %$.tag% %$.msg:::drop-last-lf%") +# RFC 5424 without the trailing newline: Victoria Logs, controller and RFC 5424 forwarders +template(name="ns-rfc5424" type="string" + string="<%$.pri%>1 %TIMESTAMP:::date-rfc3339% %HOSTNAME% %$.app% %PROCID% %MSGID% %STRUCTURED-DATA% %$.msg:::drop-last-lf%") + +# banIP and adblock put their version in the tag +set $.app = re_extract($app-name, "^(banIP|adblock)-", 0, 1, $app-name); +# rsyslog's own messages have no tag +if $.app == "" or $.app == "-" then set $.app = "rsyslogd"; +set $.msg = ltrim($msg); +set $.sev = $syslogseverity; +set $.drop = ""; + +# per-application rules shipped by each package, they can change $.app, $.msg, $.sev and set $.drop +include(file="/etc/rsyslog.d/rules.d/*.conf" mode="optional") + +if $.drop != "" then stop +set $.pri = $syslogfacility * 8 + $.sev; +if $procid == "-" then set $.tag = $.app & ":"; +else set $.tag = $.app & "[" & $procid & "]:"; diff --git a/packages/telegraf/Makefile b/packages/telegraf/Makefile index 5275ac8f4..d3687a713 100644 --- a/packages/telegraf/Makefile +++ b/packages/telegraf/Makefile @@ -94,8 +94,8 @@ define Package/telegraf/install $(INSTALL_DATA) ./files/telegraf.conf.d/mwan.conf $(1)/etc/telegraf.conf.d/mwan.conf $(INSTALL_DATA) ./files/telegraf.conf.d/ha.conf $(1)/etc/telegraf.conf.d/ha.conf $(INSTALL_DATA) ./files/telegraf.conf.d/procstat.conf $(1)/etc/telegraf.conf.d/procstat.conf - $(INSTALL_DIR) $(1)/etc/rsyslog.d/victoria-logs.d - $(INSTALL_DATA) ./files/rsyslog-victoria-logs.conf $(1)/etc/rsyslog.d/victoria-logs.d/telegraf.conf + $(INSTALL_DIR) $(1)/etc/rsyslog.d/rules.d + $(INSTALL_DATA) ./files/rsyslog-rules.conf $(1)/etc/rsyslog.d/rules.d/telegraf.conf $(INSTALL_DIR) $(1)/etc/uci-defaults $(INSTALL_BIN) ./files/uci-defaults/99-telegraf-migrate-netdata $(1)/etc/uci-defaults/99-telegraf-migrate-netdata $(INSTALL_DIR) $(1)/usr/sbin diff --git a/packages/telegraf/files/rsyslog-victoria-logs.conf b/packages/telegraf/files/rsyslog-rules.conf similarity index 100% rename from packages/telegraf/files/rsyslog-victoria-logs.conf rename to packages/telegraf/files/rsyslog-rules.conf diff --git a/packages/victoria-logs/Makefile b/packages/victoria-logs/Makefile index 9f448bbdf..0fef8465b 100644 --- a/packages/victoria-logs/Makefile +++ b/packages/victoria-logs/Makefile @@ -65,8 +65,8 @@ define Package/victoria-logs/install $(INSTALL_DATA) ./files/victoria-logs.conf $(1)/etc/config/victoria-logs $(INSTALL_DIR) $(1)/etc/rsyslog.d $(INSTALL_CONF) ./files/rsyslog-victoria-logs.conf $(1)/etc/rsyslog.d/victoria-logs.conf - $(INSTALL_DIR) $(1)/etc/rsyslog.d/victoria-logs.d - $(INSTALL_DATA) ./files/rsyslog-victoria-logs.d.conf $(1)/etc/rsyslog.d/victoria-logs.d/victoria-logs.conf + $(INSTALL_DIR) $(1)/etc/rsyslog.d/rules.d + $(INSTALL_DATA) ./files/rsyslog-rules.conf $(1)/etc/rsyslog.d/rules.d/victoria-logs.conf $(INSTALL_DIR) $(1)/etc/uci-defaults $(INSTALL_BIN) ./files/35_victoria-logs $(1)/etc/uci-defaults/35_victoria-logs endef diff --git a/packages/victoria-logs/files/rsyslog-victoria-logs.d.conf b/packages/victoria-logs/files/rsyslog-rules.conf similarity index 100% rename from packages/victoria-logs/files/rsyslog-victoria-logs.d.conf rename to packages/victoria-logs/files/rsyslog-rules.conf diff --git a/packages/victoria-logs/files/rsyslog-victoria-logs.conf b/packages/victoria-logs/files/rsyslog-victoria-logs.conf index 44985b36f..c29a07679 100644 --- a/packages/victoria-logs/files/rsyslog-victoria-logs.conf +++ b/packages/victoria-logs/files/rsyslog-victoria-logs.conf @@ -1,32 +1,13 @@ -# Rsyslog configuration for VictoriaLogs - -# RFC 5424 without the trailing newline, using the cleaned up fields set below -template(name="victoria-logs" type="string" - string="<%$.pri%>1 %TIMESTAMP:::date-rfc3339% %$.host% %$.app% %PROCID% %MSGID% %STRUCTURED-DATA% %$.msg%") +# Rsyslog configuration for VictoriaLogs, fields are cleaned up by /etc/rsyslog.d/rules.conf ruleset(name="victoria-logs") { - # rsyslog uses the FQDN only if DNS answered when it started - set $.host = field($hostname, 46, 1); - # banIP and adblock put their version in the tag - set $.app = re_extract($app-name, "^(banIP|adblock)-", 0, 1, $app-name); - # rsyslog's own messages have no tag - if $.app == "" or $.app == "-" then set $.app = "rsyslogd"; - set $.msg = ltrim($msg); - set $.sev = $syslogseverity; - set $.drop = ""; - - # per-application rules shipped by each package, they can change $.msg, $.sev and set $.drop - include(file="/etc/rsyslog.d/victoria-logs.d/*.conf" mode="optional") - - set $.pri = $syslogfacility * 8 + $.sev; - - if $.drop == "" then action( + action( type="omfwd" target="127.0.0.1" port="5514" protocol="tcp" TCP_Framing="octet-counted" - Template="victoria-logs" + Template="ns-rfc5424" action.resumeRetryCount="-1" queue.type="linkedList" diff --git a/packages/victoria-metrics/Makefile b/packages/victoria-metrics/Makefile index ab2d8c499..a9f2b6437 100644 --- a/packages/victoria-metrics/Makefile +++ b/packages/victoria-metrics/Makefile @@ -66,8 +66,8 @@ define Package/victoria-metrics/install $(INSTALL_DIR) $(1)/etc/config $(INSTALL_DATA) ./files/victoria-metrics.conf $(1)/etc/config/victoria-metrics $(INSTALL_DATA) ./files/vmalert.conf $(1)/etc/config/vmalert - $(INSTALL_DIR) $(1)/etc/rsyslog.d/victoria-logs.d - $(INSTALL_DATA) ./files/rsyslog-victoria-logs.conf $(1)/etc/rsyslog.d/victoria-logs.d/victoria-metrics.conf + $(INSTALL_DIR) $(1)/etc/rsyslog.d/rules.d + $(INSTALL_DATA) ./files/rsyslog-rules.conf $(1)/etc/rsyslog.d/rules.d/victoria-metrics.conf endef define Package/victoria-metrics/postinst diff --git a/packages/victoria-metrics/files/rsyslog-victoria-logs.conf b/packages/victoria-metrics/files/rsyslog-rules.conf similarity index 100% rename from packages/victoria-metrics/files/rsyslog-victoria-logs.conf rename to packages/victoria-metrics/files/rsyslog-rules.conf From 8cf53a83d79ce0bedefe878cfb439190b7cb0a78 Mon Sep 17 00:00:00 2001 From: Giacomo Sanchietti Date: Thu, 12 Nov 2026 10:50:09 +0100 Subject: [PATCH 41/51] feat(ns-api): list blocklist bans The Threat Shield IP page had nothing to show when fail2ban banned nobody, even while banIP lists dropped traffic all the time. New method list-blocklist-bans: the addresses dropped by banIP lists in the last hour, read from VictoriaLogs, one row per address, list and direction, most hits first, at most 500 rows. It returns an empty list when VictoriaLogs can't be reached. Assisted-by: Claude Code:Opus 5.5 --- packages/ns-api/README.md | 15 +++++++++++++ packages/ns-api/files/ns.threatshield | 32 +++++++++++++++++++++++++++ 2 files changed, 47 insertions(+) diff --git a/packages/ns-api/README.md b/packages/ns-api/README.md index 40004226f..b356623ba 100644 --- a/packages/ns-api/README.md +++ b/packages/ns-api/README.md @@ -6533,6 +6533,21 @@ Response example: `time` is the ban start (unix timestamp), `timeout` the ban duration in seconds (`-1` for a permanent ban), `active` tells if the ban is still in place, `failures` and `matches` are the failures and log lines that triggered the ban. Bans are kept until fail2ban purges them (`dbpurgeage`, default 1 day); they survive reboot only when the data storage is mounted. +### list-blocklist-bans + +List the IP addresses banned by banIP lists, the most active first: +``` +api-cli ns.threatshield list-blocklist-bans +``` + +Response example: +```json +{"data": [{"ip": "203.0.113.77", "list": "blocklist", "direction": "inbound", "time": 1762412400, "hits": 12, "matches": [""]}]} +``` + +`list` is the banIP feed, `direction` is `inbound` (banned source) or `outbound` (banned destination), `time` is the last logged drop (unix timestamp), `hits` the logged drops and `matches` up to 5 latest log lines. +Rows come from the banIP drops logged in VictoriaLogs in the last hour, at most 500 rows; `hits` is a lower bound because banIP rate-limits its log lines. + ### remove-active-block Unban an IP address from all fail2ban jails: diff --git a/packages/ns-api/files/ns.threatshield b/packages/ns-api/files/ns.threatshield index 5219e9e93..5a8c6939f 100644 --- a/packages/ns-api/files/ns.threatshield +++ b/packages/ns-api/files/ns.threatshield @@ -18,6 +18,7 @@ from euci import EUci from nethsec.utils import ValidationError, validation_error, generic_error from nethsec import utils, firewall import base64 +import calendar import time import sqlite3 import subprocess @@ -25,6 +26,15 @@ import subprocess # NethSecurity jail list, hard-coded in packages/ns-api/files/ns.threatshield and packages/ns-threat_shield/files/{ts-fail2ban,99-nethsec-fail2ban,banip-defaults,fail2ban/jail.d/10-ns-threat_shield.conf}: keep them in sync JAILS = ['ns-ssh', 'ns-webui', 'ns-openvpn', 'ns-proxy-auth', 'ns-proxy-scan'] +# VictoriaLogs query: banIP drops of the last hour, one row per (ip, feed, direction); pre-* lines have no feed +BANIP_LOGS_QUERY = ( + 'app_name:kernel "banIP/" | extract "banIP///: " | filter feed:* ' + r'| replace_regexp ("\\.v[46](MAC)?$", "") at feed ' + '| extract if (chain:inbound) "SRC= " | extract if (chain:outbound) "DST= " | filter ip:* ' + '| stats by (ip, feed, chain) count() hits, max(_time) last, json_values(_msg) sort by (_time desc) limit 5 as matches ' + '| sort by (hits desc, last desc) | limit 500' +) + ## continent codes map continent_table = { @@ -1143,6 +1153,25 @@ def list_recent_bans(): return bans +def vl_epoch(ts): + # VictoriaLogs timestamps are RFC3339 UTC + return calendar.timegm(time.strptime(ts[:19], "%Y-%m-%dT%H:%M:%S")) + + +def list_blocklist_bans(): + try: + vl_addr = EUci().get("victoria-logs", "main", "http_listen_addr", default="127.0.0.1:9428") + data = urllib.parse.urlencode({"query": BANIP_LOGS_QUERY, "start": "1h"}).encode() + with urllib.request.urlopen(f"http://{vl_addr}/select/logsql/query", data=data, timeout=5) as resp: + rows = [json.loads(line) for line in resp.read().splitlines() if line.strip()] + bans = [{"ip": r["ip"], "list": r["feed"], "direction": r["chain"], "time": vl_epoch(r["last"]), + "hits": int(r["hits"]), + "matches": [m["_msg"] for m in json.loads(r.get("matches") or "[]")]} for r in rows] + except Exception: + bans = [] + return {"data": bans} + + def is_ip_blocked(): data = json.loads(sys.stdin.read()) if "ip" not in data or data["ip"] == "": @@ -1253,6 +1282,7 @@ if cmd == 'list': 'delete-blocked': {'address': '1.2.3.4'}, 'list-active-blocks': {}, 'list-recent-bans': {}, + 'list-blocklist-bans': {}, 'remove-active-block': { 'ip': '' }, 'is-ip-blocked': {'ip': ''}, 'dns-list-blocklist': {}, @@ -1334,6 +1364,8 @@ elif cmd == 'call': ret = list_active_blocks() elif action == 'list-recent-bans': ret = list_recent_bans() + elif action == 'list-blocklist-bans': + ret = list_blocklist_bans() elif action == 'remove-active-block': ret = remove_active_block() elif action == 'is-ip-blocked': From f7a6f83c40a50f15213a90093ffd25d22e73a1c2 Mon Sep 17 00:00:00 2001 From: Tommaso Bailetti Date: Thu, 12 Nov 2026 11:44:50 +0100 Subject: [PATCH 42/51] feat: moving nft logs out of the kernel log (#2010) --- config/ulogd.conf | 6 ------ files/etc/uci-defaults/99-nethsec-conloglevel | 12 ++++++++++++ 2 files changed, 12 insertions(+), 6 deletions(-) delete mode 100644 config/ulogd.conf create mode 100644 files/etc/uci-defaults/99-nethsec-conloglevel diff --git a/config/ulogd.conf b/config/ulogd.conf deleted file mode 100644 index 753eb734f..000000000 --- a/config/ulogd.conf +++ /dev/null @@ -1,6 +0,0 @@ -# Enable ulogd to receive nft logs over NFLOG -CONFIG_PACKAGE_ulogd=y -CONFIG_PACKAGE_ulogd-mod-nflog=y -CONFIG_PACKAGE_ulogd-mod-syslog=y -CONFIG_PACKAGE_ulogd-mod-extra=y -CONFIG_PACKAGE_kmod-nfnetlink-log=y diff --git a/files/etc/uci-defaults/99-nethsec-conloglevel b/files/etc/uci-defaults/99-nethsec-conloglevel new file mode 100644 index 000000000..1dc7527aa --- /dev/null +++ b/files/etc/uci-defaults/99-nethsec-conloglevel @@ -0,0 +1,12 @@ +# +# Copyright (C) 2026 Nethesis S.r.l. +# SPDX-License-Identifier: GPL-2.0-only +# + +# Keep nft log lines and other kernel noise off the console +[ "$(uci -q get system.@system[0].conloglevel)" != "" ] && exit 0 + +uci -q batch << EOI +set system.@system[0].conloglevel="4" +commit system +EOI From d1bcced0fec427e31b71616c16fdfbcb585dcde6 Mon Sep 17 00:00:00 2001 From: Giacomo Sanchietti Date: Thu, 12 Nov 2026 14:27:20 +0100 Subject: [PATCH 43/51] chore(ns-ui): build UI from release-8.9.0 Build the UI from the head of the nethsecurity-ui release-8.9.0 branch, which has the Threat Shield custom lists pages. Replace it with the tagged UI release later. Assisted-by: Claude Code:Opus 5.5 --- packages/ns-ui/Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/ns-ui/Makefile b/packages/ns-ui/Makefile index 2e75e3252..b266e63a4 100644 --- a/packages/ns-ui/Makefile +++ b/packages/ns-ui/Makefile @@ -12,7 +12,7 @@ PKG_RELEASE:=1 PKG_SOURCE_PROTO:=git PKG_SOURCE_URL:=https://github.com/NethServer/nethsecurity-ui.git -PKG_SOURCE_VERSION:=809aa4cfa08f80463542421df1e8ca37653d96aa +PKG_SOURCE_VERSION:=455432490c9e32175fa4c25d6441022dcf3be51f PKG_SOURCE_SUBDIR:=nethsecurity-ui-$(PKG_SOURCE_VERSION) PKG_BUILD_DIR:=$(BUILD_DIR)/$(PKG_SOURCE_SUBDIR) PKG_MIRROR_HASH:=skip From c5eb4deda3d57e1bb63825a437eab80b6da589e5 Mon Sep 17 00:00:00 2001 From: Tommaso Bailetti Date: Thu, 12 Nov 2026 15:58:26 +0100 Subject: [PATCH 44/51] feat(netifyd): added monitoring for statistics --- packages/netifyd/Makefile | 4 +- packages/netifyd/README.md | 13 ++++++ .../files/etc/telegraf.conf.d/netifyd.conf | 44 +++++++++++++++++++ packages/telegraf/README.md | 5 +++ 4 files changed, 65 insertions(+), 1 deletion(-) create mode 100644 packages/netifyd/files/etc/telegraf.conf.d/netifyd.conf diff --git a/packages/netifyd/Makefile b/packages/netifyd/Makefile index e816a8ba2..da6ab9f67 100644 --- a/packages/netifyd/Makefile +++ b/packages/netifyd/Makefile @@ -3,7 +3,7 @@ include $(TOPDIR)/rules.mk PKG_NAME:=netifyd NETIFYD_VERSION:=5.2.9 PKG_VERSION:=$(NETIFYD_VERSION) -PKG_RELEASE:=1 +PKG_RELEASE:=2 PKG_MAINTAINER:=Darryl Sokoloski PKG_LICENSE:=Unlicensed @@ -200,6 +200,8 @@ define Package/netifyd/install $(INSTALL_DATA) ./files/usr/share/netifyd/plugins.d/99-netify-sink-http-auto.conf $(1)/usr/share/netifyd/plugins.d/99-netify-sink-http-auto.conf # nethesis additional files $(INSTALL_BIN) ./files/usr/sbin/ns-netifyd-configure.py $(1)/usr/sbin/ns-netifyd-configure + $(INSTALL_DIR) $(1)/etc/telegraf.conf.d + $(INSTALL_DATA) ./files/etc/telegraf.conf.d/netifyd.conf $(1)/etc/telegraf.conf.d/netifyd.conf # netify-plm $(INSTALL_BIN) $(PKG_BUILD_DIR)/$(NETIFYD_FILE_PLM) $(1)/usr/lib/$(NETIFYD_FILE_PLM) $(LN) /usr/lib/$(NETIFYD_FILE_PLM) $(1)/usr/lib/$(NETIFYD_LINK_PLM) diff --git a/packages/netifyd/README.md b/packages/netifyd/README.md index 26ac4fdfa..7da427d1c 100644 --- a/packages/netifyd/README.md +++ b/packages/netifyd/README.md @@ -111,3 +111,16 @@ uci add_list netifyd.config.firewall_traffic='forward' uci commit netifyd reload_config ``` + +## Monitoring + +The package ships `/etc/telegraf.conf.d/netifyd.conf`. Every 60 seconds Telegraf reads `/var/run/netifyd/status.json`, which netifyd rewrites every 15 seconds. When netifyd is stopped the file is missing and Telegraf logs an error for this input. + +Metrics: +``` +netifyd_flows_in_use = flow table entries in use (also flow_count, flows_active, flows_expiring, flows_expired, flows_purged) +netifyd_lan_flow_dropped, netifyd_wan_flow_dropped = flows dropped, either because the flow table is full or the system is under load +netifyd_plugin_license_status_id{plugin="proc-nfa", license_status="valid"} = 3 when valid +``` + +Plugins that don't report a status (core processor, sinks) are skipped. diff --git a/packages/netifyd/files/etc/telegraf.conf.d/netifyd.conf b/packages/netifyd/files/etc/telegraf.conf.d/netifyd.conf new file mode 100644 index 000000000..7aceff81b --- /dev/null +++ b/packages/netifyd/files/etc/telegraf.conf.d/netifyd.conf @@ -0,0 +1,44 @@ +# netifyd agent status: flow table usage and plugin license status +# netifyd rewrites /var/run/netifyd/status.json every update_interval (15s). + +[[inputs.file]] + files = ["/var/run/netifyd/status.json"] + interval = "60s" + data_format = "json_v2" + + [[inputs.file.json_v2]] + measurement_name = "netifyd" + [[inputs.file.json_v2.field]] + path = "flow_count" + [[inputs.file.json_v2.field]] + path = "flows_active" + [[inputs.file.json_v2.field]] + path = "flows_in_use" + [[inputs.file.json_v2.field]] + path = "flows_expiring" + [[inputs.file.json_v2.field]] + path = "flows_expired" + [[inputs.file.json_v2.field]] + path = "flows_purged" + # Flows dropped on the lan/wan capture interfaces (10-nfqueue.conf), flow table full or system under load + [[inputs.file.json_v2.field]] + path = "stats.lan.flow_dropped" + rename = "lan_flow_dropped" + [[inputs.file.json_v2.field]] + path = "stats.wan.flow_dropped" + rename = "wan_flow_dropped" + + # license_status_id 3 is "valid"; plugins without a status are skipped + [[inputs.file.json_v2]] + measurement_name = "netifyd_plugin" + [[inputs.file.json_v2.object]] + path = "plugins.@values" + included_keys = ["status_license_status_id"] + tags = ["tag", "status_license_status"] + [inputs.file.json_v2.object.renames] + tag = "plugin" + status_license_status = "license_status" + status_license_status_id = "license_status_id" + + [inputs.file.tags] + influxdb_db = "os-metrics" diff --git a/packages/telegraf/README.md b/packages/telegraf/README.md index 96426cfc3..ba005cfc8 100644 --- a/packages/telegraf/README.md +++ b/packages/telegraf/README.md @@ -9,6 +9,7 @@ Telegraf is the metrics collection agent that gathers host and service metrics a ``` /usr/libexec/telegraf-services ← service status via ubus /var/run/mwan3/iface_state/ ← WAN interface status via mwan3 state files +/var/run/netifyd/status.json ← netifyd flow table and plugin licenses /proc filesystem ← CPU, memory, disk, network │ ▼ @@ -143,6 +144,10 @@ procstat_lookup_running{filter="openvpn"} = number of matching processes curl -s 'http://127.0.0.1:8428/api/v1/query?query=sum(procstat_memory_rss)by(filter)' ``` +### netifyd Monitoring (netifyd.conf) + +Shipped by the `netifyd` package, see [its README](../netifyd/README.md#monitoring). + ## Advanced Configuration To add custom metrics or modify collection intervals, edit the `/etc/telegraf.conf.d/` files following [Telegraf documentation](https://docs.influxdata.com/telegraf/). Common customizations: From b369c14442ff05e6636ddb4002d50b27de32848a Mon Sep 17 00:00:00 2001 From: Tommaso Bailetti Date: Thu, 12 Nov 2026 18:07:22 +0100 Subject: [PATCH 45/51] fix(ns-api-server): using syslog correctly, with locking and connecting --- packages/ns-api-server/files/src/logs/logs.go | 42 ++++++++++++++----- 1 file changed, 31 insertions(+), 11 deletions(-) diff --git a/packages/ns-api-server/files/src/logs/logs.go b/packages/ns-api-server/files/src/logs/logs.go index a3e96a405..df394c811 100644 --- a/packages/ns-api-server/files/src/logs/logs.go +++ b/packages/ns-api-server/files/src/logs/logs.go @@ -14,42 +14,62 @@ import ( "io" "log/syslog" "os" + "sync" ) -var writer *syslog.Writer +var ( + mu sync.Mutex + tag string + writer *syslog.Writer +) // Output receives the log lines when syslog isn't available var Output io.Writer = os.Stderr func Init(name string) { - w, err := syslog.New(syslog.LOG_DAEMON|syslog.LOG_INFO, name) - if err != nil { + tag = name + if _, err := connect(); err != nil { fmt.Fprintln(Output, "[ERR][LOGS] cannot connect to syslog: "+err.Error()) - return } - writer = w +} + +// connect returns the syslog writer, retrying the connection if Init couldn't open it +func connect() (*syslog.Writer, error) { + mu.Lock() + defer mu.Unlock() + if writer == nil && tag != "" { + w, err := syslog.New(syslog.LOG_DAEMON|syslog.LOG_INFO, tag) + if err != nil { + return nil, err + } + writer = w + } + return writer, nil } func Info(msg string) { - if writer == nil { + w, _ := connect() + if w == nil { fmt.Fprintln(Output, msg) return } - writer.Info(msg) + w.Info(msg) } func Err(msg string) { - if writer == nil { + w, _ := connect() + if w == nil { fmt.Fprintln(Output, msg) return } - writer.Err(msg) + w.Err(msg) } func Crit(msg string) { - if writer == nil { + w, _ := connect() + if w == nil { fmt.Fprintln(Output, msg) return } - writer.Crit(msg) + w.Crit(msg) } From c3ad293d05d43691e93a557e5703ef789dd1fc5c Mon Sep 17 00:00:00 2001 From: Tommaso Bailetti Date: Fri, 13 Nov 2026 09:23:30 +0100 Subject: [PATCH 46/51] fix: removing from log even more sensible informations (#2015) --- .../files/src/configuration/configuration.go | 6 ++- .../files/src/middleware/middleware.go | 30 +++++++------ .../files/src/middleware/middleware_test.go | 43 +++++++++++++++++++ 3 files changed, 66 insertions(+), 13 deletions(-) diff --git a/packages/ns-api-server/files/src/configuration/configuration.go b/packages/ns-api-server/files/src/configuration/configuration.go index 3ffb08e31..f3ef8b86c 100644 --- a/packages/ns-api-server/files/src/configuration/configuration.go +++ b/packages/ns-api-server/files/src/configuration/configuration.go @@ -81,7 +81,11 @@ func Init() { if os.Getenv("SENSITIVE_LIST") != "" { Config.SensitiveList = strings.Split(os.Getenv("SENSITIVE_LIST"), ",") } else { - Config.SensitiveList = []string{"password", "secret", "token"} + Config.SensitiveList = []string{ + "password", "old_password", "ssh_password", "bind_password", "pppoe_password", "passphrase", + "secret", "token", "oinkcode", + "peer_private_key", "pre_shared_key", "private_key", "preshared_key", "Psk", "Crt", + } } if os.Getenv("DOWNLOAD_FILE_PATH") != "" { diff --git a/packages/ns-api-server/files/src/middleware/middleware.go b/packages/ns-api-server/files/src/middleware/middleware.go index 084fe4bcc..4c8df9b85 100644 --- a/packages/ns-api-server/files/src/middleware/middleware.go +++ b/packages/ns-api-server/files/src/middleware/middleware.go @@ -13,6 +13,7 @@ import ( "bytes" "io" "regexp" + "slices" "strings" "time" "unicode/utf8" @@ -39,6 +40,22 @@ type login struct { var jwtMiddleware *jwt.GinJWTMiddleware var identityKey = "id" +// maskSensitiveFields replaces with XXX the string value of every field named exactly as one of the fields. +// It covers both "":"" and the "","" pairs of the ns.commit changes. +func maskSensitiveFields(body string, fields []string) string { + // ns.wireguard import-configuration sends the whole configuration, private key included + if strings.Contains(body, `"path":"ns.wireguard"`) { + fields = append(slices.Clone(fields), "config") + } + + for _, field := range fields { + r := regexp.MustCompile(`([{\[,]"` + regexp.QuoteMeta(field) + `"[:,])"(?:[^"\\]|\\.)*"`) + body = r.ReplaceAllString(body, `${1}"XXX"`) + } + + return body +} + const onBehalfOfKey = "on_behalf_of" const onBehalfOfMaxLen = 64 const onBehalfOfTruncationMarker = "…" @@ -219,19 +236,8 @@ func InitJWT() *jwt.GinJWTMiddleware { // remove all spaces jsonB = strings.ReplaceAll(jsonB, " ", "") - // create regex for sensitive words - for _, s := range configuration.Config.SensitiveList { - // create regex - r1 := regexp.MustCompile(`"` + s + `":"(.*?)"`) // match "token|password|secret":"" - r2 := regexp.MustCompile(`"` + s + `","(.*?)"`) // match "token|password|secret","" - - // apply regex - jsonB = r1.ReplaceAllString(jsonB, `"`+s+`":"XXX"`) - jsonB = r2.ReplaceAllString(jsonB, `"`+s+`":"XXX"`) - } - // compose req body - reqBody = jsonB + reqBody = maskSensitiveFields(jsonB, configuration.Config.SensitiveList) } logs.Info("[AUTH] authorization success for user " + utils.SanitizeForLog(claims["id"].(string)) + claimsSuffixOnBehalfOf(claims) + ". " + reqMethod + " " + reqURI + " " + utils.SanitizeForLog(reqBody)) diff --git a/packages/ns-api-server/files/src/middleware/middleware_test.go b/packages/ns-api-server/files/src/middleware/middleware_test.go index 655a19d3d..26ac5756f 100644 --- a/packages/ns-api-server/files/src/middleware/middleware_test.go +++ b/packages/ns-api-server/files/src/middleware/middleware_test.go @@ -34,6 +34,49 @@ func lastIPv4(line string) string { return m[len(m)-1] } +func TestMaskSensitiveFields(t *testing.T) { + fields := []string{"password", "bind_password", "peer_private_key", "pre_shared_key", "private_key", "Psk"} + + cases := map[string]struct{ in, want string }{ + "wireguard tunnel, keeping the public key": { + `{"path":"ns.wireguard","method":"edit-tunnel","payload":{"id":"wg1","server_public_key":"cHVi","peer_private_key":"cHJpdg==","pre_shared_key":"cHNr","route_all_traffic":false}}`, + `{"path":"ns.wireguard","method":"edit-tunnel","payload":{"id":"wg1","server_public_key":"cHVi","peer_private_key":"XXX","pre_shared_key":"XXX","route_all_traffic":false}}`, + }, + "wireguard import config": { + `{"path":"ns.wireguard","method":"import-configuration","payload":{"config":"W0ludGVyZmFjZV0="}}`, + `{"path":"ns.wireguard","method":"import-configuration","payload":{"config":"XXX"}}`, + }, + "config of other paths": { + `{"path":"ns.uci","method":"get","payload":{"config":"network"}}`, + `{"path":"ns.uci","method":"get","payload":{"config":"network"}}`, + }, + "only exact field names": { + `{"Psk":"static","psk":"x","bind_password":"p","password_changed":"1"}`, + `{"Psk":"XXX","psk":"x","bind_password":"XXX","password_changed":"1"}`, + }, + "value equal to a field is not taken for a field": { + `{"name":"password","user":"root"}`, + `{"name":"password","user":"root"}`, + }, + "escaped quotes inside the value": { + `{"password":"a\"b","user":"root"}`, + `{"password":"XXX","user":"root"}`, + }, + "commit changes": { + `{"changes":{"network":[["set","wg1","private_key","cHJpdg=="],["set","wg1","disabled","0"]]}}`, + `{"changes":{"network":[["set","wg1","private_key","XXX"],["set","wg1","disabled","0"]]}}`, + }, + } + + for name, c := range cases { + t.Run(name, func(t *testing.T) { + if got := maskSensitiveFields(c.in, fields); got != c.want { + t.Fatalf("got %q, want %q", got, c.want) + } + }) + } +} + // TestLoginLogInjection reproduces the unauthenticated DoS. banIP bans EVERY IP // found on a physical line matching its search term, so a crafted username must // never put an attacker-chosen IP onto the failed-auth log line (whether via a From ed21df29972ceb6b2126f6a609f5223d98ed9146 Mon Sep 17 00:00:00 2001 From: Tommaso Bailetti Date: Fri, 13 Nov 2026 17:36:21 +0100 Subject: [PATCH 47/51] fix: addressing service issues on close role switches (#1930) --- .../files/etc/hotplug.d/keepalived/01-ubus | 3 ++ .../etc/hotplug.d/keepalived/551-dnsmasq | 2 + .../etc/hotplug.d/keepalived/555-dropbear | 2 + .../files/lib/functions/keepalived/hotplug.sh | 9 ++++ packages/ns-api/README.md | 4 +- packages/ns-api/files/ns.ha | 2 +- packages/ns-ha/Makefile | 5 ++- packages/ns-ha/README.md | 19 +++++--- packages/ns-ha/files/00-lock | 43 ++++++++++++++++--- packages/ns-ha/files/05-alert-state | 3 ++ packages/ns-ha/files/10-adjust | 4 ++ packages/ns-ha/files/100-conntrackd | 2 + packages/ns-ha/files/500-dhcp-force | 4 ++ packages/ns-ha/files/500-nathelpers | 4 ++ packages/ns-ha/files/560-mac-binding | 2 + packages/ns-ha/files/600-acme | 2 + packages/ns-ha/files/600-mwan3 | 2 + packages/ns-ha/files/600-snort | 2 + packages/ns-ha/files/700-nginx | 2 + packages/ns-ha/files/800-adblock | 2 + packages/ns-ha/files/800-banip | 2 + packages/ns-ha/files/800-dedalo | 2 + packages/ns-ha/files/800-flashstart | 2 + packages/ns-ha/files/800-netifyd | 2 + packages/ns-ha/files/800-ui | 2 + packages/ns-ha/files/850-vpn | 14 ++++++ packages/ns-ha/files/{600-ipsec => 860-ipsec} | 2 + .../ns-ha/files/{600-openvpn => 860-openvpn} | 2 + packages/ns-ha/files/900-ddns | 2 + packages/ns-ha/files/900-ns-plug | 2 + packages/ns-ha/files/900-phonehome | 2 + packages/ns-ha/files/900-telegraf | 2 + packages/ns-ha/files/999-stop-fault | 4 ++ packages/ns-ha/files/999-unlock | 15 +++++-- packages/ns-ha/files/ns-ha-disable | 3 +- packages/ns-ha/files/ns-ha-enable | 7 ++- 36 files changed, 161 insertions(+), 22 deletions(-) create mode 100644 packages/ns-ha/files/850-vpn rename packages/ns-ha/files/{600-ipsec => 860-ipsec} (84%) rename packages/ns-ha/files/{600-openvpn => 860-openvpn} (84%) diff --git a/packages/keepalived/files/etc/hotplug.d/keepalived/01-ubus b/packages/keepalived/files/etc/hotplug.d/keepalived/01-ubus index ab5907f74..177f1aefe 100644 --- a/packages/keepalived/files/etc/hotplug.d/keepalived/01-ubus +++ b/packages/keepalived/files/etc/hotplug.d/keepalived/01-ubus @@ -1,6 +1,9 @@ #!/bin/sh . /lib/functions.sh +. /lib/functions/keepalived/hotplug.sh + +ns_ha_chain_is_stale && exit 0 KEEPALIVED_STATUS_DIR="/var/run/keepalived" diff --git a/packages/keepalived/files/etc/hotplug.d/keepalived/551-dnsmasq b/packages/keepalived/files/etc/hotplug.d/keepalived/551-dnsmasq index d43598806..1762a530c 100644 --- a/packages/keepalived/files/etc/hotplug.d/keepalived/551-dnsmasq +++ b/packages/keepalived/files/etc/hotplug.d/keepalived/551-dnsmasq @@ -3,6 +3,8 @@ # shellcheck source=/dev/null . /lib/functions/keepalived/hotplug.sh +ns_ha_chain_is_stale && exit 0 + set_service_name dnsmasq set_restart_if_master diff --git a/packages/keepalived/files/etc/hotplug.d/keepalived/555-dropbear b/packages/keepalived/files/etc/hotplug.d/keepalived/555-dropbear index 2b9f314ff..dbd18478f 100644 --- a/packages/keepalived/files/etc/hotplug.d/keepalived/555-dropbear +++ b/packages/keepalived/files/etc/hotplug.d/keepalived/555-dropbear @@ -3,6 +3,8 @@ # shellcheck source=/dev/null . /lib/functions/keepalived/hotplug.sh +ns_ha_chain_is_stale && exit 0 + set_service_name dropbear set_reload_if_backup diff --git a/packages/keepalived/files/lib/functions/keepalived/hotplug.sh b/packages/keepalived/files/lib/functions/keepalived/hotplug.sh index 694632754..20963a96c 100644 --- a/packages/keepalived/files/lib/functions/keepalived/hotplug.sh +++ b/packages/keepalived/files/lib/functions/keepalived/hotplug.sh @@ -189,6 +189,15 @@ call_cb() { fi } +# True when a newer keepalived event started after this hotplug chain, see ns-ha 00-lock +ns_ha_chain_is_stale() { + local mine latest + + mine=$(cat "/var/run/ns-ha/chain.$$" 2>/dev/null) || return 1 + latest=$(cat /var/run/ns-ha/last_event 2>/dev/null) + [ "$mine" != "$latest" ] +} + keepalived_hotplug() { [ -z "$(get_master_cb)" ] && set_master_cb _notify_master [ -z "$(get_backup_cb)" ] && set_backup_cb _notify_backup diff --git a/packages/ns-api/README.md b/packages/ns-api/README.md index b356623ba..aeae37899 100644 --- a/packages/ns-api/README.md +++ b/packages/ns-api/README.md @@ -9312,8 +9312,8 @@ Response example: } ``` -`lock_status` is `enabled` only when `keepalived.globals.ns_lock_timeout` is set; otherwise it is `disabled`. -`lock_timeout` shows the configured timeout in seconds. +`lock_status` is `disabled` only when `keepalived.globals.ns_lock_timeout` is set to `0`; otherwise it is `enabled`. +`lock_timeout` shows the timeout in seconds, `120` when the option is unset. Error response example: ```json diff --git a/packages/ns-api/files/ns.ha b/packages/ns-api/files/ns.ha index 4a049a656..518e7361a 100755 --- a/packages/ns-api/files/ns.ha +++ b/packages/ns-api/files/ns.ha @@ -751,7 +751,7 @@ def init_remote(ssh_password, lan_interface): def get_lock_status(uci): - lock_timeout = uci.get('keepalived', 'globals', 'ns_lock_timeout', default='') + lock_timeout = uci.get('keepalived', 'globals', 'ns_lock_timeout', default='120') ret = { "lock_status": "disabled", diff --git a/packages/ns-ha/Makefile b/packages/ns-ha/Makefile index 15dda14f6..ccbed5307 100644 --- a/packages/ns-ha/Makefile +++ b/packages/ns-ha/Makefile @@ -64,11 +64,9 @@ define Package/ns-ha/install $(INSTALL_DATA) ./files/500-nathelpers $(1)/etc/hotplug.d/keepalived $(INSTALL_DATA) ./files/500-netmap $(1)/etc/hotplug.d/keepalived $(INSTALL_DATA) ./files/560-mac-binding $(1)/etc/hotplug.d/keepalived - $(INSTALL_DATA) ./files/600-openvpn $(1)/etc/hotplug.d/keepalived $(INSTALL_DATA) ./files/600-mwan3 $(1)/etc/hotplug.d/keepalived $(INSTALL_DATA) ./files/600-qosify $(1)/etc/hotplug.d/keepalived $(INSTALL_DATA) ./files/600-snort $(1)/etc/hotplug.d/keepalived - $(INSTALL_DATA) ./files/600-ipsec $(1)/etc/hotplug.d/keepalived $(INSTALL_DATA) ./files/600-acme $(1)/etc/hotplug.d/keepalived $(INSTALL_DATA) ./files/700-nginx $(1)/etc/hotplug.d/keepalived $(INSTALL_DATA) ./files/800-adblock $(1)/etc/hotplug.d/keepalived @@ -78,6 +76,9 @@ define Package/ns-ha/install $(INSTALL_DATA) ./files/800-flashstart $(1)/etc/hotplug.d/keepalived $(INSTALL_DATA) ./files/800-ui $(1)/etc/hotplug.d/keepalived $(INSTALL_DATA) ./files/800-dedalo $(1)/etc/hotplug.d/keepalived + $(INSTALL_DATA) ./files/850-vpn $(1)/etc/hotplug.d/keepalived + $(INSTALL_DATA) ./files/860-ipsec $(1)/etc/hotplug.d/keepalived + $(INSTALL_DATA) ./files/860-openvpn $(1)/etc/hotplug.d/keepalived $(INSTALL_DATA) ./files/900-ns-plug $(1)/etc/hotplug.d/keepalived $(INSTALL_DATA) ./files/900-phonehome $(1)/etc/hotplug.d/keepalived $(INSTALL_DATA) ./files/900-telegraf $(1)/etc/hotplug.d/keepalived diff --git a/packages/ns-ha/README.md b/packages/ns-ha/README.md index 574bb03c4..267ac839f 100644 --- a/packages/ns-ha/README.md +++ b/packages/ns-ha/README.md @@ -68,11 +68,15 @@ The setup process automatically does the following: key-based authentication is allowed - configure conntrackd to sync the connection tracking table -Keepalived hotplug locking is disabled by default and is usually not needed. Leave -`keepalived.globals.ns_lock_timeout` unset unless keepalived state transitions overlap and restart/stop -events race with each other, as in the dedalo/dpi failover. When the option is set, -the hotplug chain waits up to the configured timeout before letting the next event proceed. -To enable the locking mechanism, set `keepalived.globals.ns_lock_timeout` to a positive integer representing the timeout in seconds, suggested value is 120 seconds, since OpenVPN and Netifyd have lng `term_timeout` option. +Keepalived hotplug events are serialized by a lock: a new event waits up to `keepalived.globals.ns_lock_timeout` +seconds (default `120`) for the running one before proceeding anyway. +Only the most recent event is applied: when a newer event starts, the scripts of older events still running or +waiting skip their actions, and `999-unlock` logs `superseded by a newer event`. +To disable the lock, set `keepalived.globals.ns_lock_timeout` to `0`: +``` +uci set keepalived.globals.ns_lock_timeout=0 +uci commit keepalived +``` In this example: - `primary_node_ip` is the primary node, with LAN IP `192.168.100.238` @@ -605,6 +609,11 @@ Executed when a node becomes the active (master) node: - Enables all network interfaces and services that were active on the failed primary using `/usr/libexec/ns-ha-enable` script - Activates WireGuard interfaces, IPsec tunnels, and routes imported from `/etc/ha` +WAN interfaces come up first and the gratuitous ARP is sent right after, then the services (dnsmasq, adblock, +banIP, Snort and the others) are restarted. WireGuard and IPsec interfaces come up after them (`850-vpn`, calling +`ns-ha-enable --vpn`), followed by the swanctl and OpenVPN restarts, so traffic and protection are back +before VPNs restore. + #### NOTIFY_BACKUP Executed on the backup node during normal operation or when the primary node recovers: diff --git a/packages/ns-ha/files/00-lock b/packages/ns-ha/files/00-lock index 210696d39..b1c427c47 100644 --- a/packages/ns-ha/files/00-lock +++ b/packages/ns-ha/files/00-lock @@ -8,33 +8,66 @@ # concurrent hotplug chains from racing when keepalived transitions happen in # quick succession. # +# Each event also gets a sequence number before waiting for the lock: scripts +# call ns_ha_chain_is_stale and skip their work once a newer event has started, +# so only the most recent event is applied regardless of lock acquisition order. +# # The lock is released by 999-unlock at the end of the hotplug chain. -# Because hotplug-call sources each script in a subshell, a flag file is used -# to communicate whether the lock was actually acquired to 999-unlock. +# Because hotplug-call sources each script in a subshell, a flag file holding +# the hotplug-call PID tells 999-unlock which chain acquired the lock. When that +# chain dies before 999-unlock (e.g. keepalived stopped), the next waiter takes +# the lock over instead of waiting for the timeout. # -# On timeout (60 s) the event proceeds with a warning rather than being dropped, +# On timeout the event proceeds with a warning rather than being dropped, # to avoid leaving the system in an inconsistent state. +# $$ is the PID of hotplug-call, shared by every script of this chain: drop a leftover of a dead chain with the same PID +rm -f "/var/run/ns-ha/chain.$$" + case "$ACTION" in NOTIFY_MASTER|NOTIFY_BACKUP|NOTIFY_FAULT|NOTIFY_STOP) ;; *) return 0 2>/dev/null || exit 0 ;; esac +mkdir -p /var/run/ns-ha +lock /var/lock/ns-ha-seq +seq=$(( $(cat /var/run/ns-ha/last_event 2>/dev/null || echo 0) + 1 )) +echo "$seq" > /var/run/ns-ha/last_event +lock -u /var/lock/ns-ha-seq +echo "$seq" > "/var/run/ns-ha/chain.$$" + +# Chain files of hotplug-call processes that died before 999-unlock, e.g. killed by a keepalived stop +for chain in /var/run/ns-ha/chain.*; do + [ -d "/proc/${chain##*.}" ] || rm -f "$chain" +done + LOCKFILE="/var/lock/keepalived-hotplug.lock" ACQUIRED_FLAG="/var/lock/keepalived-hotplug-acquired" TIMEOUT=$(uci -q get keepalived.globals.ns_lock_timeout) +TIMEOUT=${TIMEOUT:-120} elapsed=0 -if [ -z "$TIMEOUT" ] || [ "$TIMEOUT" -le 0 ]; then +if [ "$TIMEOUT" -le 0 ]; then # Locking disabled by configuration return 0 2>/dev/null || exit 0 fi while [ "$elapsed" -lt "$TIMEOUT" ]; do if lock -n "$LOCKFILE" > /dev/null 2>&1; then - touch "$ACQUIRED_FLAG" + echo "$$" > "$ACQUIRED_FLAG" return 0 2>/dev/null || exit 0 fi + # Take over the lock when its holder chain died before 999-unlock, serialized so only one waiter releases it + lock /var/lock/ns-ha-seq + holder=$(cat "$ACQUIRED_FLAG" 2>/dev/null) + if [ -n "$holder" ] && [ ! -d "/proc/$holder" ]; then + logger -t ns-ha "WARNING: previous event holder $holder is gone, releasing its lock" + rm -f "$ACQUIRED_FLAG" + lock -u "$LOCKFILE" + lock -u /var/lock/ns-ha-seq + continue + fi + lock -u /var/lock/ns-ha-seq sleep 1 elapsed=$((elapsed + 1)) done diff --git a/packages/ns-ha/files/05-alert-state b/packages/ns-ha/files/05-alert-state index fcf7c8f65..f699e0912 100644 --- a/packages/ns-ha/files/05-alert-state +++ b/packages/ns-ha/files/05-alert-state @@ -5,6 +5,9 @@ # . /lib/functions.sh +. /lib/functions/keepalived/hotplug.sh + +ns_ha_chain_is_stale && exit 0 record_alert_event() { local option="$1" diff --git a/packages/ns-ha/files/10-adjust b/packages/ns-ha/files/10-adjust index 7978efb26..1c7fe6b56 100644 --- a/packages/ns-ha/files/10-adjust +++ b/packages/ns-ha/files/10-adjust @@ -1,5 +1,9 @@ #!/bin/sh +. /lib/functions/keepalived/hotplug.sh + +ns_ha_chain_is_stale && exit 0 + if [ "$ACTION" == "NOTIFY_MASTER" ]; then /usr/libexec/ns-ha-enable elif [ "$ACTION" == "NOTIFY_SYNC" ]; then diff --git a/packages/ns-ha/files/100-conntrackd b/packages/ns-ha/files/100-conntrackd index f7830ae8f..06367ae39 100644 --- a/packages/ns-ha/files/100-conntrackd +++ b/packages/ns-ha/files/100-conntrackd @@ -1,6 +1,8 @@ # shellcheck source=/dev/null . /lib/functions/keepalived/hotplug.sh +ns_ha_chain_is_stale && exit 0 + if [ "$ACTION" == "NOTIFY_BACKUP" ]; then /usr/libexec/conntrackd.sh backup elif [ "$ACTION" == "NOTIFY_MASTER" ]; then diff --git a/packages/ns-ha/files/500-dhcp-force b/packages/ns-ha/files/500-dhcp-force index 486b10799..18d8622ed 100644 --- a/packages/ns-ha/files/500-dhcp-force +++ b/packages/ns-ha/files/500-dhcp-force @@ -1,5 +1,9 @@ #!/bin/sh +. /lib/functions/keepalived/hotplug.sh + +ns_ha_chain_is_stale && exit 0 + if [ "$ACTION" == "NOTIFY_MASTER" ]; then # Enable force option for all dnsmasq sections dnsmasq_sections=$(uci show dhcp | grep "=dnsmasq" | cut -d. -f2 | cut -d= -f1) diff --git a/packages/ns-ha/files/500-nathelpers b/packages/ns-ha/files/500-nathelpers index 94afea7de..ff3a31d5c 100644 --- a/packages/ns-ha/files/500-nathelpers +++ b/packages/ns-ha/files/500-nathelpers @@ -1,5 +1,9 @@ #!/bin/sh +. /lib/functions/keepalived/hotplug.sh + +ns_ha_chain_is_stale && exit 0 + if [ "$ACTION" == "NOTIFY_MASTER" ]; then if [ -f /etc/modules.d/ns-nathelpers ]; then /usr/sbin/load-kernel-modules diff --git a/packages/ns-ha/files/560-mac-binding b/packages/ns-ha/files/560-mac-binding index a668cdc1e..e265bb05b 100644 --- a/packages/ns-ha/files/560-mac-binding +++ b/packages/ns-ha/files/560-mac-binding @@ -2,6 +2,8 @@ . /lib/functions/keepalived/hotplug.sh +ns_ha_chain_is_stale && exit 0 + set_service_name ns-binding set_stop_if_backup diff --git a/packages/ns-ha/files/600-acme b/packages/ns-ha/files/600-acme index a261b0660..dff19aaed 100644 --- a/packages/ns-ha/files/600-acme +++ b/packages/ns-ha/files/600-acme @@ -3,6 +3,8 @@ . /lib/functions/keepalived/hotplug.sh . /lib/functions/keepalived/ns.sh +ns_ha_chain_is_stale && exit 0 + set_service_name acme set_restart_if_master diff --git a/packages/ns-ha/files/600-mwan3 b/packages/ns-ha/files/600-mwan3 index 05fb1608e..8c71d2846 100644 --- a/packages/ns-ha/files/600-mwan3 +++ b/packages/ns-ha/files/600-mwan3 @@ -3,6 +3,8 @@ # shellcheck source=/dev/null . /lib/functions/keepalived/hotplug.sh +ns_ha_chain_is_stale && exit 0 + set_service_name mwan3 set_restart_if_master diff --git a/packages/ns-ha/files/600-snort b/packages/ns-ha/files/600-snort index 017076b47..c16696bc1 100644 --- a/packages/ns-ha/files/600-snort +++ b/packages/ns-ha/files/600-snort @@ -3,6 +3,8 @@ . /lib/functions/keepalived/hotplug.sh . /lib/functions/keepalived/ns.sh +ns_ha_chain_is_stale && exit 0 + set_service_name snort set_restart_if_master diff --git a/packages/ns-ha/files/700-nginx b/packages/ns-ha/files/700-nginx index a28000a57..cb888ae14 100644 --- a/packages/ns-ha/files/700-nginx +++ b/packages/ns-ha/files/700-nginx @@ -3,6 +3,8 @@ # shellcheck source=/dev/null . /lib/functions/keepalived/hotplug.sh +ns_ha_chain_is_stale && exit 0 + set_service_name nginx set_restart_if_master diff --git a/packages/ns-ha/files/800-adblock b/packages/ns-ha/files/800-adblock index c127663f7..00b2336c8 100644 --- a/packages/ns-ha/files/800-adblock +++ b/packages/ns-ha/files/800-adblock @@ -3,6 +3,8 @@ . /lib/functions/keepalived/hotplug.sh . /lib/functions/keepalived/ns.sh +ns_ha_chain_is_stale && exit 0 + set_service_name adblock set_restart_if_master diff --git a/packages/ns-ha/files/800-banip b/packages/ns-ha/files/800-banip index 448b8fd64..aa01417a6 100644 --- a/packages/ns-ha/files/800-banip +++ b/packages/ns-ha/files/800-banip @@ -2,6 +2,8 @@ . /lib/functions/keepalived/hotplug.sh +ns_ha_chain_is_stale && exit 0 + set_service_name banip set_restart_if_master diff --git a/packages/ns-ha/files/800-dedalo b/packages/ns-ha/files/800-dedalo index e3395f2c4..05222bde8 100644 --- a/packages/ns-ha/files/800-dedalo +++ b/packages/ns-ha/files/800-dedalo @@ -2,6 +2,8 @@ . /lib/functions/keepalived/hotplug.sh +ns_ha_chain_is_stale && exit 0 + set_service_name dedalo set_restart_if_master diff --git a/packages/ns-ha/files/800-flashstart b/packages/ns-ha/files/800-flashstart index 16c3eb927..8230fa08e 100644 --- a/packages/ns-ha/files/800-flashstart +++ b/packages/ns-ha/files/800-flashstart @@ -2,6 +2,8 @@ . /lib/functions/keepalived/hotplug.sh +ns_ha_chain_is_stale && exit 0 + set_service_name flashstart set_restart_if_master diff --git a/packages/ns-ha/files/800-netifyd b/packages/ns-ha/files/800-netifyd index de4d53a83..4a17ec046 100644 --- a/packages/ns-ha/files/800-netifyd +++ b/packages/ns-ha/files/800-netifyd @@ -3,6 +3,8 @@ . /lib/functions/keepalived/hotplug.sh . /lib/functions/keepalived/ns.sh +ns_ha_chain_is_stale && exit 0 + set_service_name netifyd set_restart_if_master diff --git a/packages/ns-ha/files/800-ui b/packages/ns-ha/files/800-ui index 490157872..8a1652441 100644 --- a/packages/ns-ha/files/800-ui +++ b/packages/ns-ha/files/800-ui @@ -2,6 +2,8 @@ . /lib/functions/keepalived/hotplug.sh +ns_ha_chain_is_stale && exit 0 + set_service_name ns-ui set_restart_if_master diff --git a/packages/ns-ha/files/850-vpn b/packages/ns-ha/files/850-vpn new file mode 100644 index 000000000..cd3f729c1 --- /dev/null +++ b/packages/ns-ha/files/850-vpn @@ -0,0 +1,14 @@ +#!/bin/sh + +# +# Copyright (C) 2026 Nethesis S.r.l. +# SPDX-License-Identifier: GPL-2.0-only +# + +. /lib/functions/keepalived/hotplug.sh + +ns_ha_chain_is_stale && exit 0 + +if [ "$ACTION" == "NOTIFY_MASTER" ]; then + /usr/libexec/ns-ha-enable --vpn +fi diff --git a/packages/ns-ha/files/600-ipsec b/packages/ns-ha/files/860-ipsec similarity index 84% rename from packages/ns-ha/files/600-ipsec rename to packages/ns-ha/files/860-ipsec index d0ee03007..4bb4b91fe 100644 --- a/packages/ns-ha/files/600-ipsec +++ b/packages/ns-ha/files/860-ipsec @@ -3,6 +3,8 @@ # shellcheck source=/dev/null . /lib/functions/keepalived/hotplug.sh +ns_ha_chain_is_stale && exit 0 + set_service_name swanctl set_restart_if_master diff --git a/packages/ns-ha/files/600-openvpn b/packages/ns-ha/files/860-openvpn similarity index 84% rename from packages/ns-ha/files/600-openvpn rename to packages/ns-ha/files/860-openvpn index 3ecf25829..b4da0862d 100644 --- a/packages/ns-ha/files/600-openvpn +++ b/packages/ns-ha/files/860-openvpn @@ -3,6 +3,8 @@ # shellcheck source=/dev/null . /lib/functions/keepalived/hotplug.sh +ns_ha_chain_is_stale && exit 0 + set_service_name openvpn set_restart_if_master diff --git a/packages/ns-ha/files/900-ddns b/packages/ns-ha/files/900-ddns index 27c7b57a8..9bdaf48eb 100644 --- a/packages/ns-ha/files/900-ddns +++ b/packages/ns-ha/files/900-ddns @@ -2,6 +2,8 @@ . /lib/functions/keepalived/hotplug.sh +ns_ha_chain_is_stale && exit 0 + set_service_name ddns set_restart_if_master diff --git a/packages/ns-ha/files/900-ns-plug b/packages/ns-ha/files/900-ns-plug index 1dd207ff6..562cf015c 100644 --- a/packages/ns-ha/files/900-ns-plug +++ b/packages/ns-ha/files/900-ns-plug @@ -4,6 +4,8 @@ . /lib/functions/keepalived/hotplug.sh . /lib/functions/keepalived/ns.sh +ns_ha_chain_is_stale && exit 0 + set_service_name ns-plug set_restart_if_master diff --git a/packages/ns-ha/files/900-phonehome b/packages/ns-ha/files/900-phonehome index 2dbf51365..71cf3c407 100644 --- a/packages/ns-ha/files/900-phonehome +++ b/packages/ns-ha/files/900-phonehome @@ -4,6 +4,8 @@ . /lib/functions/keepalived/hotplug.sh . /lib/functions/keepalived/ns.sh +ns_ha_chain_is_stale && exit 0 + set_service_name phonehome if [ "$ACTION" == "NOTIFY_BACKUP" ]; then diff --git a/packages/ns-ha/files/900-telegraf b/packages/ns-ha/files/900-telegraf index eee680034..2b59fd5bb 100644 --- a/packages/ns-ha/files/900-telegraf +++ b/packages/ns-ha/files/900-telegraf @@ -8,6 +8,8 @@ # shellcheck source=/dev/null . /lib/functions/keepalived/hotplug.sh +ns_ha_chain_is_stale && exit 0 + set_service_name telegraf DROPINS="/etc/telegraf.conf.d/ping.conf /etc/telegraf.conf.d/dns.conf" diff --git a/packages/ns-ha/files/999-stop-fault b/packages/ns-ha/files/999-stop-fault index 37f84bb1f..7f79400e9 100644 --- a/packages/ns-ha/files/999-stop-fault +++ b/packages/ns-ha/files/999-stop-fault @@ -1,5 +1,9 @@ #!/bin/sh +. /lib/functions/keepalived/hotplug.sh + +ns_ha_chain_is_stale && exit 0 + # Tear down all services when a node is in fault state or keepalived has been manually stopped if [ "$ACTION" == "NOTIFY_STOP" ] || [ "$ACTION" == "NOTIFY_FAULT" ]; then logger -t ns-ha "Node is in $ACTION state, stopping all services" diff --git a/packages/ns-ha/files/999-unlock b/packages/ns-ha/files/999-unlock index e1a67e0a6..99afd1807 100644 --- a/packages/ns-ha/files/999-unlock +++ b/packages/ns-ha/files/999-unlock @@ -4,19 +4,26 @@ # SPDX-License-Identifier: GPL-2.0-only # # Release the global keepalived hotplug lock acquired by 00-lock. -# Only acts when the flag file created by 00-lock is present — this avoids -# incorrectly releasing a lock held by a concurrent event in the rare case -# where 00-lock timed out and proceeded without acquiring the lock. +# Only acts when the flag file created by 00-lock holds this chain's PID, so a +# chain that timed out and proceeded without the lock doesn't release it. case "$ACTION" in NOTIFY_MASTER|NOTIFY_BACKUP|NOTIFY_FAULT|NOTIFY_STOP) ;; *) return 0 2>/dev/null || exit 0 ;; esac +# shellcheck source=/dev/null +. /lib/functions/keepalived/hotplug.sh + +if ns_ha_chain_is_stale; then + log_info "$ACTION superseded by a newer event, skipped remaining actions" +fi +rm -f "/var/run/ns-ha/chain.$$" + LOCKFILE="/var/lock/keepalived-hotplug.lock" ACQUIRED_FLAG="/var/lock/keepalived-hotplug-acquired" -if [ -f "$ACQUIRED_FLAG" ]; then +if [ "$(cat "$ACQUIRED_FLAG" 2>/dev/null)" = "$$" ]; then rm -f "$ACQUIRED_FLAG" lock -u "$LOCKFILE" fi diff --git a/packages/ns-ha/files/ns-ha-disable b/packages/ns-ha/files/ns-ha-disable index afe9b2b5a..a8c7e6a2d 100644 --- a/packages/ns-ha/files/ns-ha-disable +++ b/packages/ns-ha/files/ns-ha-disable @@ -108,9 +108,10 @@ if __name__ == "__main__": if status.get("role") != "backup": sys.exit(0) # If --force is provided, skip the role check and proceed + # WAN first: the new master already sent the gratuitous ARP, this node must stop answering for the WAN IPs + disable_interfaces('wan_interfaces') disable_interfaces('wg_interfaces') disable_interfaces('ipsec_interfaces') - disable_interfaces('wan_interfaces') disable_hotspot() # Do not apply network changes yet, they will be applied when switching to primary if args.force: diff --git a/packages/ns-ha/files/ns-ha-enable b/packages/ns-ha/files/ns-ha-enable index 84235238e..fca79c050 100644 --- a/packages/ns-ha/files/ns-ha-enable +++ b/packages/ns-ha/files/ns-ha-enable @@ -155,9 +155,12 @@ if __name__ == "__main__": if status.get("state") != "master": # Execute only on master node, no matter the role sys.exit(0) + # VPN interfaces come up in a later hotplug step (850-vpn), after the essential services + if '--vpn' in sys.argv: + enable_interfaces('wg_interfaces') + enable_interfaces('ipsec_interfaces') + sys.exit(0) enable_interfaces('wan_interfaces') - enable_interfaces('wg_interfaces') - enable_interfaces('ipsec_interfaces') enable_hotspot_mac() send_gratuitous_arp('wan_interfaces') subprocess.run(["/sbin/reload_config"], capture_output=True) From 0112bca0ceaa1c19b0fd57b49c1ab63dc4a07930 Mon Sep 17 00:00:00 2001 From: Tommaso Bailetti Date: Mon, 16 Nov 2026 14:29:04 +0100 Subject: [PATCH 48/51] refactor: making subscription caching if success (#2013) --- AGENTS.md | 1 + packages/ns-api/README.md | 8 +- packages/ns-api/files/ns.subscription | 4 +- packages/ns-ha/files/900-ns-plug | 6 +- packages/ns-plug/Makefile | 8 +- packages/ns-plug/README.md | 15 ++ packages/ns-plug/files/20_ns-plug | 1 + packages/ns-plug/files/subscription-info | 58 ------ .../ns-plug/files/subscription-info-refresh | 8 + packages/ns-plug/files/subscription-info.init | 17 ++ packages/ns-plug/files/subscription-info.py | 179 ++++++++++++++++++ 11 files changed, 238 insertions(+), 67 deletions(-) delete mode 100755 packages/ns-plug/files/subscription-info create mode 100644 packages/ns-plug/files/subscription-info-refresh create mode 100644 packages/ns-plug/files/subscription-info.init create mode 100644 packages/ns-plug/files/subscription-info.py diff --git a/AGENTS.md b/AGENTS.md index 9fa1a8391..a9ab64ba6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -88,6 +88,7 @@ recent host Ruby (4.x), so the site is built in a `ruby:3.3` container and the - To add a package to the image, create a corresponding `config/.conf` fragment that enables it at build time. - Renovate manages external package versions via magic comments in Makefiles: `# renovate: datasource=github-tags depName=Org/Repo` - `packages/netifyd` is download-only: prebuilt per-arch binaries, filenames and hashes in `netify-dist.mk`, regenerated by `tools/netifyd-update/netifyd-update.py`. No compile step. +- Subscription status (`ns.subscription info`) is read from the `/etc/ns-plug/subscription.json` cache kept by `subscription-info` in `ns-plug`; everything else only checks `ns-plug.config.system_id`. - `packages/python3-nethsec/` (the `nethsec` Python library used by all `ns.*` API scripts) is vendored in this repo, not fetched from an external project — read `packages/python3-nethsec/src/nethsec/` directly rather than looking it up on GitHub. - fail2ban comes from upstream `net/fail2ban` in the pinned packages feed, patched to skip the fw3-era firewall include that restarts it on every firewall reload (`patches/feeds/packages/100-fail2ban-no-firewall-include.patch`) and to keep its DB on the data storage when mounted, else in `/var/run/fail2ban` (`patches/feeds/packages/101-fail2ban-data-storage.patch`); its jails, filters, `ns-insights` action, `ts-fail2ban` generator and `30-fail2ban` hotplug restart live in `ns-threat_shield`. diff --git a/packages/ns-api/README.md b/packages/ns-api/README.md index aeae37899..321c812bc 100644 --- a/packages/ns-api/README.md +++ b/packages/ns-api/README.md @@ -2784,7 +2784,7 @@ Error response: ### info -Retrieve subscription information from remote server: +Retrieve subscription information, from the local cache kept by `subscription-info` (see ns-plug README): ``` api-cli ns.subscription info ``` @@ -2796,11 +2796,15 @@ Success response: "systemd_id": "1af7701a-b2c5-4445-9718-e102c80aef55", "plan": "Trial Pizza", "expiration": 1697183326, - "active": true + "active": true, + "checked_at": 1762940000, + "stale": false } ``` If the subscription does not expire, `expiration` is set to `0`. +`checked_at` is the timestamp of the last answer from the remote server, `0` if there's none. +`stale` is `true` when the last check couldn't reach the remote server and the cached answer is returned. Error response: ```json diff --git a/packages/ns-api/files/ns.subscription b/packages/ns-api/files/ns.subscription index 0478ee8e1..e826b72d7 100755 --- a/packages/ns-api/files/ns.subscription +++ b/packages/ns-api/files/ns.subscription @@ -46,7 +46,7 @@ def info(): u = EUci() try: ret = {} - p = subprocess.run(["/usr/sbin/subscription-info", "1"], check=True, capture_output=True) + p = subprocess.run(["/usr/sbin/subscription-info"], check=True, capture_output=True) data = json.loads(p.stdout) except: sid = u.get('ns-plug', 'config', 'system_id', default=None) @@ -63,7 +63,7 @@ def info(): expiration = 0 type = u.get('ns-plug', 'config', 'type', default='') - ret = {"server_id": data["id"], "systemd_id": data["uuid"], "plan": data["subscription"]["subscription_plan"]["name"], "expiration": expiration, "active": active, "type": type} + ret = {"server_id": data["id"], "systemd_id": data["uuid"], "plan": data["subscription"]["subscription_plan"]["name"], "expiration": expiration, "active": active, "type": type, "checked_at": data.get("checked_at", 0), "stale": data.get("stale", False)} if type == "enterprise": ret["organization"] = data.get("organization", "") diff --git a/packages/ns-ha/files/900-ns-plug b/packages/ns-ha/files/900-ns-plug index 562cf015c..adf02e780 100644 --- a/packages/ns-ha/files/900-ns-plug +++ b/packages/ns-ha/files/900-ns-plug @@ -14,11 +14,11 @@ set_stop_if_backup RESTORE_LIST="/tmp/ns-ha/tmp/restore_list" if [ "$ACTION" == "NOTIFY_BACKUP" ]; then - update_cron "disable" "send-heartbeat send-backup send-inventory ns-push-reports update-packages" + update_cron "disable" "send-heartbeat send-backup send-inventory ns-push-reports update-packages subscription-info" elif [ "$ACTION" == "NOTIFY_MASTER" ]; then - update_cron "enable" "send-heartbeat send-backup send-inventory ns-push-reports update-packages" + update_cron "enable" "send-heartbeat send-backup send-inventory ns-push-reports update-packages subscription-info" elif [ "$ACTION" == "NOTIFY_SYNC" ]; then - update_cron "disable" "send-heartbeat send-backup send-inventory ns-push-reports update-packages" + update_cron "disable" "send-heartbeat send-backup send-inventory ns-push-reports update-packages subscription-info" # Remove backup.pass if it has been unset on the primary if ! grep -q /etc/backup.pass "$RESTORE_LIST" && [ -f /etc/backup.pass ]; then rm -f /etc/backup.pass diff --git a/packages/ns-plug/Makefile b/packages/ns-plug/Makefile index 57ada5b86..0085ab0a7 100644 --- a/packages/ns-plug/Makefile +++ b/packages/ns-plug/Makefile @@ -21,7 +21,7 @@ define Package/ns-plug CATEGORY:=NethSecurity TITLE:=NethSecurity controller client URL:=https://github.com/NethServer/nethsecurity-controller/ - DEPENDS:=+openvpn +lscpu +python3-nethsec +python3-yaml +telegraf +victoria-metrics +jq + DEPENDS:=+openvpn +lscpu +python3-nethsec +python3-requests +python3-yaml +telegraf +victoria-metrics +jq PKGARCH:=all endef @@ -56,6 +56,7 @@ if [ -z "$${IPKG_INSTROOT}" ]; then crontab -l | grep -v "/usr/sbin/send-backup" | sort | uniq | crontab - crontab -l | grep -v "/usr/sbin/send-inventory" | sort | uniq | crontab - crontab -l | grep -v "/usr/sbin/send-heartbeat" | sort | uniq | crontab - + crontab -l | grep -v "/usr/sbin/subscription-info" | sort | uniq | crontab - sed -i '/\/usr\/libexec\/ns-plug\/mwan-hooks/d' /etc/mwan3.user fi exit 0 @@ -85,7 +86,10 @@ define Package/ns-plug/install $(INSTALL_BIN) ./files/send-inventory.init $(1)/etc/init.d/send-inventory $(INSTALL_BIN) ./files/register $(1)/usr/sbin $(INSTALL_BIN) ./files/unregister $(1)/usr/sbin - $(INSTALL_BIN) ./files/subscription-info $(1)/usr/sbin + $(INSTALL_BIN) ./files/subscription-info.py $(1)/usr/sbin/subscription-info + $(INSTALL_BIN) ./files/subscription-info.init $(1)/etc/init.d/subscription-info + $(INSTALL_BIN) ./files/subscription-info-refresh $(1)/usr/share/ns-plug/hooks/register/50subscription-info + $(INSTALL_BIN) ./files/subscription-info-refresh $(1)/usr/share/ns-plug/hooks/unregister/50subscription-info $(INSTALL_BIN) ./files/update-packages $(1)/usr/sbin $(INSTALL_BIN) ./files/inventory $(1)/usr/sbin $(INSTALL_BIN) ./files/ns-download $(1)/usr/bin diff --git a/packages/ns-plug/README.md b/packages/ns-plug/README.md index c14907a97..306947b0c 100644 --- a/packages/ns-plug/README.md +++ b/packages/ns-plug/README.md @@ -89,6 +89,21 @@ To deregister the machine, execute: unregister ``` +### Subscription status + +`subscription-info` prints the subscription status, cached in `/etc/ns-plug/subscription.json`. +The cache isn't kept across image upgrades. + +The remote server is checked: +- at boot, by the `subscription-info` service, retrying for about 40 minutes until it answers +- every 4 hours by cron, with `subscription-info --refresh` +- on register and unregister, by the `50subscription-info` hooks +- when reading the status and the cache is missing, for another system, not valid, or valid but not + confirmed for more than a day; at most once every 30 seconds, with a 5 seconds timeout + +Only an answer from the remote server changes the cache: a timeout or a server error keeps the last known status. +A valid status that can't be confirmed for more than a day is reported as unknown. + ### Hooks The registration can be customized by adding scripts inside the `/usr/share/ns-plug/hooks/` directory: diff --git a/packages/ns-plug/files/20_ns-plug b/packages/ns-plug/files/20_ns-plug index c2fb219be..66ab3b4a2 100644 --- a/packages/ns-plug/files/20_ns-plug +++ b/packages/ns-plug/files/20_ns-plug @@ -4,6 +4,7 @@ crontab -l | grep -q '/usr/sbin/send-backup' || echo '02 2 * * * sleep $(( RANDOM % 1800 )); /usr/sbin/send-backup' >> /etc/crontabs/root crontab -l | grep -q '/usr/sbin/send-heartbeat' || echo '*/10 * * * * sleep $(( RANDOM % 60 )); /usr/sbin/send-heartbeat' >> /etc/crontabs/root crontab -l | grep -q '/usr/sbin/send-inventory' || echo '05 3 * * * sleep $(( RANDOM % 1800 )); /usr/sbin/send-inventory' >> /etc/crontabs/root +crontab -l | grep -q '/usr/sbin/subscription-info' || echo '15 */4 * * * sleep $(( RANDOM % 1800 )); /usr/sbin/subscription-info --refresh' >> /etc/crontabs/root if [ ! -f /etc/repo-channel ]; then echo "stable" > /etc/repo-channel diff --git a/packages/ns-plug/files/subscription-info b/packages/ns-plug/files/subscription-info deleted file mode 100755 index 8044984dd..000000000 --- a/packages/ns-plug/files/subscription-info +++ /dev/null @@ -1,58 +0,0 @@ -#!/bin/sh - -# -# Copyright (C) 2023 Nethesis S.r.l. -# SPDX-License-Identifier: GPL-2.0-only -# - -# -# Retrieve subscription information -# The script takes an optional timeout parameter -# - -timeout=${1:-20} - -system_id=$(uci -q get ns-plug.config.system_id) - -if [ -z "$system_id" ]; then - # no subscription - echo '{"uuid": ""}' - exit 0 -fi - -type=$(uci -q get ns-plug.config.type) -secret=$(uci -q get ns-plug.config.secret) - -if [ "$type" = "enterprise" ]; then - resp=$(/usr/bin/curl -f -s -m $timeout --retry-delay 1 --retry 2 -L \ - -H "Accept: application/json" \ - --user "$system_id:$secret" \ - "$(uci -q get ns-plug.config.collect_url)/info") || exit $? - - jq -c ' - .data as $s | - { - uuid: ($s.system_id // ""), - id: ($s.system_key // ""), - system_name: ($s.name // ""), - organization: ($s.organization.name // ""), - subscription: { - status: (if $s.registered and (($s.suspended // false) | not) then "valid" else "invalid" end), - valid_until: null, - subscription_plan: { name: ($s.organization.name // "-") } - } - } - ' < GRACE_PERIOD: + return None + return cache + + +def info(u): + system_id = u.get("ns-plug", "config", "system_id", default="") + if not system_id: + return {"uuid": ""} + + cache = usable_cache(system_id) + if cache is None or cache["state"] != "valid": + attempt = read_json(ATTEMPT_FILE) or {} + if time.time() - attempt.get("time", 0) >= THROTTLE: + refresh(u, 5, blocking=False) + cache = usable_cache(system_id) + + attempt = read_json(ATTEMPT_FILE) or {} + ret = { + "uuid": system_id, + "id": None, + "subscription": {"valid_until": None, "subscription_plan": {"name": "-"}}, + "checked_at": 0, + "stale": not attempt.get("ok", True), + } + if cache: + ret.update(cache.get("data") or {}) + ret["uuid"] = system_id + ret["checked_at"] = cache["checked_at"] + ret["subscription"] = ret["subscription"] or {"valid_until": None, "subscription_plan": {"name": "-"}} + # status is None when the state is unknown + ret["subscription"]["status"] = cache["state"] if cache else None + return ret + + +def main(): + parser = argparse.ArgumentParser(description="Retrieve subscription information") + group = parser.add_mutually_exclusive_group() + group.add_argument("--refresh", action="store_true", help="check the remote server now") + group.add_argument("--wait", action="store_true", help="check the remote server until it answers") + args = parser.parse_args() + + u = EUci() + if args.refresh: + sys.exit(0 if refresh(u, 20) else 1) + if args.wait: + for delay in WAIT_DELAYS: + time.sleep(delay) + if refresh(u, 20): + sys.exit(0) + sys.exit(1) + print(json.dumps(info(u))) + + +if __name__ == "__main__": + main() From ca3e4d99342038e870c13123473e07e1138ce20b Mon Sep 17 00:00:00 2001 From: Giacomo Sanchietti Date: Tue, 10 Nov 2026 14:11:43 +0100 Subject: [PATCH 49/51] feat(python3-nethsec): filter conntrack listings Live trace lists only the connections of one client, so list_connections() now accepts extra conntrack arguments and returns an empty list when conntrack prints nothing. Assisted-by: Claude Code:claude-opus-5-5 --- packages/python3-nethsec/src/nethsec/conntrack/__init__.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/packages/python3-nethsec/src/nethsec/conntrack/__init__.py b/packages/python3-nethsec/src/nethsec/conntrack/__init__.py index 8712432fb..d768a15d9 100644 --- a/packages/python3-nethsec/src/nethsec/conntrack/__init__.py +++ b/packages/python3-nethsec/src/nethsec/conntrack/__init__.py @@ -65,7 +65,7 @@ def __parse_connection_info(flow: Element) -> dict: return result -def list_connections(labels: list = None): +def list_connections(labels: list = None, extra_args: list = None): """ List all network connections. @@ -73,6 +73,7 @@ def list_connections(labels: list = None): - labels: optional list of label strings to filter by. Only connections that have ALL the specified labels are returned. If ``None`` or empty, all connections are returned. + - extra_args: optional list of extra conntrack arguments, e.g. ``["--orig-src", "10.0.0.1"]``. Returns: list of connections. @@ -80,7 +81,11 @@ def list_connections(labels: list = None): cmd = ["conntrack", "-L", "-o", "labels,xml"] if labels: cmd.extend(["-l", ",".join(labels)]) + if extra_args: + cmd.extend(extra_args) result = subprocess.run(cmd, capture_output=True, text=True) + if not result.stdout.strip(): + return [] root = ElementTree.fromstring(result.stdout) connections = [] for flow in root.findall('flow'): From a8e814a303faa049ed5ca6a114aa514a29e00cb1 Mon Sep 17 00:00:00 2001 From: Giacomo Sanchietti Date: Tue, 10 Nov 2026 14:33:51 +0100 Subject: [PATCH 50/51] feat(ns-api): add live trace troubleshooting API Administrators cannot tell which firewall layer blocks a client. ns.livetrace traces one client for a limited time and reports the blocking layer and rule, DNS queries, live connections and routing hints, using nftables tracing and tcpdump. Assisted-by: Claude Code:claude-sonnet-5-5 --- packages/ns-api/Makefile | 6 + packages/ns-api/README.md | 213 +++++++++ packages/ns-api/files/ns-livetrace.py | 571 ++++++++++++++++++++++++ packages/ns-api/files/ns.livetrace | 287 ++++++++++++ packages/ns-api/files/ns.livetrace.json | 13 + 5 files changed, 1090 insertions(+) create mode 100755 packages/ns-api/files/ns-livetrace.py create mode 100755 packages/ns-api/files/ns.livetrace create mode 100644 packages/ns-api/files/ns.livetrace.json diff --git a/packages/ns-api/Makefile b/packages/ns-api/Makefile index 930202e46..4dba8f17e 100644 --- a/packages/ns-api/Makefile +++ b/packages/ns-api/Makefile @@ -23,14 +23,17 @@ define Package/ns-api URL:=https://github.com/NethServer/nethsecurity-controller/ DEPENDS:= \ +adblock \ + +conntrack \ +coreutils-date \ +coreutils-stty \ + +ip-full \ +python3-idna \ +python3-nethsec \ +python3-openssl \ +python3-requests \ +python3-semver \ +python3-urllib \ + +tcpdump \ +whiptail \ +sshpass \ +wireguard-tools @@ -179,6 +182,8 @@ define Package/ns-api/install $(INSTALL_DATA) ./files/ns.ha.json $(1)/usr/share/rpcd/acl.d/ $(INSTALL_BIN) ./files/ns.flows $(1)/usr/libexec/rpcd/ $(INSTALL_DATA) ./files/ns.flows.json $(1)/usr/share/rpcd/acl.d/ + $(INSTALL_BIN) ./files/ns.livetrace $(1)/usr/libexec/rpcd/ + $(INSTALL_DATA) ./files/ns.livetrace.json $(1)/usr/share/rpcd/acl.d/ $(INSTALL_DIR) $(1)/lib/upgrade/keep.d $(INSTALL_CONF) files/ns-api.keep $(1)/lib/upgrade/keep.d/ns-api $(INSTALL_CONF) files/msmtp.keep $(1)/lib/upgrade/keep.d/msmtp @@ -187,6 +192,7 @@ define Package/ns-api/install $(INSTALL_BIN) ./files/load-kernel-modules $(1)/usr/sbin/load-kernel-modules $(INSTALL_BIN) ./files/setup $(1)/usr/sbin/setup $(INSTALL_BIN) ./files/firewall-apply-default-logging $(1)/usr/sbin/firewall-apply-default-logging + $(INSTALL_BIN) ./files/ns-livetrace.py $(1)/usr/libexec/ns-livetrace $(INSTALL_DIR) $(1)/etc/config $(INSTALL_CONF) ./files/config/ns-api $(1)/etc/config/ns-api $(INSTALL_CONF) ./files/config/ns-wizard $(1)/etc/config/ns-wizard diff --git a/packages/ns-api/README.md b/packages/ns-api/README.md index 321c812bc..644300da3 100644 --- a/packages/ns-api/README.md +++ b/packages/ns-api/README.md @@ -7995,6 +7995,219 @@ Example response: } ``` +## ns.livetrace + +Trace the live traffic of one client to find which layer blocks it. +One session at a time. Results stay readable after the session ends. + +### start + +Start a session. A running session is stopped first. + +Parameters: + +- `ip`: client IP address +- `duration`: seconds, from 10 to 600, default 120 +- `port`: optional, destination port of new connections, from 1 to 65535 +- `protocol`: optional, `tcp` or `udp` + +Missing, `null`, `0` and `""` mean not set. `port` and `protocol` do not filter DNS queries. + +```bash +api-cli ns.livetrace start --data '{"ip": "10.10.10.50", "duration": 120, "port": 443, "protocol": "tcp"}' +``` + +Example response: + +```json +{ + "message": "success" +} +``` + +Errors: + +- validation: `invalid_ip_address` (also for scoped, IPv4-mapped, multicast, loopback and unspecified addresses), + `invalid_duration`, `invalid_port`, `invalid_protocol` +- `collector_not_started`: the collector did not start, the reason is in `failure` of `status` +- `session_busy`: the running session did not stop within 5 seconds + +### stop + +Stop the running session: + +```bash +api-cli ns.livetrace stop +``` + +Example response: + +```json +{ + "message": "success" +} +``` + +### status + +Return the session state: + +```bash +api-cli ns.livetrace status +``` + +Example response: + +```json +{ + "running": true, + "ip": "10.10.10.50", + "duration": 120, + "port": 0, + "protocol": "", + "remaining": 87, + "blocked": [ + { + "protocol": "tcp", + "source": "10.10.10.50", + "destination": "1.0.0.1", + "destination_port": "80", + "layer": "threat_shield_ip", + "table": "banIP", + "chain": "_outbound", + "rule": "blocklist.v4", + "in_interface": "eth2", + "out_interface": "eth1", + "count": 5, + "first_seen": 1793706147, + "last_seen": 1793706152 + } + ], + "dns": [ + { + "name": "doubleclick.com", + "type": "A", + "result": "NXDOMAIN", + "filtered": true, + "count": 1, + "last_seen": 1793706213 + } + ], + "connections": [ + { + "source": "10.10.10.50", + "destination": "1.1.1.1", + "protocol": "tcp", + "source_port": "39494", + "destination_port": "80", + "source_stats": { + "packets": 6, + "bytes": 391 + }, + "destination_stats": { + "packets": 4, + "bytes": 602 + }, + "id": "4272941068", + "timeout": "115", + "state": "TIME_WAIT", + "labels": [ + "netify-analyzed" + ], + "in_interface": "eth2", + "out_interface": "eth1", + "rule": "Accept lan to wan forwarding", + "application": "wikimedia", + "dpi_protocol": "DNS", + "host": "auth.wikimedia.org" + } + ], + "allowed": [], + "failure": "", + "truncated": false +} +``` + +Example `allowed` when the session is not running: + +```json +[ + { + "protocol": "tcp", + "source": "10.10.10.50", + "destination": "1.1.1.1", + "destination_port": "443", + "in_interface": "eth2", + "out_interface": "eth1", + "rule": "Accept lan to wan forwarding", + "count": 3, + "source_ports": ["51234", "51236", "51240"] + } +] +``` + +Fields: + +- `port`, `protocol`: session filters, `0` and `""` when not set +- `failure`: error message of the collector, empty if none +- `truncated`: true if something was skipped: new connections over the rate limit, more than 200 `blocked` or + `dns` entries, more than 1000 flows (oldest dropped from `allowed`) + +`blocked`: new connections dropped or rejected. + +- `layer`: `firewall`, `dpi`, `threat_shield_ip`, `ips`, `dns_filter`, `mac_binding`, `routing` or the nftables table name +- `rule`: fw4 rule name, matching set name (e.g. banIP list) or nftables rule text +- `count`: number of distinct connections +- `application`, `host`: only with layer `dpi`, read from ns-flows, empty if the flow is unknown +- layer `routing` has empty `table` and `chain`, `rule` is one of: + - `no_route`: no route to the destination, or packet refused by reverse path filtering; + multicast and TTL 1 packets are not reported + - `private_to_wan`: a private destination (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 100.64.0.0/10, fc00::/7) + left through the device of the default route: missing route or tunnel down; the connection is also in `connections` + +`dns`: queries sent by the client and their replies. + +- `result`: response code (`NOERROR`, `NXDOMAIN`, ...), empty if no reply was seen +- `filtered`: true if adblock is enabled and the name, or a parent domain, is in its list; + the most specific allowlist or blocklist entry wins + +`connections`: conntrack entries of the client, same format as `ns.conntrack list`. Filled only while the session is running. + +- `rule`: fw4 rule that accepted the connection, only if the connection was traced +- `in_interface`, `out_interface`: from the trace, or from a route lookup if the connection was not traced +- `application`, `dpi_protocol`, `host`: read from ns-flows, if the flow is classified + +`allowed`: traced allowed connections of the last session, without traffic counters. Filled only when the session is not running. + +- grouped by `protocol`, `source`, `destination`, `destination_port`, `in_interface`, `out_interface` and `rule` +- `count`: number of traced connections, `source_ports`: their source ports +- sorted by `count`, descending + +Limitations: + +- only the first packet of each new connection and DPI-blocked packets are traced +- rate limit: 50 packets per second per direction, burst 100; needs `net.netfilter.nf_conntrack_acct=1` (OpenWrt default) +- Snort (IPS) drops are not shown: a connection dropped by Snort is listed as `allowed` +- a DPI block shows up after the flow is classified: the first packets pass +- chains with priority lower than -199 (e.g. the raw table) are not visible +- DNS filter detection covers adblock with dnsmasq only, not FlashStart +- `filtered` is also set when the query goes to an external resolver, and for adblock SafeSearch domains + (rewritten, not blocked) +- DNS over TCP and DNS over HTTPS are not captured +- with `port` or `protocol` set, ICMP is not traced +- connections opened before the session have no `rule`; the route lookup of their interfaces ignores + policy routing (multi-WAN) and port forwards +- a wrong route is detected only when a private destination leaves through the device of the default route +- port forwards: trace the public source IP with the public port; tracing the internal server shows no `rule` + and no `out_interface`; connections show the public destination address and port +- after a ruleset reload (firewall, banIP, DPI) `nft monitor trace` is restarted: packets traced before the restart + have an empty `rule` and may show the inner chain (e.g. `reject_to_wan`), connections started during the + restart are not listed +- if the traced IP is the remote side of a masqueraded connection, a DPI-blocked reply shows the WAN address and + the client port as destination and is also listed in `allowed`: trace the client instead +- if the collector is killed with SIGKILL, `nft monitor`, `tcpdump` and the `inet ns_livetrace` table stay + until `stop` or the next `start` + ## ns.objects Manage domain sets and host sets. diff --git a/packages/ns-api/files/ns-livetrace.py b/packages/ns-api/files/ns-livetrace.py new file mode 100755 index 000000000..840fdf66e --- /dev/null +++ b/packages/ns-api/files/ns-livetrace.py @@ -0,0 +1,571 @@ +#!/usr/bin/python3 +# +# Copyright (C) 2026 Nethesis S.r.l. +# SPDX-License-Identifier: GPL-2.0-only +# + +# Trace new connections and DNS queries of one client, write results to STATE. +# Usage: ns-livetrace [port] [protocol] + +import glob +import ipaddress +import json +import os +import queue +import re +import signal +import subprocess +import sys +import threading +import time + +import requests +from euci import EUci + +STATE = "/var/run/ns-livetrace.json" +PID = "/var/run/ns-livetrace.pid" +TABLE = "ns_livetrace" +MAX_ITEMS = 200 +MAX_FLOWS = 1000 +LAYERS = { + "fw4": "firewall", + "banIP": "threat_shield_ip", + "netifyd": "dpi", + "snort": "ips", + "adblock": "dns_filter", + "ns-binding": "mac_binding", +} +# chains that only execute the verdict decided by the rule jumping into them +REJECT_CHAINS = ("handle_reject", "_reject") +PRIVATE_NETS = [ + ipaddress.ip_network(n) + for n in ( + "10.0.0.0/8", + "172.16.0.0/12", + "192.168.0.0/16", + "100.64.0.0/10", + "fc00::/7", + ) +] +# fw4 zone chains reached by zone policies, forwardings and user rules +ZONE_VERDICT_RE = re.compile(r"(accept|drop|reject)_(to|from)_") + +TRACE_RE = re.compile(r"^trace id (\S+) \S+ (\S+) (\S+) (.*)$") +VERDICT_RE = re.compile(r"\(verdict (\w+)[^)]*\)$") +COMMENT_RE = re.compile(r'comment "!fw4: (.*)"') +QUERY_RE = re.compile(r": (\d+)\S* (?:\[\S+\] )*(\w+)\? (\S+) ") +REPLY_RE = re.compile(r": (\d+)\S* (?:([A-Z][A-Za-z]+)\S* )?(?:\[\S+\] )*\d+/\d+/\d+") + + +def nft(script, check=False): + subprocess.run( + ["nft", "-f", "-"], input=script, text=True, capture_output=True, check=check + ) + + +def tables(): + # a recreated table gets a new handle + return subprocess.run( + ["nft", "-j", "list", "tables"], capture_output=True, text=True + ).stdout + + +def field(regex, text): + m = re.search(regex, text) + return m.group(1) if m else "" + + +def rule_name(text): + comment = COMMENT_RE.search(text) + if comment: + return comment.group(1) + # banIP rules: the set name tells which list matched + ip_set = re.search(r"@(\S+)", text) + if ip_set: + return ip_set.group(1) + # rule resolved against a stale ruleset cache: no text to show + if text.startswith("unknown "): + return "" + text = re.sub(r"counter packets \d+ bytes \d+ ", "", text[len("rule ") :]) + return VERDICT_RE.sub("", text).strip() + + +def user_jump(t, chain): + # the stored jump is a user rule targeting this zone verdict chain + jump = t.get("jump") + return bool( + ZONE_VERDICT_RE.match(chain) + and jump + and COMMENT_RE.search(jump[2]) + and field(r"\(verdict (?:jump|goto) ([^)\s]+)", jump[2]) == chain + ) + + +def flow_key(protocol, source, source_port, destination, destination_port): + return f"{protocol}|{source}|{source_port}|{destination}|{destination_port}" + + +def is_private(address): + try: + ip = ipaddress.ip_address(address) + return any(ip in n for n in PRIVATE_NETS) + except ValueError: + return False + + +def is_multicast(address): + try: + return ipaddress.ip_address(address).is_multicast + except ValueError: + return False + + +# routes matching each destination, looked up again after ROUTE_TTL seconds +ROUTE_TTL = 10 +ROUTES = {} + + +def default_route_only(address, out): + # true when only default routes match and out is one of their devices + try: + cached = ROUTES.get(address) + if not cached or time.time() - cached[0] > ROUTE_TTL: + if len(ROUTES) >= MAX_FLOWS: + ROUTES.clear() + family = "-6" if ":" in address else "-4" + p = subprocess.run( + ["ip", family, "-j", "route", "list", "match", address], + capture_output=True, + text=True, + ) + ROUTES[address] = (time.time(), json.loads(p.stdout)) + routes = ROUTES[address][1] + return all(r.get("dst") == "default" for r in routes) and out in { + r.get("dev") for r in routes + } + except Exception: + return False + + +def dpi_flows(): + # ns-flows daemon is optional + try: + resp = requests.get("http://127.0.0.1:8080/flows", timeout=2) + return [item.get("flow") or {} for item in resp.json().get("flows", [])] + except Exception: + return [] + + +def dpi_app(flows, source, source_port, destination, destination_port): + ends = {(source, source_port), (destination, destination_port)} + for flow in flows: + local = (str(flow.get("local_ip")), str(flow.get("local_port"))) + other = (str(flow.get("other_ip")), str(flow.get("other_port"))) + if {local, other} == ends: + application = flow.get("detected_application_name") or "" + host = flow.get("host_server_name") or "" + return application.removeprefix("netify."), host + return "", "" + + +class Collector: + def __init__(self, ip, duration, port, protocol): + self.ip = ip + self.duration = duration + self.port = port + self.protocol = protocol + self.start = int(time.time()) + self.traces = {} + self.blocked = {} + self.blocked_tuples = {} + self.flows = {} + self.dns = {} + self.pending_dns = {} + self.filtered = {} + self.failure = "" + self.adblock_list = None + # nft monitor printed a rule missing from its ruleset cache + self.stale_rules = False + # something was skipped by the rate limit or a list cap + self.truncated = False + + def setup(self): + uci = EUci() + if uci.get("adblock", "global", "adb_enabled", default="0") == "1": + self.adblock_list = next( + iter(glob.glob("/tmp/dnsmasq.*.d/adb_list.overall")), None + ) + + def trace_line(self, line): + m = TRACE_RE.match(line) + if not m: + return + tid, table, chain, rest = m.groups() + if table == TABLE: + # each traced packet starts with a packet line of our own table + if rest.startswith("packet: "): + # trace id reused: keep the previous group to be closed on its own + if tid in self.traces: + self.traces[(tid, time.time())] = self.traces.pop(tid) + self.traces[tid] = { + "time": time.time(), + "last": time.time(), + "in": "", + "out": "", + "tuple": None, + "routed": False, + } + return + t = self.traces.get(tid) + if t is None: + return + t["last"] = time.time() + # any input or forward stage chain means the packet passed routing + if "input" in chain or "forward" in chain: + t["routed"] = True + if rest.startswith("packet: "): + t["in"] = t["in"] or field(r'\biif "([^"]+)"', rest) + t["out"] = t["out"] or field(r'\boif "([^"]+)"', rest) + if t["tuple"] is None: + t["ttl"] = field(r"\b(?:ip ttl|ip6 hoplimit) (\d+)", rest) + t["tuple"] = ( + # conntrack names ipv6-icmp as icmpv6 + field(r"\b(?:ip protocol|ip6 nexthdr) (\S+)", rest).replace( + "ipv6-icmp", "icmpv6" + ), + field(r"\bip6? saddr (\S+)", rest), + field(r"\b(?:tcp|udp) sport (\d+)", rest), + field(r"\bip6? daddr (\S+)", rest), + field(r"\b(?:tcp|udp) dport (\d+)", rest), + ) + return + if rest.startswith("unknown rule "): + self.stale_rules = True + is_rule = rest.startswith(("rule ", "unknown rule ")) + verdict = ( + field(r"\(verdict (\w+)", rest) + if is_rule + else field(r"^policy (\w+)", rest) + ) + if verdict in ("jump", "goto"): + if not user_jump(t, chain): + t["jump"] = (table, chain, rest) + elif verdict in ("drop", "reject") and "drop" not in t: + if "jump" in t and (chain in REJECT_CHAINS or user_jump(t, chain)): + t["drop"] = t["jump"] + else: + t["drop"] = ( + table, + chain, + rest if is_rule else "rule policy drop", + ) + elif ( + verdict == "accept" + and table == "fw4" + and not chain.startswith(("srcnat", "dstnat")) + ): + comment = COMMENT_RE.search(t["jump"][2] if user_jump(t, chain) else rest) + if comment and "accept" not in t: + t["accept"] = comment.group(1) + + def finalize(self, idle): + now = time.time() + flows = None + # unrouted groups wait longer: their input/forward lines may still be queued + for tid in [ + tid + for tid, t in self.traces.items() + if now - t["last"] >= (idle if t["routed"] or "drop" in t else idle * 10) + ]: + t = self.traces.pop(tid) + if t["tuple"] is None: + continue + protocol, source, source_port, destination, destination_port = t["tuple"] + if "drop" in t: + table, chain, text = t["drop"] + rule = rule_name(text) + layer = "dpi" if chain == "dpi_actions" else LAYERS.get(table, table) + # a flow accepted first and dropped later by DPI is blocked only + if layer == "dpi": + reply = (destination, destination_port, source, source_port) + for key in (t["tuple"], (protocol, *reply)): + self.flows.pop(flow_key(*key), None) + elif not t["routed"]: + # unjoined multicast and expiring TTL are dropped by routing on purpose + if is_multicast(destination) or t["ttl"] in ("0", "1"): + continue + # left prerouting without reaching input or forward: no route + table, chain, rule, layer = "", "", "no_route", "routing" + else: + key = flow_key(*t["tuple"]) + self.flows.pop(key, None) + self.flows[key] = { + "in_interface": t["in"], + "out_interface": t["out"], + "rule": t.get("accept", ""), + } + if len(self.flows) > MAX_FLOWS: + del self.flows[next(iter(self.flows))] + self.truncated = True + if ( + not t["out"] + or not is_private(destination) + or not default_route_only(destination, t["out"]) + ): + continue + # private destination on the default route: missing route or tunnel down + table, chain, rule, layer = "", "", "private_to_wan", "routing" + key = (protocol, source, destination, destination_port, table, chain, rule) + entry = self.blocked.get(key) + if entry is None: + if len(self.blocked) >= MAX_ITEMS: + self.truncated = True + continue + entry = self.blocked[key] = { + "protocol": protocol, + "source": source, + "destination": destination, + "destination_port": destination_port, + "layer": layer, + "table": table, + "chain": chain, + "rule": rule, + "in_interface": t["in"], + "out_interface": t["out"], + "count": 0, + "first_seen": int(t["time"]), + } + # retry while empty: ns-flows may publish the flow after the first drop + if layer == "dpi" and not entry.get("application"): + if flows is None: + flows = dpi_flows() + entry["application"], entry["host"] = dpi_app( + flows, source, source_port, destination, destination_port + ) + # count distinct connections, not packets + tuples = self.blocked_tuples.setdefault(key, set()) + if t["tuple"] not in tuples: + tuples.add(t["tuple"]) + entry["count"] += 1 + entry["last_seen"] = int(t["time"]) + + def is_filtered(self, name): + if self.adblock_list is None: + return False + if name not in self.filtered: + labels = name.split(".") + suffixes = [".".join(labels[i:]) for i in range(len(labels))] + args = [] + for s in suffixes: + args += ["-e", f"local=/{s}/", "-e", f"local=/{s}/#"] + found = set( + subprocess.run( + ["grep", "-xF", *args, self.adblock_list], + capture_output=True, + text=True, + ).stdout.splitlines() + ) + # most specific match wins, allowlist lines end with "#" + self.filtered[name] = next( + ( + f"local=/{s}/" in found + for s in suffixes + if f"local=/{s}/" in found or f"local=/{s}/#" in found + ), + False, + ) + return self.filtered[name] + + def dns_line(self, line): + m = QUERY_RE.search(line) + if m: + qid, qtype, name = m.group(1), m.group(2), m.group(3).rstrip(".") + if self.pending_dns.get(qid) == (name, qtype): + return + self.pending_dns[qid] = (name, qtype) + entry = self.dns.get((name, qtype)) + if entry is None: + if len(self.dns) >= MAX_ITEMS: + self.truncated = True + return + entry = self.dns[(name, qtype)] = { + "name": name, + "type": qtype, + "result": "", + "filtered": self.is_filtered(name), + "count": 0, + } + entry["count"] += 1 + entry["last_seen"] = int(time.time()) + return + m = REPLY_RE.search(line) + if m and m.group(1) in self.pending_dns: + entry = self.dns.get(self.pending_dns.pop(m.group(1))) + if entry: + entry["result"] = (m.group(2) or "NOERROR").upper() + + def check_skipped(self): + # false when the trace table is gone + p = subprocess.run( + ["nft", "list", "counter", "inet", TABLE, "skipped"], + capture_output=True, + text=True, + ) + if not self.truncated: + self.truncated = field(r"packets (\d+)", p.stdout) not in ("", "0") + return p.returncode == 0 + + def line(self, kind, line): + (self.trace_line if kind == "trace" else self.dns_line)(line) + + def write(self, running): + state = { + "running": running, + "ip": self.ip, + "duration": self.duration, + "port": self.port, + "protocol": self.protocol, + "start": self.start, + "blocked": list(self.blocked.values()), + "dns": list(self.dns.values()), + "flows": self.flows, + "failure": self.failure, + "truncated": self.truncated, + } + with open(STATE + ".tmp", "w") as f: + json.dump(state, f) + os.replace(STATE + ".tmp", STATE) + + +def reader(proc, kind, lines): + for line in proc.stdout: + lines.put((kind, line.rstrip("\n"))) + + +def main(): + ip = str(ipaddress.ip_address(sys.argv[1])) + duration = int(sys.argv[2]) + port = int(sys.argv[3]) if len(sys.argv) > 3 else 0 + protocol = sys.argv[4] if len(sys.argv) > 4 else "" + if protocol not in ("", "tcp", "udp"): + raise ValueError("invalid protocol") + family = "ip6" if ":" in ip else "ip" + # th dport is only meaningful on tcp/udp headers + l4proto = protocol or ("{ tcp, udp }" if port else "") + match = (f"meta l4proto {l4proto} " if l4proto else "") + ( + f"th dport {port} " if port else "" + ) + collector = Collector(ip, duration, port, protocol) + stop = threading.Event() + signal.signal(signal.SIGTERM, lambda *_: stop.set()) + collector.write(True) + procs = [] + threads = [] + lines = queue.Queue() + try: + collector.setup() + nft(f"table inet {TABLE}\ndelete table inet {TABLE}\n") + new = ( + f"{family} saddr {ip} {match}ct state new ct original packets 1", + f"{family} daddr {ip} {match}ct state new ct original packets 1", + ) + # DPI blocks a flow after its first packets + blocked = f"{family} saddr {ip} {match}ct label netify-blocked" + # accept only ends this chain; new connections reaching the counter were not traced + rules = "".join( + f"{r} limit rate 50/second burst 100 packets meta nftrace set 1 accept\n" + for r in (*new, blocked) + ) + "".join(f"{r} counter name skipped\n" for r in new) + nft( + f"table inet {TABLE} {{\ncounter skipped {{}}\nchain pre {{\n" + f"type filter hook prerouting priority -199;\n{rules}}}\n}}\n", + check=True, + ) + # only queries sent by the client and their replies + dns_filter = f"udp and ((src host {ip} and dst port 53) or (dst host {ip} and src port 53))" + + def spawn(kind, cmd): + proc = subprocess.Popen( + cmd, + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + text=True, + errors="replace", + ) + threads.append( + threading.Thread(target=reader, args=(proc, kind, lines), daemon=True) + ) + threads[-1].start() + return proc + + known = tables() + for kind, cmd in ( + ("trace", ["nft", "monitor", "trace"]), + ("dns", ["tcpdump", "-l", "-n", "-i", "any", dns_filter]), + ): + procs.append(spawn(kind, cmd)) + monitor = threads[0] + with open(PID, "w") as f: + f.write(str(os.getpid())) + end = time.time() + duration + last_write = 0 + while time.time() < end and not stop.is_set(): + try: + collector.line(*lines.get(timeout=0.5)) + except queue.Empty: + pass + if time.time() - last_write >= 1: + # a recreated table reuses rule handles: no unknown rule is printed + current = tables() + if current != known: + known = current + collector.stale_rules = True + # nft monitor caches the ruleset at start: restart it after a reload + if collector.stale_rules: + procs[0].kill() + procs[0].wait() + # lines of the old monitor must not ask for another restart + monitor.join(1) + while not lines.empty(): + collector.line(*lines.get()) + # groups cut by the restart would be reported as no_route + collector.traces = { + k: t + for k, t in collector.traces.items() + if t["routed"] or "drop" in t + } + procs[0] = spawn("trace", procs[0].args) + monitor = threads[-1] + collector.stale_rules = False + for proc in procs: + if proc.poll() is not None: + raise RuntimeError(f"{proc.args[0]} exited") + collector.finalize(0.5) + if not collector.check_skipped(): + raise RuntimeError("trace table removed") + collector.write(True) + last_write = time.time() + except Exception as e: + collector.failure = (getattr(e, "stderr", None) or str(e)).strip() + finally: + collector.check_skipped() + nft(f"delete table inet {TABLE}\n") + for proc in procs: + proc.kill() + proc.wait() + for thread in threads: + thread.join(1) + # process lines still queued before closing the open groups + try: + while not lines.empty(): + collector.line(*lines.get()) + except Exception as e: + collector.failure = collector.failure or str(e) + collector.finalize(0) + collector.write(False) + if os.path.exists(PID): + os.remove(PID) + + +if __name__ == "__main__": + main() diff --git a/packages/ns-api/files/ns.livetrace b/packages/ns-api/files/ns.livetrace new file mode 100755 index 000000000..c19254725 --- /dev/null +++ b/packages/ns-api/files/ns.livetrace @@ -0,0 +1,287 @@ +#!/usr/bin/python3 +# +# Copyright (C) 2026 Nethesis S.r.l. +# SPDX-License-Identifier: GPL-2.0-only +# + +import fcntl +import ipaddress +import json +import os +import signal +import subprocess +import sys +import time +from collections import defaultdict + +import requests +from nethsec import conntrack +from nethsec.utils import validation_error + +STATE = "/var/run/ns-livetrace.json" +PID = "/var/run/ns-livetrace.pid" +LOCK = "/var/run/ns-livetrace.lock" +FLOW_FIELDS = ("protocol", "source", "source_port", "destination", "destination_port") +ALLOWED_FIELDS = ( + "protocol", + "source", + "destination", + "destination_port", + "in_interface", + "out_interface", + "rule", +) + + +def running_pid(): + try: + with open(PID) as f: + pid = int(f.read()) + with open(f"/proc/{pid}/cmdline", "rb") as f: + return pid if b"ns-livetrace" in f.read() else None + except (OSError, ValueError): + return None + + +def delete_table(): + subprocess.run( + ["nft", "delete", "table", "inet", "ns_livetrace"], capture_output=True + ) + + +def stop(): + pid = running_pid() + if pid is not None: + try: + os.kill(pid, signal.SIGTERM) + except ProcessLookupError: + pass + # a SIGKILLed collector leaves its table behind + for _ in range(50): + if running_pid() is None: + delete_table() + return + time.sleep(0.1) + + +def start(data): + ip = data.get("ip", "") + duration = data.get("duration", 120) + try: + addr = ipaddress.ip_address(ip) + # nft cannot trace these addresses + if ( + not isinstance(ip, str) + or "%" in str(addr) + or getattr(addr, "ipv4_mapped", None) + or addr.is_multicast + or addr.is_loopback + or addr.is_unspecified + ): + raise ValueError + except ValueError: + return validation_error("ip", "invalid_ip_address", ip) + ip = str(addr) + # bool is an int subclass + if type(duration) is not int or not 10 <= duration <= 600: + return validation_error("duration", "invalid_duration", duration) + port = data.get("port") or 0 + protocol = data.get("protocol") or "" + if type(port) is not int or not 0 <= port <= 65535: + return validation_error("port", "invalid_port", port) + if protocol not in ("", "tcp", "udp"): + return validation_error("protocol", "invalid_protocol", protocol) + # serialize concurrent starts; the fd is not inherited by the collector + with open(LOCK, "w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX) + stop() + if running_pid() is not None: + return {"error": "session_busy"} + # a collector dying before its first write must not show the old session + if os.path.exists(STATE): + os.remove(STATE) + proc = subprocess.Popen( + ["/usr/libexec/ns-livetrace", ip, str(duration), str(port), protocol], + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + start_new_session=True, + ) + # wait for the collector so the next status reports running + for _ in range(50): + if running_pid() is not None or proc.poll() is not None: + break + time.sleep(0.1) + if running_pid() is None: + # kill the late collector and its helpers so no orphan session survives + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + proc.wait() + delete_table() + return {"error": "collector_not_started"} + return {"message": "success"} + + +def dpi_flows(): + # ns-flows daemon is optional + try: + resp = requests.get("http://127.0.0.1:8080/flows", timeout=2) + flows = {} + for item in resp.json().get("flows", []): + flow = item.get("flow") or {} + ct_id = (flow.get("conntrack") or {}).get("id") + if ct_id is None: + continue + application = flow.get("detected_application_name") or "" + flows[str(ct_id)] = { + "application": application.removeprefix("netify."), + "dpi_protocol": flow.get("detected_protocol_name") or "", + "host": flow.get("host_server_name") or "", + } + return flows + except Exception: + return {} + + +def route_devs(addresses): + devs = dict.fromkeys(addresses, "") + names = {} + for a in addresses: + try: + names[str(ipaddress.ip_address(a))] = a + except ValueError: + pass + if not names: + return devs + # one ip process for all addresses, results matched by normalized dst + try: + p = subprocess.run( + ["ip", "-j", "-force", "-batch", "-"], + input="".join(f"route get {a}\n" for a in names), + capture_output=True, + text=True, + ) + except OSError: + return devs + for line in p.stdout.splitlines(): + try: + route = json.loads(line)[0] + name = names[str(ipaddress.ip_address(route["dst"]))] + except (ValueError, IndexError, KeyError, TypeError): + continue + if route.get("type") != "local": + devs[name] = route.get("dev", "") + return devs + + +def status(): + try: + with open(STATE) as f: + state = json.load(f) + except (OSError, ValueError): + state = { + "ip": "", + "duration": 0, + "start": 0, + "blocked": [], + "dns": [], + "flows": {}, + "failure": "", + } + running = running_pid() is not None + connections = [] + if running: + seen = set() + untraced = [] + dpi = dpi_flows() + ip = state["ip"] + port = state.get("port", 0) + # conntrack needs a protocol to filter by port + protocols = [state.get("protocol", "")] + if port and not protocols[0]: + protocols = ["tcp", "udp"] + queries = [] + for p in protocols: + proto = ["-p", p] if p else [] + dport = ["--dport", str(port)] if port else [] + sport = ["--reply-port-src", str(port)] if port else [] + queries += [ + ["--orig-src", ip, *proto, *dport], + ["--reply-src", ip, *proto, *sport], + ] + for args in queries: + for c in conntrack.list_connections(extra_args=args): + if c["id"] in seen: + continue + seen.add(c["id"]) + key = "|".join(c.get(k, "") for k in FLOW_FIELDS) + conn = {**c, **state["flows"].get(key, {}), **dpi.get(c["id"], {})} + # not traced, derive interfaces from the routing table + if "in_interface" not in conn: + untraced.append(conn) + connections.append(conn) + devs = route_devs( + {a for c in untraced for a in (c["source"], c["destination"])} + ) + for conn in untraced: + conn["in_interface"] = devs[conn["source"]] + conn["out_interface"] = devs[conn["destination"]] + allowed = defaultdict(list) + if not running: + # traced allowed flows of the last session, source ports merged + for key, flow in state.get("flows", {}).items(): + protocol, source, sport, destination, port = key.split("|") + extra = (flow.get(k, "") for k in ALLOWED_FIELDS[4:]) + allowed[(protocol, source, destination, port, *extra)].append(sport) + return { + "running": running, + "ip": state["ip"], + "duration": state["duration"], + "port": state.get("port", 0), + "protocol": state.get("protocol", ""), + "remaining": max(0, int(state["start"] + state["duration"] - time.time())) + if running + else 0, + "blocked": state["blocked"], + "dns": state["dns"], + "connections": connections, + "allowed": [ + {**dict(zip(ALLOWED_FIELDS, k)), "count": len(p), "source_ports": p} + for k, p in sorted(allowed.items(), key=lambda i: len(i[1]), reverse=True) + ], + "failure": state.get("failure", ""), + "truncated": state.get("truncated", False), + } + + +if __name__ == "__main__": + cmd = sys.argv[1] + if cmd == "list": + print( + json.dumps( + { + "start": { + "ip": "10.10.10.50", + "duration": 120, + "port": 443, + "protocol": "tcp", + }, + "stop": {}, + "status": {}, + } + ) + ) + elif cmd == "call": + action = sys.argv[2] + if action == "start": + print(json.dumps(start(json.load(sys.stdin)))) + elif action == "stop": + # a starting collector has its table but no PID file yet + with open(LOCK, "w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX) + stop() + print(json.dumps({"message": "success"})) + elif action == "status": + print(json.dumps(status())) diff --git a/packages/ns-api/files/ns.livetrace.json b/packages/ns-api/files/ns.livetrace.json new file mode 100644 index 000000000..cc3f8bbcc --- /dev/null +++ b/packages/ns-api/files/ns.livetrace.json @@ -0,0 +1,13 @@ +{ + "livetrace-manager": { + "description": "Trace live traffic of a client", + "write": {}, + "read": { + "ubus": { + "ns.livetrace": [ + "*" + ] + } + } + } +} From bbcb360377790d10c826d0bd0e5c48575d0e5ee8 Mon Sep 17 00:00:00 2001 From: Giacomo Sanchietti Date: Tue, 17 Nov 2026 11:10:33 +0100 Subject: [PATCH 51/51] chore(ns-ui): TEMP build UI from live trace branch Build the UI from the nethsecurity-ui firewall_debug branch to test the live trace page. Drop this commit before merging. Assisted-by: Claude Code:Opus 5.5 --- packages/ns-ui/Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/ns-ui/Makefile b/packages/ns-ui/Makefile index b266e63a4..ec3ad44fd 100644 --- a/packages/ns-ui/Makefile +++ b/packages/ns-ui/Makefile @@ -12,7 +12,7 @@ PKG_RELEASE:=1 PKG_SOURCE_PROTO:=git PKG_SOURCE_URL:=https://github.com/NethServer/nethsecurity-ui.git -PKG_SOURCE_VERSION:=455432490c9e32175fa4c25d6441022dcf3be51f +PKG_SOURCE_VERSION:=6badfc71e7cca48f91f95bde4a140b2e63e29aee PKG_SOURCE_SUBDIR:=nethsecurity-ui-$(PKG_SOURCE_VERSION) PKG_BUILD_DIR:=$(BUILD_DIR)/$(PKG_SOURCE_SUBDIR) PKG_MIRROR_HASH:=skip