搬瓦工 nftables 防火墙配置要点

话题来源: 搬瓦工防火墙 nftables | 服务器安全

搬瓦工的VPS常被用于搭建个人站点或小型业务,防火墙的细粒度控制直接决定了服务的安全底线。nftables 作为 Linux 官方推荐的下一代过滤框架,既能兼容 IPv4/IPv6,又提供了更简洁的语法和更低的内核开销。要想在搬瓦工上实现“只放行我想要的流量”,得先把表、链、规则的层次划分理清。

表与链的结构化思考

在 nftables 里,table相当于容器,chain是流向入口,而每条 rule 才是具体的过滤动作。搬瓦工的默认网络接口是 eth0,建议使用 inet 类型的表,以一次声明同时覆盖 IPv4 与 IPv6。

  • 创建表:nft add table inet bwg_fw,名字可随意,但在备份时最好保持一致。
  • 输入链:nft 'add chain inet bwg_fw input { type filter hook input priority 0; policy drop; }',默认策略设为 drop,防止遗漏的端口被意外放行。
  • 输出链:nft add chain inet bwg_fw output { type filter hook output priority 0; policy accept; },大多数场景保持 accept 即可。

常用规则速写

# 允许本机回环
nft 'add rule inet bwg_fw input iifname "lo" accept comment "Loopback"'

# 允许已建立/关联的会话
nft 'add rule inet bwg_fw input ct state established,related accept comment "Established"'

# 只放行 SSH(假设改为 2222 端口)
nft 'add rule inet bwg_fw input tcp dport 2222 ct state new accept comment "SSH"'

# 允许 IPv4 Ping
nft 'add rule inet bwg_fw input ip protocol icmp icmp type echo-request accept comment "ICMPv4"'

# 允许 IPv6 Ping
nft 'add rule inet bwg_fw input ip6 nexthdr icmpv6 icmpv6 type echo-request accept comment "ICMPv6"'

持久化与自动化

搬瓦工的系统在每次重启时会重新加载 /etc/nftables.conf,因此把当前规则写入该文件是必须的步骤。sudo sh -c "nft list ruleset > /etc/nftables.conf" 完成后记得启用自启:systemctl enable nftables && systemctl start nftables。如果你经常通过 API 更新白名单,建议把白名单写入单独的 set,如 nft add set inet bwg_fw whitelist { type ipv4_addr; flags interval; },随后只需 nft add rule inet bwg_fw input ip saddr @whitelist accept 即可实现动态放行。

故障排查小技巧

  • 查看完整规则集:nft list ruleset,注意每条规则后面的 # handle,删除时必须使用该句柄。
  • 临时放宽策略:nft add rule inet bwg_fw input priority -10 accept comment "Rescue",确保在误删核心规则后还能登录。
  • 日志审计:在链中加入 log prefix "nft-drop: "drop,可以快速定位被拦截的流量。

12 条评论

发表回复