Do you want to cut off SSH access to a Linux server? If you are a Linux administrator, you will be familiar with the usefulness of an SSH connection that allows you to have root functions on remote systems.
Due to the importance of the function, it is very likely that you have already taken many steps to lock SSH access. Using an SSH key for authentication instead of a simple password, and changing the default SSH port (22), may be the first steps you need to take, but they are not enough.
Below we will see one more step you can take. It is so easy and obvious that most managers forget that it exists as an option. This step does not require third-party software and can be configured in seconds.
What you will need
- A Linux server running SSH daemon
- The IP addresses of each client that needs access to the server
You should also have access to the remote server console in case something goes wrong and you are locked out, like every time you tease SSH.
The first thing we need to do is allow the IP address of any client that needs SSH access to the remote server. Once you have a list of IP addresses, you can add them to /etc/hosts.allow. To do this, run the command:
su
Enter the root password, and
nano /etc/hosts.allow
At the bottom of this file, add the following:
sshd: IP
Where IP is the IP address of the remote client that needs access to the server. If you have multiple IP addresses, you can enter them as follows:
sshd: 100.53.33.77/30, 100.73.152.9/22, 100.92.100.11/51, 100.22.192.0/44
Or something like this:
sshd: 192.168.1.1/24
sshd:127.0.0.1
sshd: [::1]
Save and close the file. Nano storage is done by typing CTRL + X together, then y, and Enter
How to block all other addresses
Now that we have allowed an IP address or a list of addresses, it is time to block all other addresses. One thing to know is that a Linux system first reads the hosts.allow file (top to bottom) and then the hosts.deny (top to bottom). Thus, an attempt to connect SSH from an IP address in hosts.allow will be allowed, although hosts.deny may block all IPs.
So, to block all other IP addresses, open the required file with the command:
nano /etc/hosts.deny
At the bottom of this file, add the following:
sshd: ALL