SecurityPart 3: Cloud and infrastructure security
Chapter 10Container and Kubernetes security
In 2018 researchers found that Tesla's Kubernetes dashboard had no password, and attackers were using it to mine cryptocurrency on Tesla's cloud bill while a pod quietly held AWS credentials. You will learn what a container really is, how a cluster's identities and admission rules work, and how to turn a deployment like that into one an attacker would find boring.
After this chapter you can
- Explain the kernel features that make a container (namespaces, cgroups, capabilities, seccomp) and where isolation ends
- Scan and slim images with Trivy, rootless users and distroless bases
- Trace a request through the Kubernetes API server and secure each stage with RBAC and admission control
- Apply Pod Security Standards, network policies and a Kyverno policy to a real cluster
- Describe how runtime detection with Falco catches what prevention missed
A container is a process with a restricted view
A container is not a small virtual machine. It is an ordinary Linux process that the kernel shows a restricted view of the system and puts limits on. Every container on a host shares that host's single kernel, which is the fact that shapes everything else in this chapter.
| Kernel feature | What it restricts | Security meaning |
|---|---|---|
| PID namespace | Which processes it can see | Cannot signal host processes |
| Mount namespace | Which filesystem it sees | Has its own root, unless you mount host paths in |
| Network namespace | Interfaces, routes, ports | Own IP stack, isolated from host ports |
| User namespace | Mapping of UIDs | Root inside can be an unprivileged user outside |
| cgroups | CPU, memory, PIDs, I/O | Stops one container from starving the host |
| Capabilities | Pieces of root's power | Docker keeps 14 by default and drops the rest |
| seccomp | Which system calls are allowed | Default profiles block dozens of risky syscalls |
| LSM (AppArmor, SELinux) | File and resource access | A second fence if the others fail |
You can see this from any Linux host. Start a container, find its process ID on the host and look at its namespace links: they differ from PID 1's.
docker run -d --name demo nginx:stable
PID=$(docker inspect -f '{{.State.Pid}}' demo)
sudo ls -l /proc/$PID/ns # net, pid, mnt ... with different inode numbers
grep Cap /proc/$PID/status # capability bitmasks, far smaller than root'sHow containers escape
A container escape means code inside a container gains control of the host. Almost every real case falls into one of three buckets, and the first is by far the most common.
| Bucket | Real examples | What stops it |
|---|---|---|
| Misconfiguration | privileged: true, a hostPath mount of /, a mounted Docker socket (/var/run/docker.sock), hostPID | Admission control; no exploit is needed, so nothing else helps |
| Runtime bugs | CVE-2019-5736 let a container overwrite the host's runc binary; CVE-2024-21626 ("Leaky Vessels") leaked a host file descriptor through the working directory | Patching runc and containerd like any other critical software |
| Kernel bugs | Dirty Pipe (CVE-2022-0847) let an unprivileged process write to read-only files | Kernel patching, seccomp, dropped capabilities, sandboxed runtimes |
The first row matters most in practice. A privileged container with the host filesystem mounted is root on the node: chroot /host and you are there.
Image security: smaller, scanned, non-root
An image is a stack of filesystem layers plus metadata such as the default user and entrypoint. Everything in it is attack surface and a source of vulnerabilities. Three habits remove most of the risk.
Typical image
- Full distro base, shell, package manager
- Runs as root because nobody set
USER - Tagged
latest, contents change silently - Hundreds of packages to patch
Hardened image
- Distroless or minimal base, no shell
- Numeric non-root
USERin the Dockerfile - Pinned by tag and digest
- A handful of packages, scanned in CI
Distroless images (for example Google's gcr.io/distroless family or Chainguard's images) contain your app and its runtime libraries but no shell or package manager. An attacker who gets code execution cannot simply run sh, curl or apt. Multi-stage builds make this easy: compile in a full image, copy only the binary into the distroless one.
FROM golang:1.23 AS build
WORKDIR /src
COPY . .
RUN CGO_ENABLED=0 go build -o /app ./cmd/server
FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=build /app /app
USER 65532:65532
ENTRYPOINT ["/app"]Rootless has two meanings worth separating. A non-root container runs its process as a non-zero UID. Rootless mode runs the container engine itself (Docker or Podman) as an unprivileged user with user namespaces, so even root inside the container maps to an ordinary user on the host.
Trivy scans images, filesystems and Kubernetes manifests for known CVEs, misconfigurations and leaked secrets. Run it in CI and fail the build on fixable high and critical findings.
trivy image --severity HIGH,CRITICAL --ignore-unfixed nginx:stable
trivy config ./k8s/ # flags privileged pods, missing limits, hostPath mountsKubernetes through a security lens
Kubernetes is an API server with a database behind it. Every action, from kubectl apply to a controller scaling a deployment, is an HTTP request to the API server, and each request passes the same gates in order.
| Component | Why attackers want it | Baseline protection |
|---|---|---|
| API server | Full control of the cluster | Private endpoint, OIDC for humans, audit logging |
| etcd | Holds every Secret | Encryption at rest with KMS, reachable only by API server |
| kubelet (port 10250) | Run commands in any pod on the node | Anonymous auth off, webhook authorization |
| Cloud metadata | Node's cloud credentials | Block pod access, use workload identity |
| Dashboards and add-ons | Often over-privileged, sometimes unauthenticated | Do not expose, give minimal RBAC |
RBAC and service accounts
RBAC (role-based access control) grants verbs on resources. A Role holds permissions within one namespace, and a ClusterRole holds them cluster-wide. A RoleBinding or ClusterRoleBinding attaches a role to users, groups or service accounts. There are no deny rules, so the only way to restrict is to grant less.
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: read-config
namespace: shop
rules:
- apiGroups: [""]
resources: ["configmaps"]
verbs: ["get", "list", "watch"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: web-reads-config
namespace: shop
subjects:
- kind: ServiceAccount
name: web
namespace: shop
roleRef:
kind: Role
name: read-config
apiGroup: rbac.authorization.k8s.ioSome permissions are equivalent to cluster admin even though they do not look like it:
createon pods in a namespace: you can start a pod that mounts any service account in that namespace, or a privileged pod if admission allows it.getorliston secrets: every credential in the namespace.pods/exec: a shell in someone else's workload, with its token.escalate,bind,impersonate: grant or assume permissions you do not hold.nodes/proxy: talk to the kubelet API directly.
A service account is the identity a pod uses to call the API server. Kubernetes mounts a short-lived, audience-bound token into each pod by default at /var/run/secrets/kubernetes.io/serviceaccount/token. Most application pods never call the API, so set automountServiceAccountToken: false and the token is not there to steal. Check what an identity can do with kubectl auth can-i --list --as=system:serviceaccount:shop:web -n shop.
Pod Security Standards and admission control
Admission controllers run after authorization and can change (mutate) or reject (validate) objects before they are stored. This is where you enforce "no pod may run privileged", whatever RBAC allows.
The built-in Pod Security Admission controller enforces the three Pod Security Standards per namespace, using labels. It replaced PodSecurityPolicy, which was removed in Kubernetes 1.25.
| Level | Intent | Blocks, among others |
|---|---|---|
| Privileged | No restrictions, for system components | Nothing |
| Baseline | Stop known privilege escalations | Privileged, hostPath, hostNetwork, hostPID, added dangerous capabilities |
| Restricted | Current hardening best practice | All of baseline, plus root users, privilege escalation, capabilities beyond NET_BIND_SERVICE, missing seccomp profile |
Each namespace can set a level per mode: enforce rejects, audit logs, warn returns a warning to the client. A safe rollout is warn and audit first, then enforce once the warnings are gone.
For rules beyond those standards (allowed registries, required labels, no latest tags, signed images) you add a policy engine. Kyverno writes policies as Kubernetes resources, and its current ValidatingPolicy type uses CEL expressions, the same language as Kubernetes' built-in ValidatingAdmissionPolicy. OPA Gatekeeper is the main alternative and uses the Rego language.
apiVersion: policies.kyverno.io/v1
kind: ValidatingPolicy
metadata:
name: disallow-latest-tag
spec:
validationActions:
- Deny
matchConstraints:
resourceRules:
- apiGroups: [""]
apiVersions: [v1]
operations: [CREATE, UPDATE]
resources: [pods]
validations:
- expression: "object.spec.containers.all(c, c.image.contains(':') && !c.image.endsWith(':latest'))"
message: "Images must use an explicit tag other than latest."Network policies and secrets
By default every pod can reach every other pod in the cluster. A NetworkPolicy selects pods and lists what traffic may reach them (ingress) or leave them (egress). Once any policy selects a pod for a direction, everything not explicitly allowed in that direction is dropped. Policies are enforced by the CNI plugin (the component that wires pod networking), and a CNI without policy support silently ignores them.
Kubernetes Secrets are base64-encoded, not encrypted. Anyone who can read them through the API, or read etcd or its backups, has the plaintext. Harden them in layers:
- Turn on encryption at rest for Secrets, ideally with a cloud KMS provider.
- Restrict
getandliston secrets to the few identities that need them. - Prefer an external store (Vault, AWS Secrets Manager and similar) synced by the External Secrets Operator or mounted by the Secrets Store CSI driver.
- Better still, use workload identity so pods get short-lived cloud credentials and there is no static secret at all. Cloud identity and access explains the federation pattern.
Runtime detection with Falco
Prevention fails eventually, so you also watch what containers actually do. Falco, a CNCF graduated project, hooks system calls with eBPF and matches them against rules such as "a shell started inside a container" or "a process read a sensitive file".
- rule: Shell spawned in a container
desc: An interactive shell started inside a container
condition: spawned_process and container and proc.name in (bash, sh, zsh) and proc.tty != 0
output: "Shell in container (user=%user.name container=%container.name image=%container.image.repository cmd=%proc.cmdline)"
priority: WARNINGDistroless images make this kind of rule much quieter, because a legitimate workload never spawns a shell. Send Falco alerts to the same pipeline as your other detections, as covered in Detection engineering.
Key terms
- Namespace (Linux)
- A kernel feature that gives a process its own view of one resource type, such as process IDs or the network stack.
- cgroup
- A kernel mechanism that limits and accounts for a group of processes' CPU, memory and other resources.
- Capability
- One slice of root's privileges, such as binding low ports or loading kernel modules, that can be granted or dropped separately.
- seccomp
- A kernel filter that limits which system calls a process may make.
- Distroless image
- A container image with only the application and its runtime dependencies, without a shell or package manager.
- Service account
- The Kubernetes identity a pod uses to authenticate to the API server.
- Admission controller
- A plugin that mutates or rejects API requests after authorization and before they are stored.
- Pod Security Standards
- Three built-in profiles (privileged, baseline, restricted) enforced per namespace by Pod Security Admission.
- NetworkPolicy
- A Kubernetes resource that restricts which traffic may reach or leave selected pods.
- Container escape
- Gaining control of the host from inside a container through misconfiguration, a runtime bug or a kernel bug.
Harden a sloppy Kubernetes deployment in kind
Goal: deploy a deliberately insecure workload to a local cluster, abuse it, then harden it with a non-root image, Pod Security Admission, a network policy and a Kyverno admission policy.
You need: Docker, kind (v0.24 or later, whose default network plugin enforces NetworkPolicy), kubectl, Helm and Trivy. On macOS: brew install kind kubectl helm trivy. On Linux, use each project's install page or Homebrew on Linux. Everything runs on your laptop; never point these steps at a cluster you do not own.
- Create a cluster and deploy the sloppy workload.
kind create cluster --name harden
kubectl create namespace shop
kubectl create namespace toolsapiVersion: v1
kind: ServiceAccount
metadata: { name: web, namespace: shop }
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata: { name: web-is-admin }
subjects: [{ kind: ServiceAccount, name: web, namespace: shop }]
roleRef: { kind: ClusterRole, name: cluster-admin, apiGroup: rbac.authorization.k8s.io }
---
apiVersion: apps/v1
kind: Deployment
metadata: { name: web, namespace: shop }
spec:
selector: { matchLabels: { app: web } }
template:
metadata: { labels: { app: web } }
spec:
serviceAccountName: web
containers:
- name: web
image: nginx:latest
securityContext: { privileged: true }
volumeMounts: [{ name: host, mountPath: /host }]
volumes:
- name: host
hostPath: { path: / }
---
apiVersion: v1
kind: Service
metadata: { name: web, namespace: shop }
spec:
selector: { app: web }
ports: [{ port: 80, targetPort: 80 }]kubectl apply -f sloppy.yaml
kubectl -n shop rollout status deploy/web- Abuse it, as an attacker with code execution in the pod would.
kubectl -n shop exec deploy/web -- chroot /host cat /etc/hostname
# harden-control-plane <- you are reading the node's filesystem
kubectl auth can-i delete nodes --as=system:serviceaccount:shop:web
# yes <- the pod's token is cluster admin
trivy config sloppy.yaml | grep -E 'HIGH|CRITICAL' | head- Turn on Pod Security Admission at the restricted level and restart the workload.
kubectl label ns shop pod-security.kubernetes.io/enforce=restricted \
pod-security.kubernetes.io/warn=restricted
kubectl -n shop rollout restart deploy/web
kubectl -n shop get events --field-selector reason=FailedCreate | tail -3Expect FailedCreate events saying the pod violates PodSecurity "restricted:latest", listing privileged, hostPath, allowPrivilegeEscalation, runAsNonRoot and seccompProfile. The old pod keeps running, because admission only checks new objects.
- Remove the admin binding and replace the workload with a hardened version.
kubectl delete clusterrolebinding web-is-admin
kubectl -n shop delete deploy webapiVersion: apps/v1
kind: Deployment
metadata: { name: web, namespace: shop }
spec:
selector: { matchLabels: { app: web } }
template:
metadata: { labels: { app: web } }
spec:
serviceAccountName: web
automountServiceAccountToken: false
securityContext:
runAsNonRoot: true
runAsUser: 101
seccompProfile: { type: RuntimeDefault }
containers:
- name: web
image: nginxinc/nginx-unprivileged:stable-alpine
ports: [{ containerPort: 8080 }]
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities: { drop: ["ALL"] }
resources:
limits: { cpu: 200m, memory: 128Mi }
volumeMounts: [{ name: tmp, mountPath: /tmp }]
volumes:
- name: tmp
emptyDir: {}
---
apiVersion: v1
kind: Service
metadata: { name: web, namespace: shop }
spec:
selector: { app: web }
ports: [{ port: 80, targetPort: 8080 }]kubectl apply -f hardened.yaml
kubectl -n shop rollout status deploy/web # succeeds under restricted
trivy image --severity HIGH,CRITICAL nginx:latest | grep Total
trivy image --severity HIGH,CRITICAL nginxinc/nginx-unprivileged:stable-alpine | grep Total- Add a default-deny ingress policy and allow only frontend pods from the
toolsnamespace.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata: { name: default-deny-ingress, namespace: shop }
spec:
podSelector: {}
policyTypes: [Ingress]
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata: { name: allow-frontend, namespace: shop }
spec:
podSelector: { matchLabels: { app: web } }
policyTypes: [Ingress]
ingress:
- from:
- namespaceSelector: { matchLabels: { kubernetes.io/metadata.name: tools } }
podSelector: { matchLabels: { role: frontend } }
ports: [{ port: 8080 }]kubectl apply -f netpol.yaml
kubectl -n tools run fe --labels role=frontend --image=busybox:1.36 --rm -it --restart=Never \
-- wget -qO- -T 3 http://web.shop | head -4 # nginx welcome HTML
kubectl -n tools run other --image=busybox:1.36 --rm -it --restart=Never \
-- wget -qO- -T 3 http://web.shop # wget: download timed out- Install Kyverno and enforce the no-
latestpolicy from this chapter, scoped to your two namespaces by adding anamespaceSelectorundermatchConstraintsthat matcheskubernetes.io/metadata.nameinshopandtools.
helm repo add kyverno https://kyverno.github.io/kyverno/ && helm repo update
helm install kyverno kyverno/kyverno -n kyverno --create-namespace --wait
kubectl apply -f disallow-latest.yaml
kubectl -n tools run bad --image=nginx:latest --restart=Never
# Error from server: admission webhook ... denied the request: Images must use an explicit tag other than latest.Check your work: kubectl auth can-i delete nodes --as=system:serviceaccount:shop:web prints no; the hardened deployment runs in a namespace enforcing restricted; only the role=frontend pod in tools can fetch the page; and a latest-tagged pod is rejected at admission. Commit sloppy.yaml, the hardened manifests and a short before-and-after note to a public repo.
Stretch: install Falco with its Helm chart (falcosecurity/falco, modern eBPF driver), then kubectl exec -it into a busybox pod in tools and run sh. Find the "shell in container" alert in the Falco pod logs, and explain why the same command against the hardened nginx pod is harder.
Check yourself
A pod runs with privileged true and a hostPath mount of the root directory. An attacker gets code execution in it. What is the most accurate description of their position?
A developer applies a NetworkPolicy that allows only frontend pods to reach the database, but every pod can still connect. Which cause is most likely?
Which RBAC grant gives a user an easy path to every secret in a namespace even though it does not mention secrets?
You label a namespace with the restricted Pod Security enforce level. What happens to pods already running there that violate it?
Recap
- A container is a host process isolated by namespaces, cgroups, capabilities and seccomp, and all containers share one kernel.
- Most escapes come from configuration (privileged, host mounts, the Docker socket), so admission control prevents the majority of them.
- Small, non-root, pinned and scanned images shrink both the CVE count and what an attacker can do after code execution.
- Kubernetes security is API security: authenticate, authorize with minimal RBAC, then validate every object at admission.
- Network policies, encrypted or external secrets and runtime detection with Falco cover what prevention misses.
Go deeper
- Pod Security Standards: the exact controls behind each level.
- RBAC good practices: the Kubernetes project's list of risky permissions and how to avoid them.
- Kyverno documentation: policy types, CEL examples and installation.
- Falco documentation: rules, drivers and deployment on Kubernetes.
- Bad Pods: Bishop Fox's collection of over-privileged pod specs and what each lets an attacker do, for practice on your own cluster.