nftables 簡介

nftables 是 Linux 一組新興起的封包過濾工具,他的目的是要取代大家耳熟能詳的 iptables。那麼到底為何要取代 iptables 呢,而其又有什麼優點呢?...

nftables 是 Linux 一組新興起的封包過濾工具,他的目的是要取代大家耳熟能詳的 iptables。那麼到底為何要取代 iptables 呢,而其又有什麼優點呢?

在 Linux 上的防火牆或封包過濾一般都是透過 netfilter 這個 kernel 的功能去實作的,包含 iptables、ebtables、firewalld 等軟體都一樣,而 nftables 當然也是如此,只不過它和其他軟體的不同之處在於:nftables 是直接控制 netfilter,設定上非常貼切 kernel netfilter 的原始格式,也因此可以只用單一工具就控制所有類型的協定。不像 iptables 只能控制 IPv4、想要設定 IPv6 得用 ip6tables、想要控制 bridge 就要用 ebtables。

也因為它是直接控制 netfilter,所以它也可以顯示或控制其他防火牆程式寫在 netfilter 中的表,像是用 iptables 沒辦法檢視 firewalld 到底寫了哪些 rules 在 kernel 中,但 nftables 就可以。

更新:iptables 有兩種版本,一種是基於 xtables 的舊框架 (legacy);另一種則是基於 netfilter 的版本 (nf_tables),只有用 netfilter 的版本 nftables 才看得到 iptables 的規則喔。可以用 iptables -V 來檢視目前用的是哪個版本。

$ sudo nft list tables
table ip filter
table ip6 filter
table bridge filter
table ip security
table ip raw
table ip mangle
table ip nat
table ip6 security
table ip6 raw
table ip6 mangle
table ip6 nat
table bridge nat
table inet firewalld
table ip firewalld
table ip6 firewalld
nftables 可以顯示出 iptables 以及 firewalld 在 netfilter 中的表
$ sudo iptables -t firewalld -L -v
iptables v1.8.4 (nf_tables): table 'firewalld' does not exist
Perhaps iptables or your kernel needs to be upgraded.
iptables 卻顯示不出 firewalld 的表

nftables 表的類型

Type Protocol Chain Type
ip IPv4 filter
nat
route
ip6 IPv6 filter
nat
route
inet IPv4&IPv6 filter
nat
arp ARP filter
bridge Ethernet filter
netdev Any filter

藉由定義不同類型的表,可以過濾不同類型的封包。而且若是單純要過濾 port,更可以用 inet 一次兼顧 IPv4 & IPv6,就不需要寫兩次同樣的 rule 了。

結語

以往使用 iptables 的最大問題便是當要修改規則時,因為 docker / wireguard / kubernetes 都共用同一張表,造成他們的 Chain 都一起被洗掉,不得不跟著重啟這些服務。若未來各服務的 rule 都獨立在不同 tables 中,相信可以避免這類問題的發生。

nftables 的功能也相對的較 iptables 強大,光 nft(8) man page 就長達 3425 行,這裡就不詳述使用方式,有興趣的人可以參考以下網址的文件學習。