#!/usr/bin/env bash
# Härtet SSH und richtet getrennten SFTP-only-Zugriff für Mitarbeiter ein.
#
# Ergebnis:
# - ADMIN_USER: SSH + SFTP per Schlüssel, sudo wie bisher.
# - Mitglieder von SFTP_GROUP: ausschließlich internes SFTP, Chroot auf
#   DATA_ROOT/users/%u, keine Shell, kein Port-Forwarding.
# - Für SFTP-only-Nutzer ist Passwortauthentifizierung erlaubt; für Admin nicht.
#
# Erst ausführen, nachdem SSH-Key-Login für ADMIN_USER in einer zweiten
# Sitzung erfolgreich getestet wurde.
#
# Verwendung:
#   sudo bash 07-harden-ssh.sh ./local-llm.env

set -euo pipefail
CONFIG="${1:-./local-llm.env}"
[[ -r "$CONFIG" ]] || { echo "Konfiguration fehlt: $CONFIG"; exit 1; }
# shellcheck disable=SC1090
source "$CONFIG"

for v in ADMIN_USER SSH_ADMIN_GROUP SFTP_GROUP DATA_ROOT; do
  [[ -n "${!v:-}" && "${!v}" != __*__ ]] || { echo "Bitte $v in $CONFIG setzen."; exit 1; }
done
[[ "${EUID}" -eq 0 ]] || { echo "Bitte mit sudo/root ausführen."; exit 1; }

HOME_DIR="$(getent passwd "$ADMIN_USER" | cut -d: -f6)"
KEYS="$HOME_DIR/.ssh/authorized_keys"
[[ -s "$KEYS" ]] || {
  echo "ABBRUCH: Kein authorized_keys für $ADMIN_USER gefunden."
  echo "SSH-Key zuerst einrichten und in einer zweiten Sitzung testen."
  exit 1
}

groupadd -f "$SSH_ADMIN_GROUP"
groupadd -f "$SFTP_GROUP"
usermod -aG "$SSH_ADMIN_GROUP" "$ADMIN_USER"

# Chroot-Pfad muss vollständig root-owned und nicht gruppen-/welt-schreibbar sein.
install -d -o root -g root -m 0755 "$DATA_ROOT"
install -d -o root -g root -m 0755 "$DATA_ROOT/users"

cat >/etc/ssh/sshd_config.d/20-office-ai-hardening.conf <<EOF
PermitRootLogin no
PasswordAuthentication no
KbdInteractiveAuthentication no
PubkeyAuthentication yes
X11Forwarding no
AllowTcpForwarding no
PermitTunnel no
AllowGroups ${SSH_ADMIN_GROUP} ${SFTP_GROUP}

Match Group ${SFTP_GROUP}
    ChrootDirectory ${DATA_ROOT}/users/%u
    ForceCommand internal-sftp
    PasswordAuthentication yes
    KbdInteractiveAuthentication no
    PubkeyAuthentication no
    X11Forwarding no
    AllowTcpForwarding no
    PermitTunnel no
EOF

sshd -t
systemctl reload ssh

echo
echo "SSH/SFTP-Härtung aktiv."
echo "Admin '$ADMIN_USER': Key-Login testen und bestehende Sitzung bis dahin offen lassen."
echo "Mitarbeiter: mit 08-add-office-user.sh anlegen; sie erhalten nur SFTP im eigenen Chroot."
