From 56dd0255dca8aae2da954b4f974e08b9ac4aeef8 Mon Sep 17 00:00:00 2001 From: Sergei Poljanski Date: Sun, 15 Nov 2026 21:59:16 +0400 Subject: [PATCH] monitoring: watch peers, devices, accounts and logins 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 --- README.md | 2 + ansible/README.md | 26 + ansible/inventory/host_vars/asxpio-ops.yaml | 15 + .../inventory/host_vars/asxpio-services.yaml | 28 + .../files/dashboards/Security/security.json | 2057 +++++++++++++++++ .../monitoring/templates/alert-rules.yaml.j2 | 314 ++- .../roles/monitoring_agent/defaults/main.yaml | 53 + .../files/security-metrics.py | 395 ++++ .../files/security-metrics.service | 9 + .../files/security-metrics.timer | 10 + .../roles/monitoring_agent/handlers/main.yaml | 4 + .../roles/monitoring_agent/tasks/main.yaml | 33 + .../templates/security-metrics.json.j2 | 16 + 13 files changed, 2961 insertions(+), 1 deletion(-) create mode 100644 ansible/roles/monitoring/files/dashboards/Security/security.json create mode 100644 ansible/roles/monitoring_agent/defaults/main.yaml create mode 100755 ansible/roles/monitoring_agent/files/security-metrics.py create mode 100644 ansible/roles/monitoring_agent/files/security-metrics.service create mode 100644 ansible/roles/monitoring_agent/files/security-metrics.timer create mode 100644 ansible/roles/monitoring_agent/handlers/main.yaml create mode 100644 ansible/roles/monitoring_agent/templates/security-metrics.json.j2 diff --git a/README.md b/README.md index b755f5d..2291331 100644 --- a/README.md +++ b/README.md @@ -40,6 +40,8 @@ Both are reachable for administration only over WireGuard | `xmpp` | services | ejabberd, apushd and tackygram for asxp.io; secrets stay in `/opt/xmpp/state` | | `acme_forward` | services | port 80: ACME challenges to Traefik on ops, 404 otherwise | | `xray` | services | Xray VLESS Reality on :443, config in the vault | +| `monitoring_agent` | both | node_exporter, cAdvisor, Alloy (logs to Loki); `security-metrics` timer | +| `monitoring` | ops | Prometheus, Loki, Grafana at gf.asxp.io (WireGuard only), dashboards and alert rules | | `restic_backup` | both | nightly restic backup to object storage, hel1 and fsn1 | | `s3_replicate` | services | daily copy of the hel1 buckets into their fsn1 twins | diff --git a/ansible/README.md b/ansible/README.md index 784bfcf..9983a0d 100644 --- a/ansible/README.md +++ b/ansible/README.md @@ -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 | diff --git a/ansible/inventory/host_vars/asxpio-ops.yaml b/ansible/inventory/host_vars/asxpio-ops.yaml index 089e44e..be25574 100644 --- a/ansible/inventory/host_vars/asxpio-ops.yaml +++ b/ansible/inventory/host_vars/asxpio-ops.yaml @@ -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] diff --git a/ansible/inventory/host_vars/asxpio-services.yaml b/ansible/inventory/host_vars/asxpio-services.yaml index 9cbeb2d..f15fbd4 100644 --- a/ansible/inventory/host_vars/asxpio-services.yaml +++ b/ansible/inventory/host_vars/asxpio-services.yaml @@ -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] diff --git a/ansible/roles/monitoring/files/dashboards/Security/security.json b/ansible/roles/monitoring/files/dashboards/Security/security.json new file mode 100644 index 0000000..a444b4b --- /dev/null +++ b/ansible/roles/monitoring/files/dashboards/Security/security.json @@ -0,0 +1,2057 @@ +{ + "uid": "asxpio-security", + "title": "Security", + "tags": [ + "asxpio", + "security" + ], + "timezone": "browser", + "editable": false, + "refresh": "1m", + "time": { + "from": "now-24h", + "to": "now" + }, + "schemaVersion": 39, + "graphTooltip": 1, + "links": [ + { + "title": "Dashboards", + "type": "dashboards", + "asDropdown": true, + "includeVars": false, + "keepTime": true, + "tags": [] + } + ], + "panels": [ + { + "type": "row", + "title": "Unexpected (each of these alerts)", + "collapsed": false, + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 0 + }, + "panels": [], + "id": 1 + }, + { + "type": "stat", + "title": "WireGuard peers", + "description": "Peers not in wireguard_clients", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "count(security_wg_peer_info{known=\"false\"}) or vector(0)", + "refId": "A", + "instant": true, + "range": false + } + ], + "gridPos": { + "h": 4, + "w": 3, + "x": 0, + "y": 1 + }, + "fieldConfig": { + "defaults": { + "color": { + "mode": "thresholds" + }, + "noValue": "0", + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + }, + { + "color": "red", + "value": 1 + } + ] + } + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "calcs": [ + "lastNotNull" + ], + "fields": "", + "values": false + }, + "colorMode": "background", + "graphMode": "none", + "textMode": "value" + }, + "id": 2 + }, + { + "type": "stat", + "title": "VPC devices", + "description": "Addresses answering ping on the private network, not in security_vpc_hosts", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "count(group by (ip) (security_vpc_host_info{known=\"false\"})) or vector(0)", + "refId": "A", + "instant": true, + "range": false + } + ], + "gridPos": { + "h": 4, + "w": 3, + "x": 3, + "y": 1 + }, + "fieldConfig": { + "defaults": { + "color": { + "mode": "thresholds" + }, + "noValue": "0", + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + }, + { + "color": "red", + "value": 1 + } + ] + } + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "calcs": [ + "lastNotNull" + ], + "fields": "", + "values": false + }, + "colorMode": "background", + "graphMode": "none", + "textMode": "value" + }, + "id": 3 + }, + { + "type": "stat", + "title": "Accounts", + "description": "Login accounts, and members of sudo or docker, outside the baseline", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "count(security_user_info{known=\"false\"} or security_group_member_info{known=\"false\"}) or vector(0)", + "refId": "A", + "instant": true, + "range": false + } + ], + "gridPos": { + "h": 4, + "w": 3, + "x": 6, + "y": 1 + }, + "fieldConfig": { + "defaults": { + "color": { + "mode": "thresholds" + }, + "noValue": "0", + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + }, + { + "color": "red", + "value": 1 + } + ] + } + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "calcs": [ + "lastNotNull" + ], + "fields": "", + "values": false + }, + "colorMode": "background", + "graphMode": "none", + "textMode": "value" + }, + "id": 4 + }, + { + "type": "stat", + "title": "Listening ports", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "count(security_listening_port_info{known=\"false\"}) or vector(0)", + "refId": "A", + "instant": true, + "range": false + } + ], + "gridPos": { + "h": 4, + "w": 3, + "x": 9, + "y": 1 + }, + "fieldConfig": { + "defaults": { + "color": { + "mode": "thresholds" + }, + "noValue": "0", + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + }, + { + "color": "red", + "value": 1 + } + ] + } + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "calcs": [ + "lastNotNull" + ], + "fields": "", + "values": false + }, + "colorMode": "background", + "graphMode": "none", + "textMode": "value" + }, + "id": 5 + }, + { + "type": "stat", + "title": "Containers", + "description": "Privileged, host network or PID, host root or the Docker socket, outside the baseline", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "count(security_container_privileged_info{known=\"false\"}) or vector(0)", + "refId": "A", + "instant": true, + "range": false + } + ], + "gridPos": { + "h": 4, + "w": 3, + "x": 12, + "y": 1 + }, + "fieldConfig": { + "defaults": { + "color": { + "mode": "thresholds" + }, + "noValue": "0", + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + }, + { + "color": "red", + "value": 1 + } + ] + } + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "calcs": [ + "lastNotNull" + ], + "fields": "", + "values": false + }, + "colorMode": "background", + "graphMode": "none", + "textMode": "value" + }, + "id": 6 + }, + { + "type": "stat", + "title": "File changes (24 h)", + "description": "accounts, sudoers, sshd, wireguard, authorized_keys", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum(changes(security_fileset_hash[24h]))", + "refId": "A", + "instant": true, + "range": false + } + ], + "gridPos": { + "h": 4, + "w": 3, + "x": 15, + "y": 1 + }, + "fieldConfig": { + "defaults": { + "color": { + "mode": "thresholds" + }, + "noValue": "0", + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + }, + { + "color": "orange", + "value": 1 + } + ] + } + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "calcs": [ + "lastNotNull" + ], + "fields": "", + "values": false + }, + "colorMode": "background", + "graphMode": "none", + "textMode": "value" + }, + "id": 7 + }, + { + "type": "stat", + "title": "SSH logins (24 h)", + "description": "", + "datasource": { + "type": "loki", + "uid": "loki" + }, + "targets": [ + { + "datasource": { + "type": "loki", + "uid": "loki" + }, + "expr": "sum(count_over_time({job=\"journal\", unit=\"ssh.service\"} |~ `Accepted \\S+ for ` [24h]))", + "refId": "A", + "instant": true, + "range": false, + "queryType": "instant" + } + ], + "gridPos": { + "h": 4, + "w": 3, + "x": 18, + "y": 1 + }, + "fieldConfig": { + "defaults": { + "color": { + "mode": "thresholds" + }, + "noValue": "0", + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "blue", + "value": null + } + ] + } + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "calcs": [ + "lastNotNull" + ], + "fields": "", + "values": false + }, + "colorMode": "background", + "graphMode": "none", + "textMode": "value" + }, + "id": 8 + }, + { + "type": "stat", + "title": "Failed SSH (24 h)", + "description": "", + "datasource": { + "type": "loki", + "uid": "loki" + }, + "targets": [ + { + "datasource": { + "type": "loki", + "uid": "loki" + }, + "expr": "sum(count_over_time({job=\"journal\", unit=\"ssh.service\"} |~ `Failed \\S+ for |Invalid user |Connection closed by (authenticating|invalid) user ` [24h]))", + "refId": "A", + "instant": true, + "range": false, + "queryType": "instant" + } + ], + "gridPos": { + "h": 4, + "w": 3, + "x": 21, + "y": 1 + }, + "fieldConfig": { + "defaults": { + "color": { + "mode": "thresholds" + }, + "noValue": "0", + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "blue", + "value": null + } + ] + } + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "calcs": [ + "lastNotNull" + ], + "fields": "", + "values": false + }, + "colorMode": "background", + "graphMode": "none", + "textMode": "value" + }, + "id": 9 + }, + { + "type": "row", + "title": "Networks", + "collapsed": false, + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 5 + }, + "panels": [], + "id": 10 + }, + { + "type": "table", + "title": "WireGuard peers", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "security_wg_peer_last_handshake_seconds * 1000 * on (host, interface, peer) group_left (allowed_ips, known) security_wg_peer_info", + "refId": "A", + "instant": true, + "range": false, + "format": "table" + } + ], + "gridPos": { + "h": 8, + "w": 10, + "x": 0, + "y": 6 + }, + "fieldConfig": { + "defaults": { + "custom": { + "filterable": true + } + }, + "overrides": [ + { + "matcher": { + "id": "byName", + "options": "known" + }, + "properties": [ + { + "id": "mappings", + "value": [ + { + "type": "value", + "options": { + "true": { + "text": "yes", + "color": "green" + }, + "false": { + "text": "NO", + "color": "red" + } + } + } + ] + }, + { + "id": "custom.cellOptions", + "value": { + "type": "color-background" + } + }, + { + "id": "custom.width", + "value": 80 + } + ] + }, + { + "matcher": { + "id": "byName", + "options": "Value" + }, + "properties": [ + { + "id": "displayName", + "value": "last handshake" + }, + { + "id": "unit", + "value": "dateTimeFromNow" + }, + { + "id": "mappings", + "value": [ + { + "type": "value", + "options": { + "0": { + "text": "never" + } + } + } + ] + } + ] + } + ] + }, + "transformations": [ + { + "id": "organize", + "options": { + "excludeByName": { + "Time": true, + "__name__": true, + "instance": true, + "job": true + }, + "indexByName": { + "host": 0, + "interface": 1, + "peer": 2, + "allowed_ips": 3, + "known": 4, + "Value": 5 + } + } + } + ], + "options": { + "showHeader": true, + "cellHeight": "sm" + }, + "id": 11 + }, + { + "type": "table", + "title": "WireGuard endpoints", + "description": "Where each peer last connected from. A network (/16) not seen for that peer in 14 days alerts.", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "security_wg_peer_endpoint_info", + "refId": "A", + "instant": true, + "range": false, + "format": "table" + } + ], + "gridPos": { + "h": 8, + "w": 7, + "x": 10, + "y": 6 + }, + "fieldConfig": { + "defaults": { + "custom": { + "filterable": true + } + }, + "overrides": [ + { + "matcher": { + "id": "byName", + "options": "known" + }, + "properties": [ + { + "id": "mappings", + "value": [ + { + "type": "value", + "options": { + "true": { + "text": "yes", + "color": "green" + }, + "false": { + "text": "NO", + "color": "red" + } + } + } + ] + }, + { + "id": "custom.cellOptions", + "value": { + "type": "color-background" + } + }, + { + "id": "custom.width", + "value": 80 + } + ] + }, + { + "matcher": { + "id": "byName", + "options": "Value" + }, + "properties": [ + { + "id": "custom.hidden", + "value": true + } + ] + } + ] + }, + "transformations": [ + { + "id": "organize", + "options": { + "excludeByName": { + "Time": true, + "__name__": true, + "instance": true, + "job": true + }, + "indexByName": { + "host": 0, + "peer": 1, + "endpoint": 2, + "net": 3 + } + } + } + ], + "options": { + "showHeader": true, + "cellHeight": "sm" + }, + "id": 12 + }, + { + "type": "table", + "title": "Private network (VPC) devices", + "description": "Ping sweep of the VPC from both hosts, every minute. A device that drops ICMP is not seen.", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "group by (ip, known) (security_vpc_host_info)", + "refId": "A", + "instant": true, + "range": false, + "format": "table" + } + ], + "gridPos": { + "h": 8, + "w": 7, + "x": 17, + "y": 6 + }, + "fieldConfig": { + "defaults": { + "custom": { + "filterable": true + } + }, + "overrides": [ + { + "matcher": { + "id": "byName", + "options": "known" + }, + "properties": [ + { + "id": "mappings", + "value": [ + { + "type": "value", + "options": { + "true": { + "text": "yes", + "color": "green" + }, + "false": { + "text": "NO", + "color": "red" + } + } + } + ] + }, + { + "id": "custom.cellOptions", + "value": { + "type": "color-background" + } + }, + { + "id": "custom.width", + "value": 80 + } + ] + }, + { + "matcher": { + "id": "byName", + "options": "Value" + }, + "properties": [ + { + "id": "custom.hidden", + "value": true + } + ] + } + ] + }, + "transformations": [ + { + "id": "organize", + "options": { + "excludeByName": { + "Time": true, + "__name__": true, + "instance": true, + "job": true + }, + "indexByName": { + "ip": 0, + "known": 1 + } + } + } + ], + "options": { + "showHeader": true, + "cellHeight": "sm" + }, + "id": 13 + }, + { + "type": "table", + "title": "Listening ports", + "description": "Outside loopback. Known entries show the allowlist entry (a range or *), others the port.", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "security_listening_port_info", + "refId": "A", + "instant": true, + "range": false, + "format": "table" + } + ], + "gridPos": { + "h": 9, + "w": 24, + "x": 0, + "y": 14 + }, + "fieldConfig": { + "defaults": { + "custom": { + "filterable": true + } + }, + "overrides": [ + { + "matcher": { + "id": "byName", + "options": "known" + }, + "properties": [ + { + "id": "mappings", + "value": [ + { + "type": "value", + "options": { + "true": { + "text": "yes", + "color": "green" + }, + "false": { + "text": "NO", + "color": "red" + } + } + } + ] + }, + { + "id": "custom.cellOptions", + "value": { + "type": "color-background" + } + }, + { + "id": "custom.width", + "value": 80 + } + ] + }, + { + "matcher": { + "id": "byName", + "options": "Value" + }, + "properties": [ + { + "id": "displayName", + "value": "sockets" + } + ] + } + ] + }, + "transformations": [ + { + "id": "organize", + "options": { + "excludeByName": { + "Time": true, + "__name__": true, + "instance": true, + "job": true + }, + "indexByName": { + "host": 0, + "scope": 1, + "proto": 2, + "port": 3, + "process": 4, + "known": 5, + "Value": 6 + } + } + } + ], + "options": { + "showHeader": true, + "cellHeight": "sm" + }, + "id": 14 + }, + { + "type": "row", + "title": "Accounts and keys", + "collapsed": false, + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 23 + }, + "panels": [], + "id": 15 + }, + { + "type": "table", + "title": "Login accounts", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "security_user_info", + "refId": "A", + "instant": true, + "range": false, + "format": "table" + } + ], + "gridPos": { + "h": 8, + "w": 8, + "x": 0, + "y": 24 + }, + "fieldConfig": { + "defaults": { + "custom": { + "filterable": true + } + }, + "overrides": [ + { + "matcher": { + "id": "byName", + "options": "known" + }, + "properties": [ + { + "id": "mappings", + "value": [ + { + "type": "value", + "options": { + "true": { + "text": "yes", + "color": "green" + }, + "false": { + "text": "NO", + "color": "red" + } + } + } + ] + }, + { + "id": "custom.cellOptions", + "value": { + "type": "color-background" + } + }, + { + "id": "custom.width", + "value": 80 + } + ] + }, + { + "matcher": { + "id": "byName", + "options": "Value" + }, + "properties": [ + { + "id": "custom.hidden", + "value": true + } + ] + } + ] + }, + "transformations": [ + { + "id": "organize", + "options": { + "excludeByName": { + "Time": true, + "__name__": true, + "instance": true, + "job": true + }, + "indexByName": { + "host": 0, + "user": 1, + "uid": 2, + "shell": 3, + "known": 4 + } + } + } + ], + "options": { + "showHeader": true, + "cellHeight": "sm" + }, + "id": 16 + }, + { + "type": "table", + "title": "sudo and docker members", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "security_group_member_info", + "refId": "A", + "instant": true, + "range": false, + "format": "table" + } + ], + "gridPos": { + "h": 8, + "w": 6, + "x": 8, + "y": 24 + }, + "fieldConfig": { + "defaults": { + "custom": { + "filterable": true + } + }, + "overrides": [ + { + "matcher": { + "id": "byName", + "options": "known" + }, + "properties": [ + { + "id": "mappings", + "value": [ + { + "type": "value", + "options": { + "true": { + "text": "yes", + "color": "green" + }, + "false": { + "text": "NO", + "color": "red" + } + } + } + ] + }, + { + "id": "custom.cellOptions", + "value": { + "type": "color-background" + } + }, + { + "id": "custom.width", + "value": 80 + } + ] + }, + { + "matcher": { + "id": "byName", + "options": "Value" + }, + "properties": [ + { + "id": "custom.hidden", + "value": true + } + ] + } + ] + }, + "transformations": [ + { + "id": "organize", + "options": { + "excludeByName": { + "Time": true, + "__name__": true, + "instance": true, + "job": true + }, + "indexByName": { + "host": 0, + "group": 1, + "user": 2, + "known": 3 + } + } + } + ], + "options": { + "showHeader": true, + "cellHeight": "sm" + }, + "id": 17 + }, + { + "type": "table", + "title": "authorized_keys", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "security_authorized_keys", + "refId": "A", + "instant": true, + "range": false, + "format": "table" + } + ], + "gridPos": { + "h": 8, + "w": 10, + "x": 14, + "y": 24 + }, + "fieldConfig": { + "defaults": { + "custom": { + "filterable": true + } + }, + "overrides": [ + { + "matcher": { + "id": "byName", + "options": "known" + }, + "properties": [ + { + "id": "mappings", + "value": [ + { + "type": "value", + "options": { + "true": { + "text": "yes", + "color": "green" + }, + "false": { + "text": "NO", + "color": "red" + } + } + } + ] + }, + { + "id": "custom.cellOptions", + "value": { + "type": "color-background" + } + }, + { + "id": "custom.width", + "value": 80 + } + ] + }, + { + "matcher": { + "id": "byName", + "options": "Value" + }, + "properties": [ + { + "id": "displayName", + "value": "keys" + } + ] + } + ] + }, + "transformations": [ + { + "id": "organize", + "options": { + "excludeByName": { + "Time": true, + "__name__": true, + "instance": true, + "job": true + }, + "indexByName": { + "host": 0, + "user": 1, + "file": 2, + "Value": 3 + } + } + } + ], + "options": { + "showHeader": true, + "cellHeight": "sm" + }, + "id": 18 + }, + { + "type": "table", + "title": "Watched files: last change", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "security_fileset_mtime_seconds * 1000", + "refId": "A", + "instant": true, + "range": false, + "format": "table" + } + ], + "gridPos": { + "h": 7, + "w": 8, + "x": 0, + "y": 32 + }, + "fieldConfig": { + "defaults": { + "custom": { + "filterable": true + } + }, + "overrides": [ + { + "matcher": { + "id": "byName", + "options": "known" + }, + "properties": [ + { + "id": "mappings", + "value": [ + { + "type": "value", + "options": { + "true": { + "text": "yes", + "color": "green" + }, + "false": { + "text": "NO", + "color": "red" + } + } + } + ] + }, + { + "id": "custom.cellOptions", + "value": { + "type": "color-background" + } + }, + { + "id": "custom.width", + "value": 80 + } + ] + }, + { + "matcher": { + "id": "byName", + "options": "Value" + }, + "properties": [ + { + "id": "displayName", + "value": "changed" + }, + { + "id": "unit", + "value": "dateTimeFromNow" + }, + { + "id": "mappings", + "value": [ + { + "type": "value", + "options": { + "0": { + "text": "never" + } + } + } + ] + } + ] + } + ] + }, + "transformations": [ + { + "id": "organize", + "options": { + "excludeByName": { + "Time": true, + "__name__": true, + "instance": true, + "job": true + }, + "indexByName": { + "host": 0, + "set": 1, + "Value": 2 + } + } + } + ], + "options": { + "showHeader": true, + "cellHeight": "sm" + }, + "id": 19 + }, + { + "type": "table", + "title": "Open sessions", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "security_sessions", + "refId": "A", + "instant": true, + "range": false, + "format": "table" + } + ], + "gridPos": { + "h": 7, + "w": 6, + "x": 8, + "y": 32 + }, + "fieldConfig": { + "defaults": { + "custom": { + "filterable": true + } + }, + "overrides": [ + { + "matcher": { + "id": "byName", + "options": "known" + }, + "properties": [ + { + "id": "mappings", + "value": [ + { + "type": "value", + "options": { + "true": { + "text": "yes", + "color": "green" + }, + "false": { + "text": "NO", + "color": "red" + } + } + } + ] + }, + { + "id": "custom.cellOptions", + "value": { + "type": "color-background" + } + }, + { + "id": "custom.width", + "value": 80 + } + ] + }, + { + "matcher": { + "id": "byName", + "options": "Value" + }, + "properties": [ + { + "id": "displayName", + "value": "sessions" + } + ] + } + ] + }, + "transformations": [ + { + "id": "organize", + "options": { + "excludeByName": { + "Time": true, + "__name__": true, + "instance": true, + "job": true + }, + "indexByName": { + "host": 0, + "user": 1, + "origin": 2, + "Value": 3 + } + } + } + ], + "options": { + "showHeader": true, + "cellHeight": "sm" + }, + "id": 20 + }, + { + "type": "table", + "title": "Containers with host access", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "security_container_privileged_info", + "refId": "A", + "instant": true, + "range": false, + "format": "table" + } + ], + "gridPos": { + "h": 7, + "w": 10, + "x": 14, + "y": 32 + }, + "fieldConfig": { + "defaults": { + "custom": { + "filterable": true + } + }, + "overrides": [ + { + "matcher": { + "id": "byName", + "options": "known" + }, + "properties": [ + { + "id": "mappings", + "value": [ + { + "type": "value", + "options": { + "true": { + "text": "yes", + "color": "green" + }, + "false": { + "text": "NO", + "color": "red" + } + } + } + ] + }, + { + "id": "custom.cellOptions", + "value": { + "type": "color-background" + } + }, + { + "id": "custom.width", + "value": 80 + } + ] + }, + { + "matcher": { + "id": "byName", + "options": "Value" + }, + "properties": [ + { + "id": "custom.hidden", + "value": true + } + ] + } + ] + }, + "transformations": [ + { + "id": "organize", + "options": { + "excludeByName": { + "Time": true, + "__name__": true, + "instance": true, + "job": true + }, + "indexByName": { + "host": 0, + "name": 1, + "flags": 2, + "known": 3 + } + } + } + ], + "options": { + "showHeader": true, + "cellHeight": "sm" + }, + "id": 21 + }, + { + "type": "row", + "title": "SSH", + "collapsed": false, + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 39 + }, + "panels": [], + "id": 22 + }, + { + "type": "timeseries", + "title": "Logins by user and source", + "datasource": { + "type": "loki", + "uid": "loki" + }, + "targets": [ + { + "datasource": { + "type": "loki", + "uid": "loki" + }, + "expr": "sum by (host, user, src) (count_over_time({job=\"journal\", unit=\"ssh.service\"} |~ `Accepted \\S+ for ` | regexp `Accepted \\S+ for (?P\\S+) from (?P\\S+)` [$__interval]))", + "legendFormat": "{{host}}: {{user}} from {{src}}", + "refId": "A", + "instant": false, + "range": true + } + ], + "gridPos": { + "h": 7, + "w": 12, + "x": 0, + "y": 40 + }, + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "bars", + "fillOpacity": 60, + "stacking": { + "mode": "normal" + } + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "id": 23 + }, + { + "type": "timeseries", + "title": "Failed logins", + "datasource": { + "type": "loki", + "uid": "loki" + }, + "targets": [ + { + "datasource": { + "type": "loki", + "uid": "loki" + }, + "expr": "sum by (host) (count_over_time({job=\"journal\", unit=\"ssh.service\"} |~ `Failed \\S+ for |Invalid user |Connection closed by (authenticating|invalid) user ` [$__interval]))", + "legendFormat": "{{host}}", + "refId": "A", + "instant": false, + "range": true + } + ], + "gridPos": { + "h": 7, + "w": 12, + "x": 12, + "y": 40 + }, + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "bars", + "fillOpacity": 60, + "stacking": { + "mode": "normal" + } + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "id": 24 + }, + { + "type": "logs", + "title": "Logins", + "datasource": { + "type": "loki", + "uid": "loki" + }, + "targets": [ + { + "datasource": { + "type": "loki", + "uid": "loki" + }, + "expr": "{job=\"journal\", unit=\"ssh.service\"} |~ `Accepted \\S+ for `", + "refId": "A", + "instant": false, + "range": true + } + ], + "gridPos": { + "h": 9, + "w": 12, + "x": 0, + "y": 47 + }, + "options": { + "showTime": true, + "showLabels": false, + "wrapLogMessage": true, + "sortOrder": "Descending", + "enableLogDetails": true + }, + "id": 25 + }, + { + "type": "logs", + "title": "sudo, su and account changes", + "datasource": { + "type": "loki", + "uid": "loki" + }, + "targets": [ + { + "datasource": { + "type": "loki", + "uid": "loki" + }, + "expr": "{job=\"journal\"} |~ `sudo:.*COMMAND|su\\[\\d+\\]|useradd|usermod|userdel|groupadd|gpasswd|chpasswd|passwd\\[\\d+\\]`", + "refId": "A", + "instant": false, + "range": true + } + ], + "gridPos": { + "h": 9, + "w": 12, + "x": 12, + "y": 47 + }, + "options": { + "showTime": true, + "showLabels": false, + "wrapLogMessage": true, + "sortOrder": "Descending", + "enableLogDetails": true + }, + "id": 26 + }, + { + "type": "row", + "title": "Forgejo and web logins", + "collapsed": false, + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 56 + }, + "panels": [], + "id": 27 + }, + { + "type": "stat", + "title": "Forgejo", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "description": "Growth in users, admins, keys or runners alerts.", + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "security_forgejo_objects", + "legendFormat": "{{kind}}", + "refId": "A", + "instant": true, + "range": false + } + ], + "gridPos": { + "h": 7, + "w": 8, + "x": 0, + "y": 57 + }, + "fieldConfig": { + "defaults": { + "color": { + "mode": "fixed", + "fixedColor": "blue" + } + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "calcs": [ + "lastNotNull" + ], + "fields": "", + "values": false + }, + "colorMode": "value", + "graphMode": "none", + "textMode": "value_and_name" + }, + "id": 28 + }, + { + "type": "timeseries", + "title": "Failed web logins", + "datasource": { + "type": "loki", + "uid": "loki" + }, + "targets": [ + { + "datasource": { + "type": "loki", + "uid": "loki" + }, + "expr": "sum(count_over_time({container=\"forgejo\"} |= `Failed authentication attempt` [$__interval]))", + "legendFormat": "Forgejo", + "refId": "A", + "instant": false, + "range": true + }, + { + "datasource": { + "type": "loki", + "uid": "loki" + }, + "expr": "sum(count_over_time({job=\"traefik-access\"} |= `\"grafana@docker\"` |~ `\"POST /login HTTP/[0-9.]+\" 401 ` [$__interval]))", + "legendFormat": "Grafana", + "refId": "B", + "instant": false, + "range": true + }, + { + "datasource": { + "type": "loki", + "uid": "loki" + }, + "expr": "sum(count_over_time({job=\"traefik-access\"} |= `\"asxpio@docker\"` |~ `\"POST /admin/login HTTP/[0-9.]+\" (401|429) ` [$__interval]))", + "legendFormat": "asxp.io admin", + "refId": "C", + "instant": false, + "range": true + } + ], + "gridPos": { + "h": 7, + "w": 16, + "x": 8, + "y": 57 + }, + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "bars", + "fillOpacity": 60, + "stacking": { + "mode": "normal" + } + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "id": 29 + }, + { + "type": "logs", + "title": "Failed web logins", + "datasource": { + "type": "loki", + "uid": "loki" + }, + "targets": [ + { + "datasource": { + "type": "loki", + "uid": "loki" + }, + "expr": "{container=\"forgejo\"} |= `Failed authentication attempt`", + "refId": "A", + "instant": false, + "range": true + }, + { + "datasource": { + "type": "loki", + "uid": "loki" + }, + "expr": "{job=\"traefik-access\"} |~ `\"POST /(admin/)?login HTTP/[0-9.]+\" (401|429) `", + "refId": "B", + "instant": false, + "range": true + } + ], + "gridPos": { + "h": 8, + "w": 24, + "x": 0, + "y": 64 + }, + "options": { + "showTime": true, + "showLabels": false, + "wrapLogMessage": true, + "sortOrder": "Descending", + "enableLogDetails": true + }, + "id": 30 + } + ] +} \ No newline at end of file diff --git a/ansible/roles/monitoring/templates/alert-rules.yaml.j2 b/ansible/roles/monitoring/templates/alert-rules.yaml.j2 index c6fb8ca..7503382 100644 --- a/ansible/roles/monitoring/templates/alert-rules.yaml.j2 +++ b/ansible/roles/monitoring/templates/alert-rules.yaml.j2 @@ -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\\S+) from (?P\\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 %} diff --git a/ansible/roles/monitoring_agent/defaults/main.yaml b/ansible/roles/monitoring_agent/defaults/main.yaml new file mode 100644 index 0000000..b5cdc8a --- /dev/null +++ b/ansible/roles/monitoring_agent/defaults/main.yaml @@ -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 " 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- +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: "" diff --git a/ansible/roles/monitoring_agent/files/security-metrics.py b/ansible/roles/monitoring_agent/files/security-metrics.py new file mode 100755 index 0000000..8e03f99 --- /dev/null +++ b/ansible/roles/monitoring_agent/files/security-metrics.py @@ -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 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 ' 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()) diff --git a/ansible/roles/monitoring_agent/files/security-metrics.service b/ansible/roles/monitoring_agent/files/security-metrics.service new file mode 100644 index 0000000..2c8f864 --- /dev/null +++ b/ansible/roles/monitoring_agent/files/security-metrics.service @@ -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 diff --git a/ansible/roles/monitoring_agent/files/security-metrics.timer b/ansible/roles/monitoring_agent/files/security-metrics.timer new file mode 100644 index 0000000..1a245ec --- /dev/null +++ b/ansible/roles/monitoring_agent/files/security-metrics.timer @@ -0,0 +1,10 @@ +[Unit] +Description=Security state for Prometheus, every minute + +[Timer] +OnBootSec=1min +OnUnitActiveSec=1min +AccuracySec=5s + +[Install] +WantedBy=timers.target diff --git a/ansible/roles/monitoring_agent/handlers/main.yaml b/ansible/roles/monitoring_agent/handlers/main.yaml new file mode 100644 index 0000000..c28484f --- /dev/null +++ b/ansible/roles/monitoring_agent/handlers/main.yaml @@ -0,0 +1,4 @@ +--- +- name: Reload systemd + ansible.builtin.systemd: + daemon_reload: true diff --git a/ansible/roles/monitoring_agent/tasks/main.yaml b/ansible/roles/monitoring_agent/tasks/main.yaml index 66d7283..f38bf71 100644 --- a/ansible/roles/monitoring_agent/tasks/main.yaml +++ b/ansible/roles/monitoring_agent/tasks/main.yaml @@ -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 }}" diff --git a/ansible/roles/monitoring_agent/templates/security-metrics.json.j2 b/ansible/roles/monitoring_agent/templates/security-metrics.json.j2 new file mode 100644 index 0000000..89b8853 --- /dev/null +++ b/ansible/roles/monitoring_agent/templates/security-metrics.json.j2 @@ -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 }}