Files
loki/scripts/hetzner/sync-infra.sh
CatoandClaude Fable 5.1 df113dc811 feat(security): threat detection for the box, the GitHub org and the laptop (#708)
A 2026-09-14 posture audit found the box well guarded (default-deny ufw,
keys-only SSH, fail2ban, unattended upgrades, offsite restic) but blind: no
intrusion or integrity detection at all, and the GitHub org with secret
scanning off on all 48 repos and every marketplace action allowed with the
box's root SSH key in an org secret. This adds the detection layer on the
existing alert channel, so a break-in becomes one Telegram message within
five minutes instead of a discovery months later.

- install-security-watch.sh: security-check.sh (5-min timer) alerts on
  CHANGE only — guards down, sshd drift, edits to the files an intruder
  touches (sshd/sudoers/authorized_keys/cron/PAM/ld.so.preload/Caddy/ufw/
  monitoring/units), new internet-facing ports, new privileged accounts,
  SSH logins from never-seen IPs that are not GitHub runners, processes
  from /tmp or miners, new setuid binaries, new containers, stale offsite
  backup, week-old pending reboot. Baselines seed silently; one grouped
  message per tick; every message ends with what to do.
- github-security-check.sh (daily): new secret-scanning alert, new critical
  dependency alert, repo turning public, new member/collaborator/deploy
  key, Actions allowlist loosened. Every API call guarded: a failed call
  skips its check and keeps the baseline (the first version paged an error
  body as a policy change, and a wiped baseline would flood "new" next day).
- Caddy JSON access log on every vhost (snippet + sync-infra template) and
  a fail2ban caddy-scan jail: 8 probes for /.env, /.git, wp-login, cgi-bin
  … in 10 min = 24h ban. Proven by scanning orangecat.ch from the laptop
  (tenth request refused); a real scanner was banned within minutes.
- sshd drop-in: 3 tries, no X11, dead-peer detection, AllowUsers root ubuntu.
- scripts/local/laptop-security-check (user timer, 30 min): new network
  listener, sshd running, screen lock off, upgrades off, ~/.ssh changes,
  new login account, gh identity change, week-old reboot; delivered through
  the box's lib-alert over SSH, desktop notification as fallback.
- test-security-check.sh (test:ops): 39 assertions extracting the shipped
  heredocs; the property under test is "speaks once on change, never when
  nothing changed".
- docs/telegram-notifications.md: every new message registered.

Applied outside the repo in the same session: secret scanning + push
protection on 41/44 active repos (3 private repos are not eligible on the
plan) and as org defaults; Dependabot alerts + automated security fixes on
all 44; org Actions policy = GitHub-owned + verified + an explicit allowlist
of the 11 third-party actions the fleet uses.


Claude-Session: https://claude.ai/code/session_01G6ax7X9GfarifcZUiqsVJm

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-14 04:29:11 -07:00

125 lines
4.9 KiB
Bash

#!/usr/bin/env bash
# Generate + push systemd units, launch scripts, and Caddy vhosts for every
# app in apps.conf. Idempotent. Does NOT touch the four pre-existing services
# (bridge, loki, orangecat, evig) or any /opt/<app>/.env.
# Usage: sync-infra.sh [app ...] (no args = all)
source "$(dirname "${BASH_SOURCE[0]}")/lib.sh"
apps=("$@")
[ ${#apps[@]} -eq 0 ] && mapfile -t apps < <(app_names)
# One-time: Caddy import dir + import line
box 'sudo mkdir -p /etc/caddy/apps.d
grep -q "import apps.d" /etc/caddy/Caddyfile || \
echo "import apps.d/*.caddy" | sudo tee -a /etc/caddy/Caddyfile >/dev/null'
for app in "${apps[@]}"; do
app_lookup "$app"
echo "=== sync $NAME (port $PORT) ==="
launch=$(sed "s|__PORT__|$PORT|g" "$(dirname "${BASH_SOURCE[0]}")/launch.sh.tmpl")
# Unquoted heredoc on purpose ($NAME expands). That makes every backtick in
# it a command substitution run HERE: two comments once quoted "systemctl
# reset-failed" and "systemctl restart" in backticks, and every sync ran both
# on the machine doing the sync — polkit refusals on the box, silent on a
# laptop. test-register-site.sh keeps this file backtick-free.
unit=$(cat <<EOF
[Unit]
Description=$NAME application server (self-hosted, generated by sync-infra.sh)
After=network-online.target postgresql.service
Wants=network-online.target
# Never enter the start-limit "failed" lockout: a crash-looping app should keep
# retrying (Restart=on-failure) instead of staying down until a manual
# systemctl reset-failed.
StartLimitIntervalSec=0
# Any failure fires an instant Telegram (see install-host-alerts.sh). Wired here
# so a newly-synced app is alertable from its first boot, not only after a
# separate install-host-alerts run.
#
# MUST be in [Unit]. systemd ignores OnFailure in [Service] — it logs "Unknown
# key 'OnFailure' in section [Service], ignoring" and carries on, so the unit
# looks fine and simply never alerts. It sat in [Service] until 2026-09-11, and
# the effect was exactly what the comment above promises it prevents: 10 of 28
# app units had NO failure alerting, every one of them created after the last
# install-host-alerts run, which is the only other thing that wires it.
OnFailure=notify-failure@%n.service
[Service]
Type=simple
User=ubuntu
WorkingDirectory=/opt/$NAME/app
ExecStart=/opt/$NAME/app/launch.sh
Restart=on-failure
RestartSec=3
# Bound the stop phase so a systemctl restart can't block on a slow-draining
# Next process (default 90s). KillMode=mixed SIGTERMs the main proc then SIGKILLs
# the cgroup, freeing the port fast for the new process.
#
# 3s, not 15: a Next standalone server closes its listener on SIGTERM and then
# waits on keep-alive connections the proxy never closes, so the drain never
# finishes and the whole timeout is served as 502s. Measured on loki
# (2026-08-14): ~13s of refused connections per deploy. Cut the wait; the
# matching lb_try_duration below hides what is left.
TimeoutStopSec=3
KillMode=mixed
# Memory ceiling: a leaking/runaway Next process is OOM-killed (and restarted)
# alone instead of taking the whole small box down. MemoryHigh throttles first.
MemoryMax=1G
MemoryHigh=768M
StandardOutput=journal
StandardError=journal
[Install]
WantedBy=multi-user.target
EOF
)
box "sudo mkdir -p /opt/$NAME/app && sudo chown -R ubuntu:ubuntu /opt/$NAME
cat > /opt/$NAME/app/launch.sh <<'LAUNCH_EOF'
$launch
LAUNCH_EOF
chmod +x /opt/$NAME/app/launch.sh
sudo tee /etc/systemd/system/$NAME-app.service >/dev/null <<'UNIT_EOF'
$unit
UNIT_EOF
sudo systemctl daemon-reload && sudo systemctl enable $NAME-app >/dev/null 2>&1"
if [ "$DOMAINS" != "-" ]; then
caddy_domains="${DOMAINS//,/, }"
vhost=$(cat <<EOF
$caddy_domains {
import access_log
encode zstd gzip
handle_path /uploads/* {
root * /opt/$NAME/uploads
file_server
}
reverse_proxy 127.0.0.1:$PORT {
flush_interval -1
# Re-dial across a restart instead of returning 502 the moment the upstream
# refuses. A deploy takes the port down for a few seconds; without this that
# window is served to users as errors. Only the dial is retried, so a request
# that already reached the app is never replayed.
lb_try_duration 20s
lb_try_interval 250ms
}
}
EOF
)
box "sudo tee /etc/caddy/apps.d/$NAME.caddy >/dev/null <<'CADDY_EOF'
$vhost
CADDY_EOF
sudo mkdir -p /opt/$NAME/uploads && sudo chown ubuntu:ubuntu /opt/$NAME/uploads"
fi
done
box 'sudo caddy validate --config /etc/caddy/Caddyfile >/dev/null && sudo systemctl reload caddy && echo "caddy reloaded OK"'
# Keep the watchdog's monitored targets in lockstep with apps.conf. targets.conf
# is SSOT-derived from apps.conf, but by a SEPARATE script — so a newly-synced
# public app was NOT monitored until someone re-ran install-watchdog by hand.
# solon was deployed but never added to targets → externally dark for weeks with
# no alert (2026-07). Refreshing here makes "provisioned" imply "monitored".
bash "$HERE/install-watchdog.sh"