Mục tiêu chương / Learning objectives
- Tích hợp bảo mật vào toàn bộ SDLC (shift-left security): threat modeling, SAST/DAST, SCA trong CI/CD pipeline cloud-native.
- Phân tích OWASP Cloud-Native Application Security Top 10 và ánh xạ tới controls cụ thể trên AWS/Azure/GCP.
- Cấu hình API Gateway security: authentication (OAuth2/JWT/API keys), rate limiting, throttling, request validation, và logging tập trung.
- Triển khai mutual TLS (mTLS) giữa microservices dùng service mesh (Istio/Linkerd) và hiểu trade-off về complexity vs. security.
- Quản lý secrets an toàn trong cloud-native applications: AWS Secrets Manager, Azure Key Vault secret injection, HashiCorp Vault agent sidecar.
- Đảm bảo container image integrity qua image signing (cosign/Notary v2) và enforce admission control trong Kubernetes pipeline.
1. Lý thuyết cốt lõi / Core theory
1.1. Secure SDLC trong Cloud — Shift-Left Security (Secure SDLC)
Shift-left có nghĩa là đưa bảo mật vào sớm nhất trong vòng đời phát triển, thay vì chỉ test ở giai đoạn cuối. Trong cloud-native CI/CD:
- Pre-commit hooks: secret scanning (git-secrets, trufflehog), linting (hadolint cho Dockerfile, kube-score cho K8s YAML).
- SAST (Static Application Security Testing): Phân tích source code không cần chạy. Tools: Semgrep, SonarQube, CodeQL (GitHub Advanced Security). Tích hợp vào PR checks — fail build nếu có HIGH findings.
- SCA (Software Composition Analysis): Kiểm tra third-party dependencies cho CVEs. Tools: OWASP Dependency-Check, Snyk, Dependabot. Quan trọng: 80%+ của modern app là open-source dependencies.
- DAST (Dynamic Application Security Testing): Test ứng dụng đang chạy. OWASP ZAP, Burp Suite Enterprise. Chạy trong staging environment trong CI/CD pipeline.
- Container scanning: Trivy, Grype scan Docker images cho CVEs và misconfigurations trước khi push lên registry.
DevSecOps pipeline stages: Code → SAST+SCA → Build → Container Scan → Test → DAST → Staging → Penetration Test → Production → CSPM+RASP monitoring. Mỗi stage là một security gate.
1.2. OWASP Cloud-Native Application Security Top 10 (OWASP Cloud-Native Top 10)
- CN-1: Insecure cloud/container/orchestration configs: Misconfigured S3 buckets, privileged containers, exposed Kubernetes API server. Control: CIS Benchmark automation, CSPM.
- CN-2: Injection flaws (cloud-native context): SQL injection, event injection trong Lambda, NoSQL injection cho DynamoDB/CosmosDB. Control: input validation, parameterized queries, WAF.
- CN-3: Improper authentication & authorization: Missing API authentication, broken JWT validation, SSRF via metadata endpoint. Control: API Gateway auth, IMDSv2.
- CN-4: CI/CD pipeline risks: Poisoned pipeline (supply chain attack), unsecured CI runners, leaked secrets in build logs. Control: ephemeral runners, secrets management, pipeline hardening.
- CN-5: Insecure secrets management: Hardcoded credentials in code/env vars/Docker images. Control: Vault/KMS injection, never log secrets.
- CN-6: Over-permissive identities: Overly permissive IAM roles, service accounts with cluster-admin. Control: least privilege, periodic access reviews.
- CN-7: Insecure network exposure: Services exposed without authentication, missing TLS, no network segmentation. Control: mTLS, NetworkPolicy, API Gateway.
- CN-8: Supply chain vulnerabilities: Malicious packages (typosquatting), compromised base images, dependency confusion attacks. Control: private registries, image signing, SBOM.
- CN-9: Asset management failures: Shadow IT cloud accounts, untracked resources, forgotten development environments. Control: Cloud governance, tagging policies, resource inventory.
- CN-10: Insufficient logging & monitoring: Missing CloudTrail, no alerting on suspicious API calls. Control: centralized logging, SIEM integration, security event alerting.
1.3. API Gateway Security (API security)
API Gateway là entry point cho cloud-native applications — điểm hội tụ của nhiều security controls:
- Authentication: OAuth 2.0 + OpenID Connect (OIDC) cho user auth. API Keys cho service-to-service (less secure, không có expiry). JWT validation tại gateway — không để backend services tự validate lại.
- Rate limiting & throttling: AWS API Gateway: Usage Plans với API keys — giới hạn requests/second và burst. Azure API Management: rate-limit-by-key policy. Ngăn DDoS và abuse.
- Request validation: Schema validation (JSON Schema/OpenAPI spec) tại gateway reject malformed requests sớm, giảm load cho backend và giảm injection surface.
- Logging: Mọi API call phải được log với: timestamp, caller identity, endpoint, status code, latency. AWS API Gateway → CloudWatch Logs/S3. Azure APIM → Azure Monitor/Log Analytics.
- CORS policy: Restrict allowed origins, methods, headers. Avoid wildcard
*origins trong production.
1.4. Microservices Security — mTLS & Service Mesh (Microservices security)
Trong microservices architecture, service-to-service communication bên trong cluster cần bảo mật. mTLS (Mutual TLS) xác thực hai chiều: client và server đều present certificate, đảm bảo cả authentication và encryption.
- Istio: Service mesh phổ biến nhất. Sidecar proxy (Envoy) inject vào mỗi pod, transparent mTLS giữa services. Control plane (istiod) manage certificates tự động. PeerAuthentication policy enforce mTLS. AuthorizationPolicy control ai được gọi ai (east-west traffic control).
- Linkerd: Nhẹ hơn Istio, mTLS by default, zero-config approach. Phù hợp cho teams không muốn complexity của Istio.
- Certificate management: Cert-manager tự động issue và renew TLS certificates từ Let's Encrypt hoặc internal CA. Kết hợp với service mesh = zero-touch mTLS.
1.5. Secrets Management & Container Image Security (Secrets & image security)
Secrets management tiers:
- Bad (avoid): Hardcoded trong source code, environment variables trong Dockerfile, secrets trong Kubernetes YAML committed to git.
- Better: Kubernetes Secrets (base64 encoded, not encrypted by default) — enable etcd encryption at rest + RBAC restrict access.
- Best: External secret stores với dynamic secrets. AWS Secrets Manager: auto-rotate database passwords. Azure Key Vault: CSI driver mount secrets vào pod như filesystem. HashiCorp Vault: agent sidecar inject secrets vào container environment at runtime — secret không bao giờ lưu trong K8s etcd.
Container image security chain:
- Image signing với cosign:
cosign sign --key cosign.key myregistry/myimage:tag. Verify:cosign verify --key cosign.pub myregistry/myimage:tag. Đảm bảo image không bị tamper giữa build và deploy. - Notary v2 (notation): CNCF standard cho supply chain security, tích hợp với OCI registries (ECR, ACR, GCR).
- SBOM (Software Bill of Materials): Syft generate SBOM (SPDX/CycloneDX format) — danh sách tất cả dependencies trong image. Grype scan SBOM cho CVEs. SBOM là yêu cầu trong US Executive Order 14028 (Improving Nation's Cybersecurity).
- Admission control: Kubernetes Admission Webhook + Connaisseur/Kyverno enforce "only signed images from trusted registry" — reject pods với unsigned images.
2. Bài thực hành / Hands-on lab
Lab 1 — Azure DevOps Pipeline Security: Trivy + SAST + Secrets Management
OS: Any · Tool: Azure CLI.
- Kiểm tra Azure DevOps pipelines và variable groups (tìm secrets lưu sai chỗ):
# Kiểm tra pipelines và variable groups
az pipelines list --org https://dev.azure.com/myorg --project myproject -o table 2>/dev/null || \
echo "Install Azure DevOps extension: az extension add --name azure-devops"
az pipelines variable-group list \
--org https://dev.azure.com/myorg \
--project myproject -o table 2>/dev/null
# Tạo secret trong Azure Key Vault (đúng cách)
az keyvault secret set \
--vault-name myVault \
--name "appDbPassword" \
--value "$(openssl rand -base64 32)" \
--description "Application database password - auto-generated"
# Xem secret metadata (không xem value)
az keyvault secret show \
--vault-name myVault \
--name "appDbPassword" \
--query "{Name:name,Created:attributes.created,Expires:attributes.expires,Enabled:attributes.enabled}" \
-o json
Ví dụ Azure DevOps pipeline YAML với security gates:
# azure-pipeline-secure.yml
trigger:
branches:
include: [ main, develop ]
stages:
- stage: SecurityScan
displayName: 'Security Gates'
jobs:
- job: SAST
steps:
- task: UsePythonVersion@0
inputs:
versionSpec: '3.11'
# SAST with Semgrep
- script: |
pip install semgrep
semgrep --config=auto --error --json > semgrep-results.json
python3 -c "
import json
r = json.load(open('semgrep-results.json'))
highs = [f for f in r.get('results',[]) if f.get('extra',{}).get('severity') in ['ERROR','WARNING']]
print(f'SAST findings: {len(highs)} HIGH/CRITICAL')
if highs: exit(1)
"
displayName: 'Semgrep SAST Scan'
# SCA with OWASP Dependency Check
- script: |
docker run --rm \
-v $(Build.SourcesDirectory):/src \
owasp/dependency-check:latest \
--scan /src --format JSON --out /src/dc-report \
--failOnCVSS 7
displayName: 'OWASP Dependency Check'
- job: ContainerScan
steps:
# Container image vulnerability scan
- script: |
docker build -t myapp:$(Build.BuildId) .
docker run --rm \
-v /var/run/docker.sock:/var/run/docker.sock \
aquasec/trivy:latest image \
--severity HIGH,CRITICAL \
--exit-code 1 \
myapp:$(Build.BuildId)
displayName: 'Trivy Image Scan - Block on CRITICAL'
✅ Kết quả mong đợi / Expected output: Key Vault secret tạo thành công với auto-generated random password. Pipeline YAML: Semgrep exit code 1 (block build) nếu có SAST findings severity ERROR. Trivy exit code 1 nếu có CRITICAL CVEs — build bị dừng, không deploy image vulnerable. Variable groups không nên chứa plaintext passwords — chỉ Key Vault references.
Lab 2 — API Security Testing với curl + OWASP ZAP
OS: Ubuntu 22.04 · Tool: Bash + curl + OWASP ZAP.
#!/bin/bash
# API Security testing script
API_BASE="https://api.example.com/v1"
echo "=== Test 1: Authentication bypass ==="
# Attempt access with invalid Bearer token
HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" \
-H "Authorization: Bearer invalidtoken123" \
"$API_BASE/admin/users")
echo "Invalid token response: $HTTP_CODE (expected: 401 or 403)"
echo ""
echo "=== Test 2: SQL Injection in query parameter ==="
# Test SQLi in query string
RESPONSE=$(curl -s -v \
-X GET "$API_BASE/users?id=1%27%20OR%20%271%27%3D%271" \
2>&1 | grep -E "< HTTP|error|SQL|syntax")
echo "SQLi test response headers:"
echo "$RESPONSE"
echo ""
echo "=== Test 3: OWASP ZAP API Scan ==="
# Full automated API security scan (requires ZAP running or Docker)
# docker run --rm -v $(pwd):/zap/wrk:rw \
# ghcr.io/zaproxy/zaproxy:stable \
# zap-api-scan.py \
# -t https://api.example.com/openapi.json \
# -f openapi \
# -r /zap/wrk/zap-report.html \
# -J /zap/wrk/zap-report.json \
# -z "-config api.disablekey=true"
echo "(ZAP scan: replace with actual API URL and OpenAPI spec path)"
echo ""
echo "=== Test 4: Rate limiting check ==="
# Send 20 rapid requests and check for 429 Too Many Requests
for i in $(seq 1 20); do
CODE=$(curl -s -o /dev/null -w "%{http_code}" "$API_BASE/health")
echo -n "$CODE "
done
echo ""
echo "If no 429 seen above: Rate limiting may not be configured!"
✅ Kết quả mong đợi / Expected output: Test 1: 401/403 = authentication working. Nếu 200 = critical vulnerability. Test 2: phải không thấy SQL error messages — nếu có = injection vulnerability exposed. Test 4: sau 10-15 requests nên thấy 429 Too Many Requests — nếu tất cả 200 = rate limiting chưa cấu hình. ZAP report HTML chứa findings phân loại theo risk level (High/Medium/Low).
3. Tình huống doanh nghiệp / Real-world scenario
Bối cảnh:
Một startup SaaS B2B phát hiện trong log rằng AWS access keys của họ đã bị exfiltrate từ một public GitHub repository (developer commit nhầm). Attacker đã dùng keys để tạo EC2 instances cho crypto mining trước khi bị phát hiện. Security team cần post-incident hardening và ngăn tái diễn.
Root cause & Remediation:
- Root cause: AWS access keys hardcoded trong application config, committed to public GitHub. Không có pre-commit hook để detect secrets. Không có GitGuardian/TruffleHog monitoring.
- Immediate response: Revoke compromised keys ngay lập tức (
aws iam delete-access-key). Rotate tất cả credentials. Enable AWS GuardDuty để detect subsequent unauthorized activity. - OWASP CN-5 remediation: Migrate từ static access keys sang IAM Roles (EC2 instance profile). Cấu hình AWS Secrets Manager cho database credentials với auto-rotation 30 ngày. Add pre-commit hook:
detect-secrets scanblock commits chứa high-entropy strings. - Pipeline hardening (CN-4): Implement GitHub Advanced Security secret scanning. Thêm Trivy secret scan trong CI/CD. Enforce branch protection rules: require PR review, no force push.
- Monitoring: CloudTrail → EventBridge rule alert on
RunInstancestừ unfamiliar regions. Budget alert nếu spending tăng bất thường >20%.
Bài học CCSP: Supply chain security (CN-8) và secrets management (CN-5) là hai trong số những vectors phổ biến nhất. Defense: không bao giờ dùng static long-lived credentials — luôn dùng IAM Roles hoặc managed identities.
4. Tự kiểm tra / Knowledge check
- Giải thích "shift-left security" và lợi ích về chi phí so với phát hiện lỗ hổng ở production. Nêu 3 security tools tương ứng với 3 giai đoạn khác nhau trong CI/CD pipeline.
- OWASP Cloud-Native Top 10 khác gì so với OWASP Web Application Top 10 truyền thống? Lấy 2 ví dụ về vulnerabilities đặc thù cho cloud-native context.
- mTLS giải quyết vấn đề gì mà TLS thông thường không giải quyết được? Trade-off khi implement Istio service mesh là gì?
- So sánh 3 tier của secrets management: environment variables, Kubernetes Secrets, và HashiCorp Vault. Khi nào upgrade từ K8s Secrets sang external vault?
- Container image signing với cosign bảo vệ chống lại loại tấn công nào trong software supply chain? Mô tả luồng từ build đến deployment.
- Một microservice gọi API của microservice khác với HTTP (không có TLS). Liệt kê tất cả security risks và đề xuất remediation với service mesh.