ipset

出自 ArchWiki

ipsetiptables Linux 防火墙的配套应用程序。它允许您设置规则,以便快速轻松地阻止一组 IP 地址,以及其他功能。

iptables 的继任者 nftables 具有 使用集合的内置基础设施ipset-translate 工具可用于将 “ipset”(用于 iptables)转换为 nftables 集合,详见 从 ipset 迁移到 nftables

安装

安装 ipset 软件包。

配置

阻止网络列表

首先创建一个新的“集合”,用于存放网络地址。这将创建一个名为 “myset” 的新的 “hash” 类型的 “net” 网络地址集合。

# ipset create myset hash:net

# ipset -N myset nethash

将您想要阻止的任何 IP 地址添加到集合中。

# ipset add myset 14.144.0.0/12
# ipset add myset 27.8.0.0/13
# ipset add myset 58.16.0.0/15
# ipset add myset 1.1.1.0/24

最后,配置 iptables 以阻止该集合中的任何地址。此命令将在 “INPUT” 链的顶部添加一个规则,以 “-m” 匹配来自 ipset 的名为 “myset” 的集合(--match-set),当它是 “src” 数据包时 “DROP” 或阻止它。

# iptables -I INPUT -m set --match-set myset src -j DROP

阻止 IP 地址列表

首先创建一个新的 “集合”,用于存放 IP 地址。这将创建一个名为 “myset-ip” 的新的 “hash” 类型的 “ip” 地址集合。

# ipset create myset-ip hash:ip

# ipset -N myset-ip iphash

将您想要阻止的任何 IP 地址添加到集合中。

# ipset add myset-ip 1.1.1.1
# ipset add myset-ip 2.2.2.2

最后,配置 iptables 以阻止该集合中的任何地址。

# iptables -I INPUT -m set --match-set myset-ip src -j DROP

使 ipset 持久化

您创建的 ipset 存储在内存中,重启后将会消失。要使 ipset 持久化,您必须执行以下操作

首先,将 ipset 保存到 /etc/ipset.conf

# ipset save > /etc/ipset.conf

然后 启用 ipset.service,其工作方式类似于 iptables.service,用于恢复 iptables 规则

警告: 曾观察到一个(罕见)错误 FS#79674,导致 iptables.service 因缺少 ipset 而失败,尽管 ipset.service 成功。如果您需要 100% 确保您的防火墙完好无损,请使用冗余安全措施并考虑使用监控脚本。
注意: 当前 ipset save > /etc/ipset.conf 存在一个错误,该错误以与 ipset list 相同的格式写入输出,并且当在 systemd 中启用 ipset 时,它将无法恢复您的 ipset。解决方法是使用:ipset -o save save > /etc/ipset.conf。此问题目前在 archlinux/packaging/packages/ipset#2 中公开。

使用 PeerGuardian 和其他阻止列表进行阻止

Maeyanie.com 的作者开发的 pg2ipset-gitAUR 工具,结合 ipset-update.sh 脚本,可以与 cron 一起使用以自动更新各种阻止列表。目前,默认情况下,已实施对以下内容的阻止:国家/地区、Tor 出口节点和 Bluetack pg2 列表。

其他命令

查看集合

# ipset list

# ipset -L

删除集合

# ipset destroy myset

# ipset -X myset

删除所有集合

# ipset destroy

请参阅 ipset(8) 以获取更多信息。

优化

iprangeAUR 工具可以帮助减少 ipset.conf 中的条目,方法是合并相邻范围或消除重叠范围。如果表大小很大,这可以提高路由器/防火墙性能。此工具还可以将主机名列表转换为 IP。

虽然 ipset 旨在能够很好地扩展,但这并不意味着无限扩展。特别是,一些国家/地区拥有非常大的 IP 地址空间,这将导致地理阻止效率低下。