Network Security Infrastructure (โครงสร้างพื้นฐานความปลอดภัยเครือข่าย)

1.1 ภาพรวมและวิวัฒนาการของ Firewall

1.1.1 ความเป็นมาและประวัติศาสตร์ (History & Evolution)

Firewall คืออุปกรณ์หรือซอฟต์แวร์ที่ทำหน้าที่ควบคุมการรับ-ส่งข้อมูลเครือข่ายตาม กฎ (Rules) ที่กำหนดไว้ล่วงหน้า เพื่อแบ่งแยกและปกป้องเครือข่ายภายในจากภัยคุกคามภายนอก

%%{init: {'theme': 'base', 'themeVariables': {
  'primaryColor': '#282828',
  'primaryTextColor': '#ebdbb2',
  'primaryBorderColor': '#504945',
  'lineColor': '#a89984',
  'secondaryColor': '#3c3836',
  'tertiaryColor': '#1d2021',
  'background': '#282828',
  'mainBkg': '#282828',
  'nodeBorder': '#504945',
  'clusterBkg': '#32302f',
  'titleColor': '#fabd2f',
  'edgeLabelBackground': '#3c3836',
  'fontFamily': 'monospace'
}}}%%

flowchart TB
  subgraph era1["ยุคที่ 1: 1980s — Packet Filtering"]
    A["📦 Static Packet Filter - (กรองแพ็กเก็ตพื้นฐาน)"]
  end
  subgraph era2["ยุคที่ 2: 1990s — Stateful"]
    B["🔄 Stateful Inspection - (ตรวจสอบสถานะการเชื่อมต่อ)"]
  end
  subgraph era3["ยุคที่ 3: 2000s — Application Layer"]
    C["🖥️ Application Firewall - (WAF, Proxy-based)"]
  end
  subgraph era4["ยุคที่ 4: 2010s+ — NGFW"]
    D["🧠 Next-Gen Firewall - (DPI, IPS/IDS, AI)"]
  end

  A --> B --> C --> D

  style era1 fill:#3c3836,stroke:#fabd2f,color:#ebdbb2
  style era2 fill:#3c3836,stroke:#b8bb26,color:#ebdbb2
  style era3 fill:#3c3836,stroke:#83a598,color:#ebdbb2
  style era4 fill:#3c3836,stroke:#d3869b,color:#ebdbb2
  style A fill:#1d2021,stroke:#fabd2f,color:#fabd2f
  style B fill:#1d2021,stroke:#b8bb26,color:#b8bb26
  style C fill:#1d2021,stroke:#83a598,color:#83a598
  style D fill:#1d2021,stroke:#d3869b,color:#d3869b

1.2 ประเภทของ Firewall (Types of Firewalls)

1.2.1 Packet Filtering Firewall (ไฟร์วอลล์กรองแพ็กเก็ต)

Packet Filtering Firewall ทำงานที่ Network Layer (Layer 3) และ Transport Layer (Layer 4) โดยตรวจสอบข้อมูลหัวแพ็กเก็ต (Header) ได้แก่:

คุณสมบัติ รายละเอียด
ความเร็ว สูงมาก (ไม่ต้องเก็บ state)
ความซับซ้อน ต่ำ
ข้อจำกัด ไม่รู้สถานะการเชื่อมต่อ
ตัวอย่าง ACL บน Router, iptables พื้นฐาน

1.2.2 Stateful Inspection Firewall (ไฟร์วอลล์ตรวจสอบสถานะ)

Stateful Inspection หรือ Dynamic Packet Filtering ทำงานโดยการติดตาม สถานะการเชื่อมต่อ (Connection State) ผ่าน State Table ซึ่งบันทึก:

%%{init: {'theme': 'base', 'themeVariables': {
  'primaryColor': '#282828',
  'primaryTextColor': '#ebdbb2',
  'primaryBorderColor': '#504945',
  'lineColor': '#a89984',
  'background': '#282828',
  'mainBkg': '#282828',
  'nodeBorder': '#504945',
  'clusterBkg': '#32302f',
  'titleColor': '#fabd2f',
  'edgeLabelBackground': '#3c3836',
  'fontFamily': 'monospace'
}}}%%

stateDiagram-v2
  [*] --> NEW : แพ็กเก็ตแรก (SYN)
  NEW --> ESTABLISHED : SYN-ACK ได้รับ
  ESTABLISHED --> RELATED : เปิด connection ใหม่ที่เกี่ยวข้อง
  ESTABLISHED --> CLOSE_WAIT : FIN ได้รับ
  RELATED --> ESTABLISHED : ส่งข้อมูลผ่าน
  CLOSE_WAIT --> [*] : การเชื่อมต่อสิ้นสุด
  ESTABLISHED --> INVALID : ผิดรูปแบบ
  INVALID --> [*] : DROP แพ็กเก็ต

States หลักใน Netfilter/iptables:

State ความหมาย
NEW แพ็กเก็ตเริ่มต้นการเชื่อมต่อใหม่
ESTABLISHED แพ็กเก็ตเป็นส่วนหนึ่งของการเชื่อมต่อที่มีอยู่
RELATED แพ็กเก็ตเกี่ยวข้องกับ connection ที่มีอยู่ (เช่น FTP data channel)
INVALID แพ็กเก็ตที่ไม่สามารถระบุ state ได้

1.2.3 Application Layer Firewall / WAF (ไฟร์วอลล์ระดับแอปพลิเคชัน)

Application Layer Firewall ทำงานที่ Layer 7 สามารถตรวจสอบเนื้อหาจริงของแพ็กเก็ต:

1.2.4 Next-Generation Firewall — NGFW (ไฟร์วอลล์รุ่นใหม่)

NGFW รวมความสามารถของ Firewall รุ่นก่อนหน้าและเพิ่มเติม:

ประเภท Layer State DPI IPS ตัวอย่าง
Packet Filter 3-4 ACL Router
Stateful 3-4 iptables
App Layer 7 Squid, ModSecurity
NGFW 2-7 Palo Alto, Fortinet

1.3 Stateful vs Stateless Firewalls (เปรียบเทียบเชิงลึก)

1.3.1 การเปรียบเทียบหลักการทำงาน

%%{init: {'theme': 'base', 'themeVariables': {
  'primaryColor': '#282828',
  'primaryTextColor': '#ebdbb2',
  'primaryBorderColor': '#504945',
  'lineColor': '#a89984',
  'background': '#282828',
  'mainBkg': '#282828',
  'nodeBorder': '#504945',
  'clusterBkg': '#32302f',
  'titleColor': '#fabd2f',
  'edgeLabelBackground': '#3c3836',
  'fontFamily': 'monospace'
}}}%%

flowchart TB
  subgraph stateless["🔴 Stateless — ตรวจทุกแพ็กเก็ตแยกกัน"]
    P1["แพ็กเก็ต A - SYN"] --> R1{"ตรวจ Rules - เฉพาะ Header"}
    P2["แพ็กเก็ต B - ACK"] --> R2{"ตรวจ Rules - เฉพาะ Header"}
    R1 -->|"ALLOW/DENY"| OUT1["ผลลัพธ์"]
    R2 -->|"ALLOW/DENY"| OUT2["ผลลัพธ์"]
  end

  subgraph stateful["🟢 Stateful — จำสถานะการเชื่อมต่อ"]
    P3["แพ็กเก็ต A - SYN"] --> ST["State Table - (ตารางสถานะ)"]
    ST --> R3{"ตรวจ Rules - + State"}
    P4["แพ็กเก็ต B - ACK"] --> ST
    R3 -->|"ALLOW"| OUT3["ผลลัพธ์"]
  end

  style stateless fill:#3c3836,stroke:#fb4934,color:#ebdbb2
  style stateful fill:#3c3836,stroke:#b8bb26,color:#ebdbb2
  style ST fill:#1d2021,stroke:#fabd2f,color:#fabd2f

1.3.2 การคำนวณทรัพยากรที่ใช้ (Resource Calculation)

Stateful Firewall ต้องการหน่วยความจำสำหรับ State Table โดยสามารถประมาณได้:

Mstate = Nconn × Sentry

โดยที่:

ตัวอย่างการคำนวณ:

สมมติ Web Server มี concurrent connections = 50,000 และ entry size = 300 bytes:

Mstate = 50,000 × 300 = 15,000,000 bytes 14.3 MB

สำหรับ Enterprise ที่มี 500,000 connections:

Mstate = 500,000 × 300 = 150,000,000 bytes 143 MB

1.4 Security Zones และ Network Topologies (โซนความปลอดภัยและโทโพโลยี)

1.4.1 แนวคิด Security Zones

Security Zone คือกลุ่มของทรัพยากรเครือข่ายที่มีระดับความน่าเชื่อถือ (Trust Level) เดียวกัน และมีนโยบายการเข้าถึงเหมือนกัน

%%{init: {'theme': 'base', 'themeVariables': {
  'primaryColor': '#282828',
  'primaryTextColor': '#ebdbb2',
  'primaryBorderColor': '#504945',
  'lineColor': '#a89984',
  'background': '#282828',
  'mainBkg': '#282828',
  'nodeBorder': '#504945',
  'clusterBkg': '#32302f',
  'titleColor': '#fabd2f',
  'edgeLabelBackground': '#3c3836',
  'fontFamily': 'monospace'
}}}%%

flowchart TB
  INTERNET["🌐 Internet - (Untrusted Zone - Trust = 0)"]

  subgraph DMZ["🟡 DMZ - (Demilitarized Zone — Trust = 50)"]
    WEB["🖥️ Web Server"]
    MAIL["📧 Mail Server"]
    DNS["🔍 DNS Server"]
  end

  subgraph INTERNAL["🟢 Internal Network - (Trusted Zone — Trust = 100)"]
    PC["💻 User Workstations"]
    DB["🗄️ Database Server"]
    FILE["📁 File Server"]
    AD["🔑 Active Directory"]
  end

  subgraph MGMT["🔵 Management Zone - (Restricted — Trust = 75)"]
    FW_MGMT["⚙️ Firewall Console"]
    SIEM["📊 SIEM/Log Server"]
  end

  INTERNET -->|"HTTP/HTTPS - SMTP"| DMZ
  DMZ -->|"DB Queries - (Filtered)"| DB
  PC --> INTERNAL
  FW_MGMT -.->|"SSH Only"| INTERNET

  style DMZ fill:#3c3836,stroke:#fabd2f,color:#ebdbb2
  style INTERNAL fill:#3c3836,stroke:#b8bb26,color:#ebdbb2
  style MGMT fill:#3c3836,stroke:#83a598,color:#ebdbb2
  style INTERNET fill:#1d2021,stroke:#fb4934,color:#fb4934

1.4.2 DMZ (Demilitarized Zone) — โซน Demilitarized

DMZ คือโซนกลางระหว่าง Internet และเครือข่ายภายใน ทำหน้าที่รองรับ Public-facing Services โดยแยกออกจากเครือข่ายหลัก:

1.4.3 โทโพโลยี Dual-Homed DMZ

%%{init: {'theme': 'base', 'themeVariables': {
  'primaryColor': '#282828',
  'primaryTextColor': '#ebdbb2',
  'primaryBorderColor': '#504945',
  'lineColor': '#a89984',
  'background': '#282828',
  'mainBkg': '#282828',
  'nodeBorder': '#504945',
  'clusterBkg': '#32302f',
  'titleColor': '#fabd2f',
  'edgeLabelBackground': '#3c3836',
  'fontFamily': 'monospace'
}}}%%

flowchart TB
  I["🌐 Internet"]
  FW1["🔥 Firewall ภายนอก - (Outer Firewall)"]
  FW2["🔥 Firewall ภายใน - (Inner Firewall)"]

  subgraph DMZ_ZONE["🟡 DMZ"]
    WEB["Web Server - 192.168.1.10"]
    SMTP["Mail Server - 192.168.1.20"]
  end

  subgraph INT_ZONE["🟢 Internal Network"]
    APP["App Server - 10.0.0.10"]
    DB["Database - 10.0.0.20"]
    CLIENT["Clients - 10.0.0.0/24"]
  end

  I --> FW1 --> DMZ_ZONE --> FW2 --> INT_ZONE

  style DMZ_ZONE fill:#3c3836,stroke:#fabd2f,color:#ebdbb2
  style INT_ZONE fill:#3c3836,stroke:#b8bb26,color:#ebdbb2
  style FW1 fill:#1d2021,stroke:#fb4934,color:#fb4934
  style FW2 fill:#1d2021,stroke:#fb4934,color:#fb4934

1.5 Firewall Rules และ Policies (กฎและนโยบาย)

1.5.1 หลักการเขียน Firewall Rules

กฎทอง (Golden Rules) ของ Firewall Policy:

  1. Default Deny — ปฏิเสธทุกอย่างโดย default แล้วค่อยเปิดที่จำเป็น
  2. Least Privilege — เปิดเฉพาะสิ่งที่จำเป็นสำหรับการทำงาน
  3. Rule Ordering — กฎที่เข้มงวดกว่าต้องอยู่ก่อน
  4. Logging — บันทึก traffic ที่ถูก deny และที่น่าสงสัย
  5. Regular Review — ตรวจสอบและอัปเดตกฎเป็นระยะ

1.5.2 ตัวอย่าง Firewall Rule Table

Rule # Direction Source Destination Port/Protocol Action Log
1 IN Any 192.168.1.10 80/TCP ALLOW NO
2 IN Any 192.168.1.10 443/TCP ALLOW NO
3 IN 10.0.0.0/8 Any 22/TCP ALLOW YES
4 IN Any Any 22/TCP DENY YES
5 OUT 10.0.0.0/8 Any Any ALLOW NO
99 ANY Any Any Any DENY YES

1.5.3 การคำนวณ Firewall Throughput

Throughput คือปริมาณข้อมูลที่ Firewall ประมวลผลได้ต่อวินาที:

Teffective = Thardware × ( 1 - Oinspection )

โดยที่:

ตัวอย่าง: Firewall มี T_hardware = 10 Gbps, overhead จาก DPI = 30%:

Teffective = 10 × (1-0.30) = 10 × 0.70 = 7 Gbps

1.6 Network Segmentation และ VLANs (การแบ่งส่วนเครือข่าย)

1.6.1 แนวคิด Network Segmentation

Network Segmentation คือการแบ่งเครือข่ายขนาดใหญ่ออกเป็นส่วนย่อย (Segments) เพื่อ:

1.6.2 VLAN (Virtual Local Area Network)

VLAN ทำให้สามารถแบ่ง broadcast domain แบบ logical บน physical switch เดียวกัน:

%%{init: {'theme': 'base', 'themeVariables': {
  'primaryColor': '#282828',
  'primaryTextColor': '#ebdbb2',
  'primaryBorderColor': '#504945',
  'lineColor': '#a89984',
  'background': '#282828',
  'mainBkg': '#282828',
  'nodeBorder': '#504945',
  'clusterBkg': '#32302f',
  'titleColor': '#fabd2f',
  'edgeLabelBackground': '#3c3836',
  'fontFamily': 'monospace'
}}}%%

flowchart TB
  subgraph SW["Physical Switch (สวิตช์จริง 1 ตัว)"]
    subgraph VLAN10["VLAN 10 — HR - 10.10.10.0/24"]
      H1["💻 HR-PC1"] 
      H2["💻 HR-PC2"]
    end
    subgraph VLAN20["VLAN 20 — Finance - 10.20.20.0/24"]
      F1["💻 Finance-PC1"]
      F2["🖨️ Finance-Printer"]
    end
    subgraph VLAN30["VLAN 30 — IT - 10.30.30.0/24"]
      I1["🖥️ Server1"]
      I2["🖥️ Server2"]
    end
  end

  ROUTER["🔀 Layer 3 Router/Switch - (Inter-VLAN Routing)"]

  VLAN10 <-->|"Trunk Port - 802.1Q"| ROUTER
  VLAN20 <-->|"Trunk Port - 802.1Q"| ROUTER
  VLAN30 <-->|"Trunk Port - 802.1Q"| ROUTER

  style VLAN10 fill:#3c3836,stroke:#83a598,color:#ebdbb2
  style VLAN20 fill:#3c3836,stroke:#fabd2f,color:#ebdbb2
  style VLAN30 fill:#3c3836,stroke:#d3869b,color:#ebdbb2
  style SW fill:#1d2021,stroke:#504945,color:#a89984
  style ROUTER fill:#1d2021,stroke:#b8bb26,color:#b8bb26

1.6.3 IEEE 802.1Q VLAN Tagging

802.1Q เพิ่ม 4-byte Tag เข้าไปใน Ethernet frame:

Field ขนาด ความหมาย
TPID 2 bytes Tag Protocol Identifier (0x8100)
PCP 3 bits Priority Code Point (QoS)
DEI 1 bit Drop Eligible Indicator
VID 12 bits VLAN ID (1–4094)

จำนวน VLAN สูงสุด:

NVLAN = 212 = 4,096 VLANs

(VLAN 0 และ 4095 สงวนไว้ ใช้งานได้จริง 1–4094)


1.7 UFW (Uncomplicated Firewall) — คู่มือการใช้งานฉบับสมบูรณ์

1.7.1 ภาพรวมและสถาปัตยกรรม UFW

UFW (Uncomplicated Firewall) คือ front-end สำหรับ iptables บน Linux ที่ถูกออกแบบมาให้ใช้งานง่าย พัฒนาโดย Ubuntu team และเป็น default firewall บน Ubuntu/Debian

%%{init: {'theme': 'base', 'themeVariables': {
  'primaryColor': '#282828',
  'primaryTextColor': '#ebdbb2',
  'primaryBorderColor': '#504945',
  'lineColor': '#a89984',
  'background': '#282828',
  'mainBkg': '#282828',
  'nodeBorder': '#504945',
  'clusterBkg': '#32302f',
  'titleColor': '#fabd2f',
  'edgeLabelBackground': '#3c3836',
  'fontFamily': 'monospace'
}}}%%

flowchart TB
  USER["👤 ผู้ใช้งาน - (Admin)"]
  UFW["🛡️ UFW - (/usr/sbin/ufw)"]
  subgraph RULES["UFW Rule Files"]
    URULES["/etc/ufw/user.rules"]
    USER6["/etc/ufw/user6.rules"]
    BEFORE["/etc/ufw/before.rules"]
    AFTER["/etc/ufw/after.rules"]
  end
  IPTABLES["⚙️ iptables / ip6tables - (Kernel Netfilter)"]
  KERNEL["🐧 Linux Kernel - Netfilter Framework"]

  USER -->|"คำสั่ง ufw"| UFW
  UFW -->|"แปลงเป็น rules"| RULES
  RULES -->|"โหลด rules"| IPTABLES
  IPTABLES -->|"จัดการ packet"| KERNEL

  style UFW fill:#1d2021,stroke:#fabd2f,color:#fabd2f
  style RULES fill:#3c3836,stroke:#83a598,color:#ebdbb2
  style IPTABLES fill:#1d2021,stroke:#b8bb26,color:#b8bb26
  style KERNEL fill:#1d2021,stroke:#d3869b,color:#d3869b

1.7.2 การติดตั้งและเริ่มต้นใช้งาน UFW

# ติดตั้ง UFW (ถ้ายังไม่มี)
sudo apt update && sudo apt install ufw -y    # Debian/Ubuntu
sudo dnf install ufw -y                        # Fedora/RHEL
sudo pacman -S ufw                             # Arch Linux

# ตรวจสอบสถานะ
sudo ufw status
sudo ufw status verbose
sudo ufw status numbered    # แสดงพร้อมเลขกฎ

# เปิด/ปิด UFW
sudo ufw enable             # เปิดใช้งาน (จะ block ทุกอย่างที่ไม่ได้อนุญาต)
sudo ufw disable            # ปิดการใช้งาน
sudo ufw reload             # โหลด rules ใหม่โดยไม่หยุดบริการ
sudo ufw reset              # รีเซ็ต rules ทั้งหมด (ระวัง!)

1.7.3 การตั้งค่า Default Policy

# ตั้งค่า Default Policy — สำคัญมาก ต้องทำก่อนเปิด UFW
sudo ufw default deny incoming    # ปฏิเสธ traffic ขาเข้าทั้งหมดโดย default
sudo ufw default allow outgoing   # อนุญาต traffic ขาออกทั้งหมด
sudo ufw default deny forward     # ปฏิเสธ packet forwarding (สำหรับ router)

# ตรวจสอบ default policy
sudo ufw status verbose | grep "Default"

1.7.4 กรณีที่ 1 — เซิร์ฟเวอร์เว็บพื้นฐาน (Web Server)

# ===== กรณี: Web Server สาธารณะ =====
# อนุญาตเฉพาะ HTTP, HTTPS และ SSH

# วิธีที่ 1: ระบุชื่อ service (UFW จะค้นหา port จาก /etc/services)
sudo ufw allow ssh
sudo ufw allow http
sudo ufw allow https

# วิธีที่ 2: ระบุ port ตรง ๆ
sudo ufw allow 22/tcp
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp

# วิธีที่ 3: ใช้ Application Profile (ถ้ามี)
sudo ufw app list                  # ดูรายการ profiles
sudo ufw allow 'Nginx Full'        # HTTP + HTTPS
sudo ufw allow 'Apache Full'

# ตรวจสอบผลลัพธ์
sudo ufw status verbose

1.7.5 กรณีที่ 2 — จำกัดการเข้าถึง SSH จาก IP เฉพาะ

# ===== กรณี: จำกัด SSH ให้เฉพาะ IP ของ Admin =====

# อนุญาต SSH จาก IP เฉพาะ
sudo ufw allow from 203.0.113.10 to any port 22

# อนุญาต SSH จาก subnet ของ VPN admin
sudo ufw allow from 10.10.10.0/24 to any port 22 proto tcp

# ปฏิเสธ SSH จากทุกที่อื่น
sudo ufw deny 22/tcp

# อนุญาต SSH จากหลาย IP (ทำทีละ rule)
sudo ufw allow from 203.0.113.10 to any port 22
sudo ufw allow from 198.51.100.5 to any port 22
sudo ufw deny 22/tcp

# หมายเหตุ: UFW ประมวลผล rules ตามลำดับ — rule แรกที่ match จะถูกใช้

1.7.6 กรณีที่ 3 — Database Server (เฉพาะ Internal)

# ===== กรณี: MySQL/PostgreSQL เข้าถึงได้เฉพาะ Internal Network =====

# MySQL (port 3306) — อนุญาตเฉพาะ LAN
sudo ufw allow from 10.0.0.0/8 to any port 3306 proto tcp
sudo ufw deny 3306/tcp

# PostgreSQL (port 5432) — อนุญาตเฉพาะ app server
sudo ufw allow from 10.0.1.50 to any port 5432 proto tcp
sudo ufw deny 5432/tcp

# Redis (port 6379) — localhost เท่านั้น
sudo ufw deny 6379/tcp    # ปิด Redis จากภายนอกทั้งหมด
# Redis ควร bind ที่ 127.0.0.1 ใน redis.conf ด้วย

# MongoDB (port 27017)
sudo ufw allow from 10.0.0.0/24 to any port 27017 proto tcp
sudo ufw deny 27017/tcp

1.7.7 กรณีที่ 4 — Mail Server

# ===== กรณี: Mail Server ที่รับ-ส่งอีเมล =====

# SMTP (25) — รับอีเมลจากภายนอก
sudo ufw allow 25/tcp

# SMTP Submission (587) — ส่งอีเมลจาก clients
sudo ufw allow 587/tcp

# SMTPS (465) — SMTP over SSL
sudo ufw allow 465/tcp

# IMAP (143) — รับอีเมลจาก clients
sudo ufw allow 143/tcp

# IMAPS (993) — IMAP over SSL
sudo ufw allow 993/tcp

# POP3S (995) — POP3 over SSL
sudo ufw allow 995/tcp

# ปิด POP3 ที่ไม่เข้ารหัส
sudo ufw deny 110/tcp

1.7.8 กรณีที่ 5 — Rate Limiting เพื่อป้องกัน Brute Force

# ===== กรณี: ป้องกัน SSH Brute Force ด้วย Rate Limiting =====
# UFW limit จะบล็อก IP ที่พยายาม connect มากกว่า 6 ครั้งใน 30 วินาที

sudo ufw limit ssh
sudo ufw limit 22/tcp

# ตรวจสอบว่า limit ถูกเพิ่มแล้ว
sudo ufw status verbose | grep LIMIT

# สำหรับ port อื่น ๆ ที่ต้องการ rate limit
sudo ufw limit 3389/tcp    # RDP

# ดู iptables rules ที่ UFW สร้างขึ้นสำหรับ limit
sudo iptables -L ufw-user-limit -n -v

1.7.9 กรณีที่ 6 — Block IP ที่น่าสงสัย

# ===== กรณี: บล็อก IP/Subnet ที่น่าสงสัย =====

# บล็อก IP เฉพาะ
sudo ufw deny from 192.168.100.50

# บล็อกทั้ง subnet
sudo ufw deny from 10.20.0.0/16

# บล็อก IP จากการส่ง traffic ไปที่ port ใดก็ตาม
sudo ufw deny from 203.0.113.0/24 to any

# บล็อก IP ไม่ให้เข้าถึง port เฉพาะ
sudo ufw deny from 198.51.100.5 to any port 80

# ลบการบล็อก (ต้องทราบ rule number)
sudo ufw status numbered
sudo ufw delete [rule_number]

# หรือลบโดยระบุ rule เดิม
sudo ufw delete deny from 192.168.100.50

1.7.10 กรณีที่ 7 — Docker และ UFW (ปัญหาที่พบบ่อย)

# ===== ปัญหา: Docker bypass UFW rules =====
# Docker แก้ไข iptables โดยตรง ทำให้ UFW rules ไม่ทำงานกับ container ports

# วิธีแก้ไข: แก้ /etc/ufw/after.rules เพิ่ม rules ที่ท้ายไฟล์
sudo nano /etc/ufw/after.rules
# เพิ่มที่ท้ายไฟล์ /etc/ufw/after.rules
*filter
:ufw-user-forward - [0:0]
:DOCKER-USER - [0:0]
-A DOCKER-USER -j ufw-user-forward

-A ufw-user-forward -o docker0 -p tcp -d 172.17.0.0/16 --dport 3306 -j ACCEPT
-A ufw-user-forward -o docker0 -j DROP
COMMIT
# หรือใช้ /etc/docker/daemon.json เพื่อปิด iptables ของ Docker
sudo nano /etc/docker/daemon.json
{
  "iptables": false
}
sudo systemctl restart docker
sudo ufw reload

1.7.11 กรณีที่ 8 — UFW Logging

# ===== การตั้งค่า Logging =====

# เปิด logging
sudo ufw logging on       # เปิด logging ระดับ low (default)
sudo ufw logging low      # log เฉพาะ blocked packets (เบา)
sudo ufw logging medium   # log blocked + invalid packets
sudo ufw logging high     # log ทุกอย่าง (หนักมาก)
sudo ufw logging full     # log ทุก packet รวม accepted

# ปิด logging
sudo ufw logging off

# ดู log
sudo tail -f /var/log/ufw.log

# กรอง log หา connection ที่ถูกบล็อก
sudo grep "BLOCK" /var/log/ufw.log | tail -20

# วิเคราะห์ IPs ที่ถูกบล็อกมากที่สุด
sudo grep "BLOCK" /var/log/ufw.log | \
  grep -oP 'SRC=\K[0-9.]+' | \
  sort | uniq -c | sort -rn | head -10

1.7.12 กรณีที่ 9 — การตั้งค่าสำหรับ VPN Server (WireGuard)

# ===== กรณี: ตั้งค่า UFW สำหรับ WireGuard VPN Server =====

# อนุญาต WireGuard port (default 51820/UDP)
sudo ufw allow 51820/udp

# เปิด IP forwarding ใน kernel
echo "net.ipv4.ip_forward=1" | sudo tee -a /etc/sysctl.conf
echo "net.ipv6.conf.all.forwarding=1" | sudo tee -a /etc/sysctl.conf
sudo sysctl -p

# แก้ไข /etc/ufw/before.rules เพิ่ม NAT rules
# (สำหรับ WireGuard ที่ต้องการ masquerade traffic ออก internet)
sudo nano /etc/ufw/before.rules
# เพิ่มก่อนบรรทัด *filter ใน before.rules
*nat
:POSTROUTING ACCEPT [0:0]
-A POSTROUTING -s 10.8.0.0/8 -o eth0 -j MASQUERADE
COMMIT
# เปิด DEFAULT_FORWARD_POLICY ใน /etc/default/ufw
sudo sed -i 's/DEFAULT_FORWARD_POLICY="DROP"/DEFAULT_FORWARD_POLICY="ACCEPT"/' \
  /etc/default/ufw

sudo ufw reload

1.7.13 กรณีที่ 10 — การจัดการ Rules ขั้นสูง

# ===== การจัดการ Rules อย่างละเอียด =====

# ดู rules พร้อมเลขลำดับ
sudo ufw status numbered

# ลบ rule ด้วยเลขลำดับ
sudo ufw delete 3

# แทรก rule ที่ตำแหน่งใดก็ได้
sudo ufw insert 1 allow from 10.0.0.1 to any port 22

# ดู rules ทั้งหมดในรูปแบบ iptables
sudo ufw show raw

# Export/Backup rules ปัจจุบัน
sudo cp /etc/ufw/user.rules /etc/ufw/user.rules.backup
sudo cp /etc/ufw/user6.rules /etc/ufw/user6.rules.backup

# ดู Application Profiles ที่มี
sudo ufw app list
sudo ufw app info 'Nginx Full'
sudo ufw app info OpenSSH

1.7.14 Script ตั้งค่า UFW อัตโนมัติสำหรับ Web Server

#!/usr/bin/env python3
"""
สคริปต์ตั้งค่า UFW อัตโนมัติสำหรับ Web Server
Author: Network Security Course
วิชา: Network Security Infrastructure
"""

import subprocess
import sys
import logging
from typing import List, Tuple

# ตั้งค่า logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s%(levelname)s%(message)s'
)
logger = logging.getLogger(__name__)


def run_ufw_command(args: List[str]) -> Tuple[int, str, str]:
    """
    รันคำสั่ง UFW และส่งคืนผลลัพธ์
    
    Args:
        args: รายการ arguments สำหรับคำสั่ง ufw
        
    Returns:
        tuple: (return_code, stdout, stderr)
    """
    cmd = ['sudo', 'ufw'] + args
    logger.debug(f"รันคำสั่ง: {' '.join(cmd)}")
    
    result = subprocess.run(
        cmd,
        capture_output=True,
        text=True
    )
    return result.returncode, result.stdout, result.stderr


def setup_web_server_firewall(
    admin_ips: List[str],
    enable_https: bool = True,
    enable_mail: bool = False
) -> bool:
    """
    ตั้งค่า UFW สำหรับ Web Server ตามมาตรฐาน Security
    
    Args:
        admin_ips: รายการ IP addresses ของ admin ที่อนุญาตให้ SSH
        enable_https: เปิดใช้ HTTPS (port 443) หรือไม่
        enable_mail: เปิดพอร์ต Mail server หรือไม่
        
    Returns:
        bool: True ถ้าตั้งค่าสำเร็จ
    """
    
    logger.info("เริ่มตั้งค่า UFW สำหรับ Web Server")
    
    # ขั้นตอนที่ 1: รีเซ็ต UFW
    logger.info("ขั้นตอน 1: รีเซ็ต UFW rules ทั้งหมด")
    run_ufw_command(['--force', 'reset'])
    
    # ขั้นตอนที่ 2: ตั้งค่า Default Policy
    logger.info("ขั้นตอน 2: ตั้งค่า Default Policy (Deny All)")
    run_ufw_command(['default', 'deny', 'incoming'])
    run_ufw_command(['default', 'allow', 'outgoing'])
    
    # ขั้นตอนที่ 3: เปิด SSH เฉพาะ admin IPs
    logger.info(f"ขั้นตอน 3: เปิด SSH สำหรับ {len(admin_ips)} IP(s)")
    for ip in admin_ips:
        code, out, err = run_ufw_command(
            ['allow', 'from', ip, 'to', 'any', 'port', '22', 'proto', 'tcp']
        )
        if code == 0:
            logger.info(f"  ✓ อนุญาต SSH จาก {ip}")
        else:
            logger.error(f"  ✗ ไม่สามารถเพิ่ม rule สำหรับ {ip}: {err}")
            return False
    
    # ปิด SSH จากที่อื่น
    run_ufw_command(['deny', '22/tcp'])
    
    # ขั้นตอนที่ 4: เปิด HTTP
    logger.info("ขั้นตอน 4: เปิด HTTP (port 80)")
    run_ufw_command(['allow', '80/tcp'])
    
    # ขั้นตอนที่ 5: เปิด HTTPS ถ้าต้องการ
    if enable_https:
        logger.info("ขั้นตอน 5: เปิด HTTPS (port 443)")
        run_ufw_command(['allow', '443/tcp'])
    
    # ขั้นตอนที่ 6: เปิด Mail ports ถ้าต้องการ
    if enable_mail:
        logger.info("ขั้นตอน 6: เปิด Mail ports")
        mail_ports = ['25/tcp', '587/tcp', '465/tcp', '993/tcp', '995/tcp']
        for port in mail_ports:
            run_ufw_command(['allow', port])
            logger.info(f"  ✓ เปิด port {port}")
    
    # ขั้นตอนที่ 7: เปิด rate limiting สำหรับ SSH
    logger.info("ขั้นตอน 7: เปิด Rate Limiting สำหรับ SSH")
    run_ufw_command(['limit', 'ssh'])
    
    # ขั้นตอนที่ 8: เปิด Logging
    logger.info("ขั้นตอน 8: เปิด UFW Logging")
    run_ufw_command(['logging', 'medium'])
    
    # ขั้นตอนที่ 9: เปิดใช้งาน UFW
    logger.info("ขั้นตอน 9: เปิดใช้งาน UFW")
    code, out, err = run_ufw_command(['--force', 'enable'])
    if code != 0:
        logger.error(f"ไม่สามารถเปิด UFW: {err}")
        return False
    
    logger.info("✓ ตั้งค่า UFW สำเร็จ!")
    
    # แสดงสรุป rules
    _, status, _ = run_ufw_command(['status', 'verbose'])
    logger.info(f" - สรุป UFW Rules: - {status}")
    
    return True


def block_ip_list(ip_list: List[str]) -> None:
    """
    บล็อก IP addresses รายการจากไฟล์ threat intelligence
    
    Args:
        ip_list: รายการ IP ที่ต้องการบล็อก
    """
    logger.info(f"กำลังบล็อก {len(ip_list)} IP addresses")
    
    for ip in ip_list:
        ip = ip.strip()
        if not ip or ip.startswith('#'):
            continue  # ข้าม comment และบรรทัดว่าง
            
        code, _, err = run_ufw_command(['deny', 'from', ip])
        if code == 0:
            logger.info(f"  ✓ บล็อก {ip}")
        else:
            logger.warning(f"  ⚠ ไม่สามารถบล็อก {ip}: {err}")


# ตัวอย่างการใช้งาน
if __name__ == '__main__':
    
    # กำหนด IP ของ admin
    ADMIN_IPS = [
        '203.0.113.10',    # Admin หลัก
        '10.10.10.0/24',   # VPN Admin subnet
        '198.51.100.5',    # Backup admin
    ]
    
    # ตั้งค่า Web Server firewall
    success = setup_web_server_firewall(
        admin_ips=ADMIN_IPS,
        enable_https=True,
        enable_mail=False
    )
    
    if not success:
        logger.error("การตั้งค่า UFW ล้มเหลว")
        sys.exit(1)
    
    # บล็อก IPs จาก threat list
    THREAT_IPS = [
        '192.0.2.100',
        '192.0.2.200',
        '10.20.30.0/24',
    ]
    block_ip_list(THREAT_IPS)

1.7.15 สรุปคำสั่ง UFW ที่ใช้บ่อย

หมวดหมู่ คำสั่ง คำอธิบาย
สถานะ ufw status verbose ดูสถานะและ rules ทั้งหมด
สถานะ ufw status numbered ดู rules พร้อมเลขลำดับ
Default ufw default deny incoming ปฏิเสธขาเข้าทั้งหมด
Default ufw default allow outgoing อนุญาตขาออกทั้งหมด
Allow ufw allow 80/tcp เปิด port 80 TCP
Allow ufw allow from X to any port 22 เปิด SSH จาก IP X
Deny ufw deny from 1.2.3.4 บล็อก IP
Limit ufw limit ssh Rate limit SSH
Delete ufw delete [N] ลบ rule ที่เลข N
Insert ufw insert 1 allow ... แทรก rule ที่ตำแหน่ง 1
Log ufw logging medium เปิด logging ระดับ medium
Reset ufw --force reset รีเซ็ต rules ทั้งหมด
App ufw app list ดูรายการ App Profiles
Show ufw show raw ดู raw iptables rules

1.8 iptables — Advanced Firewall Configuration

1.8.1 โครงสร้าง iptables

iptables ทำงานผ่าน Tables และ Chains ใน Linux Kernel Netfilter:

%%{init: {'theme': 'base', 'themeVariables': {
  'primaryColor': '#282828',
  'primaryTextColor': '#ebdbb2',
  'primaryBorderColor': '#504945',
  'lineColor': '#a89984',
  'background': '#282828',
  'mainBkg': '#282828',
  'nodeBorder': '#504945',
  'clusterBkg': '#32302f',
  'titleColor': '#fabd2f',
  'edgeLabelBackground': '#3c3836',
  'fontFamily': 'monospace'
}}}%%

flowchart LR
  PKT_IN["📦 Packet ขาเข้า"]
  PKT_OUT["📤 Packet ขาออก"]
  LOCAL["🖥️ Local Process"]

  subgraph NETFILTER["Netfilter Framework"]
    subgraph RAW["Table: raw"]
      PREROUTE_R["PREROUTING"]
      OUTPUT_R["OUTPUT"]
    end
    subgraph MANGLE["Table: mangle"]
      PREROUTE_M["PREROUTING"]
      FORWARD_M["FORWARD"]
      OUTPUT_M["OUTPUT"]
      INPUT_M["INPUT"]
      POSTROUTE_M["POSTROUTING"]
    end
    subgraph NAT_T["Table: nat"]
      PREROUTE_N["PREROUTING - (DNAT)"]
      OUTPUT_N["OUTPUT"]
      POSTROUTE_N["POSTROUTING - (SNAT/MASQ)"]
    end
    subgraph FILTER["Table: filter ⭐"]
      INPUT_F["INPUT"]
      FORWARD_F["FORWARD"]
      OUTPUT_F["OUTPUT"]
    end
  end

  PKT_IN --> PREROUTE_R --> PREROUTE_M --> PREROUTE_N
  PREROUTE_N -->|"Local"| INPUT_M --> INPUT_F --> LOCAL
  PREROUTE_N -->|"Forward"| FORWARD_M --> FORWARD_F --> POSTROUTE_M --> POSTROUTE_N --> PKT_OUT
  LOCAL --> OUTPUT_R --> OUTPUT_M --> OUTPUT_N --> OUTPUT_F --> POSTROUTE_M

  style FILTER fill:#3c3836,stroke:#fabd2f,color:#ebdbb2
  style NAT_T fill:#3c3836,stroke:#83a598,color:#ebdbb2
  style MANGLE fill:#3c3836,stroke:#504945,color:#a89984
  style RAW fill:#3c3836,stroke:#504945,color:#a89984

1.8.2 คำสั่ง iptables พื้นฐาน

# ดู rules ทั้งหมด
sudo iptables -L -n -v --line-numbers

# ดูเฉพาะ table ที่ต้องการ
sudo iptables -t filter -L -n -v
sudo iptables -t nat -L -n -v
sudo iptables -t mangle -L -n -v

# เพิ่ม rule อนุญาต
sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT

# เพิ่ม rule ด้วย Stateful inspection
sudo iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

# บล็อก IP
sudo iptables -A INPUT -s 192.168.1.100 -j DROP

# ตั้ง Default Policy
sudo iptables -P INPUT DROP
sudo iptables -P FORWARD DROP
sudo iptables -P OUTPUT ACCEPT

# บันทึก rules
sudo iptables-save > /etc/iptables/rules.v4
sudo ip6tables-save > /etc/iptables/rules.v6

# โหลด rules จากไฟล์
sudo iptables-restore < /etc/iptables/rules.v4

1.9 nftables — Modern Firewall Framework

1.9.1 ภาพรวม nftables

nftables คือ framework สำหรับ packet filtering ที่มาแทน iptables ใน Linux kernel สมัยใหม่ (Kernel 3.13+) มีข้อดีดังนี้:

# ดู ruleset ทั้งหมด
sudo nft list ruleset

# สร้าง table และ chain
sudo nft add table inet filter
sudo nft add chain inet filter input { type filter hook input priority 0 \; policy drop \; }
sudo nft add chain inet filter forward { type filter hook forward priority 0 \; policy drop \; }
sudo nft add chain inet filter output { type filter hook output priority 0 \; policy accept \; }

# เพิ่ม rules
sudo nft add rule inet filter input ct state established,related accept
sudo nft add rule inet filter input tcp dport { 22, 80, 443 } accept
sudo nft add rule inet filter input ip saddr 10.0.0.0/8 tcp dport 22 accept

# บันทึก nftables config
sudo nft list ruleset > /etc/nftables.conf
sudo systemctl enable nftables

1.10 Lab — สร้าง DMZ และ Security Zones

1.10.1 สถาปัตยกรรม Lab Environment

%%{init: {'theme': 'base', 'themeVariables': {
  'primaryColor': '#282828',
  'primaryTextColor': '#ebdbb2',
  'primaryBorderColor': '#504945',
  'lineColor': '#a89984',
  'background': '#282828',
  'mainBkg': '#282828',
  'nodeBorder': '#504945',
  'clusterBkg': '#32302f',
  'titleColor': '#fabd2f',
  'edgeLabelBackground': '#3c3836',
  'fontFamily': 'monospace'
}}}%%

flowchart TB
  INET["🌐 Simulated Internet - 172.16.0.0/24"]

  subgraph GW["🔥 Linux Gateway / Firewall - (Ubuntu 22.04 — 3 NICs)"]
    ETH0["eth0: 172.16.0.1 - (WAN)"]
    ETH1["eth1: 192.168.1.1 - (DMZ)"]
    ETH2["eth2: 10.0.0.1 - (LAN)"]
  end

  subgraph DMZ_LAB["🟡 DMZ Network - 192.168.1.0/24"]
    WEB_LAB["🖥️ Web Server - 192.168.1.10 - nginx"]
    FTP_LAB["📁 FTP Server - 192.168.1.20 - vsftpd"]
  end

  subgraph LAN_LAB["🟢 Internal LAN - 10.0.0.0/24"]
    PC_LAB["💻 Client PC - 10.0.0.100"]
    DB_LAB["🗄️ DB Server - 10.0.0.200 - MySQL"]
  end

  INET --> ETH0
  ETH1 --- DMZ_LAB
  ETH2 --- LAN_LAB

  style DMZ_LAB fill:#3c3836,stroke:#fabd2f,color:#ebdbb2
  style LAN_LAB fill:#3c3836,stroke:#b8bb26,color:#ebdbb2
  style GW fill:#1d2021,stroke:#fb4934,color:#fb4934

1.10.2 ขั้นตอน Lab Setup

# ===== ขั้นตอนที่ 1: ตั้งค่า Linux Gateway =====

# เปิด IP Forwarding
sudo sysctl -w net.ipv4.ip_forward=1
echo "net.ipv4.ip_forward=1" | sudo tee -a /etc/sysctl.conf

# กำหนดค่า network interfaces
sudo ip addr add 172.16.0.1/24 dev eth0
sudo ip addr add 192.168.1.1/24 dev eth1
sudo ip addr add 10.0.0.1/24 dev eth2

# ===== ขั้นตอนที่ 2: ตั้งค่า UFW สำหรับ DMZ =====

sudo ufw --force reset
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw default deny forward    # ปิด forwarding โดย default

# เปิด HTTP จาก Internet ไปยัง Web Server ใน DMZ
sudo ufw route allow in on eth0 out on eth1 \
    proto tcp to 192.168.1.10 port 80

# เปิด HTTPS
sudo ufw route allow in on eth0 out on eth1 \
    proto tcp to 192.168.1.10 port 443

# เปิดให้ DMZ ส่ง DB queries ไปยัง Internal LAN เฉพาะ MySQL port
sudo ufw route allow in on eth1 out on eth2 \
    proto tcp from 192.168.1.10 to 10.0.0.200 port 3306

# เปิดให้ Internal LAN เข้าถึง Internet ได้ทั้งหมด
sudo ufw route allow in on eth2 out on eth0

# ===== ขั้นตอนที่ 3: ตั้งค่า NAT =====
# เพิ่มใน /etc/ufw/before.rules
cat << 'EOF' | sudo tee -a /etc/ufw/before.rules

*nat
:POSTROUTING ACCEPT [0:0]
-A POSTROUTING -s 10.0.0.0/24 -o eth0 -j MASQUERADE
-A POSTROUTING -s 192.168.1.0/24 -o eth0 -j MASQUERADE
COMMIT
EOF

sudo ufw enable
sudo ufw status verbose

1.11 สรุปโดยรวม (Summary)

Network Security Infrastructure เป็นรากฐานสำคัญของระบบความปลอดภัยทางไซเบอร์ ที่ผสมผสานหลักการหลายด้านเข้าด้วยกัน:

Firewalls วิวัฒนาการจาก Packet Filtering พื้นฐานมาสู่ Next-Generation Firewall ที่มีความสามารถ Deep Packet Inspection และ Application Awareness ซึ่งแต่ละรุ่นมีข้อดี-ข้อเสียต่างกันตาม Use Case ที่นำไปใช้

Security Zones โดยเฉพาะ DMZ ช่วยสร้างชั้นการป้องกัน (Layered Defense) ที่จำกัดผลกระทบเมื่อ Public-facing Services ถูกโจมตี โดยไม่ให้ผู้โจมตีเข้าถึง Internal Network ได้โดยตรง

Network Segmentation ด้วย VLANs ช่วยลด Attack Surface และป้องกัน Lateral Movement ของผู้โจมตีภายในองค์กร และยังช่วยให้ปฏิบัติตามกฎระเบียบต่าง ๆ ได้ง่ายขึ้น

UFW เป็นเครื่องมือที่ทรงพลังและใช้งานง่ายสำหรับ Linux Firewall Management ครอบคลุมทั้ง Web Server, Mail Server, Database, VPN, Docker และการป้องกัน Brute Force Attack ด้วย Rate Limiting

หัวใจสำคัญของ Firewall Policy คือ Default Deny — ปฏิเสธทุกอย่างก่อน แล้วค่อยเปิดเฉพาะที่จำเป็นตามหลัก Least Privilege


เอกสารอ้างอิง (References)

  1. NIST SP 800-41 Rev 1Guidelines on Firewalls and Firewall Policy, National Institute of Standards and Technology, 2009
  2. Ubuntu DocumentationUFW - Uncomplicated Firewall, Canonical Ltd., https://help.ubuntu.com/community/UFW
  3. The Linux Documentation ProjectLinux iptables HOWTO, https://www.netfilter.org/documentation/
  4. nftables Wikinftables: replace iptables, https://wiki.nftables.org/
  5. IEEE 802.1Q-2018IEEE Standard for Local and Metropolitan Area Networks — Bridges and Bridged Networks, IEEE, 2018
  6. RFC 4271A Border Gateway Protocol 4 (BGP-4), IETF, 2006
  7. Cheswick, W.R., Bellovin, S.M., Rubin, A.D.Firewalls and Internet Security: Repelling the Wily Hacker, Addison-Wesley, 2003
  8. Stallings, W.Network Security Essentials: Applications and Standards, 6th Edition, Pearson, 2017
  9. Northcutt, S., Novak, J.Network Intrusion Detection, 3rd Edition, New Riders, 2002
  10. OWASPWeb Application Firewall (WAF), https://owasp.org/www-community/Web_Application_Firewall