Brain Phrye

code cooking diy fiction personal photos politics reviews tools 


Fail2ban on FreeBSD

I’ve come across a number of posts describing how to set up fail2ban on FreeBSD. Every damn one of them modifies a .conf file which is a fail2ban no-no. And the package in ports even tells you this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
Please do not edit the fail2ban.conf, jail.conf, or any other
files in the distributen as they will be overwritten upon each
upgrade of the port. Instead, create new files named *.local e.g.
fail2ban.local or jail.local.

For more information, see the official manual:
http://www.fail2ban.org/wiki/index.php/MANUAL_0_8#Configuration

If you have custom filters or actions and you are upgrading from
0.9.x please check them.

So I’m going to describe here how you configure fail2ban in FreeBSD to keep an eye on ssh failed logins without changing any of the distributed .conf files and maybe people will stop doing that.

First, create the file for the ipfw rules in /usr/local/etc/ipfw.rules:

1
2
3
4
5
6
7
8
9
# Initial setting
/bin/sh /etc/rc.firewall open

# fail2ban IPs
if ! ipfw table 1 info > /dev/null 2>&1; then
  ipfw table 1 create
  ipfw table 1 flush
fi
ipfw add 1 deny ip from "table(1)" to me

To get these to be run on boot run these commands:

1
2
3
4
5
if ! sysrc -f /etc/rc.conf -c firewall_enable=YES; then
  sysrc firewall_enable="YES"
  sysrc firewall_type="open"
  sysrc firewall_script="/usr/local/etc/ipfw.rules"
fi

To get this working without rebooting, run service ipfw restart.

Next up, install fail2ban: pkg install py36-fail2ban

Now you just need to configure it. Add the following two files:

/usr/local/etc/fail2ban/action.d/ipfw-table.local :

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
# Fail2Ban configuration file
#
# Author: Nick Munger
# Modified by: Cyril Jaquier
# Modified by: Kevin Lyda

[Definition]

actionstart =
actionstop =
actioncheck =
actionban = ipfw table 1 add <ip>
actionunban = ipfw table 1 delete <ip>

/usr/local/etc/fail2ban/jail.local :

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
[DEFAULT]
ignoreip = 127.0.0.1/8

# JAILS
[sshd]
enabled = true
mode = aggressive
action = ipfw-table[name=SSH,port=ssh,protocol=tcp]
logpath = /var/log/auth.log
findtime = 600
maxretry = 3
bantime = 3600

Note changing findtime and bantime to prime numbers a bit larger than those defaults will probably frustrate attackers a little bit more. Running primes 3600 4000 can give you some options.

To get this working without rebooting, run service fail2ban restart.

There you go. No distributed .conf files modified. This is now easy to keep up to date while maintaining your customisations.