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

Solution 1:

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.

Solution 2:

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