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

Security: Overview và Roadmap

Security không phải là một "feature" mà bạn thêm vào cuối project. Nó là mindset — một cách suy nghĩ xuyên suốt từ khi thiết kế đến khi deploy. Mục tiêu của section này là giúp bạn hiểu các nguyên lý bảo mật cốt lõi, các vulnerability phổ biến, và cách xây dựng hệ thống an toàn từ đầu.

🔐 "Security is not a product, but a process." — Bruce Schneier


Cấu trúc section

security/
├── README.md                              ← file này
├── auth/
│   ├── README.md                          ← Authentication & Authorization chi tiết
│   ├── session-vs-jwt.md                  ← Session-based vs JWT
│   ├── oauth2-and-oidc.md                 ← OAuth 2.0, OpenID Connect
│   └── advanced-auth.md                   ← MFA, SSO, Zero Trust
├── owasp-and-common-vulns.md              ← OWASP Top 10 + mitigations
├── secure-coding.md                       ← Input validation, XSS, CSRF, SQL injection
├── crypto-basics.md                       ← Hashing, encryption, signatures
├── api-and-web-security.md                ← API keys, rate limiting, CORS
├── distributed-systems-security.md        ← mTLS, secrets management, zero trust
└── interview-and-big-picture.md           ← Câu hỏi phỏng vấn + big picture

Bức tranh tổng thể: CIA Triad

Mọi thứ trong security đều xoay quanh 3 nguyên tắc này:

           ┌──────────────────┐
           │  CONFIDENTIALITY │  ← Data chỉ được truy cập bởi những người có quyền
           └──────────────────┘
                    ▲
                    │
         ┌──────────┴──────────┐
         │                     │
┌────────▼────────┐   ┌────────▼────────┐
│   INTEGRITY     │   │  AVAILABILITY   │
│ Data không bị   │   │  System luôn    │
│ thay đổi trái   │   │  sẵn sàng khi   │
│ phép            │   │  cần            │
└─────────────────┘   └─────────────────┘

Confidentiality (Bảo mật): Mã hóa data at rest & in transit, access control
Integrity (Toàn vẹn): Checksums, digital signatures, audit logs
Availability (Khả dụng): DDoS protection, redundancy, monitoring


Defense in Depth

Security không nên dựa vào một lớp bảo vệ duy nhất. Bạn cần nhiều lớp — nếu một lớp bị vượt qua, còn các lớp khác.

┌────────────────────────────────────┐
│  Perimeter (Firewall, WAF)        │
├────────────────────────────────────┤
│  Network (VPC, Security Groups)   │
├────────────────────────────────────┤
│  Application (Auth, Input Val.)   │
├────────────────────────────────────┤
│  Data (Encryption, Access Ctrl)   │
└────────────────────────────────────┘

Roadmap học Security

Level 1: Foundation 🌱

Mục tiêu: Hiểu các khái niệm cơ bản và threat landscape

Nội dung:

  1. CIA Triad & Security Principles (1 tuần)

    • Confidentiality, Integrity, Availability
    • Least privilege, Defense in depth, Fail securely
  2. Authentication & Authorization basics (2 tuần)

    • Password hashing (bcrypt, argon2)
    • Session-based auth vs JWT
    • OAuth 2.0 flows (authorization code, client credentials)
    • RBAC (Role-Based Access Control)
  3. Common Web Vulnerabilities (2 tuần)

    • SQL Injection & prevention (prepared statements)
    • XSS (Cross-Site Scripting) - stored, reflected, DOM-based
    • CSRF (Cross-Site Request Forgery) & tokens
    • Open redirects, clickjacking
  4. HTTPS & TLS basics (1 tuần)

    • Certificate chains, CA
    • TLS handshake
    • Certificate pinning

Resources:

Practice:


Level 2: Practical Security 🛠️

Mục tiêu: Apply security practices trong code và infrastructure

Nội dung:

  1. Secure Coding Practices (2 tuần)

    • Input validation & sanitization
    • Output encoding
    • Parameterized queries
    • Security headers (CSP, X-Frame-Options, HSTS)
    • Dependency scanning (Dependabot, Snyk)
  2. API Security (2 tuần)

    • API authentication (API keys, OAuth, mTLS)
    • Rate limiting & throttling
    • Input validation for JSON/XML
    • API versioning security implications
    • GraphQL security (query depth limiting, etc.)
  3. Cryptography Basics (2 tuần)

    • Hashing vs Encryption vs Encoding
    • Symmetric encryption (AES-GCM)
    • Asymmetric encryption (RSA, ECC)
    • Digital signatures
    • Key management best practices
  4. Secrets Management (1 tuần)

    • Environment variables (what NOT to do)
    • Vault, AWS Secrets Manager, GCP Secret Manager
    • Rotation strategies
    • Least privilege for service accounts

Resources:

Practice:

  • Audit một project cũ, tìm vulnerabilities
  • Implement secure login flow từ đầu
  • Set up secrets rotation với Vault

Level 3: Advanced Security 🚀

Mục tiêu: Security cho distributed systems và enterprise environments

Nội dung:

  1. Advanced Authentication (2 tuần)

    • Multi-Factor Authentication (TOTP, WebAuthn)
    • Single Sign-On (SAML, OpenID Connect)
    • Zero Trust Architecture
    • Passwordless authentication (passkeys)
  2. Security in Distributed Systems (3 tuần)

    • mTLS (mutual TLS) for service-to-service
    • Service mesh security (Istio, Linkerd)
    • API Gateway security
    • Distributed tracing for security audit
    • Supply chain security (SBOM, Sigstore)
  3. Cloud Security (2 tuần)

    • IAM policies & least privilege
    • Network security (VPC, Security Groups, NACLs)
    • Encryption at rest & in transit
    • Cloud-native security tools (GuardDuty, Security Hub)
    • Compliance frameworks (SOC 2, ISO 27001, GDPR)
  4. Incident Response & Security Operations (2 tuần)

    • Logging & monitoring for security events
    • SIEM (Security Information and Event Management)
    • Incident response playbooks
    • Post-mortem & lessons learned
    • Threat modeling (STRIDE, DREAD)

Resources:

Practice:

  • Tham gia bug bounty programs (HackerOne, Bugcrowd)
  • Conduct threat modeling cho một hệ thống
  • Implement mTLS cho microservices
  • Set up monitoring & alerting cho security events

Nguyên tắc cốt lõi

1. Never Trust, Always Verify (Zero Trust)

Không assume rằng traffic bên trong network là safe. Verify mọi request, mọi user, mọi service.

// Sai
if (req.headers['x-internal-request']) {
    // Skip authentication — trust internal requests
}

// Đúng
const user = await authenticate(req);
const authorized = await authorize(user, resource);
if (!authorized) throw new ForbiddenError();

2. Principle of Least Privilege

Mỗi user, service, process chỉ được access đúng những gì cần thiết, không hơn.

// Sai: service account có quyền admin toàn bộ database
GRANT ALL PRIVILEGES ON *.* TO 'api-service'@'%';

// Đúng: chỉ cho phép SELECT/INSERT trên specific tables
GRANT SELECT, INSERT ON app_db.orders TO 'api-service'@'%';

3. Fail Securely

Khi có lỗi, default behavior phải là deny access, không phải allow.

// Sai
func checkPermission(userID, resource string) bool {
    perm, err := db.GetPermission(userID, resource)
    if err != nil {
        return true  // Lỗi → cho phép?! 🔥
    }
    return perm.Allowed
}

// Đúng
func checkPermission(userID, resource string) bool {
    perm, err := db.GetPermission(userID, resource)
    if err != nil {
        log.Error("permission check failed", err)
        return false  // Lỗi → deny access
    }
    return perm.Allowed
}

4. Security by Design, Not Afterthought

Tích hợp security vào từng bước trong SDLC:

  • Design: Threat modeling
  • Development: Secure coding practices, SAST (Static Application Security Testing)
  • Testing: Penetration testing, DAST (Dynamic Application Security Testing)
  • Deployment: Security scanning images, least privilege policies
  • Operations: Monitoring, incident response

Red Flags phổ biến

🚩 Credentials hardcoded trong code

// NEVER do this
dbURL := "postgres://admin:password123@prod-db.com/users"

🚩 Sensitive data trong logs

log.Info("User login", "email", email, "password", password)  // 😱

🚩 Không validate input

query := fmt.Sprintf("SELECT * FROM users WHERE id = %s", userID)
// SQL injection nếu userID = "1 OR 1=1"

🚩 Dùng weak hashing cho password

hash := md5.Sum([]byte(password))  // MD5 is broken!

🚩 Missing rate limiting

// Attacker có thể brute-force password không giới hạn

Security Checklist trước khi ship

  • Secrets không bị commit vào git (pre-commit hooks)
  • Dependencies được scan thường xuyên (Dependabot, Snyk)
  • Authentication required cho mọi sensitive endpoints
  • Authorization được enforce ở server-side
  • Input validation cho mọi user input
  • SQL queries dùng prepared statements / parameterized queries
  • Passwords được hash bằng bcrypt/argon2
  • HTTPS enforced (HSTS header)
  • Security headers (CSP, X-Frame-Options, etc.)
  • Rate limiting cho login & sensitive operations
  • Logs không chứa sensitive data
  • Error messages không leak internal info
  • Backup & recovery plan
  • Incident response plan
  • Security monitoring & alerting

Common Interview Topics

  1. OWASP Top 10: Chuẩn bị giải thích + mitigation cho top 5
  2. Auth vs Authz: Sự khác biệt, JWT vs session, OAuth flows
  3. XSS, CSRF, SQL Injection: Cách hoạt động + cách phòng chống
  4. HTTPS/TLS: Certificate verification, TLS handshake
  5. API Security: Rate limiting, authentication schemes
  6. Secrets Management: Best practices, tools
  7. Zero Trust: Principles, how to implement

Tools & Frameworks cần biết

Security Testing:

  • OWASP ZAP, Burp Suite
  • Nmap, Wireshark
  • sqlmap, XSStrike

Secrets Management:

  • HashiCorp Vault
  • AWS Secrets Manager, GCP Secret Manager
  • SOPS, git-crypt

Vulnerability Scanning:

  • Snyk, Dependabot
  • Trivy (container images)
  • SonarQube

Monitoring & SIEM:

  • Splunk, ELK Stack
  • AWS GuardDuty, GCP Security Command Center
  • Falco (runtime security)

Đọc theo thứ tự

  1. auth/README.md — Nền tảng về authentication & authorization
  2. owasp-and-common-vulns.md — Các vulnerability phổ biến
  3. secure-coding.md — Best practices khi code
  4. crypto-basics.md — Cryptography 101
  5. api-and-web-security.md — Bảo mật APIs & web apps
  6. distributed-systems-security.md — Security cho microservices
  7. interview-and-big-picture.md — Tổng hợp & luyện phỏng vấn

💡 Remember: The only secure system is one that is powered off, cast in a block of concrete, and sealed in a lead-lined room with armed guards. And even then I have my doubts. — Gene Spafford