Allow SSH for specific IP Address and block all others

Allow SSH for specific IP Address and block all others

Solution 1:

Using /etc/hosts.allow And /etc/hosts.deny File

SSHD will first check /etc/hosts.allow for entries. If there is no rule in /etc/hosts.allow which fits SSHD will go on checking /etc/hosts.deny for rules.

So you need to add:

vim /etc/hosts.deny

sshd: ALL EXCEPT LOCAL

To block every SSH connection, except localhost, which is not in /etc/hosts.allow.

vim /etc/hosts.allow

sshd: 192.168.178.10

sshd: 192.168.178.11

sshd: 192.168.178.10/255.255.255.0

To allow specific IPs. Last rule is an example for an IP range.

Solution 2:

Using iptables

However using /etc/hosts.allow and /etc/hosts.deny is not the recommended method to allow SSH only for a few IPs. You should consider using iptables for that job.

You could allow SSH for a specific IP by using a rule like:

iptables -A INPUT -m state –state NEW,ESTABLISHED,RELATED –source x.x.x.x -p tcp –dport 22 -j ACCEPT

iptables -A INPUT -m state –state NEW,ESTABLISHED,RELATED -p tcp –dport 22 -j DROP

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.