Fail2ban and LXC containers

When using Fail2ban (log file scanner and ip blocker) with LXC containers, Fail2ban is usually installed on the host where it scans container log files. Let’s watch apache error logs of a lxc container called “MYCONTAINER”.

First configure a jail in /etc/fail2ban/jail.conf on the host:

[apache]

enabled  = true
port     = http,https
filter   = apache-auth
logpath  =  /var/lib/lxc/MYCONTAINER/rootfs/var/log/apache*/*error.log
maxretry = 6

Now create an action with FORWARD rules for NAT hosts/LXC containers, because by defult Fail2ban just creates INPUT rules.
I recommend ipset with Fail2ban, it allows mass blocking IPs without flooding an iptables chain.

First install ipset:

apt-get install ipset

Copy an existing ipset action:

cd /etc/fail2ban/action.d
cp iptables-ipset-proto6.conf iptables-ipset-proto6-fwd.conf 

Now add a FORWARD rule (copy corresponding INPUT rule) to actionstart and actionstop in /etc/fail2ban/action.d/iptables-ipset-proto6-fwd.conf:

[Definition]

# Option: actionstart
# Notes.: command executed once at the start of Fail2Ban.
# Values: CMD
#
actionstart = ipset -exist create fail2ban-<name> hash:ip timeout <bantime>
 iptables -I INPUT -p <protocol> -m multiport --dports <port> -m set --match-set fail2ban-<name> src -j <blocktype>
 iptables -I FORWARD -p <protocol> -m multiport --dports <port> -m set --match-set fail2ban-<name> src -j <blocktype>

# Option: actionstop
# Notes.: command executed once at the end of Fail2Ban
# Values: CMD
#
actionstop = iptables -D INPUT -p <protocol> -m multiport --dports <port> -m set --match-set fail2ban-<name> src -j <blocktype>
 iptables -D FORWARD -p <protocol> -m multiport --dports <port> -m set --match-set fail2ban-<name> src -j <blocktype>
 ipset flush fail2ban-<name>
 ipset destroy fail2ban-<name>

Adjust the default banaction in /etc/fail2ban/jail.conf:

banaction = iptables-ipset-proto6-fwd

Restart fail2ban:

service fail2ban restart

Check iptables:

# iptables -L -n
Chain INPUT (policy ACCEPT)
target     prot opt source               destination         
REJECT     tcp  --  0.0.0.0/0            0.0.0.0/0            multiport dports 80,443 match-set fail2ban-apache-auth src reject-with icmp-port-unreachable
...
Chain FORWARD (policy ACCEPT)
target     prot opt source               destination         
REJECT     tcp  --  0.0.0.0/0            0.0.0.0/0            multiport dports 80,443 match-set fail2ban-apache-auth src reject-with icmp-port-unreachable
...

List blocked IPs:

# fail2ban-client status apache-auth
# ipset list fail2ban-apache-auth

Tested on Debian Jessie.

Advertisements