Change the SSH Port
Changing the default SSH port (22) is a basic security measure to reduce automated attacks.
- Open the SSH configuration file:
vi /etc/ssh/sshd_config - Find the line
#Port 22, remove the#comment, and change22to a high-numbered port (e.g., above 10000). - Save and exit.
Important: Ensure the new port is open in your firewall/security group before restarting SSH.
Configure SSH Key Authentication and Disable Password Login
Using key-based authentication and disabling password login for the root account is an effective defense against brute-force attacks.
1. Generate an SSH Key Pair
On your local machine, run:
ssh-keygen -t rsa -b 4096
Follow the prompts to save the key (default location is fine) and set a strong passphrase for extra security.
This creates two files in ~/.ssh/:
id_rsa: Private key. Keep this secret and secure.id_rsa.pub: Public key. This will be uploaded to the server.
2. Upload the Public Key to the Server
For the root user, ensure the .ssh directory exists and has correct permissions, then append the public key:
mkdir -p /root/.ssh
chmod 700 /root/.ssh
cat /root/.ssh/id_rsa.pub >> /root/.ssh/authorized_keys
chmod 600 /root/.ssh/authorized_keys
3. Configure the SSH Server
Edit /etc/ssh/sshd_config and ensure these settings are present:
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys
PasswordAuthentication no
# Optionally, restrict root login to key-based only:
PermitRootLogin prohibit-password
If you changed the port in the first step, verify the Port directive is set correctly.
4. Restart SSH and Test
Before disconnecting, open a new terminal and test key-based login. Then restart the SSH service:
- For systemd systems:
systemctl restart sshd - For SysV init systems:
service sshd restart
Security Best Practices:
- Back up your private key; losing it means losing server access.
- Never leave the private key on the server; only the public key (
authorized_keys) should remain. - Use a strong passphrase for your private key.
- Consider using different key pairs for different servers to limit risk.
After completing these steps, your server will only accept SSH key authentication, significantly improving security.