Skip to content

Self-hosted monitoring for homelabs: host and container metrics and uptime checks from all your machines in one dashboard, with an optional AI agent that diagnoses incidents and suggests fixes.

feat: network checks (listening ports, firewall fingerprints, optional internet check)

karloks2005e3ee7b433516
diff --git a/README.md b/README.md
index 00ce730..8d34606 100644
--- a/README.md
+++ b/README.md
@@ -32,12 +32,16 @@ for what every component can touch and the limits of each protection.
- **System health per server**: reboots, OOM-killer activity, kernel fault flags,
clock synchronisation and pending reboots, plus (with the optional system helper)
whether the last shutdown was clean and which process the OOM killer stopped.
+- **Network at a glance**: which ports each server listens on (and which are reachable
+ from other machines), whether its firewall configuration changed, and, if you turn
+ it on, whether it can still reach the internet.
- **Incidents with sensible alert rules**: disk (with per-mount overrides), inodes,
memory, swap, load per CPU core, container restart loops, failing healthchecks,
reboots and crashes, OOM kills, kernel faults, unsynchronised clocks, an
unreachable or slow Docker daemon, containers that crash or are killed for running
- out of memory, containers that vanish or change image, possible memory leaks, and
- servers that stop reporting. One incident per problem, opened only after a sustained
+ out of memory, containers that vanish or change image, possible memory leaks, new
+ ports opened to the network, firewall changes, lost internet or DNS, and servers
+ that stop reporting. One incident per problem, opened only after a sustained
breach where that makes sense and resolved automatically when it clears.
Thresholds are editable by admins.
- **Add servers with one command and one click**: click **Connect a server**, run
@@ -393,6 +397,9 @@ Alternatives:
alert thresholds (including any per-mount overrides), a **System** row and a
**Containers** list. Both lists start closed. A filter box appears for servers
with more than 10 containers.
+- **Network** row: internet reachability, how many ports the server listens on and how
+ many are exposed, and the firewall state, opening into the listener list and the last
+ 7 days of port and firewall changes.
- **System** row: one line of status chips (when it booted, last shutdown, clock,
OOM kills in the last 24 hours, kernel, pending updates) that opens into the
last 7 days of reboots, OOM kills and kernel messages. A chip that says
@@ -432,6 +439,11 @@ stops firing.
| Possible memory leak (steady climb over 12 hours) | 10 MB/h and 20% growth | warning |
| Docker unreachable (after it worked before) | 3 check-ins in a row | critical |
| Docker slow to list containers | over 2000 ms, 3 check-ins in a row | warning |
+| New listener reachable from other machines | stays open 60 minutes | warning |
+| Firewall configuration changed | stays open 60 minutes | info |
+| Firewall protection reduced (ufw turned off, rules removed, a file gone) | stays open 60 minutes | warning |
+| No internet (only if the check is on) | 3 check-ins in a row | warning |
+| DNS failing (only if the check is on) | 3 check-ins in a row | warning |
| Server stopped reporting | 3 missed check-ins | critical |
| Host rebooted | stays open 60 minutes | info (critical after an unclean shutdown) |
| OOM killer fired | stays open 60 minutes | warning (critical at 3 or more) |
@@ -439,6 +451,13 @@ stops firing.
| Clock not synchronised | 3 check-ins in a row | warning |
| Reboot required | – | info |
+New listening ports and firewall changes are noticed the same way, by comparing with
+what the previous check-in saw. The first report is a silent baseline, an unreadable
+or empty report is treated as unknown (never as "everything closed"), and short-lived
+programs using random high ports (loopback ones and all UDP ones) are ignored. A new
+port bound only to the loopback address is recorded but doesn't open an incident; one
+reachable from other machines does. Events are capped like the container ones.
+
Container exits, removals and image changes are noticed by comparing each check-in
with the previous one, matching containers **by name** (Compose recreates them with
new IDs). Nothing is reported on a server's first check-in or when Docker was
@@ -563,6 +582,7 @@ standard-library Python.
| `HOMELAB_JOIN_TOKEN` | empty | Single-use token from **Connect a server**; required over the VPN listener. |
| `HOMELAB_ENROLL_KEY` | empty | Join immediately instead of waiting for approval. |
| `HOMELAB_SERVER_NAME` | host's `/etc/hostname` | Name shown on the dashboard. |
+| `HOMELAB_CONNECTIVITY_TARGETS` | empty (check off) | Optional internet check: up to 5 comma-separated `host:port` targets (hostnames or IPv4), e.g. `1.1.1.1:443,9.9.9.9:443`. The collector opens a TCP connection and looks the name up; it sends nothing. Set on each collector; the dashboard cannot set it. |
| `HOMELAB_STATE_DIR` | `/var/lib/homelab-collector` | Where the token is saved (mount a volume here). |
| `HOMELAB_MACHINE_ID` | host's `/etc/machine-id` | Identity used to recognise reinstalled machines. |
| `HOMELAB_DASHBOARD_HOST` | empty | `true` marks this machine as the one running the dashboard (set in the Compose files for the stack's own collector; leave it unset elsewhere). |
@@ -588,7 +608,12 @@ from the backend's response to each report.
proxy mounts the socket; it has no network, answers three read-only requests and
strips environment variables, labels, mounts and error text from what it returns.
Everything a collector reports about containers is validated again by the backend
- (types, ranges, lengths, counts) before it is stored. The collector still mounts `/`
+ (types, ranges, lengths, counts) before it is stored.
+- **Network checks are passive.** Listening ports are read from the host's `/proc`
+ (protocol, port and scope only, no process names), the firewall check reads known
+ configuration files and reports only a hash and a rule count (never the rules, and not
+ the live ruleset, which would need `CAP_NET_ADMIN`), and the internet check is off
+ unless you configure its targets on that collector. The collector still mounts `/`
read-only; without capabilities it can't read other users' private files through it.
- **Collector endpoints are not public.** On the server stack the public listener
returns 404 for register, poll, enroll and ingest; they exist only on the
@@ -694,8 +719,9 @@ columns are added with `ALTER TABLE ... IF NOT EXISTS` in the startup hook in
carries the boot ID, OOM counter, kernel flags, clock state and last shutdown), one
per filesystem in `mount_metrics` and one per container in `container_metrics` (which
also records the exit code, out-of-memory flag, finish time and image ID), all with the
-same timestamp. `system_events` holds reboots, OOM kills, kernel messages and container
-changes (appeared, removed, image changed), `join_tokens` the hashed single-use tokens, and per-mount disk
+same timestamp. `system_events` holds reboots, OOM kills, kernel messages, container
+changes (appeared, removed, image changed) and network changes (ports opened or closed,
+firewall changes); `listener_states` and `firewall_states` hold what was last seen, `join_tokens` the hashed single-use tokens, and per-mount disk
thresholds live in `app_settings`. `docker/postgres/init/01_create_users.sql` initialises
the `users` table on a fresh volume.
@@ -788,6 +814,9 @@ same address as everything else.
| "Cross-site request refused" (403) on a button or form | The request came from another origin. Open the dashboard at the address you normally use. If a proxy in front rewrites the `Host` header, add your dashboard URL to `CORS_ORIGINS`. |
| The **System** row shows *unknown* for last shutdown or has no kernel messages | The optional system helper isn't running. Start it with `docker compose --profile system-events up -d`. *Unknown* for reboot-required on non-Debian hosts is expected. |
| `Error response … cannot assign requested address` for the collector gate | `COLLECTOR_BIND` is set to an address that doesn't exist yet (VPN not up). Start the VPN first, or fix the address. |
+| The **Network** row says *no config found* for the firewall | None of the known firewall files exist on that host (`/etc/ufw`, `/etc/nftables.conf`, `/etc/iptables/rules.v4`). The check reads configuration, not the live ruleset, so a host that configures its firewall some other way shows this. |
+| The **Network** row says *not checked* for the internet | The check is opt-in. Set `HOMELAB_CONNECTIVITY_TARGETS` on that collector (for example `1.1.1.1:443`). |
+| Listeners show *unknown* or the Network row is empty | The collector couldn't read the host's network tables (older collector, or a table with more than 500,000 sockets). An unreadable report never raises a "port closed" alert. |
| Server marked offline | It missed 3 check-ins in a row. Check the machine, its collector log and its route to the dashboard. The incident resolves on the next report. |
## License
diff --git a/SECURITY.md b/SECURITY.md
index c043dc6..3c41f04 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -166,6 +166,31 @@ What the collector deliberately does not ask Docker for: `/info`, `/events`, log
write. Checking registries for newer images would need outbound network access and is tracked
separately (#38) as an opt-in, isolated component rather than part of the collector or proxy.
+## Network checks
+
+The collector's network checks are passive or opt-in, and add no privileges:
+
+- **Listening ports** are read from the host's own network tables (`/proc/1/net`, the host's view; a
+ container's own `/proc/net` would show only the container's sockets). Only protocol, port and scope
+ (loopback, all interfaces, one address) are collected. Process names are not, because matching sockets
+ to other users' processes needs privileges the collector doesn't have. Short-lived programs using
+ random high ports (loopback ones and all UDP ones) are ignored.
+- **Firewall configuration** is read from a fixed list of files (`/etc/ufw/*.rules`, `ufw.conf`,
+ `nftables.conf`, `iptables/rules.v4` and `rules.v6`), never following symlinks and never reading more than
+ 1 MB. Only a short hash and a rule count leave the host, because the rules themselves reveal your
+ network layout. This sees configuration, not the live ruleset: reading that needs `CAP_NET_ADMIN`,
+ which can also change the firewall, so the collector doesn't have it.
+- **The internet check is off by default.** When enabled it only opens a TCP connection and looks the
+ name up, sending nothing. Its targets come from the collector's own environment
+ (`HOMELAB_CONNECTIVITY_TARGETS`), never from the dashboard, so a compromised dashboard can't point
+ probes at anything. Targets are limited to five hostnames or IPv4 addresses, and a probe cannot delay
+ a check-in beyond a fixed deadline.
+- **Unreadable never means closed.** If any network table can't be read, or is too large to read
+ completely, the listener report is unknown rather than partial, so it can't make ports look closed.
+ Reports are validated again by the backend and capped, and events are capped per check-in and per hour.
+- **Visibility.** Like all monitoring data, the list of listening ports and firewall state is visible to
+ every signed-in account. Keep registration closed on a public dashboard.
+
## Other exposure to be aware of
- The collector mounts the host filesystem read-only at `/hostfs` to read disk usage and a few
diff --git a/TESTS.md b/TESTS.md
index 1b6bc6d..e2aa4b4 100644
--- a/TESTS.md
+++ b/TESTS.md
@@ -4,7 +4,7 @@ Vexion ships with an automated test suite. This page explains how to run it, wha
covers (and what it doesn't), and what every single test is for, so you can decide
whether a failure matters before you upgrade or change your setup.
-- **413 test cases** from 234 test functions (some functions run once per input).
+- **507 test cases** from 292 test functions (some functions run once per input).
- **About 15 to 20 seconds** to run. No Docker, PostgreSQL, Redis, network or root access needed.
- **Safe to run next to a live install.** The tests use a throwaway in-memory database
and fakes; they never touch your running containers or your data. (Two collector
@@ -35,7 +35,7 @@ pytest
A healthy run ends with a line like:
```text
-413 passed, 3 warnings in 17.0s
+507 passed, 3 warnings in 17.0s
```
The warnings are harmless notices from the libraries (FastAPI deprecating the
@@ -131,6 +131,7 @@ docker compose logs --tail 20 collector # "Sent host metrics and N contai
| [`test_docker_proxy.py`](#test_docker_proxypy) | 91 | The read-only Docker proxy: what it allows, refuses and hides. |
| [`test_enrollment.py`](#test_enrollmentpy) | 10 | Enrollment keys, collector credentials and offline-server detection. |
| [`test_health_checks.py`](#test_health_checkspy) | 4 | The assistant's fixed health checks and the critical-only webhook. |
+| [`test_network_checks.py`](#test_network_checkspy) | 94 | The host's real network totals, listening-port inventory, optional internet check, firewall fingerprints, and the validation of all of it. |
| [`test_pending_collectors.py`](#test_pending_collectorspy) | 28 | Adding servers: approval, join tokens, strict mode, re-pairing safety. |
| [`test_rules.py`](#test_rulespy) | 20 | Alert thresholds: sustained breaches, per-mount disks, settings validation. |
| [`test_system_checks.py`](#test_system_checkspy) | 17 | Reboot, OOM, kernel-fault, clock and pending-reboot detection, and the System row's event list. |
@@ -399,6 +400,116 @@ tested hardest (91 cases). If any of these fail, do not run the proxy until it i
| `test_unknown_check_is_rejected` | Asking for any check that isn't one of the fixed ones raises an error. |
| `test_daily_checkup_alerts_only_for_critical_findings` | The daily check-up notifies the webhook only when something is critical. |
+### test_network_checks.py
+
+Network checks: the host's real traffic totals, which ports it listens on, whether it can
+reach the internet, and whether its firewall configuration changed. The collector parts read
+`/proc` and files, so most tests build a fake host in a temporary folder and feed the
+parsers odd, huge or hostile content.
+
+**Host network totals (collector)**
+
+| Test | What it checks |
+|---|---|
+| `test_network_totals_come_from_the_hosts_physical_interfaces` | Totals come from the host's real network cards only. The collector container's own interface is never used, and Docker's virtual interfaces are skipped so traffic isn't counted twice. |
+| `test_without_sysfs_virtual_interfaces_are_skipped_by_name` | If the hardware list isn't visible, loopback, bridge and virtual interfaces are skipped by name. |
+| `test_inside_a_container_an_unreadable_host_table_is_unknown_not_the_containers_own` | If the host's table can't be read, the totals are *unknown* instead of silently reporting the container's own traffic as the host's. |
+| `test_only_a_collector_on_the_host_itself_may_fall_back_to_proc_net` | Only a collector running directly on the host may fall back to its own network view. |
+| `test_garbage_and_oversized_network_tables_are_survived` | Malformed lines are skipped, and an oversized table is refused. |
+
+**Listening ports (collector)**
+
+| Test | What it checks |
+|---|---|
+| `test_listeners_are_read_with_their_scope` | Listening ports are read for TCP and UDP, IPv4 and IPv6, and classified as loopback only, all interfaces or one address; ordinary connections and connected UDP sockets are not listeners. |
+| `test_the_same_port_on_ipv4_and_ipv6_is_one_listener` | The same port on IPv4 and IPv6 counts once. |
+| `test_ephemeral_ports_are_skipped_but_exposed_high_tcp_ports_are_not` *(9 inputs)* | Random high ports used by programs talking out (loopback ones, and all UDP ones) are skipped, while high TCP ports reachable from other machines (such as Docker's random published ports) are kept. The collector and backend apply the same rule. |
+| `test_missing_or_garbage_tables_are_unknown_or_ignored` | Nothing readable means *unknown*; junk lines and impossible ports are ignored. |
+| `test_one_unreadable_table_makes_the_whole_answer_unknown_not_partial` | If any one of the four tables can't be read, the whole answer is unknown, so a partial picture can never look like closed ports. |
+| `test_a_table_longer_than_the_cap_is_unknown_because_a_truncated_read_could_fake_closed_ports` | A table over the line limit is treated as unknown, not truncated. |
+| `test_a_busy_hosts_connection_table_does_not_hide_its_listeners` | Thousands of ordinary connections don't hide the real listeners, and the table is streamed rather than loaded into memory. |
+| `test_a_container_never_reports_its_own_sockets_as_the_hosts` | A collector in a container never mistakes the container's own sockets for the host's. |
+| `test_the_listener_report_is_capped` | At most 512 listeners are reported. |
+
+**Internet check (collector, off by default)**
+
+| Test | What it checks |
+|---|---|
+| `test_connectivity_is_off_unless_targets_are_configured` | With no targets configured the check does nothing and sends no data. |
+| `test_valid_targets_are_parsed_deduplicated_and_capped` *(3 inputs)* | `host:port` targets (hostname or IPv4) are accepted, deduplicated and capped at 5. |
+| `test_malformed_targets_are_ignored` *(19 inputs)* | URLs, spaces, shell characters, bad ports, IPv6 literals, mistyped IPs, usernames, paths and over-long names are all ignored. |
+| `test_results_are_summarised` *(5 inputs)* | The results become ok, degraded, DNS failing or down. |
+| `test_a_reachable_target_reports_ok_with_its_latency` | Reachable targets report ok and the typical connection time. |
+| `test_unresolvable_names_are_reported_as_dns_failure` | Names that don't resolve are reported as a DNS failure, not as the internet being down. |
+| `test_a_hung_probe_cannot_stall_the_check_in` | A probe that hangs cannot delay the collector's report beyond a fixed deadline. |
+| `test_probes_only_connect_and_never_send_data` | The probes open a connection and send nothing. |
+
+**Firewall files (collector)**
+
+| Test | What it checks |
+|---|---|
+| `test_firewall_files_are_reduced_to_a_hash_a_rule_count_and_the_ufw_flag` | Each known firewall file is reduced to a short hash and a rule count, plus whether ufw is enabled. |
+| `test_the_firewall_report_never_contains_the_rules_themselves` | No rule text, address or comment ever appears in what is reported. |
+| `test_ufw_disabled_is_reported_and_changes_the_fingerprint` | Turning ufw off is visible, and changes the fingerprint. |
+| `test_no_known_firewall_file_means_none` | No firewall files means no report. |
+| `test_symlinked_oversized_and_binary_firewall_files_are_handled_safely` | Symlinks are not followed, files over 1 MB are skipped, and binary content doesn't crash anything. |
+
+**Validation and state (backend)**
+
+| Test | What it checks |
+|---|---|
+| `test_a_listener_report_must_be_a_list` *(5 inputs)* | Anything but a list is rejected. |
+| `test_listener_entries_are_validated_deduplicated_and_filtered` | Unknown protocols and scopes, bad or non-integer ports, junk entries and ephemeral ports are dropped, and duplicates merged. |
+| `test_the_listener_list_is_capped` | The backend accepts at most 512 listeners per report. |
+| `test_firewall_reports_are_validated` | Only known file names with a proper 16-hex-character hash and a sane rule count are accepted; the ufw flag must be a real boolean. |
+
+**Listening-port changes and incidents (backend)**
+
+| Test | What it checks |
+|---|---|
+| `test_the_first_listener_report_is_only_a_baseline` | The first report creates no events. |
+| `test_a_new_exposed_listener_is_recorded_and_raises_a_warning` | A new port reachable from other machines is recorded and raises a warning incident. |
+| `test_a_new_loopback_listener_is_an_event_without_an_incident` | A new loopback-only port is recorded, but raises no incident. |
+| `test_a_closed_listener_is_recorded_and_clears_its_incident` | A closed port is recorded and clears its incident. |
+| `test_the_listener_incident_clears_with_the_event_window` | The incident clears by itself after the event window. |
+| `test_unchanged_listeners_create_no_events_or_duplicate_rows` | Unchanged listeners create nothing and never duplicate stored rows. |
+| `test_an_empty_or_missing_listener_report_never_looks_like_everything_closed` | An empty list, a missing field or garbage is ignored rather than read as every port closing. |
+| `test_a_burst_of_new_listeners_is_capped_with_one_notice` | A burst of new ports records at most 10 events per check-in plus one notice. |
+| `test_sustained_port_flapping_is_capped_per_hour` | Ports opening and closing constantly cannot flood the database. |
+| `test_listener_state_is_removed_with_the_server` | Deleting a server removes its stored listeners and firewall fingerprints. |
+
+**Firewall changes and incidents (backend)**
+
+| Test | What it checks |
+|---|---|
+| `test_the_first_firewall_report_is_only_a_baseline` | The first report creates no events. |
+| `test_unchanged_firewall_files_report_nothing` | Unchanged files report nothing. |
+| `test_changed_rules_are_informational_and_fewer_rules_are_a_warning` | Changed rules are informational; a drop in the rule count is a warning. |
+| `test_disabling_ufw_is_a_warning_and_enabling_it_is_informational` | Turning ufw off is a warning; turning it on is informational. |
+| `test_a_firewall_file_disappearing_is_a_warning_and_one_appearing_is_informational` | A firewall file vanishing is a warning; a new one appearing is informational. |
+| `test_all_firewall_files_vanishing_is_noticed` | If every firewall file disappears, that is noticed. |
+| `test_missing_or_malformed_firewall_reports_are_ignored` | Missing or malformed reports are ignored. |
+| `test_the_firewall_incident_clears_with_the_event_window` | The firewall incident clears after the event window. |
+
+**Internet incidents (backend)**
+
+| Test | What it checks |
+|---|---|
+| `test_sustained_internet_loss_warns_and_recovery_clears` | The internet being down for several check-ins in a row raises a warning that clears on recovery. |
+| `test_sustained_dns_failure_is_its_own_warning` | A sustained DNS failure is reported separately. |
+| `test_degraded_unchecked_and_malformed_internet_status_never_alerts` | Partly reachable, unchecked and malformed statuses never raise an incident. |
+| `test_internet_latency_must_be_a_sane_number` | Absurd latency values are dropped. |
+
+**Dashboard data and limits (backend)**
+
+| Test | What it checks |
+|---|---|
+| `test_the_overview_shows_listeners_firewall_and_network_events` | The dashboard receives the listeners, firewall fingerprints, events and internet status. |
+| `test_network_events_have_their_own_list_and_do_not_crowd_the_other_rows` | Network events appear in the Network row and cannot push reboots or container changes out of theirs. |
+| `test_the_network_lists_are_bounded` | The dashboard's listener list is capped at 200 and the event list at 15. |
+| `test_network_events_follow_the_normal_retention` | Old network events are deleted with the other old data. |
+| `test_crafted_event_keys_cannot_raise_incidents_for_closed_or_loopback_ports` | Malformed or misleading stored event keys cannot raise an incident for a port that isn't open or isn't exposed. |
+
### test_pending_collectors.py
Adding servers: approval, join tokens and strict mode. These protect your install
diff --git a/collector-compose.yml b/collector-compose.yml
index ec2837e..8059a56 100644
--- a/collector-compose.yml
+++ b/collector-compose.yml
@@ -17,6 +17,8 @@ services:
HOMELAB_API_URL: ${HOMELAB_API_URL:?Set HOMELAB_API_URL to your backend address}
HOMELAB_ENROLL_KEY: ${HOMELAB_ENROLL_KEY:-}
HOMELAB_SERVER_NAME: ${HOMELAB_SERVER_NAME:-}
+ # Optional internet check, off when empty: comma-separated host:port targets this collector tries to reach.
+ HOMELAB_CONNECTIVITY_TARGETS: ${HOMELAB_CONNECTIVITY_TARGETS:-}
# Docker data comes through the read-only proxy; the collector has no Docker socket.
HOMELAB_DOCKER_HOST: /run/docker-proxy/docker.sock
volumes:
diff --git a/compose.yml b/compose.yml
index 664c138..517f4c8 100644
--- a/compose.yml
+++ b/compose.yml
@@ -81,6 +81,8 @@ services:
# on the dashboard. An optional enrollment key skips that approval.
HOMELAB_ENROLL_KEY: ${HOMELAB_ENROLL_KEY:-}
HOMELAB_SERVER_NAME: ${HOMELAB_SERVER_NAME:-}
+ # Optional internet check, off when empty: comma-separated host:port targets this collector tries to reach.
+ HOMELAB_CONNECTIVITY_TARGETS: ${HOMELAB_CONNECTIVITY_TARGETS:-}
# Docker data comes through the read-only proxy; the collector has no Docker socket.
HOMELAB_DOCKER_HOST: /run/docker-proxy/docker.sock
volumes:
diff --git a/docker-compose-example.yml b/docker-compose-example.yml
index 612b67d..34c4453 100644
--- a/docker-compose-example.yml
+++ b/docker-compose-example.yml
@@ -97,6 +97,8 @@ services:
# on the dashboard. An optional enrollment key skips that approval.
HOMELAB_ENROLL_KEY: ${HOMELAB_ENROLL_KEY:-}
HOMELAB_SERVER_NAME: ${HOMELAB_SERVER_NAME:-}
+ # Optional internet check, off when empty: comma-separated host:port targets this collector tries to reach.
+ HOMELAB_CONNECTIVITY_TARGETS: ${HOMELAB_CONNECTIVITY_TARGETS:-}
# Docker data comes through the read-only proxy; the collector has no Docker socket.
HOMELAB_DOCKER_HOST: /run/docker-proxy/docker.sock
HOMELAB_CHECK_INTERVAL_SECONDS: ${HOMELAB_CHECK_INTERVAL_SECONDS:-60}
diff --git a/docker-compose.server.yml b/docker-compose.server.yml
index 927181c..6d69129 100644
--- a/docker-compose.server.yml
+++ b/docker-compose.server.yml
@@ -94,6 +94,8 @@ services:
# on the dashboard. An optional enrollment key skips that approval.
HOMELAB_ENROLL_KEY: ${HOMELAB_ENROLL_KEY:-}
HOMELAB_SERVER_NAME: ${HOMELAB_SERVER_NAME:-}
+ # Optional internet check, off when empty: comma-separated host:port targets this collector tries to reach.
+ HOMELAB_CONNECTIVITY_TARGETS: ${HOMELAB_CONNECTIVITY_TARGETS:-}
# Docker data comes through the read-only proxy; the collector has no Docker socket.
HOMELAB_DOCKER_HOST: /run/docker-proxy/docker.sock
HOMELAB_CHECK_INTERVAL_SECONDS: ${HOMELAB_CHECK_INTERVAL_SECONDS:-60}
diff --git a/example.env b/example.env
index 10ed39f..c7327a3 100644
--- a/example.env
+++ b/example.env
@@ -105,6 +105,11 @@ HOMELAB_MACHINE_ID=
FRONTEND_BIND=127.0.0.1
FRONTEND_PORT=5173
+# Optional internet-reachability check run by the collector, off when empty. Comma-separated
+# host:port targets (hostnames or IPv4, at most 5); it only opens a TCP connection and looks the name
+# up, sending nothing. Set per collector, never from the dashboard. Example: 1.1.1.1:443,9.9.9.9:443
+HOMELAB_CONNECTIVITY_TARGETS=
+
# --- Connecting remote servers over a VPN (docker-compose.server.yml) ---
# Collectors never use the public address. They report to the collector gate, which you
# publish on your VPN address only (for OpenVPN, the server's tun address, e.g. 10.8.0.1).
diff --git a/src/agent/collector.py b/src/agent/collector.py
index 60b98cc..3a4a596 100644
--- a/src/agent/collector.py
+++ b/src/agent/collector.py
@@ -14,12 +14,14 @@ from __future__ import annotations
import ctypes
import ctypes.util
+import hashlib
import http.client
import json
import os
import platform
import re
import socket
+import threading
import time
import urllib.error
import urllib.request
@@ -59,21 +61,268 @@ def _memory() -> dict[str, float]:
}
-def _network_totals() -> tuple[int, int]:
+def _host_net_dirs() -> list[Path]:
+ """Where the host's network tables are. PID 1's view is the host's; a container's own /proc/net is not.
+
+ Only a collector running directly on the host may fall back to /proc/net. Inside a container that
+ fallback would silently report the container's own interfaces and sockets as the host's.
+ """
+ return [HOST_PROC / "1/net"] + ([HOST_PROC / "net"] if HOST_PROC == Path("/proc") else [])
+
+
+def _read_net_table(name: str) -> list[str] | None:
+ """The lines of a host network table (e.g. ``tcp``, ``dev``), or None if it can't be read."""
+ for directory in _host_net_dirs():
+ try:
+ with open(directory / name, "rb") as handle:
+ data = handle.read(MAX_NET_TABLE_BYTES + 1)
+ except OSError:
+ continue
+ if len(data) <= MAX_NET_TABLE_BYTES:
+ return data.decode("utf-8", errors="replace").splitlines()
+ return None
+
+
+MAX_NET_TABLE_BYTES = 8 * 1024 * 1024
+# Name prefixes of interfaces that are never physical, used only when sysfs can't say.
+_VIRTUAL_INTERFACES = ("lo", "veth", "docker", "br-", "virbr", "tun", "tap", "wg", "dummy", "ifb", "vboxnet", "vmnet")
+
+
+def _physical_interfaces() -> set[str] | None:
+ """Interfaces backed by real hardware (they have a ``device`` entry in sysfs), or None if sysfs isn't visible."""
+ base = HOST_ROOT / "sys/class/net"
+ try:
+ return {entry.name for entry in base.iterdir() if (entry / "device").exists()}
+ except OSError:
+ return None
+
+
+def _network_totals() -> tuple[int, int] | None:
+ """Bytes sent and received over the host's physical interfaces, or None if the host's table is unreadable.
+
+ Virtual interfaces (Docker bridges, veth pairs, loopback) are left out: their traffic is already
+ counted on the physical interface and would be counted twice.
+ """
+ lines = _read_net_table("dev")
+ if lines is None:
+ return None
+ physical = _physical_interfaces()
sent = received = 0
- for line in (HOST_PROC / "net/dev").read_text().splitlines()[2:]:
+ for line in lines[2:]:
if ":" not in line:
continue
interface, raw = line.split(":", 1)
- if interface.strip() == "lo":
+ interface = interface.strip()
+ if (interface not in physical) if physical else interface.startswith(_VIRTUAL_INTERFACES):
+ continue
+ try:
+ fields = [int(value) for value in raw.split()]
+ except ValueError:
continue
- fields = [int(value) for value in raw.split()]
if len(fields) >= 9:
received += fields[0]
sent += fields[8]
return sent, received
+EPHEMERAL_PORT_START = 32768 # Linux's default ephemeral range starts here
+MAX_LISTENERS = 512
+MAX_NET_TABLE_LINES = 500_000
+_ZERO_V6 = "0" * 32
+
+
+def _listener_scope(address: str) -> str | None:
+ """loopback, any (all interfaces) or specific, from a hex address in /proc/net/tcp(6) byte order."""
+ if len(address) == 8: # IPv4: stored little-endian, so the first octet is the last byte
+ return "any" if address == "00000000" else "loopback" if address.endswith("7F") else "specific"
+ if len(address) == 32:
+ if address == _ZERO_V6:
+ return "any"
+ if address == "00000000000000000000000001000000":
+ return "loopback"
+ if address.startswith("0000000000000000FFFF0000"): # IPv4-mapped IPv6
+ return _listener_scope(address[24:])
+ return "specific"
+ return None
+
+
+def listener_tracked(proto: str, port: int, scope: str) -> bool:
+ """Ephemeral ports are skipped: loopback ones, and every UDP one, are programs talking out, not services."""
+ return not (port >= EPHEMERAL_PORT_START and (scope == "loopback" or proto == "udp"))
+
+
+def _scan_listeners(table: str, proto: str) -> set[tuple[str, int, str]] | None:
+ """Listeners in one host network table, streamed so a busy server's huge connection table costs no memory.
+
+ None if the table can't be read or is longer than MAX_NET_TABLE_LINES: a truncated read could miss
+ listeners and make them look closed, so it is treated as unknown instead.
+ """
+ for directory in _host_net_dirs():
+ try:
+ handle = open(directory / table, "r", encoding="utf-8", errors="replace")
+ except OSError:
+ continue
+ found: set[tuple[str, int, str]] = set()
+ with handle:
+ try:
+ for number, line in enumerate(handle):
+ if number > MAX_NET_TABLE_LINES:
+ return None
+ if number:
+ found |= _parse_listener_line(line, proto)
+ except OSError:
+ continue
+ return found
+ return None
+
+
+def _parse_listener_line(line: str, proto: str) -> set[tuple[str, int, str]]:
+ fields = line.split()
+ if len(fields) < 4:
+ return set()
+ address, _, port_hex = fields[1].partition(":")
+ # TCP LISTEN is state 0A; a bound, unconnected UDP socket is state 07 with no remote address.
+ listening = fields[3] == "0A" if proto == "tcp" else fields[3] == "07" and fields[2].startswith(("00000000:0000", _ZERO_V6 + ":0000"))
+ if not listening:
+ return set()
+ try:
+ port = int(port_hex, 16)
+ except ValueError:
+ return set()
+ scope = _listener_scope(address)
+ return {(proto, port, scope)} if scope and 1 <= port <= 65535 and listener_tracked(proto, port, scope) else set()
+
+
+def collect_listeners() -> list[dict[str, Any]] | None:
+ """What is listening on the host (protocol, port, scope), read passively from /proc. None if unreadable.
+
+ No process names are collected: matching sockets to other users' processes needs privileges the
+ collector deliberately doesn't have. If any table is unreadable the whole answer is unknown, so a
+ partial picture can never be mistaken for ports having closed.
+ """
+ found: set[tuple[str, int, str]] = set()
+ for table, proto in (("tcp", "tcp"), ("tcp6", "tcp"), ("udp", "udp"), ("udp6", "udp")):
+ listeners = _scan_listeners(table, proto)
+ if listeners is None:
+ return None
+ found |= listeners
+ return [{"proto": proto, "port": port, "scope": scope} for proto, port, scope in sorted(found)[:MAX_LISTENERS]]
+
+
+_HOSTNAME = re.compile(r"(?=.{1,253}$)([A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)(\.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*")
+_IPV4 = re.compile(r"(\d{1,3})(\.\d{1,3}){3}")
+MAX_CONNECTIVITY_TARGETS = 5
+CONNECT_TIMEOUT_SECONDS = 3.0
+CONNECTIVITY_DEADLINE_SECONDS = 6.0
+
+
+def _connectivity_targets() -> list[tuple[str, int]]:
+ """``host:port`` entries from HOMELAB_CONNECTIVITY_TARGETS (hostnames or IPv4 only). Empty means the check is off."""
+ targets: list[tuple[str, int]] = []
+ for entry in os.getenv("HOMELAB_CONNECTIVITY_TARGETS", "").split(","):
+ host, _, port = entry.strip().rpartition(":")
+ # A name whose last label is all digits isn't a valid hostname; it is a mistyped IP address.
+ valid_host = _IPV4.fullmatch(host) and all(int(part) <= 255 for part in host.split(".")) or (_HOSTNAME.fullmatch(host) and not host.rsplit(".", 1)[-1].isdigit())
+ if valid_host and port.isdigit() and 1 <= int(port) <= 65535 and (host, int(port)) not in targets:
+ targets.append((host, int(port)))
+ elif entry.strip():
+ print(f"Ignoring invalid connectivity target {entry.strip()[:60]!r}", flush=True)
+ return targets[:MAX_CONNECTIVITY_TARGETS]
+
+
+def _probe(host: str, port: int, results: dict[tuple[str, int], dict[str, Any]]) -> None:
+ """Resolve the name (if it is one) and open a TCP connection. Nothing is sent over it."""
+ outcome: dict[str, Any] = {"dns": None if _IPV4.fullmatch(host) else False, "tcp": False, "ms": None}
+ results[(host, port)] = outcome # visible even if this thread outlives the deadline
+ started = time.monotonic()
+ try:
+ address = host if outcome["dns"] is None else socket.getaddrinfo(host, port, type=socket.SOCK_STREAM)[0][4][0]
+ if outcome["dns"] is not None:
+ outcome["dns"] = True
+ socket.create_connection((address, port), CONNECT_TIMEOUT_SECONDS).close()
+ outcome["tcp"], outcome["ms"] = True, int((time.monotonic() - started) * 1000)
+ except (OSError, IndexError):
+ pass
+
+
+def summarise_connectivity(results: list[dict[str, Any]]) -> str:
+ """ok (all reachable), degraded (some), dns_failed (names don't resolve, nothing else wrong) or down."""
+ if all(result["tcp"] for result in results):
+ return "ok"
+ if any(result["tcp"] for result in results):
+ return "degraded"
+ return "dns_failed" if all(result["dns"] is False for result in results) else "down"
+
+
+def collect_connectivity() -> dict[str, Any]:
+ """Can this host reach the internet? Off unless HOMELAB_CONNECTIVITY_TARGETS is set on this collector.
+
+ The targets come from the collector's own environment, never from the dashboard, so a compromised
+ dashboard can't point these probes anywhere.
+ """
+ targets = _connectivity_targets()
+ if not targets:
+ return {"internet_status": None, "internet_latency_ms": None}
+ results: dict[tuple[str, int], dict[str, Any]] = {}
+ threads = [threading.Thread(target=_probe, args=(host, port, results), daemon=True) for host, port in targets]
+ deadline = time.monotonic() + CONNECTIVITY_DEADLINE_SECONDS
+ for thread in threads:
+ thread.start()
+ for thread in threads:
+ thread.join(max(0.0, deadline - time.monotonic()))
+ outcomes = [dict(results.get(target) or {"dns": False, "tcp": False, "ms": None}) for target in targets]
+ latencies = sorted(outcome["ms"] for outcome in outcomes if outcome["ms"] is not None)
+ return {"internet_status": summarise_connectivity(outcomes), "internet_latency_ms": latencies[len(latencies) // 2] if latencies else None}
+
+
+# Firewall configuration files that are looked at, by a fixed name. Only a hash and a rule count leave the host.
+FIREWALL_FILES = (("ufw", "etc/ufw/user.rules"), ("ufw6", "etc/ufw/user6.rules"), ("ufw-conf", "etc/ufw/ufw.conf"),
+ ("nftables", "etc/nftables.conf"), ("iptables", "etc/iptables/rules.v4"), ("ip6tables", "etc/iptables/rules.v6"))
+MAX_FIREWALL_FILE_BYTES = 1024 * 1024
+
+
+def _read_regular_file(path: Path, limit: int) -> bytes | None:
+ """File contents up to ``limit`` bytes; None for symlinks, non-files, unreadable or larger files."""
+ try:
+ descriptor = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)
+ except OSError:
+ return None
+ try:
+ data = os.read(descriptor, limit + 1)
+ except OSError:
+ return None
+ finally:
+ os.close(descriptor)
+ return data if len(data) <= limit else None
+
+
+def collect_firewall() -> dict[str, Any] | None:
+ """A fingerprint of the host's firewall configuration files; never their contents (which reveal the network layout).
+
+ This sees configuration, not the live ruleset: reading that needs CAP_NET_ADMIN, which could also change
+ the firewall, so the collector doesn't have it. Returns None if no known firewall file exists.
+ """
+ files: list[dict[str, Any]] = []
+ ufw_enabled: bool | None = None
+ for name, relative in FIREWALL_FILES:
+ data = _read_regular_file(HOST_ROOT / relative, MAX_FIREWALL_FILE_BYTES)
+ if data is None:
+ continue
+ text = data.decode("utf-8", errors="replace")
+ lines = [line.strip() for line in text.splitlines()]
+ if name == "ufw-conf":
+ for line in lines:
+ if line.upper().startswith("ENABLED="):
+ ufw_enabled = line.split("=", 1)[1].strip().lower() == "yes"
+ rules = 0
+ elif name in ("nftables",):
+ rules = sum(1 for line in lines if line and not line.startswith("#"))
+ else:
+ rules = sum(1 for line in lines if line.startswith("-A "))
+ files.append({"name": name, "sha": hashlib.sha256(data).hexdigest()[:16], "rules": rules})
+ return {"files": files, "ufw_enabled": ufw_enabled} if files else None
+
+
# Filesystems worth reporting: anything backed by a block device, plus these pooled/network ones.
NON_DEVICE_FS_TYPES = {"zfs", "nfs", "nfs4", "cifs", "smb3", "fuse.mergerfs", "fuse.sshfs"}
SKIPPED_FS_TYPES = {"squashfs", "overlay", "tmpfs", "devtmpfs"}
@@ -257,7 +506,7 @@ def collect_host() -> tuple[dict[str, Any], dict[str, Any]]:
loads = os.getloadavg()
except (AttributeError, OSError):
loads = (0.0, 0.0, 0.0)
- sent, received = _network_totals()
+ network = _network_totals()
uptime = float((HOST_PROC / "uptime").read_text().split()[0])
host = {
"cpu_utilization_pct": cpu_pct,
@@ -265,10 +514,13 @@ def collect_host() -> tuple[dict[str, Any], dict[str, Any]]:
**memory,
"disk_usage_pct": round(disk_pct, 2),
"disk_inodes_pct": round(inode_pct, 2) if inode_pct is not None else None,
- "net_bytes_sent_mb": round(sent / MiB, 3),
- "net_bytes_recv_mb": round(received / MiB, 3),
+ "net_bytes_sent_mb": round(network[0] / MiB, 3) if network else None,
+ "net_bytes_recv_mb": round(network[1] / MiB, 3) if network else None,
"system_uptime_seconds": round(uptime, 1),
"mounts": collect_mounts(),
+ "listeners": collect_listeners(),
+ "firewall": collect_firewall(),
+ **collect_connectivity(),
**collect_system(),
}
server = {
diff --git a/src/backend/main.py b/src/backend/main.py
index bd295ba..b6686c2 100644
--- a/src/backend/main.py
+++ b/src/backend/main.py
@@ -23,7 +23,7 @@ from sqlalchemy import case, func, inspect, text
from .alerts import CONTAINER_RULE_PREFIX, CRITICAL, SERVER_OFFLINE_RULE, SEVERITIES, active_rule_keys, raise_alert, resolve_alerts, sync_alerts
from .auth import authenticate_user, get_recent_logs, get_user_from_session, logout_user, record_audit_log, register_user
from .db import SessionLocal, check_database, get_db
-from .models import AppSetting, AuditLog, Base, ChatMessage, ContainerMetric, Conversation, EnrollmentKey, HostMetric, IncidentAlert, JoinToken, MountMetric, PendingCollector, Server, SystemEvent, User
+from .models import AppSetting, AuditLog, Base, ChatMessage, ContainerMetric, Conversation, EnrollmentKey, FirewallState, HostMetric, IncidentAlert, JoinToken, ListenerState, MountMetric, PendingCollector, Server, SystemEvent, User
from .db import engine
from .config import (
@@ -44,7 +44,7 @@ from .config import (
SESSION_COOKIE_SECURE,
SESSION_TTL_SECONDS,
)
-from .rules import DEFAULT_THRESHOLDS, HOST_RULE_PREFIX, container_rules, host_rules, validate_thresholds, detect_system_events, system_rules, SYSTEM_RULE_PREFIX, validate_mount_thresholds, validate_helper_events, REBOOT_DETAILS, REBOOT_KEY_PREFIX, detect_container_events, memory_trend_rules, CONTAINER_EVENT_KINDS, MAX_CONTAINER_EVENTS_PER_CHECKIN, MAX_CONTAINER_EVENTS_PER_HOUR, TREND_RULE_PREFIX
+from .rules import DEFAULT_THRESHOLDS, HOST_RULE_PREFIX, container_rules, host_rules, validate_thresholds, detect_system_events, system_rules, SYSTEM_RULE_PREFIX, validate_mount_thresholds, validate_helper_events, REBOOT_DETAILS, REBOOT_KEY_PREFIX, detect_container_events, memory_trend_rules, CONTAINER_EVENT_KINDS, MAX_CONTAINER_EVENTS_PER_CHECKIN, MAX_CONTAINER_EVENTS_PER_HOUR, TREND_RULE_PREFIX, NETWORK_EVENT_KINDS, NETWORK_RULE_PREFIX, MAX_NETWORK_EVENTS_PER_CHECKIN, MAX_NETWORK_EVENTS_PER_HOUR, INTERNET_STATUSES, LISTENER_SCOPES, FIREWALL_LABELS, detect_listener_changes, detect_firewall_changes, network_rules, validate_listeners, validate_firewall
from .rate_limit import enforce_ip_limit, enforce_login_limit, enforce_register_limit, reset_limits
from ..agent.service import delete_agent_conversation, send_agent_message
@@ -196,6 +196,7 @@ def startup_event():
("boot_id", "VARCHAR(64)"), ("oom_kill_total", "INTEGER"), ("kernel_tainted", "INTEGER"),
("ntp_synced", "BOOLEAN"), ("reboot_required", "BOOLEAN"), ("last_shutdown", "VARCHAR(16)"),
("docker_status", "VARCHAR(16)"), ("docker_reason", "VARCHAR(16)"), ("docker_latency_ms", "INTEGER"),
+ ("internet_status", "VARCHAR(16)"), ("internet_latency_ms", "INTEGER"),
):
connection.execute(text(f"ALTER TABLE host_metrics ADD COLUMN IF NOT EXISTS {column} {column_type}"))
for column, column_type in (("exit_code", "INTEGER"), ("oom_killed", "BOOLEAN"), ("finished_at", "TIMESTAMP WITH TIME ZONE"), ("image_id", "VARCHAR(80)")):
@@ -550,7 +551,7 @@ def recent_system_events(db, since: datetime) -> dict[int, list[dict]]:
OOM kills out of the list. Every other kind stays one row per occurrence.
"""
result: dict[int, list[dict]] = {}
- for event in db.query(SystemEvent).filter(SystemEvent.time >= since, SystemEvent.kind != "kernel_error", SystemEvent.kind.notin_(CONTAINER_EVENT_KINDS)).order_by(SystemEvent.time.desc()):
+ for event in db.query(SystemEvent).filter(SystemEvent.time >= since, SystemEvent.kind != "kernel_error", SystemEvent.kind.notin_(CONTAINER_EVENT_KINDS + NETWORK_EVENT_KINDS)).order_by(SystemEvent.time.desc()):
rows = result.setdefault(event.server_id, [])
if len(rows) < SYSTEM_EVENTS_SHOWN:
rows.append({"time": event.time.isoformat(), "first_time": event.time.isoformat(), "kind": event.kind, "detail": event.detail, "count": 1})
@@ -586,6 +587,20 @@ def recent_container_events(db, since: datetime) -> dict[int, list[dict]]:
return result
+NETWORK_EVENTS_SHOWN = 15
+LISTENERS_SHOWN = 200
+
+
+def recent_network_events(db, since: datetime) -> dict[int, list[dict]]:
+ """Each server's recent network changes (ports opened or closed, firewall changes), newest first."""
+ result: dict[int, list[dict]] = {}
+ for event in db.query(SystemEvent).filter(SystemEvent.time >= since, SystemEvent.kind.in_(NETWORK_EVENT_KINDS)).order_by(SystemEvent.time.desc()):
+ rows = result.setdefault(event.server_id, [])
+ if len(rows) < NETWORK_EVENTS_SHOWN:
+ rows.append({"time": event.time.isoformat(), "kind": event.kind, "detail": event.detail})
+ return result
+
+
@app.get("/monitoring/overview")
def monitoring_overview(session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None, db=Depends(get_db)):
# Servers belong to the install: everyone signed in can view them, only admins manage them.
@@ -596,6 +611,14 @@ def monitoring_overview(session_id: Annotated[str | None, Cookie(alias=SESSION_C
since = datetime.now(timezone.utc) - timedelta(days=7)
events = recent_system_events(db, since)
container_events = recent_container_events(db, since)
+ network_events = recent_network_events(db, since)
+ listeners: dict[int, list[dict]] = {}
+ for row in db.query(ListenerState).order_by(ListenerState.port, ListenerState.proto):
+ if len(listeners.setdefault(row.server_id, [])) < LISTENERS_SHOWN:
+ listeners[row.server_id].append({"proto": row.proto, "port": row.port, "scope": row.scope, "first_seen": row.first_seen.isoformat()})
+ firewalls: dict[int, list[dict]] = {}
+ for row in db.query(FirewallState).order_by(FirewallState.name):
+ firewalls.setdefault(row.server_id, []).append({"name": row.name, "label": FIREWALL_LABELS.get(row.name, row.name), "rules": row.rules, "enabled": row.enabled, "updated_at": row.updated_at.isoformat()})
result = []
for server in servers:
metric = db.query(HostMetric).filter(HostMetric.server_id == server.id).order_by(HostMetric.time.desc()).first()
@@ -607,7 +630,8 @@ def monitoring_overview(session_id: Annotated[str | None, Cookie(alias=SESSION_C
"check_interval_seconds": server.check_interval_seconds, "is_dashboard_host": server.is_dashboard_host,
"active_alert_count": alert_counts.get(server.id, 0),
"last_seen_at": server.last_seen_at.isoformat() if server.last_seen_at else None,
- "host": ({key: getattr(metric, key) for key in ("time", "cpu_utilization_pct", "load_1m", "load_5m", "load_15m", "ram_used_gb", "ram_available_gb", "ram_pct", "swap_pct", "disk_usage_pct", "disk_inodes_pct", "net_bytes_sent_mb", "net_bytes_recv_mb", "system_uptime_seconds", "oom_kill_total", "kernel_tainted", "ntp_synced", "reboot_required", "last_shutdown", "docker_status", "docker_reason", "docker_latency_ms")} if metric else None),
+ "host": ({key: getattr(metric, key) for key in ("time", "cpu_utilization_pct", "load_1m", "load_5m", "load_15m", "ram_used_gb", "ram_available_gb", "ram_pct", "swap_pct", "disk_usage_pct", "disk_inodes_pct", "net_bytes_sent_mb", "net_bytes_recv_mb", "system_uptime_seconds", "oom_kill_total", "kernel_tainted", "ntp_synced", "reboot_required", "last_shutdown", "docker_status", "docker_reason", "docker_latency_ms", "internet_status", "internet_latency_ms")} if metric else None),
+ "network": {"listeners": listeners.get(server.id, []), "firewall": firewalls.get(server.id, []), "events": network_events.get(server.id, [])},
"container_events": container_events.get(server.id, []),
"system_events": events.get(server.id, []),
"mounts": [{key: getattr(m, key) for key in ("mount", "fs_type", "total_gb", "used_gb", "used_pct", "inodes_pct")} for m in mounts],
@@ -1002,6 +1026,8 @@ def delete_monitored_server(server_id: int, session_id: Annotated[str | None, Co
db.query(ContainerMetric).filter(ContainerMetric.server_id == server.id).delete(synchronize_session=False)
db.query(MountMetric).filter(MountMetric.server_id == server.id).delete(synchronize_session=False)
db.query(SystemEvent).filter(SystemEvent.server_id == server.id).delete(synchronize_session=False)
+ db.query(ListenerState).filter(ListenerState.server_id == server.id).delete(synchronize_session=False)
+ db.query(FirewallState).filter(FirewallState.server_id == server.id).delete(synchronize_session=False)
db.query(IncidentAlert).filter(IncidentAlert.server_id == server.id).delete(synchronize_session=False)
db.query(PendingCollector).filter(PendingCollector.approved_server_id == server.id).delete(synchronize_session=False)
db.delete(server)
@@ -1086,18 +1112,64 @@ def _clean_container(raw, now: datetime) -> dict | None:
return clean
-def record_container_events(db, server_id: int, events: list[tuple[str, str, str]], now: datetime) -> None:
- """Store container changes, with hard caps so churn (CI containers coming and going) can't flood the table."""
+def record_capped_events(db, server_id: int, events: list[tuple[str, str, str]], kinds: tuple[str, ...], notice_kind: str, subject: str, now: datetime,
+ per_check_in: int, per_hour: int) -> None:
+ """Store (kind, detail, key) events with hard caps, so churn can't flood the table.
+
+ At most ``per_check_in`` are stored per call and ``per_hour`` per server and category; anything beyond
+ that is summarised by a single notice per hour.
+ """
if not events:
return
since = now - timedelta(hours=1)
- recent = db.query(func.count(SystemEvent.id)).filter(SystemEvent.server_id == server_id, SystemEvent.kind.in_(CONTAINER_EVENT_KINDS), SystemEvent.time >= since).scalar() or 0
- allowed = events[:max(0, min(MAX_CONTAINER_EVENTS_PER_CHECKIN, MAX_CONTAINER_EVENTS_PER_HOUR - recent))]
- for kind, detail, name in allowed:
- db.add(SystemEvent(server_id=server_id, time=now, kind=kind, detail=detail[:512], event_key=name[:128]))
+ recent = db.query(func.count(SystemEvent.id)).filter(SystemEvent.server_id == server_id, SystemEvent.kind.in_(kinds), SystemEvent.time >= since).scalar() or 0
+ allowed = events[:max(0, min(per_check_in, per_hour - recent))]
+ for kind, detail, key in allowed:
+ db.add(SystemEvent(server_id=server_id, time=now, kind=kind, detail=detail[:512], event_key=key[:128]))
dropped = len(events) - len(allowed)
- if dropped and not db.query(SystemEvent.id).filter(SystemEvent.server_id == server_id, SystemEvent.kind == "container_notice", SystemEvent.time >= since).first():
- db.add(SystemEvent(server_id=server_id, time=now, kind="container_notice", detail=f"{dropped} more container changes were not recorded (too many at once)"))
+ if dropped and not db.query(SystemEvent.id).filter(SystemEvent.server_id == server_id, SystemEvent.kind == notice_kind, SystemEvent.time >= since).first():
+ db.add(SystemEvent(server_id=server_id, time=now, kind=notice_kind, detail=f"{dropped} more {subject} were not recorded (too many at once)"))
+
+
+def record_container_events(db, server_id: int, events: list[tuple[str, str, str]], now: datetime) -> None:
+ record_capped_events(db, server_id, events, CONTAINER_EVENT_KINDS, "container_notice", "container changes", now, MAX_CONTAINER_EVENTS_PER_CHECKIN, MAX_CONTAINER_EVENTS_PER_HOUR)
+
+
+def sync_listeners(db, server_id: int, listeners: list[tuple[str, int, str]] | None, now: datetime) -> list[tuple[str, str, str]]:
+ """Update the known listeners from a validated report and return what changed.
+
+ The first report is a silent baseline. An empty report is treated as unknown rather than as "everything
+ closed", since a host always listens on something and an empty list means the table couldn't be read.
+ """
+ if not listeners:
+ return []
+ current = set(listeners)
+ known = {(row.proto, row.port, row.scope): row for row in db.query(ListenerState).filter(ListenerState.server_id == server_id)}
+ events = detect_listener_changes(known, current)
+ for key in sorted(current - known.keys()):
+ db.add(ListenerState(server_id=server_id, proto=key[0], port=key[1], scope=key[2], first_seen=now, last_seen=now))
+ for key in known.keys() - current:
+ db.delete(known[key])
+ for key in current & known.keys():
+ known[key].last_seen = now
+ return events
+
+
+def sync_firewall(db, server_id: int, firewall: dict, now: datetime) -> list[tuple[str, str, str]]:
+ """Update the stored firewall fingerprints from a validated report and return what changed (see detect_firewall_changes)."""
+ known = {row.name: row for row in db.query(FirewallState).filter(FirewallState.server_id == server_id)}
+ events = detect_firewall_changes(known, firewall)
+ for name, (sha, count) in firewall["files"].items():
+ enabled = firewall["ufw_enabled"] if name == "ufw-conf" else None
+ if name in known:
+ row = known[name]
+ if (row.sha, row.rules, row.enabled) != (sha, count, enabled):
+ row.sha, row.rules, row.enabled, row.updated_at = sha, count, enabled, now
+ else:
+ db.add(FirewallState(server_id=server_id, name=name, sha=sha, rules=count, enabled=enabled, updated_at=now))
+ for name in known.keys() - firewall["files"].keys():
+ db.delete(known[name])
+ return events
def _clean_system_fields(fields: dict) -> None:
@@ -1113,6 +1185,10 @@ def _clean_system_fields(fields: dict) -> None:
fields["docker_reason"] = None
if "docker_latency_ms" in fields:
fields["docker_latency_ms"] = _whole_number(fields["docker_latency_ms"], 0, 600_000)
+ if "internet_status" in fields and fields["internet_status"] not in INTERNET_STATUSES:
+ fields["internet_status"] = None
+ if "internet_latency_ms" in fields:
+ fields["internet_latency_ms"] = _whole_number(fields["internet_latency_ms"], 0, 600_000)
if "boot_id" in fields:
fields["boot_id"] = fields["boot_id"][:64] if isinstance(fields["boot_id"], str) and fields["boot_id"] else None
@@ -1159,10 +1235,18 @@ def ingest_metrics(payload: MetricsIngestRequest, authorization: Annotated[str |
record_container_events(db, server.id, detect_container_events(previous_containers, containers), now)
for container in containers:
db.add(ContainerMetric(server_id=server.id, time=now, **container))
+ # Listening ports and firewall files: compare with what was seen last time (collectors that don't send them are skipped).
+ network_events: list[tuple[str, str, str]] = []
+ if "listeners" in payload.host:
+ network_events += sync_listeners(db, server.id, validate_listeners(payload.host["listeners"]), now)
+ if "firewall" in payload.host and (firewall := validate_firewall(payload.host["firewall"])) is not None:
+ network_events += sync_firewall(db, server.id, firewall, now)
+ record_capped_events(db, server.id, network_events, NETWORK_EVENT_KINDS, "network_notice", "network changes", now, MAX_NETWORK_EVENTS_PER_CHECKIN, MAX_NETWORK_EVENTS_PER_HOUR)
db.flush() # the rules read this check-in back from the history tables
thresholds = get_alert_thresholds(db)
sync_alerts(db, server.id, HOST_RULE_PREFIX, host_rules(db, server, thresholds, active_rule_keys(db, server.id, HOST_RULE_PREFIX), get_mount_thresholds(db)))
sync_alerts(db, server.id, SYSTEM_RULE_PREFIX, system_rules(db, server, thresholds, now, active_rule_keys(db, server.id, SYSTEM_RULE_PREFIX)))
+ sync_alerts(db, server.id, NETWORK_RULE_PREFIX, network_rules(db, server, thresholds, now))
# The collector sends no containers when Docker is unreachable; keep container alerts as they are rather than resolving them all.
if containers:
sync_alerts(db, server.id, CONTAINER_RULE_PREFIX, container_rules(db, server.id, containers, thresholds, now))
diff --git a/src/backend/models.py b/src/backend/models.py
index 522b246..974da86 100644
--- a/src/backend/models.py
+++ b/src/backend/models.py
@@ -1,7 +1,7 @@
from datetime import datetime, timezone
from typing import Optional
-from sqlalchemy import Boolean, DateTime, Float, ForeignKey, Integer, String, Text
+from sqlalchemy import Boolean, DateTime, Float, ForeignKey, Integer, String, Text, UniqueConstraint
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
@@ -183,6 +183,9 @@ class HostMetric(Base):
docker_status: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)
docker_reason: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)
docker_latency_ms: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
+ # Whether the host can reach the internet (ok | degraded | dns_failed | down); None when the check is off.
+ internet_status: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)
+ internet_latency_ms: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
class SystemEvent(Base):
@@ -215,6 +218,36 @@ class MountMetric(Base):
inodes_pct: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
+class ListenerState(Base):
+ """A port the host is listening on, as last seen. One row per listener, so comparing check-ins needs no history."""
+
+ __tablename__ = "listener_states"
+ __table_args__ = (UniqueConstraint("server_id", "proto", "port", "scope"),)
+
+ id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True)
+ server_id: Mapped[int] = mapped_column(ForeignKey("servers.id", ondelete="CASCADE"), index=True, nullable=False)
+ proto: Mapped[str] = mapped_column(String(8), nullable=False) # tcp | udp
+ port: Mapped[int] = mapped_column(Integer, nullable=False)
+ scope: Mapped[str] = mapped_column(String(16), nullable=False) # loopback | any | specific
+ first_seen: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc), nullable=False)
+ last_seen: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc), nullable=False)
+
+
+class FirewallState(Base):
+ """Fingerprint of one firewall configuration file as last seen: a hash and a rule count, never the rules."""
+
+ __tablename__ = "firewall_states"
+ __table_args__ = (UniqueConstraint("server_id", "name"),)
+
+ id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True)
+ server_id: Mapped[int] = mapped_column(ForeignKey("servers.id", ondelete="CASCADE"), index=True, nullable=False)
+ name: Mapped[str] = mapped_column(String(16), nullable=False)
+ sha: Mapped[str] = mapped_column(String(16), nullable=False)
+ rules: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
+ enabled: Mapped[Optional[bool]] = mapped_column(Boolean, nullable=True) # only meaningful for ufw-conf
+ updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc), nullable=False)
+
+
class ContainerMetric(Base):
__tablename__ = "container_metrics"
diff --git a/src/backend/rules.py b/src/backend/rules.py
index 509da3c..f3f43b7 100644
--- a/src/backend/rules.py
+++ b/src/backend/rules.py
@@ -11,11 +11,12 @@ from datetime import datetime, timedelta, timezone
from sqlalchemy import func
from .alerts import CONTAINER_RULE_PREFIX, CRITICAL, INFO, WARNING
-from .models import ContainerMetric, HostMetric, MountMetric, SystemEvent
+from .models import ContainerMetric, FirewallState, HostMetric, ListenerState, MountMetric, SystemEvent
HOST_RULE_PREFIX = "host:"
SYSTEM_RULE_PREFIX = "system:"
TREND_RULE_PREFIX = "trend:"
+NETWORK_RULE_PREFIX = "network:"
DEFAULT_THRESHOLDS: dict[str, float | int] = {
"disk_warning_pct": 85, "disk_critical_pct": 95,
@@ -394,6 +395,122 @@ def container_rules(db, server_id: int, containers: list[dict], thresholds: dict
return firing
+NETWORK_EVENT_KINDS = ("port_opened", "port_closed", "firewall_changed", "firewall_weakened", "network_notice")
+MAX_NETWORK_EVENTS_PER_CHECKIN = 10
+MAX_NETWORK_EVENTS_PER_HOUR = 40
+MAX_LISTENERS = 512
+EPHEMERAL_PORT_START = 32768
+LISTENER_PROTOCOLS = ("tcp", "udp")
+LISTENER_SCOPES = {"loopback": "loopback only", "any": "all interfaces", "specific": "a specific address"}
+FIREWALL_LABELS = {"ufw": "ufw IPv4 rules", "ufw6": "ufw IPv6 rules", "ufw-conf": "ufw settings", "nftables": "nftables.conf",
+ "iptables": "iptables rules.v4", "ip6tables": "ip6tables rules.v6"}
+_SHA16 = re.compile(r"[0-9a-f]{16}")
+INTERNET_STATUSES = ("ok", "degraded", "dns_failed", "down")
+
+
+def listener_tracked(proto: str, port: int, scope: str) -> bool:
+ """Ephemeral ports are skipped: loopback ones and all UDP ones are programs talking out, not services."""
+ return not (port >= EPHEMERAL_PORT_START and (scope == "loopback" or proto == "udp"))
+
+
+def validate_listeners(raw) -> list[tuple[str, int, str]] | None:
+ """The tracked, well-formed listeners a collector reported (deduplicated, capped), or None if it isn't a list."""
+ if not isinstance(raw, list):
+ return None
+ found: set[tuple[str, int, str]] = set()
+ for item in raw[:MAX_LISTENERS + 100]:
+ if not isinstance(item, dict):
+ continue
+ proto, port, scope = item.get("proto"), item.get("port"), item.get("scope")
+ if proto in LISTENER_PROTOCOLS and scope in LISTENER_SCOPES and isinstance(port, int) and not isinstance(port, bool) and 1 <= port <= 65535 and listener_tracked(proto, port, scope):
+ found.add((proto, port, scope))
+ return sorted(found)[:MAX_LISTENERS]
+
+
+def validate_firewall(raw) -> dict | None:
+ """{"files": {name: (sha, rules)}, "ufw_enabled": bool | None} from a collector's report, or None if unusable.
+
+ A report of None means the collector found no firewall files at all, which is a real (empty) state.
+ """
+ if raw is None:
+ return {"files": {}, "ufw_enabled": None}
+ if not isinstance(raw, dict) or not isinstance(raw.get("files"), list):
+ return None
+ files: dict[str, tuple[str, int]] = {}
+ for item in raw["files"][:len(FIREWALL_LABELS) * 2]:
+ if not isinstance(item, dict):
+ continue
+ name, sha, count = item.get("name"), item.get("sha"), item.get("rules")
+ if name in FIREWALL_LABELS and name not in files and isinstance(sha, str) and _SHA16.fullmatch(sha) and isinstance(count, int) and not isinstance(count, bool) and 0 <= count <= 1_000_000:
+ files[name] = (sha, count)
+ enabled = raw.get("ufw_enabled")
+ return {"files": files, "ufw_enabled": enabled if isinstance(enabled, bool) else None}
+
+
+def _listener_text(proto: str, port: int, scope: str) -> str:
+ return f"{proto}/{port} ({LISTENER_SCOPES[scope]})"
+
+
+def detect_listener_changes(known: dict[tuple[str, int, str], object], current: set[tuple[str, int, str]]) -> list[tuple[str, str, str]]:
+ """(kind, detail, key) for ports that opened or closed. Nothing is reported without a baseline or a current list."""
+ if not known or not current:
+ return []
+ events = [("port_opened", f"New listener: {_listener_text(*key)}", "/".join(map(str, key))) for key in sorted(current - known.keys())]
+ events += [("port_closed", f"Listener closed: {_listener_text(*key)}", "/".join(map(str, key))) for key in sorted(known.keys() - current)]
+ return events
+
+
+def detect_firewall_changes(known: dict[str, FirewallState], firewall: dict) -> list[tuple[str, str, str]]:
+ """(kind, detail, name) for changes since the last report; a report that lowers protection is "weakened"."""
+ if not known:
+ return [] # first report for this server is only a baseline
+ events: list[tuple[str, str, str]] = []
+ for name, (sha, count) in sorted(firewall["files"].items()):
+ label, row = FIREWALL_LABELS[name], known.get(name)
+ if row is None:
+ events.append(("firewall_changed", f"{label} appeared", name))
+ elif row.sha != sha:
+ if name == "ufw-conf" and row.enabled is True and firewall["ufw_enabled"] is False:
+ events.append(("firewall_weakened", "ufw was enabled and is now disabled", name))
+ elif name == "ufw-conf" and row.enabled is False and firewall["ufw_enabled"] is True:
+ events.append(("firewall_changed", "ufw was disabled and is now enabled", name))
+ elif name == "ufw-conf":
+ events.append(("firewall_changed", f"{label} changed", name))
+ elif count < row.rules:
+ events.append(("firewall_weakened", f"{label} lost rules ({row.rules} to {count})", name))
+ else:
+ events.append(("firewall_changed", f"{label} changed ({row.rules} to {count} rules)", name))
+ events += [("firewall_weakened", f"{FIREWALL_LABELS[name]} is no longer present", name) for name in sorted(known.keys() - firewall["files"].keys())]
+ return events
+
+
+def network_rules(db, server, thresholds: dict, now: datetime) -> dict[str, tuple[str, str, str]]:
+ """Incidents for the internet check, newly exposed listeners and firewall changes."""
+ host, sustained = server.hostname, thresholds["sustained_checks"]
+ firing: dict[str, tuple[str, str, str]] = {}
+ samples = db.query(HostMetric).filter(HostMetric.server_id == server.id).order_by(HostMetric.time.desc(), HostMetric.id.desc()).limit(sustained).all()
+ if len(samples) >= sustained:
+ if all(sample.internet_status == "down" for sample in samples):
+ firing[f"{NETWORK_RULE_PREFIX}internet"] = (WARNING, f"{host} cannot reach the internet", "Every connectivity target failed for several check-ins in a row. Check the uplink, the router and the host's network settings.")
+ elif all(sample.internet_status == "dns_failed" for sample in samples):
+ firing[f"{NETWORK_RULE_PREFIX}dns"] = (WARNING, f"DNS is failing on {host}", "The connectivity targets can't be resolved by name, for several check-ins in a row. Check the DNS servers the host uses.")
+ since = now - timedelta(minutes=thresholds["event_window_minutes"])
+ events = db.query(SystemEvent).filter(SystemEvent.server_id == server.id, SystemEvent.kind.in_(NETWORK_EVENT_KINDS), SystemEvent.time >= since).order_by(SystemEvent.time.desc()).all()
+ open_ports = {(row.proto, row.port, row.scope) for row in db.query(ListenerState).filter(ListenerState.server_id == server.id)}
+ for event in events:
+ if event.kind == "port_opened" and event.event_key:
+ proto, _, rest = event.event_key.partition("/")
+ port, _, scope = rest.partition("/")
+ if scope != "loopback" and port.isdigit() and (proto, int(port), scope) in open_ports:
+ firing[f"{NETWORK_RULE_PREFIX}port:{proto}/{port}"] = (WARNING, f"New listener on {proto}/{port} on {host}", f"{event.detail}. Something started listening on a port that other machines can reach. Expected after starting a service; investigate if you didn't.")
+ for kind, severity, title in (("firewall_weakened", WARNING, f"Firewall protection was reduced on {host}"), ("firewall_changed", INFO, f"Firewall configuration changed on {host}")):
+ details = list(dict.fromkeys(event.detail for event in events if event.kind == kind))[:3]
+ if details:
+ firing[f"{NETWORK_RULE_PREFIX}firewall"] = (severity, title, "; ".join(details) + ". This reads configuration files, not the live ruleset. If you didn't make the change, check the host.")
+ break
+ return firing
+
+
MAX_TREND_CONTAINERS = 100
MAX_TREND_ROWS = 300_000
MIN_SAMPLES_PER_BUCKET = 5
diff --git a/src/frontend/src/App.jsx b/src/frontend/src/App.jsx
index cc75218..bd33e41 100644
--- a/src/frontend/src/App.jsx
+++ b/src/frontend/src/App.jsx
@@ -737,6 +737,63 @@ function SystemSection({ server, open, onToggle }) {
)
}
+const NETWORK_EVENT_LABELS = { port_opened: 'Port opened', port_closed: 'Port closed', firewall_changed: 'Firewall', firewall_weakened: 'Firewall', network_notice: 'Notice' }
+const NETWORK_EVENT_CLASSES = { port_opened: 'text-amber-300', port_closed: 'text-[#9aa0a6]', firewall_changed: 'text-sky-300', firewall_weakened: 'text-red-300', network_notice: 'text-[#9aa0a6]' }
+const LISTENER_SCOPE_LABELS = { loopback: 'loopback only', any: 'all interfaces', specific: 'one address' }
+const INTERNET_LABELS = { ok: ['reachable', 'ok'], degraded: ['partly reachable', 'warn'], dns_failed: ['DNS failing', 'warn'], down: ['down', 'warn'] }
+
+function networkChips(server) {
+ const host = server.host
+ const network = server.network || { listeners: [], firewall: [], events: [] }
+ const internet = INTERNET_LABELS[host.internet_status]
+ const exposed = network.listeners.filter((listener) => listener.scope !== 'loopback').length
+ const ufw = network.firewall.find((file) => file.name === 'ufw-conf')
+ const ruleFiles = network.firewall.filter((file) => file.name !== 'ufw-conf' && file.rules > 0)
+ const firewall = [ufw ? (ufw.enabled === true ? 'ufw enabled' : ufw.enabled === false ? 'ufw disabled' : null) : null, ...ruleFiles.map((file) => `${file.label.split(' ')[0]} ${file.rules} rules`)].filter(Boolean)
+ return [
+ ['Internet', internet ? internet[0] : 'not checked', internet ? internet[1] : 'unknown'],
+ ['Listening', network.listeners.length ? `${network.listeners.length} ports · ${exposed} exposed` : 'unknown', network.listeners.length ? 'ok' : 'unknown'],
+ ['Firewall', firewall.length ? firewall.join(' · ') : 'no config found', ufw?.enabled === false ? 'warn' : firewall.length ? 'ok' : 'unknown'],
+ ]
+}
+
+function NetworkSection({ server, open, onToggle }) {
+ const network = server.network || { listeners: [], firewall: [], events: [] }
+ const chips = networkChips(server)
+ const exposed = network.listeners.filter((listener) => listener.scope !== 'loopback')
+ const local = network.listeners.filter((listener) => listener.scope === 'loopback')
+ const listenerLine = (listener) => <li key={`${listener.proto}-${listener.port}-${listener.scope}`} className="whitespace-nowrap rounded-md bg-white/5 px-2 py-1 font-mono text-xs text-[#cfcfcf]" title={LISTENER_SCOPE_LABELS[listener.scope]}>{listener.proto}/{listener.port}</li>
+ return (
+ <div className="mt-4 rounded-xl border border-neutral-800">
+ <button type="button" onClick={onToggle} aria-expanded={open} className="flex w-full flex-wrap items-center gap-x-4 gap-y-1 rounded-xl px-3 py-2.5 text-left text-sm transition hover:bg-white/3">
+ <Chevron open={open} />
+ <span className="text-white">Network</span>
+ {chips.map(([label, value, tone]) => <span key={label} className="whitespace-nowrap text-xs text-[#7f8589]">{label} <span className={`font-medium ${CHIP_CLASSES[tone]}`}>{value}</span></span>)}
+ </button>
+ {open && (
+ <div className="space-y-4 border-t border-neutral-800 px-3 py-3">
+ {network.listeners.length > 0 && <div>
+ <div className="mb-2 text-xs uppercase tracking-[0.2em] text-[#7f8589]">Listening ports</div>
+ {exposed.length > 0 && <div className="mb-2"><div className="mb-1 text-xs text-amber-300">Reachable from other machines ({exposed.length})</div><ul className="flex flex-wrap gap-1.5">{exposed.map(listenerLine)}</ul></div>}
+ {local.length > 0 && <div><div className="mb-1 text-xs text-[#7f8589]">This machine only ({local.length})</div><ul className="flex flex-wrap gap-1.5">{local.map(listenerLine)}</ul></div>}
+ </div>}
+ <div>
+ <div className="mb-2 text-xs uppercase tracking-[0.2em] text-[#7f8589]">Recent changes · 7 days</div>
+ {network.events.length ? <ul className="space-y-1.5 text-sm">{network.events.map((event, index) => (
+ <li key={`${event.time}-${event.kind}-${index}`} className="flex flex-wrap items-baseline gap-x-3 gap-y-0.5">
+ <span className="w-24 shrink-0 text-xs text-[#7f8589]" title={new Date(event.time).toLocaleString()}>{formatAgo(event.time)}</span>
+ <span className={`w-24 shrink-0 text-xs font-medium ${NETWORK_EVENT_CLASSES[event.kind] || 'text-[#cfcfcf]'}`}>{NETWORK_EVENT_LABELS[event.kind] || event.kind}</span>
+ <span className="min-w-0 flex-1 basis-60 break-words text-[#bcbcbc]">{event.detail}</span>
+ </li>
+ ))}</ul> : <p className="text-sm text-[#9aa0a6]">No new listeners or firewall changes in the last 7 days.</p>}
+ </div>
+ <p className="text-xs text-[#7f8589]">The firewall chip reads configuration files, not the live ruleset. The internet check is off unless <code>HOMELAB_CONNECTIVITY_TARGETS</code> is set on that machine's collector.</p>
+ </div>
+ )}
+ </div>
+ )
+}
+
const HEALTH_CLASSES = { healthy: 'text-[#7f8589]', unhealthy: 'text-red-300', starting: 'text-amber-300' }
const ALERT_STYLES = {
@@ -801,6 +858,7 @@ const refresh = async () => {
const [collapsedServers, toggleServer, setCollapsedServers] = useStoredIdSet('homelab.collapsedServers')
const [openContainerLists, toggleContainerList] = useIdSet()
const [openSystemLists, toggleSystemList] = useIdSet()
+ const [openNetworkLists, toggleNetworkList] = useIdSet()
const allCollapsed = servers.length > 0 && servers.every((server) => collapsedServers.has(server.id))
const dashboardHost = servers.find((server) => server.is_dashboard_host)
const dashboardHostId = dashboardHost?.id
@@ -902,6 +960,7 @@ const refresh = async () => {
{metric && <StorageBars mounts={mounts} thresholds={overview.disk_thresholds} mountThresholds={overview.mount_thresholds} />}
{metric?.docker_status === 'unreachable' && <DockerNotice host={metric} />}
{metric && <SystemSection server={server} open={openSystemLists.has(server.id)} onToggle={() => toggleSystemList(server.id)} />}
+ {metric && <NetworkSection server={server} open={openNetworkLists.has(server.id)} onToggle={() => toggleNetworkList(server.id)} />}
{server.containers.length > 0 && <ContainerSection server={server} open={openContainerLists.has(server.id)} onToggle={() => toggleContainerList(server.id)} />}
<div className="mt-3 text-xs text-[#7f8589]">Last check: {server.last_seen_at ? new Date(server.last_seen_at).toLocaleString() : 'Never'}</div>
</>}
diff --git a/tests/test_network_checks.py b/tests/test_network_checks.py
new file mode 100644
index 0000000..56a737b
--- /dev/null
+++ b/tests/test_network_checks.py
@@ -0,0 +1,642 @@
+import json
+import os
+import time
+from datetime import datetime, timedelta, timezone
+from pathlib import Path
+
+os.environ.setdefault("DATABASE_URL", "sqlite://")
+os.environ.setdefault("REDIS_URL", "redis://localhost:6379/0")
+
+import pytest
+from sqlalchemy import create_engine
+from sqlalchemy.orm import sessionmaker
+
+from src.agent import collector
+from src.backend import alerts, main, rules
+from src.backend.models import Base, FirewallState, HostMetric, IncidentAlert, ListenerState, Server, SystemEvent, User
+
+TOKEN = "collector-token"
+
+
+# --- collector: host network totals ----------------------------------------------------------------
+
+def _dev_line(name, received, sent):
+ return f"{name:>8}: {received} 1 0 0 0 0 0 0 {sent} 1 0 0 0 0 0 0"
+
+
+DEV_HEADER = "Inter-| Receive | Transmit\n face |bytes packets errs drop fifo frame compressed multicast|bytes packets errs drop fifo colls carrier compressed\n"
+
+
+def _fake_host(tmp_path, monkeypatch, host_dev=None, own_dev=None, physical=("eno2", "wlo1")):
+ proc, root = tmp_path / "proc", tmp_path / "root"
+ (proc / "1/net").mkdir(parents=True)
+ (proc / "net").mkdir()
+ if host_dev is not None:
+ (proc / "1/net/dev").write_text(DEV_HEADER + "\n".join(host_dev) + "\n")
+ if own_dev is not None:
+ (proc / "net/dev").write_text(DEV_HEADER + "\n".join(own_dev) + "\n")
+ for name in ("lo", "docker0", "veth123", "eno2", "wlo1"):
+ (root / "sys/class/net" / name).mkdir(parents=True)
+ if name in physical:
+ (root / "sys/class/net" / name / "device").mkdir()
+ monkeypatch.setattr(collector, "HOST_PROC", proc)
+ monkeypatch.setattr(collector, "HOST_ROOT", root)
+ return proc, root
+
+
+def test_network_totals_come_from_the_hosts_physical_interfaces(tmp_path, monkeypatch):
+ _fake_host(tmp_path, monkeypatch,
+ host_dev=[_dev_line("lo", 999, 999), _dev_line("eno2", 1000, 400), _dev_line("wlo1", 500, 100), _dev_line("docker0", 777, 777), _dev_line("veth123", 888, 888)],
+ own_dev=[_dev_line("lo", 5, 5), _dev_line("eth0", 7, 3)])
+
+ # The collector container's own eth0 is never used, and Docker's virtual interfaces would double count.
+ assert collector._network_totals() == (500, 1500)
+
+
+def test_without_sysfs_virtual_interfaces_are_skipped_by_name(tmp_path, monkeypatch):
+ _proc, root = _fake_host(tmp_path, monkeypatch, host_dev=[_dev_line("lo", 9, 9), _dev_line("eno2", 100, 50), _dev_line("veth9", 70, 70), _dev_line("br-abc", 60, 60), _dev_line("docker0", 40, 40)])
+ import shutil
+ shutil.rmtree(root / "sys")
+
+ assert collector._network_totals() == (50, 100)
+
+
+def test_inside_a_container_an_unreadable_host_table_is_unknown_not_the_containers_own(tmp_path, monkeypatch):
+ _fake_host(tmp_path, monkeypatch, host_dev=None, own_dev=[_dev_line("eth0", 7, 3)])
+
+ assert collector._network_totals() is None
+
+
+def test_only_a_collector_on_the_host_itself_may_fall_back_to_proc_net(monkeypatch):
+ monkeypatch.setattr(collector, "HOST_PROC", Path("/host/proc"))
+ assert collector._host_net_dirs() == [Path("/host/proc/1/net")]
+ monkeypatch.setattr(collector, "HOST_PROC", Path("/proc"))
+ assert collector._host_net_dirs() == [Path("/proc/1/net"), Path("/proc/net")]
+
+
+def test_garbage_and_oversized_network_tables_are_survived(tmp_path, monkeypatch):
+ proc, _root = _fake_host(tmp_path, monkeypatch, host_dev=[_dev_line("eno2", 100, 50), "garbage without a colon", "eno2: not numbers at all", _dev_line("wlo1", 1, 1)])
+ assert collector._network_totals() == (51, 101)
+
+ (proc / "1/net/dev").write_bytes(b"x" * (collector.MAX_NET_TABLE_BYTES + 10))
+ assert collector._network_totals() is None
+
+
+# --- collector: listening ports ---------------------------------------------------------------------
+
+TCP_HEADER = " sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode\n"
+ZERO6 = "0" * 32
+
+
+def _sock(address, port, state, remote="00000000:0000"):
+ return f" 0: {address}:{port:04X} {remote} {state} 00000000:00000000 00:00000000 00000000 0 0 1 1 0"
+
+
+def _net_tables(tmp_path, monkeypatch, **tables):
+ proc = tmp_path / "proc"
+ (proc / "1/net").mkdir(parents=True)
+ for name, lines in tables.items():
+ (proc / "1/net" / name).write_text(TCP_HEADER + "\n".join(lines) + "\n")
+ monkeypatch.setattr(collector, "HOST_PROC", proc)
+
+
+def test_listeners_are_read_with_their_scope(tmp_path, monkeypatch):
+ _net_tables(tmp_path, monkeypatch,
+ tcp=[_sock("0100007F", 5432, "0A"), _sock("00000000", 80, "0A"), _sock("0100A8C0", 8080, "0A"), _sock("00000000", 443, "01", "0100A8C0:C350")],
+ tcp6=[_sock(ZERO6, 22, "0A"), _sock("00000000000000000000000001000000", 631, "0A"), _sock("0000000000000000FFFF00000100007F", 9000, "0A")],
+ udp=[_sock("00000000", 5353, "07"), _sock("00000000", 5355, "01", "0100A8C0:0035")], udp6=[])
+
+ found = {(item["proto"], item["port"], item["scope"]) for item in collector.collect_listeners()}
+
+ assert found == {("tcp", 5432, "loopback"), ("tcp", 80, "any"), ("tcp", 8080, "specific"), ("tcp", 22, "any"), ("tcp", 631, "loopback"), ("tcp", 9000, "loopback"), ("udp", 5353, "any")}
+
+
+def test_the_same_port_on_ipv4_and_ipv6_is_one_listener(tmp_path, monkeypatch):
+ _net_tables(tmp_path, monkeypatch, tcp=[_sock("00000000", 80, "0A")], tcp6=[_sock(ZERO6, 80, "0A")], udp=[], udp6=[])
+
+ assert collector.collect_listeners() == [{"proto": "tcp", "port": 80, "scope": "any"}]
+
+
[email protected]("proto, port, scope, tracked", [
+ ("tcp", 80, "any", True), ("tcp", 5432, "loopback", True), ("udp", 5353, "any", True), ("udp", 53, "loopback", True),
+ ("tcp", 45983, "loopback", False), ("udp", 40000, "any", False), ("udp", 40000, "specific", False),
+ ("tcp", 40000, "any", True), ("tcp", 40000, "specific", True),
+])
+def test_ephemeral_ports_are_skipped_but_exposed_high_tcp_ports_are_not(proto, port, scope, tracked):
+ assert collector.listener_tracked(proto, port, scope) is tracked
+ assert rules.listener_tracked(proto, port, scope) is tracked
+
+
+def test_missing_or_garbage_tables_are_unknown_or_ignored(tmp_path, monkeypatch):
+ _net_tables(tmp_path, monkeypatch)
+ assert collector.collect_listeners() is None # nothing readable
+
+ proc = tmp_path / "proc"
+ for name in ("tcp6", "udp", "udp6"):
+ (proc / "1/net" / name).write_text(TCP_HEADER)
+ (proc / "1/net/tcp").write_text(TCP_HEADER + "\n".join(["garbage", "", "1: nonsense", "0: ZZZ:GG 00000000:0000 0A", "0: 0100007F:0000 00000000:0000 0A", "0: 0100007F:FFFFF 00000000:0000 0A", _sock("00000000", 22, "0A")]) + "\n")
+ assert collector.collect_listeners() == [{"proto": "tcp", "port": 22, "scope": "any"}]
+
+
+def test_one_unreadable_table_makes_the_whole_answer_unknown_not_partial(tmp_path, monkeypatch):
+ _net_tables(tmp_path, monkeypatch, tcp=[_sock("00000000", 22, "0A")], tcp6=[], udp=[]) # udp6 is missing
+
+ assert collector.collect_listeners() is None
+
+
+def test_a_table_longer_than_the_cap_is_unknown_because_a_truncated_read_could_fake_closed_ports(tmp_path, monkeypatch):
+ monkeypatch.setattr(collector, "MAX_NET_TABLE_LINES", 100)
+ _net_tables(tmp_path, monkeypatch, tcp=[_sock("00000000", 22, "0A")] + [_sock("0100A8C0", 40000 + number, "01", "0100A8C0:C350") for number in range(150)], tcp6=[], udp=[], udp6=[])
+
+ assert collector.collect_listeners() is None
+
+
+def test_a_busy_hosts_connection_table_does_not_hide_its_listeners(tmp_path, monkeypatch):
+ connections = [_sock("0100A8C0", 20000 + number, "01", "0100A8C0:C350") for number in range(5000)]
+ _net_tables(tmp_path, monkeypatch, tcp=[_sock("00000000", 443, "0A")] + connections, tcp6=[], udp=[], udp6=[])
+
+ assert collector.collect_listeners() == [{"proto": "tcp", "port": 443, "scope": "any"}]
+
+
+def test_a_container_never_reports_its_own_sockets_as_the_hosts(tmp_path, monkeypatch):
+ proc = tmp_path / "proc"
+ (proc / "net").mkdir(parents=True)
+ (proc / "net/tcp").write_text(TCP_HEADER + _sock("00000000", 9999, "0A") + "\n")
+ monkeypatch.setattr(collector, "HOST_PROC", proc) # a container's /proc/net only has the container's sockets
+
+ assert collector.collect_listeners() is None
+
+
+def test_the_listener_report_is_capped(tmp_path, monkeypatch):
+ monkeypatch.setattr(collector, "MAX_NET_TABLE_LINES", 10_000)
+ _net_tables(tmp_path, monkeypatch, tcp=[_sock("00000000", port, "0A") for port in range(1, 700)], tcp6=[], udp=[], udp6=[])
+
+ assert len(collector.collect_listeners()) == collector.MAX_LISTENERS
+
+
+# --- collector: connectivity ------------------------------------------------------------------------
+
+def test_connectivity_is_off_unless_targets_are_configured(monkeypatch):
+ monkeypatch.delenv("HOMELAB_CONNECTIVITY_TARGETS", raising=False)
+ assert collector.collect_connectivity() == {"internet_status": None, "internet_latency_ms": None}
+
+
[email protected]("value, expected", [
+ ("1.1.1.1:443", [("1.1.1.1", 443)]),
+ ("example.com:443, 9.9.9.9:53 ,example.com:443", [("example.com", 443), ("9.9.9.9", 53)]),
+ ("a.com:1,b.com:2,c.com:3,d.com:4,e.com:5,f.com:6,g.com:7", [("a.com", 1), ("b.com", 2), ("c.com", 3), ("d.com", 4), ("e.com", 5)]),
+])
+def test_valid_targets_are_parsed_deduplicated_and_capped(monkeypatch, value, expected):
+ monkeypatch.setenv("HOMELAB_CONNECTIVITY_TARGETS", value)
+ assert collector._connectivity_targets() == expected
+
+
[email protected]("bad", ["", "nohost", ":443", "host:", "host:0", "host:65536", "host:abc", "host:-1", "http://example.com:443", "exa mple.com:443", "example.com;rm -rf /:443",
+ "999.1.1.1:443", "1.1.1:443", "[::1]:443", "-bad.com:443", "a" * 300 + ".com:443", "user@host:443", "host:443/path", "host\n:443"])
+def test_malformed_targets_are_ignored(monkeypatch, bad):
+ monkeypatch.setenv("HOMELAB_CONNECTIVITY_TARGETS", bad)
+ assert collector._connectivity_targets() == []
+
+
[email protected]("results, status", [
+ ([{"dns": None, "tcp": True}, {"dns": True, "tcp": True}], "ok"),
+ ([{"dns": None, "tcp": True}, {"dns": True, "tcp": False}], "degraded"),
+ ([{"dns": False, "tcp": False}, {"dns": False, "tcp": False}], "dns_failed"),
+ ([{"dns": None, "tcp": False}, {"dns": True, "tcp": False}], "down"),
+ ([{"dns": False, "tcp": False}, {"dns": None, "tcp": False}], "down"),
+])
+def test_results_are_summarised(results, status):
+ assert collector.summarise_connectivity(results) == status
+
+
+def test_a_reachable_target_reports_ok_with_its_latency(monkeypatch):
+ monkeypatch.setenv("HOMELAB_CONNECTIVITY_TARGETS", "example.com:443,1.1.1.1:443")
+ monkeypatch.setattr(collector.socket, "getaddrinfo", lambda host, port, **kw: [(None, None, None, "", ("93.184.216.34", port))])
+
+ class Connection:
+ def close(self):
+ pass
+
+ monkeypatch.setattr(collector.socket, "create_connection", lambda address, timeout: Connection())
+
+ result = collector.collect_connectivity()
+
+ assert result["internet_status"] == "ok" and isinstance(result["internet_latency_ms"], int)
+
+
+def test_unresolvable_names_are_reported_as_dns_failure(monkeypatch):
+ monkeypatch.setenv("HOMELAB_CONNECTIVITY_TARGETS", "example.com:443")
+ monkeypatch.setattr(collector.socket, "getaddrinfo", lambda *a, **k: (_ for _ in ()).throw(OSError("no dns")))
+
+ assert collector.collect_connectivity()["internet_status"] == "dns_failed"
+
+
+def test_a_hung_probe_cannot_stall_the_check_in(monkeypatch):
+ monkeypatch.setenv("HOMELAB_CONNECTIVITY_TARGETS", "1.1.1.1:443")
+ monkeypatch.setattr(collector, "CONNECTIVITY_DEADLINE_SECONDS", 0.3)
+ monkeypatch.setattr(collector.socket, "create_connection", lambda address, timeout: time.sleep(3))
+
+ started = time.monotonic()
+ result = collector.collect_connectivity()
+
+ assert time.monotonic() - started < 1.5 and result["internet_status"] == "down"
+
+
+def test_probes_only_connect_and_never_send_data(monkeypatch):
+ monkeypatch.setenv("HOMELAB_CONNECTIVITY_TARGETS", "1.1.1.1:443")
+ sent = []
+
+ class Connection:
+ def close(self):
+ pass
+
+ def send(self, data):
+ sent.append(data)
+
+ sendall = send
+
+ monkeypatch.setattr(collector.socket, "create_connection", lambda address, timeout: Connection())
+ collector.collect_connectivity()
+
+ assert sent == []
+
+
+# --- collector: firewall files ----------------------------------------------------------------------
+
+def _firewall_root(tmp_path, monkeypatch, files):
+ root = tmp_path / "root"
+ for relative, content in files.items():
+ path = root / relative
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_bytes(content if isinstance(content, bytes) else content.encode())
+ root.mkdir(exist_ok=True)
+ monkeypatch.setattr(collector, "HOST_ROOT", root)
+ return root
+
+
+UFW_RULES = "*filter\n:ufw-user-input - [0:0]\n-A ufw-user-input -p tcp --dport 22 -j ACCEPT\n-A ufw-user-input -p tcp --dport 8443 -s 10.0.0.0/8 -j ACCEPT\nCOMMIT\n"
+
+
+def test_firewall_files_are_reduced_to_a_hash_a_rule_count_and_the_ufw_flag(tmp_path, monkeypatch):
+ _firewall_root(tmp_path, monkeypatch, {"etc/ufw/user.rules": UFW_RULES, "etc/ufw/ufw.conf": "# comment\nENABLED=yes\nLOGLEVEL=low\n", "etc/nftables.conf": "#!/usr/sbin/nft -f\n\nflush ruleset\ntable inet filter {\n}\n"})
+
+ report = collector.collect_firewall()
+
+ by_name = {item["name"]: item for item in report["files"]}
+ assert by_name["ufw"]["rules"] == 2 and by_name["nftables"]["rules"] == 3 and report["ufw_enabled"] is True
+ assert all(len(item["sha"]) == 16 for item in report["files"])
+
+
+def test_the_firewall_report_never_contains_the_rules_themselves(tmp_path, monkeypatch):
+ _firewall_root(tmp_path, monkeypatch, {"etc/ufw/user.rules": UFW_RULES + "# secret-internal-subnet 10.99.0.0/16\n"})
+
+ dumped = json.dumps(collector.collect_firewall())
+
+ assert "10.0.0.0" not in dumped and "8443" not in dumped and "secret-internal-subnet" not in dumped
+
+
+def test_ufw_disabled_is_reported_and_changes_the_fingerprint(tmp_path, monkeypatch):
+ _firewall_root(tmp_path, monkeypatch, {"etc/ufw/ufw.conf": "ENABLED=yes\n"})
+ enabled = collector.collect_firewall()
+ _firewall_root(tmp_path, monkeypatch, {"etc/ufw/ufw.conf": "ENABLED=no\n"})
+ disabled = collector.collect_firewall()
+
+ assert (enabled["ufw_enabled"], disabled["ufw_enabled"]) == (True, False) and enabled["files"][0]["sha"] != disabled["files"][0]["sha"]
+
+
+def test_no_known_firewall_file_means_none(tmp_path, monkeypatch):
+ _firewall_root(tmp_path, monkeypatch, {})
+ assert collector.collect_firewall() is None
+
+
+def test_symlinked_oversized_and_binary_firewall_files_are_handled_safely(tmp_path, monkeypatch):
+ root = _firewall_root(tmp_path, monkeypatch, {"etc/ufw/user6.rules": "x", "etc/iptables/rules.v6": b"\xff\xfe\x00" * 10})
+ secret = tmp_path / "secret.txt"
+ secret.write_text("root:hash")
+ (root / "etc/ufw/user.rules").symlink_to(secret) # must not be followed
+ (root / "etc/nftables.conf").write_bytes(b"#" * (collector.MAX_FIREWALL_FILE_BYTES + 1)) # too large
+
+ names = {item["name"] for item in collector.collect_firewall()["files"]}
+
+ assert names == {"ufw6", "ip6tables"}
+
+
+# --- backend ---------------------------------------------------------------------------------------
+
+def db():
+ engine = create_engine("sqlite://")
+ Base.metadata.create_all(engine)
+ session = sessionmaker(bind=engine)()
+ session.add(User(id=1, name="Owner", email="[email protected]", password_hash="x", role="admin"))
+ session.add(Server(id=5, owner_id=1, hostname="nas", check_interval_seconds=60, collector_token_hash=main._hash_secret(TOKEN)))
+ session.commit()
+ return session
+
+
+def _ingest(db, **host):
+ main.ingest_metrics(main.MetricsIngestRequest(server_id=5, host=host), authorization=f"Bearer {TOKEN}", session_id=None, db=db)
+
+
+def _l(proto, port, scope="any"):
+ return {"proto": proto, "port": port, "scope": scope}
+
+
+BASE_PORTS = [_l("tcp", 22), _l("tcp", 5432, "loopback")]
+
+
+def _active(db):
+ return {alert.rule_key: alert for alert in db.query(IncidentAlert).filter_by(status="active")}
+
+
+def _events(db, *kinds):
+ return [(event.kind, event.detail, event.event_key) for event in db.query(SystemEvent).filter(SystemEvent.kind.in_(kinds or rules.NETWORK_EVENT_KINDS)).order_by(SystemEvent.id)]
+
+
[email protected]("raw", [None, 5, "x", {}, {"proto": "tcp"}])
+def test_a_listener_report_must_be_a_list(raw):
+ assert rules.validate_listeners(raw) is None
+
+
+def test_listener_entries_are_validated_deduplicated_and_filtered():
+ raw = [_l("tcp", 80), _l("tcp", 80), _l("sctp", 80), _l("tcp", 0), _l("tcp", 65536), _l("tcp", "80"), _l("tcp", True), _l("tcp", 1.5), _l("tcp", 80, "everywhere"),
+ {"proto": "tcp"}, None, 5, "x", _l("tcp", 45000, "loopback"), _l("udp", 45000), _l("udp", 53, "specific")]
+
+ assert rules.validate_listeners(raw) == [("tcp", 80, "any"), ("udp", 53, "specific")]
+
+
+def test_the_listener_list_is_capped():
+ assert len(rules.validate_listeners([_l("tcp", port) for port in range(1, 2000)])) == rules.MAX_LISTENERS
+
+
+def test_firewall_reports_are_validated():
+ sha = "0123456789abcdef"
+ assert rules.validate_firewall(None) == {"files": {}, "ufw_enabled": None}
+ assert rules.validate_firewall("x") is None and rules.validate_firewall({"files": "x"}) is None and rules.validate_firewall({}) is None
+ good = {"files": [{"name": "ufw", "sha": sha, "rules": 3}], "ufw_enabled": True}
+ assert rules.validate_firewall(good) == {"files": {"ufw": (sha, 3)}, "ufw_enabled": True}
+ junk = {"files": [{"name": "passwd", "sha": sha, "rules": 1}, {"name": "ufw", "sha": "NOT-HEX", "rules": 1}, {"name": "ufw6", "sha": sha, "rules": -1}, {"name": "ufw6", "sha": sha, "rules": "5"},
+ {"name": "ufw6", "sha": sha, "rules": True}, {"name": "nftables", "sha": sha, "rules": 10**9}, {"name": "iptables", "sha": sha, "rules": 2}, {"name": "iptables", "sha": sha, "rules": 9}, 5, None], "ufw_enabled": "yes"}
+ assert rules.validate_firewall(junk) == {"files": {"iptables": (sha, 2)}, "ufw_enabled": None}
+
+
+def test_the_first_listener_report_is_only_a_baseline(db):
+ _ingest(db, listeners=BASE_PORTS)
+
+ assert _events(db) == [] and db.query(ListenerState).count() == 2
+
+
+def test_a_new_exposed_listener_is_recorded_and_raises_a_warning(db):
+ _ingest(db, listeners=BASE_PORTS)
+ _ingest(db, listeners=BASE_PORTS + [_l("tcp", 8080)])
+
+ assert _events(db) == [("port_opened", "New listener: tcp/8080 (all interfaces)", "tcp/8080/any")]
+ alert = _active(db)["network:port:tcp/8080"]
+ assert alert.severity == alerts.WARNING and "8080" in alert.title
+
+
+def test_a_new_loopback_listener_is_an_event_without_an_incident(db):
+ _ingest(db, listeners=BASE_PORTS)
+ _ingest(db, listeners=BASE_PORTS + [_l("tcp", 6379, "loopback")])
+
+ assert [kind for kind, _d, _k in _events(db)] == ["port_opened"] and not [key for key in _active(db) if key.startswith("network:port")]
+
+
+def test_a_closed_listener_is_recorded_and_clears_its_incident(db):
+ _ingest(db, listeners=BASE_PORTS)
+ _ingest(db, listeners=BASE_PORTS + [_l("tcp", 8080)])
+ _ingest(db, listeners=BASE_PORTS)
+
+ assert [kind for kind, _d, _k in _events(db)] == ["port_opened", "port_closed"]
+ assert "network:port:tcp/8080" not in _active(db) and db.query(ListenerState).count() == 2
+
+
+def test_the_listener_incident_clears_with_the_event_window(db):
+ _ingest(db, listeners=BASE_PORTS)
+ _ingest(db, listeners=BASE_PORTS + [_l("tcp", 8080)])
+ db.query(SystemEvent).update({"time": datetime.now(timezone.utc) - timedelta(hours=3)})
+ db.commit()
+ _ingest(db, listeners=BASE_PORTS + [_l("tcp", 8080)])
+
+ assert "network:port:tcp/8080" not in _active(db)
+
+
+def test_unchanged_listeners_create_no_events_or_duplicate_rows(db):
+ for _ in range(3):
+ _ingest(db, listeners=BASE_PORTS)
+
+ assert _events(db) == [] and db.query(ListenerState).count() == 2
+
+
+def test_an_empty_or_missing_listener_report_never_looks_like_everything_closed(db):
+ _ingest(db, listeners=BASE_PORTS)
+ _ingest(db, listeners=[])
+ _ingest(db, listeners=None)
+ _ingest(db) # an old collector that doesn't send the field
+ _ingest(db, listeners="garbage")
+
+ assert _events(db) == [] and db.query(ListenerState).count() == 2
+
+
+def test_a_burst_of_new_listeners_is_capped_with_one_notice(db):
+ _ingest(db, listeners=BASE_PORTS)
+ _ingest(db, listeners=BASE_PORTS + [_l("tcp", port) for port in range(9000, 9030)])
+
+ kinds = [kind for kind, _d, _k in _events(db)]
+ assert kinds.count("port_opened") == rules.MAX_NETWORK_EVENTS_PER_CHECKIN and kinds.count("network_notice") == 1
+
+
+def test_sustained_port_flapping_is_capped_per_hour(db):
+ _ingest(db, listeners=BASE_PORTS)
+ for round_number in range(12):
+ extra = [_l("tcp", 9000 + number + round_number * 100) for number in range(15)]
+ _ingest(db, listeners=BASE_PORTS + extra)
+
+ kinds = [kind for kind, _d, _k in _events(db)]
+ assert len(kinds) <= rules.MAX_NETWORK_EVENTS_PER_HOUR + 1 and kinds.count("network_notice") == 1
+
+
+def test_listener_state_is_removed_with_the_server(db, monkeypatch):
+ monkeypatch.setattr(main, "_require_admin", lambda session_id, db: {"id": 1})
+ _ingest(db, listeners=BASE_PORTS, firewall={"files": [{"name": "ufw", "sha": "0123456789abcdef", "rules": 1}], "ufw_enabled": None})
+
+ main.delete_monitored_server(5, session_id="s", db=db)
+
+ assert db.query(ListenerState).count() == 0 and db.query(FirewallState).count() == 0
+
+
+def _fw(*files, enabled=None):
+ return {"files": [{"name": name, "sha": sha, "rules": count} for name, sha, count in files], "ufw_enabled": enabled}
+
+
+SHA_A, SHA_B, SHA_C = "a" * 16, "b" * 16, "c" * 16
+
+
+def test_the_first_firewall_report_is_only_a_baseline(db):
+ _ingest(db, firewall=_fw(("ufw", SHA_A, 4), ("ufw-conf", SHA_B, 0), enabled=True))
+
+ assert _events(db) == [] and db.query(FirewallState).count() == 2 and not [k for k in _active(db) if k.startswith("network:")]
+
+
+def test_unchanged_firewall_files_report_nothing(db):
+ for _ in range(3):
+ _ingest(db, firewall=_fw(("ufw", SHA_A, 4)))
+
+ assert _events(db) == []
+
+
+def test_changed_rules_are_informational_and_fewer_rules_are_a_warning(db):
+ _ingest(db, firewall=_fw(("ufw", SHA_A, 4)))
+ _ingest(db, firewall=_fw(("ufw", SHA_B, 6)))
+ assert _events(db) == [("firewall_changed", "ufw IPv4 rules changed (4 to 6 rules)", "ufw")]
+ assert _active(db)["network:firewall"].severity == alerts.INFO
+
+ _ingest(db, firewall=_fw(("ufw", SHA_C, 2)))
+ assert [kind for kind, _d, _k in _events(db)][-1] == "firewall_weakened"
+ assert _active(db)["network:firewall"].severity == alerts.WARNING
+
+
+def test_disabling_ufw_is_a_warning_and_enabling_it_is_informational(db):
+ _ingest(db, firewall=_fw(("ufw-conf", SHA_A, 0), enabled=True))
+ _ingest(db, firewall=_fw(("ufw-conf", SHA_B, 0), enabled=False))
+ assert _events(db) == [("firewall_weakened", "ufw was enabled and is now disabled", "ufw-conf")]
+ assert _active(db)["network:firewall"].severity == alerts.WARNING
+
+ _ingest(db, firewall=_fw(("ufw-conf", SHA_C, 0), enabled=True))
+ assert _events(db)[-1][:2] == ("firewall_changed", "ufw was disabled and is now enabled")
+
+
+def test_a_firewall_file_disappearing_is_a_warning_and_one_appearing_is_informational(db):
+ _ingest(db, firewall=_fw(("ufw", SHA_A, 4), ("nftables", SHA_B, 9)))
+ _ingest(db, firewall=_fw(("nftables", SHA_B, 9), ("iptables", SHA_C, 1)))
+
+ assert _events(db) == [("firewall_changed", "iptables rules.v4 appeared", "iptables"), ("firewall_weakened", "ufw IPv4 rules is no longer present", "ufw")]
+ assert db.query(FirewallState).count() == 2
+
+
+def test_all_firewall_files_vanishing_is_noticed(db):
+ _ingest(db, firewall=_fw(("ufw", SHA_A, 4)))
+ _ingest(db, firewall=None)
+
+ assert [kind for kind, _d, _k in _events(db)] == ["firewall_weakened"] and db.query(FirewallState).count() == 0
+
+
+def test_missing_or_malformed_firewall_reports_are_ignored(db):
+ _ingest(db, firewall=_fw(("ufw", SHA_A, 4)))
+ _ingest(db)
+ _ingest(db, firewall="garbage")
+ _ingest(db, firewall={"files": "x"})
+ _ingest(db, firewall=_fw(("passwd", SHA_B, 1), ("ufw", "not-a-hash", 1))) # valid shape, but no usable entry
+
+ assert [kind for kind, _d, _k in _events(db)] == ["firewall_weakened"] # only the last one: the real file is now absent
+
+
+def test_the_firewall_incident_clears_with_the_event_window(db):
+ _ingest(db, firewall=_fw(("ufw", SHA_A, 4)))
+ _ingest(db, firewall=_fw(("ufw", SHA_B, 5)))
+ db.query(SystemEvent).update({"time": datetime.now(timezone.utc) - timedelta(hours=3)})
+ db.commit()
+ _ingest(db, firewall=_fw(("ufw", SHA_B, 5)))
+
+ assert "network:firewall" not in _active(db)
+
+
+def test_sustained_internet_loss_warns_and_recovery_clears(db):
+ for _ in range(2):
+ _ingest(db, internet_status="down")
+ assert "network:internet" not in _active(db)
+ _ingest(db, internet_status="down")
+ assert _active(db)["network:internet"].severity == alerts.WARNING
+
+ _ingest(db, internet_status="ok", internet_latency_ms=20)
+ assert "network:internet" not in _active(db)
+
+
+def test_sustained_dns_failure_is_its_own_warning(db):
+ for _ in range(3):
+ _ingest(db, internet_status="dns_failed")
+
+ assert "network:dns" in _active(db) and "network:internet" not in _active(db)
+
+
+def test_degraded_unchecked_and_malformed_internet_status_never_alerts(db):
+ for _ in range(4):
+ _ingest(db, internet_status="degraded")
+ for _ in range(4):
+ _ingest(db, internet_status=None)
+ for _ in range(4):
+ _ingest(db, internet_status="<script>", internet_latency_ms="fast")
+
+ assert not [key for key in _active(db) if key.startswith("network:")]
+ assert db.query(HostMetric).filter(HostMetric.internet_status == "<script>").count() == 0
+
+
+def test_internet_latency_must_be_a_sane_number(db):
+ _ingest(db, internet_status="ok", internet_latency_ms=10**9)
+ _ingest(db, internet_status="ok", internet_latency_ms=42)
+
+ assert [row.internet_latency_ms for row in db.query(HostMetric).order_by(HostMetric.id)] == [None, 42]
+
+
+def test_the_overview_shows_listeners_firewall_and_network_events(db, monkeypatch):
+ monkeypatch.setattr(main, "_current_user", lambda session_id, db: {"id": 1})
+ _ingest(db, listeners=BASE_PORTS, firewall=_fw(("ufw-conf", SHA_A, 0), enabled=False), internet_status="ok", internet_latency_ms=12)
+ _ingest(db, listeners=BASE_PORTS + [_l("tcp", 8080)], firewall=_fw(("ufw-conf", SHA_A, 0), enabled=False), internet_status="ok", internet_latency_ms=12)
+
+ server = main.monitoring_overview(session_id="s", db=db)["servers"][0]
+
+ assert [(item["proto"], item["port"], item["scope"]) for item in server["network"]["listeners"]] == [("tcp", 22, "any"), ("tcp", 5432, "loopback"), ("tcp", 8080, "any")]
+ assert server["network"]["firewall"][0]["label"] == "ufw settings" and server["network"]["firewall"][0]["enabled"] is False
+ assert [event["kind"] for event in server["network"]["events"]] == ["port_opened"]
+ assert (server["host"]["internet_status"], server["host"]["internet_latency_ms"]) == ("ok", 12)
+
+
+def test_network_events_have_their_own_list_and_do_not_crowd_the_other_rows(db, monkeypatch):
+ monkeypatch.setattr(main, "_current_user", lambda session_id, db: {"id": 1})
+ db.add(SystemEvent(server_id=5, time=datetime.now(timezone.utc) - timedelta(days=2), kind="reboot", detail="The host rebooted"))
+ db.commit()
+ _ingest(db, listeners=BASE_PORTS)
+ _ingest(db, listeners=BASE_PORTS + [_l("tcp", port) for port in range(9000, 9008)])
+
+ server = main.monitoring_overview(session_id="s", db=db)["servers"][0]
+
+ assert [event["kind"] for event in server["system_events"]] == ["reboot"] and server["container_events"] == []
+ assert len(server["network"]["events"]) == 8
+
+
+def test_the_network_lists_are_bounded(db, monkeypatch):
+ monkeypatch.setattr(main, "_current_user", lambda session_id, db: {"id": 1})
+ now = datetime.now(timezone.utc)
+ for number in range(300):
+ db.add(ListenerState(server_id=5, proto="tcp", port=1000 + number, scope="any", first_seen=now, last_seen=now))
+ for number in range(40):
+ db.add(SystemEvent(server_id=5, time=now - timedelta(minutes=number), kind="port_opened", detail=f"New listener: tcp/{number}", event_key=f"tcp/{number}/any"))
+ db.commit()
+
+ network = main.monitoring_overview(session_id="s", db=db)["servers"][0]["network"]
+
+ assert len(network["listeners"]) == main.LISTENERS_SHOWN and len(network["events"]) == main.NETWORK_EVENTS_SHOWN
+
+
+def test_network_events_follow_the_normal_retention(db):
+ old = datetime.now(timezone.utc) - timedelta(days=40)
+ db.add_all([SystemEvent(server_id=5, time=old, kind=kind, detail="x", event_key="x") for kind in rules.NETWORK_EVENT_KINDS])
+ db.commit()
+
+ assert main.purge_old_metrics(db) == len(rules.NETWORK_EVENT_KINDS)
+
+
+def test_crafted_event_keys_cannot_raise_incidents_for_closed_or_loopback_ports(db):
+ now = datetime.now(timezone.utc)
+ db.add_all([
+ SystemEvent(server_id=5, time=now, kind="port_opened", detail="x", event_key="tcp/8080/any"), # not actually open
+ SystemEvent(server_id=5, time=now, kind="port_opened", detail="x", event_key="garbage"),
+ SystemEvent(server_id=5, time=now, kind="port_opened", detail="x", event_key="tcp/notaport/any"),
+ ])
+ db.add_all([ListenerState(server_id=5, proto="tcp", port=5432, scope="loopback", first_seen=now, last_seen=now), ListenerState(server_id=5, proto="tcp", port=22, scope="any", first_seen=now, last_seen=now)])
+ db.add(SystemEvent(server_id=5, time=now, kind="port_opened", detail="x", event_key="tcp/5432/loopback"))
+ db.commit()
+
+ _ingest(db, listeners=BASE_PORTS)
+
+ assert not [key for key in _active(db) if key.startswith("network:port")]