Software engineering notes

Linux iptables

基本設定

/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

Troubleshootings

發生 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

Web app 開 80 port 遇到 permission denied

只有 root 才可以開小於 1024 的 port,最簡單的解決方法就是先開一個高一點的 port (e.g. 8080),再用 iptable 去 forward 80 -> 8080

iptables -t mangle -A PREROUTING -p tcp --dport 80 -j MARK --set-mark 1
iptables -t mangle -A PREROUTING -p tcp --dport 443 -j MARK --set-mark 1
iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8080
iptables -t nat -A PREROUTING -p tcp --dport 443 -j REDIRECT --to-port 8181
iptables -I INPUT -m state --state NEW -m tcp -p tcp --dport 8080 -m mark --mark 1 -j ACCEPT
iptables -I INPUT -m state --state NEW -m tcp -p tcp --dport 8181 -m mark --mark 1 -j ACCEPT