Linux使用系统防火墙结合定时任务,自动拦截暴力破解密码的登录IP

177 阅读2分钟

本文已参与 ⌈新人创作礼⌋ 活动,一起开启掘金创作之路

Linux使用系统防火墙结合定时任务,自动拦截暴力破解密码的登录IP

使用方法:

  1. 复制到linux系统,命令为xxx.sh ;通过chmod +x 附加执行权限;
  2. 通过系统定时任务crontab -e 编辑定时任务,如每个小时执行一次 */60 * * * * /opt/xp/firewall.sh
#!/bin/bash
#脚本用途:从日志文件/var/log/secure中获取暴力破解密码的来源IP地址,并自动添加firewalld规则(破解次数超过10次)。
#配合crontab使用
#
#文件路径
file='/var/log/secure';
#logfile='./securelog.txt';
logfile='/opt/xp/securelog.txt';
#
#获取当前时间
current=`date +%Y-%m-%d_%H:%M:%S`;
echo "当前时间是:" $current "begin..." >> $logfile;
#
#截取当前时间中的日期
var=`date | cut -c 5-11`;
today=`date +"%b %_d"`;
#过滤/var/log/secure文件中当前日期,Failed password出现的次数;如果大于10次,则考虑增加firewalld规则
row_number=`cat /var/log/secure| grep "$today"| grep "Failed password"| wc -l`
if [ $row_number -lt 10 ];then
 echo "$row_number次破解,暂不处理" >> $logfile;
elif [ $row_number -ge 10 ];then
 echo "not secure"  >> $logfile;
 #
 #获取当前firewalld中IP地址
 #fire=`firewall-cmd --list-rich-rules | grep -v '/'|egrep -o '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'`;
 #
 #获取ip地址并去重,统计个数
 num=`cat $file | grep "Failed password"|egrep -o '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'| sort -u| wc -l`
 #echo $num;
 #
 #做if判断,如果为0,则没有攻击;如果为1,则有一个攻击来源ip,直接添加firewall规则;如果大于1个,则for循环抛出ip,添加规则。
 if [ $num -eq 0 ];then
  echo "very secure!">>$logfile;
 elif [ $num -eq 1 ];then
  #repeat 获取单个ip的重复次数,如果大于10,则认为是攻击,添加规则
  repeat=`cat $file | grep "Failed password"|egrep -o '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'| wc -l`
  if [ $repeat -gt 10 ];then
   ipcount=`cat $file | grep "Failed password"|egrep -o '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'| sort -u`
   firewall-cmd --add-rich-rule="rule family='ipv4' source address=$ipcount reject" &&  firewall-cmd --permanent --add-rich-rule="rule family='ipv4' source address=$ipcount reject"
   if [ $? -eq 0 ]; then
    echo "only one ip;add firewall rule succeed! $ipcount">>$logfile;
   else
    echo "only one ip;add firewall rule failed! $ipcount">>$logfile;
   fi
  fi
 elif [ $num -gt 1 ];then
  echo "more then one ip;" >> $logfile;
  for ip in `cat $file | grep "Failed password"|egrep -o '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'| sort -u`
  do
   # echo $ip;
   # firewall-cmd --add-rich-rule="rule family='ipv4' source address=$ip reject"
   if [ `cat $file | grep "Failed password"|egrep -o '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'|grep $ip|wc -l` -gt 10 ];then
    firewall-cmd --add-rich-rule="rule family='ipv4' source address=$ip reject" && firewall-cmd --permanent  --add-rich-rule="rule family='ipv4' source address=$ip reject"
    if [ $? -eq 0 ]; then
              echo "more then one ip;add firewall rule succeed! $ip">>$logfile;
                else
     echo "more then one ip;add firewall rule failed! $ip">>$logfile;
                fi

   fi
  done
 else
  echo "something error!!!" >> $logfile;
 fi

fi
#end