#!/bin/bash
# fixed 95/01/24
# purpose: check /var/log/secure with illegal trying to login, and
# call iptables to drop this ip
# vi /etc/hosts.allow
# sshd: ALL: spawn ( /etc/sshdropinvalidip.sh )& : ALLOW
#
logfile="/var/log/secure"
droplist="/etc/sshdropinvalidip.txt"
filterroot="Failed password for root"
filterinvaliduser="Failed password for invalid user"
getlines="33"
limitcounts="5"
checkfilterroot=`/usr/bin/tail -n $getlines $logfile | grep -ir "$filterroot" | awk '{print $11}' | sort`
checkfilterinvaliduser=`tail -n $getlines $logfile | grep "$filterinvaliduser" | awk '{print $13}' | sort`
echo "### check Failed password for root"
echo "$checkfilterroot"
echo "### check Failed password for invalid user"
echo "$checkfilterinvaliduser"
echo ""
echo "### filterroot line"
/usr/bin/tail -n $getlines $logfile | grep -ir "$filterroot" | awk '{print $11}' | sed 's/::ffff://' | sort | uniq |
while read ip; do
echo "try to illegally login from $ip"
checkfilterrootipcount=`echo $checkfilterroot | grep $ip | wc -w`
echo "try to illegally login counts $checkfilterrootipcount"
if [ $checkfilterrootipcount -gt $limitcounts ]; then
echo "must be dropped $ip"
iptablescurrentip=`iptables -L INPUT -n | grep "$ip" | grep "tcp dpt:22" | awk '{print $4}'`
if [ -z $iptablescurrentip ]; then
echo "iptables insert $ip"
echo $ip >> $droplist
iptables -I INPUT -s $ip -p tcp –dport 22 -j DROP
iptables -I FORWARD -s $ip -p tcp –dport 22 -j DROP
echo "done"
else
echo "had has $ip, do nothing"
echo "done"
fi
else
echo "pass $ip"
fi
done
echo "### filterinvaliduser"
/usr/bin/tail -n $getlines $logfile | grep "$filterinvaliduser" | awk '{print $13}' | sed 's/::ffff://' | sort | uniq |
while read ip; do
echo "try to illegally login from $ip"
checkfilterinvaliduseripcount=`echo $checkfilterinvaliduser | grep $ip | wc -w`
echo "try to illegally login counts $checkfilterinvaliduseripcount"
if [ $checkfilterinvaliduseripcount -gt $limitcounts ]; then
echo "must be dropped $ip"
iptablescurrentip=`iptables -L INPUT -n | grep "$ip" | grep "tcp dpt:22" | awk '{print $4}'`
if [ -z "$iptablescurrentip" ]; then
echo "iptables insert $ip"
echo $ip >> $droplist
iptables -I INPUT -s $ip -p tcp –dport 22 -j DROP
iptables -I FORWARD -s $ip -p tcp –dport 22 -j DROP
echo "done"
else
echo "had has $ip, do nothing"
echo "done"
fi
else
echo "pass $ip"
fi
done
留言