This lesson combines 2 topics: Container Security, Kubernetes Security.
Learning Objectives
- Understand the container threat model: the shared kernel makes containers "weaker" than VMs
- Choose a secure base image: distroless, Alpine, Debian slim — the trade-offs
- Do not run containers as
root: USER directive, non-root UID, file permissions - Handle secrets correctly at build time and runtime (BuildKit secrets, env injection)
- Scan images with Trivy in CI and with ECR scan-on-push
- Know the classic container escape CVEs: CVE-2019-5736 (runc), CVE-2022-0492 (cgroup)
- Configure runtime hardening: read-only rootfs, seccomp profile, AppArmor/SELinux
- Know the Kubernetes threat surface: API server, kubelet, etcd, workload
- Apply Pod Security Standards (Privileged / Baseline / Restricted), which replace the old PSP
- Design RBAC correctly: Role/ClusterRole, RoleBinding/ClusterRoleBinding, ServiceAccount
- Configure NetworkPolicy: default-deny, ingress/egress rules
- Manage secrets safely: understand the base64 trap, use External Secrets Operator + AWS Secrets Manager/Vault
- Deploy a policy engine: OPA Gatekeeper or Kyverno
- Audit the cluster with kube-bench (CIS benchmark) and kubescape
Part 1: Container Security
1. Threat model: Container vs VM
The weakness of containers: if an attacker breaks out of the namespace/cgroup (container escape), they stand directly on the host kernel — and own the whole host. A VM has to break out through the hypervisor (much harder).
| Attack layer | Container | VM |
|---|---|---|
| Application bug | Equivalent | Equivalent |
| Image supply chain | High (pulling public images) | Lower (AMIs are rarely pulled at random) |
| Kernel vulnerability | Every container is affected | Only 1 VM is affected (if the guest kernel differs from the host) |
| Runtime escape | runc, containerd bugs | Hypervisor bugs (very rare) |
| Cross-tenant | Needs PSS Restricted + gVisor/Kata | Strong by default |
Principle: for multi-tenant workloads, use Firecracker (used by Lambda, Fargate), Kata Containers, or gVisor to get VM-grade isolation with a container experience.
2. Image security: choosing a base image
The base image spectrum, from "fat" to "minimal"
| Base | Size | Shell? | Package manager? | Use case |
|---|---|---|---|---|
ubuntu:22.04 | ~80 MB | Yes (bash) | apt | Debug, full env |
debian:12-slim | ~30 MB | Yes (bash) | apt | Production when you need libc + shell |
alpine:3.19 | ~7 MB | Yes (ash) | apk | Minimal production (musl libc) |
gcr.io/distroless/static | ~2 MB | No | No | Go binary, static link |
gcr.io/distroless/nodejs24-debian13 | ~80 MB | No | No | Node app, runtime only |
scratch | 0 MB | No | No | Fully static Go binary |
Distroless — "nothing to hack"
# Multi-stage build with distroless
FROM golang:1.22-alpine AS builder
WORKDIR /src
COPY . .
RUN CGO_ENABLED=0 go build -o /app/server ./cmd/server
# Runtime: only the binary + minimal libs, no shell, no apt
FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=builder /app/server /server
USER nonroot:nonroot
ENTRYPOINT ["/server"]
Distroless has no /bin/sh, apt, curl, wget — even if an attacker gets a shell in, there are no tools to pivot with. Trade-off: you cannot debug with docker exec; you have to use a kubectl debug ephemeral container.
Alpine vs Debian slim
Alpine uses musl libc (not glibc). Consequences:
- Some glibc-only binaries (e.g. precompiled Python wheels, libvips) do not run
- The DNS resolver behaves differently (Alpine has a DNS bug with long search domains)
- The image is tiny (~7 MB)
Debian slim uses glibc — broad compatibility, and the image is still small (~30 MB). A safer default for teams that do not want to debug musl quirks.
Minimize layers and .dockerignore
# ❌ BAD: many junk layers
FROM ubuntu:22.04
RUN apt-get update
RUN apt-get install -y curl
RUN apt-get install -y python3
RUN rm -rf /var/lib/apt/lists/*
# ✅ GOOD: 1 layer, cleaned up in the same layer
FROM ubuntu:22.04
RUN apt-get update && \
apt-get install -y --no-install-recommends curl python3 && \
rm -rf /var/lib/apt/lists/*
# .dockerignore — avoid COPYing junk (secrets, host node_modules)
.git
.env
.env.*
node_modules
*.log
**/Dockerfile
**/docker-compose*.yml
3. Do not run containers as root
The problem with running as root
# ❌ By default a Dockerfile runs with UID=0
FROM node:24
COPY . /app
WORKDIR /app
CMD ["node", "server.js"]
If an attacker gets RCE in the container and escapes, they are already root on the host. Even without escaping, root inside the container can:
- Read/write every file in the container filesystem
- Bind ports < 1024
- Modify volumes mounted from the host if they are not read-only
The correct non-root pattern
FROM node:24-alpine
WORKDIR /app
# 1. Copy source (still needs root to set ownership)
COPY --chown=node:node package*.json ./
RUN npm ci --omit=dev
COPY --chown=node:node . .
# 2. Drop privileges before CMD
USER node # the node image already has a `node` user, UID=1000
EXPOSE 3000 # >= 1024 so non-root can bind it
CMD ["node", "server.js"]
Create a new user if the base image has none
FROM debian:12-slim
# Create a non-root user with a fixed UID/GID
RUN groupadd --gid 10001 app && \
useradd --uid 10001 --gid 10001 --shell /sbin/nologin --no-create-home app
WORKDIR /app
COPY --chown=10001:10001 ./build /app
USER 10001:10001
ENTRYPOINT ["/app/server"]
Why a fixed UID? When Kubernetes mounts a PVC, file ownership follows the numeric UID. If an image rebuild changes the UID, the app loses permission to read its old data. A UID >= 10000 avoids clashing with system UIDs.
File permission gotcha
# ❌ Forgot --chown → the file belongs to root, the non-root user cannot write it
COPY app.py /app/app.py
USER app
CMD ["python", "/app/app.py"] # if the app needs to write /app/cache → fails
# ✅ Set ownership at copy time
COPY --chown=app:app app.py /app/app.py
4. Handling secrets in images
The wrong pattern (don't do this)
# ❌ The secret lives in a layer, everyone who pulls the image can see it
COPY .env /app/.env
ENV DATABASE_PASSWORD=hunter2
# All an attacker needs
docker history --no-trunc your-image:latest # sees the ENV value
docker save your-image | tar xO | grep -ai password # sees .env in the layer
The right pattern
Option 1 — BuildKit secrets (for build-time secrets such as an npm token)
# syntax=docker/dockerfile:1.6
FROM node:24-alpine
WORKDIR /app
COPY package*.json ./
RUN --mount=type=secret,id=npmrc,target=/root/.npmrc \
npm ci --omit=dev
COPY . .
CMD ["node", "server.js"]
# Build with a secret that is not stored in any layer
docker build --secret id=npmrc,src=$HOME/.npmrc -t app .
The secret is only mounted during the build step and is not in the final image.
Option 2 — Runtime injection (for runtime secrets)
# Docker Compose
docker run -e DATABASE_URL=$(aws secretsmanager get-secret-value ...) app
# Kubernetes — use a Secret object or External Secrets Operator (see Part 2 of this lesson)
# AWS ECS — use `secrets` in the Task Definition (pulled from Secrets Manager/SSM)
Option 3 — Sidecar / init container fetches the secret
An init container calls Vault/Secrets Manager and writes the secret to a shared volume (emptyDir tmpfs); the main container reads it from the volume. The secret never ends up in the image or in an env var (env vars leak easily via /proc/<pid>/environ).
5. Image scanning in CI
Trivy — scanning in CI
# .github/workflows/build.yml
name: Build & Scan
on: [push]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Build image
run: docker build -t app:${{ github.sha }} .
- name: Trivy scan
uses: aquasecurity/trivy-action@master
with:
image-ref: app:${{ github.sha }}
format: sarif
output: trivy-results.sarif
severity: CRITICAL,HIGH
exit-code: 1 # fail the build if there is a HIGH/CRITICAL
- name: Upload to GitHub Security
if: always()
uses: github/codeql-action/upload-sarif@v3
with:
sarif_file: trivy-results.sarif
Trivy detects:
- OS package vulnerabilities (Debian/Alpine/RHEL CVE database)
- Language deps vulnerabilities (npm, pip, Go modules)
- Misconfiguration (Dockerfile best practice)
- Secret strings in the image (private keys, tokens)
ECR scan-on-push
# Enable enhanced scanning (powered by Inspector)
aws ecr put-registry-scanning-configuration \
--scan-type ENHANCED \
--rules '[{
"scanFrequency": "CONTINUOUS_SCAN",
"repositoryFilters": [{"filter": "*", "filterType": "WILDCARD"}]
}]'
# Push the image, the scan runs automatically
docker tag app:latest 111111111111.dkr.ecr.us-east-1.amazonaws.com/app:latest
docker push 111111111111.dkr.ecr.us-east-1.amazonaws.com/app:latest
# View findings
aws ecr describe-image-scan-findings \
--repository-name app \
--image-id imageTag=latest
Enhanced scan (Inspector v2) continuously re-scans when new CVEs appear — not only at push time. Basic scan runs only once, at push.
6. Classic container escape CVEs
CVE-2019-5736 — runc escape
runc (the runtime used by Docker and containerd) allowed a malicious container to overwrite the runc binary on the host. The next time the host calls runc exec → it runs the attacker's code as root.
Fix: upgrade runc >= 1.0.0-rc7 (Docker >= 18.09.2, 2019); every release up to and including 1.0.0-rc6 is vulnerable. Lesson: a runtime CVE = every container on the host is affected. Patch the host kernel + runtime promptly.
CVE-2022-0492 — cgroup release_agent
A container with CAP_SYS_ADMIN (not granted by default, but many CI/CD platforms enable it) can write to /sys/fs/cgroup/release_agent so that the host runs a script when the cgroup empties → escape.
Fix: Linux kernel patch + do not grant CAP_SYS_ADMIN to containers (Kubernetes does not grant it by default). Do not use docker run --privileged for production workloads.
CVE-2024-21626 — runc leaky file descriptor ("Leaky Vessels")
runc <= 1.1.11 leaked a file descriptor /proc/self/fd/<n> pointing to the host filesystem → the container could cd outside via a symlink. Fix: upgrade runc >= 1.1.12.
General lessons
Defense in depth:
1. Patch the kernel + runc/containerd regularly
2. Drop CAP_SYS_ADMIN, CAP_NET_ADMIN if the app does not need them
3. Read-only rootfs so the attacker cannot write binaries
4. The default seccomp profile blocks dangerous syscalls
5. Non-root user — even after an escape there is no root on the host
7. Runtime hardening
Read-only root filesystem
# Docker
docker run --read-only --tmpfs /tmp:size=64M app
# Kubernetes
securityContext:
readOnlyRootFilesystem: true
runAsNonRoot: true
runAsUser: 10001
allowPrivilegeEscalation: false
capabilities:
drop: ["ALL"]
If the app writes logs → mount a separate volume / emptyDir for the directories it needs to write. Everything else is read-only by default → the attacker cannot drop binaries.
Seccomp profile — block dangerous syscalls
Seccomp (secure computing mode) filters the syscalls a container is allowed to make. Docker and containerd have a default profile that blocks ~44 rarely used syscalls (e.g. mount, reboot, kexec_load).
# Docker uses the default
docker run --security-opt seccomp=default.json app
# Custom profile for an app that only does HTTP
docker run --security-opt seccomp=./minimal.json app
The oci-seccomp-bpf-hook tool (Red Hat) records the syscalls the app actually uses and generates a minimal seccomp profile.
AppArmor / SELinux
- AppArmor (Ubuntu, Debian): path-based MAC. A profile declares "binary X may read /var/log/, may not open sockets". Docker has a default profile,
docker-default. - SELinux (RHEL, Fedora, Amazon Linux): label-based MAC. Every process and file has a security label; the policy decides which labels can interact with which.
Both provide yet another layer of defense — even if the attacker escapes the namespace, MAC stops them from accessing files outside the policy. Do not use --security-opt apparmor=unconfined in production.
Part 2: Kubernetes Security
1. The Kubernetes threat surface
| Component | Common vulnerabilities | Mitigation |
|---|---|---|
| kube-apiserver | Anonymous auth, unbounded RBAC, exposed port 6443 | Disable anonymous, audit log, NetworkPolicy/SG to restrict IPs |
| etcd | Plain-text secrets on disk, exposed port 2379 | Encryption-at-rest (EncryptionConfiguration), mTLS, never expose to the internet |
| kubelet | Port 10250 read/write API, anonymous requests | --anonymous-auth=false, --authorization-mode=Webhook |
| Container runtime | runc CVEs, images with CVEs | Patch runc, image scanning |
| Workload | Excessive permissions, container escape | Pod Security Standard, RBAC, NetworkPolicy |
Managed K8s (EKS, GKE, AKS) takes care of the control plane (apiserver, etcd, scheduler). You are still responsible for workloads, RBAC, network policy, and secret management — this is the Shared Responsibility model for K8s.
2. Pod Security Standards (PSS)
PSP (Pod Security Policy) was deprecated in K8s 1.21 and removed in 1.25. It is replaced by Pod Security Standards + the Pod Security Admission controller (built in since 1.25).
Three levels
| Level | Use case |
|---|---|
| Privileged | System daemons (CNI, CSI, monitoring agent) — only in specific namespaces |
| Baseline | Regular workloads that need no host access |
| Restricted | Production, multi-tenant workloads — required |
Applying PSS via namespace labels
apiVersion: v1
kind: Namespace
metadata:
name: prod
labels:
# enforce = reject violating pods; audit = log; warn = stderr warning
pod-security.kubernetes.io/enforce: restricted
pod-security.kubernetes.io/enforce-version: v1.28
pod-security.kubernetes.io/audit: restricted
pod-security.kubernetes.io/warn: restricted
A Pod that satisfies Restricted
apiVersion: v1
kind: Pod
metadata:
name: app
namespace: prod
spec:
automountServiceAccountToken: false # do not auto-mount if the app does not call the K8s API
securityContext:
runAsNonRoot: true
runAsUser: 10001
runAsGroup: 10001
fsGroup: 10001
seccompProfile:
type: RuntimeDefault
containers:
- name: app
image: app:1.0
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop: ["ALL"]
resources:
requests: { cpu: 100m, memory: 128Mi }
limits: { cpu: 500m, memory: 512Mi }
volumeMounts:
- { name: tmp, mountPath: /tmp }
volumes:
- { name: tmp, emptyDir: { medium: Memory, sizeLimit: 64Mi } }
3. RBAC: Role, ClusterRole, Binding, ServiceAccount
Telling them apart
| Object | Scope | Used for |
|---|---|---|
| Role | 1 namespace | Permissions within that namespace (Pod, Service, ConfigMap...) |
| ClusterRole | Whole cluster | Cluster-wide permissions (Node, PV) or reusable across NS |
| RoleBinding | 1 namespace | Grants a Role or ClusterRole to a subject within the NS |
| ClusterRoleBinding | Whole cluster | Grants a ClusterRole to a subject across all NS |
| ServiceAccount | 1 namespace | The pod's identity (default by default) |
Example: ServiceAccount + Role + Binding
---
apiVersion: v1
kind: ServiceAccount
metadata:
name: app-sa
namespace: prod
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: configmap-reader
namespace: prod
rules:
- apiGroups: [""]
resources: ["configmaps"]
resourceNames: ["app-config"] # only this specific ConfigMap
verbs: ["get", "list", "watch"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: app-config-read
namespace: prod
subjects:
- kind: ServiceAccount
name: app-sa
namespace: prod
roleRef:
kind: Role
name: configmap-reader
apiGroup: rbac.authorization.k8s.io
---
apiVersion: v1
kind: Pod
metadata:
name: app
namespace: prod
spec:
serviceAccountName: app-sa # use the new SA, not default
containers:
- { name: app, image: app:1.0 }
Anti-pattern: cluster-admin for a ServiceAccount
# ❌ DON'T do this
- kind: ServiceAccount
name: default
roleRef:
kind: ClusterRole
name: cluster-admin
A pod with a cluster-admin SA = RCE in the pod = the cluster is taken over. The most common source is a sloppy Helm chart that binds cluster-admin "to make installation easier".
Auditing RBAC
# List every binding to a subject
kubectl get rolebindings,clusterrolebindings -A -o json | \
jq '.items[] | select(.subjects[]?.name=="app-sa") | .metadata.name'
# Handy tools: rbac-lookup, rbac-tool
rbac-lookup app-sa --kind serviceaccount
# Check whether an identity can perform an action
kubectl auth can-i delete pods --as=system:serviceaccount:prod:app-sa
4. NetworkPolicy
By default K8s allows every pod to talk to every pod. NetworkPolicy is a stateless firewall at L3/L4 used to apply default-deny + allow only the traffic you need.
⚠ NetworkPolicy only takes effect if the CNI plugin supports it (Calico, Cilium, AWS VPC CNI with policy enforcement). Flannel by default does not enforce it.
Default deny all traffic
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny-all
namespace: prod
spec:
podSelector: {} # matches every pod in the NS
policyTypes:
- Ingress
- Egress
Allow specific traffic
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: api-allow
namespace: prod
spec:
podSelector:
matchLabels: { app: api }
policyTypes: [Ingress, Egress]
ingress:
- from:
- podSelector:
matchLabels: { app: web } # only web pods may reach api
ports:
- { protocol: TCP, port: 8080 }
egress:
- to: # api may call DNS
- namespaceSelector:
matchLabels: { kubernetes.io/metadata.name: kube-system }
podSelector:
matchLabels: { k8s-app: kube-dns }
ports:
- { protocol: UDP, port: 53 }
- to: # api may call RDS by IP
- ipBlock:
cidr: 10.0.20.0/24
ports:
- { protocol: TCP, port: 5432 }
Best practice
1. Namespace-level default-deny (1 NetworkPolicy that blocks all)
2. Per-app NetworkPolicy that explicitly allows ingress + egress
3. Don't forget egress DNS (port 53) — without it service discovery breaks
4. Test with "kubectl exec ... -- nc -zv target port" before rollout
Cilium also supports L7 policy (block HTTP method/path) and eBPF observability — layered on top of the standard NetworkPolicy.
5. Secret management
The K8s Secret base64 trap
apiVersion: v1
kind: Secret
metadata:
name: db
type: Opaque
data:
password: aHVudGVyMg== # ← NOT encryption, just base64 of "hunter2"
data.password is only base64-encoded (decode it with echo aHVudGVyMg== | base64 -d). Anyone who can run kubectl get secret can see it.
# By default it is stored as plain text in etcd (not encrypted)
kubectl exec -n kube-system etcd-master -- \
etcdctl get /registry/secrets/default/db --print-value-only
# → JSON with the password in plain text
The real layers of defense
- Encryption-at-rest for etcd: configure
EncryptionConfigurationwith a KMS provider (AWS KMS / GCP KMS / Vault). Managed EKS/GKE enable it by default. - RBAC on Secret objects: restrict
get secretsto only the ServiceAccounts that need it. - External secret store: the real secret lives outside K8s (AWS Secrets Manager, HashiCorp Vault), and K8s only holds a reference.
External Secrets Operator (ESO)
---
apiVersion: external-secrets.io/v1beta1
kind: SecretStore
metadata:
name: aws-sm
namespace: prod
spec:
provider:
aws:
service: SecretsManager
region: us-east-1
auth:
jwt: # IRSA: the pod assumes an IAM role via its ServiceAccount
serviceAccountRef:
name: app-sa
---
apiVersion: external-secrets.io/v1beta1
kind: ExternalSecret
metadata:
name: db-secret
namespace: prod
spec:
refreshInterval: 1h # auto-rotate
secretStoreRef:
name: aws-sm
kind: SecretStore
target:
name: db # name of the K8s Secret to sync
data:
- secretKey: password # key in the K8s Secret
remoteRef:
key: prod/app/db # path in AWS Secrets Manager
property: password
ESO + IRSA (IAM Role for ServiceAccount): pod identity = IAM role; ESO pulls the secret from AWS Secrets Manager and materializes it as a K8s Secret that you mount as usual. The real secret lives in Secrets Manager, with rotation, audit, and KMS encryption.
Vault Agent Injector
Annotate the pod → a Vault Agent sidecar mounts the secret into /vault/secrets/. The secret never exists in a K8s Secret object.
6. Admission Controller: OPA Gatekeeper vs Kyverno
An admission controller intercepts requests before the API server stores them in etcd. It is used to enforce cluster-wide policy.
OPA Gatekeeper
Uses Rego (OPA's DSL). Powerful and generic — but with a steep learning curve.
apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata:
name: k8srequiredlabels
spec:
crd:
spec:
names: { kind: K8sRequiredLabels }
validation:
openAPIV3Schema:
type: object
properties:
labels: { type: array, items: { type: string } }
targets:
- target: admission.k8s.gatekeeper.sh
rego: |
package k8srequiredlabels
violation[{"msg": msg}] {
required := input.parameters.labels
provided := input.review.object.metadata.labels
missing := required[_]
not provided[missing]
msg := sprintf("missing label %v", [missing])
}
---
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sRequiredLabels
metadata:
name: ns-must-have-owner
spec:
match:
kinds: [{ apiGroups: [""], kinds: ["Namespace"] }]
parameters:
labels: ["owner", "cost-center"]
Kyverno
YAML-based — easier to read and write than Rego. Popular with K8s-native teams.
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: require-non-root
spec:
validationFailureAction: Enforce
rules:
- name: check-runAsNonRoot
match:
any:
- resources:
kinds: [Pod]
validate:
message: "Containers must run as non-root"
pattern:
spec:
securityContext:
runAsNonRoot: true
Kyverno supports: validate, mutate (auto-add labels), generate (create a default NetworkPolicy when a NS is created), and image signature verification (cosign).
| Criterion | OPA Gatekeeper | Kyverno |
|---|---|---|
| Language | Rego (steep curve) | YAML (familiar) |
| Mutation | Yes (newer) | Yes (mature) |
| Use beyond K8s | Yes (OPA is generic) | K8s-only |
| Community | CNCF graduated | CNCF incubating |
| Image verify | Via extension | Built-in cosign |
7. Auditing the cluster: kube-bench, kubescape
kube-bench — CIS Kubernetes Benchmark
# Run on a node (assuming a kubeadm cluster)
docker run --rm --pid=host \
-v /etc:/etc:ro -v /var:/var:ro \
aquasec/kube-bench:latest run --targets node
# Sample output
# [PASS] 4.2.1 Ensure that the --anonymous-auth argument is set to false
# [FAIL] 4.2.6 Ensure that the --make-iptables-util-chains argument is set to true
# [WARN] 4.2.9 Ensure that the --event-qps argument is set to 0 or a level which ensures appropriate event capture
The CIS Benchmark contains hundreds of checks for apiserver flags, kubelet config, and etcd permissions. Most important for EKS: run with the target --benchmark eks-1.5.0 (the managed control plane bypasses many checks, so it focuses on nodes + workloads).
kubescape
# Scan against the NSA/CISA framework
kubescape scan framework nsa --submit=false
# Scan only the workloads in a namespace
kubescape scan --include-namespaces prod
It can be integrated into CI to fail a PR if a manifest violates best practices (no-resource-limits, allow-privilege-escalation...).
Review Questions
-
Why does a container sharing the same kernel as the host make its security boundary weaker than a VM's?
Show answer
Containers use namespaces + cgroups to isolate processes, but they all share the same kernel as the host. A kernel vulnerability or a bug in runc/containerd lets an attacker "break out" of the namespace and stand directly on the host kernel → full control of the host and every other container.
A VM has a hypervisor that creates its own virtualized hardware, and the guest kernel is separate from the host kernel. To escape, the attacker has to exploit a hypervisor vulnerability — a small, heavily audited surface. That is why sensitive multi-tenant setups usually use Firecracker/Kata (microVMs) instead of plain containers.
-
How does a distroless image differ from Alpine, and when should you choose distroless?
Show answer
Alpine still has a shell (
ash), a package manager (apk), and busybox utilities. Distroless removes all of that — only the app binary + minimal libs (libc, ssl certs, timezone). An attacker who gets a shell into distroless has nosh,curl, orwgetto pivot with.Choose distroless when: (1) the app is static (Go binary), (2) a simple Node/Python/Java runtime, (3) you do not need to debug inside the container. Trade-off: you cannot
docker exec sh— you have to use akubectl debugephemeral container or a separate debug image for dev. -
What is wrong with
COPY .env /app/.envin a Dockerfile, even if you delete the file afterwards?Show answer
Every
COPYcreates an immutable layer. Even if a later step runsRUN rm /app/.env, the file is still in the old layer — it is only "hidden" in the new layer. Anyone who pulls the image can see it withdocker history --no-truncordocker save | tar xO.Fix: use BuildKit secrets (
--mount=type=secret) for build-time secrets, or inject at runtime via env var/Secrets Manager. -
Why is running a container with
--privilegeddangerous?Show answer
--privilegedgrants all Linux capabilities, disables seccomp, and exposes host devices. The container can: (1) mount the host filesystem (/dev/sda), (2) load kernel modules, (3) escape via cgroup release_agent (CVE-2022-0492), (4) write to/proc/sys/*to tweak the host. RCE in the container = root on the host.Only use
--privilegedfor system tools (special Docker-in-Docker cases, kernel module loaders) — never for app workloads. In K8s, setallowPrivilegeEscalation: false,privileged: falsevia the Pod Security Standard. -
Why should a non-root user's UID be fixed and >= 10000?
Show answer
Fixed: K8s mounts PVs/PVCs by numeric UID (not name). If rebuilding the image changes the UID, the app loses permission to read the old data on the volume — causing an outage. Set a fixed UID (e.g.
10001) in the Dockerfile so it stays consistent across builds.>= 10000: UIDs < 1000 are usually reserved for users/system services on the host (root=0, daemon=1, sshd=74...). A clashing UID can cause permission confusion between the container and the host (especially when mounting a hostPath). A UID >= 10000 avoids clashes and is clearly a "container app user".
-
Why was PSP (Pod Security Policy) replaced by Pod Security Standards?
Show answer
PSP had many problems: (1) policies were separate K8s objects → hard to apply consistently, (2) RBAC between PSP and SA was complex and easy to mismatch silently, (3) ordering was undefined when several PSPs matched, (4) poor UX — admins had to write their own policies for each cluster.
PSS standardizes 3 levels (Privileged/Baseline/Restricted) — like "presets" — applied with a simple namespace label. Pod Security Admission is built in since K8s 1.25, with no extra controller to install. PSP was removed in 1.25.
-
Is a K8s Secret object "secure"? What do you have to do to really protect it?
Show answer
A K8s Secret is only base64-encoded, not encrypted. By default it is stored as plain text in etcd. Anyone with
get secretspermission in the NS, or who can read etcd, can see the value.The real layers of defense: (1) Encryption-at-rest for etcd with a KMS provider, (2) RBAC restricting
get secrets, (3) use an external secret store (Secrets Manager, Vault) — the real secret lives outside K8s, and K8s only holds a reference via ESO or the Vault Agent Injector. Most important of all: the secret gets its own rotation and audit log. -
Is NetworkPolicy actually enforced in every cluster?
Show answer
No. NetworkPolicy is a spec; enforcement depends on the CNI plugin. Calico, Cilium, AWS VPC CNI (with enforcement enabled), Azure CNI fully enforce it. Plain Flannel does not enforce it. Many teams apply NetworkPolicies while the cluster runs a CNI that does not enforce them → they think they have a firewall, but in reality the traffic is still open.
You must verify: create a blocking policy, exec into a test pod and run
nc -zvto see whether it is denied. -
Why is binding the
cluster-adminClusterRole to the default ServiceAccount dangerous?Show answer
Every pod in a namespace uses the
defaultSA by default. If thedefaultSA hascluster-admin, any pod in that NS has full cluster control via the API server. An attacker gets RCE in 1 pod → makes API calls with the mounted token (/var/run/secrets/kubernetes.io/serviceaccount/token) → creates a new Pod inkube-systemwith hostPath/→ takes over the node → takes over the cluster.Best practice: (1) do not grant
cluster-adminto workload SAs, (2)automountServiceAccountToken: falseif the pod does not call the K8s API, (3) create a dedicated SA with a minimal Role for each app. -
What is the most important difference between OPA Gatekeeper and Kyverno for a K8s team?
Show answer
The policy language. Gatekeeper uses Rego (OPA DSL) — powerful and generic (used for microservice authorization, Terraform validation...), but with a steep learning curve and hard to debug. Kyverno uses YAML, familiar to K8s admins — you write policies like manifests with no new DSL to learn, but it is less flexible for complex logic.
Choosing: a team that already uses OPA elsewhere (API gateway, Terraform) → Gatekeeper for consistency. A pure K8s team that prioritizes fast adoption → Kyverno. Kyverno also has built-in image signature verification (cosign) and generate policies (auto-create a NetworkPolicy/ResourceQuota when a NS is created) — Gatekeeper needs extensions for these.
Hands-on Exercises
Part 1: Container Security
# 1. Build an image with distroless and non-root
mkdir container-lab && cd container-lab
cat > app.go <<'EOF'
package main
import "net/http"
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("hello\n"))
})
http.ListenAndServe(":8080", nil)
}
EOF
cat > go.mod <<'EOF'
module app
go 1.22
EOF
cat > Dockerfile <<'EOF'
FROM golang:1.22-alpine AS builder
WORKDIR /src
COPY . .
RUN CGO_ENABLED=0 go build -o /out/app .
FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=builder /out/app /app
USER nonroot:nonroot
EXPOSE 8080
ENTRYPOINT ["/app"]
EOF
docker build -t app:distroless .
docker run -d -p 8080:8080 --name app --read-only --cap-drop ALL app:distroless
curl localhost:8080
# 2. Scan with Trivy
docker run --rm -v /var/run/docker.sock:/var/run/docker.sock \
aquasec/trivy:latest image --severity HIGH,CRITICAL app:distroless
# 3. Try to get a shell (there is no shell)
docker exec -it app /bin/sh # → exec failed: not found
# 4. Build with a BuildKit secret
DOCKER_BUILDKIT=1 docker build \
--secret id=npmtoken,src=$HOME/.npmrc \
-t app:secret-build .
# 5. Cleanup
docker rm -f app
Part 2: Kubernetes Security
# You need a cluster (minikube, kind, or a dev EKS)
kind create cluster --name sec-lab
# 1. Apply the restricted Pod Security Standard to a namespace
kubectl create namespace lab
kubectl label namespace lab \
pod-security.kubernetes.io/enforce=restricted \
pod-security.kubernetes.io/warn=restricted
# 2. Try to deploy a violating pod (runs as root) → rejected
kubectl run nginx -n lab --image=nginx:1.27
# → Error: violates PodSecurity "restricted:v1.28": ...
# 3. Deploy a pod that complies with PSS Restricted
cat <<'EOF' | kubectl apply -f -
apiVersion: v1
kind: Pod
metadata: { name: ok, namespace: lab }
spec:
automountServiceAccountToken: false
securityContext:
runAsNonRoot: true
runAsUser: 10001
seccompProfile: { type: RuntimeDefault }
containers:
- name: app
image: nginxinc/nginx-unprivileged:1.27
ports: [{ containerPort: 8080 }]
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities: { drop: ["ALL"] }
EOF
# 4. Create a default-deny NetworkPolicy + allow DNS
cat <<'EOF' | kubectl apply -f -
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata: { name: default-deny, namespace: lab }
spec: { podSelector: {}, policyTypes: [Ingress, Egress] }
EOF
# 5. Install Kyverno and write a policy
kubectl create -f https://github.com/kyverno/kyverno/releases/download/v1.12.0/install.yaml
# Sample policy: require an "owner" label on every pod
# 6. Run kube-bench
kubectl apply -f https://raw.githubusercontent.com/aquasecurity/kube-bench/main/job.yaml
kubectl logs job/kube-bench
# 7. Cleanup
kind delete cluster --name sec-lab
References
- Docker security overview
- Distroless images
- Trivy documentation
- BuildKit secrets
- Amazon ECR image scanning
- OWASP Docker Top 10
- Pod Security Standards
- Using RBAC Authorization
- Network Policies
- External Secrets Operator
- OPA Gatekeeper
- Kyverno docs
- CIS Kubernetes Benchmark