1.火牆介紹
- netfilter:真正的防火牆,位於內核空間。
- iptables:它其實不是真正的防火牆,可以將其理解成一個客戶端代理,用戶通過iptables這個代理,將用戶的安全設定執行到對應的“安全框架”中,這個安全框架纔是真正的防火牆,這個框架的名字就是netfilter。
- iptables|firewalld(兩個工具)
2.火牆管理工具切換
- 在rhel8中默認使用的是
firewalld
- firewalld----->iptables
dnf install iptables-services -y
安裝iptables服務systemctl stop firewalld
停止firewalldsystemctl disable firewalld
開機也不啓動firewalldsystemctl mask firewalld
凍結firewalldsystemctl enable --now iptables
打開iptables
- iptales -------> fiewalld
systemctl stop iptables
停止iptablessystemctl disable iptables
開機也不啓動iptablessystemctl mask iptables
凍結iptablessystemctl enable --now firewalld
打開firewalld
3.iptables 的使用
-
/etc/sysconfig/iptables
iptables 策略記錄文件
-
永久保存策略
-
iptales-save > /etc/sysconfig/iptables
-
service iptables save
-
-這兩種方法都是更改
/etc/sysconfig/iptables
這個文件 -
如果不改文件,你對火牆進行操作之後,restart,它又會恢復原樣
4.火牆默認策略
- 默認策略中的5條鏈
input | 輸入 |
---|---|
output | 輸出 |
forward | 轉發 |
postrouting | 路由之後 |
prerouting | 路由之後 |
- 默認的3張表
filter | 經過本機內核的數據(input output forward) |
---|---|
nat | 不經過內核的數據(postrouting,prerouting,input,output) |
mangle | 當filter和nat表不夠用時使用(input, output ,forward, postrouting,prerouting,) |
5.iptables命令
- iptables
參數 | 作用 |
---|---|
-t | 指定表名稱 |
-n | 不做解析 |
-L | 查看 |
-A | 添加策略 |
-p | 協議 |
–dport | 目的地端口 |
-s | 來源 |
-j | 動作 |
-j ACCEPT | 允許 |
-j DROP | 丟棄 |
-j REJECT | 拒絕 |
-j SNAT | 源地址轉換 |
-j DNAT | 目的地地址轉換 |
-N | 新建鏈 |
-E | 更改鏈名稱 |
-X | 刪除鏈 |
-D | 刪除規則 |
-I | 插入規則 |
-R | 更改規則 |
-P | 更改默認規則 |
- iptables是按規則一條一條執行的,遇到匹配的規則時,就不再繼續執行下一條了,所以要想讓其執行第二條規則,應該將其插入到第一條中
- 例子:
- 數據包狀態:
- RELATED 建立過連接的
- ESTABLISHED 正在連接的
- NEW 新的
iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
##允許已經認證過的
iptables -A INPUT -m state --state NEW -i lo -j ACCEPT
##允許迴環
iptables -A INPUT -m state --state NEW -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -m state --state NEW -p tcp --dport 443 -j ACCEPT
iptables -A INPUT -m state --state NEW -p tcp --dport 53 -j ACCEPT
##允許 80 443 53 端口訪問
iptables -A INPUT -m state --state NEW ! -s 192.168.1.15 -p tcp --dport 22 -j ACCEPT
##允許除了192.168.1.15之外的主機通過22端口訪問
iptables -A INPUT -m state --state NEW -j REJECT
service iptables save
- 如下圖設置也可以雖然也可以通過之前的方法設置,但是會大大降低火牆的效率
- 實驗準備:VMware下一臺雙網卡主機,兩臺單網卡主機
- 在本機設置雙網卡,ip分別爲192.168.1.33和172.25.254.33
- 一臺單網卡主機ip爲172.25.254.20,網關設置爲172.25.254.33
- 一臺單網卡主機ip是192.168.1.15(作爲測試主機)
- 保證雙網卡主機的內核路由功能是開啓的(雙網卡主機充當路由)
- nat表中的dnat snat
- SNAT
iptables -t nat -A POSTROUTING -o ens160 -j SNAT --to-source 192.168.1.33
##所有從ens160出去的所有數據都僞裝成192.168.1.33這個ip
- 這樣做,可以使172.25.254.20訪問到192.168.1.15
- DNAT
iptables -t nat -A PREROUTING -i ens160 -j DNAT --to-dest 172.25.254.30
##所有從ens160進來的數據都僞裝成172.25.254.33這個ip
- 這樣做,可以使192.168.1.15訪問到172.25.254.20