Linux – fail2ban block ports rules iptable

fail2baniptableslinuxsshUbuntu

I just installed Ubuntu Server 14.04 and don't have much experience with IPtables. I am trying to get a basic setup going where I only accept SSH connections on port 22 and 2222. I actually have that working with no problem using fail2ban ssh. Then I wanted to block all other ports except 423 and 4242 but either method of DROPing all connections that are not listed seems not to work and it blocks me out of everything. Below is the setup that works:

-P INPUT ACCEPT
-P FORWARD ACCEPT
-P OUTPUT ACCEPT
-N fail2ban-ssh
-A INPUT -p tcp -m multiport --dports 22,2222 -j fail2ban-ssh
-A fail2ban-ssh -j RETURN

I tried to change it either to:

-P INPUT DROP
-P FORWARD ACCEPT
-P OUTPUT ACCEPT
-N fail2ban-ssh
-A INPUT -p tcp -m multiport --dports 22,2222 -j fail2ban-ssh
-A fail2ban-ssh -j RETURN

or:

-P INPUT ACCEPT
-P FORWARD ACCEPT
-P OUTPUT ACCEPT
-N fail2ban-ssh
-A INPUT -p tcp -m multiport --dports 22,2222 -j fail2ban-ssh
-A INPUT -j DROP
-A fail2ban-ssh -j RETURN

I have noticed that the rules for fail2ban-ssh are automatically added to my iptables on boot because if I save them with iptables-persistant they are entered twice. How do I go about blocking everything accept those 2 ports using fail2ban? Is it a bad fail2ban configuration or do I need to add the

fail2ban-ssh -j Return

somewhere else in my code.

Best Answer

You need to have additional rule actually permitting you to connect, because fail2ban-ssh chain is created to add new rules from fail2ban programm.

Working example:

-P INPUT DROP
-P FORWARD ACCEPT
-P OUTPUT ACCEPT
-N fail2ban-ssh
-A INPUT -p tcp -m multiport --dports 22,2222 -s <YOUR-IP> -j ACCEPT
-A INPUT -p tcp -m multiport --dports 22,2222 -j fail2ban-ssh
-A fail2ban-ssh -j RETURN

This question isn't really related to fail2ban. In your "setup that works" actually any connection will work to any port except banned by fail2ban programm.