08 - Protect the mail server with Fail2Ban

As I mentioned in other pages, it's a good ideea to slow down the brute force attackers with tools like fail2ban.
On FreeBSD, fail2ban can protect specific services using the firewall, ipfw or pf. Since I don't want this server to use multiple firewalls, I only enable ipfw protection methods.

If the kernel configuration file is the same as on the first page, IPFW firewall should be enabled on startup, using a 'default allow' policy. You should take this in consideration when setting up the firewall. Fail2ban banning method with ipfw refers ti a 'table 1', where it adds offending IP addresses. I don't want to change this behaviour, so I'll use the IPFW table numbered 1 for this purpose. If the kernel is compiled with the default configuration file, there should be added additional rules to /etc/rc.firewall.local, to allow more traffic, or a 'ipfw add 65000 pass ip from any to any' rule, since the ipfw module installed by default uses a 'default deny' policy.

### Enable the firewall, add a DENY rule for TCP packets coming from table\(1\), table used by fail2ban to hold offending hosts. It is possible to use pf instead of ipfw

# cat << DELIMITER > /etc/rc.firewall.local
fwcmd="/sbin/ipfw -q"

# Flush old rules
${fwcmd} flush

# Block hosts detected as offending by fail2ban
${fwcmd} add deny tcp from table\(1\) to any

Make the firewall script startable by the /etc/rc.d/ipfw script
# chmod +x /etc/rc.firewall.local
# echo 'firewall_enable="YES"' >> /etc/rc.conf
# echo 'firewall_script="/etc/rc.firewall.local"' >> /etc/rc.conf

The rules can be applied immediately
# /etc/rc.d/ipfw start

### Fail2ban installation and setup

# cd /usr/ports/security/py-fail2ban; portupgrade -Np

### Adjust fail2ban timing parameters and ignoreip list
### Create the jails for fail2ban. Adjust timing parameters to taste. If anything goes wrong, the banned hosts list can be purged using 'ipfw table\(1\) flush' or 'ipfw table 1 delete'.

# cat << DELIMITER >> /usr/local/etc/fail2ban/jail.conf
enabled = true
filter = dovecot
action = bsd-ipfw
logpath = /var/log/maillog
maxretry = 2
bantime = 43200

enabled  = true
filter   = postfix
action   = bsd-ipfw
logpath  = /var/log/maillog
bantime  = 3600
maxretry = 8

enabled  = true
filter   = sasl
action   = bsd-ipfw
logpath  = /var/log/maillog
bantime  = 3600
maxretry = 3

### Enable automatic startup for fail2ban

# echo 'fail2ban_enable="YES"' >> /etc/rc.conf
### Start fail2ban
# service fail2ban start
### Test if it's working properly. Login to another host and force some failures which should trigger fail2ban, check /var/log/fail2ban.log

Prev: Configure Postfix with MySQL support, SASL, Dovecot LDA, virtual users