Block SSH Access with hosts.allow and hosts.deny
How to block or allow IP addresses on Linux using two simple files? These files are hosts.allow and hosts.deny, and they allow you to block or allow IP addresses quickly, without dealing with complicated firewall rules.
With this capability, you can quickly block a suspicious IP address to avoid potential malicious activities; or you can limit, for example, SSH connections only to specific addresses, so you don't have to worry about third parties gaining access to your servers or computers.
Let me show you how it's done, demonstrating SSH access to a machine. All you need is a running Linux instance and a user with sudo privileges.
Log in to your Linux machine and open a terminal window. First, let's deny all access to the SSH daemon. Open the hosts.deny file with the command sudo nano /etc/hosts.deny. At the end of this file, add:
sshd: ALL
Save and close the file.
Next, open the hosts.allow file with the command sudo nano /etc/hosts.allow. Let's say you want to allow SSH access only for two machines on your network, at IP addresses 192.168.1.62 and 192.168.1.152. To do this, add the line:
sshd: 192.168.1.62, 192.168.1.152
Save and close the file.
At this point, only these two machines are allowed to access your computer or server via SSH. Keep in mind that the hosts.deny file is read before hosts.allow, so setting sshd: ALL in hosts.deny is only overridden if there's an entry in hosts.allow.
If you set hosts.deny with sshd: ALL and don't add a corresponding entry in hosts.allow, nobody will be allowed to access the machine via SSH. And that's it! You've added another layer of security to your Linux machines using hosts.deny and hosts.allow.
That was just one piece. The course teaches the whole path — from your first command to exam day.