**We are currently moving to a new host. Please pardon any errors!**
Restrict SSH access by Country via hosts.allow and hosts.deny | Debugge
 

Restrict SSH access by country IP via hosts.allow and hosts.deny

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.

I’m using nano because it’s my favorite editor. Obviously you could use vi, pico, gedit, etc.

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

Remember: Do not close your SSH connection until you have tested this thoroughly so you don’t lock yourself out of your own server!

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.

Author:  Crimm

Software engineer (PHP, Bat, VBS), Sr. Systems Admin, Techie, Father, Gamer, Anime watcher (Wannabe Otaku), & full of geek!