fail2ban自定义规则拦截跨境扫描恶意IP
为什么要拦截跨境扫描
很多服务器会持续受到来自海外IP的端口扫描和暴力破解。
如果你的业务只面向国内用户,直接屏蔽大陆地区以外的IP能大幅降低攻击风险。
fail2ban 是一款入侵防御工具,可以读取日志、自动封禁异常IP。
通过自定义规则,你可以灵活地将跨境扫描的IP加入黑名单。
安装与基础配置
在 CentOS / Ubuntu 上安装 fail2ban:
# CentOS 7/8
yum install epel-release -y
yum install fail2ban -y
# Ubuntu 20.04+
apt update
apt install fail2ban -y
安装后启动并设置开机自启:
systemctl start fail2ban
systemctl enable fail2ban
fail2ban 的默认配置文件在 /etc/fail2ban/jail.conf,但建议创建本地覆盖文件 /etc/fail2ban/jail.local,避免升级时被覆盖。
编写自定义规则拦截境外IP
拦截跨境扫描的核心思路:在 fail2ban 的过滤规则里加入对 IP 地理位置的判断,或直接封禁特定国家/地区的 IP 段。
这里介绍两种常用方法。
方法一:基于 IP 段的白名单/黑名单(适用于已知C段)
如果你确认某些境外IP段是恶意的,可直接添加到 ignoreip 的反向配置中。
不过更灵活的做法是使用 action 调用系统防火墙直接封禁整个国家。
方法二:结合 GeoIP 模块自动匹配
前提:安装 GeoIP 工具(geoip-bin)或使用 maxmind 数据库。
- 安装依赖:
apt install geoip-bin -y
# 或者 yum install GeoIP -y
- 下载地理IP数据库(免费版):
wget https://geolite.maxmind.com/download/geoip/database/GeoLite2-Country.tar.gz
tar -xzf GeoLite2-Country.tar.gz -C /usr/share/GeoIP/
- 编写自定义过滤规则
/etc/fail2ban/filter.d/sshd-badcountry.conf:
[Definition]
failregex = ^.*from .*$
ignoreregex =
- 创建 action 文件
/etc/fail2ban/action.d/geoip-block.conf:
[Definition]
actionban = if [ $(geoiplookup | grep -c 'China') -eq 0 ]; then iptables -A fail2ban- -s -j DROP; fi
actionunban = iptables -D fail2ban- -s -j DROP
[Init]
name = default
- 在
jail.local中启用自定义规则:
[sshd-badcountry]
enabled = true
filter = sshd-badcountry
logpath = /var/log/auth.log
action = geoip-block
bantime = 86400
maxretry = 3
findtime = 600
说明:上述 action 会在封禁前检查 IP 是否不在中国,若不在则添加 iptables 规则封禁。
你可以将 China 替换成其他允许的国家。
简化方案:直接封禁非中国大陆IP段
如果你不想用 GeoIP,可以找到中国大陆 IP 段列表(从 APNIC 获取)并加到 ignoreip 白名单,然后封禁所有其他 IP。
但这种方法维护成本高,更推荐使用 GeoIP 方式。
验证与排错
重启 fail2ban 使配置生效:
systemctl restart fail2ban
检查 jail 状态:
fail2ban-client status
fail2ban-client status sshd-badcountry
用模拟攻击测试:
# 从境外IP尝试SSH登录3次失败
ssh -o BatchMode=yes root@你的服务器
# 查看日志
cat /var/log/fail2ban.log | grep 'Ban'
如果发现合法的国内 IP 被误封,检查 GeoIP 数据库是否过时,或调整 maxretry 和 findtime。
常见问题解答
Q: 我的服务器只有 IPv6,怎么处理?
A: 确保 GeoIP 库支持 IPv6,并添加 ip6tables 规则。可以在 action 中同时调用 ip6tables。
Q: 使用 GeoIP 会导致性能下降吗?
A: 每次封禁才执行一次 geoiplookup,影响极小。但如果频繁触发,建议增加 findtime 或提高 maxretry。
Q: 如何只允许特定国家的 IP 访问?
A: 将 actionban 改为“如果 IP 不在允许国家列表中则封禁”,并将白名单国家写入脚本。
通过以上步骤,你已经掌握了 fail2ban 自定义规则拦截跨境扫描恶意IP 的核心技巧。
建议先在测试环境验证,再应用到生产服务器。
如果遇到异常,优先回看日志和 fail2ban-client status 输出。