Last active
January 27, 2024 01:40
-
-
Save zerwes/f9f659a0751ee3acb6ba8910a9185f3d to your computer and use it in GitHub Desktop.
opnsense fail2ban sync script
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /bin/bash | |
# complementing https://github.com/zerwes/opnsense-fail2ban | |
# script will check all banned IPs listed in a list of fail2ban jails | |
# and compare them against a opnsense alias, | |
# removing the elements that are not in the ban list from fail2ban | |
# | |
# this will ensure that banned IPs that for what reaseon ever are left | |
# in the opnsense alias are cleaned up (avoiding neverending bans) | |
declare -i DEBUG=0 | |
declare LOGLEVEL=CRITICAL | |
if [ "$1" = "-v" ]; then | |
DEBUG=1 | |
LOGLEVEL=INFO | |
fi | |
# for each opnsense_alias you use in your fail 2 ban actions, | |
# you should define one part of code like this | |
# name of the opnsense alias | |
declare F2BAN_BLOCK=F2BAN_BLOCK_main | |
[ $DEBUG -gt 0 ] && echo "... $F2BAN_BLOCK" | |
declare -a BANNEDIPS=() | |
# lopp all jails using the same action i.e. the same opnsense alias as defined in F2BAN_BLOCK | |
for jail in f2b_jail1 f2b_jail2; do | |
BANNEDIPS+=($(fail2ban-client get $jail banned | sed 's/^\[//g; s/]$//g; s/,//g')) | |
done | |
declare -a OPNIPS=($(/usr/local/sbin/opnsense-fail2ban.py -g $F2BAN_BLOCK -a list | grep "has the members" | sed "s/.*: //g;s/;/' '/g; s/^/'/g; s/$/'/g")) | |
# debug | |
if [ $DEBUG -gt 0 ]; then | |
echo "BANNEDIPS : ${BANNEDIPS[*]}" | |
echo "OPNIPS : ${OPNIPS[*]}" | |
fi | |
for ip in ${OPNIPS[@]}; do | |
[ $DEBUG -gt 0 ] && echo "... checking IP $ip" | |
if [[ "${BANNEDIPS[*]}" =~ "${ip}" ]]; then | |
[ $DEBUG -gt 0 ] && echo "$ip is OK" | |
else | |
[ $DEBUG -gt 0 ] && echo "$ip is NOTOK" | |
/usr/local/sbin/opnsense-fail2ban.py -g $F2BAN_BLOCK -a unban -i ${ip//\'/} -l $LOGLEVEL | |
fi | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment