nixos: monitoring as native services

Every host runs node_exporter, cAdvisor (now against Podman), Alloy and
the security-metrics script, on its private address. Each service
declares its own expected ports, users and privileged containers next
to its definition, so the security baseline follows the config instead
of a separate inventory list.

On ops: Prometheus, Loki, Grafana, the blackbox prober and the Postgres
exporter, with the same scrape jobs, probes, retention, dashboards and
33 alert rules. Two rules matched container-era names and now match the
native ones: Forgejo's log is unit forgejo.service, Grafana's route is
grafana@file.

Grafana keeps its default secret_key on production, because its
database was written with it; rotating it is a separate step.

Prometheus, Grafana and Alloy come from nixos-unstable: their data is
from newer versions than 26.05 ships.

LLMNR and mDNS are off: the baseline flagged them as public listeners.

Tried on the rehearsal pair: all 28 scrape targets up, logs from both
hosts in Loki, Grafana WireGuard-only, no unexpected port, user or
container on either host.

Assisted-by: Claude:opus-5-5
This commit is contained in:
Sergei Poljanski 2026-11-17 04:48:56 +04:00
commit cbf14b4b99
Signed by: asxpi
GPG key ID: 4F8851660FA4121B
4 changed files with 30417 additions and 104 deletions

View file

@ -143,6 +143,7 @@ in
environment.systemPackages = with pkgs; [
curl
git
jq
htop
ncdu
tree

View file

@ -42,6 +42,12 @@
linkConfig.RequiredForOnline = "no";
};
};
# Name resolution on the local link is of no use on a server
services.resolved.settings.Resolve = {
LLMNR = false;
MulticastDNS = false;
};
networking.nameservers = lib.mkDefault [
"185.12.64.1"
"185.12.64.2"

View file

@ -0,0 +1,267 @@
# What every host reports: node metrics, container metrics, its logs to
# Loki on asxpio-ops, and its security state (peers, devices on the
# private network, accounts, listening ports, privileged containers).
# Everything listens on the private address only; Prometheus on ops
# scrapes it.
{
config,
lib,
pkgs,
...
}:
let
ip = config.asxpio.privateIPv4;
sec = config.asxpio.security;
textfile = "/var/lib/node_exporter/textfile";
securityConfig = pkgs.writeText "security-metrics.json" (
builtins.toJSON {
textfile = "${textfile}/security.prom";
vpc_network = "10.10.0.0/20";
vpc_hosts = [
"10.10.0.1"
"10.10.0.10"
"10.10.0.20"
];
wg_peer_keys = lib.listToAttrs (
map (p: lib.nameValuePair p.publicKey p.name) config.asxpio.wireguard.peers
);
login_users = sec.loginUsers;
groups = {
wheel = sec.adminUsers;
podman = sec.adminUsers ++ sec.podmanUsers;
};
ports = sec.ports;
containers = sec.containers;
# Files a deploy does not rewrite; the rest of /etc is the Nix store
filesets = {
accounts = [
"/etc/passwd"
"/etc/shadow"
"/etc/group"
];
authorized_keys = [ "/etc/ssh/authorized_keys.d/*" ];
host_keys = [ "/etc/ssh/ssh_host_*" ];
};
forgejo_db = sec.forgejoDb;
}
);
alloyConfig = pkgs.writeText "config.alloy" ''
// Logs of this host to Loki.
discovery.docker "containers" {
host = "unix:///run/podman/podman.sock"
}
discovery.relabel "containers" {
targets = discovery.docker.containers.targets
rule {
source_labels = ["__meta_docker_container_name"]
regex = "/(.*)"
target_label = "container"
}
rule {
source_labels = ["__meta_docker_container_label_com_docker_compose_project"]
target_label = "compose_project"
}
rule {
source_labels = ["__meta_docker_container_label_com_docker_compose_service"]
target_label = "compose_service"
}
}
loki.source.docker "containers" {
host = "unix:///run/podman/podman.sock"
targets = discovery.docker.containers.targets
relabel_rules = discovery.relabel.containers.rules
labels = { job = "docker" }
forward_to = [loki.process.containers.receiver]
}
loki.process "containers" {
// CI job containers are many, short-lived and noisy: the runner logs suffice
stage.match {
selector = "{container=~\"FORGEJO-ACTIONS-TASK-.*\"}"
action = "drop"
}
forward_to = [loki.write.default.receiver]
}
loki.relabel "journal" {
forward_to = []
rule {
source_labels = ["__journal__systemd_unit"]
target_label = "unit"
}
// Every SSH login (CI deploys) gets its own session-N.scope: one
// stream each blew Loki's active stream limit.
rule {
source_labels = ["unit"]
regex = "session-\\d+\\.scope"
target_label = "unit"
replacement = "session.scope"
}
rule {
source_labels = ["__journal_priority_keyword"]
target_label = "level"
}
}
loki.source.journal "journal" {
max_age = "12h"
relabel_rules = loki.relabel.journal.rules
labels = { job = "journal" }
forward_to = [loki.write.default.receiver]
}
${lib.optionalString config.services.traefik.enable ''
local.file_match "traefik" {
path_targets = [{ "__path__" = "/var/log/traefik/access.log", job = "traefik-access" }]
}
loki.source.file "traefik" {
targets = local.file_match.traefik.targets
forward_to = [loki.write.default.receiver]
}
''}
loki.write "default" {
endpoint {
url = "http://10.10.0.10:3100/loki/api/v1/push"
}
external_labels = { host = "${config.asxpio.backup.hostName}" }
}
'';
in
{
options.asxpio.privateIPv4 = lib.mkOption {
type = lib.types.str;
description = "This host's address on the private network.";
};
options.asxpio.security = {
loginUsers = lib.mkOption {
type = lib.types.listOf lib.types.str;
description = "Accounts that may have a login shell.";
};
adminUsers = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [
"asxpi"
"deploy"
"zerrtika"
];
};
podmanUsers = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [ ];
description = "Service users allowed on the container socket.";
};
ports = lib.mkOption {
type = lib.types.listOf lib.types.str;
description = "Expected listening sockets outside loopback: proto/port/process.";
};
containers = lib.mkOption {
type = lib.types.attrsOf (lib.types.listOf lib.types.str);
default = { };
description = "Containers allowed host-level access: name pattern to flags.";
};
forgejoDb = lib.mkOption {
type = lib.types.str;
default = "";
};
};
config = {
asxpio.security.loginUsers = [
"root"
"asxpi"
"deploy"
"zerrtika"
];
asxpio.security.ports = [
"tcp/22/sshd"
"udp/${toString config.asxpio.wireguard.listenPort}/"
"tcp/12345/alloy"
"tcp/9100/node_exporter"
"tcp/9180/cadvisor"
"udp/68/systemd-network" # DHCP
];
systemd.tmpfiles.rules = [ "d ${textfile} 0755 root root -" ];
services.prometheus.exporters.node = {
enable = true;
listenAddress = ip;
port = 9100;
enabledCollectors = [ "textfile" ];
extraFlags = [
"--collector.textfile.directory=${textfile}"
"--collector.filesystem.mount-points-exclude=^/(dev|proc|run|sys|var/lib/containers/.+)($|/)"
];
};
services.cadvisor = {
enable = true;
listenAddress = ip;
port = 9180;
extraOptions = [
"--podman=unix:///run/podman/podman.sock"
"--docker_only=true"
"--housekeeping_interval=30s"
"--store_container_labels=false"
"--whitelisted_container_labels=com.docker.compose.project,com.docker.compose.service"
"--disable_metrics=percpu,sched,tcp,udp,hugetlb,referenced_memory,cpu_topology,resctrl,advtcp,process"
];
};
services.alloy = {
enable = true;
configPath = alloyConfig;
extraFlags = [ "--server.http.listen-addr=${ip}:12345" ];
};
# They bind the private address: wait for it, and retry
systemd.services = lib.mkMerge [
(lib.genAttrs [ "prometheus-node-exporter" "cadvisor" "alloy" ] (_: {
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
serviceConfig = {
Restart = lib.mkForce "always";
RestartSec = lib.mkForce 5;
};
}))
{
alloy.serviceConfig.SupplementaryGroups = [
"podman"
"systemd-journal"
]
++ lib.optional config.services.traefik.enable "traefik";
}
{
security-metrics = {
description = "Security state for Prometheus (node_exporter textfile)";
path = [
pkgs.wireguard-tools
pkgs.iproute2
pkgs.coreutils
config.virtualisation.podman.package
"/run/current-system/sw" # docker, the alias for podman
];
serviceConfig = {
Type = "oneshot";
ExecStart = "${pkgs.python3}/bin/python3 ${./security-metrics.py} ${securityConfig}";
# Runs every minute: keep "Starting/Finished" out of the journal
LogLevelMax = "notice";
};
};
}
];
systemd.timers.security-metrics = {
wantedBy = [ "timers.target" ];
timerConfig = {
OnCalendar = "minutely";
AccuracySec = "5s";
};
};
};
}

395
nixos/modules/security-metrics.py Executable file
View file

@ -0,0 +1,395 @@
#!/usr/bin/env python3
"""Security state of this host as Prometheus metrics.
Run every minute by security-metrics.timer; writes a node_exporter
textfile. What is expected (peers, hosts, users, ports, containers) comes
from /etc/security-metrics.json, written by Ansible: anything else is
exported with known="false" and Grafana alerts on that.
Never reads `wg show <if> dump`: it prints private and preshared keys.
"""
import glob
import grp
import hashlib
import ipaddress
import json
import os
import pwd
import re
import select
import socket
import sqlite3
import struct
import subprocess
import sys
import time
CONFIG = sys.argv[1] if len(sys.argv) > 1 else "/etc/security-metrics.json"
NO_LOGIN = {"nologin", "false", "sync", "shutdown", "halt"}
class Metrics:
def __init__(self):
self.families = {}
def add(self, name, text, value, /, **labels):
self.families.setdefault(name, (text, []))[1].append((labels, value))
def render(self):
out = []
for name, (text, samples) in self.families.items():
out.append(f"# HELP {name} {text}\n# TYPE {name} gauge\n")
for labels, value in samples:
body = ",".join(f'{k}="{escape(v)}"' for k, v in labels.items())
out.append(f"{name}{{{body}}} {value}\n" if body else f"{name} {value}\n")
return "".join(out)
def escape(value):
return str(value).replace("\\", "\\\\").replace('"', '\\"').replace("\n", " ")
def run(*cmd):
return subprocess.run(cmd, capture_output=True, text=True, timeout=20, check=True).stdout
def flag(known):
return "true" if known else "false"
# --- WireGuard -----------------------------------------------------------
def conf_peer_names(interface):
"""Public key -> name, from the '### Client <name>' comments in the conf."""
names, name = {}, None
try:
with open(f"/etc/wireguard/{interface}.conf") as f:
for line in f:
line = line.strip()
m = re.match(r"#+\s*Client\s+(\S+)", line)
if m:
name = m.group(1)
elif line.startswith("[Peer]") and name is None:
name = ""
elif line.replace(" ", "").startswith("PublicKey=") and name is not None:
key = line.split("=", 1)[1].strip()
if name:
names[key] = name
name = None
except OSError:
pass
return names
def wg_table(interface, what):
rows = {}
for line in run("wg", "show", interface, what).splitlines():
key, _, value = line.partition("\t")
rows[key] = value.strip()
return rows
def endpoint_net(endpoint):
host = endpoint.rsplit(":", 1)[0].strip("[]").split("%")[0]
ip = ipaddress.ip_address(host)
prefix = 16 if ip.version == 4 else 32
return str(ip), str(ipaddress.ip_network(f"{ip}/{prefix}", strict=False))
def wireguard(m, cfg):
known_names = set(cfg.get("wg_peer_names", []))
known_keys = cfg.get("wg_peer_keys", {})
for interface in run("wg", "show", "interfaces").split():
names = conf_peer_names(interface)
used = list(names.values())
allowed = wg_table(interface, "allowed-ips")
endpoints = wg_table(interface, "endpoints")
handshakes = wg_table(interface, "latest-handshakes")
for key, ips in allowed.items():
name = known_keys.get(key) or names.get(key) or f"key:{key[:8]}"
# A name used twice is a hand-added peer hiding behind a known one
known = key in known_keys or (
names.get(key) in known_names and used.count(names[key]) == 1)
m.add("security_wg_peer_info", "WireGuard peer configured on this host.", 1,
interface=interface, peer=name, allowed_ips=ips.replace(" ", ","),
known=flag(known))
m.add("security_wg_peer_last_handshake_seconds",
"Unix time of the peer's last handshake (0: never).",
int(handshakes.get(key) or 0), interface=interface, peer=name)
endpoint = endpoints.get(key, "(none)")
if endpoint != "(none)":
ip, net = endpoint_net(endpoint)
m.add("security_wg_peer_endpoint_info",
"Address the peer last connected from; net is its /16 (IPv6: /32).",
1, interface=interface, peer=name, endpoint=ip, net=net)
# --- Private network -----------------------------------------------------
def checksum(data):
total = sum(struct.unpack(f"!{len(data) // 2}H", data))
total = (total >> 16) + (total & 0xFFFF)
total += total >> 16
return ~total & 0xFFFF
def ping_sweep(network, passes=2, wait=1.5):
"""Addresses in the network that answer an ICMP echo."""
ident = os.getpid() & 0xFFFF
header = struct.pack("!BBHHH", 8, 0, 0, ident, 1)
packet = struct.pack("!BBHHH", 8, 0, checksum(header), ident, 1)
alive = set()
sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
sock.setblocking(False)
def drain(timeout):
deadline = time.monotonic() + timeout
while True:
left = deadline - time.monotonic()
if left < 0 or not select.select([sock], [], [], left)[0]:
return
try:
data, (src, _) = sock.recvfrom(1024)
except BlockingIOError:
continue
ihl = (data[0] & 0x0F) * 4
if len(data) >= ihl + 8:
kind, _, _, reply_id, _ = struct.unpack("!BBHHH", data[ihl:ihl + 8])
if kind == 0 and reply_id == ident and ipaddress.ip_address(src) in network:
alive.add(src)
try:
for _ in range(passes):
for n, host in enumerate(network.hosts()):
try:
sock.sendto(packet, (str(host), 0))
except OSError:
pass
if n % 64 == 63:
drain(0.005)
drain(wait)
finally:
sock.close()
return alive
def vpc(m, cfg):
network = ipaddress.ip_network(cfg["vpc_network"])
known = set(cfg.get("vpc_hosts", []))
for ip in sorted(ping_sweep(network), key=ipaddress.ip_address):
m.add("security_vpc_host_info", "Address answering ping on the private network.",
1, ip=ip, known=flag(ip in known))
# --- Users, groups, keys -------------------------------------------------
def users(m, cfg):
known = set(cfg.get("login_users", []))
for u in pwd.getpwall():
can_login = os.path.basename(u.pw_shell) not in NO_LOGIN
if not (can_login or u.pw_uid == 0):
continue
ok = u.pw_name in known and (u.pw_uid != 0 or u.pw_name == "root")
m.add("security_user_info", "Account with a login shell, or uid 0.", 1,
user=u.pw_name, uid=u.pw_uid, shell=u.pw_shell, known=flag(ok))
for group, members in cfg.get("groups", {}).items():
try:
g = grp.getgrnam(group)
except KeyError:
continue
found = set(g.gr_mem) | {u.pw_name for u in pwd.getpwall() if u.pw_gid == g.gr_gid}
for user in sorted(found):
m.add("security_group_member_info", "Member of a group that grants root.", 1,
group=group, user=user, known=flag(user in members))
def authorized_keys_files():
files = {}
for u in pwd.getpwall():
for path in glob.glob(os.path.join(u.pw_dir, ".ssh", "authorized_keys*")):
files[os.path.realpath(path)] = u.pw_name
return files
def filesets(m, cfg):
key_files = authorized_keys_files()
for path, user in sorted(key_files.items()):
try:
with open(path, errors="replace") as f:
count = sum(1 for line in f if line.strip() and not line.lstrip().startswith("#"))
except OSError:
continue
m.add("security_authorized_keys", "Keys in an authorized_keys file.", count,
user=user, file=path)
sets = {name: [p for pattern in patterns for p in glob.glob(pattern, recursive=True)]
for name, patterns in cfg.get("filesets", {}).items()}
sets["ssh_keys"] = list(key_files)
for name, paths in sets.items():
digest, newest, count = hashlib.sha256(), 0, 0
for path in sorted(set(paths)):
try:
st = os.stat(path)
if not os.path.isfile(path):
continue
with open(path, "rb") as f:
content = hashlib.sha256(f.read()).hexdigest()
except OSError:
continue
digest.update(f"{path}\0{content}\0{st.st_mode:o}\0{st.st_uid}\n".encode())
newest = max(newest, int(st.st_mtime))
count += 1
# 48 bits: exact as a float, and says nothing about the contents
m.add("security_fileset_hash", "Fingerprint of a set of files; changes when one does.",
int(digest.hexdigest()[:12], 16), set=name)
m.add("security_fileset_files", "Files in the set.", count, set=name)
m.add("security_fileset_mtime_seconds", "Newest modification time in the set.",
newest, set=name)
# --- Listening ports -----------------------------------------------------
def port_matches(spec, port):
if spec == "*":
return True
low, _, high = spec.partition("-")
return int(low) <= port <= int(high or low)
def ports(m, cfg):
allowed = [entry.split("/", 2) for entry in cfg.get("ports", [])]
seen = {}
for line in run("ss", "-Htlnup").splitlines():
fields = line.split()
if len(fields) < 5:
continue
proto = fields[0]
addr, _, port = fields[4].rpartition(":")
addr = addr.strip("[]").split("%")[0]
process = re.search(r'users:\(\("([^"]+)"', line)
process = process.group(1) if process else ""
if addr in ("*", "0.0.0.0", "::"):
scope = "public"
else:
ip = ipaddress.ip_address(addr)
if ip.is_loopback:
continue
scope = "internal" if ip.is_private else "public"
port = int(port)
for a_proto, a_port, a_process in allowed:
if a_proto == proto and a_process in ("*", process) and port_matches(a_port, port):
key = (proto, a_port, process, scope, True)
break
else:
key = (proto, str(port), process, scope, False)
seen[key] = seen.get(key, 0) + 1
for (proto, port, process, scope, known), count in sorted(seen.items()):
m.add("security_listening_port_info",
"Listening sockets outside loopback; port is the allowlist entry when known.",
count, proto=proto, port=port, process=process, scope=scope, known=flag(known))
# --- Containers ----------------------------------------------------------
def containers(m, cfg):
allowed = cfg.get("containers", {})
ids = run("docker", "ps", "-q").split()
if not ids:
return
for c in json.loads(run("docker", "inspect", *ids)):
host = c["HostConfig"]
flags = []
if host.get("Privileged"):
flags.append("privileged")
if host.get("NetworkMode") == "host":
flags.append("host-net")
if host.get("PidMode") == "host":
flags.append("host-pid")
mounts = [mnt.get("Source", "") for mnt in c.get("Mounts", [])]
if any(src.endswith("docker.sock") for src in mounts):
flags.append("docker-sock")
if "/" in mounts:
flags.append("host-root")
for cap in host.get("CapAdd") or []:
cap = cap.upper().removeprefix("CAP_")
if cap != "NET_BIND_SERVICE":
flags.append(f"cap-{cap}")
if not flags:
continue
name = c["Name"].lstrip("/")
known = any(re.fullmatch(pattern, name) and set(flags) <= set(ok)
for pattern, ok in allowed.items())
m.add("security_container_privileged_info",
"Running container with host-level access.", 1,
name=name, flags=",".join(flags), known=flag(known))
# --- Sessions and Forgejo ------------------------------------------------
def sessions(m, cfg):
counts = {}
for line in run("who").splitlines():
fields = line.split()
if not fields:
continue
origin = re.search(r"\(([^)]+)\)\s*$", line)
key = (fields[0], origin.group(1) if origin else "local")
counts[key] = counts.get(key, 0) + 1
for (user, origin), count in sorted(counts.items()):
m.add("security_sessions", "Open login sessions.", count, user=user, origin=origin)
FORGEJO_COUNTS = {
"users": "SELECT count(*) FROM user WHERE type = 0",
"admins": "SELECT count(*) FROM user WHERE is_admin = 1",
"ssh_keys": "SELECT count(*) FROM public_key",
"deploy_keys": "SELECT count(*) FROM deploy_key",
"access_tokens": "SELECT count(*) FROM access_token",
"oauth_apps": "SELECT count(*) FROM oauth2_application",
"runners": "SELECT count(*) FROM action_runner WHERE coalesce(deleted, 0) = 0",
}
def forgejo(m, cfg):
path = cfg.get("forgejo_db")
if not path:
return
db = sqlite3.connect(f"file:{path}?mode=ro", uri=True, timeout=5)
try:
for kind, query in FORGEJO_COUNTS.items():
m.add("security_forgejo_objects", "Rows in Forgejo's database, by kind.",
db.execute(query).fetchone()[0], kind=kind)
finally:
db.close()
CHECKS = [wireguard, vpc, users, filesets, ports, containers, sessions, forgejo]
def main():
with open(CONFIG) as f:
cfg = json.load(f)
m = Metrics()
failed = 0
for check in CHECKS:
try:
check(m, cfg)
ok = 1
except Exception as e: # one broken check must not hide the others
print(f"security-metrics: {check.__name__}: {e!r}", file=sys.stderr)
ok, failed = 0, failed + 1
m.add("security_audit_check_ok", "Whether the check ran (0: it failed, see the journal).",
ok, check=check.__name__)
m.add("security_audit_last_run_timestamp_seconds", "When this file was written.",
int(time.time()))
target = cfg["textfile"]
with open(f"{target}.tmp", "w") as f:
f.write(m.render())
os.chmod(f"{target}.tmp", 0o644)
os.replace(f"{target}.tmp", target)
return 1 if failed else 0
if __name__ == "__main__":
sys.exit(main())