ModSecurity WAF
ModSecurity เป็น Web Application Firewall แบบ Open-source ที่ได้รับความนิยมสูงสุด ทำงานเป็น Module บน Apache, Nginx หรือ IIS ตรวจจับและป้องกันการโจมตีเว็บไซต์แบบ Real-time โดยใช้ Rules ในการวิเคราะห์ HTTP Requests
สำหรับองค์กรที่ต้องการลดค่าใช้จ่ายด้าน Security ModSecurity เป็นทางเลือกที่ดีเพราะไม่มีค่า License ใช้ OWASP CRS ที่เป็น Open-source เช่นกัน ลดค่าใช้จ่ายจาก Commercial WAF ที่มีราคาสูง
Installation และ Configuration
# === ModSecurity Installation สำหรับ Nginx ===
# 1. ติดตั้ง Dependencies (Ubuntu/Debian)
sudo apt update
sudo apt install -y \
libmodsecurity3 \
libmodsecurity-dev \
nginx-module-modsecurity
# หรือ Build จาก Source
git clone https://github.com/SpiderLabs/ModSecurity
cd ModSecurity
git submodule init && git submodule update
./build.sh && ./configure && make && sudo make install
# 2. ติดตั้ง OWASP CRS
cd /etc/nginx
sudo git clone https://github.com/coreruleset/coreruleset /etc/nginx/owasp-crs
sudo cp /etc/nginx/owasp-crs/crs-setup.conf.example /etc/nginx/owasp-crs/crs-setup.conf
# 3. ModSecurity Configuration
# /etc/nginx/modsecurity/modsecurity.conf
# === Main Configuration ===
# SecRuleEngine On
# SecRequestBodyAccess On
# SecResponseBodyAccess Off
# SecRequestBodyLimit 13107200
# SecRequestBodyNoFilesLimit 131072
# SecRequestBodyLimitAction Reject
#
# # Temp Files
# SecTmpDir /tmp/modsecurity/tmp
# SecDataDir /tmp/modsecurity/data
#
# # Audit Log
# SecAuditEngine RelevantOnly
# SecAuditLogRelevantStatus "^(?:5|4(?!04))"
# SecAuditLogParts ABIJDEFHZ
# SecAuditLogType Serial
# SecAuditLog /var/log/nginx/modsec_audit.log
#
# # Debug Log (ปิดใน Production)
# SecDebugLog /var/log/nginx/modsec_debug.log
# SecDebugLogLevel 0
#
# # Performance
# SecPcreMatchLimit 100000
# SecPcreMatchLimitRecursion 100000
#
# # Include OWASP CRS
# Include /etc/nginx/owasp-crs/crs-setup.conf
# Include /etc/nginx/owasp-crs/rules/*.conf
# 4. Nginx Configuration
# /etc/nginx/nginx.conf
# load_module modules/ngx_http_modsecurity_module.so;
#
# http {
# modsecurity on;
# modsecurity_rules_file /etc/nginx/modsecurity/modsecurity.conf;
#
# server {
# listen 443 ssl http2;
# server_name example.com;
#
# location / {
# modsecurity on;
# proxy_pass http://backend;
# }
#
# # Disable WAF for trusted paths
# location /wp-admin/admin-ajax.php {
# modsecurity off;
# proxy_pass http://backend;
# }
# }
# }
# 5. ทดสอบ
sudo nginx -t
sudo systemctl reload nginx
# ทดสอบ SQL Injection (ควรถูก Block)
curl "https://example.com/?id=1' OR '1'='1"
# ทดสอบ XSS (ควรถูก Block)
curl "https://example.com/?q="
echo "ModSecurity installed and configured"
Cost Analysis Script
# waf_cost_analysis.py — เปรียบเทียบค่าใช้จ่าย WAF Solutions
from dataclasses import dataclass
from typing import List, Dict
@dataclass
class WAFSolution:
name: str
type: str # open-source, cloud, appliance
license_yearly: float
infra_monthly: float # Server/Cloud cost
management_hours_monthly: float
hourly_rate: float # Admin hourly rate
features: List[str]
class WAFCostAnalyzer:
"""เปรียบเทียบค่าใช้จ่าย WAF Solutions"""
def __init__(self):
self.solutions: List[WAFSolution] = []
def add_solution(self, solution: WAFSolution):
self.solutions.append(solution)
def calculate_tco(self, solution: WAFSolution, years=3):
"""คำนวณ Total Cost of Ownership"""
license_total = solution.license_yearly * years
infra_total = solution.infra_monthly * 12 * years
management_total = (solution.management_hours_monthly *
solution.hourly_rate * 12 * years)
total = license_total + infra_total + management_total
return {
"license": license_total,
"infrastructure": infra_total,
"management": management_total,
"total": total,
"monthly_avg": total / (years * 12),
}
def compare(self, years=3):
"""เปรียบเทียบทุก Solutions"""
print(f"\n{'='*65}")
print(f"WAF Cost Comparison ({years}-Year TCO)")
print(f"{'='*65}")
results = []
for sol in self.solutions:
tco = self.calculate_tco(sol, years)
results.append((sol, tco))
results.sort(key=lambda x: x[1]["total"])
print(f"\n{'Solution':<25} {'License':>12} {'Infra':>12} "
f"{'Mgmt':>12} {'Total':>12}")
print("-" * 75)
for sol, tco in results:
print(f"{sol.name:<25} "
f" "
f" "
f" "
f"")
# Savings
if len(results) >= 2:
cheapest = results[0]
expensive = results[-1]
savings = expensive[1]["total"] - cheapest[1]["total"]
pct = savings / expensive[1]["total"] * 100
print(f"\nSavings: ({pct:.0f}%) "
f"using {cheapest[0].name} vs {expensive[0].name}")
return results
# === เปรียบเทียบ ===
analyzer = WAFCostAnalyzer()
analyzer.add_solution(WAFSolution(
name="ModSecurity + OWASP CRS",
type="open-source",
license_yearly=0,
infra_monthly=50, # Additional server resources
management_hours_monthly=8,
hourly_rate=50,
features=["SQL Injection", "XSS", "OWASP Top 10", "Custom Rules"],
))
analyzer.add_solution(WAFSolution(
name="Cloudflare WAF Pro",
type="cloud",
license_yearly=2400, # $200/month
infra_monthly=0,
management_hours_monthly=2,
hourly_rate=50,
features=["SQL Injection", "XSS", "DDoS", "Bot Management", "CDN"],
))
analyzer.add_solution(WAFSolution(
name="AWS WAF",
type="cloud",
license_yearly=720, # Base + rules
infra_monthly=100, # Request-based pricing
management_hours_monthly=4,
hourly_rate=50,
features=["SQL Injection", "XSS", "Bot Control", "Rate Limiting"],
))
analyzer.add_solution(WAFSolution(
name="Commercial WAF Appliance",
type="appliance",
license_yearly=50000,
infra_monthly=500, # Hardware/Hosting
management_hours_monthly=16,
hourly_rate=50,
features=["Full Protection", "Support", "Compliance", "API Security"],
))
analyzer.compare(years=3)
Performance Tuning
# === ModSecurity Performance Tuning ===
# 1. Paranoia Level — เลือกให้เหมาะสม
# /etc/nginx/owasp-crs/crs-setup.conf
# SecAction "id:900000, phase:1, nolog, pass, \
# t:none, setvar:tx.paranoia_level=1"
#
# Level 1: Default, False Positives น้อย (แนะนำ)
# Level 2: เพิ่มกฎ, False Positives ปานกลาง
# Level 3: เข้มงวด, False Positives มาก
# Level 4: เข้มงวดสุด, Production ไม่แนะนำ
# 2. Exclusion Rules — ลด False Positives
# /etc/nginx/modsecurity/exclusions.conf
# # WordPress Admin AJAX
# SecRule REQUEST_URI "@beginsWith /wp-admin/admin-ajax.php" \
# "id:1001, phase:1, pass, nolog, \
# ctl:ruleRemoveById=941100-941999"
#
# # API Endpoints ที่รับ JSON
# SecRule REQUEST_URI "@beginsWith /api/" \
# "id:1002, phase:1, pass, nolog, \
# ctl:ruleRemoveById=920420"
# 3. Performance Settings
# SecRequestBodyAccess On # ตรวจ Request Body
# SecResponseBodyAccess Off # ไม่ตรวจ Response (เร็วขึ้น)
# SecRequestBodyLimit 1048576 # จำกัด Body 1MB
# SecPcreMatchLimit 50000 # ลดจาก Default
# SecPcreMatchLimitRecursion 50000
# 4. Audit Log — เฉพาะที่จำเป็น
# SecAuditEngine RelevantOnly # ไม่ Log ทุก Request
# SecAuditLogParts ABFHZ # Log เฉพาะส่วนที่จำเป็น
# SecAuditLogType Concurrent # ใช้ Concurrent สำหรับ Performance
# 5. ตรวจสอบ Performance
# ab -n 1000 -c 10 https://example.com/
# siege -c 50 -t 60S https://example.com/
# 6. Monitor False Positives
# grep "ModSecurity" /var/log/nginx/error.log | \
# awk '{print $NF}' | sort | uniq -c | sort -rn | head -20
# 7. Log Analysis
cat /var/log/nginx/modsec_audit.log | \
grep -oP 'id "\K[0-9]+' | sort | uniq -c | sort -rn | head -10
echo "Performance tuning tips applied"
Best Practices
- เริ่มจาก Detection Mode: ตั้ง SecRuleEngine DetectionOnly ก่อน ดู Logs แล้วค่อยเปลี่ยนเป็น On
- Paranoia Level 1: เริ่มจาก Level 1 False Positives น้อย ค่อยเพิ่มถ้าต้องการ
- Exclusion Rules: สร้าง Exclusion สำหรับ False Positives แทนการปิด Rules ทั้งหมด
- ปิด Response Body Scan: ไม่จำเป็นสำหรับเว็บส่วนใหญ่ เพิ่ม Performance
- Log Rotation: ตั้ง Log Rotation สำหรับ Audit Log ป้องกัน Disk Full
- Regular Update: อัพเดท OWASP CRS อย่างน้อยเดือนละครั้ง
แนวทางป้องกันภัยไซเบอร์สำหรับองค์กรไทย
ภัยคุกคามทางไซเบอร์ในปี 2026 มีความซับซ้อนมากขึ้น Ransomware ยังคงเป็นภัยอันดับหนึ่ง โดยผู้โจมตีใช้ AI ช่วยสร้าง Phishing Email ที่แนบเนียนขึ้น องค์กรควรมี Multi-Layered Security ตั้งแต่ Perimeter Defense ด้วย Next-Gen Firewall Endpoint Protection ด้วย EDR Solution และ Network Detection and Response
การฝึกอบรมพนักงานเป็นสิ่งสำคัญที่สุด เพราะ Human Error เป็นสาเหตุหลักของการรั่วไหลข้อมูล ควรจัด Security Awareness Training อย่างน้อยไตรมาสละครั้ง ทำ Phishing Simulation ทดสอบพนักงาน และมี Incident Response Plan ที่ชัดเจน ฝึกซ้อมเป็นประจำ
สำหรับกฎหมาย PDPA ของไทย องค์กรต้องมี Data Protection Officer แจ้งวัตถุประสงค์การเก็บข้อมูลอย่างชัดเจน ขอ Consent ก่อนใช้ข้อมูลส่วนบุคคล มีมาตรการรักษาความปลอดภัยที่เหมาะสม และแจ้งเหตุ Data Breach ภายใน 72 ชั่วโมง
ModSecurity คืออะไร
Open-source WAF ทำงานบน Apache Nginx IIS ตรวจจับป้องกัน SQL Injection XSS CSRF File Inclusion ใช้ OWASP CRS เป็นชุดกฎพื้นฐาน ฟรีไม่มีค่า License
ModSecurity ช่วยลดค่าใช้จ่ายอย่างไร
Open-source ไม่มีค่า License เทียบ Commercial WAF หลักแสนถึงล้านต่อปี ลด Traffic Bot Attack Server ไม่ต้องประมวลผล Malicious Requests ลด Bandwidth Compute Cost ป้องกัน Data Breach
OWASP CRS คืออะไร
ชุดกฎสำหรับ ModSecurity จาก OWASP ครอบคลุม OWASP Top 10 SQL Injection XSS RCE LFI/RFI มี Paranoia Level 1-4 Level 1 เหมาะเว็บทั่วไป Level 4 เข้มงวดสุด
ModSecurity กับ Cloudflare WAF ต่างกันอย่างไร
ModSecurity Open-source ติดตั้งบน Server ฟรี ต้อง Manage เอง Cloudflare เป็น Cloud Service ไม่ต้อง Manage มีค่าใช้จ่ายรายเดือน ModSecurity เหมาะทีมมี Technical Skills Cloudflare เหมาะต้องการความง่าย
สรุป
ModSecurity เป็น Open-source WAF ที่ช่วยปกป้องเว็บไซต์และลดค่าใช้จ่ายเมื่อเทียบกับ Commercial WAF ใช้ OWASP CRS เป็นชุดกฎพื้นฐาน เริ่มจาก Detection Mode แล้วค่อยเปลี่ยนเป็น On ใช้ Paranoia Level 1 สร้าง Exclusion Rules ลด False Positives ปิด Response Body Scan เพิ่ม Performance อัพเดท CRS สม่ำเสมอ
