Postfix ban failed logins script

Fail2ban hasn’t been working for me, I still have people running brute force attacks on my Postfix server, so I though I’d rig up something myself.

This consists of a bash script that identifies multiple failures and bans them, run on cron every 10 minutes. It checks for both smtp and pop/imap login failures.

#!/bin/sh
# postfix ban failed login ips
# get all failed ip addresses into files
cat /var/log/maillog | grep "authentication failed" | grep -Eo "([0-9]{1,3}[\.]){3}[0-9]{1,3}" > ~admin/mail_fail_smtp
cat /var/log/maillog | grep "auth failed" | grep -Eo "rip=([0-9]{1,3}[\.]){3}[0-9]{1,3}" > ~admin/mail_fail_imap
find ~admin/mail_fail_imap -type f -exec sed -i 's/rip=//g' {} \;
# only get over 5 fails (change the limit= part to change)
sort ~admin/mail_fail_imap | uniq -cd | awk -v limit=5 '$1 > limit{print $2}' > ~admin/mail_fail_imap_over5
sort ~admin/mail_fail_smtp | uniq -cd | awk -v limit=5 '$1 > limit{print $2}' > ~admin/mail_fail_smtp_over5
# read through files and add IP to hosts.deny if not there already
while read p; do
if grep $p /etc/hosts.deny; then
echo $p " already added"
else
echo ALL: $p >> /etc/hosts.deny
fi
done < ~admin/mail_fail_smtp_over5
while read p; do
if grep $p /etc/hosts.deny; then
echo $p " already added"
else
echo ALL: $p >> /etc/hosts.deny
fi
done < ~admin/mail_fail_imap_over5
# clean up
rm -f ~admin/mail_fail_smtp
rm -f ~admin/mail_fail_imap
rm -f ~admin/mail_fail_smtp_over5
rm -f ~admin/mail_fail_imap_over5

Then added to crontab:

*/10 * * * * /home/admin/postfix_ban_ips.sh > /dev/null

And just in case the localhost fails and is unintentionally blocked (this is quicker than filtering it out above):

echo "ALL: 127.0.0.1" >> /etc/hosts.allow

Monitor server cpu resources with email notification

I thought I’d write a quick script to keep an eye on which processes/users are using too many cpu cycles on my CentOS server. This checks the usage over the previous 5 minutes and emails a detailed list of cpu-hungry processes if it’s over the defined limit. Run it from cron to keep an eye on those resources:

#!/bin/bash
CPU_LIMIT="10" # relevant to number of cores, so quad-core at capacity is 4
EMAIL="your@email.com"
  if [ $(echo "$(cat /proc/loadavg | cut -d " " -f 2) >= $CPU_LIMIT" | bc) = 1 ]; then
ps ax --sort=-pcpu o user,pid,pcpu,pmem,vsz,rss,stat,time,comm | mail -s "CPU OVER LIMIT ON `hostname`" $EMAIL
  fi

That’s all folks!