6.7. 使用 nftables 来限制连接数量
您可以使用
nftables
来限制连接数或限制到建立给定数量连接的块 IP 地址,以防止它们使用太多的系统资源。
6.7.1. 使用 nftables 限制连接数量
nft
工具的 ct count
参数可让管理员限制连接数量。这个步骤描述了如何限制进入的连接的基本示例。
先决条件
- example_table 中的基础example_chain 存在。
过程 6.19. 使用 nftables 限制连接数量
- 添加一条规则,仅允许从 IPv4 地址同时连接到
SSH
端口(22
),并从同一 IP 拒绝所有进一步连接:# nft add rule ip example_table example_chain tcp dport ssh meter example_meter { ip saddr ct count over 2 } counter reject
- 另外,还可以显示上一步中创建的 meter:
# nft list meter ip example_table example_meter table ip example_table { meter example_meter { type ipv4_addr size 65535 elements = { 192.0.2.1 : ct count over 2 , 192.0.2.2 : ct count over 2 } } }
elements
条目显示当前与该规则匹配的地址。在这个示例中,elements
列出已活跃连接到 SSH 端口的 IP 地址。请注意,输出不会显示活跃连接的数量,或者连接是否被拒绝。
6.7.2. 在一分钟内尝试超过十个进入的 TCP 连接的 IP 地址
nftables
框架可让管理员动态更新集合。本节解释了如何使用这个功能临时阻止在一分钟内建立十个 IPv4 TCP 连接的主机。五分钟后,nftables
会自动从拒绝列表中删除 IP 地址。
过程 6.20. 在一分钟内尝试超过十个进入的 TCP 连接的 IP 地址
- 使用 ip 地址系列创建 filter 表:
# nft add table ip filter
- 在 filter 表中添加输入链:
# nft add chain ip filter input { type filter hook input priority 0 \; }
- 在 filter 表中添加名为 denylist 的集合:
# nft add set ip filter denylist { type ipv4_addr \; flags dynamic, timeout \; timeout 5m \; }
这个命令为 IPv4 地址创建动态设置。timeout 5m
参数定义nftables
在 5 分钟后自动删除集合中的条目。 - 添加一条规则,该规则会在一分钟内尝试建立十个新的 TCP 连接的主机源 IP 地址添加到
denylist
集:# nft add rule ip filter input ip protocol tcp ct state new, untracked limit rate over 10/minute add @denylist { ip saddr }
- 添加一条规则,该规则丢弃来自
denylist
集合中 IP 地址的所有连接:# nft add rule ip filter input ip saddr @denylist drop
6.7.3. 其他资源
- 如需更多信息,请参阅 第 6.4.2 节 “在 nftables 中使用命名集”。