防火牆是伺服器安全的第一道防線。本文系統解析 Linux 防火牆核心概念、Netfilter/iptables 架構 (table/chain/rule)、流量處理流程、TCP Wrappers 應用層過濾、firewalld 區域模型與實戰規則配置範例。
適用於支援 libwrap.so 的服務 (xinetd 管理服務、sshd、vsftpd 等)。
/etc/hosts.allow:符合 → 允許/etc/hosts.deny:符合 → 拒絕# /etc/hosts.allow
ALL: 127.0.0.1 # 本機所有服務
sshd: 192.168.1.0/255.255.255.0 # SSH 僅允許內網
vsftpd: 10.0.0.50 # FTP 僅允許特定 IP
# /etc/hosts.deny
sshd: ALL # SSH 預設拒絕所有 (配合 allow 白名單)
vsftpd: ALL
檢測服務是否支援:ldd $(which sshd) | grep libwrap 有輸出即支援。
| 表 | 用途 | 鏈 |
|---|---|---|
| filter | 封包過濾 (最常用) | INPUT、OUTPUT、FORWARD |
| nat | 網址轉換 (SNAT/DNAT/REDIRECT/MASQUERADE) | PREROUTING、POSTROUTING、OUTPUT |
| mangle | 封包標記/修改 (QoS、策略路由) | PREROUTING、INPUT、FORWARD、OUTPUT、POSTROUTING |
| raw | 連線追蹤豁免 (NOTRACK) | PREROUTING、OUTPUT |



iptables -L -n -v --line-numbers
iptables -t nat -L -n -v --line-numbers
# 1. 設定預設策略
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT
# 2. 允許本機回環
iptables -A INPUT -i lo -j ACCEPT
iptables -A OUTPUT -o lo -j ACCEPT
# 3. 允許已建立/相關連線
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
# 4. 允許 ICMP (ping)
iptables -A INPUT -p icmp -j ACCEPT
# 5. 開放特定服務埠
iptables -A INPUT -p tcp --dport 22 -m state --state NEW -j ACCEPT # SSH
iptables -A INPUT -p tcp --dport 80 -m state --state NEW -j ACCEPT # HTTP
iptables -A INPUT -p tcp --dport 443 -m state --state NEW -j ACCEPT # HTTPS
# 6. 拒絕其他並回應 icmp-host-prohibited
iptables -A INPUT -j REJECT --reject-with icmp-host-prohibited
iptables -A FORWARD -j REJECT --reject-with icmp-host-prohibited
# SNAT (固定公網 IP)
iptables -t nat -A POSTROUTING -s 192.168.1.0/24 -j SNAT --to-source 203.0.113.10
# MASQUERADE (動態公網 IP,如 ADSL)
iptables -t nat -A POSTROUTING -s 192.168.1.0/24 -o eth0 -j MASQUERADE
# DNAT (埠轉發:公網 8080 → 內網 192.168.1.10:80)
iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 8080 -j DNAT --to-destination 192.168.1.10:80
# 需配合 FORWARD 允許
iptables -A FORWARD -p tcp -d 192.168.1.10 --dport 80 -j ACCEPT
# 儲存
iptables-save > /etc/sysconfig/iptables # CentOS/RHEL
iptables-save > /etc/iptables/rules.v4 # Debian/Ubuntu
# 恢復
iptables-restore < /etc/sysconfig/iptables
--permanent 並 --reload)firewall-cmd --get-default-zone
firewall-cmd --set-default-zone=public
firewall-cmd --zone=public --add-service=http --permanent
firewall-cmd --zone=public --add-port=8080/tcp --permanent
firewall-cmd --zone=public --add-rich-rule='rule family="ipv4" source address="192.168.1.100" service name="ssh" accept' --permanent
firewall-cmd --reload
firewall-cmd --list-all


