Semgrep SAST + Chaos Engineering
Semgrep SAST Chaos Engineering Security Resilience Pipeline CI/CD Vulnerability Detection Chaos Testing WAF Auth Secrets Production
| Phase | Tool | What | When |
|---|---|---|---|
| Code Review | Semgrep | Static Analysis หา Vulnerability | Pre-commit + PR |
| Build | Semgrep + Trivy | SAST + Container Scan | CI Pipeline |
| Staging | Chaos Mesh / Litmus | Inject Failure ทดสอบ Security | หลัง Deploy Staging |
| Production | Chaos Monkey / Gremlin | Continuous Chaos Testing | สม่ำเสมอ (Weekly) |
| Monitor | Prometheus + Grafana | ตรวจ Security Metrics | ตลอดเวลา |
Semgrep Rules & Configuration
# === Semgrep SAST Setup ===
# Install
# pip install semgrep
# semgrep --config auto .
# semgrep --config p/owasp-top-ten .
# semgrep --config p/security-audit .
# Custom Rule (.semgrep.yml)
# rules:
# - id: hardcoded-secret
# patterns:
# - pattern: |
# $KEY = "..."
# - metavariable-regex:
# metavariable: $KEY
# regex: (password|secret|api_key|token)
# message: "Hardcoded secret found in $KEY"
# severity: ERROR
# languages: [python, javascript, typescript]
#
# - id: sql-injection
# patterns:
# - pattern: |
# cursor.execute(f"... {$VAR} ...")
# message: "Possible SQL injection via f-string"
# severity: ERROR
# languages: [python]
#
# - id: command-injection
# patterns:
# - pattern: |
# os.system($CMD)
# - pattern-not: |
# os.system("...")
# message: "Possible command injection"
# severity: ERROR
# languages: [python]
from dataclasses import dataclass
@dataclass
class SemgrepRule:
rule_id: str
severity: str
vulnerability: str
languages: str
fix: str
rules = [
SemgrepRule("hardcoded-secret",
"ERROR",
"Hardcoded Password API Key Token ใน Code",
"All Languages",
"ใช้ Environment Variable หรือ Secret Manager"),
SemgrepRule("sql-injection",
"ERROR",
"SQL Injection ผ่าน f-string String Concat",
"Python Java PHP",
"ใช้ Parameterized Query Prepared Statement"),
SemgrepRule("xss-reflected",
"ERROR",
"Cross-site Scripting จาก User Input",
"JavaScript TypeScript",
"ใช้ Output Encoding DOMPurify"),
SemgrepRule("command-injection",
"ERROR",
"OS Command Injection ผ่าน os.system subprocess",
"Python",
"ใช้ subprocess.run กับ List Arguments ไม่ใช่ shell=True"),
SemgrepRule("insecure-deserialization",
"WARNING",
"Pickle yaml.load ไม่ปลอดภัย",
"Python",
"ใช้ yaml.safe_load json.loads แทน"),
]
print("=== Semgrep Rules ===")
for r in rules:
print(f" [{r.rule_id}] Severity: {r.severity}")
print(f" Vuln: {r.vulnerability}")
print(f" Lang: {r.languages}")
print(f" Fix: {r.fix}")
Chaos Security Testing
# === Chaos Security Experiments ===
# Litmus Chaos Experiment (Kubernetes)
# apiVersion: litmuschaos.io/v1alpha1
# kind: ChaosExperiment
# metadata:
# name: pod-network-loss
# spec:
# definition:
# scope: Namespaced
# permissions: [...]
# args:
# - -name TOTAL_CHAOS_DURATION
# -value '60'
# - -name NETWORK_INTERFACE
# -value 'eth0'
# - -name NETWORK_PACKET_LOSS_PERCENTAGE
# -value '100'
@dataclass
class ChaosExperiment:
experiment: str
target: str
security_test: str
expected_behavior: str
failure_indicates: str
experiments = [
ChaosExperiment("Pod Network Loss",
"API Gateway Pod",
"WAF ยังทำงานเมื่อ Backend ล่ม",
"WAF return 503 ไม่ Bypass ไป Backend",
"WAF Bypass เมื่อ Backend Unreachable"),
ChaosExperiment("Auth Service Kill",
"Authentication Service",
"ระบบ Deny Access เมื่อ Auth ล่ม",
"Return 401/503 ไม่ให้ Access โดยไม่ Auth",
"Allow Access โดยไม่ Auth (Fail-open)"),
ChaosExperiment("Secret Store Unavailable",
"HashiCorp Vault / AWS Secrets Manager",
"Service ใช้ Cached Secrets หรือ Fail Safely",
"ใช้ Cached Secret ทำงานต่อ หรือ 503",
"Expose Default/Empty Secrets"),
ChaosExperiment("Rate Limiter Failure",
"Rate Limiting Service",
"ระบบยัง Limit Rate เมื่อ Service ล่ม",
"Fallback Rate Limit ทำงาน",
"ไม่มี Rate Limit (DDoS Vulnerable)"),
ChaosExperiment("Certificate Expiry Simulation",
"TLS Certificate",
"Auto-renew ทำงาน ไม่ให้ Certificate หมดอายุ",
"Certificate Renewed ก่อนหมด",
"Service ล่มเพราะ Certificate Expired"),
ChaosExperiment("Error Response Leak",
"Application Error Handler",
"Error Response ไม่รั่ว Stack Trace Secrets",
"Generic Error Message ไม่มี Internal Info",
"Stack Trace DB Connection String รั่ว"),
]
print("=== Chaos Security Experiments ===")
for e in experiments:
print(f"\n [{e.experiment}] Target: {e.target}")
print(f" Security Test: {e.security_test}")
print(f" Expected: {e.expected_behavior}")
print(f" Failure: {e.failure_indicates}")
CI/CD Pipeline
# === Security Pipeline ===
# GitHub Actions
# name: Security Pipeline
# on: [pull_request]
# jobs:
# semgrep:
# runs-on: ubuntu-latest
# steps:
# - uses: actions/checkout@v4
# - uses: returntocorp/semgrep-action@v1
# with:
# config: >-
# p/default
# p/owasp-top-ten
# p/security-audit
# generateSarif: true
# - uses: github/codeql-action/upload-sarif@v3
# with:
# sarif_file: semgrep.sarif
#
# chaos-staging:
# needs: [deploy-staging]
# runs-on: ubuntu-latest
# steps:
# - name: Run Chaos Experiment
# run: |
# kubectl apply -f chaos/auth-kill.yaml
# sleep 60
# # Verify security controls
# curl -s https://staging.example.com/api/protected | grep -q "401"
# kubectl delete -f chaos/auth-kill.yaml
@dataclass
class PipelineStage:
stage: str
tool: str
trigger: str
block_on: str
output: str
stages = [
PipelineStage("Pre-commit",
"Semgrep (local)",
"git commit",
"ERROR severity findings",
"Block commit + Show finding"),
PipelineStage("PR Review",
"Semgrep (CI)",
"Pull Request",
"ERROR + WARNING severity",
"PR Comment + SARIF Upload"),
PipelineStage("Build",
"Semgrep + Trivy",
"Merge to main",
"Critical/High CVE",
"Block Build + Alert"),
PipelineStage("Staging Chaos",
"Litmus Chaos",
"Deploy to Staging",
"Security Control Failure",
"Block Production Deploy"),
PipelineStage("Production Monitor",
"Prometheus + Semgrep Cloud",
"Continuous",
"New Critical Finding",
"PagerDuty Alert"),
]
print("=== Pipeline Stages ===")
for s in stages:
print(f" [{s.stage}] Tool: {s.tool}")
print(f" Trigger: {s.trigger}")
print(f" Block: {s.block_on}")
print(f" Output: {s.output}")
เคล็ดลับ
- Shift-left: ใช้ Semgrep ตั้งแต่ Pre-commit หา Bug เร็ว
- OWASP: เริ่มจาก p/owasp-top-ten Rule Set ครอบคลุมสุด
- Fail-closed: ทดสอบ Chaos ว่าระบบ Fail-closed ไม่ Fail-open
- Blast Radius: เริ่ม Chaos จาก Staging ก่อน Production
- Automate: ทำ Security Pipeline อัตโนมัติ ไม่พึ่ง Manual
Semgrep คืออะไร
Open Source SAST Pattern Matching 30+ Languages YAML Rules SQL Injection XSS Secrets 3000+ Rules CI/CD Fast Scan ล้าน Lines วินาที
Chaos Engineering คืออะไร
ทดสอบ Resilience จงใจทำ Failure Kill Process Network Failure Chaos Monkey Litmus Gremlin Hypothesis Blast Radius Production
รวมกันอย่างไร
Semgrep ตรวจ Code Chaos ทดสอบ Security Controls WAF Auth Rate Limiter Secrets Fail-closed Error Handling Pipeline SAST+Chaos
CI/CD Integration ทำอย่างไร
Pre-commit Semgrep PR Review CI SARIF Build Trivy Staging Chaos Litmus Production Monitor PagerDuty Block ERROR WARNING
สรุป
Semgrep SAST Chaos Engineering Security Resilience Pipeline CI/CD OWASP Vulnerability Chaos Testing Fail-closed Monitor Production
