In this guide I will show how to secure your SSH server.

The SSH protocol (also referred to as Secure Shell) is a method for secure remote login from one computer to another. It provides several alternative options for strong authentication, and it protects the communications security and integrity with strong encryption. It is a secure alternative to the non-protected login protocols (such as telnet, rlogin) and insecure file transfer methods (such as FTP).

My test server was online for only two hours. When I logged in, I saw this message.

Last failed login: Fri May 22 12:51:07 CEST 2020 from on ssh:notty
There were 718 failed login attempts since the last successful login.

I need to secure my server to avoid attacks.

Change the Default SSH Port

Using a non-standard port for SSH connection helps avoid automated attacks on your server.

To change port SSH you need to edit sshd configuration file. In my case I will change default port 22 to custom 54321.

# nano /etc/ssh/sshd_config

Uncomment the line and change port number, save the configuration and restart sshd service.

# systemctl restart sshd

Verify that the SSH is listening on the port you specified by connecting to it.

# netstat -ntulp | grep ssh

SSH port has been successfully changed. To connect to the server with SSH custom port use the next command.

# ssh [email protected]_address  -p54321

Restrict SSH Access Using iptables

You can restrict SSH connection to only allow authorized IP addresses.
To allow SSH connections only from run the following command:

# iptables -A INPUT -p tcp -m tcp --dport 54321 -s -j ACCEPT

To disable SSH connection from all other hosts run the following command:

# iptables -A INPUT -p tcp -m tcp --dport 54321 -m state --state NEW -j DROP

Save your new rules using the following command:

# iptables-save > /etc/sysconfig/iptables

Use SSH Keys Instead of Passwords

Using passwords for SSH authentication is insecure. If one of your users sets a weak password, your server can be compromised. To avoid this, you can use ssh key for authentication without a password.

Please take a look at the guide – How to set up SSH keys

Disable Password-Based Logins on Your Server

Password authentication in SSH is a big security risk if your user sets a weak password. If you are using SSH keys for SSH authentication, you can disable the server password authentication altogether.

You need to edit sshd configuration file.

# nano /etc/ssh/sshd_config

Find the line that contains the PasswordAuthentication and change it to “no”

Warning! Before restarting the ssh daemon to take the changes into effect, be sure you have created and configured an SSH key to use for login.

Restart sshd service to apply the configuration.

# systemctl restart sshd

I showed you the basic security tips for an SSH server.