本文将指导您如何通过iptablesipset结合AbuseIPDB的IP黑名单,自动更新并阻止恶意IP地址的扫描和攻击。此方法可以有效减少VPS上的恶意流量,提升服务器的安全性。


准备工作

在开始之前,请确保您的VPS已经安装了iptablesipset。如果没有安装,可以通过以下命令进行安装:

sudo apt-get update
sudo apt-get install iptables ipset

创建脚本

我们将创建两个脚本:一个用于在系统启动时初始化防火墙规则,另一个用于定期更新IP黑名单。

1. 启动时初始化脚本

/root/cron/ban_at_boot.sh中创建以下脚本:

#!/bin/bash
cd /root/cron

sleep 10 # 等待Docker等服务启动

# 创建ipset集合
ipset create banned_ips hash:ip hashsize 65536 maxelem 1000000

# 创建并应用iptables规则
iptables -N BANNED
iptables -I FORWARD -j BANNED
iptables -I INPUT -j BANNED
iptables -I BANNED -m set --match-set banned_ips src -j DROP

# 下载AbuseIPDB黑名单
wget -q https://raw.githubusercontent.com/borestad/blocklist-abuseipdb/main/abuseipdb-s100-1d.ipv4 -O abuseipdb-s100-1d.ipv4
if [ ! -f abuseipdb-s100-1d.ipv4 ]; then
    exit 1
fi

# 将IP添加到ipset集合中
awk '!/^#/ && $1 ~ /^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/ { print $1 }' abuseipdb-s100-1d.ipv4 | while IFS= read -r line; do
    ipset add banned_ips "$line"
done

2. 定期更新脚本

/root/cron/ban.sh中创建以下脚本:

#!/bin/bash
cd /root/cron

# 下载最新的AbuseIPDB黑名单
wget -q https://raw.githubusercontent.com/borestad/blocklist-abuseipdb/main/abuseipdb-s100-1d.ipv4 -O abuseipdb-s100-1d.ipv4
if [ ! -f abuseipdb-s100-1d.ipv4 ]; then
    exit 1
fi

# 清空现有的ipset集合
ipset flush banned_ips

# 将新的IP添加到ipset集合中
awk '!/^#/ && $1 ~ /^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/ { print $1 }' abuseipdb-s100-1d.ipv4 | while IFS= read -r line; do
    ipset add banned_ips "$line"
done

设置计划任务

为了让脚本自动运行,我们需要将它们添加到cron任务中。

  1. 打开cron编辑器:

    crontab -e
  2. 添加以下行:

    0 5 * * * /bin/bash /root/cron/ban.sh
    @reboot /bin/bash /root/cron/ban_at_boot.sh

    这将在每天凌晨5点更新IP黑名单,并在每次系统启动时初始化防火墙规则。

删除规则

如果您需要删除已添加的规则,可以使用以下命令:

iptables -D BANNED -m set --match-set banned_ips src -j DROP
iptables -D INPUT -j BANNED
iptables -D FORWARD -j BANNED
iptables -X BANNED
ipset destroy banned_ips

总结

通过以上步骤,您可以有效地阻止恶意IP地址对VPS的扫描和攻击。此方法不仅自动化了IP黑名单的更新,还确保了系统启动时的安全性。定期更新黑名单和监控系统日志,可以进一步提升服务器的安全性。

注意事项

  • IP黑名单的来源:本文使用了AbuseIPDB的黑名单,您可以根据需要选择其他来源的黑名单。
  • 性能影响:大量IP地址的过滤可能会对服务器性能产生一定影响,建议根据实际情况调整hashsizemaxelem参数。
  • 日志记录:建议定期检查iptables日志,确保规则按预期工作。

通过以上优化,您的VPS将更加安全,能够有效抵御恶意扫描和攻击。

本文转载自:https://www.nodeseek.com/post-288587-1

标签: VPS安全, iptables, ipset, abuseipdb, 阻止恶意扫描

添加新评论

登录身份: 饺子. 退出 »