自动防御系统- telnet ,ftp,pop3
#!/bin/bash#Basic defence hack script //描述脚本作用,防御攻击
WORKDIR=/var/log/deny_ip #设定脚本工作目录
if [ ! -d $WORKDIR ];then
mkdir -p $WORKDIR
fi
#Get suspect record from log in nearest 1 min.
LOGFILE=/var/log/secure #从/var/log/secure日志中提取错误日志
LOGFILE2=/var/log/deny_ip/secure.log #放到本地脚本中减少资源损耗
ACTION=`env LC_TIME=en date +%e" "%H":"%M":" -d -1min` #设置时间为当前时间的前1分钟
#sshd keywords
word1="login" #提取错误日志的关键字1
word2="proftpd"
word3="popa3d"
word4="imapd"
word5="invalid password for"
word6="connect from"
grep "$ACTION" $LOGFILE |grep -E "$word1|$word2|$word3|$word4|$word5|$word6" > $LOGFILE2
#上面这步将含有关键字1和2的记录放在交换文件中,下面四句作用是提取错误日志中含有关键字的记录中的IP,也就是猜你密码的那些IP地址。然后把这些IP进行排序和计数,方便后面继续进行判断。
#Nov 23 06:25:17 ai2 login: invalid password for 'root'on '/dev/pts/0' from '124.128.87.156'
#Nov 23 06:30:30 ai2 login: invalid password for 'UNKNOWN'on '/dev/pts/0' from '124.128.87.156'
#Nov 24 08:09:00 ai2 in.telnetd: connect from 118.232.252.46 (118.232.252.46)
#Nov 24 08:09:01 ai2 login: invalid password for 'UNKNOWN'on '/dev/pts/0' from '118-232-252-46.dynamic.kbronet.com.tw'
#猜密码
grep "$word1" $LOGFILE2 |grep "$word5" |awk '{print $13}'|sed "s/'//g" > $WORKDIR/iplist1
grep "$word1" $LOGFILE2 |grep "$word5" |awk '{print $13}'|sed "s/'//g"|awk -F "." '{print $1}'|grep '-'|sed "s/-/./g" >> $WORKDIR/iplist1
#Nov 23 09:06:36 ai2 proftpd: connect from 177.159.14.42 (177.159.14.42)
grep "$word2" $LOGFILE2 |grep "$word6" |awk '{print $8}' >> $WORKDIR/iplist1
#Nov 23 17:53:59 ai2 popa3d: connect from 176.61.137.234 (176.61.137.234)
grep "$word3" $LOGFILE2 |grep "$word6" |awk '{print $8}' >> $WORKDIR/iplist1
#Nov 23 18:54:02 ai2 imapd: connect from 176.61.137.234 (176.61.137.234)
grep "$word4" $LOGFILE2 |grep "$word6" |awk '{print $8}' >> $WORKDIR/iplist1
#排除域名网IP和192.168.10.1的外网IP
scanner=`cat $WORKDIR/iplist1|grep -v '192.168.'|grep -v '27.115.75.253'| sort|uniq -c|awk '{print $1"="$2}'`
#设计一个循环,区分哪些IP是可疑IP,初步设定为一分钟内出现了5次密码错误或错误用户的IP,可以自己改。
for i in $scanner
do
#定义一个变量NUM,以“=”作为分隔符,NUM将获取这个IP一分钟内出现的次数,变量IP将记录对应的IP地址。
declare -i NUM
NUM=`echo $i|awk -F= '{print $1}'`
IP=`echo $i|awk -F= '{print $2}'`
#判断,如果NUM变量大于5次,同时iptables的INPUT链中,没有出现过这个IP,则直接用iptables丢弃所有来自这个IP地址发送的请求。同时把这个丢弃该IP的时间,以及这个IP在这个时间段内被记录的次数进行登记。
if [ $NUM -gt 5 ] && [ -z "`iptables -vnL INPUT|grep $IP`" ] ;then
/usr/sbin/iptables -I INPUT -s $IP -m state --state NEW,RELATED,ESTABLISHED -j DROP
echo "`date`" >> $WORKDIR/scanner.log
echo "$IP"="$NUM" >> $WORKDIR/scanner.log
echo "$IP" >> $WORKDIR/oldrecord.log
else
echo "`date`" >> $WORKDIR/suspect.log
echo "$NUM"="$IP" >> $WORKDIR/suspect.log
fi
done
页:
[1]