Restrict SSH to one IP

firewall

Restricting access to SSH to only allow specified IPs is a good practice for securing your server. Also it is very simple to do. All it take is a change to one file and you are done. Be careful doing this if you have a dynamic IP. You don’t to get locked out of your server if your IP changes.

Open /etc/sysconfig/iptables with your texteditor

Remove or comment out your current SSH rule
It should look something like this: -A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT

Add these 2 lines, replace the xxx.xxx.xxx.xxx with the IP you want to allow access from. Also if you have changed your SSH port, change it in both lines to.

-A INPUT -p tcp -m state --state NEW --source xxx.xxx.xxx.xxx -m tcp --dport 22 -j ACCEPT
-A INPUT -p tcp -m state --state NEW  -m tcp --dport 22 -j DROP

If you would like to lock it down even more you can add ,ESTABLISHED,RELATED after NEW like this NEW,ESTABLISHED,RELATED. This make the rules apply to any established connections. So if someone is already connect via SSH and is not using an allowed IP their connect will be terminated when the rule is applied.

This is what my iptables config look like.

*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -p tcp -m state --state NEW --source 192.168.1.10 -m tcp --dport 22 -j ACCEPT
-A INPUT -p tcp -m state --state NEW  -m tcp --dport 22 -j DROP
-A INPUT -m state --state NEW -p tcp --dport 80 -j ACCEPT
-A INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -j REJECT --reject-with icmp-host-prohibited
COMMIT

Leave a Comment