SSH Server Hardening (Linux)
Disable password auth, lock down SSH to key-only access, change the default port, and restrict user logins. Works on Ubuntu, Debian, Fedora, and openSUSE.
Distrosubuntu, debian, fedora, opensuse, centos, rocky
Shell
bashUpdated
Script
# 1. Generate an SSH key pair on your LOCAL machine (skip if you have one)
# ssh-keygen -t ed25519 -C "your-email@example.com"
# 2. Copy your public key to the server (run from your LOCAL machine)
# ssh-copy-id -i ~/.ssh/id_ed25519.pub user@server-ip
# 3. Run the rest ON THE SERVER after confirming key login works
# Back up original config
sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak
# Apply hardened settings
sudo tee /etc/ssh/sshd_config.d/99-hardened.conf > /dev/null <<'EOF'
# Disable password authentication — key-only
PasswordAuthentication no
PubkeyAuthentication yes
# Disable root login entirely
PermitRootLogin no
# Disable unused auth methods
ChallengeResponseAuthentication no
KbdInteractiveAuthentication no
UsePAM yes
# Limit login window
LoginGraceTime 30
MaxAuthTries 3
MaxSessions 5
# Disable forwarding unless needed
AllowTcpForwarding no
X11Forwarding no
AllowAgentForwarding no
# Only allow specific users (edit as needed)
# AllowUsers yourusername
# Use modern key exchange and ciphers only
KexAlgorithms curve25519-sha256,curve25519-sha256@libssh.org
Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com,aes128-gcm@openssh.com
MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com
EOF
# Validate config before restarting
sudo sshd -t && echo "Config OK — restarting SSH"
# Restart SSH (use the right service name for your distro)
sudo systemctl restart ssh 2>/dev/null || sudo systemctl restart sshd
What this does
Applies a drop-in config to /etc/ssh/sshd_config.d/99-hardened.conf that:
- Disables password authentication (prevents brute-force attacks)
- Disables root login
- Disables unused forwarding and agent features
- Restricts to modern cryptographic algorithms only
Prerequisites
Critical: Copy your SSH public key to the server before disabling password auth, or you will lock yourself out.
# From your LOCAL machine:
ssh-keygen -t ed25519 -C "you@example.com" # if you don't have a key
ssh-copy-id -i ~/.ssh/id_ed25519.pub user@server-ip
Verify key login works in a separate terminal before proceeding.
Changing the default port (optional)
Add to 99-hardened.conf before restarting:
Port 2222
Then connect with ssh -p 2222 user@server and update any firewall rules.
Firewall (UFW — Ubuntu/Debian)
sudo ufw allow from trusted-ip to any port 22
sudo ufw deny 22
sudo ufw enable
Notes
- The
sshd -tcheck validates config before restart — if it fails, no changes are applied - Original config is backed up to
/etc/ssh/sshd_config.bak - On Fedora/RHEL the service is
sshd; on Debian/Ubuntu it’sssh AllowUsersdirective is commented out — uncomment and edit to whitelist specific accounts