Secure remote access is the backbone of any modern Linux environment. While passwords are convenient, they’re also the weakest link in the security chain. Switching to SSH key authentication not only eliminates the risk of brute‑force password attacks but also gives you granular control over who can log in and from where. In this guide we’ll walk you through the entire process—from generating a robust key pair to hardening the SSH daemon—so you can lock down your servers with confidence.
What You’ll Need
- A Linux server (any distribution that runs OpenSSH)
- A local workstation (Linux, macOS, or Windows with WSL/PowerShell)
- Sudo or root privileges on the server
- An internet connection for package updates
- A text editor (vim, nano, or your favorite IDE)
Step 1: Generate a Strong SSH Key Pair
Open a terminal on your local machine and run:
ssh-keygen -t ed25519 -a 100 -C "[email protected]"
The -t ed25519 flag creates a modern, high‑performance elliptic‑curve key. The -a 100 option applies 100 rounds of key‑derivation function (KDF) to protect the private key with a passphrase. When prompted, choose a memorable passphrase and store the private key in the default location (~/.ssh/id_ed25519). This passphrase adds an extra layer of security in case the key file is ever stolen.
Step 2: Harden the SSH Daemon Configuration
Edit the SSH server configuration file (/etc/ssh/sshd_config) with root privileges:
sudo nano /etc/ssh/sshd_config
Make the following changes (add them if they don’t exist):
# Use only protocol 2
Protocol 2
# Disable root login over SSH
PermitRootLogin no
# Disallow password authentication
PasswordAuthentication no
# Enforce public key authentication
PubkeyAuthentication yes
# Limit authentication attempts
MaxAuthTries 3
# Use a strong MAC algorithm list
MACs [email protected],[email protected]
# Enable only strong ciphers
Ciphers [email protected],[email protected]
# Optional: Restrict which users can SSH
AllowUsers alice bob
# Optional: Limit SSH to specific network interfaces
ListenAddress 0.0.0.0:22
After saving, test the syntax to avoid locking yourself out:
sudo sshd -t
If no output appears, the configuration is syntactically correct. Reload the daemon:
sudo systemctl reload sshd
Step 3: Copy Your Public Key to the Server
The easiest way is to use ssh-copy-id:
ssh-copy-id -i ~/.ssh/id_ed25519.pub [email protected]
If ssh-copy-id isn’t available, you can manually append the key:
cat ~/.ssh/id_ed25519.pub | ssh [email protected] 'mkdir -p ~/.ssh && chmod 700 ~/.ssh && cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys'
Verify the key was added correctly by listing the authorized_keys file on the server.
Step 4: Disable Password Authentication Globally
Even though we set PasswordAuthentication no earlier, it’s worth double‑checking. Open /etc/ssh/sshd_config again and ensure the line is present and uncommented. Then restart the service:
sudo systemctl restart sshd
Attempt to log in without a key to confirm the server rejects password attempts.
Step 5: Restrict SSH Access by User and IP
Limiting which accounts can SSH reduces the attack surface. In sshd_config, use the AllowUsers directive with optional @IP patterns:
AllowUsers [email protected]/24 [email protected]
This example permits alice only from the local LAN and bob from a single external IP. After editing, reload the daemon.
Step 6: Use SSH Agent Forwarding Securely (Optional)
If you need to hop from one server to another, enable agent forwarding on your local ~/.ssh/config:
Host your.server.com
ForwardAgent yes
On the remote host, ensure AllowAgentForwarding yes is set (it’s enabled by default). Remember: never enable forwarding on untrusted machines, as it can expose your private key to malicious users.
Step 7: Add an Extra Layer – Two‑Factor Authentication (Optional)
For high‑value servers, combine key auth with a one‑time password (OTP). Install google-authenticator on the server:
sudo apt-get install libpam-google-authenticator # Debian/Ubuntu
sudo yum install google-authenticator # RHEL/CentOS
Run the setup for the user you want to protect:
google-authenticator
Follow the prompts to generate a QR code, secret key, and emergency codes. Then edit /etc/pam.d/sshd and add:
auth required pam_google_authenticator.so nullok
Finally, enable ChallengeResponseAuthentication in sshd_config:
ChallengeResponseAuthentication yes
Restart SSH and you’ll be asked for the OTP after the key verification.
Common Mistakes to Avoid
1. Leaving PasswordAuthentication enabled. Even a single password‑enabled account can become an entry point for brute‑force attacks.
2. Storing the private key without a passphrase. If the file is compromised, attackers gain immediate access.
3. Using RSA keys with default 2048‑bit size. Modern standards favor Ed25519 or RSA‑4096 for stronger security.
4. Forgetting to reload sshd after changes. The old configuration stays active until you restart or reload.
5. Setting PermitRootLogin yes inadvertently. Root logins bypass user‑level restrictions and should be disabled.
6. Copying the key to the wrong user’s ~/.ssh directory. Permissions will be wrong, and SSH will reject the key.
Tips and Tricks
– Use a hardware security key (YubiKey, Nitrokey) with OpenSSH’s sk-ssh-ed25519 support for phishing‑proof authentication.
– Rotate keys regularly. Generate a new pair every six months and revoke the old public key from authorized_keys.
– Audit your authorized_keys file. Prefix each key with a comment (e.g., ssh-ed25519 AAA… alice@laptop) to track ownership.
– Enable logging. Set LogLevel VERBOSE in sshd_config to capture key‑based login attempts for forensic analysis.
– Use firewall rules. Combine SSH hardening with ufw or iptables to allow port 22 only from trusted networks.
Frequently Asked Questions
Can I use the same SSH key on multiple servers?
Yes, you can reuse a single key pair across many hosts, but it’s best practice to generate a dedicated key for each environment (production, staging, personal) to limit exposure if one server is compromised.
What should I do if I lose my private key?
Immediately remove the corresponding public key from every authorized_keys file it resides in. Then generate a new key pair, distribute the new public key, and consider enabling two‑factor authentication as a backup.
Is Ed25519 compatible with older SSH clients?
Most modern SSH clients (OpenSSH 6.5+) support Ed25519. If you need to connect from an older client, keep an RSA‑4096 key as a fallback and list both keys in authorized_keys.
Conclusion
Switching from password‑based SSH logins to key authentication dramatically reduces the attack surface of your Linux servers. By following the steps above—generating a strong Ed25519 key, tightening sshd_config, restricting users and IPs, and optionally adding two‑factor authentication—you’ll create a robust, future‑proof remote‑access strategy. Remember to audit your setup regularly, rotate keys, and stay aware of common pitfalls. With these practices in place, you can focus on building and scaling your services rather than worrying about unauthorized access.





