Jex’s Note

防火牆 Iptable

基本設定

/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

附加設定

-A INPUT -p tcp --dport 445 -j ACCEPT    // for samba
-A INPUT -p tcp -s 10.160.55.77     --dport 11211 -j ACCEPT // for memcache
-A INPUT -p tcp -m state --state NEW --dport 4123 -j ACCEPT   // ssh port 改成 4123
-A INPUT -p icmp -j ACCEPT // allow ping

啟動防火牆

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

檢查是否設定成功

sudo iptables -L

重開後防火牆自動啟動

編輯 sudo vim /etc/network/if-pre-up.d/firewall:

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

permission :

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

Q & A

發生 iptables-restore: line 36 failed

雖然 36 行是指向 COMMIT, 但並不是它的問題, 是前面一些設定的問題,

把下面這些刪除再跑一次看看, 在 Raspberry Pi 發現不刪會一直過不了

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

Comments