Chapter 32 Exercises: Container and Kubernetes Security
Exercise 1: Container Detection and Enumeration
Difficulty: Beginner
You have gained a shell on a Linux system during a penetration test. Write a script that determines whether you are inside a container, identifies the container runtime (Docker, containerd, CRI-O), and enumerates key information about the container environment.
Your script should check:
- /proc/1/cgroup for container indicators
- The presence of /.dockerenv
- Environment variables indicating Kubernetes
- Mounted service account tokens
- Available capabilities
- Mounted filesystems of interest
Expected Output: A summary report listing all findings and their security implications.
Exercise 2: Dockerfile Security Audit
Difficulty: Beginner
Review the following Dockerfile and identify all security issues. For each issue, explain the risk and provide a corrected version.
FROM ubuntu:latest
RUN apt-get update && apt-get install -y python3 python3-pip curl wget netcat
ENV DATABASE_PASSWORD=SuperSecret123!
ENV API_KEY=sk-proj-a1b2c3d4e5f6g7h8
COPY . /app
WORKDIR /app
RUN pip3 install -r requirements.txt
EXPOSE 22 80 443 8080
CMD ["python3", "app.py"]
List at least eight distinct security issues and provide a hardened Dockerfile.
Exercise 3: Docker Image Layer Forensics
Difficulty: Intermediate
A developer claims they removed secrets from a Docker image by adding a RUN rm /app/config/secrets.json command in a later layer. Using docker save, tar, and manual inspection, demonstrate why this is insufficient. Write a step-by-step procedure to:
- Save the image to a tar file
- Extract and examine individual layers
- Recover the "deleted" secrets file
- Report the finding with remediation guidance
Exercise 4: Docker Bench Security Assessment
Difficulty: Intermediate
Run Docker Bench for Security against your lab Docker installation. For each WARN finding, document:
- The specific check that failed
- The CIS benchmark control it maps to
- The risk if left unremediated
- The specific command or configuration change to fix it
- Any potential operational impact of the fix
Prioritize findings into Critical, High, Medium, and Low categories.
Exercise 5: Privileged Container Escape
Difficulty: Intermediate
In your lab environment, perform the following:
- Start a privileged container:
docker run --privileged -it alpine sh - From inside the container, enumerate the host's block devices
- Mount the host root filesystem
- Read
/etc/shadowfrom the host - Write a proof-of-concept cron job that would establish a reverse shell on the host
- Document the full attack chain and recommend mitigations
⚠️ Safety Warning: Only perform this in your personal lab environment. Never attempt container escapes in shared or production environments.
Exercise 6: Docker Socket Exploitation
Difficulty: Intermediate
Set up a container with the Docker socket mounted (-v /var/run/docker.sock:/var/run/docker.sock). Using only curl (not the Docker CLI), interact with the Docker API to:
- List all running containers
- Inspect a specific container's configuration
- Create a new container with host filesystem access
- Start the container and exec a command in it
- Read a sensitive file from the host
Document each API call with the full URL, method, headers, and request body.
Exercise 7: Kubernetes RBAC Enumeration
Difficulty: Intermediate
Using kubectl in your Minikube lab, create an intentionally overprivileged setup:
- Create a namespace called
insecure-app - Create a ServiceAccount with
cluster-adminClusterRoleBinding - Deploy a pod using this ServiceAccount
- From inside the pod, enumerate all permissions
- Demonstrate secrets access across namespaces
- Fix the RBAC configuration to follow least privilege
- Verify the fix by repeating the enumeration
Provide all YAML manifests and commands.
Exercise 8: Kubernetes Secret Discovery
Difficulty: Intermediate
In your Minikube lab:
- Create secrets in three different ways: as environment variables, as mounted volumes, and as Kubernetes Secret objects
- Deploy a pod that uses each method
- From a separate pod with read access to secrets, find and decode each secret
- Check if secrets are encrypted at rest in etcd
- Recommend and implement encryption at rest for etcd
- Document the entire process with security implications of each storage method
Exercise 9: Network Policy Implementation and Bypass Testing
Difficulty: Intermediate
Set up a multi-namespace Kubernetes environment:
- Create namespaces:
frontend,backend,database - Deploy simple HTTP server pods in each
- Verify that pods can communicate across namespaces (no network policies)
- Implement network policies that:
- Allow
frontendpods to reachbackendonly on port 8080 - Allowbackendto reachdatabaseonly on port 5432 - Deny all other inter-namespace traffic - Verify the policies work by testing allowed and denied connections
- Attempt to bypass the network policies through DNS, metadata services, or other vectors
Exercise 10: Container Image Supply Chain Assessment
Difficulty: Advanced
Perform a supply chain security assessment on a multi-stage build process:
- Create a Dockerfile that uses a base image, installs dependencies from pip, and copies application code
- Use Trivy to scan the base image and document all CVEs
- Use Syft to generate an SBOM
- Check if image signing is implemented (cosign)
- Verify image integrity by comparing digests
- Create a "compromised" version of a dependency and demonstrate how it would propagate
- Implement and test defenses: digest pinning, signature verification, admission controller policies
Exercise 11: Kubelet API Exploitation
Difficulty: Advanced
In your lab environment:
- Identify the kubelet API endpoint on your Minikube node
- Attempt unauthenticated access to the kubelet API
- If authentication is required, use a valid token to access the API
- List all pods running on the node via the kubelet API
- Execute a command in a pod through the kubelet API (bypassing kubectl/API server)
- Explain why kubelet API access is dangerous even when the API server is properly secured
- Implement kubelet authentication and authorization hardening
Exercise 12: Cloud Metadata Service from Pods
Difficulty: Advanced
In a simulated cloud environment (or actual cloud if available):
- Deploy a pod in your Kubernetes cluster
- Attempt to access the cloud provider's Instance Metadata Service (IMDS)
- If accessible, extract IAM/service account credentials
- Demonstrate what actions these credentials allow
- Implement defenses: - Block IMDS access via network policy - Use IMDSv2 (hop limit) where applicable - Implement Pod Identity / Workload Identity
- Verify each defense's effectiveness
Exercise 13: Kubernetes Security Audit Script
Difficulty: Advanced
Write a comprehensive Python script that audits a Kubernetes cluster for security issues. The script should check:
- Pods running as root
- Pods with privileged security context
- Missing resource limits
- Default service account usage
- Overpermissioned RBAC roles (wildcard verbs/resources)
- Missing network policies per namespace
- Secrets not encrypted at rest
- Exposed services (NodePort, LoadBalancer)
- Pods with host namespace access (hostPID, hostNetwork, hostIPC)
- Missing pod security standards
The script should output a structured report with severity ratings and remediation steps.
Exercise 14: Multi-Stage Container Attack Chain
Difficulty: Advanced
Design and execute a complete attack chain in your lab:
- Start with a vulnerable web application running in a Kubernetes pod
- Exploit the web application vulnerability to gain a shell in the pod
- Enumerate the Kubernetes environment from within the pod
- Discover and decode secrets
- Use discovered credentials to access another service
- Attempt to escalate privileges via RBAC misconfiguration
- Attempt a container escape
- Document the full attack chain with timestamps, commands, and evidence
- Write a penetration test report section for this finding
Exercise 15: Admission Controller Policy Design
Difficulty: Advanced
Using OPA Gatekeeper or Kyverno in your Minikube lab:
- Install the admission controller
- Write policies that enforce:
- No privileged containers
- No containers running as root
- Required resource limits on all pods
- No
latestimage tags - Required image registry allowlist - No host path mounts - Test each policy by attempting to deploy violating resources
- Test that compliant resources are accepted
- Document the policies and their security rationale
Exercise 16: Container Runtime Comparison
Difficulty: Intermediate
Research and compare the security properties of different container runtimes:
- runc — Standard OCI runtime
- gVisor (runsc) — Application kernel providing system call interception
- Kata Containers — Lightweight VMs for container isolation
For each runtime: - Describe the isolation mechanism - Identify strengths and weaknesses from a security perspective - Explain which container escape techniques are mitigated - Discuss performance trade-offs - Recommend use cases where each runtime is appropriate
Exercise 17: Incident Response — Compromised Container
Difficulty: Advanced
Simulate a container compromise incident:
- Deploy a "compromised" pod that runs a crypto miner (simulate with a CPU-intensive process)
- Using Kubernetes audit logs and runtime monitoring (Falco or similar), detect the compromise
- Perform forensic analysis: - Capture the container's filesystem - Analyze network connections - Review process listings - Examine Kubernetes audit logs
- Contain the incident (isolate the pod without destroying evidence)
- Write an incident report including timeline, impact, and remediation steps
Exercise 18: Secure CI/CD Pipeline for Containers
Difficulty: Advanced
Design and implement a secure CI/CD pipeline for container deployment:
- Create a simple application with a Dockerfile
- Set up a pipeline (GitHub Actions, GitLab CI, or Jenkins) that: - Lints the Dockerfile (hadolint) - Scans the built image for vulnerabilities (Trivy) - Checks for embedded secrets (Trufflehog, GitLeaks) - Signs the image (cosign) - Pushes to a private registry - Deploys to Kubernetes with admission controller validation
- Test the pipeline by introducing each type of issue and verifying it is caught
- Document the pipeline architecture and security controls
Bonus Challenge: Capture the Flag
Difficulty: Expert
Deploy Kubernetes Goat (https://madhuakula.com/kubernetes-goat/) in your lab and complete all scenarios:
- Sensitive keys in codebases
- DIND (Docker-in-Docker) exploitation
- SSRF in Kubernetes pod
- Container escape to host
- Docker CIS benchmarking
- Kubernetes CIS benchmarking
- Attacking private registry
- NodePort exposed service
- Helm v2 tiller deployment
- Analyzing crypto mining
Document your approach, findings, and key learnings for each scenario. Create a comprehensive write-up suitable for a blog post or internal knowledge base article.