一、基本结构

table ip filter {
    chain input {}
}

结构说明:

table → chain → rule

二、常见 Hook

Hook说明
input入站
output出站
forward转发

三、创建基础防火墙(完整可用)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
# 创建表
nft add table ip filter

# 创建链(带 hook)
nft add chain ip filter input { type filter hook input priority 0 \; policy drop \; }

# 允许本地回环
nft add rule ip filter input iif lo accept

# 允许已建立连接
nft add rule ip filter input ct state established,related accept

# 放行 SSH
nft add rule ip filter input tcp dport 22 accept

四、规则写法

1
nft add rule ip filter input tcp dport 80 accept

多端口

1
nft add rule ip filter input tcp dport {80,443} accept

五、删除规则(必须掌握)

方法 1:通过 handle 删除(推荐)

1
nft -a list chain ip filter input
查看带 handle 的规则
1
nft -a list ruleset

输出示例:

handle 5 tcp dport 22 accept

删除:

1
nft delete rule ip filter input handle 5

方法 2:清空整条链

1
nft flush chain ip filter input

方法 3:删除整张表

1
nft delete table ip filter

六、Sets(高性能推荐)

创建 set

1
nft add set ip filter allowed_ips { type ipv4_addr \; }

添加元素:

1
nft add element ip filter allowed_ips { 1.1.1.1, 2.2.2.2 }

使用:

1
nft add rule ip filter input ip saddr @allowed_ips accept

删除元素

1
nft delete element ip filter allowed_ips { 1.1.1.1 }

删除 set

1
nft delete set ip filter allowed_ips

七、NAT(端口转发)

1
2
3
4
5
nft add table ip nat

nft add chain ip nat prerouting { type nat hook prerouting priority -100 \; }

nft add rule ip nat prerouting tcp dport 80 dnat to 127.0.0.1:8080

删除 NAT 规则

同样使用 handle:

1
2
nft -a list chain ip nat prerouting
nft delete rule ip nat prerouting handle <ID>

八、限速(防爆破)

1
nft add rule ip filter input tcp dport 22 ct state new limit rate 10/minute accept

九、日志调试

1
nft add rule ip filter input log prefix "NFT: "

查看:

1
journalctl -f | grep NFT

十、常用排查命令

查看规则

1
nft list ruleset

查看带 handle

1
nft -a list ruleset

查看表

1
nft list tables

查看 set

1
nft list sets

十一、实用建议(重要)

1. 始终使用完整命令

1
nft add rule ...

2. 优先使用 set

性能更高,适合:

  • 黑名单
  • 白名单
  • CrowdSec

3. 删除规则必须用 handle

nftables 不支持像 iptables 那样按内容删除


4. 操作前建议备份

1
nft list ruleset > backup.nft

十二、一句话总结

  • nftables 核心结构:
table → chain → rule → set
  • 添加规则:
1
nft add rule ...
  • 删除规则:
1
nft delete rule ... handle <ID>
  • 高性能:
1
set + 引用