monitoring: watch peers, devices, accounts and logins
All checks were successful
deploy / ansible (push) Successful in 8m12s

Monitoring covered availability only: a new WireGuard peer, a machine
on the private network, an extra account or key, or a login from
outside the VPN would have gone unnoticed.

security-metrics runs every minute on both hosts and exports what it
finds for node_exporter: WireGuard peers and where they connect from,
addresses answering a ping sweep of the VPC, login accounts, sudo and
docker members, listening ports, containers with host-level access,
and fingerprints of the account, sudoers, sshd, WireGuard and
authorized_keys files. Each item is compared with a baseline in the
role defaults and host_vars and exported with known="true|false", so a
deliberate change has to update the baseline with it. On ops it also
counts Forgejo users, keys and runners.

Grafana gets a Security dashboard and an alert group for anything
unknown, a changed access file, an SSH login from outside WireGuard,
failed-login bursts on SSH, Forgejo, Grafana and the asxp.io admin, a
new container, and for logs or the collector itself going quiet, which
would otherwise blind the rest.

It never reads `wg show dump`, which prints preshared keys.

Assisted-by: Claude:fable-5-2
This commit is contained in:
Sergei Poljanski 2026-11-15 21:59:16 +04:00
commit 56dd0255dc
Signed by: asxpi
GPG key ID: 4F8851660FA4121B
12 changed files with 2961 additions and 1 deletions

View file

@ -61,6 +61,32 @@ service to answer.
[traefik-crawlers-statistics](https://git.asxp.io/asxpi/traefik-crawlers-statistics);
update `roles/crawler_alert/files/` from there.
## Security monitoring
`security-metrics` (role `monitoring_agent`, every minute on both hosts)
exports WireGuard peers, devices answering on the VPC, login accounts,
sudo/docker members, listening ports and containers with host access, each
with `known="true|false"` against a baseline, plus fingerprints of the
account, sudoers, sshd, WireGuard and `authorized_keys` files. Grafana
(dashboard Security, alert group `security`) mails on anything unknown, a
changed file, an SSH login from outside WireGuard, failed-login bursts
(SSH, Forgejo, Grafana, asxp.io admin), new Forgejo users, keys or
runners, and logs or the collector going quiet.
A deliberate change needs its baseline updated in the same commit, or it
alerts until it is:
| Change | Variable |
|---|---|
| WireGuard client | `wireguard_clients` (`group_vars/all/wireguard.yaml`) |
| Server on the VPC | `security_vpc_hosts` |
| Account, sudo or docker member | `security_login_users`, `security_sudo_users`, `security_docker_users` |
| Published or listening port | `security_ports_extra` (host_vars) |
| Privileged container, host network, Docker socket | `security_containers_extra` (host_vars) |
Defaults are in `roles/monitoring_agent/defaults/main.yaml`. The VPC check
is a ping sweep: a device that drops ICMP is not seen.
## Bootstrap playbooks
| Playbook | Purpose |

View file

@ -28,3 +28,18 @@ restic_pre_hooks:
- docker exec storage-garage /garage meta snapshot --all
- sqlite3 /opt/forgejo/data/gitea/gitea.db ".backup '$STAGE/forgejo-gitea.db'"
restic_schedule: "*-*-* 03:30:00"
# Security baseline (role monitoring_agent)
security_login_users_extra: [git]
security_docker_users_extra: [git]
security_wg_peer_names: "{{ wireguard_clients | map(attribute='name') | list }}"
security_forgejo_db: "{{ services_base_path }}/forgejo/data/gitea/gitea.db"
security_ports_extra:
- tcp/80/docker-proxy
- tcp/443/docker-proxy
- tcp/3000/docker-proxy # Forgejo, for the runners over the VPC
- "tcp/{{ monitoring_loki_port }}/docker-proxy"
- tcp/8080/docker-proxy # Traefik dashboard, WireGuard address
- "udp/{{ wireguard_port }}/"
security_containers_extra:
traefik: [docker-sock]

View file

@ -26,3 +26,31 @@ restic_pre_hooks:
- docker exec xmpp-ejabberd-1 ejabberdctl backup /opt/ejabberd/database/nightly.backup
- sqlite3 /var/lib/docker/volumes/xmpp_database/_data/ejabberd.sqlite ".backup '$STAGE/ejabberd.sqlite'"
restic_schedule: "*-*-* 04:15:00"
# Security baseline (role monitoring_agent)
security_wg_peer_keys:
"0gRrNiV4FjP6ipczZCRD3dsnK7k7rl6IyjG84fPaJB4=": asxpio-ops
security_ports_extra:
- tcp/80/docker-proxy # ACME challenges, forwarded to ops
- tcp/443/xray
- udp/*/xray # outbound relay sockets
- tcp/*/forgejo-runner # cache server, random ports
- tcp/8000/docker-proxy # SillyTavern, WireGuard address
- tcp/25565/docker-proxy # Minecraft
- udp/19132/docker-proxy
- tcp/5222/docker-proxy # XMPP
- tcp/5223/docker-proxy
- tcp/5269/docker-proxy
- tcp/5443/docker-proxy
- tcp/7777/docker-proxy # SOCKS5 bytestreams
- tcp/8448/docker-proxy # Matrix federation
- tcp/3478/docker-proxy # TURN and its relay ranges
- udp/3478/docker-proxy
- udp/49160-49199/docker-proxy
- udp/50000-50099/docker-proxy
- udp/52820/ # WireGuard
security_containers_extra:
forgejo-runner: [host-net, docker-sock]
forgejo-runner-interop: [docker-sock]
"FORGEJO-ACTIONS-TASK-.*": [docker-sock] # docker_host: automount
xray: [host-net]

File diff suppressed because it is too large Load diff

View file

@ -1,4 +1,4 @@
# Managed by Ansible (role monitoring). Generated; see the commit adding it.
# Managed by Ansible (role monitoring).
{% raw %}
apiVersion: 1
groups:
@ -199,4 +199,316 @@ groups:
for: 0m
labels: { severity: warning }
annotations: { summary: "hel1 -> fsn1 bucket replica: last good run {{ $values.A.Value | printf \"%.0f\" }} hours ago" }
# Security: unexpected peers, devices, accounts, ports and containers
# (metrics from security-metrics, role monitoring_agent) and logins
# (Loki). The baseline lives in that role's defaults and in host_vars.
- orgId: 1
name: security
folder: Alerts
interval: 1m
rules:
- uid: sec-wg-peer-unknown
title: "Unknown WireGuard peer"
condition: C
data:
- refId: A
relativeTimeRange: { from: 900, to: 0 }
datasourceUid: prometheus
model: { refId: A, expr: "security_wg_peer_info{known=\"false\"}", instant: true, intervalMs: 30000, maxDataPoints: 43200 }
- refId: C
datasourceUid: __expr__
model: { refId: C, type: threshold, expression: A, conditions: [ { evaluator: { type: gt, params: [0] } } ] }
noDataState: OK
execErrState: Error
for: 0m
labels: { severity: critical }
annotations: { summary: "WireGuard peer {{ $labels.peer }} ({{ $labels.allowed_ips }}) on {{ $labels.host }} is not in wireguard_clients" }
- uid: sec-wg-endpoint-new
title: "WireGuard peer on a new network"
condition: C
data:
- refId: A
relativeTimeRange: { from: 900, to: 0 }
datasourceUid: prometheus
model: { refId: A, expr: "security_wg_peer_endpoint_info unless on (host, interface, peer, net) max_over_time(security_wg_peer_endpoint_info[14d] offset 30m) and on (host) (security_audit_last_run_timestamp_seconds offset 1d)", instant: true, intervalMs: 30000, maxDataPoints: 43200 }
- refId: C
datasourceUid: __expr__
model: { refId: C, type: threshold, expression: A, conditions: [ { evaluator: { type: gt, params: [0] } } ] }
noDataState: OK
execErrState: Error
for: 0m
labels: { severity: warning }
annotations: { summary: "{{ $labels.peer }} connected to {{ $labels.host }} from {{ $labels.endpoint }}: no address in {{ $labels.net }} was seen for it in 14 days" }
- uid: sec-vpc-host-unknown
title: "Unknown device on the private network"
condition: C
data:
- refId: A
relativeTimeRange: { from: 900, to: 0 }
datasourceUid: prometheus
model: { refId: A, expr: "security_vpc_host_info{known=\"false\"}", instant: true, intervalMs: 30000, maxDataPoints: 43200 }
- refId: C
datasourceUid: __expr__
model: { refId: C, type: threshold, expression: A, conditions: [ { evaluator: { type: gt, params: [0] } } ] }
noDataState: OK
execErrState: Error
for: 2m
labels: { severity: critical }
annotations: { summary: "{{ $labels.ip }} answers on the VPC (seen from {{ $labels.host }}) and is not in security_vpc_hosts" }
- uid: sec-user-unknown
title: "Unknown login account"
condition: C
data:
- refId: A
relativeTimeRange: { from: 900, to: 0 }
datasourceUid: prometheus
model: { refId: A, expr: "security_user_info{known=\"false\"}", instant: true, intervalMs: 30000, maxDataPoints: 43200 }
- refId: C
datasourceUid: __expr__
model: { refId: C, type: threshold, expression: A, conditions: [ { evaluator: { type: gt, params: [0] } } ] }
noDataState: OK
execErrState: Error
for: 0m
labels: { severity: critical }
annotations: { summary: "{{ $labels.host }}: account {{ $labels.user }} (uid {{ $labels.uid }}, {{ $labels.shell }}) is not in security_login_users" }
- uid: sec-group-member-unknown
title: "Unknown member of sudo or docker"
condition: C
data:
- refId: A
relativeTimeRange: { from: 900, to: 0 }
datasourceUid: prometheus
model: { refId: A, expr: "security_group_member_info{known=\"false\"}", instant: true, intervalMs: 30000, maxDataPoints: 43200 }
- refId: C
datasourceUid: __expr__
model: { refId: C, type: threshold, expression: A, conditions: [ { evaluator: { type: gt, params: [0] } } ] }
noDataState: OK
execErrState: Error
for: 0m
labels: { severity: critical }
annotations: { summary: "{{ $labels.host }}: {{ $labels.user }} is in group {{ $labels.group }}" }
- uid: sec-files-changed
title: "Access files changed"
condition: C
data:
- refId: A
relativeTimeRange: { from: 900, to: 0 }
datasourceUid: prometheus
model: { refId: A, expr: "changes(security_fileset_hash[15m])", instant: true, intervalMs: 30000, maxDataPoints: 43200 }
- refId: C
datasourceUid: __expr__
model: { refId: C, type: threshold, expression: A, conditions: [ { evaluator: { type: gt, params: [0] } } ] }
noDataState: OK
execErrState: Error
for: 0m
labels: { severity: warning }
annotations: { summary: "{{ $labels.host }}: a file in set {{ $labels.set }} changed (accounts, sudoers, sshd, wireguard or authorized_keys)" }
- uid: sec-port-unknown
title: "Unexpected listening port"
condition: C
data:
- refId: A
relativeTimeRange: { from: 900, to: 0 }
datasourceUid: prometheus
model: { refId: A, expr: "security_listening_port_info{known=\"false\"}", instant: true, intervalMs: 30000, maxDataPoints: 43200 }
- refId: C
datasourceUid: __expr__
model: { refId: C, type: threshold, expression: A, conditions: [ { evaluator: { type: gt, params: [0] } } ] }
noDataState: OK
execErrState: Error
for: 3m
labels: { severity: warning }
annotations: { summary: "{{ $labels.host }}: {{ $labels.process }} listens on {{ $labels.proto }}/{{ $labels.port }} ({{ $labels.scope }}), not in security_ports" }
- uid: sec-container-privileged
title: "Container with unexpected host access"
condition: C
data:
- refId: A
relativeTimeRange: { from: 900, to: 0 }
datasourceUid: prometheus
model: { refId: A, expr: "security_container_privileged_info{known=\"false\"}", instant: true, intervalMs: 30000, maxDataPoints: 43200 }
- refId: C
datasourceUid: __expr__
model: { refId: C, type: threshold, expression: A, conditions: [ { evaluator: { type: gt, params: [0] } } ] }
noDataState: OK
execErrState: Error
for: 0m
labels: { severity: critical }
annotations: { summary: "{{ $labels.host }}: container {{ $labels.name }} runs with {{ $labels.flags }}" }
- uid: sec-container-new
title: "New container"
condition: C
data:
- refId: A
relativeTimeRange: { from: 900, to: 0 }
datasourceUid: prometheus
model: { refId: A, expr: "group by (host, name) (container_last_seen{name!=\"\", name!~\"[a-z]+_[a-z]+\"}) unless on (host, name) group by (host, name) (max_over_time(container_last_seen{name!=\"\"}[7d] offset 30m))", instant: true, intervalMs: 30000, maxDataPoints: 43200 }
- refId: C
datasourceUid: __expr__
model: { refId: C, type: threshold, expression: A, conditions: [ { evaluator: { type: gt, params: [0] } } ] }
noDataState: OK
execErrState: Error
for: 0m
labels: { severity: warning }
annotations: { summary: "{{ $labels.host }}: container {{ $labels.name }} was not seen in the last 7 days" }
- uid: sec-forgejo-new
title: "Forgejo: new user, key or runner"
condition: C
data:
- refId: A
relativeTimeRange: { from: 900, to: 0 }
datasourceUid: prometheus
model: { refId: A, expr: "security_forgejo_objects{kind=~\"users|admins|ssh_keys|deploy_keys|runners\"} - security_forgejo_objects offset 15m", instant: true, intervalMs: 30000, maxDataPoints: 43200 }
- refId: C
datasourceUid: __expr__
model: { refId: C, type: threshold, expression: A, conditions: [ { evaluator: { type: gt, params: [0] } } ] }
noDataState: OK
execErrState: Error
for: 0m
labels: { severity: warning }
annotations: { summary: "Forgejo: {{ $labels.kind }} grew by {{ $values.A.Value | printf \"%.0f\" }}" }
- uid: sec-ssh-outside
title: "SSH login from outside WireGuard"
condition: C
data:
- refId: A
relativeTimeRange: { from: 300, to: 0 }
datasourceUid: loki
model: { refId: A, expr: "sum by (host, user, src) (count_over_time({job=\"journal\", unit=\"ssh.service\"} |~ `Accepted \\S+ for ` !~ `Accepted \\S+ for git from ` | regexp `Accepted \\S+ for (?P<user>\\S+) from (?P<src>\\S+)` | src !~ `10\\.20\\.0\\.\\d+|10\\.10\\.(\\d|1[0-5])\\.\\d+` [5m]))", queryType: instant, intervalMs: 60000, maxDataPoints: 43200 }
- refId: C
datasourceUid: __expr__
model: { refId: C, type: threshold, expression: A, conditions: [ { evaluator: { type: gt, params: [0] } } ] }
noDataState: OK
execErrState: Error
for: 0m
labels: { severity: critical }
annotations: { summary: "{{ $labels.host }}: {{ $labels.user }} logged in over SSH from {{ $labels.src }}" }
- uid: sec-ssh-failed-internal
title: "Failed SSH logins from inside"
condition: C
data:
- refId: A
relativeTimeRange: { from: 600, to: 0 }
datasourceUid: loki
model: { refId: A, expr: "sum by (host) (count_over_time({job=\"journal\", unit=\"ssh.service\"} |~ `Failed \\S+ for |Invalid user |Connection closed by (authenticating|invalid) user ` |~ ` (10\\.20\\.0\\.\\d+|10\\.10\\.(\\d|1[0-5])\\.\\d+) port ` [10m]))", queryType: instant, intervalMs: 60000, maxDataPoints: 43200 }
- refId: C
datasourceUid: __expr__
model: { refId: C, type: threshold, expression: A, conditions: [ { evaluator: { type: gt, params: [2] } } ] }
noDataState: OK
execErrState: Error
for: 0m
labels: { severity: warning }
annotations: { summary: "{{ $labels.host }}: {{ $values.A.Value | printf \"%.0f\" }} failed SSH logins from WireGuard or VPC addresses in 10 minutes" }
- uid: sec-ssh-failed-burst
title: "Failed SSH logins spike"
condition: C
data:
- refId: A
relativeTimeRange: { from: 600, to: 0 }
datasourceUid: loki
model: { refId: A, expr: "sum by (host) (count_over_time({job=\"journal\", unit=\"ssh.service\"} |~ `Failed \\S+ for |Invalid user |Connection closed by (authenticating|invalid) user ` [10m]))", queryType: instant, intervalMs: 60000, maxDataPoints: 43200 }
- refId: C
datasourceUid: __expr__
model: { refId: C, type: threshold, expression: A, conditions: [ { evaluator: { type: gt, params: [150] } } ] }
noDataState: OK
execErrState: Error
for: 0m
labels: { severity: warning }
annotations: { summary: "{{ $labels.host }}: {{ $values.A.Value | printf \"%.0f\" }} failed SSH logins in 10 minutes (usual: about 10)" }
- uid: sec-login-failed-forgejo
title: "Failed logins: Forgejo"
condition: C
data:
- refId: A
relativeTimeRange: { from: 600, to: 0 }
datasourceUid: loki
model: { refId: A, expr: "sum(count_over_time({container=\"forgejo\"} |= `Failed authentication attempt` [10m]))", queryType: instant, intervalMs: 60000, maxDataPoints: 43200 }
- refId: C
datasourceUid: __expr__
model: { refId: C, type: threshold, expression: A, conditions: [ { evaluator: { type: gt, params: [10] } } ] }
noDataState: OK
execErrState: Error
for: 0m
labels: { severity: warning }
annotations: { summary: "Forgejo: {{ $values.A.Value | printf \"%.0f\" }} failed logins in 10 minutes" }
- uid: sec-login-failed-grafana
title: "Failed logins: Grafana"
condition: C
data:
- refId: A
relativeTimeRange: { from: 600, to: 0 }
datasourceUid: loki
model: { refId: A, expr: "sum(count_over_time({job=\"traefik-access\"} |= `\"grafana@docker\"` |~ `\"POST /login HTTP/[0-9.]+\" 401 ` [10m]))", queryType: instant, intervalMs: 60000, maxDataPoints: 43200 }
- refId: C
datasourceUid: __expr__
model: { refId: C, type: threshold, expression: A, conditions: [ { evaluator: { type: gt, params: [4] } } ] }
noDataState: OK
execErrState: Error
for: 0m
labels: { severity: warning }
annotations: { summary: "Grafana: {{ $values.A.Value | printf \"%.0f\" }} failed logins in 10 minutes" }
- uid: sec-login-failed-asxpio
title: "Failed logins: asxp.io admin"
condition: C
data:
- refId: A
relativeTimeRange: { from: 600, to: 0 }
datasourceUid: loki
model: { refId: A, expr: "sum(count_over_time({job=\"traefik-access\"} |= `\"asxpio@docker\"` |~ `\"POST /admin/login HTTP/[0-9.]+\" (401|429) ` [10m]))", queryType: instant, intervalMs: 60000, maxDataPoints: 43200 }
- refId: C
datasourceUid: __expr__
model: { refId: C, type: threshold, expression: A, conditions: [ { evaluator: { type: gt, params: [4] } } ] }
noDataState: OK
execErrState: Error
for: 0m
labels: { severity: warning }
annotations: { summary: "asxp.io admin: {{ $values.A.Value | printf \"%.0f\" }} failed or rate-limited logins in 10 minutes" }
- uid: sec-logs-stopped
title: "Logs stopped arriving"
condition: C
data:
- refId: A
relativeTimeRange: { from: 900, to: 0 }
datasourceUid: prometheus
model: { refId: A, expr: "sum by (host) (rate(loki_write_sent_entries_total[10m]))", instant: true, intervalMs: 30000, maxDataPoints: 43200 }
- refId: C
datasourceUid: __expr__
model: { refId: C, type: threshold, expression: A, conditions: [ { evaluator: { type: lt, params: [0.001] } } ] }
noDataState: OK
execErrState: Error
for: 5m
labels: { severity: critical }
annotations: { summary: "Alloy on {{ $labels.host }} has sent Loki nothing for 10 minutes: every log-based alert is blind" }
- uid: sec-audit-stale
title: "Security metrics stale"
condition: C
data:
- refId: A
relativeTimeRange: { from: 900, to: 0 }
datasourceUid: prometheus
model: { refId: A, expr: "(time() - security_audit_last_run_timestamp_seconds > 600) or on (host) (up{job=\"node\"} == 1 unless on (host) security_audit_last_run_timestamp_seconds)", instant: true, intervalMs: 30000, maxDataPoints: 43200 }
- refId: C
datasourceUid: __expr__
model: { refId: C, type: threshold, expression: A, conditions: [ { evaluator: { type: gt, params: [0] } } ] }
noDataState: OK
execErrState: Error
for: 5m
labels: { severity: critical }
annotations: { summary: "security-metrics on {{ $labels.host }} has not written its file for 10 minutes, or the file is gone" }
- uid: sec-audit-check-failed
title: "Security check failing"
condition: C
data:
- refId: A
relativeTimeRange: { from: 900, to: 0 }
datasourceUid: prometheus
model: { refId: A, expr: "1 - security_audit_check_ok", instant: true, intervalMs: 30000, maxDataPoints: 43200 }
- refId: C
datasourceUid: __expr__
model: { refId: C, type: threshold, expression: A, conditions: [ { evaluator: { type: gt, params: [0] } } ] }
noDataState: OK
execErrState: Error
for: 5m
labels: { severity: warning }
annotations: { summary: "security-metrics on {{ $labels.host }}: check {{ $labels.check }} fails (journalctl -u security-metrics)" }
{% endraw %}

View file

@ -0,0 +1,53 @@
---
# Security baseline for security-metrics: what each host is expected to
# have. Anything else is exported with known="false" and alerts (rules in
# role monitoring). Per-host additions go in host_vars as *_extra.
# Accounts with a login shell
security_login_users: [root, asxpi, deploy, zerrtika]
security_login_users_extra: []
# Members of groups that amount to root
security_sudo_users: [asxpi, deploy, zerrtika]
security_docker_users: [asxpi, deploy, zerrtika]
security_docker_users_extra: []
# Addresses expected on the private network (.1 is Hetzner's gateway)
security_vpc_hosts:
- "{{ vpc_network.split('/')[0].rsplit('.', 1)[0] }}.1"
- "{{ asxpio_ops_vpc_ip }}"
- "{{ asxpio_services_vpc_ip }}"
# WireGuard peers: by the "### Client <name>" comment in the interface's
# conf (the server), or by public key -> name (a client)
security_wg_peer_names: []
security_wg_peer_keys: {}
# Listening sockets outside loopback: proto/port/process. port is a number,
# a range or *; process is the owner `ss -p` shows (empty for the kernel).
security_ports:
- tcp/22/sshd
- udp/68/dhclient
- "tcp/12345/alloy"
- "tcp/{{ monitoring_node_exporter_port }}/node_exporter"
- "tcp/{{ monitoring_cadvisor_port }}/cadvisor"
security_ports_extra: []
# Containers allowed host-level access: name (regex) -> flags, out of
# privileged, host-net, host-pid, host-root, docker-sock, cap-<NAME>
security_containers:
cadvisor: [privileged, host-net, host-root]
node-exporter: [host-net, host-pid, host-root]
alloy: [host-net, docker-sock]
security_containers_extra: {}
# Files whose change alerts, by set. authorized_keys files of every
# account are always watched (set ssh_keys).
security_filesets:
accounts: [/etc/passwd, /etc/shadow, /etc/group, /etc/gshadow]
sudoers: [/etc/sudoers, "/etc/sudoers.d/*"]
sshd: [/etc/ssh/sshd_config, "/etc/ssh/sshd_config.d/*"]
wireguard: ["/etc/wireguard/*.conf"]
# Forgejo's SQLite database, where this host runs Forgejo
security_forgejo_db: ""

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())

View file

@ -0,0 +1,9 @@
[Unit]
Description=Security state for Prometheus (node_exporter textfile)
After=docker.service
[Service]
Type=oneshot
ExecStart=/usr/local/sbin/security-metrics
# Runs every minute: keep "Starting/Finished" out of the journal
LogLevelMax=notice

View file

@ -0,0 +1,10 @@
[Unit]
Description=Security state for Prometheus, every minute
[Timer]
OnBootSec=1min
OnUnitActiveSec=1min
AccuracySec=5s
[Install]
WantedBy=timers.target

View file

@ -0,0 +1,4 @@
---
- name: Reload systemd
ansible.builtin.systemd:
daemon_reload: true

View file

@ -20,3 +20,36 @@
health_check_enabled: true
health_check_host: "{{ vpc_ip }}"
health_check_port: "{{ monitoring_node_exporter_port }}"
# Security state (WireGuard peers, private network, users, keys, ports,
# containers) as metrics; the baseline is in defaults and host_vars.
- name: Install security-metrics
ansible.builtin.copy:
src: security-metrics.py
dest: /usr/local/sbin/security-metrics
mode: "0700"
- name: Write the security baseline
ansible.builtin.template:
src: security-metrics.json.j2
dest: /etc/security-metrics.json
mode: "0600"
- name: Install the security-metrics units
ansible.builtin.copy:
src: "{{ item }}"
dest: "/etc/systemd/system/{{ item }}"
mode: "0644"
loop: [security-metrics.service, security-metrics.timer]
notify: Reload systemd
- name: Flush handlers
ansible.builtin.meta: flush_handlers
- name: Enable the security-metrics timer
ansible.builtin.systemd:
name: security-metrics.timer
enabled: true
state: started
# A dry run has not installed the unit yet
ignore_errors: "{{ ansible_check_mode }}"

View file

@ -0,0 +1,16 @@
{{ {
'textfile': monitoring_textfile_dir ~ '/security.prom',
'vpc_network': vpc_network,
'vpc_hosts': security_vpc_hosts,
'wg_peer_names': security_wg_peer_names,
'wg_peer_keys': security_wg_peer_keys,
'login_users': security_login_users + security_login_users_extra,
'groups': {
'sudo': security_sudo_users,
'docker': security_docker_users + security_docker_users_extra,
},
'ports': security_ports + security_ports_extra,
'containers': security_containers | combine(security_containers_extra),
'filesets': security_filesets,
'forgejo_db': security_forgejo_db,
} | to_nice_json }}