🔐 Security✍️ Khoa📅 19/04/2026☕ 8 phút đọc

Threat Modeling — Nghĩ Như Hacker, Phòng Như Kiến Trúc Sư

"Attackers think in graphs, defenders think in lists." Bạn có danh sách checklist dài 3 trang, nhưng attacker chỉ cần TÌM 1 đường đi. Threat modeling giúp bạn nghĩ bằng graph.

OWASP Top 10 dạy bạn cái gì nguy hiểm. Threat modeling dạy bạn ở đâu trong hệ thống của bạn nó nguy hiểm, và tại sao attacker muốn tấn công chỗ đó.


1. Threat Modeling là gì?

Threat modeling = Structured approach to identify:
  1. WHAT are we building? (architecture + data flows)
  2. WHAT can go wrong? (threats)
  3. WHAT are we doing about it? (mitigations)
  4. Did we do a good job? (validation)

Khi nào cần:
  → Thiết kế hệ thống mới (design phase)
  → Thêm feature mới liên quan đến auth, payment, PII
  → Thay đổi architecture lớn (monolith → microservices)
  → Integrate third-party service mới
  → Compliance requirements (SOC2, PCI-DSS, GDPR)

Ai tham gia:
  → Engineers (biết cách hệ thống hoạt động)
  → Security team (biết attack vectors)
  → Product (biết data sensitivity)
  → 60-90 phút meeting, whiteboard

2. STRIDE Framework — Phân loại Threats

2.1 STRIDE Categories

S — Spoofing (Giả mạo danh tính)
  "Ai đó giả vờ là người khác"
  → Fake login, stolen tokens, IP spoofing
  Mitigation: Strong auth, MFA, mTLS

T — Tampering (Sửa đổi dữ liệu)
  "Ai đó thay đổi data mà không được phép"
  → Man-in-the-middle, SQL injection, modify request payload
  Mitigation: TLS, input validation, checksums, digital signatures

R — Repudiation (Chối bỏ hành vi)
  "Ai đó phủ nhận đã làm gì đó"
  → "Tôi không bao giờ đặt đơn hàng đó"
  Mitigation: Audit logs, digital signatures, timestamps

I — Information Disclosure (Lộ thông tin)
  "Data bị lộ cho người không được phép"
  → Error messages leak stack trace, log chứa passwords
  Mitigation: Encryption, access control, sanitize errors/logs

D — Denial of Service (Từ chối dịch vụ)
  "Làm hệ thống không thể phục vụ"
  → DDoS, resource exhaustion, algorithmic complexity attack
  Mitigation: Rate limiting, WAF, autoscaling, input limits

E — Elevation of Privilege (Leo thang quyền)
  "Ai đó có quyền nhiều hơn cho phép"
  → IDOR, JWT manipulation, missing auth checks
  Mitigation: RBAC/ABAC, principle of least privilege

2.2 STRIDE Applied

Scenario: E-commerce Order API

Data Flow:
  User → [API Gateway] → [Order Service] → [DB]
                       → [Payment Service] → [Stripe]
                       → [Notification Service] → [Email]

Threat Analysis:
┌─────────────┬──────────────────────────────────┬────────────────────┐
│ Component   │ Threat (STRIDE)                  │ Mitigation         │
├─────────────┼──────────────────────────────────┼────────────────────┤
│ API Gateway │ S: Stolen JWT → impersonate user │ JWT rotation, MFA  │
│             │ D: DDoS flood                    │ Rate limit, WAF    │
├─────────────┼──────────────────────────────────┼────────────────────┤
│ Order Svc   │ T: Modify order amount           │ Server-side price  │
│             │ E: IDOR (access other's orders)  │ Ownership check    │
│             │ R: Deny placing order             │ Audit log          │
├─────────────┼──────────────────────────────────┼────────────────────┤
│ Payment Svc │ S: Replay payment request        │ Idempotency key    │
│             │ I: Log credit card number        │ PCI compliance     │
├─────────────┼──────────────────────────────────┼────────────────────┤
│ DB          │ I: Unencrypted PII               │ Encrypt at rest    │
│             │ T: SQL injection                  │ Prepared statements│
├─────────────┼──────────────────────────────────┼────────────────────┤
│ Email Svc   │ S: Send email as someone else    │ Verify sender      │
│             │ I: Leak order details in email    │ Minimal PII        │
└─────────────┴──────────────────────────────────┴────────────────────┘

3. Data Flow Diagrams (DFD) — Vẽ trước khi phân tích

3.1 DFD Elements

  ┌─────────┐
  │ External│  ← Entities (users, external systems)
  │ Entity  │
  └────┬────┘
       │
       ▼ Data Flow (arrows with labels)
  ┌─────────┐
  │ Process │  ← Processes (services, functions)
  └────┬────┘
       │
       ▼
  ═══════════
  ║ Data    ║  ← Data Stores (databases, caches, files)
  ║ Store   ║
  ═══════════
       │
  - - -│- - -   ← Trust Boundary (network boundary, auth boundary)
       │          MỌI data flow cross boundary = THREAT!

3.2 DFD Ví dụ: Authentication Flow

  ┌──────┐                    ┌─────────────┐
  │ User │─── credentials ──→ │   Auth      │
  └──────┘                    │   Service   │
     ▲                        └──────┬──────┘
     │                               │
     │ JWT token                     │ verify password
     │                               ▼
     │                        ═══════════════
     │                        ║  User DB    ║
     │                        ║  (hashed)   ║
     │                        ═══════════════
     │                               │
     │          ┌────────────────────┘
     │          ▼
     │   ┌─────────────┐
     └── │  Token       │
         │  Service     │── store session ──→ ══════════
         └─────────────┘                      ║ Redis  ║
                                              ══════════

Trust boundaries:
  --- Internet / API Gateway ---  (1)
  --- Internal network ---         (2)
  --- Database network ---         (3)

Threats per boundary:
  (1): Spoofing, credential stuffing, DDoS
  (2): Lateral movement, service impersonation
  (3): SQL injection, data exfiltration

4. Attack Trees — Visualize Attack Scenarios

Goal: Steal user's payment info

├── 1. Attack the application
│   ├── 1.1 SQL Injection
│   │   ├── 1.1.1 Find unparameterized query [LOW effort]
│   │   └── 1.1.2 Extract credit card table
│   ├── 1.2 XSS to steal session
│   │   ├── 1.2.1 Find reflected XSS
│   │   └── 1.2.2 Inject script to exfiltrate cookies
│   └── 1.3 IDOR to view other users' data
│       └── 1.3.1 Enumerate user IDs in API [LOW effort]
│
├── 2. Attack the infrastructure
│   ├── 2.1 Compromise server
│   │   ├── 2.1.1 Exploit unpatched CVE
│   │   └── 2.1.2 SSH with leaked credentials
│   └── 2.2 Intercept network traffic
│       └── 2.2.1 MITM (nếu không có TLS)
│
└── 3. Social engineering
    ├── 3.1 Phishing admin credentials
    └── 3.2 Insider threat

Priority: Low effort + high impact paths TRƯỚC
  → 1.3.1 (IDOR) và 1.1.1 (SQLi) là top priority

5. Supply Chain Security

5.1 Rủi ro thực tế

Incidents nổi tiếng:
  → SolarWinds (2020): Malware trong build pipeline
  → Log4Shell (2021): Critical vuln trong ubiquitous library
  → event-stream (2018): Maintainer bán npm package cho attacker
  → colors.js (2022): Maintainer tự sabotage package

Bạn pull 200 dependencies → bạn trust 200 maintainers
+ tất cả transitive dependencies.

5.2 Mitigations

1. SBOM (Software Bill of Materials)
   → Danh sách tất cả dependencies + versions
   → Generate: syft, trivy, cyclonedx-gomod
   → Dùng để: track vulnerabilities, compliance

2. Dependency Scanning
   → Go: govulncheck (official), Nancy
   → Multi-language: Snyk, Dependabot, Trivy
   → Chạy trong CI pipeline

3. Lock files
   → Go: go.sum (checksum verification)
   → npm: package-lock.json
   → COMMIT lock files vào git

4. Minimal Dependencies
   → Trước khi thêm dependency: "Có cần không?"
   → Check: maintenance status, download count, security history
   → Left-pad lesson: đôi khi tự viết 10 dòng tốt hơn import

5. Container Image Scanning
   → Trivy, Grype, Clair
   → Scan trong CI, block deploy nếu critical CVE
   → Dùng distroless/minimal base images

6. Sigstore / cosign
   → Sign container images
   → Verify image provenance
   → "Image này thật sự được build bởi CI của chúng ta?"

6. Compliance Frameworks — Technical Implications

SOC 2 (Service Organization Control):
  → Audit logs cho mọi data access
  → Access control reviews (quarterly)
  → Encryption at rest + in transit
  → Incident response plan documented
  → Technical: centralized logging, RBAC, TLS everywhere

PCI-DSS (Payment Card Industry):
  → KHÔNG lưu full card number (tokenize via Stripe/Adyen)
  → Network segmentation cho payment systems
  → Quarterly vulnerability scans
  → Penetration testing annually
  → Technical: separate VPC cho payment, WAF, IDS

GDPR (General Data Protection Regulation):
  → Right to deletion ("forget me")
  → Data portability (export user data)
  → Consent management
  → Data Processing Agreements với vendors
  → Technical: soft delete + purge job, export API,
    data residency (EU data stays in EU)

ISO 27001:
  → Information Security Management System (ISMS)
  → Risk assessment process
  → Asset inventory
  → Technical: documented procedures, annual audits

7. Security Incident Response

Phase 1: DETECTION
  → SIEM alerts (Splunk, ELK)
  → WAF alerts (unusual patterns)
  → User reports
  → Vulnerability disclosure program

Phase 2: CONTAINMENT
  → Short-term: Block IP, disable compromised account
  → Long-term: Patch vulnerability, rotate credentials
  → Preserve evidence (logs, memory dumps)
  → DO NOT reboot servers (destroys forensic evidence)

Phase 3: ERADICATION
  → Remove malware/backdoor
  → Patch all affected systems
  → Verify no persistence mechanisms

Phase 4: RECOVERY
  → Restore from clean backups
  → Monitor closely for re-compromise
  → Gradual return to normal operations

Phase 5: LESSONS LEARNED
  → Blameless post-mortem (giống incident management)
  → Update threat model
  → Improve detection capabilities
  → Communication: customers, regulators (nếu data breach)

8. Threat Modeling Checklist

□ Vẽ Data Flow Diagram cho hệ thống
□ Xác định trust boundaries
□ Apply STRIDE cho mỗi component/data flow
□ Tạo attack tree cho high-value assets
□ Prioritize: impact × likelihood
□ Define mitigations cho top threats
□ Review dependencies (SBOM, scanning)
□ Document trong ADR hoặc security design doc
□ Schedule regular review (quarterly hoặc mỗi major change)

Tài liệu tham khảo


💡 Remember: Security không phải feature bạn thêm vào sprint cuối. Nó là lens bạn nhìn qua khi thiết kế MỌI feature. Threat model sớm, threat model thường xuyên. 🔐