Mục tiêu chương / Learning objectives
- Phân tích rủi ro bảo mật của hypervisor và VM isolation trong môi trường multi-tenant cloud, bao gồm VM escape và cross-tenant attacks.
- Áp dụng container security best practices: Docker hardening, Kubernetes RBAC, NetworkPolicy, PodSecurityAdmission, và OPA Gatekeeper cho production workloads.
- Đánh giá attack surface của serverless functions (AWS Lambda/Azure Functions) và implement controls chống event injection và over-privileged execution roles.
- Thiết kế cloud network security với VPC/VNET segmentation, Security Groups, NACLs, WAF, và PrivateLink để loại bỏ public internet exposure.
- Implement cloud identity security: federated identity, managed identities, workload identity federation, và service account hardening.
- Sử dụng IaC security tools (Checkov, tfsec, CloudFormation Guard) và đánh giá compliance theo CIS AWS/Azure Foundations Benchmark.
1. Lý thuyết cốt lõi / Core theory
1.1. Virtualization Security — Hypervisor & VM Isolation (Virtualization security)
Nền tảng của cloud là virtualization. Hypervisor (Virtual Machine Monitor) là phần mềm quản lý VMs trên physical host. Hai loại:
- Type 1 (Bare-metal): Chạy trực tiếp trên hardware — VMware ESXi, Microsoft Hyper-V, AWS Nitro (custom ARM-based hypervisor), KVM. Performance tốt hơn, attack surface nhỏ hơn vì không có host OS.
- Type 2 (Hosted): Chạy trên host OS — VirtualBox, VMware Workstation. Thường dùng cho development, không cho production cloud.
VM Isolation & Security risks:
- VM Escape: Malicious VM khai thác lỗ hổng hypervisor để truy cập host hoặc VM khác. Rất hiếm nhưng catastrophic. Mitigated bởi: hypervisor patching, hardware-assisted virtualization (Intel VT-x/AMD-V), và nested virtualization disabled khi không cần.
- Cross-tenant risk: Trong public cloud multi-tenant, VMs của các khách hàng khác nhau chia sẻ physical hardware. Side-channel attacks (Spectre/Meltdown) có thể leak information qua CPU cache. CSP mitigate bằng microcode patches và dedicated hosts (AWS Dedicated Hosts, Azure Dedicated Hosts).
- Confidential Computing: Hardware-based Trusted Execution Environment (TEE) đảm bảo data-in-use được bảo vệ ngay cả với CSP. AWS Nitro Enclaves, Azure Confidential VMs (AMD SEV-SNP), GCP Confidential VMs.
1.2. Container Security — Docker & Kubernetes Hardening (Container security)
Docker hardening best practices:
- Chạy containers với non-root user:
USER 1001trong Dockerfile. Tránh--privilegedflag. - Read-only filesystem:
docker run --read-only. Mount chỉ những volume cần thiết. - Giới hạn Linux capabilities:
--cap-drop ALL --cap-add NET_BIND_SERVICE. Không cho phép privilege escalation:--security-opt no-new-privileges. - Dùng distroless hay minimal base images (Google Distroless, Alpine) để giảm attack surface.
- Image scanning: Trivy, Snyk, Clair — scan trước khi push lên registry.
Kubernetes security controls:
- RBAC (Role-Based Access Control): Mỗi ServiceAccount có Roles/ClusterRoles với least-privilege. Tránh cluster-admin binding rộng rãi.
- NetworkPolicy: Default deny-all, chỉ allow traffic cần thiết giữa pods. Implement bằng Calico, Cilium, hoặc native CNI plugin.
- PodSecurityAdmission (PSA): Thay thế PodSecurityPolicy (deprecated K8s 1.25). Ba profiles: Privileged, Baseline, Restricted. Production pods phải ở Restricted.
- OPA Gatekeeper: Policy-as-code — enforce custom policies như "no latest tag", "require resource limits", "no host networking". Policies viết bằng Rego language.
- Secrets management: Không hardcode secrets trong YAML. Dùng Kubernetes Secrets + RBAC, hoặc tốt hơn là External Secrets Operator kết nối với AWS Secrets Manager/Azure Key Vault.
1.3. Serverless Security — Lambda & Functions Attack Surface (Serverless security)
Serverless (FaaS) loại bỏ OS management nhưng tạo ra attack surface mới:
- Event injection: Input từ event triggers (S3 events, API Gateway, SQS) không được sanitize → SQL injection, command injection trong Lambda handler. Mitigation: input validation, parameterized queries, principle of least trust cho event sources.
- Over-privileged execution roles: Lambda execution role với
*actions là misconfiguration phổ biến nhất. Mỗi function nên có role riêng với chỉ permissions cần thiết (least privilege). AWS: checkaws lambda get-function-configuration --function-name X | jq .Rolerồi audit IAM role. - Dependency vulnerabilities: Serverless code package có thể chứa vulnerable libraries. Cần SCA (Software Composition Analysis) trong CI/CD pipeline trước khi deploy.
- Cold start & timing attacks: Reuse của execution environment có thể leak thông tin giữa invocations nếu code không clean up properly (in-memory state).
- SSRF in serverless: Lambda trong VPC có thể bị exploit để reach internal resources hoặc metadata endpoint (169.254.169.254). IMDSv2 (Instance Metadata Service v2) bắt buộc token-based access, giảm SSRF risk.
1.4. Cloud Network Security — VPC/VNET, WAF, PrivateLink (Cloud network security)
- VPC/VNET design: Segmentation bằng subnets (public/private/data). Public subnet: load balancers only. Private subnet: application servers. Data subnet: databases, với no internet access.
- Security Groups (AWS) / NSG (Azure): Stateful firewall ở instance/NIC level. Principle: default deny, whitelist only required ports/sources.
- NACLs (AWS Network ACLs): Stateless, ở subnet level. Bổ sung cho Security Groups — dùng để block known malicious IPs hoặc force deny.
- WAF (Web Application Firewall): AWS WAF, Azure WAF (Front Door/Application Gateway), GCP Cloud Armor. Protect against OWASP Top 10 attacks. Managed rules + custom rules.
- PrivateLink/VPC Peering: AWS PrivateLink & Azure Private Link: access cloud services (S3, Azure Storage) qua private network, không qua internet. VPC Peering: connect hai VPCs riêng biệt. Transit Gateway (AWS)/Virtual WAN (Azure): hub for multiple VPCs/VNets.
1.5. IaC Security & Cloud Identity Hardening (IaC security & identity)
Infrastructure as Code (IaC) Security:
- Terraform scanning: Checkov, tfsec, Terrascan scan Terraform code trước khi apply. Phát hiện: open security groups, unencrypted storage, public S3 buckets, missing logging.
- ARM Template validation: Azure What-If deployment + az deployment validate. Microsoft Defender for DevOps scan ARM/Bicep templates.
- CloudFormation Guard: AWS native policy-as-code cho CloudFormation templates. Rules viết bằng Guard DSL.
- Drift detection: AWS Config, Azure Policy, GCP Config Connector phát hiện khi actual cloud resources khác với IaC definition (configuration drift).
Cloud Identity Security:
- Federated Identity: SAML 2.0/OIDC federation từ corporate IdP (Azure AD, Okta) tới CSP. Không cần tạo cloud-native users — giảm identity sprawl.
- Managed Identities (Azure) / IAM Roles for EC2 (AWS): Workloads lấy credentials tự động từ metadata service, không cần hardcode access keys. Credentials rotate tự động.
- Workload Identity Federation (GCP): Cho phép workloads ngoài GCP (GitHub Actions, AWS Lambda) authenticate với GCP mà không cần service account key file.
- CIS Benchmarks: CIS AWS Foundations Benchmark v3.0 & CIS Azure Foundations Benchmark v2.0 là tiêu chuẩn hardening phổ biến nhất. Được map vào AWS Security Hub Security Standards và Microsoft Defender for Cloud Regulatory Compliance.
2. Bài thực hành / Hands-on lab
Lab 1 — Audit Azure NSG & AKS Security với PowerShell + kubectl
OS: Windows 11 · Tool: PowerShell + Az module + kubectl.
# Liệt kê tất cả NSGs và resource groups
Get-AzNetworkSecurityGroup | Select-Object Name, ResourceGroupName, Location | Format-Table
# Xem NSG rules bằng Azure CLI (dễ filter hơn)
az network nsg list -o table
# Tìm NSG rules cho phép Inbound từ Internet (CidrIp 0.0.0.0/0)
az network nsg rule list --nsg-name myNSG -g myRG `
--query "[?access=='Allow' && direction=='Inbound' && sourceAddressPrefix=='*']" `
-o table
# Kết nối AKS cluster
az aks get-credentials --resource-group myRG --name myAKS --overwrite-existing
# Kiểm tra tất cả pods trong tất cả namespaces
kubectl get pods -A -o wide
# Audit RBAC - xem tất cả ClusterRoleBindings với cluster-admin
kubectl get clusterrolebindings -o json | `
python3 -c "import json,sys; [print(b['metadata']['name'], '->', b.get('subjects','[]')) for b in json.load(sys.stdin)['items'] if b.get('roleRef',{}).get('name')=='cluster-admin']"
# Kiểm tra permissions của current service account
kubectl auth can-i --list --namespace default
✅ Kết quả mong đợi / Expected output: NSG list hiển thị tên, RG, location. NSG inbound rules với source * = overly permissive (finding). AKS pods list với namespace/node placement. ClusterRoleBindings với cluster-admin = audit carefully. kubectl auth can-i --list hiển thị permissions của current context — nên thấy limited set, không phải wildcard *.
Lab 2 — Container Security Audit với Docker inspect, Trivy & kube-bench
OS: Ubuntu 22.04 · Tool: Docker + Trivy + kube-bench.
# Cài đặt Trivy (image vulnerability scanner)
# curl -sfL https://raw.githubusercontent.com/aquasecurity/trivy/main/contrib/install.sh | sh -s -- -b /usr/local/bin
# Kiểm tra cấu hình security của container đang chạy
docker inspect mycontainer 2>/dev/null | python3 -c "
import json, sys
try:
c = json.load(sys.stdin)[0]
hc = c['HostConfig']
cfg = c['Config']
print('=== Container Security Audit ===')
print(f'Privileged: {hc.get(\"Privileged\", False)}')
print(f'User: {cfg.get(\"User\", \"root (WARNING!)\") or \"root (WARNING!)\"}')
print(f'Network Mode: {hc.get(\"NetworkMode\", \"bridge\")}')
print(f'Read-Only FS: {hc.get(\"ReadonlyRootfs\", False)}')
print(f'PID Mode: {hc.get(\"PidMode\", \"\")}')
caps_add = hc.get('CapAdd') or []
caps_drop = hc.get('CapDrop') or []
print(f'Caps Added: {caps_add}')
print(f'Caps Dropped: {caps_drop}')
except Exception as e:
print(f'Error: {e}. Run: docker run -d --name mycontainer nginx:alpine')
"
# Scan Docker image cho CVEs (thay nginx:alpine bằng image thực)
trivy image --severity HIGH,CRITICAL nginx:alpine 2>/dev/null | head -40
# Chạy CIS Kubernetes Benchmark (cần có cluster hoặc minikube)
# docker run --pid=host --network=host --userns=host --cap-add=audit_write \
# -v /etc:/etc:ro -v /var:/var:ro -v /usr/lib:/usr/lib:ro \
# aquasec/kube-bench:latest --benchmark cis-1.8 2>/dev/null | grep -E "FAIL|WARN" | head -20
echo "--- Checking for containers running as root ---"
docker ps -q | xargs -I{} docker inspect {} \
--format '{{.Name}} User={{.Config.User}} Privileged={{.HostConfig.Privileged}}' 2>/dev/null
✅ Kết quả mong đợi / Expected output: Container audit hiển thị Privileged: false (good), User: 1001 (good, not root), ReadOnlyRootfs: true (good). Trivy scan hiển thị CVEs với severity HIGH/CRITICAL và CVE IDs — cần patch base image. kube-bench FAIL items là remediation priorities. Containers chạy User="" nghĩa là root — critical finding trong CIS Benchmark.
3. Tình huống doanh nghiệp / Real-world scenario
Bối cảnh:
Một công ty e-commerce deploy microservices trên Azure Kubernetes Service (AKS). Trong pentest, red team phát hiện: (1) Pod chạy với privileged=true, (2) ServiceAccount có ClusterAdmin binding, (3) NetworkPolicy không được cấu hình — mọi pod có thể communicate với nhau. Red team escalate từ compromised frontend pod để access database pod và extract customer data.
Remediation plan:
- Immediate (0-4h): Remove privileged=true từ tất cả pod specs. Revoke ClusterAdmin từ application ServiceAccounts. Enable Pod Security Admission ở Restricted profile cho production namespace.
- Network segmentation (4-8h): Deploy default-deny NetworkPolicy:
kubectl apply -f default-deny-all.yaml. Tạo specific allow policies: frontend → backend API (port 8080), backend → database (port 5432 only). - Identity hardening (8-24h): Tạo separate ServiceAccount cho mỗi service với minimal permissions. Enable AKS Workload Identity (replace pod-managed identity). Audit RBAC với
kubectl-who-cantool. - Ongoing: Integrate Trivy vào CI/CD pipeline — block deployment nếu có CRITICAL CVEs. Enable Microsoft Defender for Containers — real-time threat detection cho AKS.
Bài học CCSP: Container/Kubernetes security là "defense-in-depth" — không có single control đủ. Kết hợp: image scanning (supply chain) + PSA (runtime) + NetworkPolicy (lateral movement) + RBAC (privilege) + monitoring (detection).
4. Tự kiểm tra / Knowledge check
- VM Escape attack là gì? CSP mitigate risk này như thế nào trong kiến trúc AWS Nitro và Azure Hyper-V? Tại sao Confidential Computing không thay thế hoàn toàn VM isolation?
- So sánh Kubernetes PodSecurityAdmission (PSA) với PodSecurityPolicy (PSP) đã deprecated. Tại sao PSP bị loại bỏ? Cách migrate sang PSA Restricted profile?
- Serverless event injection attack khác gì với traditional SQL injection? Lấy ví dụ với AWS Lambda trigger từ API Gateway và cách mitigate.
- Giải thích sự khác biệt giữa Security Groups và NACLs trong AWS. Khi nào dùng NACL thay vì Security Group?
- IaC drift detection là gì và tại sao quan trọng cho cloud security? Checkov và AWS Config phục vụ use case khác nhau như thế nào?
- Managed Identity (Azure) và IAM Role for EC2 (AWS) giải quyết vấn đề gì mà static access keys không thể? Rủi ro gì vẫn còn tồn tại?