#!/usr/bin/env bash set -euo pipefail SCRIPT_NAME="$(basename "$0")" SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" SKILL_ROOT="$(dirname "$SCRIPT_DIR")" : "${OUTPUT_DIR:=$SKILL_ROOT/outputs}" : "${BACKUP_DIR:=$OUTPUT_DIR/backups}" : "${TEMPLATE_DIR:=$SKILL_ROOT/templates}" log_info() { echo "[INFO] $(date -Iseconds) $*"; } log_warn() { echo "[WARN] $(date -Iseconds) $*" >&2; } log_error() { echo "[ERROR] $(date -Iseconds) $*" >&2; } die() { log_error "$@"; exit 1; } require_confirm() { local require="${REQUIRE_CONFIRM:-1}" local phrase="${CONFIRM_PHRASE:-I UNDERSTAND THIS CAN LOCK ME OUT}" if [[ "$require" != "1" ]]; then return 0 fi echo echo "CONFIRMATION REQUIRED" echo "Type the phrase exactly to continue:" echo " $phrase" read -r input [[ "$input" == "$phrase" ]] || die "Confirmation phrase mismatch; aborting." } render_template() { local port="$1" sed "s/{{SSH_PORT}}/$port/g" "$TEMPLATE_DIR/sshd_config.tpl" } sshd_binary() { if command -v sshd &>/dev/null; then echo "sshd" elif [[ -x /usr/sbin/sshd ]]; then echo "/usr/sbin/sshd" else echo "" fi } reload_service() { if systemctl list-units --type=service | grep -qE '^sshd\.service'; then sudo systemctl reload sshd elif systemctl list-units --type=service | grep -qE '^ssh\.service'; then sudo systemctl reload ssh else die "Could not find ssh/sshd service under systemctl" fi } main() { mkdir -p "$OUTPUT_DIR" "$BACKUP_DIR" local dry="${DRY_RUN:-1}" [[ "$dry" == "0" ]] || die "Refusing to apply with DRY_RUN=$dry. Export DRY_RUN=0 to proceed." require_confirm local ssh_port="${SSH_PORT:-22}" local sshd sshd="$(sshd_binary)" [[ -n "$sshd" ]] || die "sshd binary not found" [[ -f /etc/ssh/sshd_config ]] || die "/etc/ssh/sshd_config not found" log_info "Backing up current sshd_config" sudo cp -a /etc/ssh/sshd_config "$BACKUP_DIR/sshd_config.before" log_info "Writing new sshd_config from template" render_template "$ssh_port" | sudo tee /etc/ssh/sshd_config >/dev/null log_info "Validating sshd config (sshd -t)" sudo "$sshd" -t || { log_error "sshd config validation failed; restoring backup" sudo cp -a "$BACKUP_DIR/sshd_config.before" /etc/ssh/sshd_config die "Aborted due to invalid sshd_config" } log_info "Reloading SSH service" reload_service log_info "SSH hardening applied. Verify you still have access before closing sessions." log_info "If you are locked out, use scripts/rollback/emergency_restore.sh from console." } [[ "${BASH_SOURCE[0]}" == "$0" ]] && main "$@"