nftables 使用:屏蔽与放行端口

nftables 是 Linux 上用于替代 iptables 的防火墙框架。本文记录 Debian / Ubuntu 环境中常用的 nftables 操作,包括安装、屏蔽指定端口、默认拒绝入站并放行指定端口、验证规则和回滚。

如果通过 SSH 连接服务器,修改防火墙前务必放行 SSH 端口,例如 22。否则规则应用后可能会把自己锁在服务器外面。

安装 nftables

1
2
3
sudo apt update
sudo apt install -y nftables
sudo systemctl enable --now nftables

查看服务状态:

1
systemctl status nftables

备份当前配置

修改前先备份原配置:

1
sudo cp /etc/nftables.conf /etc/nftables.conf.bak.$(date +%F-%H%M%S)

如果当前系统已经存在规则,也可以导出当前规则集:

1
sudo nft list ruleset | sudo tee /etc/nftables.ruleset.bak

示例一:屏蔽指定 IPv4 端口

下面示例屏蔽 IPv4 入站 TCP / UDP 8000 端口,其他流量不受影响。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
sudo tee /etc/nftables.conf > /dev/null << 'EOF'
#!/usr/sbin/nft -f

flush ruleset

table inet filter {
    chain input {
        type filter hook input priority filter; policy accept;

        ip protocol tcp tcp dport 8000 drop
        ip protocol udp udp dport 8000 drop
    }
}
EOF

应用配置:

1
2
sudo nft -f /etc/nftables.conf
sudo systemctl restart nftables

验证规则:

1
sudo nft list ruleset

示例二:默认拒绝入站,只放行指定端口

下面示例采用更严格的策略:默认拒绝入站,仅放行本机回环、已建立连接、ICMP、SSH、HTTPS 和 8000 端口。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
sudo tee /etc/nftables.conf > /dev/null << 'EOF'
#!/usr/sbin/nft -f

flush ruleset

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

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

        ip protocol icmp accept
        ip6 nexthdr ipv6-icmp accept

        tcp dport { 22, 443, 8000 } accept
        udp dport { 8000 } accept
    }

    chain forward {
        type filter hook forward priority filter; policy drop;
    }

    chain output {
        type filter hook output priority filter; policy accept;
    }
}
EOF

应用配置:

1
2
sudo nft -f /etc/nftables.conf
sudo systemctl restart nftables

验证规则和服务状态:

1
2
sudo nft list ruleset
systemctl status nftables

临时添加或删除规则

临时添加屏蔽规则,重启 nftables 后会失效:

1
2
sudo nft add rule inet filter input tcp dport 8000 drop
sudo nft add rule inet filter input udp dport 8000 drop

查看带 handle 的规则:

1
sudo nft -a list chain inet filter input

删除指定规则时,把 handle 替换为实际编号:

1
sudo nft delete rule inet filter input handle 10

回滚配置

如果只是临时清空当前规则:

1
sudo nft flush ruleset

如果需要恢复备份配置:

1
2
3
sudo cp /etc/nftables.conf.bak.YYYY-MM-DD-HHMMSS /etc/nftables.conf
sudo nft -f /etc/nftables.conf
sudo systemctl restart nftables

常用检查命令

1
2
3
4
sudo nft list ruleset
sudo nft -a list ruleset
systemctl status nftables
sudo journalctl -u nftables --no-pager -n 50

注意事项

  • policy drop 会默认拒绝入站流量,配置前必须确认 SSH 端口已放行。
  • table inet 同时适用于 IPv4 和 IPv6;使用 ip 条件时只匹配 IPv4,使用 ip6 条件时只匹配 IPv6。
  • 修改 /etc/nftables.conf 后,需要执行 sudo nft -f /etc/nftables.conf 或重启 nftables 服务才能生效。
  • 如果服务器由云厂商安全组控制,还需要同时检查云安全组规则。