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:

  1. Save the image to a tar file
  2. Extract and examine individual layers
  3. Recover the "deleted" secrets file
  4. 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:

  1. The specific check that failed
  2. The CIS benchmark control it maps to
  3. The risk if left unremediated
  4. The specific command or configuration change to fix it
  5. 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:

  1. Start a privileged container: docker run --privileged -it alpine sh
  2. From inside the container, enumerate the host's block devices
  3. Mount the host root filesystem
  4. Read /etc/shadow from the host
  5. Write a proof-of-concept cron job that would establish a reverse shell on the host
  6. 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:

  1. List all running containers
  2. Inspect a specific container's configuration
  3. Create a new container with host filesystem access
  4. Start the container and exec a command in it
  5. 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:

  1. Create a namespace called insecure-app
  2. Create a ServiceAccount with cluster-admin ClusterRoleBinding
  3. Deploy a pod using this ServiceAccount
  4. From inside the pod, enumerate all permissions
  5. Demonstrate secrets access across namespaces
  6. Fix the RBAC configuration to follow least privilege
  7. Verify the fix by repeating the enumeration

Provide all YAML manifests and commands.


Exercise 8: Kubernetes Secret Discovery

Difficulty: Intermediate

In your Minikube lab:

  1. Create secrets in three different ways: as environment variables, as mounted volumes, and as Kubernetes Secret objects
  2. Deploy a pod that uses each method
  3. From a separate pod with read access to secrets, find and decode each secret
  4. Check if secrets are encrypted at rest in etcd
  5. Recommend and implement encryption at rest for etcd
  6. 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:

  1. Create namespaces: frontend, backend, database
  2. Deploy simple HTTP server pods in each
  3. Verify that pods can communicate across namespaces (no network policies)
  4. Implement network policies that: - Allow frontend pods to reach backend only on port 8080 - Allow backend to reach database only on port 5432 - Deny all other inter-namespace traffic
  5. Verify the policies work by testing allowed and denied connections
  6. 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:

  1. Create a Dockerfile that uses a base image, installs dependencies from pip, and copies application code
  2. Use Trivy to scan the base image and document all CVEs
  3. Use Syft to generate an SBOM
  4. Check if image signing is implemented (cosign)
  5. Verify image integrity by comparing digests
  6. Create a "compromised" version of a dependency and demonstrate how it would propagate
  7. Implement and test defenses: digest pinning, signature verification, admission controller policies

Exercise 11: Kubelet API Exploitation

Difficulty: Advanced

In your lab environment:

  1. Identify the kubelet API endpoint on your Minikube node
  2. Attempt unauthenticated access to the kubelet API
  3. If authentication is required, use a valid token to access the API
  4. List all pods running on the node via the kubelet API
  5. Execute a command in a pod through the kubelet API (bypassing kubectl/API server)
  6. Explain why kubelet API access is dangerous even when the API server is properly secured
  7. 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):

  1. Deploy a pod in your Kubernetes cluster
  2. Attempt to access the cloud provider's Instance Metadata Service (IMDS)
  3. If accessible, extract IAM/service account credentials
  4. Demonstrate what actions these credentials allow
  5. Implement defenses: - Block IMDS access via network policy - Use IMDSv2 (hop limit) where applicable - Implement Pod Identity / Workload Identity
  6. 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:

  1. Pods running as root
  2. Pods with privileged security context
  3. Missing resource limits
  4. Default service account usage
  5. Overpermissioned RBAC roles (wildcard verbs/resources)
  6. Missing network policies per namespace
  7. Secrets not encrypted at rest
  8. Exposed services (NodePort, LoadBalancer)
  9. Pods with host namespace access (hostPID, hostNetwork, hostIPC)
  10. 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:

  1. Start with a vulnerable web application running in a Kubernetes pod
  2. Exploit the web application vulnerability to gain a shell in the pod
  3. Enumerate the Kubernetes environment from within the pod
  4. Discover and decode secrets
  5. Use discovered credentials to access another service
  6. Attempt to escalate privileges via RBAC misconfiguration
  7. Attempt a container escape
  8. Document the full attack chain with timestamps, commands, and evidence
  9. 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:

  1. Install the admission controller
  2. Write policies that enforce: - No privileged containers - No containers running as root - Required resource limits on all pods - No latest image tags - Required image registry allowlist - No host path mounts
  3. Test each policy by attempting to deploy violating resources
  4. Test that compliant resources are accepted
  5. Document the policies and their security rationale

Exercise 16: Container Runtime Comparison

Difficulty: Intermediate

Research and compare the security properties of different container runtimes:

  1. runc — Standard OCI runtime
  2. gVisor (runsc) — Application kernel providing system call interception
  3. 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:

  1. Deploy a "compromised" pod that runs a crypto miner (simulate with a CPU-intensive process)
  2. Using Kubernetes audit logs and runtime monitoring (Falco or similar), detect the compromise
  3. Perform forensic analysis: - Capture the container's filesystem - Analyze network connections - Review process listings - Examine Kubernetes audit logs
  4. Contain the incident (isolate the pod without destroying evidence)
  5. 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:

  1. Create a simple application with a Dockerfile
  2. 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
  3. Test the pipeline by introducing each type of issue and verifying it is caught
  4. 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:

  1. Sensitive keys in codebases
  2. DIND (Docker-in-Docker) exploitation
  3. SSRF in Kubernetes pod
  4. Container escape to host
  5. Docker CIS benchmarking
  6. Kubernetes CIS benchmarking
  7. Attacking private registry
  8. NodePort exposed service
  9. Helm v2 tiller deployment
  10. 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.