Kill Large Scale Spammers quickly

Questions and answers about how to do stuff
Post Reply
ethandee178
Posts: 42
Joined: 26 May 2015 16:28

Kill Large Scale Spammers quickly

Post by ethandee178 »

A few weeks ago, we started getting extremely large queues of spam, typically between 10k and 100k emails in the queue. Always all spam.
Because of this, proper emails were taking 4-12 hours to get through the filter.
We took some steps with the firewall to avoid this. But I quickly noticed that the ip-base was sporadic, but the domains were always the same. Not the same domains every time, but that one domain was sending all the spam. :dance: Which is great for me. because I already wrote a script that would clean out large amounts of mail that I specify if/when there is a pattern.
Since these 'attacks' won' t go away, :naughty: I now have a cron job running this script. And I thought it may help others.
Use it if you'd like. The LIMIT variable is the max number of emails a domain should be sending. Mine is 400 because a client of ours generates 300 or so emails at a time occasionally. And I didn't want his deleted. I recommend you analyze your need first before running this.

#!/bin/bash
# The LIMIT variable is the trigger for if someone is sending too much (spammers)
LIMIT=400
COUNTER="0"
temp=""

#Separate and Sort Mailq by sender domain and clear the screen (it produces some output)
#/tmp/Queueload.txt is the text file with sender domains in it.
mailq | grep -v postmaster@ | grep @ | grep -v " " | sed 's/.*\@//' | grep -v ">: " | sort | uniq -c | sort -nr -o /tmp/Queueload.txt
cat /tmp/Queueload.txt | sed 's/ //g' | sed 's/ /,/g' | sed 's/^,//;w /tmp/Queueload.txt'
clear

#mailq begins to be manipulated again starting with /tmp/mailq.txt
mailq | tail -n +2 > /tmp/mailq.txt

#remove unnecessary lines from /tmp/mailq.txt and save the results in /tmp/mailq2.txt
while read j; do
let COUNTER=COUNTER+1;
if [ "$j" != "" ]; then
if [[ "$j" != *"Kbytes in"* ]]; then
temp="$temp""$j";
fi;
else
echo $temp >> /tmp/mailq2.txt;
temp="";
COUNTER="0";
fi;
done < /tmp/mailq.txt
#remove top lines from /tmp/mailq2.txt and create /tmp/mailq3.txt
cat /tmp/mailq2.txt | tail -n +2 > /tmp/mailq3.txt

#start reading Queueload and find out if any domain has sent a number ($NUM) that is greater than the limit ($LIMIT)
#If so, delete all of the mail from this sender domain ($DOMAIN)
while read f; do
NUM=`echo $f | sed 's/,.*//'`
DOMAIN=`echo $f | sed 's/.*,//'`

if [ "$NUM" -gt "$LIMIT" ]
then
while read k; do
if [[ "$k" == *"$DOMAIN"* ]]; then
echo $k | cut -c1-11 | postsuper -d -;
fi;
done < /tmp/mailq3.txt
fi
done < /tmp/Queueload.txt

#cleanup tmp files
rm /tmp/Queueload.txt
rm /tmp/mailq*.txt
Post Reply