How to set up iptables to block all traffic except SSH?

Check the current iptables configuration

iptables -S

Your output should be empty as follows…

  -P INPUT ACCEPT
  -P FORWARD ACCEPT
  -P OUTPUT ACCEPT

 

If your iptables is not empty as above then extra ports could be open on your machine. In this case, to flush the table, type iptables -F, then check the iptables configuration by typing iptables -S.

 

Ensure to be root

su
 

Enter following configuration commands one line at a time. Please ensure the order of entry is the same as below, otherwise you may block SSH.

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

In the above, lo is for the loopback adapter which is required by some applications and without it some applications may break.

 

You may also want to allow all traffic to output. Therefore, the following rules would apply instead of the above…

   iptables -A INPUT -i lo -j ACCEPT
   iptables -A INPUT -p tcp -m tcp --dport 22 -j ACCEPT
   iptables -P INPUT DROP

 

If you would like to allowed established and related packets then the following rules would apply. Without this you will not be able to use apt-get and git requests. Use the following instead of the above 2 rule sets.

   iptables -I INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
   iptables -A INPUT -i lo -j ACCEPT
   iptables -A INPUT -p tcp -m tcp --dport 22 -j ACCEPT
   iptables -P INPUT DROP

Once you have decided the rules most appropriate for your system, you will need to save your rules, otherwise they will not persist after rebooting

Save your rules to a file

iptables-save > /etc/iptables.conf

The above saves your rule in a file. You will then need to load your rules on every reboot

nano /etc/rc.local

Add the following line to the file, above exit 0

iptables-restore < /etc/iptables.conf
 

Below are some meanings to the rules...

ESTABLISHED meaning that the packet is associated with a connection which has seen packets in both directions

RELATED meaning that the packet is starting a new connection, but is associated with an existing connection, such as an FTP data transfer, or an ICMP error.