diff --git a/imagehost-setup.sh b/imagehost-setup.sh index a5d2a41..f4c5764 100644 --- a/imagehost-setup.sh +++ b/imagehost-setup.sh @@ -187,21 +187,28 @@ path.write_text(text) PYEOF fi -printf '%s\n' "$SFTP_STANZA" >> "$SSHD_CONFIG" - -# Additional SSH hardening (idempotent: only add if not already set) +# Apply global hardening options FIRST (before the Match block) apply_ssh_option() { local key="$1" val="$2" if grep -qiE "^\s*${key}\s" "$SSHD_CONFIG"; then sed -i -E "s|^\s*${key}\s.*|${key} ${val}|i" "$SSHD_CONFIG" else - echo "${key} ${val}" >> "$SSHD_CONFIG" + # Insert before the first Match block, or append if no Match block exists + if grep -q "^Match " "$SSHD_CONFIG"; then + sed -i "/^Match /i ${key} ${val}" "$SSHD_CONFIG" + else + echo "${key} ${val}" >> "$SSHD_CONFIG" + fi fi } -apply_ssh_option "PermitRootLogin" "prohibit-password" -apply_ssh_option "PasswordAuthentication" "yes" # needed for SFTP password auth -apply_ssh_option "MaxAuthTries" "4" -apply_ssh_option "LoginGraceTime" "30" + +apply_ssh_option "PermitRootLogin" "prohibit-password" +apply_ssh_option "PasswordAuthentication" "yes" +apply_ssh_option "MaxAuthTries" "4" +apply_ssh_option "LoginGraceTime" "30" + +# Append the Match block LAST +printf '%s\n' "$SFTP_STANZA" >> "$SSHD_CONFIG" sshd -t || die "SSH config test failed — check ${SSHD_CONFIG}" systemctl restart sshd