Debain 建立防火牆規則

查看有無建立iptables

sudo iptables -L

建立一個新檔案 iptables.firewall.rules

sudo vim /etc/iptables.firewall.rules 

內容如下

*filter

#  Allow all loopback (lo0) traffic and drop all traffic to 127/8 that doesn't use lo0
-A INPUT -i lo -j ACCEPT
-A INPUT -d 127.0.0.0/8 -j REJECT

#  Accept all established inbound connections
-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

#  Allow all outbound traffic - you can modify this to only allow certain traffic
-A OUTPUT -j ACCEPT

#  Allow HTTP and HTTPS connections from anywhere (the normal ports for websites and SSL).
-A INPUT -p tcp --dport 80 -j ACCEPT
-A INPUT -p tcp --dport 443 -j ACCEPT

#  Allow SSH connections
#
#  The -dport number should be the same port number you set in sshd_config
#
-A INPUT -p tcp -m state --state NEW --dport 22 -j ACCEPT

#  Allow ping
-A INPUT -p icmp -j ACCEPT

#  Log iptables denied calls
-A INPUT -m limit --limit 5/min -j LOG --log-prefix "iptables denied: " --log-level 7

#  Drop all other inbound - default deny unless explicitly allowed policy
-A INPUT -j DROP
-A FORWARD -j DROP

COMMIT

規則只開放 80(http), 443(https), SSH(22), ICMP 服務

啟用規則

sudo iptables-restore < /etc/iptables.firewall.rules

最後是確保每次重開機都會載入這規則

sudo vi /etc/network/if-pre-up.d/firewall

內容如下

#!/bin/sh
/sbin/iptables-restore < /etc/iptables.firewall.rules

更改檔案權限

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

linode官方教學: https://www.linode.com/docs/security/securing-your-server

其他小技巧

把80port轉到5601

sudo iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 5601

清除規則

sudo iptables -F -t nat 
sudo iptables -F