Overview
Comprehensive SSH hardening script that applies security best practices. Creates a backup before making changes and validates configuration.
The Script
#!/bin/bash
# SSH Hardening Script
# Apply security best practices to SSH configuration
set -euo pipefail
# Configuration
SSH_CONFIG="/etc/ssh/sshd_config"
BACKUP_DIR="/etc/ssh/backups"
NEW_PORT=22
# Must be root
if [ "$(id -u)" -ne 0 ]; then
echo "Error: This script must be run as root"
exit 1
fi
# Create backup
backup_config() {
mkdir -p "$BACKUP_DIR"
local backup_file="$BACKUP_DIR/sshd_config.$(date +%Y%m%d_%H%M%S)"
cp "$SSH_CONFIG" "$backup_file"
echo "Backup created: $backup_file"
}
# Apply a setting to sshd_config
apply_setting() {
local key="$1"
local value="$2"
local config="$3"
# Remove existing setting (commented or not)
sed -i "/^#*\\s*$key\\s/d" "$config"
# Add new setting
echo "$key $value" >> "$config"
echo "Set: $key $value"
}
# Main
backup_config
echo "SSH Hardening Complete!"
echo ""
echo "IMPORTANT: Test connection in a NEW terminal:"
echo " ssh -p $NEW_PORT user@$(hostname)"
echo ""
echo "Keep this session open until verified!"Usage
# Preview changes
sudo ./ssh-hardening.sh -d
# Basic hardening
sudo ./ssh-hardening.sh -k
# Change port and restrict users
sudo ./ssh-hardening.sh -p 2222 -u "admin deploy" -k
# Force without prompts
sudo ./ssh-hardening.sh -p 2222 -k -fPost-Hardening Checklist
- Test SSH connection in a new terminal BEFORE closing current session
- Ensure your SSH key is in ~/.ssh/authorized_keys
- Update any automated scripts with new port
- Consider setting up fail2ban
- ssh
- security
- hardening
- sshd_config
- firewall
- fail2ban