Secure Shell (SSH) is the de‑facto method for remote administration of Linux servers. While SSH is designed with security in mind, a default installation leaves plenty of doors open for attackers. In this guide we’ll walk you through a practical, step‑by‑step hardening process that raises the bar from “good enough” to “battle‑ready.” By the end, you’ll have a tightly locked‑down SSH service, a set of best‑practice configurations, and the confidence to audit and maintain it over time.
What You’ll Need
- A Linux server with root (or sudo) access – Ubuntu, Debian, CentOS, or any system that uses OpenSSH.
- Basic familiarity with the command line and editing text files (nano, vim, or your favourite editor).
- A secondary, non‑root user that you will use for daily administration.
- Access to a second terminal or console (in case you lock yourself out).
- Backup of your current
/etc/ssh/sshd_configfile.
Step 1: Create a Dedicated Non‑Root Admin User
Never log in as root over SSH. Instead, create a regular user and grant it sudo privileges. This limits the blast radius if credentials are compromised.
# adduser adminuser
# usermod -aG sudo adminuser # Debian/Ubuntu
# usermod -aG wheel adminuser # RHEL/CentOS Set a strong password or, better yet, configure key‑based authentication for this user (we’ll do that in Step 3). Test the new account before proceeding:
$ ssh [email protected] Step 2: Update OpenSSH to the Latest Stable Version
Older OpenSSH releases may contain known vulnerabilities. Use your distro’s package manager to ensure you’re running the most recent, security‑patched version.
# apt update && apt upgrade openssh-server # Debian/Ubuntu
# yum update openssh-server # RHEL/CentOS 7
# dnf update openssh-server # RHEL/CentOS 8+ After the upgrade, verify the version:
$ ssh -V
OpenSSH_8.9p1, OpenSSL 1.1.1k 25 Mar 2021 Step 3: Enforce Key‑Based Authentication Only
Passwords are the easiest way for brute‑force tools to gain access. Switch to public‑key authentication and disable password logins.
On your local machine, generate a key pair if you don’t already have one:
$ ssh-keygen -t ed25519 -a 100 -C "adminuser@$(hostname)"
# Press ENTER to accept the default location (~/.ssh/id_ed25519)
# Choose a strong passphrase Copy the public key to the server:
$ ssh-copy-id -i ~/.ssh/id_ed25519.pub [email protected] Now edit the SSH daemon configuration:
# nano /etc/ssh/sshd_config Set the following directives (add them if missing):
PubkeyAuthentication yes
PasswordAuthentication no
ChallengeResponseAuthentication no
UsePAM no Save the file and restart the service:
# systemctl restart sshd # most distros
# service ssh restart # older SysV init Attempt a password login to confirm it’s blocked, then verify that key login still works.
Step 4: Change the Default SSH Port
While security through obscurity isn’t a replacement for proper hardening, moving SSH off port 22 reduces noise from automated scans.
Edit sshd_config again:
# nano /etc/ssh/sshd_config Find the line that reads #Port 22 and change it to a high, non‑standard port (e.g., 4222). Remove the leading hash.
Port 4222 Update your firewall rules to allow the new port and block the old one. Example with ufw:
# ufw allow 4222/tcp
# ufw delete allow 22/tcp # optional
# ufw reload Restart SSH again, then test the connection:
$ ssh -p 4222 [email protected] Step 5: Disable Root Login and Restrict Users
Even with key‑only auth, allowing direct root logins is risky. In sshd_config, set:
PermitRootLogin no To further tighten access, use the AllowUsers directive to whitelist only the accounts you trust:
AllowUsers adminuser If you have multiple admins, separate them with spaces. After editing, reload SSH.
Step 6: Harden Cryptographic Settings
Modern ciphers and MAC algorithms provide better protection and reduce the attack surface.
Add the following to sshd_config (replace any existing Ciphers, KexAlgorithms, or MACs lines):
Ciphers [email protected],[email protected],[email protected]
KexAlgorithms [email protected],diffie-hellman-group-exchange-sha256
MACs [email protected],[email protected] These choices favor forward secrecy and authenticated encryption. Restart SSH and verify the settings with:
$ ssh -vvv [email protected] 2>&1 | grep -i "cipher|kex|mac" Step 7: Implement Rate Limiting with Fail2Ban
Even with password auth disabled, bots will still hammer your port. Fail2Ban watches log files and bans IPs that exceed a threshold.
Install and enable it:
# apt install fail2ban # Debian/Ubuntu
# yum install epel-release && yum install fail2ban # RHEL/CentOS 7
# dnf install fail2ban # RHEL/CentOS 8+ Create a custom jail for SSH (or edit the default /etc/fail2ban/jail.local):
[sshd]
enabled = true
port = 4222
filter = sshd
logpath = /var/log/auth.log # Ubuntu/Debian
#logpath = /var/log/secure # RHEL/CentOS
maxretry = 3
bantime = 3600 Start and enable the service:
# systemctl enable --now fail2ban Check the jail status:
$ fail2ban-client status sshd Step 8: Enable Two‑Factor Authentication (2FA)
For high‑value servers, adding a one‑time password (OTP) layer dramatically improves security. The google-authenticator PAM module works well with OpenSSH.
Install the module:
# apt install libpam-google-authenticator # Debian/Ubuntu
# yum install google-authenticator # RHEL/CentOS 7
# dnf install google-authenticator # RHEL/CentOS 8+ Run the setup for the admin user:
$ google-authenticator Answer “yes” to the prompts to store the secret key, enable time‑based tokens, and disallow multiple uses.
Now edit the PAM SSH file (/etc/pam.d/sshd) and add:
auth required pam_google_authenticator.so nullok Finally, tell OpenSSH to use PAM:
# nano /etc/ssh/sshd_config
ChallengeResponseAuthentication yes
UsePAM yes Restart SSH. When you connect, you’ll be asked for your password (or key) **and** the 6‑digit OTP from your authenticator app.
Common Mistakes to Avoid
1. Locking yourself out. Always keep a second terminal open and test each change before closing the original session.
2. Forgetting to update firewall rules. Changing the SSH port without adjusting ufw, firewalld, or iptables will make the service unreachable.
3. Leaving PermitRootLogin set to “yes”. Even with key‑only auth, root logins give attackers a direct path.
4. Using weak ciphers. Avoid legacy algorithms like 3des-cbc or arcfour – they are vulnerable.
5. Not backing up sshd_config. A typo can prevent SSH from starting, forcing a local console reboot.
Tips and Tricks
Audit regularly. Run sshd -T to dump the effective configuration and compare it against your hardening checklist.
Use SSH certificates. Instead of managing hundreds of public keys, a short‑lived certificate signed by an internal CA simplifies revocation.
Log to a remote SIEM. Forward /var/log/auth.log (or /var/log/secure) to a central log server for correlation with other events.
Enable TCP wrappers. Add sshd: 192.168.0.0/16 to /etc/hosts.allow and deny the rest in /etc/hosts.deny for an extra layer of IP filtering.
Frequently Asked Questions
Is changing the SSH port enough to stop attacks?
No. Port‑changing reduces automated noise but does not replace proper authentication, rate limiting, or key management. Treat it as a convenience, not a security control.
Can I disable password authentication on a server that still needs occasional password logins?
Yes. You can create a separate “maintenance” user with PasswordAuthentication yes in a dedicated Match User block. This isolates the exception from your main admin accounts.
What if I lose my 2FA device?
Configure emergency backup codes when you set up google-authenticator. Store them securely (e.g., encrypted password manager). Also keep a secondary admin user with its own 2FA device.
Conclusion
Hardening SSH is a blend of sound policy, careful configuration, and ongoing vigilance. By creating a non‑root admin account, enforcing key‑based logins, moving away from the default port, tightening cryptography, and adding layers like Fail2Ban and 2FA, you dramatically lower the risk of a successful intrusion. Remember to test each change, keep backups, and revisit the settings periodically as new vulnerabilities emerge. A well‑hardened SSH service is one of the most effective defenses in a Linux server’s security arsenal.
Photo by Kevin Ache on Unsplash



