Secure SSH access is the first line of defense for any Linux server. While the default configuration works out of the box, it also leaves doors open for brute‑force attacks, credential theft, and unauthorized access. In this guide we’ll walk through a practical, step‑by‑step process to lock down SSH without breaking your workflow. By the end you’ll have a hardened SSH service that uses key‑based authentication, limited network exposure, and automated intrusion detection—all while keeping the user experience smooth.
What You’ll Need
- A Linux server with root or sudo privileges
- An SSH client (OpenSSH, PuTTY, or similar)
- A personal workstation to generate SSH keys
- Basic familiarity with the command line
- Optional: Fail2Ban and a firewall such as ufw or firewalld
Step 1: Create a Dedicated Non‑Root User
Never log in as root over SSH. First, create a regular account and add it to the sudo group so you can perform privileged tasks when needed.
sudo adduser adminuser sudo usermod -aG sudo adminuser
Test the new account by opening a new SSH session: ssh adminuser@your_server_ip. Once you confirm you can sudo, you can safely disable root login later.
Step 2: Generate and Deploy SSH Key Pairs
Key‑based authentication eliminates password guessing entirely. On your workstation run:
ssh-keygen -t ed25519 -C "[email protected]"
Accept the default file location and protect the private key with a strong passphrase. Then copy the public key to the server:
ssh-copy-id adminuser@your_server_ip
If ssh-copy-id is unavailable, you can manually append the contents of ~/.ssh/id_ed25519.pub to /home/adminuser/.ssh/authorized_keys on the server, ensuring the directory permissions are 700 and the file permissions are 600.
Step 3: Harden the SSH Daemon Configuration
Edit /etc/ssh/sshd_config and apply the following settings. Each line replaces or adds to the default file.
# Disable root login PermitRootLogin no # Only allow our new user AllowUsers adminuser # Enforce protocol 2 (default but explicit) Protocol 2 # Use only strong ciphers and MACs Ciphers [email protected],[email protected] MACs [email protected],[email protected] # Disable empty passwords PermitEmptyPasswords no # Limit authentication attempts per connection MaxAuthTries 3 # Set idle timeout (seconds) ClientAliveInterval 300 ClientAliveCountMax 0
After saving, restart the service:
sudo systemctl restart sshd
Step 4: Disable Password Authentication Entirely
With keys in place, you can turn off password logins to block brute‑force attacks.
# In /etc/ssh/sshd_config PasswordAuthentication no ChallengeResponseAuthentication no
Restart SSH again and verify you can still connect using the key. If you lock yourself out, use the console or a rescue mode to revert the change.
Step 5: Change the Default SSH Port
Moving SSH off port 22 reduces noise from automated scanners. Choose a high, non‑privileged port (e.g., 2222 or 4242).
# In /etc/ssh/sshd_config Port 2222
Update any firewall rules to allow the new port and restart SSH. Remember to specify the new port when connecting:
ssh -p 2222 adminuser@your_server_ip
Step 6: Install and Configure Fail2Ban
Fail2Ban monitors log files and bans IPs that show malicious signs, such as repeated failed login attempts.
sudo apt-get install fail2ban # Debian/Ubuntu sudo yum install fail2ban # RHEL/CentOS
Create a local jail configuration to protect SSH:
# /etc/fail2ban/jail.local [sshd] enabled = true port = 2222 logpath = %(sshd_log)s maxretry = 5 bantime = 3600
Start and enable the service:
sudo systemctl enable fail2ban --now
Step 7: Restrict Network Access with a Firewall
Limit SSH to known IP ranges whenever possible. Using ufw as an example:
sudo ufw allow from 203.0.113.0/24 to any port 2222 proto tcp sudo ufw deny 2222/tcp # Deny all others sudo ufw enable
If you need occasional remote access from a new location, temporarily add a rule and remove it after the session.
Step 8: Enable Log Monitoring and Alerts
Regularly reviewing SSH logs helps you spot suspicious activity early. Add a cron job that greps for unusual patterns and emails you.
#!/bin/bash LOG="/var/log/auth.log" THRESH=10 COUNT=$(grep "Failed password" $LOG | wc -l) if [ $COUNT -gt $THRESH ]; then echo "High number of SSH failures: $COUNT" | mail -s "SSH Alert" [email protected] fi
Save this script as /usr/local/bin/ssh-alert.sh, make it executable, and schedule it:
chmod +x /usr/local/bin/ssh-alert.sh (crontab -l ; echo "*/30 * * * * /usr/local/bin/ssh-alert.sh") | crontab -
Common Mistakes to Avoid
1. Disabling root login before creating a sudo user. If you remove root access without an alternative, you can lock yourself out.
2. Changing the SSH port but forgetting to update firewall rules. The service will appear down.
3. Leaving PasswordAuthentication yes after adding keys. This re‑opens the password attack surface.
4. Using weak or default ciphers. Stick to modern algorithms like AES‑GCM or ChaCha20.
5. Not testing the new configuration in a separate terminal. If the connection drops, you still have the original session to revert changes.
Tips and Tricks
• Store your private key on a hardware token (YubiKey) for added protection.
• Enable AllowTcpForwarding no and PermitTunnel no unless you explicitly need them.
• Use ssh -o StrictHostKeyChecking=no only for automated scripts; otherwise keep host key verification.
• Rotate SSH keys annually and remove old entries from authorized_keys.
• Combine Fail2Ban with iptables or nftables for permanent bans.
Frequently Asked Questions
Can I still use password login for a single user?
Yes, but you must enable PasswordAuthentication yes and explicitly allow that user with Match User username blocks. It’s simpler and safer to keep passwords disabled and rely on keys.
What if I lose my private key?
Without the matching private key you cannot authenticate. Keep a backup on an encrypted USB drive or a secure cloud vault. If the key is lost, you’ll need to add a new public key to authorized_keys via console access.
Is changing the SSH port enough to stop attacks?
No. Port obscurity only reduces noise. Combine it with key‑based auth, Fail2Ban, and firewall restrictions for true security.
Conclusion
Securing SSH on Linux servers is a layered process: start with a non‑root user, enforce key‑based authentication, tighten the daemon configuration, and then add network‑level controls like firewalls and Fail2Ban. By following the eight steps above and avoiding common pitfalls, you’ll dramatically lower the risk of unauthorized access while maintaining a seamless admin experience. Remember, security is continuous—regularly audit your settings, rotate keys, and keep an eye on logs to stay ahead of emerging threats.



