From 3a72e2601c5b02731e22558cf4051b0f18dae039 Mon Sep 17 00:00:00 2001 From: Tommaso Bailetti Date: Mon, 2 Nov 2026 17:01:05 +0100 Subject: [PATCH 01/54] 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 f114356fa47afde4ed6ac699ec53fc79c22e218e Mon Sep 17 00:00:00 2001 From: Tommaso Bailetti Date: Mon, 2 Nov 2026 17:02:43 +0100 Subject: [PATCH 02/54] 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 43ba2330d7d24c2450efca5af4596fab4d1582d6 Mon Sep 17 00:00:00 2001 From: Tommaso Bailetti Date: Mon, 2 Nov 2026 17:11:56 +0100 Subject: [PATCH 03/54] 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 585d7f8c2f65ad9ff56bc2892814f0dbb27906ed Mon Sep 17 00:00:00 2001 From: Tommaso Bailetti Date: Tue, 3 Nov 2026 09:20:56 +0100 Subject: [PATCH 04/54] 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 cddc68e94a88cb9dd0163de59cb554a05814f453 Mon Sep 17 00:00:00 2001 From: Tommaso Bailetti Date: Tue, 3 Nov 2026 15:49:17 +0100 Subject: [PATCH 05/54] 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 f351d1bba0598bb1eec6c64150da094ca5744e25 Mon Sep 17 00:00:00 2001 From: Tommaso Bailetti Date: Tue, 3 Nov 2026 16:02:58 +0100 Subject: [PATCH 06/54] 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 a88d1198a8bde253125ac5f6914386df8e02e50c Mon Sep 17 00:00:00 2001 From: Tommaso Bailetti Date: Thu, 5 Nov 2026 17:04:46 +0100 Subject: [PATCH 07/54] 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 034273973104d79c621ad0f6175bc427718e51be Mon Sep 17 00:00:00 2001 From: Filippo Carletti Date: Tue, 3 Nov 2026 15:23:57 +0100 Subject: [PATCH 08/54] 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 cfb3ad1cc2418979011d5c111bf4adf319bd582b Mon Sep 17 00:00:00 2001 From: Giacomo Sanchietti Date: Wed, 4 Nov 2026 08:26:24 +0100 Subject: [PATCH 09/54] 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 fb25b4621f8dc631b5bf03d7943e7615b3f8e6c9 Mon Sep 17 00:00:00 2001 From: Giacomo Sanchietti Date: Wed, 4 Nov 2026 08:26:25 +0100 Subject: [PATCH 10/54] 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 610cafd6707c184112472e709a5f3d2ec43e55d8 Mon Sep 17 00:00:00 2001 From: Giacomo Sanchietti Date: Wed, 4 Nov 2026 08:26:42 +0100 Subject: [PATCH 11/54] 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 d99349e80f0d104e27d2ab93cd23ea8f77849aad Mon Sep 17 00:00:00 2001 From: Giacomo Sanchietti Date: Wed, 4 Nov 2026 08:31:11 +0100 Subject: [PATCH 12/54] 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 8f7bbd2dc97fcd1a89ff546890914e28d5a9564b Mon Sep 17 00:00:00 2001 From: Tommaso Bailetti Date: Wed, 4 Nov 2026 12:45:01 +0100 Subject: [PATCH 13/54] 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 a389743782ec9e034fd2d7e65c5b59072032396b Mon Sep 17 00:00:00 2001 From: Tommaso Bailetti Date: Wed, 4 Nov 2026 17:31:55 +0100 Subject: [PATCH 14/54] 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 41753386e06cd9211917cf645c9fb1a1438df492 Mon Sep 17 00:00:00 2001 From: Tommaso Bailetti Date: Wed, 4 Nov 2026 17:34:13 +0100 Subject: [PATCH 15/54] 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 7fa69d5a7..c42d65f1e 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 b2b1918ee146d166a2620edfeef78c7fb379ea6a Mon Sep 17 00:00:00 2001 From: Tommaso Bailetti Date: Wed, 4 Nov 2026 17:34:53 +0100 Subject: [PATCH 16/54] 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 a2c15775481b665493ba3353e9496a72362d12cb Mon Sep 17 00:00:00 2001 From: Tommaso Bailetti Date: Wed, 4 Nov 2026 17:41:23 +0100 Subject: [PATCH 17/54] 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 d36232f843bb25bd7780223bfe1278f5aac008c2 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/54] 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 ba2a5ab77c9179b569728df50aad14e5bf8db852 Mon Sep 17 00:00:00 2001 From: Giacomo Sanchietti Date: Thu, 5 Nov 2026 09:47:24 +0100 Subject: [PATCH 19/54] 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 62689353d6a8c89b595683495e2563925550eda6 Mon Sep 17 00:00:00 2001 From: Tommaso Bailetti Date: Fri, 6 Nov 2026 14:42:57 +0100 Subject: [PATCH 20/54] 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 ece00fcac8465e2fede5413585bde9ee657b706d Mon Sep 17 00:00:00 2001 From: Tommaso Bailetti Date: Fri, 6 Nov 2026 16:14:54 +0100 Subject: [PATCH 21/54] 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 0629da15b982ebe01c6ac09b3adde9782e23c571 Mon Sep 17 00:00:00 2001 From: Giacomo Sanchietti Date: Fri, 6 Nov 2026 17:13:15 +0100 Subject: [PATCH 22/54] 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 ef4179870..1513e4ea7 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: @@ -6163,9 +6163,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: @@ -6174,9 +6176,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). @@ -6184,7 +6186,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: @@ -6224,6 +6226,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"}' @@ -6334,6 +6338,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: @@ -7427,11 +7480,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: @@ -7440,11 +7492,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" } ] } @@ -7453,8 +7507,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 @@ -8047,10 +8100,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 c42d65f1e..acc7b2e30 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 21e5cc069..edb6a0b2e 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 2dd8f8301..d3fb4684a 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 bac939f2618961f0c3cbbc128abec7b2cc7e7403 Mon Sep 17 00:00:00 2001 From: Tommaso Bailetti Date: Fri, 6 Nov 2026 17:14:32 +0100 Subject: [PATCH 23/54] 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 acc7b2e30..bfd813492 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 551187ca3709de530b871df21861569f06bcd900 Mon Sep 17 00:00:00 2001 From: Tommaso Bailetti Date: Fri, 6 Nov 2026 17:39:10 +0100 Subject: [PATCH 24/54] 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 a7eb8599b0c02f4ae8298b154a5f7fcad918f922 Mon Sep 17 00:00:00 2001 From: Tommaso Bailetti Date: Mon, 9 Nov 2026 10:01:45 +0100 Subject: [PATCH 25/54] 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 c958549397613820b01f79cc99a4a03277f27cca Mon Sep 17 00:00:00 2001 From: Giacomo Sanchietti Date: Mon, 9 Nov 2026 15:08:51 +0100 Subject: [PATCH 26/54] 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 89ca2bbdf3807f92ba1183dacd644f5a2d0de144 Mon Sep 17 00:00:00 2001 From: Giacomo Sanchietti Date: Mon, 9 Nov 2026 15:18:44 +0100 Subject: [PATCH 27/54] 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 d7819a65e22ef5b5fcb5dc501789dbc4b20dc903 Mon Sep 17 00:00:00 2001 From: Giacomo Sanchietti Date: Mon, 9 Nov 2026 15:46:23 +0100 Subject: [PATCH 28/54] 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 582c64f34394ec5f4dcea8ddf137a3fb06c6f161 Mon Sep 17 00:00:00 2001 From: Giacomo Sanchietti Date: Mon, 9 Nov 2026 15:46:39 +0100 Subject: [PATCH 29/54] 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 11d412bb3b8863699a4a82030dc6ba33e2a648ca 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/54] 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 1513e4ea7..3fbebe5d5 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 fbe780d0f0161fbf60c1d81fe5c6e007ff6441e6 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/54] 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 e1e94a02f422d196c5855b911505ddf6904b7442 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/54] 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 535e177f21a54ea5262944d5700f33ec45c23775 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/54] 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 3fbebe5d5..dc06b7485 100644 --- a/packages/ns-api/README.md +++ b/packages/ns-api/README.md @@ -7214,6 +7214,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 1109f533ba3bc536f4645febf481508a62c40d0d Mon Sep 17 00:00:00 2001 From: Tommaso Bailetti Date: Tue, 10 Nov 2026 17:36:11 +0100 Subject: [PATCH 34/54] 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 c9f44ed336b38a58c1b5762a8c3a5e14c743ee8d Mon Sep 17 00:00:00 2001 From: Tommaso Bailetti Date: Wed, 11 Nov 2026 17:29:05 +0100 Subject: [PATCH 35/54] 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 6a455e999ceeb976b634a3a7e9e1604c7fc15c05 Mon Sep 17 00:00:00 2001 From: Tommaso Bailetti Date: Thu, 12 Nov 2026 10:34:35 +0100 Subject: [PATCH 36/54] 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 a2f3b29bb3e29a97cb1921057b9a3b1a2957c8e9 Mon Sep 17 00:00:00 2001 From: Tommaso Bailetti Date: Thu, 12 Nov 2026 11:44:50 +0100 Subject: [PATCH 37/54] 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 8d2f59c3fd878ea9b84ed265b3dd3075f29dccea Mon Sep 17 00:00:00 2001 From: Giacomo Sanchietti Date: Wed, 11 Nov 2026 08:27:51 +0100 Subject: [PATCH 38/54] 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 edb6a0b2e..6162fd63c 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 d3fb4684a..2a80dac7f 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 3e3b535bf58ccce98c0eda8a40d94958fe55f047 Mon Sep 17 00:00:00 2001 From: Giacomo Sanchietti Date: Wed, 11 Nov 2026 08:27:51 +0100 Subject: [PATCH 39/54] 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 dc06b7485..a3cd6b423 100644 --- a/packages/ns-api/README.md +++ b/packages/ns-api/README.md @@ -6137,9 +6137,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", @@ -6150,6 +6164,7 @@ Response example: { "name": "doh", "type": "community", + "custom": false, "enabled": true, "confidence": -1, "description": "public DoH-Server", @@ -6161,8 +6176,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) @@ -6213,11 +6231,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 ddd9a58239ab7cc3c042f9ea4b25f333747f366d Mon Sep 17 00:00:00 2001 From: Giacomo Sanchietti Date: Wed, 11 Nov 2026 08:27:51 +0100 Subject: [PATCH 40/54] 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 69450711cc25ef83ce0be6d709920cd21902b9d3 Mon Sep 17 00:00:00 2001 From: Giacomo Sanchietti Date: Wed, 11 Nov 2026 08:27:51 +0100 Subject: [PATCH 41/54] 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 a424378b9dd1f846405e9d7a14dad2b2c7829667 Mon Sep 17 00:00:00 2001 From: Giacomo Sanchietti Date: Thu, 12 Nov 2026 10:50:09 +0100 Subject: [PATCH 42/54] 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 a3cd6b423..d6b386b8e 100644 --- a/packages/ns-api/README.md +++ b/packages/ns-api/README.md @@ -6536,6 +6536,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 ee47b155a6686988040b892413049e55f9e46dcd Mon Sep 17 00:00:00 2001 From: Giacomo Sanchietti Date: Thu, 12 Nov 2026 14:27:20 +0100 Subject: [PATCH 43/54] 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 bfd813492..6a6cb76ee 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 b31840252e8028dc1bb25ab925348f20483fc6ad Mon Sep 17 00:00:00 2001 From: Tommaso Bailetti Date: Thu, 12 Nov 2026 15:58:26 +0100 Subject: [PATCH 44/54] 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 dec34430619ddfa6389b6532c4885a39af78a164 Mon Sep 17 00:00:00 2001 From: Tommaso Bailetti Date: Thu, 12 Nov 2026 18:07:22 +0100 Subject: [PATCH 45/54] 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 1182e0ddfa58f0a7be37b6e0e73b6c9f0b566e8b Mon Sep 17 00:00:00 2001 From: Tommaso Bailetti Date: Fri, 13 Nov 2026 09:23:30 +0100 Subject: [PATCH 46/54] 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 8e1826cd1da9e14b3d434203433df15536fede66 Mon Sep 17 00:00:00 2001 From: Tommaso Bailetti Date: Fri, 13 Nov 2026 17:36:21 +0100 Subject: [PATCH 47/54] 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 d6b386b8e..772ca18b1 100644 --- a/packages/ns-api/README.md +++ b/packages/ns-api/README.md @@ -9315,8 +9315,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 310b80e10c9e454c0e408c32d4550321775cf535 Mon Sep 17 00:00:00 2001 From: Tommaso Bailetti Date: Mon, 16 Nov 2026 14:29:04 +0100 Subject: [PATCH 48/54] 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 772ca18b1..ab8ac662e 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 affd3567e679fa469bbc8b4ab0a52cfad364e428 Mon Sep 17 00:00:00 2001 From: Tommaso Bailetti Date: Tue, 17 Nov 2026 11:14:36 +0100 Subject: [PATCH 49/54] fix(ovpn): DCO status hang and disable toggle (#2018) Issue: OpenVPN/openvpn#1146 --- packages/ns-api/README.md | 11 +++++++++-- packages/ns-api/files/ns.ovpnrw | 4 ++++ packages/ns-api/files/ns.ovpntunnel | 14 ++++++++++---- packages/ns-openvpn/files/openvpn-status | 3 +++ .../python3-nethsec/src/nethsec/ovpn/__init__.py | 2 +- .../packages/101-openvpn-dco-status-reply.patch | 15 +++++++++++++++ .../102-openvpn-dco-stats-no-tls-multi.patch | 13 +++++++++++++ 7 files changed, 55 insertions(+), 7 deletions(-) create mode 100644 patches/feeds/packages/101-openvpn-dco-status-reply.patch create mode 100644 patches/feeds/packages/102-openvpn-dco-stats-no-tls-multi.patch diff --git a/packages/ns-api/README.md b/packages/ns-api/README.md index ab8ac662e..7a4d84336 100644 --- a/packages/ns-api/README.md +++ b/packages/ns-api/README.md @@ -1118,6 +1118,7 @@ The following fields are aoptionals: - compress - auth - cipher +- disable_dco: `1` to turn off data channel offload (DCO), defaults to `0` Response example: ```json @@ -1150,6 +1151,8 @@ Add a tunnel server with p2p topology: api-cli ns.ovpntunnel add-server --data '{"ns_name": "server2", "port": "2003", "topology": "p2p", "proto": "tcp", "local": ["192.168.100.0/24"], "remote": ["192.168.5.0/24"], "secret": "#\n# 2048 bit OpenVPN static key\n#\n-----BEGIN OpenVPN Static key V1-----....----END OpenVPN Static key V1-----\n", "compress": "", "auth": "", "cipher": "", "ns_public_ip": ["1.2.3.4"], "tls_version_min": "1.2", "ifconfig_local": "192.168.3.1", "ifconfig_remote": "192.168.3.2"}' ``` +The optional `disable_dco` field set to `1` turns off data channel offload (DCO), defaults to `0`. + Response example: ```json { id"": "ns_server1" } @@ -1521,7 +1524,8 @@ Response example for a server in routed mode: "192.168.100.0/24" ], "ns_dhcp_options": [], - "ns_description": "Road Warrior 1" + "ns_description": "Road Warrior 1", + "disable_dco": "0" } ``` @@ -1555,7 +1559,8 @@ Response example for a server in bridged mode: ], "ns_pool_start": "192.168.100.240", "ns_pool_end": "192.168.100.242", - "ns_description": "Road Warrior 1" + "ns_description": "Road Warrior 1", + "disable_dco": "0" } ``` @@ -1766,6 +1771,8 @@ api-cli ns.ovpnrw set-configuration --data '{"instance": "ns_roadwarrior1", "pro Valid values for `proto` field are: `udp` and `tcp-server` +The optional `disable_dco` field set to `1` turns off data channel offload (DCO), defaults to `0`. + Required fields for routed mode: - `dev_type` field must be set to `tun` - `server` field must contain a valid CIDR diff --git a/packages/ns-api/files/ns.ovpnrw b/packages/ns-api/files/ns.ovpnrw index 8439a62dd..494d0d6d6 100755 --- a/packages/ns-api/files/ns.ovpnrw +++ b/packages/ns-api/files/ns.ovpnrw @@ -438,6 +438,8 @@ def get_configuration(ovpninstance): ret["tun_mtu"] = "1500" if not ret.get("mssfix"): ret["mssfix"] = "1450" + if not ret.get("disable_dco"): + ret["disable_dco"] = "0" if ret.get('push'): local = [] @@ -623,6 +625,7 @@ def set_configuration(args): # MTU and MSSFix settings u.set("openvpn", ovpninstance, "tun_mtu", args.get("tun_mtu", '1500')) u.set("openvpn", ovpninstance, "mssfix", args.get("mssfix", '1450')) + u.set("openvpn", ovpninstance, "disable_dco", args.get("disable_dco", '0')) u.save("openvpn") @@ -1297,6 +1300,7 @@ if cmd == 'list': "ifconfig_pool": ["10.166.54.4", "10.166.54.20"], "tun_mtu": "1500", "mssfix": "1450", + "disable_dco": "0", }, "remove-instance": {"instance": "roadwarrior1"}, "import-users": {"instance": "roadwarrior1"}, diff --git a/packages/ns-api/files/ns.ovpntunnel b/packages/ns-api/files/ns.ovpntunnel index dd1904f7f..9a1964d08 100755 --- a/packages/ns-api/files/ns.ovpntunnel +++ b/packages/ns-api/files/ns.ovpntunnel @@ -256,6 +256,7 @@ def setup_server(u, iname, tunnel): u.set("openvpn", iname, "lport", tunnel['port']) u.set('openvpn', iname, 'tun_mtu', tunnel.get('tun_mtu', '1500')) u.set('openvpn', iname, 'mssfix', tunnel.get('mssfix', '1450')) + u.set('openvpn', iname, 'disable_dco', tunnel.get('disable_dco', '0')) if tunnel['proto'] == "tcp": u.set("openvpn", iname, "proto", "tcp-server") else: @@ -588,6 +589,8 @@ def get_tunnel_client(id): tunnel['tun_mtu'] = '1500' if not tunnel.get('mssfix'): tunnel['mssfix'] = '1450' + if not tunnel.get('disable_dco'): + tunnel['disable_dco'] = '0' return tunnel @@ -635,6 +638,8 @@ def get_tunnel_server(id): tunnel['tun_mtu'] = '1500' if not tunnel.get('mssfix'): tunnel['mssfix'] = '1450' + if not tunnel.get('disable_dco'): + tunnel['disable_dco'] = '0' return tunnel @@ -651,6 +656,7 @@ def setup_client(u, iname, args): u.set('openvpn', iname, 'keepalive', '10 60') u.set('openvpn', iname, 'tun_mtu', args.get('tun_mtu', '1500')) u.set('openvpn', iname, 'mssfix', args.get('mssfix', '1450')) + u.set('openvpn', iname, 'disable_dco', args.get('disable_dco', '0')) for opt in ['cipher', 'compress', 'auth', 'port']: if args.get(opt, None): @@ -779,10 +785,10 @@ cmd = sys.argv[1] if cmd == 'list': print(json.dumps({ "import-client": {}, - "add-server": {"ns_name": "server1", "port": "2001", "server": "192.168.4.0/24", "topology": "subnet", "proto": "tcp", "local": ["192.168.100.0/24"], "remote": ["192.168.5.0/24"], "compress": "", "auth": "", "cipher": "", "secret": "", "ifconfig_local": "", "ifconfig_remote": "", "ns_public_ip": ["1.2.3.4"], "tls_version_min": "1.2","tun_mtu": "1500", "mssfix": "1450"}, - "edit-server": {"id": "ns_server1", "ns_name": "server1", "port": "2001", "server": "192.168.4.0/24", "topology": "subnet", "proto": "tcp", "local": ["192.168.100.0/24"], "remote": ["192.168.5.0/24"], "compress": "", "auth": "", "cipher": "", "secret": "", "ifconfig_local": "", "ifconfig_remote": "", "ns_public_ip": ["1.2.3.4"], "tls_version_min": "1.2", "tun_mtu": "1500", "mssfix": "1450"}, - "add-client": {"ns_name": "client1", "port": "2001", "proto": "tcp", "certificate": "XXX", "dev_type": "tun", "remote": ["192.168.5.0/24"], "compress": "", "auth": "", "cipher": "", "secret": "", "route": [], "username": "", "password": "", "ifconfig_local": "", "ifconfig_remote": "", "tun_mtu": "1500", "mssfix": "1450"}, - "edit-client": {"id": "ns_client1", "ns_name": "client2", "port": "2001", "proto": "tcp", "certificate": "XXX", "dev_type": "tun", "remote": ["192.168.5.0/24"], "compres": "", "auth": "", "cipher": "", "secret": "", "route": [], "username": "", "password": "", "ifconfig_local": "", "ifconfig_remote": "", "tun_mtu": "1500", "mssfix": "1450"}, + "add-server": {"ns_name": "server1", "port": "2001", "server": "192.168.4.0/24", "topology": "subnet", "proto": "tcp", "local": ["192.168.100.0/24"], "remote": ["192.168.5.0/24"], "compress": "", "auth": "", "cipher": "", "secret": "", "ifconfig_local": "", "ifconfig_remote": "", "ns_public_ip": ["1.2.3.4"], "tls_version_min": "1.2","tun_mtu": "1500", "mssfix": "1450", "disable_dco": "0"}, + "edit-server": {"id": "ns_server1", "ns_name": "server1", "port": "2001", "server": "192.168.4.0/24", "topology": "subnet", "proto": "tcp", "local": ["192.168.100.0/24"], "remote": ["192.168.5.0/24"], "compress": "", "auth": "", "cipher": "", "secret": "", "ifconfig_local": "", "ifconfig_remote": "", "ns_public_ip": ["1.2.3.4"], "tls_version_min": "1.2", "tun_mtu": "1500", "mssfix": "1450", "disable_dco": "0"}, + "add-client": {"ns_name": "client1", "port": "2001", "proto": "tcp", "certificate": "XXX", "dev_type": "tun", "remote": ["192.168.5.0/24"], "compress": "", "auth": "", "cipher": "", "secret": "", "route": [], "username": "", "password": "", "ifconfig_local": "", "ifconfig_remote": "", "tun_mtu": "1500", "mssfix": "1450", "disable_dco": "0"}, + "edit-client": {"id": "ns_client1", "ns_name": "client2", "port": "2001", "proto": "tcp", "certificate": "XXX", "dev_type": "tun", "remote": ["192.168.5.0/24"], "compres": "", "auth": "", "cipher": "", "secret": "", "route": [], "username": "", "password": "", "ifconfig_local": "", "ifconfig_remote": "", "tun_mtu": "1500", "mssfix": "1450", "disable_dco": "0"}, "export-client": {"name": "ns_client1"}, "list-tunnels": {}, "list-cipher": {}, diff --git a/packages/ns-openvpn/files/openvpn-status b/packages/ns-openvpn/files/openvpn-status index fdce9bc17..6c625f473 100755 --- a/packages/ns-openvpn/files/openvpn-status +++ b/packages/ns-openvpn/files/openvpn-status @@ -32,6 +32,7 @@ if not os.path.exists(args.socket_path): try: with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as tsock: + tsock.settimeout(5) tsock.connect(args.socket_path) fp = tsock.makefile(mode='r', newline='\n') @@ -46,6 +47,8 @@ try: msg = fp.readline() if args.debug: print(msg, file=sys.stderr) + if not msg: + exit(1) if "ERROR" in msg: exit(1) if "END" in msg: diff --git a/packages/python3-nethsec/src/nethsec/ovpn/__init__.py b/packages/python3-nethsec/src/nethsec/ovpn/__init__.py index 2dd2eda6a..8d2e1d153 100644 --- a/packages/python3-nethsec/src/nethsec/ovpn/__init__.py +++ b/packages/python3-nethsec/src/nethsec/ovpn/__init__.py @@ -284,7 +284,7 @@ def list_connected_clients(openvpninstance, type="subnet"): - a list of connected clients """ try: - p = subprocess.run(["/usr/bin/openvpn-status", "-t", type, f"/var/run/openvpn_{openvpninstance}.socket"], check=True, capture_output=True, text=True) + p = subprocess.run(["/usr/bin/openvpn-status", "-t", type, f"/var/run/openvpn_{openvpninstance}.socket"], check=True, capture_output=True, text=True, timeout=5) except: return {} return json.loads(p.stdout) diff --git a/patches/feeds/packages/101-openvpn-dco-status-reply.patch b/patches/feeds/packages/101-openvpn-dco-status-reply.patch new file mode 100644 index 000000000..46001a2d6 --- /dev/null +++ b/patches/feeds/packages/101-openvpn-dco-status-reply.patch @@ -0,0 +1,15 @@ +diff --git a/net/openvpn/patches/200-dco-status-reply.patch b/net/openvpn/patches/200-dco-status-reply.patch +new file mode 100644 +--- /dev/null ++++ b/net/openvpn/patches/200-dco-status-reply.patch +@@ -0,0 +1,10 @@ ++--- a/src/openvpn/sig.c +++++ b/src/openvpn/sig.c ++@@ -485,6 +485,3 @@ print_status(struct context *c, struct status_output *so) ++ { ++- if (dco_get_peer_stats(c, true) < 0) ++- { ++- return; ++- } +++ dco_get_peer_stats(c, true); ++ } diff --git a/patches/feeds/packages/102-openvpn-dco-stats-no-tls-multi.patch b/patches/feeds/packages/102-openvpn-dco-stats-no-tls-multi.patch new file mode 100644 index 000000000..1626f4e8b --- /dev/null +++ b/patches/feeds/packages/102-openvpn-dco-stats-no-tls-multi.patch @@ -0,0 +1,13 @@ +diff --git a/net/openvpn/patches/201-dco-stats-no-tls-multi.patch b/net/openvpn/patches/201-dco-stats-no-tls-multi.patch +new file mode 100644 +--- /dev/null ++++ b/net/openvpn/patches/201-dco-stats-no-tls-multi.patch +@@ -0,0 +1,8 @@ ++--- a/src/openvpn/dco_linux.c +++++ b/src/openvpn/dco_linux.c ++@@ -1222,3 +1222,4 @@ dco_get_peer_stats(struct context *c, const bool raise_sigusr1_on_err) ++ { ++- if (!c->c1.tuntap || c->c1.tuntap->dco.ifindex == 0) +++ /* tls_multi is NULL during a restart, while a persisted tun is still around */ +++ if (!c->c1.tuntap || c->c1.tuntap->dco.ifindex == 0 || !c->c2.tls_multi) ++ { From bca55e1ab8015725671eb00d5d8f698b13b4e8ff Mon Sep 17 00:00:00 2001 From: Tommaso Bailetti Date: Tue, 17 Nov 2026 15:09:52 +0100 Subject: [PATCH 50/54] fix: adjusted file limits for victoria, added new proxy to logs --- packages/ns-api-server/files/src/main.go | 1 + packages/victoria-logs/files/victoria-logs.initd | 2 ++ 2 files changed, 3 insertions(+) diff --git a/packages/ns-api-server/files/src/main.go b/packages/ns-api-server/files/src/main.go index aea61f062..b8dc18828 100644 --- a/packages/ns-api-server/files/src/main.go +++ b/packages/ns-api-server/files/src/main.go @@ -129,6 +129,7 @@ func main() { 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")) + authGroup.Any("/logs/stream_field_values", methods.ProxyTo(victoriaLogsProxy, "/select/logsql/stream_field_values")) // handle missing endpoint router.NoRoute(func(c *gin.Context) { diff --git a/packages/victoria-logs/files/victoria-logs.initd b/packages/victoria-logs/files/victoria-logs.initd index c159b6946..0fb328296 100644 --- a/packages/victoria-logs/files/victoria-logs.initd +++ b/packages/victoria-logs/files/victoria-logs.initd @@ -55,6 +55,8 @@ start_service() { procd_set_param stdout 1 procd_set_param stderr 1 procd_set_param respawn 3600 5 0 + # a search opens files from every part of every daily partition, the 4096 default ends in a fatal panic + procd_set_param limits nofile="1048576 1048576" procd_set_param command $PROG procd_append_param command -storageDataPath="$storage_path" procd_append_param command -retentionPeriod="$retention_period" From ecd85641d27a18b04b40b9da7274a8191f178050 Mon Sep 17 00:00:00 2001 From: Matteo Di Lorenzi <52289654+m-dilorenzi@users.noreply.github.com> Date: Thu, 19 Nov 2026 14:07:28 +0100 Subject: [PATCH 51/54] feat(dpi): add support for source objects in DPI rules and address group management (#2014) --- .agents/skills/netifyd/SKILL.md | 23 +- packages/ns-api/Makefile | 1 + packages/ns-api/README.md | 61 +- packages/ns-api/files/ns.dpi | 12 +- packages/ns-api/files/ns.ovpnrw | 14 +- .../post-commit/update-address-groups.py | 16 + packages/ns-dpi/Makefile | 5 +- packages/ns-dpi/README.md | 59 +- packages/ns-dpi/files/address-groups.keep | 1 + packages/ns-dpi/files/dpi | 3 + packages/ns-dpi/files/write-address-groups | 13 + .../src/nethsec/dpi/__init__.py | 325 ++++++++-- .../src/nethsec/objects/__init__.py | 7 +- packages/python3-nethsec/tests/test_dpi.py | 570 +++++++++++++++++- 14 files changed, 1048 insertions(+), 62 deletions(-) create mode 100755 packages/ns-api/files/post-commit/update-address-groups.py create mode 100644 packages/ns-dpi/files/address-groups.keep create mode 100755 packages/ns-dpi/files/write-address-groups diff --git a/.agents/skills/netifyd/SKILL.md b/.agents/skills/netifyd/SKILL.md index 48f2fe6c7..9182069cc 100644 --- a/.agents/skills/netifyd/SKILL.md +++ b/.agents/skills/netifyd/SKILL.md @@ -104,8 +104,10 @@ until the next reload and then vanishes. Change the generator or its UCI input i | `table inet netifyd` (nftables) | `/usr/sbin/ns-netifyd-configure` (on start and reload) | `/etc/config/netifyd` → `ns_config` | | `netify-application-catalog.json` and the other catalog/category files | `dpi-data-update` (nightly cron) | Netify's data service | | `/usr/share/nftables.d/table-pre/` DPI chains | `/usr/sbin/dpi-nft` | `/etc/config/dpi` | +| `address-groups.d/30-*.conf` | `nethsec.dpi.write_address_groups` (on commit, by `ns.ovpnrw`, by `/usr/sbin/dpi`) | `/etc/config/objects`, `dhcp`, `users` | -`/usr/sbin/dpi` is the whole DPI apply path: `dpi-config` → `dpi-nft` → `/etc/init.d/netifyd reload`. +`/usr/sbin/dpi` is the whole DPI apply path: `dpi-migrate` → `write-address-groups` → `dpi-config` → `dpi-nft` → +`/etc/init.d/netifyd reload`. Run it after changing `/etc/config/dpi`; don't reproduce its steps by hand. --- @@ -204,6 +206,25 @@ Two operational facts: MAC members only match via `mac ==`, so don't put them in a group a `local_ip` rule references. +The `30-` prefix belongs to `nethsec.dpi.write_address_groups`: one `30-_.conf` group +per firewall object resolving to addresses, used by a DPI rule or not, with a `# ` and a +`# , generated from the firewall objects: do not edit` header, and every other `30-*.conf` file is +removed. It runs from the `update-address-groups.py` post-commit hook (`objects`, `dhcp`, `users`), from +`ns.ovpnrw` (reserved IP of a VPN user) and from `/usr/sbin/dpi`, before `dpi-config`: at boot the `dpi` +service (`START=40`) runs it before netifyd (`START=99`); `dpi-config` only references the groups. The `30-*.conf` files are in +`/lib/upgrade/keep.d/ns-dpi`, so backups and the HA sync carry them. The agent keeps the groups it loaded +in memory, a reload doesn't drop the ones whose file was removed (it drops their single addresses, not +their networks), and on stop it saves all of them back, without comments: that's why ownership goes by +prefix. The group of a deleted object therefore comes back as a file on the next agent restart +(unreferenced, so harmless) until the next write removes it; the boot write runs between the stop that +saved it and the start that would load it, so after a reboot it is gone from memory too. The +`flush-address-group` socket command drops a group from memory and deletes its file. A `kill -9` saves nothing. Verified on a device with agent 5.2.9: a reload re-reads the groups +without restarting the agent; a range line is silently ignored, so ranges are written as CIDR blocks; +a `/0` matches nothing (in a group and inline), so it is written as two `/1`; an IPv4-mapped IPv6 address +never matches an IPv4 flow; an empty group or a missing tag matches nothing without errors. IPv6 +literals written inline in a criteria, especially the ones starting with `::`, were seen to trigger an +intermittent `criteria parse error` that takes the agent down: a group reference never does. + --- ## Verify on a live device diff --git a/packages/ns-api/Makefile b/packages/ns-api/Makefile index 45a8d2357..bc30e15b0 100644 --- a/packages/ns-api/Makefile +++ b/packages/ns-api/Makefile @@ -198,6 +198,7 @@ define Package/ns-api/install $(INSTALL_BIN) ./files/post-commit/update-timezone.py $(1)/usr/libexec/ns-api/post-commit $(INSTALL_BIN) ./files/post-commit/restart-wireguard.py $(1)/usr/libexec/ns-api/post-commit $(INSTALL_BIN) ./files/post-commit/clear-user-tokens.py $(1)/usr/libexec/ns-api/post-commit + $(INSTALL_BIN) ./files/post-commit/update-address-groups.py $(1)/usr/libexec/ns-api/post-commit $(INSTALL_BIN) ./files/pre-commit/clean-network.py $(1)/usr/libexec/ns-api/pre-commit $(INSTALL_BIN) ./files/remove-pppoe-keepalive $(1)/usr/share/ns-api $(INSTALL_DIR) $(1)/etc/uci-defaults diff --git a/packages/ns-api/README.md b/packages/ns-api/README.md index 7a4d84336..76d5e407d 100644 --- a/packages/ns-api/README.md +++ b/packages/ns-api/README.md @@ -1851,6 +1851,8 @@ The APIs can raise the following validation errors: - reserved_ip_must_be_in_server_network - reserverd_ip_already_used - reserved_ip_must_be_in_server_network +- reserved_ip_is_used: the reserved IP can't be removed while the user is used as an object, e.g. by a + DPI rule, a firewall rule or a host set; the error value lists where it is used ### disconnect-user @@ -3812,6 +3814,9 @@ Rules with `ns_visible '0'` are left out. previous schema, carry their raw `criteria` and can be renamed, enabled, disabled, reordered and deleted, but not edited - `match_all`: the rule matches every flow instead of naming application groups +- `source_objects`: objects the source references, with their `name`, `type` and `subtype` (the same + values `ns.objects list-hosts` reports). An object gone from the configuration is reported with its id + as name and `null` type - `index`: position of the rule in the list Example response: @@ -3824,7 +3829,15 @@ Example response: "name": "Block streaming", "enabled": true, "action": "block", - "source": ["192.168.1.0/24"], + "source": [], + "source_objects": [ + { + "id": "objects/ns_16faa17f", + "name": "office", + "type": "host_set", + "subtype": "host_set" + } + ], "appgroups": [ { "id": "ns_1a2b3c4d5", @@ -3841,6 +3854,7 @@ Example response: "enabled": true, "action": "allow", "source": [], + "source_objects": [], "appgroups": [], "match_all": true, "managed": true, @@ -3852,6 +3866,7 @@ Example response: "enabled": true, "action": "block", "source": [], + "source_objects": [], "appgroups": [], "match_all": false, "managed": false, @@ -3871,7 +3886,8 @@ api-cli ns.dpi add-rule --data '{ "name": "Block streaming", "enabled": true, "action": "block", - "source": ["192.168.1.0/24"], + "source": [], + "source_objects": ["objects/ns_16faa17f"], "appgroups": ["ns_1a2b3c4d5"], "match_all": false, "position": "bottom" @@ -3883,7 +3899,12 @@ api-cli ns.dpi add-rule --data '{ - `action`: mandatory, `block` or `allow`. `allow` stops the evaluation, so the rules below it don't apply to the matching flows - `source`: addresses, networks or ranges, IPv4 or IPv6, e.g. - `["192.168.1.1", "192.168.1.0/24", "10.0.0.10-10.0.0.20"]`. Empty or omitted matches every host + `["192.168.1.1", "192.168.1.0/24", "10.0.0.10-10.0.0.20"]`. Empty or omitted, together with + `source_objects`, matches every host +- `source_objects`: ids of objects whose addresses the rule is narrowed to, see `list-source-objects`: + host sets, DHCP static leases, DNS records and VPN users with a reserved IP. Domain sets are refused. + Alternative to `source`: a rule can't have both (`source_objects_with_source`). A change to a + referenced object applies to the rule on commit, without editing it - `appgroups`: ids of the application groups to match, see `list-appgroups`. Mandatory unless `match_all` is `true` - `match_all`: match every flow, optionally narrowed by `source`. `appgroups` must be empty. Defaults to @@ -3910,6 +3931,7 @@ api-cli ns.dpi edit-rule --data '{ "enabled": false, "action": "block", "source": [], + "source_objects": [], "appgroups": ["ns_1a2b3c4d5"], "match_all": false }' @@ -3923,6 +3945,34 @@ Example response: } ``` +### list-source-objects + +List the objects a rule source can reference: the same objects as `ns.objects list-hosts`, domain sets +excluded. + +```bash +api-cli ns.dpi list-source-objects +``` + +Example response: + +```json +{ + "values": [ + { + "name": "office", + "family": "ipv4", + "id": "objects/ns_16faa17f", + "singleton": false, + "subtype": "host_set", + "used": true, + "matches": ["dpi/ns_3869dc35"], + "type": "host_set" + } + ] +} +``` + ### delete-rule Delete a rule. The remaining rules are renumbered: @@ -8009,6 +8059,11 @@ Example response: Manage domain sets and host sets. +Every object resolving to addresses (host sets, DHCP static leases, DNS records, VPN users with a reserved +IP) has a netifyd address group, `/etc/netifyd/address-groups.d/30-_.conf`, used by the DPI +rules. The `update-address-groups.py` post-commit hook writes them when `objects`, `dhcp` or `users` are +committed, see the `ns-dpi` package. + ### list-domain-sets List all domain sets: diff --git a/packages/ns-api/files/ns.dpi b/packages/ns-api/files/ns.dpi index aa6a6d002..cf4f5063f 100755 --- a/packages/ns-api/files/ns.dpi +++ b/packages/ns-api/files/ns.dpi @@ -9,18 +9,20 @@ import json import sys from euci import EUci -from nethsec import dpi, utils +from nethsec import dpi, objects, utils cmd = sys.argv[1] if cmd == 'list': print(json.dumps({ 'list-rules': {}, + 'list-source-objects': {}, 'add-rule': { 'name': 'str', 'enabled': False, 'action': 'str', 'source': [], + 'source_objects': [], 'appgroups': [], 'match_all': False, 'position': 'str' @@ -31,6 +33,7 @@ if cmd == 'list': 'enabled': False, 'action': 'str', 'source': [], + 'source_objects': [], 'appgroups': [], 'match_all': False }, @@ -102,17 +105,20 @@ elif cmd == 'call': print(json.dumps(utils.generic_error('catalog_not_available'))) elif action == 'list-rules': print(json.dumps({'values': dpi.list_rules(e_uci)})) + elif action == 'list-source-objects': + print(json.dumps({'values': objects.list_objects(e_uci, include_domain_sets=False)})) elif action == 'add-rule': data = json.load(sys.stdin) config_name = dpi.add_rule(e_uci, data['name'], data['enabled'], data['action'], data.get('source', []), data.get('appgroups', []), - data.get('position', 'bottom'), data.get('match_all', False)) + data.get('position', 'bottom'), data.get('match_all', False), + data.get('source_objects', [])) print(json.dumps({'id': config_name})) elif action == 'edit-rule': data = json.load(sys.stdin) config_name = dpi.edit_rule(e_uci, data['id'], data['name'], data['enabled'], data['action'], data.get('source', []), data.get('appgroups', []), - data.get('match_all', False)) + data.get('match_all', False), data.get('source_objects', [])) print(json.dumps({'id': config_name})) elif action == 'delete-rule': data = json.load(sys.stdin) diff --git a/packages/ns-api/files/ns.ovpnrw b/packages/ns-api/files/ns.ovpnrw index 494d0d6d6..a106a0d4d 100755 --- a/packages/ns-api/files/ns.ovpnrw +++ b/packages/ns-api/files/ns.ovpnrw @@ -16,7 +16,7 @@ import pyotp import ipaddress import subprocess from euci import EUci -from nethsec import utils, ovpn, firewall, users, objects +from nethsec import utils, ovpn, firewall, users, objects, dpi from datetime import datetime, timezone import tarfile import io @@ -810,6 +810,8 @@ def add_user(args): else: users.edit_local_user(u, args['username'], extra_fields=ovpn_config) u.commit("users") + # add related address groups used by DPI rules + dpi.update_address_groups(u) return {"result": "success"} def import_users(ovpninstance): @@ -844,6 +846,12 @@ def edit_user(args): if user_id == None: return utils.validation_error("username", "user_not_found", args["username"]) + # an object needs its reserved IP: removing it would leave the rules using the user without an address + if not args["ipaddr"] and u.get("users", user_id, 'openvpn_ipaddr', default=""): + used, matches = objects.is_used_object(u, f'users/{user_id}') + if used: + return utils.validation_error("ipaddr", "reserved_ip_is_used", matches) + if args["ipaddr"] and u.get("users", user_id, 'openvpn_ipaddr', default="") != args["ipaddr"]: valid, error = is_valid_ip(ovpninstance, args["ipaddr"]) if not valid: @@ -859,6 +867,8 @@ def edit_user(args): pass u.set("users", user_id, "openvpn_enabled", args["enabled"]) u.commit("users") + # update related address groups used by DPI rules + dpi.update_address_groups(u) return {"result": "success"} def delete_user(ovpninstance, username): @@ -892,6 +902,8 @@ def delete_user(ovpninstance, username): u.commit("users") except: pass + # delete related address groups used by DPI rules + dpi.update_address_groups(u) try: revoke_user_certificate(ovpninstance, username) except: diff --git a/packages/ns-api/files/post-commit/update-address-groups.py b/packages/ns-api/files/post-commit/update-address-groups.py new file mode 100755 index 000000000..d0e2db2fa --- /dev/null +++ b/packages/ns-api/files/post-commit/update-address-groups.py @@ -0,0 +1,16 @@ +#!/usr/bin/python + +# +# Copyright (C) 2026 Nethesis S.r.l. +# SPDX-License-Identifier: GPL-2.0-only +# + +# This script writes the netifyd address groups of the firewall objects once their changes are committed: +# one file per object resolving to addresses, the ones of objects that are gone removed, and netifyd +# reloaded when a file changed. DPI rules match an object through its group. + +from euci import EUci +from nethsec import dpi + +if "objects" in changes or "dhcp" in changes or "users" in changes: # noqa: F821 + dpi.update_address_groups(EUci()) diff --git a/packages/ns-dpi/Makefile b/packages/ns-dpi/Makefile index 0931ef1bd..8377fdc2e 100644 --- a/packages/ns-dpi/Makefile +++ b/packages/ns-dpi/Makefile @@ -53,7 +53,7 @@ fi exit 0 endef -define Package/ns-plug/conffiles +define Package/ns-dpi/conffiles /etc/config/dpi endef @@ -68,6 +68,7 @@ define Package/ns-dpi/install $(INSTALL_DIR) $(1)/etc/uci-defaults $(INSTALL_DIR) $(1)/usr/share/ns-plug/hooks/unregister $(INSTALL_DIR) $(1)/etc/xtables + $(INSTALL_DIR) $(1)/lib/upgrade/keep.d $(INSTALL_CONF) ./files/connlabel.conf $(1)/etc/connlabel.conf $(LN) /etc/connlabel.conf $(1)/etc/xtables/connlabel.conf $(INSTALL_BIN) ./files/dpi.init $(1)/etc/init.d/dpi @@ -81,6 +82,8 @@ define Package/ns-dpi/install $(INSTALL_BIN) ./files/dpi-data-update.py $(1)/usr/sbin/dpi-data-update $(INSTALL_BIN) ./files/dpi-update.py $(1)/usr/sbin/dpi-update $(INSTALL_BIN) ./files/dpi-migrate.py $(1)/usr/libexec/ns-dpi/dpi-migrate + $(INSTALL_BIN) ./files/write-address-groups $(1)/usr/libexec/ns-dpi/write-address-groups + $(INSTALL_CONF) ./files/address-groups.keep $(1)/lib/upgrade/keep.d/ns-dpi $(INSTALL_CONF) ./files/20_dpi $(1)/etc/uci-defaults $(INSTALL_BIN) ./files/21_dpi_migrate $(1)/etc/uci-defaults/21_dpi_migrate $(INSTALL_BIN) ./files/23_dpi_drop_options $(1)/etc/uci-defaults/23_dpi_drop_options diff --git a/packages/ns-dpi/README.md b/packages/ns-dpi/README.md index e5bbbe5ae..658dff900 100644 --- a/packages/ns-dpi/README.md +++ b/packages/ns-dpi/README.md @@ -40,7 +40,10 @@ Rule (`rule` section): - `action`: `block` or `allow` - `priority`: evaluation order, starting at `1`; the first rule matching a flow wins - `appgroup`: list of application groups to match -- `source`: list of addresses, networks or ranges to narrow the rule to; empty means every host +- `source`: list of addresses, networks or ranges to narrow the rule to; empty, together with + `source_object`, means every host +- `source_object`: list of objects, in the form `/`, whose addresses narrow the rule, as + an alternative to `source`: host sets, DHCP static leases, DNS records and VPN users with a reserved IP - `ns_match_all`: `1` matches every flow instead of naming application groups - `ns_managed`: `1` for the rules created by the API - `criteria`: raw netifyd expression, used by the rules not created by the API; the API can't edit them @@ -71,9 +74,51 @@ config rule 'ns_9d40be71' option action 'block' option priority '2' list appgroup 'ns_1a2b3c4d' - list source '192.168.1.0/24' + list source_object 'objects/ns_16faa17f' ``` +### Objects as source + +Every firewall object resolving to addresses has a netifyd address group, +`/etc/netifyd/address-groups.d/30-_.conf`, whether a rule uses it or not: host sets, DHCP +static leases, DNS records and VPN users with a reserved IP. A rule references the object as +`local_ip == @_`, so `dpi-config` only builds the criteria and never writes a group. + +The files follow the objects, not the rules. They are written by `nethsec.dpi.write_address_groups`: + +- on commit, by the `update-address-groups.py` post-commit hook of `ns.commit`, when `objects`, `dhcp` or + `users` change; netifyd is reloaded if a file changed +- by `ns.ovpnrw` when a VPN user gets, changes or loses its reserved IP, as it commits on its own +- by `/usr/sbin/dpi`, so at boot by the `dpi` service (`START=40`), before netifyd starts (`START=99`), and + on every DPI reload + +Each file starts with a comment holding the object name, when the object has one, followed by a comment +holding the object id and `generated from the firewall objects: do not edit`. A file is rewritten only when +its content changes. The `30-` prefix belongs to the writer: every `30-*.conf` file whose object is gone, +or has no address, is removed; files with other prefixes are never touched. An object with no address has +no file: a rule referencing it matches no host, as a missing group matches nothing. The reserved IP of a +VPN user can't be removed while the user is used as an object (`ns.ovpnrw edit-user` fails with +`reserved_ip_is_used`), so a rule can lose its addresses only when the configuration is changed outside +the API, e.g. when a whole user database is deleted. + +The `30-*.conf` files are listed in `/lib/upgrade/keep.d/ns-dpi`, so they are part of the backup, of the +HA configuration sync and survive an image upgrade, always matching the configuration they come with. + +netifyd keeps the groups it loaded in memory, a reload doesn't drop the ones whose file was removed, and +when it stops it saves all of them back to the directory, without comments. So after a netifyd restart +the files lose their header until the next write, and the group of a deleted object can come back as a +file: no rule references it, and the next write removes it. The write at boot runs after the stop that +saved it and before the start that would load it again, dropping it from memory too. + +The addresses are written the way an address group can match them: + +- ranges become CIDR blocks, as address groups ignore them. A range whose first address is greater than + its last becomes the CIDR blocks of the ordered range; the host set itself is left as entered +- references to other objects are resolved +- IPv4-mapped IPv6 addresses (`::ffff:a.b.c.d`) become IPv4 addresses, as they never match IPv4 flows +- `0.0.0.0/0` and `::/0` become their two `/1` halves, as a zero length prefix matches nothing +- the zone of link-local addresses is dropped + ## Migration from the previous schema On upgrade, and every time the DPI service starts, `/usr/libexec/ns-dpi/dpi-migrate` converts the @@ -98,6 +143,16 @@ cat /etc/netifyd/netify-proc-flow-actions.json nft list chain inet fw4 dpi_actions ``` +Check the address groups of the objects: +``` +head /etc/netifyd/address-groups.d/30-* +``` + +Write them again from the configuration: +``` +/usr/libexec/ns-dpi/write-address-groups +``` + List the blocked connections: ``` conntrack -L -o label -l netify-blocked diff --git a/packages/ns-dpi/files/address-groups.keep b/packages/ns-dpi/files/address-groups.keep new file mode 100644 index 000000000..c3c6512ad --- /dev/null +++ b/packages/ns-dpi/files/address-groups.keep @@ -0,0 +1 @@ +/etc/netifyd/address-groups.d/30-*.conf diff --git a/packages/ns-dpi/files/dpi b/packages/ns-dpi/files/dpi index 228d33859..cd7c79f75 100755 --- a/packages/ns-dpi/files/dpi +++ b/packages/ns-dpi/files/dpi @@ -8,6 +8,9 @@ # Convert a configuration still on the previous schema, e.g. restored from an old backup or synced # by an HA peer: a no-op when there is nothing to migrate /usr/libexec/ns-dpi/dpi-migrate +# Write the address groups of the firewall objects, referenced by the rules with a source object. At boot +# this runs before netifyd starts, dropping the stale groups it saved when it stopped +/usr/libexec/ns-dpi/write-address-groups # Generate netify flow actions config file /usr/sbin/dpi-config # Apply nftables rules diff --git a/packages/ns-dpi/files/write-address-groups b/packages/ns-dpi/files/write-address-groups new file mode 100755 index 000000000..030b5192b --- /dev/null +++ b/packages/ns-dpi/files/write-address-groups @@ -0,0 +1,13 @@ +#!/usr/bin/python3 + +# +# Copyright (C) 2026 Nethesis S.r.l. +# SPDX-License-Identifier: GPL-2.0-only +# + +# Write the netifyd address groups of the firewall objects, see nethsec.dpi.write_address_groups + +from euci import EUci +from nethsec import dpi + +dpi.write_address_groups(EUci()) diff --git a/packages/python3-nethsec/src/nethsec/dpi/__init__.py b/packages/python3-nethsec/src/nethsec/dpi/__init__.py index 7c640ca98..d92fda6c0 100644 --- a/packages/python3-nethsec/src/nethsec/dpi/__init__.py +++ b/packages/python3-nethsec/src/nethsec/dpi/__init__.py @@ -11,6 +11,7 @@ import ipaddress import json +import os import subprocess import syslog @@ -20,6 +21,62 @@ from nethsec import objects, utils from nethsec.utils import ValidationError +NETIFYD_DATA_DIR = '/etc/netifyd' + +# UCI list name of every member kind, mapped to the API parameter it is fed by +APPGROUP_MEMBERS = { + 'app': 'applications', + 'app_category': 'application_categories', + 'proto': 'protocols', + 'proto_category': 'protocol_categories' +} + +# validation error message of every member kind +__APPGROUP_MEMBER_ERRORS = { + 'app': 'invalid_application', + 'app_category': 'invalid_application_category', + 'proto': 'invalid_protocol', + 'proto_category': 'invalid_protocol_category' +} + +# characters that would let a member value escape its quoted literal, or terminate the expression +__APPGROUP_FORBIDDEN_CHARS = '\'"\\;()\n\r\t' + +APPGROUP_NAME_MAX_LENGTH = 64 + +APPGROUP_CATALOG_FILES = { + 'applications': 'netify-application-catalog.json', + 'protocols': 'netify-protocol-catalog.json' +} + +UNCATEGORIZED_TAG = '' + +# 'allow' attaches a label no nft rule matches: it exists so a rule can win the first-match race and +# shield its traffic from the block rules below it +DPI_RULE_ACTIONS = ('block', 'allow') + +DPI_RULE_NAME_MAX_LENGTH = 64 + +DPI_MATCH_ALL_CRITERIA = '*' + +DPI_RULE_POSITIONS = ('top', 'bottom') + +# netifyd address groups, one file for every object resolving to addresses, see `write_address_groups` +ADDRESS_GROUPS_DIR = '/etc/netifyd/address-groups.d' + +# prefixes below 20 belong to the agent itself, this one belongs to `write_address_groups`: every file +# carrying it whose object is gone, or has no address anymore, is removed. The agent saves the groups it +# holds when it stops, without comments and including the ones whose file was removed while it was running: +# the prefix is what tells such a stale file apart +_ADDRESS_GROUP_FILE_PREFIX = '30-' + +# ending of the header comment of every file written by `write_address_groups`, for whoever reads it +_ADDRESS_GROUP_FILE_MARKER = 'generated from the firewall objects: do not edit' + +# (database, section type) of the objects with an address group, so the ones a rule source can reference: +# everything resolving to addresses. Domain sets are left out: they resolve to addresses only at runtime +_ADDRESS_GROUP_TYPES = (('objects', 'host'), ('dhcp', 'host'), ('dhcp', 'domain'), ('users', 'user')) + def load_applications() -> dict[int, str]: """ @@ -69,30 +126,6 @@ def load_protocols() -> dict[int, str]: # Application groups: a NethSecurity abstraction, the netifyd plugin has no group primitive. # A group is a named set of match members, expanded into an inline expression at generation time. -NETIFYD_DATA_DIR = '/etc/netifyd' - -# UCI list name of every member kind, mapped to the API parameter it is fed by -APPGROUP_MEMBERS = { - 'app': 'applications', - 'app_category': 'application_categories', - 'proto': 'protocols', - 'proto_category': 'protocol_categories' -} - -# validation error message of every member kind -__APPGROUP_MEMBER_ERRORS = { - 'app': 'invalid_application', - 'app_category': 'invalid_application_category', - 'proto': 'invalid_protocol', - 'proto_category': 'invalid_protocol_category' -} - -# characters that would let a member value escape its quoted literal, or terminate the expression -__APPGROUP_FORBIDDEN_CHARS = '\'"\\;()\n\r\t' - -APPGROUP_NAME_MAX_LENGTH = 64 - - def load_categories() -> dict[str, dict[int, str]]: """ Reads the categories loaded in memory by the engine, using the netifyd --dump-categories command. @@ -177,13 +210,6 @@ def __appgroup_vocabulary(kind: str) -> set[str] | None: # an unknown value never matches, so a missing vocabulary is a reason to skip the check, not to refuse return vocabulary if vocabulary else None -APPGROUP_CATALOG_FILES = { - 'applications': 'netify-application-catalog.json', - 'protocols': 'netify-protocol-catalog.json' -} - -UNCATEGORIZED_TAG = '' - def list_appgroup_catalog() -> dict[str, list[dict]]: """ @@ -540,16 +566,6 @@ def expand_appgroups(e_uci: EUci, config_names: list[str]) -> str: # Rules: ordered by priority, first match wins. A rule matches application groups only, optionally # narrowed to a source; what it does is decided by its action. -# 'allow' attaches a label no nft rule matches: it exists so a rule can win the first-match race and -# shield its traffic from the block rules below it -DPI_RULE_ACTIONS = ('block', 'allow') - -DPI_RULE_NAME_MAX_LENGTH = 64 - -DPI_MATCH_ALL_CRITERIA = '*' - -DPI_RULE_POSITIONS = ('top', 'bottom') - def __sorted_rules(e_uci: EUci) -> list[tuple[str, dict]]: """ @@ -656,10 +672,190 @@ def expand_source(values: list[str]) -> list[str]: return expanded +# Address groups: every object resolving to IP addresses has its netifyd address group, +# `ADDRESS_GROUPS_DIR/30-.conf`, whether a rule uses it or not: a rule source matches it as +# `local_ip == @`, and the files follow the objects as they are committed, not the rules. + +def _address_group_tag(database_id: str) -> str: + """ + The tag of the address group of an object, e.g. `objects_ns_1234` for `objects/ns_1234`. + + Args: + - database_id: id of the object in the form of `/` + + Returns: + the tag, as referenced by a criteria with `@` + """ + return database_id.replace('/', '_') + + +def _strip_zone(value: str) -> str: + """Drop the zone of a link-local address, e.g. `fe80::1%eth0/64` becomes `fe80::1/64`.""" + if '%' not in value: + return value + address, _, rest = value.partition('%') + _, slash, prefix = rest.partition('/') + return f'{address}{slash}{prefix}' + + +def _address_group_entries(e_uci: EUci, database_id: str) -> list[str]: + """ + The entries of the address group of an object, written the way an address group can match them: + ranges become CIDR blocks, as an address group silently ignores them, and a range whose first address + is greater than its last, which the object API accepts, covers the same addresses as the ordered one; an + IPv4-mapped IPv6 network becomes the IPv4 network it maps, as it never matches an IPv4 flow; a zero + length prefix, which matches nothing, is split into its two halves. A value that cannot be turned into an + address is skipped with a log line, as the agent would ignore it. + + Args: + - e_uci: euci instance + - database_id: id of the object in the form of `/` + + Returns: + the entries, empty when the object has no address the agent can match, or is gone + """ + entries = [] + for value in objects.get_object_ips(e_uci, database_id): + try: + if '-' in value: + # the host set keeps the range as entered: only the written networks are ordered + bounds = (ipaddress.ip_address(_strip_zone(part.strip())) for part in value.split('-', 1)) + first, last = sorted(bounds) + networks = list(ipaddress.summarize_address_range(first, last)) + else: + networks = [ipaddress.ip_network(_strip_zone(value.strip()), strict=False)] + except (ValueError, TypeError) as error: + syslog.syslog(syslog.LOG_WARNING, f"dpi: skipping {value!r} of {database_id}: {error}") + continue + for network in networks: + if network.version == 6 and network.prefixlen >= 96 and network.network_address.ipv4_mapped: + network = ipaddress.ip_network(f'{network.network_address.ipv4_mapped}/{network.prefixlen - 96}') + for entry in network.subnets(new_prefix=1) if network.prefixlen == 0 else [network]: + if str(entry) not in entries: + entries.append(str(entry)) + return entries + + +def write_address_groups(e_uci: EUci) -> bool: + """ + Write the address group of every object resolving to addresses, and remove every other file with the + `_ADDRESS_GROUP_FILE_PREFIX` prefix: the ones of objects that are gone or have no address anymore. A file + is rewritten only when its content changes. The agent loads the files on start and on reload. + + Args: + - e_uci: euci instance + + Returns: + True when a file was written or removed + """ + os.makedirs(ADDRESS_GROUPS_DIR, exist_ok=True) + wanted = {} + for database in sorted({database for database, _ in _ADDRESS_GROUP_TYPES}): + try: + sections = e_uci.get_all(database) + except Exception: + # the configuration doesn't exist + continue + for section in sections: + if (database, e_uci.get(database, section)) not in _ADDRESS_GROUP_TYPES: + continue + database_id = f'{database}/{section}' + entries = _address_group_entries(e_uci, database_id) + if not entries: + continue + # header: the object name, when it has one, on one line, then the id and the marker + name = ' '.join(str(e_uci.get(database, section, 'name', default='')).split()) + lines = [f'# {name}'] if name else [] + lines.append(f'# {database_id}, {_ADDRESS_GROUP_FILE_MARKER}') + lines.extend(entries) + filename = f'{_ADDRESS_GROUP_FILE_PREFIX}{_address_group_tag(database_id)}.conf' + wanted[filename] = ''.join(f'{line}\n' for line in lines) + + changed = False + for filename in os.listdir(ADDRESS_GROUPS_DIR): + if filename.startswith(_ADDRESS_GROUP_FILE_PREFIX) and filename.endswith('.conf') and filename not in wanted: + os.remove(os.path.join(ADDRESS_GROUPS_DIR, filename)) + changed = True + + for filename, content in wanted.items(): + path = os.path.join(ADDRESS_GROUPS_DIR, filename) + try: + with open(path, 'r') as fp: + if fp.read() == content: + if os.stat(path).st_mode & 0o777 != 0o644: + os.chmod(path, 0o644) + continue + except FileNotFoundError: + pass + with open(f'{path}.tmp', 'w') as fp: + fp.write(content) + # readable by the agent whatever the umask of the caller, e.g. the API server + os.chmod(f'{path}.tmp', 0o644) + os.replace(f'{path}.tmp', path) + changed = True + + return changed + + +def update_address_groups(e_uci: EUci) -> bool: + """ + Write the address groups, see `write_address_groups`, and reload the agent when a file changed and it is + running, so it loads them. To be called once the object changes are committed. + + Args: + - e_uci: euci instance + + Returns: + True when a file was written or removed. A file that can't be written is logged, not raised: the + object changes are committed already, the next update or boot writes it again + """ + try: + changed = write_address_groups(e_uci) + except OSError as error: + syslog.syslog(syslog.LOG_ERR, f"dpi: cannot write the address groups: {error}") + return False + if changed and subprocess.run(['/etc/init.d/netifyd', 'running'], capture_output=True).returncode == 0: + subprocess.run(['/etc/init.d/netifyd', 'reload'], capture_output=True) + return changed + + +# Source objects: firewall objects resolving to IP addresses, referenced by a rule instead of typing the +# addresses in. Every such object has its netifyd address group, written by `write_address_groups` +# when the object is committed, and the criteria matches it as `local_ip == @`: the criteria stays one +# term wide whatever the object holds, and a change to the object only rewrites its file. A source can +# reference the objects with an address group, see `_ADDRESS_GROUP_TYPES`. + + +def __validate_source_objects(e_uci: EUci, values: list[str], source: list[str]) -> list[str]: + """ + Validate the objects a rule source references: they must exist and resolve to addresses. Objects and + addresses are alternatives: a rule can't have both. + """ + if values and source: + raise ValidationError('source_objects', 'source_objects_with_source', values) + source_objects = [] + for value in values or []: + if not isinstance(value, str) or not objects.is_object_id(value): + raise ValidationError('source_objects', 'invalid_source_object', value) + database, _, section = value.partition('/') + if not section or (database, e_uci.get(database, section, default=None)) not in _ADDRESS_GROUP_TYPES: + raise ValidationError('source_objects', 'invalid_source_object', value) + # a user is an object only with a VPN account holding a reserved address + if database == 'users' and not e_uci.get('users', section, 'openvpn_ipaddr', default=None): + raise ValidationError('source_objects', 'invalid_source_object', value) + if value not in source_objects: + source_objects.append(value) + return source_objects + + def build_rule_criteria(e_uci: EUci, rule: dict) -> str: """ Build the criteria of a managed rule: the source, when set, ANDed with the union of its groups. + The source is made of its addresses or of the address groups of its objects, see + `write_address_groups`; a rule holding both, e.g. edited by hand, matches either. An object + without addresses has no group file: the term stays, and a missing group matches nothing. + Args: - e_uci: euci instance - rule: the rule section, as returned by `uci.get_all` @@ -669,6 +865,7 @@ def build_rule_criteria(e_uci: EUci, rule: dict) -> str: """ match = expand_appgroups(e_uci, list(rule.get('appgroup', []))) sources = [f'local_ip == {source}' for source in expand_source(list(rule.get('source', [])))] + sources += [f"local_ip == @{_address_group_tag(object_id)}" for object_id in rule.get('source_object', [])] if not match: if not sources: @@ -691,8 +888,8 @@ def list_rules(e_uci: EUci) -> list[dict]: Returns: list of dicts, each dict contains the property "id", "name", "enabled", "action", "source", - "appgroups", "match_all", "managed" and "index", plus "criteria" for the rules the API did not - create + "source_objects", "appgroups", "match_all", "managed" and "index", plus "criteria" for the rules + the API did not create. Each source object carries "id", "name", "type" and "subtype" """ groups = {section: group.get('ns_name', '') for section, group in (utils.get_all_by_type(e_uci, 'dpi', 'appgroup') or {}).items()} @@ -706,6 +903,7 @@ def list_rules(e_uci: EUci) -> list[dict]: 'enabled': rule.get('enabled', '1') == '1', 'action': rule.get('action', ''), 'source': list(rule.get('source', [])), + 'source_objects': [], 'appgroups': [{'id': group, 'name': groups.get(group, group)} for group in rule.get('appgroup', [])], 'match_all': rule.get('ns_match_all', '0') == '1', @@ -713,6 +911,25 @@ def list_rules(e_uci: EUci) -> list[dict]: 'managed': rule.get('ns_managed', '0') == '1', 'index': len(rules) } + for object_id in rule.get('source_object', []): + # an object gone from the configuration is still listed, named after its id, so the rule can be fixed + info = objects.get_info(e_uci, object_id) if objects.object_exists(e_uci, object_id) else None + if info is None: + data_rule['source_objects'].append( + {'id': object_id, 'name': object_id, 'type': None, 'subtype': None}) + continue + if info['database'] == 'objects': + # same subtype `objects.list_host_sets` reports, so the client can reuse its icons and labels + object_type = subtype = 'host_set' + if objects.is_singleton_host_set(e_uci, object_id): + address = objects.get_object_ip(e_uci, object_id) or '' + subtype = 'cidr' if '/' in address else 'range' if '-' in address else 'host' + elif info['database'] == 'dhcp': + object_type = subtype = 'dhcp_static_lease' if info['type'] == 'host' else 'dns_record' + else: + object_type = subtype = 'vpn_user' + data_rule['source_objects'].append( + {'id': object_id, 'name': info['name'], 'type': object_type, 'subtype': subtype}) if 'criteria' in rule: data_rule['criteria'] = rule.get('criteria') rules.append(data_rule) @@ -721,7 +938,8 @@ def list_rules(e_uci: EUci) -> list[dict]: def __save_rule_data(e_uci: EUci, config_name: str, name: str, enabled: bool, action: str, - source: list[str], appgroups: list[str], match_all: bool = False): + source: list[str], appgroups: list[str], match_all: bool = False, + source_objects: list[str] = None): e_uci.set('dpi', config_name, 'ns_name', name) e_uci.set('dpi', config_name, 'ns_managed', '1') e_uci.set('dpi', config_name, 'enabled', enabled) @@ -740,10 +958,15 @@ def __save_rule_data(e_uci: EUci, config_name: str, name: str, enabled: bool, ac else: # no source means every host: the option must go, not stay empty e_uci.delete('dpi', config_name, 'source') + if source_objects: + e_uci.set('dpi', config_name, 'source_object', source_objects) + else: + e_uci.delete('dpi', config_name, 'source_object') def add_rule(e_uci: EUci, name: str, enabled: bool, action: str, source: list[str], - appgroups: list[str], position: str = 'bottom', match_all: bool = False) -> str: + appgroups: list[str], position: str = 'bottom', match_all: bool = False, + source_objects: list[str] = None) -> str: """ Store a new rule. @@ -758,6 +981,8 @@ def add_rule(e_uci: EUci, name: str, enabled: bool, action: str, source: list[st - position: 'top' to evaluate the rule before every other one, 'bottom' after them - match_all: the rule matches every flow, narrowed to `source` when one is given. Mutually exclusive with `appgroups` + - source_objects: ids of the objects, in the form of `/`, whose addresses the rule is + narrowed to, as an alternative to `source`; see `_ADDRESS_GROUP_TYPES` for the accepted ones Returns: config name of the rule created @@ -771,11 +996,12 @@ def add_rule(e_uci: EUci, name: str, enabled: bool, action: str, source: list[st if position not in DPI_RULE_POSITIONS: raise ValidationError('position', 'invalid_position', position) source = __validate_source(source) + source_objects = __validate_source_objects(e_uci, source_objects, source) appgroups = __validate_appgroups(e_uci, appgroups, match_all) config_name = utils.get_random_id() e_uci.set('dpi', config_name, 'rule') - __save_rule_data(e_uci, config_name, name, enabled, action, source, appgroups, match_all) + __save_rule_data(e_uci, config_name, name, enabled, action, source, appgroups, match_all, source_objects) order = [section for section, _ in __sorted_rules(e_uci) if section != config_name] order.insert(0, config_name) if position == 'top' else order.append(config_name) @@ -786,7 +1012,7 @@ def add_rule(e_uci: EUci, name: str, enabled: bool, action: str, source: list[st def edit_rule(e_uci: EUci, config_name: str, name: str, enabled: bool, action: str, source: list[str], - appgroups: list[str], match_all: bool = False) -> str: + appgroups: list[str], match_all: bool = False, source_objects: list[str] = None) -> str: """ Edit a rule. Only rules created through the API can be edited: a rule carrying a hand-written criteria has no source and no group to fill the form with, and rewriting it would change what it @@ -803,6 +1029,8 @@ def edit_rule(e_uci: EUci, config_name: str, name: str, enabled: bool, action: s `match_all` is set - match_all: the rule matches every flow, narrowed to `source` when one is given. Mutually exclusive with `appgroups` + - source_objects: ids of the objects, in the form of `/`, whose addresses the rule is + narrowed to, as an alternative to `source`; see `_ADDRESS_GROUP_TYPES` for the accepted ones Returns: config name of the rule edited @@ -819,9 +1047,10 @@ def edit_rule(e_uci: EUci, config_name: str, name: str, enabled: bool, action: s if action not in DPI_RULE_ACTIONS: raise ValidationError('action', 'invalid_action', action) source = __validate_source(source) + source_objects = __validate_source_objects(e_uci, source_objects, source) appgroups = __validate_appgroups(e_uci, appgroups, match_all) - __save_rule_data(e_uci, config_name, name, enabled, action, source, appgroups, match_all) + __save_rule_data(e_uci, config_name, name, enabled, action, source, appgroups, match_all, source_objects) e_uci.save('dpi') return config_name diff --git a/packages/python3-nethsec/src/nethsec/objects/__init__.py b/packages/python3-nethsec/src/nethsec/objects/__init__.py index c505ac70d..4253abf82 100644 --- a/packages/python3-nethsec/src/nethsec/objects/__init__.py +++ b/packages/python3-nethsec/src/nethsec/objects/__init__.py @@ -92,7 +92,7 @@ def is_used_object(uci, database_id): if uci.get('mwan3', section, 'ns_src', default=None) == database_id or uci.get('mwan3', section, 'ns_dst', default=None) == database_id: matches.append(f'mwan3/{section}') for section in uci.get_all("dpi"): - if uci.get('dpi', section, 'source', default=None) == database_id: + if database_id in uci.get('dpi', section, 'source_object', list=True, default=[]): matches.append(f'dpi/{section}') for section in uci.get_all("objects"): try: @@ -878,7 +878,10 @@ def get_info(uci, database_id): if not name: name = uci.get(database, id, 'label', default=None) if not name: - name = id + # DPI rules keep their name here + name = uci.get(database, id, 'ns_name', default=None) + if not name: + name = id return {'database': database, 'id': id, 'name': name, 'type': type, 'family': family} except: return None diff --git a/packages/python3-nethsec/tests/test_dpi.py b/packages/python3-nethsec/tests/test_dpi.py index 739585915..b5e6e1994 100644 --- a/packages/python3-nethsec/tests/test_dpi.py +++ b/packages/python3-nethsec/tests/test_dpi.py @@ -1,3 +1,4 @@ +import os import pathlib import subprocess @@ -5,7 +6,7 @@ from euci import EUci from pytest_mock import MockFixture -from nethsec import dpi, utils +from nethsec import dpi, objects, utils from nethsec.utils import ValidationError applications = { @@ -875,6 +876,7 @@ def test_list_rules(e_uci_rules): 'enabled': True, 'action': 'block', 'source': ['192.168.1.0/24'], + 'source_objects': [], 'appgroups': [{'id': group, 'name': 'Group one'}], 'match_all': False, 'managed': True, @@ -1256,3 +1258,569 @@ def test_migrate_schema_is_idempotent(e_uci_legacy, mock_reload): assert dpi_config_file(e_uci_legacy) == config_after_first_run assert not has_pending_changes(e_uci_legacy) assert not reloaded(mock_reload) + + +# Source objects + +objects_config = """ +config host 'ns_host' + option name 'host1' + option family 'ipv4' + list ipaddr '192.168.1.10' + +config host 'ns_cidr' + option name 'cidr1' + option family 'ipv4' + list ipaddr '192.168.1.0/24' + +config host 'ns_range' + option name 'range1' + option family 'ipv4' + list ipaddr '192.168.1.10-192.168.1.13' + +config host 'ns_reversed' + option name 'reversed1' + option family 'ipv4' + list ipaddr '192.168.1.20-192.168.1.10' + list ipaddr '192.168.1.30' + +config host 'ns_nested' + option name 'nested1' + option family 'ipv4' + list ipaddr 'objects/ns_host' + list ipaddr 'dhcp/ns_lease' + list ipaddr '10.0.0.1' + list ipaddr '192.168.1.10' + +config host 'ns_mapped' + option name 'mapped1' + option family 'ipv6' + list ipaddr '::ffff:192.168.1.10' + list ipaddr '::ffff:192.168.2.0/120' + +config host 'ns_all' + option name 'all1' + option family 'ipv4' + list ipaddr '0.0.0.0/0' + +config host 'ns_all6' + option name 'all6' + option family 'ipv6' + list ipaddr '::-ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff' + +config host 'ns_zone' + option name 'zone1' + option family 'ipv6' + list ipaddr 'fe80::1%eth0' + list ipaddr 'fe80::10%eth0-fe80::11%eth0' + +config host 'ns_v6range' + option name 'v6range1' + option family 'ipv6' + list ipaddr 'fd00::1-fd00::4' + list ipaddr 'FD00::50' + +config host 'ns_with_domain' + option name 'withdomain1' + option family 'ipv4' + list ipaddr 'objects/ns_domain' + +config domain 'ns_domain' + option name 'domain1' + option family 'ipv4' + option timeout '600' + list domain 'example.com' +""" + +dhcp_config = """ +config host 'ns_lease' + option name 'lease1' + option ip '192.168.1.50' + option mac '02:00:00:00:00:50' + +config domain 'ns_record' + option name 'record.lan' + option ip '192.168.1.60' +""" + +users_config = """ +config user 'ns_vpn' + option name 'vpnuser' + option openvpn_ipaddr '10.9.0.2' + +config user 'ns_novpn' + option name 'novpnuser' +""" + + +@pytest.fixture +def e_uci_sources(e_uci_rules): + """Rules on top of a configuration holding every kind of object.""" + conf_dir = pathlib.Path(e_uci_rules.confdir()) + conf_dir.joinpath('objects').write_text(objects_config) + conf_dir.joinpath('dhcp').write_text(dhcp_config) + conf_dir.joinpath('users').write_text(users_config) + conf_dir.joinpath('mwan3').write_text('') + return e_uci_rules + + +def test_add_rule_with_source_objects(e_uci_sources): + group = group_of(e_uci_sources) + rule_id = dpi.add_rule(e_uci_sources, 'Block hosts', True, 'block', [], [group], + source_objects=['objects/ns_host', 'dhcp/ns_lease', 'objects/ns_host']) + assert e_uci_sources.get('dpi', rule_id, 'source_object', list=True) == ('objects/ns_host', 'dhcp/ns_lease') + assert e_uci_sources.get('dpi', rule_id, 'source', default=None) is None + + +@pytest.mark.parametrize('object_id', ['objects/ns_host', 'objects/ns_cidr', 'objects/ns_range', 'objects/ns_nested', + 'dhcp/ns_lease', 'dhcp/ns_record', 'users/ns_vpn']) +def test_add_rule_accepts_every_source_object_kind(e_uci_sources, object_id): + group = group_of(e_uci_sources) + rule_id = dpi.add_rule(e_uci_sources, 'Rule', True, 'block', [], [group], source_objects=[object_id]) + assert e_uci_sources.get('dpi', rule_id, 'source_object', list=True) == (object_id,) + + +@pytest.mark.parametrize('object_id', ['objects/ns_domain', 'objects/ns_missing', 'dhcp/ns_missing', 'firewall/ns_lan', + 'users/ns_novpn', '192.168.1.1', '', None, 'objects/']) +def test_add_rule_refuses_an_invalid_source_object(e_uci_sources, object_id): + group = group_of(e_uci_sources) + with pytest.raises(ValidationError) as err: + dpi.add_rule(e_uci_sources, 'Rule', True, 'block', [], [group], source_objects=[object_id]) + assert err.value.args[0] == 'source_objects' + assert err.value.args[1] == 'invalid_source_object' + + +def test_add_rule_refuses_addresses_and_source_objects_together(e_uci_sources): + group = group_of(e_uci_sources) + with pytest.raises(ValidationError) as err: + dpi.add_rule(e_uci_sources, 'Rule', True, 'block', ['192.168.1.1'], [group], + source_objects=['objects/ns_host']) + assert err.value.args[0] == 'source_objects' + assert err.value.args[1] == 'source_objects_with_source' + + +def test_edit_rule_refuses_addresses_and_source_objects_together(e_uci_sources): + group = group_of(e_uci_sources) + rule_id = dpi.add_rule(e_uci_sources, 'Rule', True, 'block', ['192.168.1.1'], [group]) + with pytest.raises(ValidationError) as err: + dpi.edit_rule(e_uci_sources, rule_id, 'Rule', True, 'block', ['192.168.1.1'], [group], + source_objects=['objects/ns_host']) + assert err.value.args[1] == 'source_objects_with_source' + + +def test_edit_rule_sets_and_clears_source_objects(e_uci_sources): + group = group_of(e_uci_sources) + rule_id = dpi.add_rule(e_uci_sources, 'Rule', True, 'block', ['192.168.1.1'], [group]) + dpi.edit_rule(e_uci_sources, rule_id, 'Rule', True, 'block', [], [group], source_objects=['users/ns_vpn']) + assert e_uci_sources.get('dpi', rule_id, 'source_object', list=True) == ('users/ns_vpn',) + assert e_uci_sources.get('dpi', rule_id, 'source', default=None) is None + dpi.edit_rule(e_uci_sources, rule_id, 'Rule', True, 'block', [], [group]) + assert e_uci_sources.get('dpi', rule_id, 'source_object', default=None) is None + + +def test_list_rules_reports_source_objects(e_uci_sources): + group = group_of(e_uci_sources) + dpi.add_rule(e_uci_sources, 'Rule', True, 'block', [], [group], + source_objects=['objects/ns_host', 'objects/ns_cidr', 'objects/ns_range', 'objects/ns_nested', + 'dhcp/ns_lease', 'dhcp/ns_record', 'users/ns_vpn']) + rule = dpi.list_rules(e_uci_sources)[0] + assert rule['source'] == [] + assert rule['source_objects'] == [ + {'id': 'objects/ns_host', 'name': 'host1', 'type': 'host_set', 'subtype': 'host'}, + {'id': 'objects/ns_cidr', 'name': 'cidr1', 'type': 'host_set', 'subtype': 'host_set'}, + {'id': 'objects/ns_range', 'name': 'range1', 'type': 'host_set', 'subtype': 'host_set'}, + {'id': 'objects/ns_nested', 'name': 'nested1', 'type': 'host_set', 'subtype': 'host_set'}, + {'id': 'dhcp/ns_lease', 'name': 'lease1', 'type': 'dhcp_static_lease', 'subtype': 'dhcp_static_lease'}, + {'id': 'dhcp/ns_record', 'name': 'record.lan', 'type': 'dns_record', 'subtype': 'dns_record'}, + {'id': 'users/ns_vpn', 'name': 'vpnuser', 'type': 'vpn_user', 'subtype': 'vpn_user'}, + ] + + +def test_list_rules_reports_a_source_object_gone_from_the_configuration(e_uci_sources): + group = group_of(e_uci_sources) + rule_id = dpi.add_rule(e_uci_sources, 'Rule', True, 'block', [], [group], source_objects=['objects/ns_host']) + e_uci_sources.set('dpi', rule_id, 'source_object', ['objects/ns_gone']) + assert dpi.list_rules(e_uci_sources)[0]['source_objects'] == [ + {'id': 'objects/ns_gone', 'name': 'objects/ns_gone', 'type': None, 'subtype': None}] + + +def test_list_rules_without_source_objects(e_uci_sources): + group = group_of(e_uci_sources) + dpi.add_rule(e_uci_sources, 'Rule', True, 'block', [], [group]) + assert dpi.list_rules(e_uci_sources)[0]['source_objects'] == [] + + +def test_build_rule_criteria_with_source_objects(e_uci_sources): + group = group_of(e_uci_sources) + rule_id = dpi.add_rule(e_uci_sources, 'Rule', True, 'block', [], [group], + source_objects=['objects/ns_host', 'users/ns_vpn']) + assert dpi.build_rule_criteria(e_uci_sources, e_uci_sources.get_all('dpi', rule_id)) == ( + "(local_ip == @objects_ns_host || local_ip == @users_ns_vpn) && (app == 'netify.netflix');" + ) + + +def test_build_rule_criteria_of_a_rule_edited_by_hand_with_addresses_and_source_objects(e_uci_sources): + # the API refuses both together, a rule edited by hand matches either + group = group_of(e_uci_sources) + rule = {'appgroup': [group], 'source': ['192.168.5.5'], 'source_object': ['objects/ns_range']} + assert dpi.build_rule_criteria(e_uci_sources, rule) == ( + "(local_ip == 192.168.5.5 || local_ip == @objects_ns_range) && (app == 'netify.netflix');" + ) + + +def test_build_rule_criteria_of_a_match_all_rule_narrowed_to_source_objects(e_uci_sources): + rule_id = dpi.add_rule(e_uci_sources, 'Rule', True, 'allow', [], [], match_all=True, + source_objects=['dhcp/ns_lease']) + assert dpi.build_rule_criteria(e_uci_sources, e_uci_sources.get_all('dpi', rule_id)) == ( + '(local_ip == @dhcp_ns_lease);' + ) + + +def test_build_rule_criteria_keeps_a_source_object_without_addresses(e_uci_sources): + # dropping the term would turn the rule into one matching every host + group = group_of(e_uci_sources) + rule_id = dpi.add_rule(e_uci_sources, 'Rule', True, 'block', [], [group], source_objects=['objects/ns_with_domain']) + assert dpi.build_rule_criteria(e_uci_sources, e_uci_sources.get_all('dpi', rule_id)) == ( + "(local_ip == @objects_ns_with_domain) && (app == 'netify.netflix');" + ) + + +def test_source_object_is_used(e_uci_sources): + group = group_of(e_uci_sources) + assert objects.is_used_object(e_uci_sources, 'objects/ns_cidr') == (False, []) + rule_id = dpi.add_rule(e_uci_sources, 'One', True, 'block', [], [group], source_objects=['objects/ns_cidr']) + assert objects.is_used_object(e_uci_sources, 'objects/ns_cidr') == (True, [f'dpi/{rule_id}']) + with pytest.raises(ValidationError) as err: + objects.delete_host_set(e_uci_sources, 'ns_cidr') + assert err.value.args[1] == 'host_set_is_used' + assert objects.is_used_object(e_uci_sources, 'dhcp/ns_record') == (False, []) + # the usage is shown with the rule name + assert objects.get_info(e_uci_sources, f'dpi/{rule_id}')['name'] == 'One' + +# Address groups + +groups_objects_db = """ +config host 'ns_host' + option name 'host1' + option family 'ipv4' + list ipaddr '192.168.1.10' + +config host 'ns_cidr' + option name 'cidr1' + option family 'ipv4' + list ipaddr '192.168.1.0/24' + +config host 'ns_range' + option name 'range1' + option family 'ipv4' + list ipaddr '192.168.1.10-192.168.1.13' + +config host 'ns_reversed' + option name 'reversed1' + option family 'ipv4' + list ipaddr '192.168.1.20-192.168.1.10' + list ipaddr '192.168.1.30' + +config host 'ns_nested' + option name 'nested1' + option family 'ipv4' + list ipaddr 'objects/ns_host' + list ipaddr 'dhcp/ns_lease' + list ipaddr '10.0.0.1' + list ipaddr '192.168.1.10' + +config host 'ns_mapped' + option name 'mapped1' + option family 'ipv6' + list ipaddr '::ffff:192.168.1.10' + list ipaddr '::ffff:192.168.2.0/120' + +config host 'ns_all' + option name 'all1' + option family 'ipv4' + list ipaddr '0.0.0.0/0' + +config host 'ns_all6' + option name 'all6' + option family 'ipv6' + list ipaddr '::-ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff' + +config host 'ns_zone' + option name 'zone1' + option family 'ipv6' + list ipaddr 'fe80::1%eth0' + list ipaddr 'fe80::10%eth0-fe80::11%eth0' + +config host 'ns_v6range' + option name 'v6range1' + option family 'ipv6' + list ipaddr 'fd00::1-fd00::4' + list ipaddr 'FD00::50' + +config host 'ns_with_domain' + option name 'withdomain1' + option family 'ipv4' + list ipaddr 'objects/ns_domain' + +config domain 'ns_domain' + option name 'domain1' + option family 'ipv4' + option timeout '600' + list domain 'example.com' +""" + +groups_dhcp_db = """ +config dnsmasq + option domain 'lan' + +config host 'ns_lease' + option name 'lease1' + option ip '192.168.1.50' + option mac '02:00:00:00:00:50' + +config domain 'ns_record' + option name 'record.lan' + option ip '192.168.1.60' +""" + +groups_users_db = """ +config local 'main' + option description 'Local users' + +config user 'ns_vpn' + option name 'vpnuser' + option database 'main' + option openvpn_ipaddr '10.9.0.2' + +config user 'ns_novpn' + option name 'novpnuser' + option database 'main' + +config user 'ns_noip' + option name 'noipuser' + option database 'main' + option openvpn_ipaddr '' +""" + +# the objects of the configuration above with at least one address, so with an address group file. +# Pending changes other tests leave in the default savedir can add more objects: assertions check these +groups_files = ['30-dhcp_ns_lease.conf', '30-dhcp_ns_record.conf', '30-objects_ns_all.conf', + '30-objects_ns_all6.conf', '30-objects_ns_cidr.conf', '30-objects_ns_host.conf', + '30-objects_ns_mapped.conf', '30-objects_ns_nested.conf', '30-objects_ns_range.conf', + '30-objects_ns_reversed.conf', '30-objects_ns_v6range.conf', '30-objects_ns_zone.conf', + '30-users_ns_vpn.conf'] + +# the objects of the configuration above without addresses, so without a file +groups_no_files = ['30-objects_ns_domain.conf', '30-objects_ns_with_domain.conf', '30-users_ns_novpn.conf', + '30-users_ns_noip.conf'] + + +@pytest.fixture +def g(tmp_path: pathlib.Path, monkeypatch) -> EUci: + """A configuration holding every kind of object, address groups in a temp dir.""" + conf_dir = tmp_path.joinpath('conf') + conf_dir.mkdir() + conf_dir.joinpath('objects').write_text(groups_objects_db) + conf_dir.joinpath('dhcp').write_text(groups_dhcp_db) + conf_dir.joinpath('users').write_text(groups_users_db) + save_dir = tmp_path.joinpath('save') + save_dir.mkdir() + monkeypatch.setattr(dpi, 'ADDRESS_GROUPS_DIR', tmp_path.joinpath('address-groups.d').as_posix()) + return EUci(confdir=conf_dir.as_posix(), savedir=save_dir.as_posix()) + + +def groups_dir() -> pathlib.Path: + return pathlib.Path(dpi.ADDRESS_GROUPS_DIR) + + +def group_file(name) -> pathlib.Path: + return groups_dir().joinpath(name) + + +def group_files() -> set: + return {path.name for path in groups_dir().iterdir()} + + +def test_address_group_tag(): + assert dpi._address_group_tag('objects/ns_host') == 'objects_ns_host' + assert dpi._address_group_tag('users/ns_vpn') == 'users_ns_vpn' + + +@pytest.mark.parametrize('object_id, entries', [ + ('objects/ns_host', ['192.168.1.10/32']), + ('objects/ns_cidr', ['192.168.1.0/24']), + # an address group ignores ranges: they become CIDR blocks + ('objects/ns_range', ['192.168.1.10/31', '192.168.1.12/31']), + ('objects/ns_v6range', ['fd00::1/128', 'fd00::2/127', 'fd00::4/128', 'fd00::50/128']), + # the object API accepts a reversed range: it covers the same addresses as the ordered one + ('objects/ns_reversed', ['192.168.1.10/31', '192.168.1.12/30', '192.168.1.16/30', '192.168.1.20/32', + '192.168.1.30/32']), + # references are resolved, duplicates dropped + ('objects/ns_nested', ['192.168.1.10/32', '192.168.1.50/32', '10.0.0.1/32']), + # an IPv4-mapped address never matches the IPv4 flow it maps + ('objects/ns_mapped', ['192.168.1.10/32', '192.168.2.0/24']), + # a zero length prefix matches nothing in a group: its two halves match everything + ('objects/ns_all', ['0.0.0.0/1', '128.0.0.0/1']), + ('objects/ns_all6', ['::/1', '8000::/1']), + ('objects/ns_zone', ['fe80::1/128', 'fe80::10/127']), + ('dhcp/ns_lease', ['192.168.1.50/32']), + ('dhcp/ns_record', ['192.168.1.60/32']), + ('users/ns_vpn', ['10.9.0.2/32']), + # objects with no address + ('users/ns_novpn', []), + ('users/ns_noip', []), + ('objects/ns_with_domain', []), + ('objects/ns_domain', []), + ('objects/ns_missing', []), +]) +def test_address_group_entries(g, object_id, entries): + assert dpi._address_group_entries(g, object_id) == entries + + +def test_write_address_groups(g): + assert dpi.write_address_groups(g) is True + # one file per object with addresses: no file for domain sets, users without a reserved IP and objects + # resolving to no address + assert set(groups_files) <= group_files() + assert not set(groups_no_files) & group_files() + assert all(name.startswith('30-') and name.endswith('.conf') for name in group_files()) + assert group_file('30-objects_ns_range.conf').read_text() == ( + '# range1\n# objects/ns_range, generated from the firewall objects: do not edit\n' + '192.168.1.10/31\n192.168.1.12/31\n') + assert group_file('30-users_ns_vpn.conf').read_text() == ( + '# vpnuser\n# users/ns_vpn, generated from the firewall objects: do not edit\n10.9.0.2/32\n') + # unchanged: nothing is written + inode = group_file('30-objects_ns_host.conf').stat().st_ino + assert dpi.write_address_groups(g) is False + assert group_file('30-objects_ns_host.conf').stat().st_ino == inode + + +def test_write_address_groups_removes_only_its_own_stale_files(g): + groups_dir().mkdir() + # other prefixes or extensions: kept + for name in ('10-agent.conf', '20-other.conf', '30-objects_ns_gone.txt'): + group_file(name).write_text('10.0.0.1\n') + # objects gone, as written here or as saved by the agent without the header: removed + group_file('30-objects_ns_gone.conf').write_text( + '# gone1\n# objects/ns_gone, generated from the firewall objects: do not edit\n10.0.0.1/32\n') + group_file('30-objects_ns_saved.conf').write_text('10.0.0.1\n') + group_file('30-objects_ns_empty.conf').write_text('') + # an object without addresses: its file goes too + group_file('30-users_ns_novpn.conf').write_text('10.9.0.3\n') + # an existing object, as saved by the agent: rewritten with the header + group_file('30-objects_ns_host.conf').write_text('192.168.1.10\n') + dpi.write_address_groups(g) + assert {'10-agent.conf', '20-other.conf', '30-objects_ns_gone.txt'} | set(groups_files) <= group_files() + assert not {'30-objects_ns_gone.conf', '30-objects_ns_saved.conf', '30-objects_ns_empty.conf', + '30-users_ns_novpn.conf'} & group_files() + assert group_file('30-objects_ns_host.conf').read_text().splitlines()[1] == ( + '# objects/ns_host, generated from the firewall objects: do not edit') + + +def test_write_address_groups_follows_the_objects(g): + dpi.write_address_groups(g) + host = group_file('30-objects_ns_host.conf') + # the object changes: its file follows, and the one of the host set holding it too + g.set('objects', 'ns_host', 'ipaddr', ['192.168.1.11']) + assert dpi.write_address_groups(g) is True + assert host.read_text().splitlines()[2:] == ['192.168.1.11/32'] + assert group_file('30-objects_ns_nested.conf').read_text().splitlines()[2:] == [ + '192.168.1.11/32', '192.168.1.50/32', '10.0.0.1/32', '192.168.1.10/32'] + # the object is renamed: the header follows + g.set('objects', 'ns_host', 'name', 'renamed') + dpi.write_address_groups(g) + assert host.read_text().splitlines()[0] == '# renamed' + # the object is deleted: its file goes + g.delete('objects', 'ns_host') + assert dpi.write_address_groups(g) is True + assert not host.exists() + # a VPN user loses its reserved IP: its file goes, and comes back with it + vpn = group_file('30-users_ns_vpn.conf') + g.delete('users', 'ns_vpn', 'openvpn_ipaddr') + dpi.write_address_groups(g) + assert not vpn.exists() + g.set('users', 'ns_vpn', 'openvpn_ipaddr', '10.9.0.5') + dpi.write_address_groups(g) + assert vpn.read_text().splitlines()[2:] == ['10.9.0.5/32'] + # a new object: a new file + g.set('dhcp', 'ns_new', 'host') + g.set('dhcp', 'ns_new', 'name', 'new1') + g.set('dhcp', 'ns_new', 'ip', '192.168.1.70') + dpi.write_address_groups(g) + assert group_file('30-dhcp_ns_new.conf').read_text().splitlines()[2:] == ['192.168.1.70/32'] + + +def test_write_address_groups_files_are_readable_whatever_the_umask(g): + umask = os.umask(0o077) + try: + dpi.write_address_groups(g) + finally: + os.umask(umask) + assert group_file('30-objects_ns_host.conf').stat().st_mode & 0o777 == 0o644 + # an unchanged file keeps its content, its mode is fixed + group_file('30-objects_ns_host.conf').chmod(0o600) + assert dpi.write_address_groups(g) is False + assert group_file('30-objects_ns_host.conf').stat().st_mode & 0o777 == 0o644 + + +def test_write_address_groups_header(g): + # an object without a name: the header holds only the id + g.delete('objects', 'ns_host', 'name') + # a name on more lines: joined on one + g.set('objects', 'ns_cidr', 'name', 'two\nlines') + dpi.write_address_groups(g) + assert group_file('30-objects_ns_host.conf').read_text() == ( + '# objects/ns_host, generated from the firewall objects: do not edit\n192.168.1.10/32\n') + assert group_file('30-objects_ns_cidr.conf').read_text().splitlines()[:2] == [ + '# two lines', '# objects/ns_cidr, generated from the firewall objects: do not edit'] + + +def test_write_address_groups_without_configurations(tmp_path, monkeypatch): + conf_dir = tmp_path.joinpath('conf') + conf_dir.mkdir() + save_dir = tmp_path.joinpath('save') + save_dir.mkdir() + monkeypatch.setattr(dpi, 'ADDRESS_GROUPS_DIR', tmp_path.joinpath('address-groups.d').as_posix()) + dpi.write_address_groups(EUci(confdir=conf_dir.as_posix(), savedir=save_dir.as_posix())) + assert not set(groups_files) & group_files() + + +def netifyd_calls(run): + return [call.args[0] for call in run.call_args_list] + + +def test_update_address_groups_reloads_a_running_agent(g, mocker): + run = mocker.patch('nethsec.dpi.subprocess.run') + run.return_value.returncode = 0 + assert dpi.update_address_groups(g) is True + assert netifyd_calls(run) == [['/etc/init.d/netifyd', 'running'], ['/etc/init.d/netifyd', 'reload']] + # nothing changed: no reload + run.reset_mock() + assert dpi.update_address_groups(g) is False + assert netifyd_calls(run) == [] + + +def test_address_group_entries_skips_an_invalid_value(g, mocker): + log = mocker.patch('nethsec.dpi.syslog.syslog') + # a range mixing the families can't become networks: it is skipped, the rest of the object is kept + g.set('objects', 'ns_reversed', 'ipaddr', ['192.168.1.10-fd00::1', '192.168.1.30']) + assert dpi._address_group_entries(g, 'objects/ns_reversed') == ['192.168.1.30/32'] + assert "skipping '192.168.1.10-fd00::1' of objects/ns_reversed" in log.call_args.args[1] + # the host set itself is left as entered + assert g.get('objects', 'ns_reversed', 'ipaddr', list=True) == ('192.168.1.10-fd00::1', '192.168.1.30') + + +def test_update_address_groups_leaves_a_stopped_agent_alone(g, mocker): + run = mocker.patch('nethsec.dpi.subprocess.run') + run.return_value.returncode = 1 + assert dpi.update_address_groups(g) is True + assert netifyd_calls(run) == [['/etc/init.d/netifyd', 'running']] + + +def test_update_address_groups_logs_a_write_failure(g, mocker): + run = mocker.patch('nethsec.dpi.subprocess.run') + mocker.patch('nethsec.dpi.write_address_groups', side_effect=PermissionError('denied')) + log = mocker.patch('nethsec.dpi.syslog.syslog') + assert dpi.update_address_groups(g) is False + assert netifyd_calls(run) == [] + assert 'cannot write the address groups' in log.call_args.args[1] From fd809bcfd995e53d23f3b6554de701ee60bf635b Mon Sep 17 00:00:00 2001 From: Matteo Di Lorenzi <52289654+m-dilorenzi@users.noreply.github.com> Date: Thu, 19 Nov 2026 15:47:17 +0100 Subject: [PATCH 52/54] feat(firewall): disable HTTPS access from WAN by default (#2020) --- files/etc/config/firewall | 1 + 1 file changed, 1 insertion(+) diff --git a/files/etc/config/firewall b/files/etc/config/firewall index 5f84d5b92..fe2c47cae 100644 --- a/files/etc/config/firewall +++ b/files/etc/config/firewall @@ -29,6 +29,7 @@ config rule 'ns_allow_https' option src 'wan' option dest_port '443' option target 'ACCEPT' + option enabled '0' config rule 'ns_allow_ui' option name 'Allow-UI-from-WAN' From a9e525244dac21d0919599d26f1015cc80998069 Mon Sep 17 00:00:00 2001 From: Tommaso Bailetti Date: Fri, 20 Nov 2026 15:01:57 +0100 Subject: [PATCH 53/54] chore: 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 6a6cb76ee..30c2d8365 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:=fe2fd0d3126efe55904c8212fb286a609b561431 PKG_SOURCE_SUBDIR:=nethsecurity-ui-$(PKG_SOURCE_VERSION) PKG_BUILD_DIR:=$(BUILD_DIR)/$(PKG_SOURCE_SUBDIR) PKG_MIRROR_HASH:=skip From 75af8bcc6b1b8c4e8f22d9070f363c5ec62afd56 Mon Sep 17 00:00:00 2001 From: Giacomo Sanchietti Date: Fri, 20 Nov 2026 17:00:54 +0100 Subject: [PATCH 54/54] fix(dpi): refuse IPv6 zones in rule sources (#2036) --- packages/python3-nethsec/src/nethsec/dpi/__init__.py | 8 ++++++-- packages/python3-nethsec/tests/test_dpi.py | 9 ++++++++- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/packages/python3-nethsec/src/nethsec/dpi/__init__.py b/packages/python3-nethsec/src/nethsec/dpi/__init__.py index d92fda6c0..f75ec40ff 100644 --- a/packages/python3-nethsec/src/nethsec/dpi/__init__.py +++ b/packages/python3-nethsec/src/nethsec/dpi/__init__.py @@ -615,6 +615,9 @@ def __validate_source(values: list[str]) -> list[str]: if not isinstance(value, str) or not value.strip(): raise ValidationError('source', 'invalid_source', value) source = value.strip() + # an IPv6 zone means nothing to local_ip, and its free text would end up in the criteria + if '%' in source: + raise ValidationError('source', 'invalid_source', value) try: if '-' in source: first, last = (ipaddress.ip_address(part.strip()) for part in source.split('-', 1)) @@ -664,11 +667,12 @@ def expand_source(values: list[str]) -> list[str]: """ expanded = [] for value in values: + # drop the zone of a value saved before it was refused, e.g. restored from a backup if '-' in value: - first, last = (ipaddress.ip_address(part.strip()) for part in value.split('-', 1)) + first, last = (ipaddress.ip_address(_strip_zone(part.strip())) for part in value.split('-', 1)) expanded.extend(str(network) for network in ipaddress.summarize_address_range(first, last)) else: - expanded.append(value) + expanded.append(_strip_zone(value)) return expanded diff --git a/packages/python3-nethsec/tests/test_dpi.py b/packages/python3-nethsec/tests/test_dpi.py index b5e6e1994..5749ab8be 100644 --- a/packages/python3-nethsec/tests/test_dpi.py +++ b/packages/python3-nethsec/tests/test_dpi.py @@ -746,7 +746,8 @@ def test_add_rule_accepts_every_source_shape(e_uci_rules, source): @pytest.mark.parametrize('source', ['not-an-ip', '192.168.1.300', '192.168.1.20-192.168.1.10', - '192.168.1.1-2001:db8::1', '']) + '192.168.1.1-2001:db8::1', '', 'fe80::1%eth0', 'fe80::1%x) || (true', + 'fe80::1%x)-fe80::2']) def test_add_rule_refuses_an_invalid_source(e_uci_rules, source): group = group_of(e_uci_rules) with pytest.raises(ValidationError) as err: @@ -916,6 +917,12 @@ def test_expand_source(): assert dpi.expand_source(['10.0.0.1-10.0.0.2']) == ['10.0.0.1/32', '10.0.0.2/32'] +def test_expand_source_drops_the_zone(): + assert dpi.expand_source(['fe80::1%x) || (true']) == ['fe80::1'] + assert dpi.expand_source(['fe80::1%eth0/64']) == ['fe80::1/64'] + assert dpi.expand_source(['fe80::1%x)-fe80::2']) == ['fe80::1/128', 'fe80::2/128'] + + def test_build_rule_criteria(e_uci_rules): group = group_of(e_uci_rules) rule_id = dpi.add_rule(e_uci_rules, 'Block streaming', True, 'block',