使用 iptables 建立/設定防火牆

使用 iptables 建立/設定防火牆

我想使用 iptables 設定防火牆。

伺服器正在執行httpd服務(httpd),作業系統是Centos7,以下資訊是安裝iptables-services後,啟動iptables,不做任何修改。

[root@iptables ~]# iptables -nL --line-numbers
Chain INPUT (policy ACCEPT)
num  target     prot opt source               destination
1    ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0            state RELATED,ESTABLISHED
2    ACCEPT     icmp --  0.0.0.0/0            0.0.0.0/0
3    ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0
4    ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0            state NEW tcp dpt:22
5    REJECT     all  --  0.0.0.0/0            0.0.0.0/0            reject-with icmp-host-prohibited

Chain FORWARD (policy ACCEPT)
num  target     prot opt source               destination
1    REJECT     all  --  0.0.0.0/0            0.0.0.0/0            reject-with icmp-host-prohibited

Chain OUTPUT (policy ACCEPT)
num  target     prot opt source               destination

正如您所看到的,在 INPUT 鏈中,第 num3 行,似乎伺服器已開啟。

但透過瀏覽器存取網頁無法正常運作。

有什麼我必須設定的嗎?

作為輸出iptables-save(取自評論):

# Generated by iptables-save v1.4.21 on Thu Sep 16 13:41:53 2021
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [527:50260]
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT
-A INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -j REJECT --reject-with icmp-host-prohibited
COMMIT
# Completed on Thu Sep 16 13:41:53 2021

答案1

正如我所懷疑的,iptables -L隱藏了額外的匹配,但iptables-save顯示了赤裸裸的事實。您的規則 #3 僅符合lo環回介面。此防火牆僅接受從外部到 tcp/22 (SSH) 的連線。

最簡單的解決方案是:

iptables -I INPUT 4 -p tcp --dport 80 -j ACCEPT
iptables -I INPUT 5 -p tcp --dport 443 -j ACCEPT

您也可以使用 conntrack 進行過濾,並將兩個規則合併為一個具有多個連接埠的規則:

iptables -I INPUT 4 -m conntrack --ctstate NEW -p tcp -m multiport --dports 80,443 -j ACCEPT -m comment --comment "HTTP/HTTPS service"

另請注意我添加的評論。使用評論每個規則,有一天,如果您的防火牆增加到超過 50 條規則,您會感謝我的建議。

不要使用-m state.這已經過時了。它確實-m conntrack在幕後使用,並且像這樣明確地拼寫它更透明。

不要使用iptables -L.正如您所看到的,它的輸出看起來“更漂亮”,優點到此結束,但它也無法呈現所有需要的細節。的輸出iptables-save看起來不太漂亮,但它顯示了所有最精細的細節,因此始終使用後者。

相關內容