menu LittleJake's Blog
color_lens
avatar
Jake Liu
Never Settle
creative commons by-nc-sa
hit
Category
keyboard_arrow_down

© 2024 LittleJake's Blog.

萌ICP备20223020号

IP攻击黑名单进阶版,基于iptables、ipset、USTC blacklist

前言

目前,服务器部署的fail2ban效果还:默认5次错误封禁24小时,查找时间24小时。

为何不加入预设黑名单服务器,提前筛选一波呢?

上手

目前发现USTC的黑名单内包含IPv6、IPv4,还包含子网CIDR范围。

查询资料发现,子网段黑名单通过ipset与iptables和ip6tables联动,能达到一个很好的效果。

通过ipset的hash缓存黑名单子网段到内存里,以组别的形式提供给iptables加速查询。

准备工具

  1. iptables(防火墙)
  2. wget(下载规则)
  3. crontab(定时更新规则)

CentOS

第一次获取

复制执行即可获取

# 获取黑名单IP
wget https://blackip.ustc.edu.cn/list.php?txt -O /tmp/blackip.txt

# 创建IPv4组ipban,并添加进iptables
ipset create ipban hash:net family inet maxelem 100000
iptables -I INPUT -m set --match-set ipban src -j DROP

# 创建IPv6组ipbanv6,并添加进ip6tables
ipset create ipbanv6 hash:net family inet6 maxelem 100000
ip6tables -I INPUT -m set --match-set ipbanv6 src -j DROP

# 筛选对应类型的IP,分别添加到对应组
for ip in `cat /tmp/blackip.txt`;
do
    if echo $ip|grep -q ":";
    then
        ipset add ipbanv6 $ip
    else
        ipset add ipban $ip
    fi
done

# 持久化iptables规则
iptables-save
ip6tables-save

定时脚本

复制执行创建定时脚本,每日0点更新

# 创建脚本
cat > /etc/blacklist.sh << EOF
#/bin/bash
wget https://blackip.ustc.edu.cn/list.php?txt -O /tmp/blackip.txt
ipset create ipban hash:net family inet maxelem 100000
iptables -D INPUT -m set --match-set ipban src -j DROP
iptables -I INPUT -m set --match-set ipban src -j DROP

ipset create ipbanv6 hash:net family inet6 maxelem 100000
ip6tables -D INPUT -m set --match-set ipbanv6 src -j DROP
ip6tables -I INPUT -m set --match-set ipbanv6 src -j DROP

ipset flush ipban
ipset flush ipbanv6

for ip in \`cat /tmp/blackip.txt\`;
do
    if echo \$ip|grep -q ":";
    then
        ipset add ipbanv6 \$ip
    else
        ipset add ipban \$ip
    fi
done
EOF

# 创建定时任务
echo "0 0 * * * root /bin/bash /etc/blacklist.sh &> /dev/null" >> /etc/crontab

后记

添加了这个之后,能够有效减少攻击的发生。同时,还可以手动建立组别,进行手动针对性封锁。

更多帮助查询:

  1. man ipset
  2. man iptables
  3. USTC IP Blacklist
Buy me a beer
Jake Liu
Never Settle

Title: IP攻击黑名单进阶版,基于iptables、ipset、USTC blacklist

Author: Jake Liu

Origin:

Creative Commons License

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) For any re-post you must give appropriate credit.

文章遵循CC许可 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 转载请注明出处

Tag:ipv6, ipv4, fail2ban, ipset, ip黑名单, blacklist

评论区

Add a new comment.

Theme