ガイド

正确的nftables防火墙,包括IPv6

中級15分で読めます更新日 2026年4月22日
短い回答

nftables用统一的规则集取代iptables,通过inet family同时覆盖IPv4和IPv6。正确的默认策略默认丢弃入站流量,接受已建立的连接,允许回环和ICMP,并且只开放你提供服务的端口。

01 为什么inet family很重要

The most common firewall mistake on a modern VPS is a v4-only ruleset. Every OnionVPS instance has a routed IPv6 /64, so services remain fully reachable over v6 unless the ruleset covers both. The inet family covers both in one place.

02 完整的基线规则集

Write it to /etc/nftables.conf and enable the service. Keep a second session open while testing.

#!/usr/sbin/nft -f
flush ruleset

table inet filter {
  chain input {
    type filter hook input priority 0; policy drop;

    ct state established,related accept
    ct state invalid drop
    iif lo accept

    ip protocol icmp accept
    ip6 nexthdr icmpv6 accept

    tcp dport { 22, 80, 443 } accept
    udp dport 51820 accept          # WireGuard

    limit rate 5/minute burst 10 packets log prefix "nft-drop: "
  }
  chain forward { type filter hook forward priority 0; policy drop; }
  chain output  { type filter hook output  priority 0; policy accept; }
}

03 安全地应用它

Schedule a flush before applying, so a mistake resolves itself rather than requiring the console.

echo 'nft flush ruleset' | at now + 10 minutes
nft -f /etc/nftables.conf
# verify you are still connected, then:
atrm $(atq | cut -f1)
systemctl enable nftables

04 永远不要阻止ICMPv6

IPv6 depends on ICMPv6 for neighbour discovery and path MTU discovery. Blocking it wholesale, which people do out of IPv4 habit, produces intermittent failures that are extremely hard to diagnose.

よくある質問

我应该使用nftables还是ufw?

ufw is a friendlier front end and handles both address families correctly by default. Use nftables directly when you need rules ufw cannot express, such as rate limiting or NAT.

我如何查看哪些数据包被丢弃?

上面的日志规则以"nft-drop"前缀写入内核日志;使用journalctl -k -g nft-drop读取它。