IPTables: allow SSH access only, nothing else in or out

How do you configure IPTables so that it will only allow SSH in, and allow no other traffic in or out?

Any safety precautions anyone can recommend?

I have a server that I believe has been migrated away from GoDaddy successfully and I believe is no longer in use.

But I want to make sure just because ... you never know. :)

Note that this is a virtual dedicated server from GoDaddy... That means no backup and virtually no support.


You need just to set the default policy to DROP on the INPUT and OUTPUT chains.

To allow SSH in, you need the following commands:

$ sudo iptables -P INPUT DROP
$ sudo iptables -P OUTPUT DROP
$ sudo iptables -A INPUT -i lo -j ACCEPT
$ sudo iptables -A INPUT -p tcp -m tcp --dport 22 -j ACCEPT
$ sudo iptables -A OUTPUT -o lo -j ACCEPT
$ sudo iptables -A OUTPUT -p tcp --sport 22 -m state --state ESTABLISHED -j ACCEPT

The last two commands allow loopback traffic as this is required by some applications to function correctly. You can restrict the SSH access from specific IP using -s source_ip option.

Executing the commands in order as shown above will cause your current SSH session to hang. This is because iptables commands take effect immediately. You need to execute them in a shell script to avoid losing the ability to connect to your machine when executing them remotely.


Something like this:

iptables -A INPUT -p tcp --dport 22 -j ACCEPT
iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
iptables -A INPUT -i lo -j ACCEPT
iptables -A INPUT -j REJECT  # or iptables -P INPUT DROP

iptables -A OUTPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
iptables -A OUTPUT -j REJECT # or iptables -P OUTPUT DROP