如何在 Ubuntu 16.04 配置 iptables 防火牆

Share

  • Add this entry to Hatena Bookmark

這幾天使用 EasyEngine 配置一台 VPS 主機,安裝好之後,發現 EasyEngine 雖然有安裝 iptables 防火牆程式,但沒有配置文件,為了服務器的安全,建議大家啟用防火牆設置,所以就需要手動來配置 iptables.rules 文件。

使用指令查看系統是否安裝防火牆:

whereis iptables

回覆狀態:

iptables: /sbin/iptables /etc/iptables.rules /usr/share/iptables /usr/share/man/man8/iptables.8.gz #表示已經安裝 iptables

如果 Ubuntu 默認沒有安裝,請運行此指令安裝 iptables 防火牆

apt-get install iptables

配置 iptables

查看防火牆配置信息,顯示如下:

#iptables -L -n

Chain INPUT (policy ACCEPT)
target prot opt source destination
Chain FORWARD (policy ACCEPT)
target prot opt source destination
Chain OUTPUT (policy ACCEPT)
target prot opt source destination

開始配置 iptables.rules 文件,因為 VPS 主機是安裝 EasyEngine 程序,所以下面的 port 要打開:

22 / TCP (Inbound / Outbound) : Standard SSH port
80 / TCP (Inbound / Outbound) : Standard HTTP port
443 / TCP(Inbound / Outbound) : Standard HTTPS port
22222 / TCP (Inbound) : To access EasyEngine admin tools
11371 / TCP (Outbound) : To connect to GPG Key Server

可將下面的配置 copy 貼上:

# sample configuration for iptables service
# you can edit this manually or use system-config-firewall
# please do not ask us to add additional ports/services to this default configuration
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-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 -p tcp -m state --state NEW -m tcp --dport 80 -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 443 -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 465 -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 587 -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 22222 -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 11371 -j ACCEPT
-A INPUT -p icmp -m limit --limit 1/s --limit-burst 10 -j ACCEPT
-A INPUT -p icmp -m limit --limit 100/sec --limit-burst 100 -j ACCEPT
-A INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -j REJECT --reject-with icmp-host-prohibited
COMMIT

我增加了兩條規則,作用是每秒鐘只允許 100 個碎片,用來防止 DDoS 攻擊

-A INPUT -p icmp -m limit --limit 1/sec --limit-burst 10 -j ACCEPT
-A INPUT -f -m limit --limit 100/sec --limit-burst 100 -j ACCEPT

使防火牆規則生效:

iptables-restore < /etc/iptables.rules

CentOS 上可以執行:service iptables save 保存規則,但是需要注意的是 Debian / Ubuntu 上 iptables 是不會保存規則的。需要按如下步驟進行,讓網卡關閉保存 iptables 規則,啟動時加載 iptables 規則。

創建 /etc/network/if-post-down.d/iptables 文件,添加如下內容:

#!/bin/bash
iptables-save > /etc/iptables.rules

添加執行權限:

chmod +x /etc/network/if-post-down.d/iptables

創建 /etc/network/if-pre-up.d/iptables 文件,添加如下內容:

#!/bin/bash
iptables-restore < /etc/iptables.rules

添加執行權限:

chmod +x /etc/network/if-pre-up.d/iptables

最後查看 iptables 規則是否生效:

iptables -L -n

iptables 的規則其實還有很多,這邊只有列出基本常用到的規則,更多的規則說明就要請各位自行上網查詢了。

HelloROOT
Follow me

Share

  • Add this entry to Hatena Bookmark

Follow Me