文章

nftables

nftables 是 iptables 的继任者,提供了一种更强大、更灵活、更高效的方式来管理 Linux 系统上的数据包过滤和 NAT(抄的,反正就是比iptables更先进)。

基本结构图如下:

Table - 表:用来组织链和规则的,主要有inet、ip4、ip6、arp、bridge(其实就是表示处理的流量类型)。

Chain - 链:表示Table中的具体的规则走什么处理链路?比如是拦截还是放行,主要有input、output、forward、prerouting、postrouting(除了前三个,其他都不太懂)。

Rule - 规则:表示具体的策略内容了,要对数据包执行的过滤条件和动作。

image-20250724180743972

基本用法:

1、创建表

1
nft add table inet my_filter_ip

2、创建一个input(入站)的链

1
nft add chain inet my_filter_ip input {type filter hook input priority 0 \; policy drop \;}

type filter 指这是一个用于过滤的链,其他类型还有route、nat

hook input 指这条链挂到输入阶段,即处理本机的数据包

priority 0 指该链的优先级,数值越小优先级越高

policy drop 指该链默认的处理策略为丢弃

\; 指nftables 命令语法中的转义分号,用于表示大括号内的语句结束

综上:该命令创建了一个默认丢弃所有入站的数据包的链,效果如下:

3、创建规则

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 放行22端口
nft add rule inet my_filter_ip input tcp dport 22 accept

# 放行多个端口
nft add rule inet my_filter_table input tcp dport { 22, 80, 443 } accept

# 丢弃某个IP的数据包
nft add rule inet my_filter_ip input ip saddr 192.168.31.100 drop

# 允许某个IP访问
nft add rule inet my_filter_ip input ip saddr 192.168.1.1 accept

# 放行到特定目标的流量
nft add rule inet my_filter_ip input ip daddr 10.9.1.13 accept

# 放行特定IP访问特定端口
nft add rule inet my_filter_ip input ip saddr 192.168.1.100 tcp dport 22 accept

# 日志记录
nft add rule inet my_filter_ip input tcp dport 22 log prefix "SSH_ACCESS: " accept

# 限制速率
nft add rule inet my_filter_ip input tcp dport 22 limit rate 10/minute accept

除了accept和drop,还有reject操作。

还可以转发流量。

还可以限制协议类型。

更多有趣的期待被发现……

本文由作者按照 CC BY 4.0 进行授权