Do you want to have SSH and/or SFTP available on your Linux (Ubuntu, Red Hat, Fedora, etc.) server and tired of seeing malicious IP’s from other countries trying to brute force into your server? I have an easy and quick solution for you. This is currently only written for US people, but if you read carefully you can easily apply this to your own country. This simple trick uses your hosts.deny and hosts.allow files to restrict what IP addresses can access your server via SSH.
Disclaimer: Be careful here, a simple typo can get you locked out of your own server. Make sure to connect via SSH and keep the connection open during this entire process. Open new SSH connections to test to ensure it’s working before you close the original SSH.
Step 1) Edit our hosts.allow file
sudo nano /etc/hosts.allow
Copy/Paste this text file:
(It’s big, so a wget may be easier. Don’t forget to back up the current hosts.allow first)
This text file uses the IP country range (CIDR format) for the United States that is found here, with some file formatting and additional statements that I added.
Step 2) Edit our hosts.deny file
sudo nano /etc/hosts.deny
Place this text in your hosts.deny file:
sshd,sshdfwd-X11: ALL
portmap: ALL
portmap: ALL
This says to deny everyone, except those IP addresses inside your hosts.allow file.
Step 3) Edits and testing
Remember to test, test, test, test! You can also add more IP’s, and ranges. A full good article on the hosts.allow file can be found here.
Finally, if you want to restrict your country, that isn’t the US, then you can simply replace the US IP’s with the IP ranges found here.