[CentOS] iptables - how to block established connections with fail2ban?

Fri Jun 28 14:58:42 UTC 2019
Bowie Bailey <Bowie_Bailey at BUC.com>

On 6/26/2019 2:41 AM, MRob wrote:
> I am working to a CentOS 6 server with nonstandard iptables system without rule for
> ACCEPT ESTABLISHED connections. All tables and chains empty (flush by legacy custom
> script) so only filter/INPUT chain has rules (also fail2ban chain):
> Chain INPUT (policy ACCEPT)
> target     prot opt source               destination
> f2b-postfix   tcp  --  
> ACCEPT     all  --
> ACCEPT     all  --
> ACCEPT     tcp  --             tcp dpt:22
> ACCEPT     tcp  --             tcp dpt:25
> ACCEPT     tcp  --             tcp dpt:80
> ACCEPT     tcp  --             tcp dpt:443
> ACCEPT     tcp  --             tcp dpt:587
> ACCEPT     tcp  --             tcp dpt:993
> ACCEPT     tcp  --             tcp dpt:995
> DROP       tcp  --             tcp flags:0x17/0x02
> Chain f2b-postfix (1 references)
> target     prot opt source               destination
> REJECT     all  --           reject-with
> icmp-port-unreachable
> REJECT     all  --           reject-with
> icmp-port-unreachable
> RETURN     all  --  
> When fail2ban block a IP address, established connections are allowed to continue,
> but with no rule to accept established connections how is that possible? Why
> doesn't f2b first rule block established connections?

The way I solved this problem was using conntrack.  I added entries to the fail2ban
action to delete connections where the source or destination matched the IP I was
trying to block.  This results in all communications from that IP being dropped
immediately.  I used a .local file to redefine the actionban.  It looks like this:

$ cat firewallcmd-allports.local
actionban = firewall-cmd --direct --add-rule ipv4 filter f2b-<name> 0 -s <ip> -j
            (conntrack -D -s <ip>; exit 0)
            (conntrack -D -d <ip>; exit 0)

You have to install the conntrack-tools package to use the conntrack command, but I
don't remember having to do anything else to make it work.