TL;DR
Disable password authentication for SSH and use SSH key pairs instead. This is much more secure than passwords.
How to Secure SSH Access
- Generate an SSH Key Pair: On your local machine (the one you’ll be connecting *from*), open a terminal or command prompt.
- If you don’t already have one, create a new key pair using the following command:
ssh-keygen -t rsa -b 4096 - You’ll be prompted for a file to save the key. The default (~/.ssh/id_rsa) is usually fine. Press Enter to accept it.
- You’ll also be asked for a passphrase. Strongly recommend setting one! This adds an extra layer of security even if your private key file is compromised.
- If you don’t already have one, create a new key pair using the following command:
- Copy the Public Key to the Server: You need to get the contents of your public key (~/.ssh/id_rsa.pub) onto the server you want to connect to.
- The easiest way is often using
ssh-copy-id:ssh-copy-id user@your_server_ip(Replace ‘user’ with your username on the server and ‘your_server_ip’ with the server’s address.)
- You will be prompted for the server password one last time. This command appends your public key to the ~/.ssh/authorized_keys file on the server.
- If
ssh-copy-idisn’t available, you can manually copy and paste the contents of ~/.ssh/id_rsa.pub into the ~/.ssh/authorized_keys file on the server (using a text editor like nano or vim).
- The easiest way is often using
- Disable Password Authentication: This is the crucial step.
- Connect to your server using SSH (you might still need your password for this one time):
ssh user@your_server_ip - Edit the SSH daemon configuration file. Usually located at /etc/ssh/sshd_config:
sudo nano /etc/ssh/sshd_config - Find these lines and change them as follows:
PasswordAuthentication noChallengeResponseAuthentication no(if present, set to ‘no’)
- Save the file (Ctrl+X, Y, Enter in nano).
- Restart the SSH service:
sudo systemctl restart sshd(or
sudo service ssh restarton older systems)
- Connect to your server using SSH (you might still need your password for this one time):
- Test Your Connection: Try connecting to your server again.
- You should now be prompted for the passphrase you set when generating the key pair, *not* your password. If it works, congratulations!
ssh user@your_server_ip
- You should now be prompted for the passphrase you set when generating the key pair, *not* your password. If it works, congratulations!
- Optional: Further Security Measures
- Change SSH Port: Change the default port (22) to a non-standard port in /etc/ssh/sshd_config. This reduces automated attacks.
- Disable Root Login: In /etc/ssh/sshd_config, set
PermitRootLogin no. - Use Fail2Ban: Install and configure Fail2Ban to automatically block attackers who repeatedly fail login attempts.