nginx+iptables+ipset 封禁频繁访问web服务的恶意IP

7 篇文章 1 订阅

ipset就像一个集合,把需要封闭的ip地址写入这个集合中,ipset 是O(1)的性能,可以有效解决iptables直接封禁大量IP的性能问题。

  • 如果是RedHat/CentOS,首先用yum(Ubuntu/Debian用将yum换为apt-get既可 )安装ipset。

    yum install ipset -y

  • ipset创建基于ip hash的集合名称,例如blacklist,timeout 3600 表示封禁3600s; iptables开启封禁80,443策略

  • ipset create blacklist hash:ip timeout 3600
    # 当然也可以不加timeout 3600 ,也可以只写ipset create blacklist hash:ip , blacklist 为集合名称,可随意, 不加就是长期封闭
    iptables -A INPUT -p tcp -m set --match-set blacklist src -m multiport --dports 443,80 -j DROP
    
    # 封禁黑名单IP的所有请求
    iptables -I INPUT -p tcp -m set --match-set blacklist src -m multiport -j DROP
    # iptables v1.4.7: multiport expection an option
    
    # 如果报上面的错误,需要按如下写
    -A INPUT -p tcp -m multiport --destination-port 443,80 -m set --match-set blocklist src -j DROP
    

    基于自定义访问频率阈值或者请求敏感关键字来创建自动筛选恶意IP的脚本/data/iptables_ipset_deny.sh。

  • #!/bin/bash
    # FILES: nginx的access.log文件
    FILES="/data/nginx/logs/access.log"
    # sensitive: 敏感关键字
    sensitive="sensitive_word"
    # threshold: 一分钟内请求频率阈值
    threshold=1000
     
    ip_file="/tmp/ip_file"
    sensitive_file="/tmp/sensitive_file"
    DATE=`date -d '1 minutes ago' +%Y:%H:%M`
     
    grep ${DATE} ${FILES} | awk '{print $1}' | sort | uniq -c | sort -n | tail -n 1 > ${ip_file}
    grep ${DATE} ${FILES} | grep -i ${sensitive} | awk '{print $1}' | sort -n | uniq > ${sensitive_file}
     
    ip_file_number=`awk '{print $1}' ${ip_file}`
    ip_file_ip=`awk '{print $2}' ${ip_file}`
     
    if [[ $ip_file_number -gt $threshold ]];then
        ipset add blacklist ${ip_file_ip} timeout 3600
    fi
    
    if [ -s ${sensitive_file} ];then
        for sensitive_ip in `cat ${sensitive_file}`
        do
            ipset add blacklist ${sensitive_ip}
        done
    fi
    

    py脚本

  • #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    #
    import os
    import time
    
    threshold = 120
    # 获取前一分钟的结果
    date = time.strftime('%Y:%H:%M', time.localtime(time.time()-60))
    filename = '/usr/share/nginx/logs/geokon.access.log '
    
    def popen(command):
        return os.popen(command).readlines()
    
    def main():
        with open('/tmp/ipset.txt', 'a') as f:
            f.write('%s: 日志搜索...........\n' % (date))
            command = "grep %s %s | awk '{counts[$1]++}; END {for(url in counts) print counts[url], url}'" % (date, filename)
            for ip in popen(command):
                num, ipaddr = ip.split(' ')
                num, ipaddr = int(num), ipaddr.strip()  # 第一个值是整型, 第二个值应当去掉空格
                if num >= threshold:
                    if all(popen('ipset list | grep %s' % (ipaddr))):  # 如果不为true 那就添加
                        f.write('每分钟大于%s次 地址: %s 将被禁止访问' % (threshold, ipaddr))
                        popen('ipset add blacklist %s timeout 3600 &>/dev/null' % (ipaddr))
                elif num >= 50:
                    f.write('访问次数 %s: %s\n' % (num, ipaddr))
            f.write('日志搜索结束.................\n\n\n')
    
    if __name__ == '__main__':
        main()
    

    用crontab定时启动脚本。

  • echo "* * * * * bash /data/iptables_ipset_deny.sh" >> /etc/crontab
    
    # 当然也可以配置crontab一分钟执行一次定时任务:
    */1 * * * * bash /data/iptables_ipset_deny.sh
    

    查看black地址

  • ipset list
    删除地址

  •  ~]# ipset del ipsetname 地址 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值