# 🔐 WEB APPLICATION SECURITY CHECKLIST 2026

> **Version:** 2026.1 | **Last Updated:** 2025 | **Format:** Print-Ready A3/A4

---

## 📋 HƯỚNG DẪN SỬ DỤNG

| 🔴 CRITICAL | 🟠 HIGH | 🟡 MEDIUM |
|-------------|---------|-----------|
| Phải làm trước khi deploy | Làm trong Sprint đầu | Lên kế hoạch trong Roadmap |

---

---

# STEP 1 — INPUT VALIDATION & SANITIZATION

> **Mô tả:** Mọi dữ liệu từ user đều là kẻ thù. Validate server-side, sanitize trước khi lưu/hiển thị, không bao giờ tin vào client-side validation.

**🔴 CRITICAL**

---

### ✅ Checklist

- [ ] Validate input **server-side** cho tất cả endpoints (không chỉ client-side)
- [ ] Áp dụng **whitelist validation** thay vì blacklist
- [ ] Giới hạn **độ dài, kiểu dữ liệu, format** cho từng trường
- [ ] Sanitize HTML output — escape `<`, `>`, `"`, `'`, `&`
- [ ] Parameterized queries / Prepared Statements cho **mọi** DB query
- [ ] Chặn **SQL Injection**: không concat string trực tiếp vào query
- [ ] Chặn **XSS**: encode output theo context (HTML/JS/URL/CSS)
- [ ] Chặn **Command Injection**: không dùng `eval()`, `exec()` với user input
- [ ] Validate **file upload**: kiểm tra MIME type thực (magic bytes), không chỉ extension
- [ ] Giới hạn **file size** upload, lưu file ngoài webroot
- [ ] Chặn **Path Traversal**: normalize path, kiểm tra `../` sequences
- [ ] Validate **JSON schema** với strict mode
- [ ] Chặn **XXE** (XML External Entity): disable external entity processing
- [ ] Sanitize **Markdown/Rich Text** trước khi render
- [ ] Kiểm tra **Regular Expression DoS (ReDoS)**: tránh catastrophic backtracking

---

### 🛠️ Tools Gợi Ý

```
• validator.js          — Node.js input validation library
• Joi / Zod / Yup       — Schema validation (TypeScript-friendly)
• DOMPurify             — Client-side HTML sanitization
• OWASP Java Encoder    — Java output encoding
• libinjection          — Detect SQL/XSS injection patterns
• Semgrep               — Static analysis tìm injection vulnerabilities
• sqlmap                — Test SQL injection (penetration testing)
```

---

---

# STEP 2 — HTTPS + HSTS

> **Mô tả:** Toàn bộ traffic phải được mã hóa. HTTP phải redirect 301 sang HTTPS. HSTS đảm bảo browser chỉ kết nối qua HTTPS, ngay cả lần đầu.

**🔴 CRITICAL**

---

### ✅ Checklist

- [ ] **TLS 1.2+ bắt buộc**, disable TLS 1.0 và TLS 1.1 hoàn toàn
- [ ] Ưu tiên **TLS 1.3** — nhanh hơn, bảo mật hơn
- [ ] Sử dụng **certificate từ CA uy tín** (Let's Encrypt, DigiCert, Sectigo)
- [ ] Certificate còn hạn > 30 ngày — **setup auto-renewal**
- [ ] Redirect **HTTP → HTTPS** với status 301 (permanent)
- [ ] Enable **HSTS header**: `Strict-Transport-Security: max-age=31536000; includeSubDomains; preload`
- [ ] Submit domain vào **HSTS Preload List** (hstspreload.org)
- [ ] Disable **weak cipher suites** (RC4, DES, 3DES, NULL)
- [ ] Enable **Forward Secrecy** (ECDHE cipher suites)
- [ ] Kiểm tra **certificate chain** đầy đủ (intermediate certs)
- [ ] Enable **OCSP Stapling** để giảm latency certificate verification
- [ ] Disable **SSL compression** (chặn CRIME attack)
- [ ] Wildcard cert `*.domain.com` — kiểm soát chặt private key
- [ ] Không mix **HTTP content** trong HTTPS page (Mixed Content)
- [ ] **Cookie Secure flag** — chỉ gửi cookie qua HTTPS

---

### 🛠️ Tools Gợi Ý

```
• SSL Labs (ssllabs.com/ssltest)  — Kiểm tra SSL/TLS config, cho điểm A+
• Let's Encrypt + Certbot          — Free SSL cert + auto-renewal
• Mozilla SSL Config Generator     — Generate nginx/apache TLS config chuẩn
• testssl.sh                       — CLI tool kiểm tra TLS từ terminal
• Qualys FreeScan                  — Scan toàn bộ SSL vulnerabilities
• cert-manager (K8s)               — Auto manage certs trong Kubernetes
```

---

---

# STEP 3 — SECURITY HEADERS (CSP & HELMET)

> **Mô tả:** HTTP Security Headers là lớp bảo vệ "miễn phí" — chỉ cần config server là xong. Ngăn chặn XSS, Clickjacking, MIME sniffing, và nhiều tấn công browser-level.

**🔴 CRITICAL**

---

### ✅ Checklist

**Content Security Policy (CSP)**
- [ ] Enable **CSP header** — define rõ trusted sources cho script/style/image
- [ ] Không dùng `unsafe-inline` và `unsafe-eval` trong CSP (nếu buộc phải dùng, có nonce/hash)
- [ ] Dùng **nonce hoặc hash** cho inline scripts thay vì `unsafe-inline`
- [ ] Set **`default-src 'none'`** rồi whitelist từng directive
- [ ] Enable **`report-uri`** hoặc `report-to` để nhận CSP violation reports
- [ ] Test CSP với **CSP Evaluator** trước khi deploy

**Other Security Headers**
- [ ] `X-Frame-Options: DENY` — chặn Clickjacking
- [ ] `X-Content-Type-Options: nosniff` — chặn MIME type sniffing
- [ ] `Referrer-Policy: strict-origin-when-cross-origin` — kiểm soát Referer header
- [ ] `Permissions-Policy` — disable camera/mic/geolocation nếu không cần
- [ ] `X-XSS-Protection: 0` — disable browser XSS filter cũ (deprecated, có thể gây hại)
- [ ] Remove hoặc obfuscate **`X-Powered-By`** header (đừng leak tech stack)
- [ ] Remove **`Server`** header hoặc set giá trị generic
- [ ] `Cross-Origin-Embedder-Policy: require-corp`
- [ ] `Cross-Origin-Opener-Policy: same-origin`
- [ ] `Cross-Origin-Resource-Policy: same-origin`
- [ ] Kiểm tra headers với **SecurityHeaders.com** — đạt điểm A+

---

### 🛠️ Tools Gợi Ý

```
• Helmet.js              — Express.js middleware set security headers tự động
• securityheaders.com    — Scan và chấm điểm security headers
• CSP Evaluator          — Google tool phân tích CSP policy
• report-uri.com         — CSP/COOP violation reporting service
• django-csp             — Django middleware cho CSP
• NextJS headers config  — next.config.js security headers
```

---

### 💡 Config Mẫu (Helmet.js)

```javascript
app.use(helmet({
  contentSecurityPolicy: {
    directives: {
      defaultSrc: ["'none'"],
      scriptSrc: ["'self'", (req, res) => `'nonce-${res.locals.nonce}'`],
      styleSrc:  ["'self'"],
      imgSrc:    ["'self'", "data:", "https:"],
      connectSrc:["'self'"],
      fontSrc:   ["'self'"],
      objectSrc: ["'none'"],
      mediaSrc:  ["'self'"],
      frameSrc:  ["'none'"],
      reportUri: "/csp-violations"
    }
  },
  hsts: { maxAge: 31536000, includeSubDomains: true, preload: true },
  referrerPolicy: { policy: "strict-origin-when-cross-origin" }
}));
```

---

---

# STEP 4 — CORS CONFIGURATION

> **Mô tả:** CORS sai cấu hình là cánh cửa mở cho attacker đọc dữ liệu từ domain khác. Không bao giờ dùng wildcard `*` cho authenticated endpoints.

**🔴 CRITICAL**

---

### ✅ Checklist

- [ ] **Không dùng `Access-Control-Allow-Origin: *`** cho endpoints cần authentication
- [ ] Whitelist **explicit danh sách origins** được phép — không dynamic reflect origin
- [ ] Kiểm tra **origin validation logic** — không dùng `startsWith()` hay `includes()` đơn giản
- [ ] `Access-Control-Allow-Credentials: true` **CHỈ** khi thực sự cần gửi cookies cross-origin
- [ ] Giới hạn **`Access-Control-Allow-Methods`** — chỉ list methods cần thiết
- [ ] Giới hạn **`Access-Control-Allow-Headers`** — không wildcard
- [ ] Set **`Access-Control-Max-Age`** hợp lý (giảm preflight requests)
- [ ] Validate **`Origin` header** server-side trước khi xử lý request
- [ ] Kiểm tra **CORS bypass**: `null` origin, `localhost`, subdomain takeover
- [ ] Không cho phép **`file://` origin** trong production
- [ ] API internal (microservices) — **block tất cả CORS** nếu không cần
- [ ] Document rõ lý do từng origin được whitelist

---

### 🛠️ Tools Gợi Ý

```
• cors (npm)             — Node.js CORS middleware
• corscanner            — Tìm CORS misconfiguration tự động
• Burp Suite            — Manual test CORS vulnerabilities
• OWASP CORS Tester     — Web-based CORS test tool
• fetch/curl            — Manual test với custom Origin header
```

---

### 💡 Config Mẫu (Node.js)

```javascript
const allowedOrigins = [
  'https://app.yourdomain.com',
  'https://admin.yourdomain.com'
];

app.use(cors({
  origin: (origin, callback) => {
    if (!origin || allowedOrigins.includes(origin)) {
      callback(null, true);
    } else {
      callback(new Error(`CORS blocked: ${origin}`));
    }
  },
  credentials: true,
  methods: ['GET', 'POST', 'PUT', 'DELETE'],
  allowedHeaders: ['Content-Type', 'Authorization'],
  maxAge: 86400
}));
```

---

---

# STEP 5 — JWT & TOKEN SECURITY

> **Mô tả:** JWT sai cấu hình là vulnerability phổ biến nhất trong modern web apps. Token phải được sign đúng, verify đúng, và có cơ chế revoke.

**🔴 CRITICAL**

---

### ✅ Checklist

**JWT Signing & Verification**
- [ ] Dùng **RS256 hoặc ES256** (asymmetric) cho production — không dùng HS256 nếu nhiều service
- [ ] **KHÔNG** accept thuật toán `none` — validate `alg` header trước khi verify
- [ ] Secret key cho HS256 phải **≥ 256 bits**, randomly generated
- [ ] Private key cho RS256/ES256 phải được **bảo vệ nghiêm ngặt** (HSM hoặc vault)
- [ ] Verify **`iss` (issuer)**, **`aud` (audience)**, **`exp` (expiry)** trong mọi request

**Token Lifecycle**
- [ ] **Access token TTL ngắn**: 15 phút — 1 giờ
- [ ] **Refresh token TTL dài hơn**: 7-30 ngày, lưu secure (httpOnly cookie)
- [ ] Implement **refresh token rotation** — mỗi lần dùng là invalidate token cũ
- [ ] Implement **token revocation list** / blacklist cho logout
- [ ] Lưu refresh token trong **httpOnly, Secure, SameSite=Strict cookie** — không localStorage
- [ ] **Không lưu sensitive data** trong JWT payload (JWT chỉ được encode, không encrypt)
- [ ] Implement **`jti` (JWT ID)** claim để track và revoke individual tokens

**Session Management**
- [ ] Re-authenticate khi thực hiện **hành động quan trọng** (đổi password, transfer)
- [ ] Invalidate tất cả tokens khi **đổi password hoặc phát hiện breach**
- [ ] Log tất cả **token issuance và revocation events**
- [ ] Implement **concurrent session limits** nếu cần

---

### 🛠️ Tools Gợi Ý

```
• jsonwebtoken (npm)     — Node.js JWT library (mature, well-tested)
• python-jose            — Python JWT với full validation
• jwt.io                 — Debug và decode JWT (KHÔNG dùng cho production secrets)
• JWTEAR                 — JWT attack tool (dùng để test)
• Auth0 / Clerk          — Managed auth service — delegate phức tạp
• Keycloak               — Self-hosted identity provider
• node-jose              — JWK/JWE support đầy đủ
```

---

---

# STEP 6 — SECRET MANAGEMENT

> **Mô tả:** Secret trong source code là breach đang chờ xảy ra. Mọi credential, API key, private key phải được quản lý tập trung, rotate thường xuyên, và audit trail đầy đủ.

**🔴 CRITICAL**

---

### ✅ Checklist

**Never Commit Secrets**
- [ ] Cài **pre-commit hook** scan secrets trước khi commit
- [ ] Add `.env`, `*.pem`, `*.key`, `secrets.*` vào **`.gitignore` global**
- [ ] Scan **toàn bộ git history** để tìm secrets đã leak (ngay bây giờ)
- [ ] Enable **GitHub/GitLab Secret Scanning** — block push nếu phát hiện secret
- [ ] Educate team: **rotate ngay khi nghi ngờ bị expose**, không chờ confirm

**Secret Storage & Access**
- [ ] Dùng **dedicated secret manager** — không hardcode trong code/config
- [ ] Secrets inject vào app qua **environment variables** lúc runtime
- [ ] Implement **least privilege**: service chỉ access secrets nó cần
- [ ] Enable **audit log** cho mọi secret access
- [ ] Rotate secrets **định kỳ** (database passwords: 90 ngày, API keys: 180 ngày)
- [ ] Rotate secrets **ngay lập tức** khi có nhân viên nghỉ việc
- [ ] Dùng **dynamic secrets** (Vault) thay static secrets khi có thể
- [ ] Tách secrets theo **environment** (dev/staging/prod — KHÔNG share)
- [ ] **Encrypt secrets at rest** trong secret manager
- [ ] Implement **break-glass procedure** cho emergency access

**Passwords & Keys**
- [ ] Hash passwords với **bcrypt (cost≥12), Argon2id, hoặc scrypt**
- [ ] **KHÔNG** dùng MD5, SHA1, SHA256 để hash passwords
- [ ] Database credentials phải dùng **connection string với vault reference**
- [ ] Private keys phải có **passphrase** + lưu trong HSM nếu production critical

---

### 🛠️ Tools Gợi Ý

```
• HashiCorp Vault        — Industry standard secret management
• AWS Secrets Manager    — Managed, auto-rotation built-in
• Azure Key Vault        — Microsoft ecosystem
• GCP Secret Manager     — Google Cloud
• Doppler               — Developer-friendly, multi-cloud
• git-secrets           — Prevent committing secrets
• truffleHog            — Scan git history cho secrets
• gitleaks              — Fast git secret scanner (CI/CD integration)
• detect-secrets        — Yelp's secret detection tool
```

---

---

# STEP 7 — RATE LIMITING ĐA TẦNG

> **Mô tả:** Rate limiting một lớp là không đủ. Cần áp dụng tại nhiều tầng: Network, Application, API endpoint, và Business Logic để chống DDoS, brute force, và credential stuffing.

**🟠 HIGH**

---

### ✅ Checklist

**Layer 1 — Network/CDN Level**
- [ ] Enable **CDN-level DDoS protection** (Cloudflare, AWS Shield, Akamai)
- [ ] Config **IP reputation filtering** — block known malicious IPs
- [ ] Set **global rate limit** tại CDN: request/second per IP
- [ ] Enable **Bot Management** — distinguish human vs bot traffic
- [ ] **Geo-blocking** cho regions không có user (nếu applicable)

**Layer 2 — Application Server Level**
- [ ] Rate limit **tất cả API endpoints** — không chỉ auth endpoints
- [ ] Implement **sliding window algorithm** thay vì fixed window
- [ ] Dùng **Redis/distributed cache** cho rate limiting (không in-memory nếu nhiều instance)
- [ ] Differentiate rate limits: authenticated users > anonymous users
- [ ] Return **`Retry-After` header** khi bị rate limited
- [ ] Return **429 Too Many Requests** (không phải 400/403)

**Layer 3 — Endpoint-Specific Limits**
- [ ] `/login`, `/register`: **5-10 requests / 15 phút / IP**
- [ ] `/forgot-password`, `/reset-password`: **3 requests / giờ / IP**
- [ ] `/api/*` authenticated: **100-1000 requests / phút / user**
- [ ] `/api/*` public: **30-60 requests / phút / IP**
- [ ] File upload endpoints: **10 requests / giờ / user**
- [ ] Search endpoints: **20 requests / phút** (heavy DB queries)
- [ ] Email/SMS sending: **5 / giờ / user** (chặn abuse)

**Layer 4 — Business Logic Level**
- [ ] Giới hạn **số lần nhập sai OTP**: 5 lần → lockout 30 phút
- [ ] **Account lockout** sau 10 lần đăng nhập sai (với CAPTCHA threshold)
- [ ] Implement **CAPTCHA** (hCaptcha/Turnstile) tại threshold — không ngay từ đầu
- [ ] Chống **credential stuffing**: velocity check, device fingerprinting
- [ ] Giới hạn số **concurrent sessions** per user

---

### 🛠️ Tools Gợi Ý

```
• express-rate-limit     — Node.js basic rate limiting
• rate-limiter-flexible  — Advanced: Redis, clustering, multiple strategies
• Nginx limit_req        — Nginx-level rate limiting
• Traefik RateLimit      — Middleware cho Traefik proxy
• Cloudflare WAF         — Enterprise WAF + rate limiting
• AWS WAF + Shield       — AWS ecosystem protection
• Redis                  — Distributed counter storage
• Upstash                — Serverless Redis cho rate limiting
```

---

### 💡 Config Mẫu (express-rate-limit + Redis)

```javascript
import rateLimit from 'express-rate-limit';
import RedisStore from 'rate-limit-redis';

// Strict limit cho auth endpoints
export const authLimiter = rateLimit({
  windowMs: 15 * 60 * 1000,  // 15 phút
  max: 5,
  store: new RedisStore({ client: redisClient }),
  message: { error: 'Too many attempts', retryAfter: '15 minutes' },
  standardHeaders: true,      // Return Retry-After header
  legacyHeaders: false,
  skipSuccessfulRequests: true // Không đếm requests thành công
});

// General API limit
export const apiLimiter = rateLimit({
  windowMs: 60 * 1000,  // 1 phút
  max: 100,
  store: new RedisStore({ client: redisClient }),
  keyGenerator: (req) => req.user?.id || req.ip // Per-user khi authenticated
});

app.use('/api/auth', authLimiter);
app.use('/api', apiLimiter);
```

---

---

# STEP 8 — APT / ANOMALY DETECTION

> **Mô tả:** Không phải mọi attack đều có signature. APT (Advanced Persistent Threats) ẩn náu trong traffic bình thường. Cần detect anomaly theo behavior, không chỉ theo pattern.

**🟠 HIGH**

---

### ✅ Checklist

**Web Application Firewall (WAF)**
- [ ] Deploy **WAF** trước application server (cloud-managed hoặc self-hosted)
- [ ] Enable **OWASP Core Rule Set (CRS)** — block OWASP Top 10 attacks
- [ ] Bắt đầu WAF ở **Detection Mode**, tune rules, rồi chuyển sang Blocking Mode
- [ ] Custom rules cho business logic của app (không chỉ generic rules)
- [ ] Regularly update WAF rules — **subscribe to threat intel feeds**

**Anomaly Detection**
- [ ] Monitor **unusual traffic patterns**: spike đột ngột, traffic giờ thấp điểm
- [ ] Alert khi **single IP** tạo quá nhiều requests khác nhau (scanning behavior)
- [ ] Detect **credential stuffing**: nhiều accounts thất bại từ cùng subnet
- [ ] Monitor **failed authentication rate** — alert khi > threshold
- [ ] Detect **account takeover patterns**: login từ new country/device
- [ ] Monitor **data exfiltration**: response size bất thường, export hàng loạt
- [ ] Detect **business logic abuse**: mua hàng bất thường, coupon abuse

**User Behavior Analytics (UBA)**
- [ ] Baseline **normal behavior** cho mỗi user/role
- [ ] Alert khi hành động **ngoài giờ làm việc** cho admin accounts
- [ ] Detect **privilege escalation attempts**
- [ ] Monitor **sensitive data access** patterns
- [ ] Implement **honeypot endpoints/fields** — không có trong UI, chỉ bot mới trigger

**Infrastructure Monitoring**
- [ ] Monitor **resource usage anomaly**: CPU spike, memory leak (có thể là cryptominer)
- [ ] Alert khi có **outbound connections** bất thường (C2 communication)
- [ ] Monitor **DNS queries** cho data exfiltration qua DNS tunneling
- [ ] Implement **Network IDS/IPS** (Suricata, Snort)
- [ ] Monitor **file integrity** cho critical system files

---

### 🛠️ Tools Gợi Ý

```
• ModSecurity + OWASP CRS  — Open source WAF
• Cloudflare WAF           — Managed, easy setup
• AWS WAF                  — Native AWS integration
• Wazuh                    — Open source SIEM + IDS
• Elastic SIEM             — ELK Stack cho security analytics
• Suricata                 — Network IDS/IPS
• OSSEC                    — Host-based intrusion detection
• Falco                    — Runtime security cho containers/K8s
• Sentry                   — Error monitoring (detect attacks via errors)
• Datadog Security         — Full-stack anomaly detection
```

---

---

# STEP 9 — STRUCTURED LOGGING

> **Mô tả:** Log là "camera an ninh" của bạn. Log không đầy đủ = không biết gì khi bị attack. Structured logging (JSON) cho phép search, alert, và correlate events dễ dàng.

**🟠 HIGH**

---

### ✅ Checklist

**What to Log (Bắt Buộc)**
- [ ] Tất cả **authentication events**: login success/fail, logout, MFA
- [ ] Tất cả **authorization failures**: 401, 403 responses
- [ ] Tất cả **input validation failures** (detect scanning/fuzzing)
- [ ] **Admin actions**: user management, config change, permission change
- [ ] **Data access events**: read/write/delete sensitive data
- [ ] **API calls**: endpoint, method, user, IP, latency, status code
- [ ] **Payment/transaction events** với full audit trail
- [ ] **Error và exception**: với stack trace nhưng không leak secrets
- [ ] **System events**: start, stop, config reload, deployment

**Log Format (Structured JSON)**
- [ ] Mỗi log entry có: **timestamp (ISO 8601 + UTC)**, level, message, requestId
- [ ] Include: **userId, sessionId, IP, userAgent, endpoint, method, statusCode**
- [ ] Include: **correlationId** để trace request qua microservices
- [ ] **KHÔNG log** passwords, tokens, credit card numbers, SSN, PII nhạy cảm
- [ ] Mask sensitive fields: `****` thay vì giá trị thực
- [ ] Log level phù hợp: ERROR/WARN/INFO/DEBUG — không dùng DEBUG ở production

**Log Infrastructure**
- [ ] **Centralize logs** vào SIEM — không chỉ để trên server
- [ ] Log phải **immutable** — không thể sửa/xóa sau khi ghi (append-only)
- [ ] Retain logs tối thiểu **90 ngày hot, 1 năm cold** (tuỳ compliance requirement)
- [ ] **Alert real-time** cho critical events (không chỉ review thủ công)
- [ ] Setup **log rotation** để tránh disk full
- [ ] Test **log pipeline** định kỳ — đảm bảo logs thực sự đến SIEM
- [ ] Separate **security logs** khỏi application logs

---

### 🛠️ Tools Gợi Ý

```
• Winston / Pino          — Node.js structured logging
• structlog               — Python structured logging
• ELK Stack               — Elasticsearch + Logstash + Kibana
• Grafana Loki            — Log aggregation, Prometheus ecosystem
• Datadog Logs            — Managed, powerful query, alerting
• Splunk                  — Enterprise SIEM, powerful search
• Sentry                  — Error tracking + performance
• OpenTelemetry           — Distributed tracing + logs standard
• Fluentd / Fluent Bit    — Log shipping agent
• AWS CloudWatch          — AWS native log management
```

---

### 💡 Log Format Chuẩn

```json
{
  "timestamp": "2026-01-15T08:23:41.123Z",
  "level": "WARN",
  "event": "AUTH_FAILED",
  "message": "Login failed: invalid credentials",
  "requestId": "req_abc123xyz",
  "correlationId": "trace_def456",
  "userId": null,
  "email": "u***@example.com",
  "ip": "203.0.113.42",
  "userAgent": "Mozilla/5.0...",
  "endpoint": "/api/auth/login",
  "method": "POST",
  "statusCode": 401,
  "attemptCount": 3,
  "geo": { "country": "VN", "city": "Hanoi" },
  "service": "auth-service",
  "version": "2.1.0",
  "environment": "production"
}
```

---

---

# STEP 10 — INCIDENT RESPONSE PLAN

> **Mô tả:** Không phải IF mà là WHEN bạn bị tấn công. Incident Response Plan phải được viết, test, và drill trước khi cần dùng. Panic là kẻ thù khi có breach.

**🟡 MEDIUM** *(nhưng Critical khi incident xảy ra)*

---

### ✅ Checklist

**Preparation (Chuẩn Bị — Làm Ngay Bây Giờ)**
- [ ] Viết **Incident Response Runbook** — step-by-step, không chung chung
- [ ] Định nghĩa **Severity Levels** (P0/P1/P2/P3) với SLA response time
- [ ] Establish **Incident Response Team**: Lead, Dev, Ops, Security, Communications, Legal
- [ ] Lưu **contact list ngoại tuyến** (phone/Signal) — email có thể bị compromise
- [ ] Chuẩn bị **war room** (Slack channel, Zoom bridge) — activate ngay khi incident
- [ ] Backup và verify **recovery procedures** hàng tháng
- [ ] Có sẵn **forensics tools** và clean environment để investigate
- [ ] Biết rõ **data breach notification obligations** (GDPR 72h, PCI DSS, v.v.)

**Detection & Classification**
- [ ] Define **indicators of compromise (IoC)** cho hệ thống của bạn
- [ ] Automated alerts cho: mass data access, privilege escalation, new admin user
- [ ] **Triage checklist** — 5 phút đầu tiên: xác định scope, đang active hay đã qua?
- [ ] Phân loại: Data Breach / Service Disruption / Account Compromise / Malware

**Containment (Khoanh Vùng)**
- [ ] Có thể **isolate affected systems** trong < 15 phút
- [ ] **Block attacker IPs/accounts** mà không xóa evidence
- [ ] Có thể **revoke tất cả sessions/tokens** trong 1 lệnh
- [ ] **Không tắt server ngay** nếu muốn forensics — snapshot trước
- [ ] Enable **emergency maintenance mode** nếu cần

**Eradication & Recovery**
- [ ] Identify và patch **root cause** trước khi restore
- [ ] **Clean restore từ known-good backup** — không giả sử system sạch
- [ ] Rotate **tất cả credentials và secrets** sau incident
- [ ] Verify **integrity** của codebase sau compromise
- [ ] Staged recovery — monitor chặt sau khi restore

**Post-Incident**
- [ ] Viết **Post-Mortem** không blame culture trong 48-72h
- [ ] Document: timeline, root cause, impact, actions taken, lessons learned
- [ ] Update **runbook** dựa trên bài học thực tế
- [ ] **Notify affected users** đúng hạn, đúng pháp luật
- [ ] Conduct **tabletop exercise** ít nhất 2 lần/năm

---

### 🛠️ Tools Gợi Ý

```
• PagerDuty              — On-call alerting, incident management
• OpsGenie              — Alert routing, escalation
• Jira / Linear          — Incident tracking
• TheHive               — Open source incident response platform
• Velociraptor           — Digital forensics, endpoint visibility
• Volatility             — Memory forensics
• Wireshark              — Network packet analysis
• MITRE ATT&CK           — Framework map attacker techniques
• Playbook (Notion/Confluence) — Document runbooks
```

---

### 📞 Incident Response Quick Reference

```
┌─────────────────────────────────────────────────┐
│           INCIDENT RESPONSE — P0 BREACH         │
├──────────┬──────────────────────────────────────┤
│ 0-5 min  │ Alert IR Lead + declare incident      │
│ 5-15 min │ Activate war room, initial triage     │
│ 15-30 min│ Containment — isolate affected system │
│ 30-60 min│ Assess scope, notify stakeholders     │
│ 1-4 hrs  │ Eradication + evidence preservation  │
│ 4-24 hrs │ Recovery + monitoring                 │
│ 24-72 hrs│ User notification (if data breach)   │
│ 72h+     │ Post-mortem + regulatory reporting    │
└──────────┴──────────────────────────────────────┘
```

---

---

# 📊 PRIORITY MATRIX — TỔNG KẾT

```
┌─────────────────────────────────────┬──────────┬───────────────┐
│ BƯỚC                                │ PRIORITY │ EFFORT        │
├─────────────────────────────────────┼──────────┼───────────────┤
│ 1. Input Validation & Sanitization  │ 🔴 CRIT  │ ████████ High │
│ 2. HTTPS + HSTS                     │ 🔴 CRIT  │ ███ Low       │
│ 3. Security Headers                 │ 🔴 CRIT  │ ██ Very Low   │
│ 4. CORS Configuration               │ 🔴 CRIT  │ ███ Low       │
│ 5. JWT & Token Security             │ 🔴 CRIT  │ ██████ Medium │
│ 6. Secret Management                │ 🔴 CRIT  │ █████ Medium  │
│ 7. Rate Limiting Đa Tầng            │ 🟠 HIGH  │ █████ Medium  │
│ 8. APT / Anomaly Detection          │ 🟠 HIGH  │ ████████ High │
│ 9. Structured Logging               │ 🟠 HIGH  │ ██████ Medium │
│ 10. Incident Response Plan          │ 🟡 MED   │ ███████ High  │
└─────────────────────────────────────┴──────────┴───────────────┘
```

---

# 🔄 MAINTENANCE SCHEDULE

| Tần Suất | Việc Cần Làm |
|----------|-------------|
| **Hàng ngày** | Review security alerts, anomaly notifications |
| **Hàng tuần** | Review rate limit logs, failed auth patterns |
| **Hàng tháng** | Rotate secrets, review user permissions, test backups |
| **Hàng quý** | Penetration test, dependency audit (`npm audit`), WAF rule review |
| **Hàng năm** | Full security audit, IR tabletop exercise, compliance review |
| **Khi deploy** | Run SAST scan, DAST scan, check security headers |
| **Khi có CVE** | Patch trong 24h (critical) / 7 ngày (high) / 30 ngày (medium) |

---

# 🔗 QUICK SCAN CHECKLIST (15 PHÚT)

> *Chạy cái này ngay bây giờ trên production*

```bash
# 1. Kiểm tra SSL
curl https://api.ssllabs.com/api/v3/analyze?host=yourdomain.com

# 2. Kiểm tra Security Headers  
curl -I https://yourdomain.com

# 3. Scan secrets trong git
gitleaks detect --source . --verbose

# 4. Kiểm tra npm vulnerabilities
npm audit --audit-level=high

# 5. Test CORS
curl -H "Origin: https://evil.com" -I https://yourdomain.com/api

# 6. Check open ports
nmap -sV yourdomain.com
```

---

> **📌 GHI NHỚ:** Security là process, không phải destination.
> Checklist này không bao giờ "done" — update nó, review nó, improve nó liên tục.

---

*🖨️ Print tip: Dùng Ctrl+P → Save as PDF → A3 landscape hoặc A4 landscape cho dễ đọc khi in*