nftables語法及例子
提示:關于nftables我寫了另一篇更好的, 點擊前往 => nftables精講(有NAT、限速、限流量、禁ping等例子)
先上我自己實際測試通過的例子,用例子便于在實踐中學習:
# 0 --- 說明 ---
下面例子中的單引號目的是為了避免nftable參數中的星號、花括號、分號等符號被shell展開解釋掉了,導致nft命令出錯。
# 1 ---- 規則集合操作 ---
nft list ruleset # 列出已有規則集
nft flush ruleset # 清除已有規則集, 這個命令會清理掉所的表、規則鏈、表。
# 2 ---- NAT和端口映射的例子,主機A有兩個網口eth0和wlan0,ssh服務是監聽在所有網絡接口的2222端口上的, wlan0可以上互聯網,http服務只監聽在eth0(ip addr=192.168.100.1)的80端口上。要實現的三個目的:
1多臺設備通過eth0上互聯網(masqurade), 2外部設備通過wlan0訪問eth0上監聽的http服務(dnat)。3外部通過22端口訪問主機A的ssh服務(端口轉發)---
nft add table ip table_unsafeNet; # 添加作用于ipv4簇的表
nft add chain ip table_unsafeNet chain_forward { type filter hook forward priority filter \; }; # 添加作用于ipv4簇轉發鏈,該鏈類型是三種基本鏈中的filter類型,使用forward鉤子,優先級是filter級,默認動作是accept(不寫,表示采用默認動作accept,如果是drop或其他動作,則必須寫明)
nft add rule ip table_unsafeNet chain_forward iifname "eth0" ip saddr 192.168.100.0/24 accept; # 添加作用于ipv4的規則:對源網絡接口是eth0, 源ip地址是100.0/24的ip數據允許
nft add rule ip table_unsafeNet chain_forward ct state related,established accept;
nft add chain ip table_unsafeNet chain_snat { type nat hook postrouting priority srcnat \; }; # 添加名為chain_snat的鏈,鏈類型是nat,鉤子是postrouting,優先級是srcnat級,默認動作允許
nft add rule ip table_unsafeNet chain_snat oifname "wlan0" masquerade; # 從wlan0出去的數據包做snat # 對從wlan0出去的數據做偽裝源ip地址操作。
nft add chain ip table_unsafeNet chain_dnat { type nat hook prerouting priority dstnat \; }; # 添加名為chain_dnat的鏈,鏈類型是nat,鉤子使用prerouting,優先級是dstnat級。默認動作是允許。
nft add rule ip table_unsafeNet chain_dnat iifname "wlan0" tcp dport 80 dnat to 192.168.100.12; # 對源網絡接口是wlan0,目標端口號是tcp 80的數據包DNAT到192.168.100.12(也可以寫成192.168.100.12:80,這里端口號不變,所以可以省略。dnat to可以也寫成dnat)。
連接主機eth0的需要上互聯網的設備需要添加默認路由ip route add default via 192.168.100.1 dev enp2s0 # 假設這臺想通過主機A的eth0上網的設備的有線網口是enp2s0,該網絡接口的ip地址要和eth0同一個網段。
# 3 ---- 禁止別人ping無線網卡ipv4地址的例子,input鉤子 ---
nft add table ip tb0 #創建表(用來容納多條鏈)。新建一個family為ip(也就是作用于ipv4地址族)的表, 表名為tb0。
nft list tables #列出所有表,這里可以看見剛剛建立的表tb0,注意tables是復數。
nft add chain ip tb0 ch0_input '{type filter hook input priority 0; policy accept; }' #創建鏈(用來容納多條規則)。在tb0表下創建鏈名為ch0_input的鏈,這條鏈的類型是filter(三種基本鏈中的一種),鏈的鉤子是input,優先級是0,策略為accept;這里"policy accept;"可以省略(因為他是默認的)
nft add rule ip tb0 ch0_input meta iifname 'wlp3s0' icmp type echo-request drop #創建規則(規則包含matches和statements)。在tb0表ch0_input鏈上創建規則。規則的matches是:在wifi網絡接口wlp3s0上的icmp請求。statements是:drop 。這里網絡接口可以寫成'wlp*'或'enp*',表示所有的wifi網絡接口或以太網卡借口。這里statements也可以寫成"reject with icmp type net-prohibited"。注意我用matches和statements都是復數,說明matches和statements是支持多個的,本例中的matches就有兩個,一個是匹配網卡,一個是匹配協議。關于mathes和statement的用法具體參考后文解釋
nft -an list table ip tb0 #列出表tb0詳情,注意table是單數。這里地址族為ip,表名tb0, -a表示顯示handle號(一種便于操作表、鏈、規則的序號,比如這里可以通過nft delete table handle 4來刪除這個表,假設handle號是4), -n數字形式
nft delete table ip tb0 #刪除表, 也可以通過表的handle號刪除
# 4 ---- 禁止訪問某個外部ipv4/ipv6的某端口號的例子,output鉤子 -----
nft add table inet tb1 #創建表。針對inet地址族(inet表示ip地址族和ip6地址族。也就是針對ipv4和ipv6地址的)
nft add chain inet tb1 ch1_output '{type filter hook output priority 0; policy accept; }' #添加鏈。 鏈類型為基本鏈中的filter鏈,鉤子為output,默認策略為accept。
nft add rule inet tb1 ch1_output ip daddr 192.168.43.148 tcp dport 22 reject with tcp reset #添加規則。 matches為兩個:1-目標ipv4地址 2-tcp 目標端口22。 statements是:使用tcp重置
nft add rule inet tb1 ch1_output ip6 daddr fe80::fe9c:cc8e:f0b6:ac7e tcp dport '{22,80}' drop #添加規則。 matches有兩個:目標ipv6地址和目標端口。statements:是drop。效果是執行ssh root@fe80::fe9c:cc8e:f0b6:ac7e%wlp3s0 無法連上ssh
nft flush ruleset #清理規則集。清理后的效果,ssh root@fe80::fe9c:cc8e:f0b6:ac7e%wlp3s0 和 ssh root@192.168.43.148也提示輸入密碼了。
#5--- 限制下載速度
nft add rule inet tb0 ch0 meta l4proto tcp limit rate over 50 kbytes/second drop; #限制inet(也就是ipv4 ipv6)下載速度50kByte/s
nftables 也有表、規則鏈、規則的概念:
表是規則鏈的容器
表有幾個family: ip/ip6/inet/arp/bridge/netdev; inet=ip和ip6的混合
鏈是規則的容器
基本鏈的類型有:
filter: 支持ip/ip6/inet/arp/bridge;不支持netdev(好像能支持?)
route: 標記數據包,支持ip和ip6,只能用于output鉤子。該功能類似iptables的mangle
nat: NAT功能,支持ip和ip6.
基本鏈的鉤子(hook)有:
ip/ip6/inet的鉤子有: prerouting,input, forward, output, postrouting.
arp的鉤子有: input, output.
netdev的鉤子有:ingress
鏈的優先級有: 數據包會遍歷鉤子上的鏈,直到走完所有鏈或被丟棄。以下是iptables的優先級參考
here's the list of different priority used in iptables:
NF_IP_PRI_CONNTRACK_DEFRAG (-400): priority of defragmentation
NF_IP_PRI_RAW (-300): traditional priority of the raw table placed before connection tracking operation
NF_IP_PRI_SELINUX_FIRST (-225): SELinux operations
NF_IP_PRI_CONNTRACK (-200): Connection tracking operations
NF_IP_PRI_MANGLE (-150): mangle operation
NF_IP_PRI_NAT_DST (-100): destination NAT
NF_IP_PRI_FILTER (0): filtering operation, the filter table
NF_IP_PRI_SECURITY (50): Place of security table where secmark can be set for example
NF_IP_PRI_NAT_SRC (100): source NAT
NF_IP_PRI_SELINUX_LAST (225): SELinux at packet exit
NF_IP_PRI_CONNTRACK_HELPER (300): connection tracking at exit
鏈的默認策略有:accept, drop, queue, continue, return.
規則:
handle 標識某個規則的數字,句柄號。插入規則的時候,position后就需要這個句柄號來定義位置。
matches 用于創建過濾器的匹配: matches很繁雜,具體參考https://wiki.nftables.org/wiki-nftables/index.php/Quick_reference-nftables_in_10_minutes
statement 數據包匹配后執行的語句。有log/reject/counter/limit/nat/queue/verdict statement。其中verdict statement可選值為:
accept: Accept the packet and stop the remain rules evaluation.
drop: Drop the packet and stop the remain rules evaluation.
queue: Queue the packet to userspace and stop the remain rules evaluation.
continue: Continue the ruleset evaluation with the next rule.
return: Return from the current chain and continue at the next rule of the last chain. In a base chain it is equivalent to accept
jump <chain>: Continue at the first rule of <chain>. It will continue at the next rule after a return statement is issued
goto <chain>: Similar to jump, but after the new chain the evaluation will continue at the last chain instead of the one containing the goto statement
鉤子之間的關系:
Local
process
^ | .-----------.
.-----------. | | | Routing |
| |-----> input / \---> | Decision |----> output \
--> prerouting --->| Routing | .-----------. \
| Decision | --> postrouting
| | /
| |---------------> forward ---------------------------
.-----------.
4.2內核后多了ingress鉤子,ingress鉤子與其他鉤子的關系如下:
.-----------.
| |-----> input ...
---> ingress ---> prerouting --->| Routing |
| Decision |
| |
| |-----> forward ...
.-----------.
命令行語法:
表操作:
# nft list tables [<family>] # 顯示所有表, 如果family不指定,則默認ip.
# nft [-n] [-a] list table [<family>] <name> # 顯示name指定的表, -n 表示數字形式顯示 -a表示顯示handle
# nft (add | delete | flush) table [<family>] <name> # 注意,另一種創建表的方式是:表、鏈、規則一并創建,例如下面的nft add chain 操作
鏈操作:
# nft (add|create) chain [<family>] <table> <name> [ { type <type> hook <hook> [device <device>] priority <priority> \; [policy <policy> \;] } ] *注釋1*
# nft (delete | list | flush) chain [<family>] <table> <chain_name> # 例如 nft list chain ip6 tbl0 chn0
# nft rename chain [<family>] <table> <name> <newname>
規則操作:
# nft add rule [<family>] <table> <chain> <matches> <statements>
# nft insert rule [<family>] <table> <chain> [position <position>] <matches> <statements>
# nft replace rule [<family>] <table> <chain> [handle <handle>] <matches> <statements>
# nft delete rule [<family>] <table> <chain> [handle <handle>]
其他:導出配置: # nft export (xml | json)
事件監控: # nft monitor [new | destroy] [tables | chains | sets | rules | elements] [xml | json]
注釋1: 鏈配置中的policy用來指定該鏈的默認策略。如果鏈配置不指定,則創建了一條看不到任何包的非基本鏈(類似iptables的自定義鏈) 。如果是netdev類型的鏈,必須要指定接口設備
命令行示例:
# ------- 表操作 ----------
# nft add table ip tbl_test1
# nft flush table ip tbl_test1 # 清掉tbl_test1表的所有規則
# ------- 鏈操作 ---------
# nft add chain ip tbl_test1 chn_test1 {type filter hook input priority 0\; policy accept\;} # 花括號內的是鏈配置,bash中分號需要轉義,如果不想轉義,可以寫成'{鏈配置}'的形式。 priority用來定義鏈的優先級。這條命令把表、鏈、規則一并創建了
# nft add chain netdev tbl_test2 chn_eth0filter '{type filter hook ingress device eth0 priority 0; }' # netdev類型的表必須指定接口
# nft add chain ip tbl_test1 nonBaseChain2 # 創建一條非基本鏈,因為非基本鏈沒有掛任何鉤子,所以它不能看到任何數據包。它用于排列規則集合(jump到該鏈)
# nft delete chain ip tbl_test1 chn_test1 # 刪除鏈,刪除前需要flush以下該鏈(nft flush chain tbl_test1 chn_test1),才能刪除
# ------- 規則操作 ---------
# nft add rule tbl_test chn_test1 ip daddr 8.8.8.8 counter # 目標地址為8.8.8.8的做計數, 使用nft list table tbl_name -nn 來查看表下的規則
# nft add rule tbl_test1 chn_test1 tcp dport != 22 accept # 運算符可以有 ==, !=, <=, >=, >, < 如果在bash中,需要\轉義,或者使用eq ne le ge gt lt來代替
# nft add rule tbl_test1 chn_test1 position 2 ip daddr 127.0.0.9 drop # position指定相對位置,后跟handle號。add是在后面添加,insert是在前面插入。(每條規則都有handle號,nft list tbl_name -n -a就可以查看句柄號)。
# nft replace rule tbl_test1 chn_test handle 3 ip daddr 127.0.0.10 drop # 替換handle指定的規則規則
# nft delete rule tbl_test1 chn_test handle 3 #刪除某規則
# nft add rule tbl_test1 chn_test ip6 nexthdr tcp # ip6下的tcp
# --------導入導出、腳本操作--------
# cat << EOF > /etc/nftables.rules > #!/usr/sbin/nft > flush ruleset > add table filter > add chain filter input > add rule filter input meta iifname lo accept > EOF # chmod u+x /etc/nftables.rules # /etc/nftables.rules # 使用nft腳本執行。注意上面的解釋器: #!/usr/local/sbin/nft,有些環境的nft路徑可能不同.
# nft list ruleset > /etc/nftables.rules # 導出規則集合 # nft flush ruleset # 沖掉規則集 # nft -f /etc/nftables.rules # 導入規則集合(記得先flush規則集,然后再導入)
# ------ 規則集合 -----
# nft list ruleset # 列出規則集
# nft list ruleset ip6 # 列出ip6規則集
# nft flush ruleset ip6 # 沖掉ip6規則集
# nft export json >ruleset.json #導出規則集為json
腳本:
可以include,例如:
#!/usr/sbin/nft
include "ipv4-nat.ruleset"
include "ipv6-nat.ruleset"
定義變量:
define google_dns = 8.8.8.8 #引用示例: add rule tb2 chn2 ip saddr $google_dns counter
define ntp_server_set = { 84.77.40.132, 176.31.53.99, 81.19.96.148, 138.100.62.8 } #引用示例:add rule tb2 chn2 ip saddr $ntp_server_set counter
格式:
#格式1: #!/usr/sbin/nft define ntp_servers = { 84.77.40.132, 176.31.53.99, 81.19.96.148, 138.100.62.8 } #flush table nat table ip nat { chain prerouting { type filter hook prerouting priority 0; policy accept; ip saddr $ntp_servers counter } chain postrouting { type filter hook postrouting priority 100; policy accept; } } #格式2: #!/usr/sbin/nft -f define ntp_servers = { 84.77.40.132, 176.31.53.99, 81.19.96.148, 138.100.62.8 } add table filter add chain filter input { type filter hook input priority 0; } add rule filter input ip saddr $ntp_servers counter
腳本例子:
flush ruleset table t_firewall { chain c_incoming { type filter hook input priority 0; policy drop; # established/related connections ct state established,related accept # loopback interface iifname lo accept # icmp icmp type echo-request accept # open tcp ports: sshd (22), httpd (80) tcp dport {ssh, http} accept } } table ip6 t_firewall6 { chain c_incoming { type filter hook input priority 0; policy drop; # established/related connections ct state established,related accept # invalid connections ct state invalid drop # loopback interface iifname lo accept # icmp # routers may also want: mld-listener-query, nd-router-solicit icmpv6 type {echo-request,nd-neighbor-solicit} accept # open tcp ports: sshd (22), httpd (80) tcp dport {ssh, http} accept } }
上面保存位文件,使用命令:ntf -f ruleSet.rs 來生效
matches: (摘錄自:https://wiki.nftables.org/wiki-nftables/index.php/Quick_reference-nftables_in_10_minutes,更詳細內容看這個鏈接吧)
格式:
obj value
obj operator value # 例如!=,<=
obj value1-value2
obj != value1-value2
obj {value1,value2,value3}
ipv4協議:
ip protocol tcp # 匹配高層協議: icmp, esp, ah, comp, udp, udplite, tcp, dccp, sctp
ip protocol != tcp
ip protocol 6
ipv4數據包長度:
ip length != 333-453
ip length { 333, 553, 673, 838}
ipv4 ttl:
ip ttl 33-55
ip ttl != 45-50
ipv4地址:
ip saddr 192.168.2.0/24
ip saddr != 192.168.2.0/24
ip saddr 192.168.3.1 ip daddr 192.168.3.100
ip saddr != 1.1.1.1
ip saddr 1.1.1.1
ip saddr & 0xff == 1
ip saddr & 0.0.0.255 < 0.0.0.127
ip daddr 192.168.0.1-192.168.0.250
ip daddr { 192.168.0.1-192.168.0.250 }
ip daddr { 192.168.5.1, 192.168.5.2, 192.168.5.3 }
ip版本號:
ip version 4
ct連接狀態:
ct state { new, established, related, untracked }
ct state != related
ct state established
ct state 8
ct方向:
ct direction original
ct direction != original
ct direction {reply, original}
ct mark:
ct mark 0
ct mark or 0x23 == 0x11
Meta信息:
meta iifname "eth0"
meta iifname {"eth0", "lo"}
meta iifname "eth*"
meta oifname "eth0"
meta iif eth0
meta oif {eth0, lo}
meta iiftype {ether, ppp, ipip, ipip6, loopback, sit, ipgre}
其他:
ip hdrlength 15
tcp flags != syn
tcp flags & (syn | ack) == syn | ack
icmp type echo-request
ether saddr 00:0f:54:0c:11:04
ether type vlan
vlan id 4094
Statement:
限速:
limit rate 400/minute
limit rate 400/hour
limit rate over 1023/second burst 10 packets
limit rate 1025 kbytes/second
limit rate 1023000 mbytes/second
limit rate 1025 bytes/second burst 512 bytes
limit rate 1025 kbytes/second burst 1023 kbytes
limit rate 1025 mbytes/second burst 1025 kbytes
limit rate 1025000 mbytes/second burst 1023 mbytes
dnat:
dnat to 192.168.3.2
dnat ct mark map { 0x00000014 : 1.2.3.4}
snat:
snat to 192.168.3.2
snat 2001:838:35f:1::-2001:838:35f:2:::100
masquerade:
masquerade
masquerade persistent,fully-random,random
masquerade to :1024
masquerade to :1024-2048
其他:
reject with icmp type net-prohibited #with <protocol> type <type>
ip protocol tcp reject with tcp reset
log
log level emerg
浙公網安備 33010602011771號