Ubuntu Server ufw Firewall – 1

用指令式的 ufw 似乎很難能處理 NAT 或其它比較進階的防火牆設定。
參考網頁:
NAT and FORWARD with Ubuntu’s ufw firewall · GitHub

1. 修改 /etc/default/ufw 設定檔中關於 FORWARD POLICY 中的設定
# cp /etc/default/ufw /etc/default/ufw.$(date +%F)
# sed -i ‘s/DEFAULT_FORWARD_POLICY=”DROP”/DEFAULT_FORWARD_POLICY=”ACCEPT”/’ /etc/default/ufw

2. 修改 /etc/ufw/sysctl.conf 設定檔
# cp /etc/ufw/sysctl.conf /etc/ufw/sysctl.conf.$(date +%F)
# sed -i ‘s|#net/ipv4/ip_forward=1|net/ipv4/ip_forward=1|’ /etc/ufw/sysctl.conf[@more@]
在 ufw 的所有規則之前生效
/etc/ufw/before.rules
在 ufw 的所有規則之後生效
/etc/ufw/after.rules

3. 修改 /etc/ufw/before.rules 設定檔
# cp /etc/ufw/before.rules /etc/ufw/before.rules.$(date +%F)
# echo -e “n# NAT table rulesn*natn:PREROUTING ACCEPT [0:0]n:POSTROUTING ACCEPT [0:0]nn# Port Forwardingsn-A PREROUTING -i eth0 -p tcp –dport 22 -j DNAT –to-destination 192.168.1.10nn# Forward traffic through eth0 – Change to match you out-interfacen-A POSTROUTING -s 192.168.1.0/24 -o eth0 -j MASQUERADEnn# don’t delete the ‘COMMIT’ line or these nat table rules won’t be processednCOMMIT” >> /etc/ufw/before.rules

4. 重新載入防火牆規則
# ufw reload

5. 檢查是否有正確設定
# iptables -t nat -L -n
Chain PREROUTING (policy ACCEPT)
target     prot opt source               destination
DNAT       tcp  —  0.0.0.0/0            0.0.0.0/0            tcp dpt:22 to:192.168.1.10

Chain INPUT (policy ACCEPT)
target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

Chain POSTROUTING (policy ACCEPT)
target     prot opt source               destination
MASQUERADE  all  —  192.168.1.0/24       0.0.0.0/0

這裡要特別注意的是,手動添加 NAT 部分的防火牆規則,在重新啟動 ufw 時並不會自動清除,如果重複執行 ufw,則同樣的規則會再添加一次,所以要手動自行清除。
# iptables -t nat -F