คู่มือนี้สอนตั้งค่า iptables Firewall บน Linux (RHEL/CentOS/Fedora/Ubuntu) เพื่อเปิด Port ที่จำเป็น และบล็อกที่เหลือ
สถานการณ์: Web Server + SSH + FTP
| Service | Port | Protocol | Action |
| Apache HTTP | 80 | TCP | Allow |
| SSH | 22 | TCP | Allow |
| FTP | 21 | TCP | Allow |
| อื่นๆ | All | All | DROP |
ตรวจสอบและติดตั้ง iptables
# ตรวจสอบ
rpm -qa | grep iptables
# ติดตั้ง (ถ้ายังไม่มี)
yum install iptables
# หรือ
apt install iptables
# เริ่ม Service
systemctl start iptables
systemctl enable iptables
ดูกฎปัจจุบัน
iptables --list
# Chain INPUT (policy ACCEPT)
# target prot opt source destination
Firewall Script (Best Practice)
#!/bin/bash
# /root/iptables-firewall.sh
ANY="0/0"
OPEN_PORTS="21 22 80"
LAN_IF="eth0"
WAN_IF="eth1"
# Default Policies
iptables -P INPUT ACCEPT
iptables -P FORWARD ACCEPT
iptables -P OUTPUT ACCEPT
# Flush Existing Rules
iptables -F INPUT
iptables -F FORWARD
iptables -F OUTPUT
# Allow Loopback
iptables -A INPUT -i lo -j ACCEPT
# Allow Established/Related Connections
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
# Allow ICMP (Ping)
iptables -A INPUT -p icmp -j ACCEPT
# Allow Specific Ports (TCP)
for port in $OPEN_PORTS; do
iptables -A INPUT -p tcp --dport $port -j ACCEPT
done
# Drop Everything Else
iptables -A INPUT -j DROP
# Save Rules
iptables-save > /etc/sysconfig/iptables
# หรือ Ubuntu: iptables-save > /etc/iptables/rules.v4
ใช้งาน Script
chmod +x /root/iptables-firewall.sh
/root/iptables-firewall.sh
iptables --list -n -v
เพิ่ม/ลบ Port
แก้ไขตัวแปร OPEN_PORTS ใน Script แล้วรันใหม่
ทำให้โหลดตอน Boot
| OS | วิธี |
| RHEL/CentOS 7+ | systemctl enable iptables |
| Ubuntu/Debian | apt install iptables-persistent (Save ตอนติดตั้ง) |
| Systemd (General) | สร้าง Service Unit เรียก iptables-restore |
ทางเลือก GUI: UFW / Firewalld
- UFW (Uncomplicated Firewall): Ubuntu Default, CLI เรียบง่าย
ufw allow 80/tcp
- Firewalld: RHEL/Fedora Default, Zone-based, Dynamic
firewall-cmd --add-port=80/tcp
- nftables: Successor ของ iptables (Kernel 3.13+) - ใช้
nft command
Best Practices
- Default Policy: DROP (INPUT/FORWARD), ACCEPT (OUTPUT)
- Allow Established/Related ก่อนทุกอย่าง
- Allow Loopback (lo)
- Limit SSH:
iptables -A INPUT -p tcp --dport 22 -m recent --update --seconds 60 --hitcount 4 -j DROP
- Log Dropped Packets:
iptables -A INPUT -j LOG --log-prefix "IPT_DROP: "
- Test ทุกครั้งหลังแก้ไข:
ssh user@server จากเครื่องอื่น
iptables เป็นพื้นฐาน Firewall ใน Linux การเข้าใจ Chain, Table, Match, Target จะช่วยให้ควบคุม Network Traffic ได้อย่างแม่นยำ