EdgeRouter Fail2Ban Persistence Through Upgrades

My last post detailed how to install and configure Fail2Ban on a Ubiquiti EdgeRouter to thwart brute force attacks against an OpenVPN server. Unfortunately, programs installed on EdgeRouters do not persist through upgrades because new images overwrite the filesystem. However, using a trick outlined here, we can set up the router to automatically install Fail2Ban and restore the settings.



First, copy your Fail2Ban configurations from the previous post into /config and create symlinks from the old location to the new:

sudo -i
mkdir /config/fail2ban
mkdir /config/fail2ban/filter.d
mv /etc/fail2ban/filter.d/openvpn.local /config/fail2ban/filter.d/
mv /etc/fail2ban/jail.local /config/fail2ban/
rm /etc/fail2ban/jail.local 
ln -s /config/fail2ban/jail.local /etc/fail2ban/jail.local
ln -s /config/fail2ban/filter.d/openvpn.local /etc/fail2ban/filter.d/openvpn.local

You may wish to confirm that Fail2Ban still works after a service fail2ban restart

Next, use vi to create a file at /config/scripts/post-config.d/install_fail2ban.sh with the content:

#!/bin/bash 
packages='fail2ban'
doneit='/var/lib/fail2ban_installed'
 if [ -e $doneit ]; then 
 exit 0 
fi
mount -t tmpfs -o size=30% tmpfs /var/lib/apt/lists
if [ $? != 0 ]; then
 echo Could not mount tmpfs on /var/lib/apt/lists 
 exit 1
fi
DEBIAN_FRONTEND=noninteractive apt-get update apt-get --no-install-recommends install -y $packages

if [ $? == 0 ]; then
 echo Package install successful
 ln -s /config/fail2ban/jail.local /etc/fail2ban/jail.local
 ln -s /config/fail2ban/filter.d/openvpn.local /etc/fail2ban/filter.d/openvpn.local
 service fail2ban restart
 touch $doneit 
else 
 echo Package install failed 
fi 
umount /var/lib/apt/lists
exit 0

Make sure that the script is executable via chmod 744 /config/scripts/post-config.d/install_fail2ban.sh

You should now be able to upgrade the router normally and the package and configuration will be automatically restored.

Note: If you are running an ER-X or ER-X-SFP, these may not have enough space to successfully install the software, in which case, you will need to delete the old system image via delete system image before the script can run successfully. After doing so, run the script manually via sudo /config/scripts/post-config.d/install_fail2ban.shor reboot the router again.

One Reply to “EdgeRouter Fail2Ban Persistence Through Upgrades”

Leave a Reply