iac/nixos/modules/security-metrics.py
Sergei Poljanski cbf14b4b99
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
2026-11-17 04:48:56 +04:00

395 lines
14 KiB
Python
Executable file

#!/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())