Last active
September 25, 2023 09:02
-
-
Save CurlyMoo/87cb5a42310a3b6daf1ce6a407185d50 to your computer and use it in GitHub Desktop.
Mailcow: Automatically add ip to blocklist
This file contains hidden or 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
# | |
# Add this file in your crontab. If there was a failed login, the ip | |
# address will be automatically added to the mailcow blocklist. | |
# | |
# I use mailcow in a personal setup so i only have one ip to be | |
# permanently allow listed. | |
# | |
# Update 19-08-2022 | |
# - Only check the IP's of the last hour (run hourly) | |
# - Only block IP's that have been blocked for 5 or more times | |
#!/bin/bash | |
export COMPOSE_INTERACTIVE_NO_CLI=1 | |
ORIFS=$IFS; | |
IFS=$' '; | |
DATE=$(date -d -1hour +'%Y-%m-%dT%H'); | |
BLACKLIST=($(docker-compose --project-directory /opt/mailcow-dockerized/ -f /opt/mailcow-dockerized/docker-compose.yml exec -T redis-mailcow redis-cli hgetall F2B_BLACKLIST | grep -E -o "([0-9]{1,3}[\.]){3}[0-9]{1,3}" | uniq | sed ':a;N> | |
NEWIPS=($(docker-compose --project-directory /opt/mailcow-dockerized/ -f /opt/mailcow-dockerized/docker-compose.yml logs -t netfilter-mailcow | grep $DATE | grep 'is banned' | grep -E -o "([0-9]{1,3}[\.]){3}[0-9]{1,3}" | uniq | sed ':a;> | |
IFS=$ORIFS; | |
MATCHED=0; | |
BLOCKED=0; | |
test -f /opt/block.tmp && rm /opt/block.tmp | |
for NIP in ${NEWIPS[*]}; do | |
MATCHED=0; | |
for CIP in ${BLACKLIST[*]}; do | |
if [ "$CIP" = "$NIP" ]; then | |
MATCHED=1; | |
fi | |
done | |
if [ $MATCHED -eq 0 ]; then | |
BLOCKED=1; | |
echo "Blocked: $NIP" | |
echo $NIP >> /opt/block.tmp | |
fi; | |
done | |
if [ $BLOCKED -eq 1 ]; then | |
sort /opt/block.tmp | uniq >> /opt/block.lst | |
sort /opt/block.lst | uniq -c > /opt/block.cnt | |
fi | |
for NIP in ${NEWIPS[*]}; do | |
if [ $(grep $NIP /opt/block.cnt | awk '{print $1}') -gt 4 ]; then | |
docker-compose --project-directory /opt/mailcow-dockerized/ -f /opt/mailcow-dockerized/docker-compose.yml exec -T redis-mailcow redis-cli hset F2B_BLACKLIST $NIP/32 1 1>/dev/null | |
fi | |
done | |
if [ $BLOCKED -eq 1 ]; then | |
docker-compose --project-directory /opt/mailcow-dockerized/ -f /opt/mailcow-dockerized/docker-compose.yml restart netfilter-mailcow 1>/dev/null 2>/dev/null | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment