TL;DR
This guide shows you how to make your SSH server more secure by limiting who can connect remotely and what they can do. We’ll cover key-based authentication, disabling password logins, restricting user access, and using a firewall.
1. Switch to Key-Based Authentication
Passwords are vulnerable to brute-force attacks. Key-based authentication is much more secure.
- Generate a key pair on your local machine: Open your terminal and run:
ssh-keygen -t rsa -b 4096Follow the prompts (you can usually accept the defaults). This creates a private key (keep this safe!) and a public key.
- Copy the public key to the server: Use `ssh-copy-id`:
ssh-copy-id user@your_server_ipEnter your password when prompted. This adds your public key to the
~/.ssh/authorized_keysfile on the server. - Test the connection: Try logging in without a password:
ssh user@your_server_ipIf it works, you’ve successfully set up key-based authentication.
2. Disable Password Authentication
Once key-based authentication is working, disable password logins to prevent brute-force attacks.
- Edit the SSH configuration file: Open
/etc/ssh/sshd_configwith a text editor (e.g., `sudo nano /etc/ssh/sshd_config`). - Find and change these settings:
- Set
PasswordAuthentication no - Set
ChallengeResponseAuthentication no(if present)
- Set
- Restart the SSH service: Use:
sudo systemctl restart sshd
3. Restrict User Access
Limit which users can connect via SSH.
- Edit the SSH configuration file: Open
/etc/ssh/sshd_configagain. - Use the
AllowUsersdirective: Add a line like this, replacinguser1anduser2with the usernames you want to allow:AllowUsers user1 user2Alternatively, use
DenyUsersto block specific users. - Restart the SSH service: Use:
sudo systemctl restart sshd
4. Use a Firewall (UFW)
A firewall adds another layer of security by controlling network traffic.
- Enable UFW: If it’s not already enabled, run:
sudo ufw enable - Allow SSH connections: By default, UFW might block SSH. Allow it with:
sudo ufw allow sshOr, specifically allow port 22 (or your custom SSH port):
sudo ufw allow 22/tcp - Check the firewall status: Run:
sudo ufw statusMake sure SSH is allowed.
5. Change the Default SSH Port (Optional)
Changing the default port makes it harder for automated attacks to find your server.
- Edit the SSH configuration file: Open
/etc/ssh/sshd_config. - Find and change the
Portdirective: ChangePort 22to a different port number (e.g.,Port 2222). Choose a port above 1024 that isn’t commonly used. - Update your firewall rules: If you changed the port, update UFW to allow the new port:
sudo ufw allow 2222/tcp(Replace 2222 with your chosen port).
- Restart the SSH service: Use:
sudo systemctl restart sshdWhen connecting, you’ll need to specify the new port using the `-p` option:
ssh -p 2222 user@your_server_ip

