Restrict ssh access using Iptable

by on January 31, 2006 · 1 comment· LAST UPDATED November 29, 2007

in

Q. How do I stop or restrict access to my OpenSSH (SSHD) server using Linux iptables based firewall?

A. Linux iptables firewall can be use to block or restrict access to ssh server. Iptables command is used to set up, maintain, and inspect the tables of IP packet filter rules in the Linux kernel. However, you can also use tcpd, access control facility for internet services.

Use iptables to Restrict ssh access

Following is simple rule that block all incoming ssh access at port 22
iptables -A INPUT -p tcp -s 0/0 --sport 513:65535 -d 195.55.55.78 --dport 22 -m state --state NEW,ESTABLISHED -j DROP

However in real life you need to use something as follows. Let us assume that your ssh server IP address is 195.55.55.78, remember ssh server use TCP port 22 for all incoming connection. With iptables you can block all incoming connection at port 22 with following two rules:

iptables -A INPUT -p tcp -s 0/0 --sport 513:65535 -d 195.55.55.78 --dport 22 -m state --state NEW,ESTABLISHED -j DROP
iptables -A OUTPUT -p tcp -s 195.55.55.78 --sport 22 -d 0/0 --dport 513:65535 -m state --state ESTABLISHED -j DROP

If you just want to deny access to group of IPS then you need to add following rules to your script:
IPS="202.54.1.20 64.66.44.22 64.66.44.25"
for i in $IPS
do
iptables -A INPUT -p tcp -s 0/0 -s $i --sport 513:65535 -d 195.55.55.78 --dport 22 -m state --state NEW,ESTABLISHED -j DROP
iptables -A OUTPUT -p tcp -s 195.55.55.78 --sport 22 -d $i --dport 513:65535 -m state --state ESTABLISHED -j DROP
done

Add all of above rules to your iptables firewall shell script (do not type @ shell prompt)

See also:

TwitterFacebookGoogle+PDF versionFound an error/typo on this page? Help us!

{ 1 comment… read it below or add one }

1 jump June 1, 2010 at 2:16 pm

How to forbid access on SSH from all addresses except the defined?

Reply

Leave a Comment

Tagged as: , , , , , , , , , , , , ,

Previous Faq:

Next Faq: