CSSLP · Domain 3 · 14%

Thiết kế phần mềm an toàn

Secure Software Design

Secure design patterns, API security (REST/GraphQL), cryptography selection, database security, microservices mTLS và mobile app security design — những quyết định kiến trúc quan trọng nhất ảnh hưởng đến bảo mật toàn hệ thống.

Mục tiêu chương / Learning objectives

1. Lý thuyết cốt lõi / Core theory

1.1. Secure Design Patterns (Patterns for Secure Software)

Design patterns cho bảo mật là solutions tái sử dụng cho security problems phổ biến: Secure Factory — tạo objects theo cách an toàn, validate inputs trước khi khởi tạo, không expose raw constructors; Intercepting Filter — centralize security checks (authentication, authorization, input validation, logging) trong filter chain trước khi request đến business logic — pattern này là nền tảng của Spring Security, ASP.NET middleware; Authorization Enforcer — tách biệt authorization logic ra khỏi business logic, một service/component chịu trách nhiệm duy nhất quyết định allow/deny; Secure Logger — log đủ thông tin cho incident response nhưng không log sensitive data (PII, credentials, session tokens).

Separation of Concerns trong bảo mật: Khi security logic trộn lẫn với business logic, cả hai đều khó maintain và dễ bị bypass. Intercepting Filter pattern đảm bảo: (1) security checks không bị skip do developer quên, (2) dễ audit — một chỗ duy nhất để review security logic, (3) cross-cutting concerns như logging, rate limiting áp dụng nhất quán.

1.2. API Security Design (REST & GraphQL Security)

REST API security checklist: HTTPS-only (HSTS header), JWT với short expiry (15 phút) + refresh token rotation, OAuth 2.0 scopes (principle of least privilege cho API clients), rate limiting (per-user và per-IP), API versioning (deprecate + remove old endpoints), không trả về stack traces trong error response, validate Content-Type, CORS whitelist cụ thể.

GraphQL-specific risks: Introspection (nên disable trên production — expose toàn bộ schema cho attacker), Batching attacks (gửi 1000 queries trong 1 request để bypass rate limit), Deep query attacks (deeply nested queries làm DB timeout), Field-level authorization (từng field cần authorization check riêng, không chỉ ở resolver level). Giải pháp: query depth limiting, complexity analysis, persisted queries.

1.3. Cryptography trong Thiết kế (Choosing the Right Crypto)

Nguyên tắc vàng: đừng tự viết crypto. Dùng thư viện chuẩn (libsodium, Bouncy Castle, Windows CNG). Lựa chọn đúng:

1.4. Database & Microservices Security Design (DB + μServices)

Database security: Parameterized queries / prepared statements (không bao giờ string concatenation cho SQL); stored procedures cần review vì vẫn có thể chứa dynamic SQL; ORM pitfalls: raw query methods (executeNativeQuery(), FromSqlRaw()) phải dùng parameters, không interpolation; principle of least privilege cho DB user (app account chỉ có SELECT/INSERT/UPDATE cần thiết, không GRANT hoặc DROP).

Microservices security: mTLS (mutual TLS) giữa services — cả client và server đều xác thực certificate; service accounts với short-lived credentials (service mesh như Istio tự rotate); API Gateway là điểm tập trung authentication/authorization, rate limiting, SSL termination; Zero Trust — mỗi service-to-service call đều phải authorized, không tin tưởng network boundary.

1.5. Mobile App Security Design (OWASP MASVS)

Certificate pinning: hardcode certificate hash vào app, từ chối TLS connections đến servers có cert không khớp — chống MITM attack kể cả khi attacker install root CA trên device. Secure storage: iOS Keychain, Android Keystore — không lưu sensitive data vào SharedPreferences/NSUserDefaults hoặc SD card. Jailbreak/Root detection: kiểm tra sự tồn tại của Cydia/Magisk, kiểm tra file system integrity — nếu device bị jailbreak/root, tăng risk vì sandbox bị bypass. Tham chiếu: OWASP MASVS (Mobile Application Security Verification Standard) — L1/L2/R (Resiliency) levels.

2. Bài thực hành / Hands-on labs

🖥️ Nền tảng / Platform: Windows 11 · Ubuntu 22.04 LTS
🛠️ Công cụ / Tools: PowerShell 7 · Bash + Semgrep

Lab 1 — Phát hiện SQL Injection và Weak Crypto trong Code (PowerShell)

OS: Windows 11 · Tool: PowerShell 7.

# Tìm SQL injection patterns (string concatenation trong SQL)
Write-Host "=== SQL Injection Risk Scan ===" -ForegroundColor Yellow
Get-ChildItem -Recurse -Include *.sql,*.cs,*.java,*.py -ErrorAction SilentlyContinue |
    Select-String -Pattern "'\s*\+\s*|string\.Format.*SELECT|EXEC\s*\(" |
    Select-Object Path, LineNumber, Line |
    Format-Table -Wrap -AutoSize

# Tìm weak hashing algorithms
Write-Host "`n=== Weak Cryptography Scan ===" -ForegroundColor Yellow
Get-ChildItem -Recurse -Include *.cs,*.java,*.py,*.js -ErrorAction SilentlyContinue |
    Select-String -Pattern "\bMD5\b|\bSHA1\b|\bSHA-1\b|\bDES\b|\bRC4\b|\bMD4\b" |
    Select-Object Path, LineNumber, Line |
    Format-Table -Wrap -AutoSize

# Demo: tạo file mẫu có vấn đề và scan
@'
// BAD: SQL concatenation — SQL injection risk
string sql = "SELECT * FROM users WHERE id = " + userId;

// BAD: MD5 for password — weak, not suitable for credentials
string hash = MD5.HashData(Encoding.UTF8.GetBytes(password));

// GOOD: parameterized query
string sql2 = "SELECT * FROM users WHERE id = @userId";

// GOOD: bcrypt for passwords
string hash2 = BCrypt.Net.BCrypt.HashPassword(password, workFactor: 12);
'@ | Out-File -FilePath "$env:TEMP\crypto-review.cs" -Encoding UTF8

Write-Host "`n=== Scan results on sample file ===" -ForegroundColor Cyan
Get-Content "$env:TEMP\crypto-review.cs" |
    Select-String -Pattern "MD5|SHA1|sql\s*=.*\+" |
    ForEach-Object { Write-Host "  LINE $($_.LineNumber): $($_.Line.Trim())" -ForegroundColor Red }
Write-Host "Items marked GOOD pass the check." -ForegroundColor Green

✅ Kết quả mong đợi / Expected output: Scan tìm thấy LINE chứa MD5.HashDatasql = "SELECT..." + userId được highlight đỏ. Lines với parameterized query và bcrypt không bị flag. Ý nghĩa: các pattern này là foundation của SAST rules — tích hợp vào CI/CD để auto-fail build khi phát hiện anti-pattern.

Lab 2 — SAST với Semgrep (OWASP Top 10) (Bash)

OS: Ubuntu 22.04 · Tool: Bash + Semgrep.

Lưu ý giáo dục: Code mẫu dưới đây minh họa các anti-patterns nguy hiểm (SQL injection, weak crypto, shell injection) để Semgrep phát hiện. Đây là nội dung học tập — không áp dụng vào code thực tế.
# Cài Semgrep
pip install semgrep 2>/dev/null

# Tạo file mẫu với các anti-pattern để Semgrep phát hiện
mkdir -p /tmp/vuln-demo
cat > /tmp/vuln-demo/bad_patterns.py << 'PYEOF'
import hashlib, sqlite3, subprocess

# ANTI-PATTERN 1: MD5 for password hashing (weak)
def hash_password_bad(password):
    return hashlib.md5(password.encode()).hexdigest()

# ANTI-PATTERN 2: SQL injection via f-string
def get_user_bad(username, conn):
    query = f"SELECT * FROM users WHERE username='{username}'"
    return conn.execute(query).fetchone()

# ANTI-PATTERN 3: shell=True with variable (command injection risk)
def run_check_bad(hostname):
    # Danger: never pass user input through shell=True
    result = subprocess.run(["ping", "-c", "1", hostname],
                            shell=False, capture_output=True)
    return result

# SECURE versions for comparison
def hash_password_good(password):
    import bcrypt
    return bcrypt.hashpw(password.encode(), bcrypt.gensalt(rounds=12))

def get_user_good(username, conn):
    return conn.execute("SELECT * FROM users WHERE username=?", (username,)).fetchone()
PYEOF

# Chạy Semgrep với Python security rules
semgrep --config p/python /tmp/vuln-demo/ 2>/dev/null | grep -E "severity|rule|found|line" | head -25

# Chạy OWASP Top 10 ruleset
semgrep --config p/owasp-top-ten /tmp/vuln-demo/ 2>/dev/null | tail -20

# Đếm secure vs insecure crypto
echo "--- Crypto Usage Analysis ---"
grep -c "hashlib\.md5\|hashlib\.sha1" /tmp/vuln-demo/bad_patterns.py | xargs echo "Weak hash calls:"
grep -c "bcrypt\|argon2\|pbkdf2" /tmp/vuln-demo/bad_patterns.py | xargs echo "Strong hash calls:"

✅ Kết quả mong đợi / Expected output: Semgrep phát hiện: (1) python.lang.security.audit.md5-used — MD5 weak hashing, (2) python.lang.security.audit.formatted-sql-query — SQL injection risk via f-string. Secure versions (bcrypt + parameterized) không bị flag. Crypto count: 1 weak, 1 strong. Ý nghĩa: Semgrep rules có thể customize thêm theo coding standards của tổ chức.

3. Tình huống doanh nghiệp / Real-world scenario

Bối cảnh:

Một e-commerce platform đang chuyển đổi từ monolith sang microservices. Security architect cần review thiết kế cho service "Payment Processing" giao tiếp với 5 services khác qua REST API.

Quyết định thiết kế bảo mật:

  1. mTLS giữa services: Dùng Istio service mesh — mỗi pod có certificate riêng, tự động rotate 24 giờ. Service chỉ accept request từ services được authorize trong policy.
  2. Cryptography: Payment data encrypt bằng AES-256-GCM. Card number tokenized (không lưu raw). Encryption keys trong HashiCorp Vault, rotate hàng tháng.
  3. API Gateway: Kong Gateway xử lý JWT validation, rate limiting (100 req/min per merchant), CORS, request/response logging.
  4. Database: Parameterized queries enforce qua ORM. DB user "payment_svc" chỉ có SELECT/INSERT trên payment_transactions table.
  5. Intercepting Filter: Middleware chain: TLS termination → JWT validation → Authorization check → Rate limit → Business logic.

Bài học: secure design decisions phải được làm sớm — retrofitting mTLS hay tokenization vào production system tốn gấp 10x so với thiết kế đúng từ đầu.

4. Tự kiểm tra / Knowledge check

  1. Intercepting Filter pattern giải quyết vấn đề gì? Cho ví dụ trong một framework cụ thể (Spring/ASP.NET).
  2. Tại sao AES-ECB mode nguy hiểm? Mode nào nên dùng thay thế và tại sao?
  3. GraphQL Introspection attack là gì và cách mitigate trên production?
  4. mTLS khác gì so với TLS thông thường? Tại sao quan trọng trong microservices?
  5. Certificate pinning bảo vệ chống tấn công nào trong mobile app? Có nhược điểm gì không?
C02: Yêu cầu bảo mật phần mềm C04: Triển khai an toàn
Thực hành trên công cụPowerShell 7 · Bash · Semgrep
Nền tảngWindows 11 · Ubuntu 22.04 LTS
Thời điểm phát hànhQ2/2026
Ngày biên soạn24/05/2026
Người biên soạnTrần Văn Hòa (MCT)
Phiên bảnv1.0
Zalo