#!/usr/bin/env bash # Tloto VPS hardening bootstrap (Phase B host). # Run as root on a fresh Ubuntu/Debian VPS BEFORE cutting password/root SSH. # # Usage: # export DEPLOY_SSH_PUBKEY='ssh-ed25519 AAAA... comment' # # optional: SKIP_SSH_LOCK=1 → configure user/firewall/docker but keep password SSH # # optional: SKIP_DOCKER=1 / SKIP_POSTGRES=1 # bash harden-vps.sh # # Safety: refuses to disable PasswordAuthentication / PermitRootLogin until # ~deploy/.ssh/authorized_keys contains a valid pubkey. set -euo pipefail DEPLOY_USER="${DEPLOY_USER:-deploy}" SSH_DROPIN="/etc/ssh/sshd_config.d/99-tloto.conf" SYSCTL_DROPIN="/etc/sysctl.d/99-tloto-harden.conf" MARKER_DIR="/var/lib/tloto-harden" mkdir -p "$MARKER_DIR" log() { printf '\n==> %s\n' "$*"; } die() { printf 'ERROR: %s\n' "$*" >&2; exit 1; } [[ "$(id -u)" -eq 0 ]] || die "Run as root." if [[ -r /etc/os-release ]]; then # shellcheck source=/dev/null . /etc/os-release case "${ID:-}" in ubuntu|debian) ;; *) die "Unsupported OS (${ID:-unknown}). Use Ubuntu 22.04/24.04 or Debian 12." ;; esac else die "Cannot read /etc/os-release" fi export DEBIAN_FRONTEND=noninteractive # --------------------------------------------------------------------------- # 0) Packages # --------------------------------------------------------------------------- log "Installing base packages" apt-get update -y apt-get install -y \ ca-certificates curl gnupg git ufw fail2ban \ unattended-upgrades apt-listchanges \ postgresql postgresql-contrib \ software-properties-common # --------------------------------------------------------------------------- # 1) deploy user + SSH key (MUST succeed before SSH lock) # --------------------------------------------------------------------------- log "Ensuring user ${DEPLOY_USER}" if ! id -u "$DEPLOY_USER" >/dev/null 2>&1; then adduser --disabled-password --gecos "Tloto deploy" "$DEPLOY_USER" fi usermod -aG sudo "$DEPLOY_USER" install -d -m 700 -o "$DEPLOY_USER" -g "$DEPLOY_USER" "/home/${DEPLOY_USER}/.ssh" AUTH_KEYS="/home/${DEPLOY_USER}/.ssh/authorized_keys" touch "$AUTH_KEYS" chown "$DEPLOY_USER:$DEPLOY_USER" "$AUTH_KEYS" chmod 600 "$AUTH_KEYS" PUBKEY="${DEPLOY_SSH_PUBKEY:-}" if [[ -z "$PUBKEY" && -f /root/.ssh/authorized_keys ]]; then # Prefer first non-comment line from root keys if present PUBKEY="$(grep -E '^(ssh-(ed25519|rsa)|ecdsa-sha2)' /root/.ssh/authorized_keys | head -n1 || true)" fi if [[ -z "$PUBKEY" && -f /root/tloto_deploy.pub ]]; then PUBKEY="$(tr -d '\r' /dev/null; then echo "$PUBKEY" >>"$AUTH_KEYS" log "Installed deploy SSH public key" else log "Deploy SSH public key already present" fi else log "WARNING: No DEPLOY_SSH_PUBKEY / root authorized_keys / /root/tloto_deploy.pub" log "Add a key before SSH lock, e.g.:" log " echo 'ssh-ed25519 AAAA... you@pc' >> ${AUTH_KEYS}" fi chown "$DEPLOY_USER:$DEPLOY_USER" "$AUTH_KEYS" chmod 600 "$AUTH_KEYS" chmod 700 "/home/${DEPLOY_USER}/.ssh" # passwordless sudo for deploy (ops convenience on single-admin VPS) SUDOERS_FILE="/etc/sudoers.d/99-${DEPLOY_USER}-tloto" cat >"$SUDOERS_FILE" </dev/null ufw default deny incoming ufw default allow outgoing ufw allow OpenSSH ufw allow 9080/tcp comment 'Tloto HTTP' ufw allow 9443/tcp comment 'Tloto HTTPS' # Docker → host Postgres via host.docker.internal (never open 5432 to Anywhere) ufw allow from 172.16.0.0/12 to any port 5432 proto tcp comment 'Docker to Postgres' ufw allow in on docker0 to any port 5432 proto tcp comment 'docker0 to PG' || true # Explicitly never needed publicly (deny is default; document intent): # 5432 Postgres, 6379 Redis, 4000/4001 app ports ufw --force enable ufw status verbose # --------------------------------------------------------------------------- # 3) fail2ban # --------------------------------------------------------------------------- log "Configuring fail2ban (sshd)" cat >/etc/fail2ban/jail.d/sshd-tloto.local <<'EOF' [sshd] enabled = true port = ssh filter = sshd backend = systemd maxretry = 4 findtime = 10m bantime = 1h EOF systemctl enable --now fail2ban systemctl restart fail2ban # --------------------------------------------------------------------------- # 4) unattended-upgrades # --------------------------------------------------------------------------- log "Enabling unattended security upgrades" apt-get install -y unattended-upgrades cat >/etc/apt/apt.conf.d/20auto-upgrades <<'EOF' APT::Periodic::Update-Package-Lists "1"; APT::Periodic::Unattended-Upgrade "1"; APT::Periodic::Download-Upgradeable-Packages "1"; APT::Periodic::AutocleanInterval "7"; EOF # Keep defaults from 50unattended-upgrades (security pocket) dpkg-reconfigure -f noninteractive unattended-upgrades || true # --------------------------------------------------------------------------- # 5) sysctl harden # --------------------------------------------------------------------------- log "Applying sysctl hardening" cat >"$SYSCTL_DROPIN" <<'EOF' # Tloto host network hardening net.ipv4.conf.all.rp_filter = 1 net.ipv4.conf.default.rp_filter = 1 net.ipv4.icmp_echo_ignore_broadcasts = 1 net.ipv4.conf.all.accept_source_route = 0 net.ipv4.conf.default.accept_source_route = 0 net.ipv4.conf.all.accept_redirects = 0 net.ipv4.conf.default.accept_redirects = 0 net.ipv4.conf.all.send_redirects = 0 net.ipv4.conf.default.send_redirects = 0 net.ipv4.tcp_syncookies = 1 net.ipv6.conf.all.accept_redirects = 0 net.ipv6.conf.default.accept_redirects = 0 EOF sysctl --system >/dev/null # --------------------------------------------------------------------------- # 6) Docker # --------------------------------------------------------------------------- if [[ "${SKIP_DOCKER:-0}" != "1" ]]; then log "Installing Docker Engine + Compose plugin" if ! command -v docker >/dev/null 2>&1; then curl -fsSL https://get.docker.com | sh fi usermod -aG docker "$DEPLOY_USER" systemctl enable --now docker docker --version docker compose version || true else log "SKIP_DOCKER=1 — skipping Docker install" fi # --------------------------------------------------------------------------- # 7) PostgreSQL localhost-only # --------------------------------------------------------------------------- if [[ "${SKIP_POSTGRES:-0}" != "1" ]]; then log "Hardening PostgreSQL (listen localhost only)" systemctl enable --now postgresql PG_CONF="$(ls /etc/postgresql/*/main/postgresql.conf 2>/dev/null | head -n1 || true)" PG_HBA="$(ls /etc/postgresql/*/main/pg_hba.conf 2>/dev/null | head -n1 || true)" [[ -n "$PG_CONF" && -n "$PG_HBA" ]] || die "PostgreSQL config not found" if grep -qE '^\s*listen_addresses\s*=' "$PG_CONF"; then sed -i -E "s/^\s*listen_addresses\s*=.*/listen_addresses = 'localhost'/" "$PG_CONF" else echo "listen_addresses = 'localhost'" >>"$PG_CONF" fi # Prefer scram for local/md5 connections where password auth is used if ! grep -q 'scram-sha-256' "$PG_HBA"; then sed -i -E 's/^(local\s+all\s+all\s+)peer/\1peer/' "$PG_HBA" || true # Do not rewrite entire hba; ensure no 0.0.0.0 host lines without comment fi systemctl restart postgresql # Verify not listening publicly (best-effort) if command -v ss >/dev/null 2>&1; then if ss -tlnp | grep -E ':5432\b' | grep -v '127.0.0.1' | grep -vq '::1'; then log "WARNING: Postgres may be listening on a non-loopback address — check ss -tlnp | grep 5432" else log "Postgres appears bound to localhost only" fi fi else log "SKIP_POSTGRES=1 — skipping Postgres harden" fi # --------------------------------------------------------------------------- # 8) SSH lock (gated) # --------------------------------------------------------------------------- write_sshd_dropin() { local lock="$1" # 0 = keys preferred but password still on; 1 = full lock if [[ "$lock" == "1" ]]; then cat >"$SSH_DROPIN" <"$SSH_DROPIN" </dev/null 2>&1; then sshd -t || die "sshd config invalid" fi systemctl reload ssh 2>/dev/null || systemctl reload sshd 2>/dev/null || systemctl reload ssh.service } if [[ "${SKIP_SSH_LOCK:-0}" == "1" ]]; then log "SKIP_SSH_LOCK=1 — writing soft SSH drop-in (passwords still allowed)" write_sshd_dropin 0 echo soft >"$MARKER_DIR/ssh_mode" elif has_deploy_key; then log "Deploy key present — applying FULL SSH lock (root/password disabled)" log "IMPORTANT: Keep this root session open. In a NEW terminal verify:" log " ssh ${DEPLOY_USER}@" write_sshd_dropin 1 echo locked >"$MARKER_DIR/ssh_mode" else log "NO deploy key — refusing full SSH lock (would lock you out)" write_sshd_dropin 0 echo soft >"$MARKER_DIR/ssh_mode" log "Next:" log " 1) From your PC: ssh-copy-id -i ~/.ssh/id_ed25519.pub ${DEPLOY_USER}@" log " or: export DEPLOY_SSH_PUBKEY='...' && re-run this script" log " 2) Test: ssh ${DEPLOY_USER}@" log " 3) Re-run: bash harden-vps.sh # will then lock SSH" fi # --------------------------------------------------------------------------- # Summary # --------------------------------------------------------------------------- log "Hardening complete (summary)" echo "User: ${DEPLOY_USER}" echo "SSH mode: $(cat "$MARKER_DIR/ssh_mode" 2>/dev/null || echo unknown)" echo "UFW: active (22, 9080, 9443)" echo "fail2ban: sshd jail" echo "Docker: $(command -v docker >/dev/null && docker --version | head -1 || echo skipped/missing)" echo "Postgres: localhost listen (unless SKIP_POSTGRES)" echo echo "Pre-deploy checklist: deploy/vps-hardening/PREDEPLOY-CHECKLIST.md" echo "Do NOT publish 5432/6379/4000/4001 on the host firewall." echo "Log out of root SSH only after deploy-key login works."