IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    Linux中通过cron定时任务过滤WEB攻击源IP

    公子发表于 2015-08-15 14:36:57
    love 0

    最近发现服务器流量有些异常,通过日志查看到有一些IP大量访问服务器,于是找到了这个脚本来过滤此类IP,具体规则为,如果在10000个请求中,有1000个请求来自于同一个IP,那么这个IP即可判定为攻击IP。

    在服务器上新创建一个脚本文件:

    vi block_ips.sh
    

    放入以下内容:

    #!/bin/bash
    
    logfiles=(
    /tmp/logs/rainbow_access.log
    /tmp/logs/eric_access.log
    )
    
    whitelist=$(last | awk '{print $3}' | grep ^[1-9] | sort | uniq | xargs)
    
    function check_root(){
      if [ $EUID -ne 0 ]; then
        echo "This script must be run as root"
        exit 1
      fi
    }
    
    function block_ips(){
      blacklist=$@
      if [ ! -z "${blacklist}" ]; then
        for ip in ${blacklist}
        do
          if ! $(echo ${whitelist} | grep -wq ${ip}); then
            if ! $(/sbin/iptables-save | grep -wq ${ip}); then
              echo "Blocked ${ip}"
              /sbin/iptables -I INPUT -s ${ip}/32 -p tcp -m tcp --dport 80 -j DROP
            fi
          fi
        done
      fi
    }
    
    function check_post(){
      page=$1
      tailnum=$2
      retry=$3
    
      command="grep -w POST ${logfile} |tail -n ${tailnum} |grep -w ${page} |awk '{print \$1}' |sort |uniq -c |awk '(\$1 > ${retry}){print \$2}'"
      blacklist=$(eval ${command})
      block_ips ${blacklist}
    }
    
    function check_all(){
      tailnum=$1
      retry=$2
    
      command="tail -n ${tailnum} ${logfile} |awk '{print \$1}' |sort |uniq -c |awk '(\$1 > ${retry}){print \$2}'"
      blacklist=$(eval ${command})
      block_ips ${blacklist}
    }
    
    check_root
    for logfile in ${logfiles[@]}
    do
      check_post wp-login.php 10000 100
      check_post wp-comments-post.php 10000 100
      check_all 10000 1000
    done
    
    

    为该文件赋予可编辑权限:

    chmod +x block_ips.sh
    

    添加自动任务,没5分钟执行一次:

    vi /etc/crontab
    

    加入以下内容:

    */5 * * * * /home/rainbow/sbin/block_attack_ips.sh
    00 01 * * * /etc/init.d/iptables restart
    

    即可。



沪ICP备19023445号-2号
友情链接