diff --git a/scripts/ubuntu-vm-security-update.sh b/scripts/ubuntu-vm-security-update.sh index 42eaca1..6116410 100644 --- a/scripts/ubuntu-vm-security-update.sh +++ b/scripts/ubuntu-vm-security-update.sh @@ -109,8 +109,30 @@ ensure_service_enabled_and_restarted() { run systemctl restart "$service" } +wait_for_fail2ban_ready() { + local attempts=10 + local delay_seconds=1 + local i + + if [[ "$DRY_RUN" == "true" ]]; then + log "DRY RUN: skipping fail2ban readiness check" + return 0 + fi + + for ((i = 1; i <= attempts; i++)); do + if fail2ban-client ping >/dev/null 2>&1; then + log "fail2ban is ready" + return 0 + fi + sleep "$delay_seconds" + done + + return 1 +} + detect_ssh_port() { local detected_port="" + local sshd_output="" if [[ -n "$SSH_PORT_OVERRIDE" ]]; then echo "$SSH_PORT_OVERRIDE" @@ -118,7 +140,10 @@ detect_ssh_port() { fi if command -v sshd >/dev/null 2>&1; then - detected_port="$(sshd -T 2>/dev/null | awk '$1 == "port" {print $2; exit}')" + if sshd_output="$(sshd -T 2>/dev/null)"; then + detected_port="$(printf '%s\n' "$sshd_output" | awk '$1 == "port" {print $2}')" + detected_port="$(printf '%s\n' "$detected_port" | head -n 1)" + fi fi if [[ -z "$detected_port" ]] && [[ -f /etc/ssh/sshd_config ]]; then @@ -330,7 +355,8 @@ EOF ensure_service_enabled_and_restarted fail2ban if [[ "$DRY_RUN" == "false" ]] && have_systemd && command -v fail2ban-client >/dev/null 2>&1; then - fail2ban-client ping | tee -a "$LOG_FILE" || die "fail2ban-client ping failed" + wait_for_fail2ban_ready || die "fail2ban-client ping failed" + fail2ban-client ping | tee -a "$LOG_FILE" fi log "Checking package integrity database availability"