使用過Linux系統的人對iptables一定不陌生,它是Linux從2.4.x版本內核開始,系統自帶的防火牆。如今Linux內核已經更新至5.11.x版本,Linux的防火牆在iptables基礎上泛生出UFW和Firewalld,並且在一些發行版中已經替代iptables。
Netfilter/Iptables
Netfilter/Iptables 是Linux系統自帶的防火牆,Iptables管理規則,Netfilter是規則的執行者,它們一起組成Linux下包過濾防火牆。
iptables內置4個表,即filter表、nat表、mangle表和raw表,分別用於實現包過濾,網絡地址轉換、包重構(修改)和數據跟蹤處理。每個表都會有相應的鏈。下圖是iptables中的四表五鏈:

鏈(chains)是數據包傳播的路徑。每一條鏈中可以有一條或多條規則,當一個數據包到達一個鏈時,iptables就會從鏈中第一條規則開始檢查,看該數據包是否滿足規則所定義的條件。如果滿足,系統就會根據該條規則所定義的方法處理該數據包;否則iptables將繼續檢查下一條規則。如果該數據包不符合鏈中任一條規則,iptables就會根據該鏈預先定義的默認策略來處理數據包。

關於iptables的原理這篇文章講得很清楚:
https://blog.csdn.net/tennysonsky/article/details/44596515
在Linux中,可以使用如下命令啟用或關閉iptables
// 啟動iptables
systemctl start iptables
// 停止iptables
systemctl stop iptables
以下是常用命令:
// 列出 INPUT 表中規則
iptables -L INPUT
// 允許3306端口TCP協議訪問
iptables -I INPUT -p tcp --dport 3306 -j ACCEPT
// 允許IP為xxx.xxx.xxx.xxx通過udp訪問本地500端口
iptables -I INPUT -p udp --dport 500 -s xxx.xxx.xxx.xxx -j ACCEPT
// -I參數是將規則插入表開頭,-A是把規則添加到表未尾,優先級最低,可做為默認規則
// 當不符合前面規則後拒絕所有請求
iptables -A INPUT -p tcp -j REJECT
// 刪除INPUT表中第1條規則
iptables -D INPUT 1
// 清空規則列表
iptables -F
iptables還能做基於內核的包轉發。關於iptables用法網上文章太多了,就不多寫。
需要注意的是,iptables規則雖然能即時生效,但並未保存。開機後會丟失。
RedHat系執行保存:
service iptables save
Debian系執行 iptables-save 列出所有規則,輸出到文件中保存。系統啟動時用 iptables-restore 恢復。
// 保存
iptables-save > /etc/iptables.conf
// 恢復
iptables-restore < /etc/iptables.conf
UFW 和 Firewalld
iptables很強大也很複雜,於是便有UFW和Firewalld。它們的命令簡單清晰很多,底層都是調用iptables。
- UFW
UFW是Ubuntu下防火牆:
// 啟動ufw
systemctl start ufw
// 停用ufw
systemctl stop ufw
以下是常用命令:
// 查詢ufw開啟狀態,打印規則
ufw status
// 允許80端口訪問
ufw allow 80
// 拒絕8000端口訪問
ufw deny 9000
// 拒絕ip為xxx.xxx.xxx.xxx訪問
ufw deny from xxx.xxx.xxx.xxx
// 允許通過tcp協議,9000-9002訪問
ufw allow 9000:9002/tcp
// 刪除規則
ufw delete allow http
- Firewalld
Firewalld是Fedora/CentOS 8之後版本自帶的防火牆:
// 啟動firewalld
systemctl start firewalld
// 停用firewalld
systemctl stop firewalld
以下是常用命令:
// 允許tcp協議8161端口訪問,--zone(作用域),--permanent(永久生效)
firewall-cmd --zone=public --add-port=8161/tcp --permanent
// 重新加載規則
firewall-cmd --reload
// 將80端口的流量轉發至8080
firewall-cmd --add-forward-port=port=80:proto=tcp:toport=8080
// 將80端口的流量轉發至192.168.0.1
firewall-cmd --add-forward-port=proto=80:proto=tcp:toaddr=192.168.1.0.1
// 將80端口的流量轉發至192.168.0.1的8080端口
firewall-cmd --add-forward-port=proto=80:proto=tcp:toaddr=192.168.0.1:toport=8080
Firewalld也有圖形界面:

原創文章,作者:投稿專員,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/234328.html