如何将30秒限4次连接的iptables规则转换为等效nftables规则
nftables等效SSH防暴力破解规则配置
你给出的iptables规则实现的是30秒内同一IP对SSH端口22的新连接超过4次就阻断的逻辑,同时带--rttl参数防止源IP伪造,下面是完全等效的nftables实现方案:
临时生效命令(重启nftables服务后失效)
如果是首次配置nftables,先创建基础的表和链:
- 创建inet协议族的filter表(同时支持IPv4和IPv6)
nft add table inet filter - 创建INPUT链,绑定input钩子,优先级为0
nft add chain inet filter INPUT '{ type filter hook input priority 0; policy accept; }' - 创建存储SSH连接源IP的动态集合,超时时间设为30秒,对应iptables的
--seconds 30参数nft add set inet filter ssh_brute '{ type ipv4_addr; flags dynamic,timeout; timeout 30s; }' - 添加规则,实现30秒内同一IP新连接超过4次就阻断的逻辑,对应你给出的两条iptables规则:
nft add rule inet filter INPUT tcp dport 22 ct state new update @ssh_brute { ip saddr timeout 30s } ct count over 4 counter drop
如果需要等效原规则的--rttl功能(校验源IP的TTL值和首次连接一致,防范伪造源IP的攻击),则改用以下配置:
- 创建同时存储源IP和TTL值的动态集合
nft add set inet filter ssh_brute_rttl '{ type ipv4_addr . integer; flags dynamic,timeout; timeout 30s; }' - 添加带TTL校验的规则
nft add rule inet filter INPUT tcp dport 22 ct state new update @ssh_brute_rttl { ip saddr . ip ttl timeout 30s } ct count over 4 counter drop
持久化配置(重启后依然生效)
把以下内容写入nftables配置文件(多数发行版路径为/etc/nftables.conf,部分自定义编译的版本可能路径不同):
#!/usr/sbin/nft -f table inet filter { set ssh_brute { type ipv4_addr flags dynamic,timeout timeout 30s size 65535 } chain INPUT { type filter hook input priority 0; policy accept; # 放行已建立连接和关联流量,大幅降低规则匹配开销 ct state established,related accept # SSH防爆破规则,等效原iptables逻辑 tcp dport 22 ct state new update @ssh_brute { ip saddr timeout 30s } ct count over 4 counter drop # 其他自定义INPUT规则可以写在下面 } }
写入完成后执行nft -f /etc/nftables.conf即可加载生效,也可以通过重启nftables服务加载配置。
规则对应说明
ct state new对应原iptables的-m state --state NEW,匹配首次建立的TCP连接- 动态集合
ssh_brute的timeout 30s对应原规则的--seconds 30,IP命中后30秒没有新连接会自动从集合中清除 ct count over 4对应原规则的--hitcount 4,30秒内同一IP的新连接数超过4就触发DROP动作update @ssh_brute { ip saddr timeout 30s }对应原规则的--set和--update操作,自动更新IP的命中记录和超时时间
内容的提问来源于stack exchange,提问作者Samuel Barata
相关产品推荐
相关产品推荐

