Skip to content

Container Security: Rootless, Capabilities, seccomp, AppArmor/SELinux, Image Scanning, Pod Security ​

"Although containers provide strong software-level isolation of resources, the use of a shared kernel invariably results in a larger inter-object attack surface than seen with hypervisors, even for container-specific OSs." — NIST, SP 800-190 Application Container Security Guide, §3.5.2 (September 2017)

Summary: A container is an ordinary Linux process that shares the host kernel, so its security is the sum of a handful of independent kernel and supply-chain controls, each of which you switch on deliberately: who the process is (non-root, user namespaces, rootless engines), what it may ask the kernel for (capabilities, no-new-privileges, seccomp, AppArmor/SELinux), what it may touch (read-only root filesystem, resource limits, network policies), what it is made of (trusted minimal images, scanning, SBOM, signatures) and what the cluster lets in at all (Pod Security Admission, policy engines). Focus: The threat model of a container (container escape, kernel attack surface, shared kernel, root in container), user namespaces with userns-remap, rootless Docker and rootless Podman, the USER instruction and non-root images, read-only root filesystem with tmpfs for writable paths, Linux capabilities (cap_drop ALL, cap_add, CAP_NET_BIND_SERVICE, the bounding/effective/ambient sets), no-new-privileges, seccomp (the default seccomp profile, a custom seccomp profile derived from it, log mode), AppArmor profiles, SELinux type enforcement and MCS labels, privileged containers, docker socket exposure and Docker-in-Docker, resource limits as security (PID limits against fork bombs, memory), image provenance (trusted base images, minimal images, distroless), image scanning (Trivy, Grype, Docker Scout; CVE, CVSS, VEX), SBOM, SLSA and cosign signing, secrets handling (no secrets in images, build secrets, runtime secret files), admission control with Kubernetes Pod Security Standards (privileged baseline restricted) and Pod Security Admission, the securityContext fields (runAsNonRoot, allowPrivilegeEscalation, readOnlyRootFilesystem, drop capabilities, seccompProfile RuntimeDefault), policy engines (Kyverno, OPA Gatekeeper), network policies, runtime security (Falco, eBPF, audit logging), the supply chain (dependency confusion, registry authentication, least privilege for CI runners), Go static binaries and security, Laravel file permissions and APP_KEY handling in containers, and the two reference documents (CIS Docker Benchmark, NIST SP 800-190). Learning goal: Given any docker run line, Compose service or Pod spec, say what an attacker with code execution inside it can do to the host and to neighbours, and rewrite it so the answer is "very little": a non-root numeric UID, no capabilities, no-new-privileges, a seccomp and LSM profile, a read-only root filesystem, limits, a default-deny network; then build the pipeline that only lets scanned, signed images from your registry into a namespace that enforces the restricted Pod Security Standard.

This chapter is the fourth in the Containers group. Containers Under the Hood owns the kernel mechanisms themselves (namespaces, cgroups v2, OverlayFS, the runtime stack runc/containerd); here they appear as security controls you configure. Images & Dockerfiles owns building images (layers, multi-stage, base images, attestation flags); this page owns what makes an image trustworthy and how to verify it. Running Containers owns docker run and Compose as a workflow; here only their security options are taught. Inside Kubernetes, RBAC, ServiceAccounts and API-server audit policy are Kubernetes Security, which links back here for Pod Security; probes and rollouts are Kubernetes Workloads; Secret objects and external secret stores are Kubernetes Config, Secrets & Storage. The pipeline that runs scans and signs images (runners, OIDC, environments) is CI/CD Pipelines; SAST/SCA policy and the incident process are Secure SDLC & Incident Response; application vulnerabilities (injection, deserialisation) that give an attacker the foothold in the first place are OWASP Top 10; host and cloud firewalls are Firewalls; the architectural case for containers is Containers & Kubernetes; Go build flags are Project Layout, Linting & Build.

Page map ​

If you are looking forGo to
The whole page in three tablesEverything in one minute
What an attacker in a container can reach, and whyWhy it exists
Namespaces 2008, Docker 1.10 seccomp, runc CVEs, PSP to PSAWhere it comes from
Shared kernel, container escape, kernel attack surfaceThreat model
Root in container, user namespaces, userns-remap, hostUsers: falseUser namespaces
Rootless Docker and rootless PodmanRootless engines
USER instruction, numeric UIDs, non-root imagesNon-root images
Capability sets, cap_drop ALL, cap_add, CAP_NET_BIND_SERVICECapabilities
no_new_privs, allowPrivilegeEscalationno-new-privileges
Default and custom seccomp profilesseccomp
AppArmor profiles, SELinux types and MCS labelsAppArmor and SELinux
--read-only, tmpfs, emptyDirRead-only root filesystem
--privileged, the Docker socket, Docker-in-DockerPrivileged containers and the socket
PID limits, fork bombs, memoryResource limits as security
Trusted, minimal and distroless base imagesImage provenance
Trivy, Grype, Docker Scout, CVE, CVSS, VEXImage scanning
SBOM, SLSA, cosignSBOM, SLSA and signing
No secrets in images, build secrets, secret filesSecrets handling
privileged / baseline / restricted, PSA labelsPod Security Standards
Every securityContext field that matterssecurityContext
Kyverno, OPA Gatekeeper, ValidatingAdmissionPolicyPolicy engines
Default-deny NetworkPolicyNetwork policies
Falco, eBPF, audit loggingRuntime security
Dependency confusion, registry auth, CI runner privilegesSupply chain
CIS Docker Benchmark, NIST SP 800-190Benchmarks
OCI config, capability-aware seccomp, /proc/self/status, knobs, errorsMechanics
CodeGo, Laravel
Nine classic problems and their fixesSolving the classic problems
Which engine, which isolation, which policy engine, which scannerChoosing
From one VM to many clustersIn architecture
Commands with expected outputLab
Wrong beliefs, summary, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

Threat to control map. Read each row as "if the attacker does X, this control stops or limits it".

Attacker stepControlDocker / ComposeKubernetes
Uses UID 0 powers inside the containerNon-root userUSER 65532:65532, --user, user:runAsNonRoot: true, runAsUser
Escapes, lands on the host as rootUser namespacerootless engine, userns-remaphostUsers: false
Calls mount, loads modules, sniffs packetsDrop capabilities--cap-drop ALL, cap_drop: [ALL]capabilities.drop: ["ALL"]
Runs a setuid binary to regain privilegesno_new_privs--security-opt no-new-privilegesallowPrivilegeEscalation: false
Calls a rarely used, buggy syscallseccompdefault profile, seccomp=profile.jsonseccompProfile.type: RuntimeDefault
Reads/writes host paths, mounts, /proc knobsAppArmor / SELinuxapparmor=..., label=...appArmorProfile, seLinuxOptions
Drops a web shell, persists a binaryRead-only root filesystem--read-only + --tmpfs /tmpreadOnlyRootFilesystem: true + emptyDir
Fork bomb, memory exhaustionLimits--pids-limit, --memoryPodPidsLimit, resources.limits
Moves laterally to the database or metadata serviceNetwork policyinternal networksNetworkPolicy default deny
Ships a backdoored or vulnerable imageSupply chainscan, sign, pin digestadmission verifies signature and digest

The runtime flags in one table (what each sets in the OCI runtime config).

Flag (Docker)Compose keyPod securityContextOCI config.json field
--user 65532:65532userrunAsUser, runAsGroupprocess.user
--cap-drop ALL --cap-add NET_BIND_SERVICEcap_drop, cap_addcapabilities.drop/addprocess.capabilities.*
--security-opt no-new-privilegessecurity_optallowPrivilegeEscalation: falseprocess.noNewPrivileges
--security-opt seccomp=p.jsonsecurity_optseccompProfilelinux.seccomp
--security-opt apparmor=psecurity_optappArmorProfileprocess.apparmorProfile
--security-opt label=level:s0:c100,c200security_optseLinuxOptionsprocess.selinuxLabel
--read-onlyread_onlyreadOnlyRootFilesystemroot.readonly
--tmpfs /tmptmpfsemptyDir: {medium: Memory}mounts[] type tmpfs
--pids-limit 128pids_limitkubelet PodPidsLimitlinux.resources.pids.limit
--privilegedprivilegedprivileged: trueeverything above switched off

Image and policy tools in one table.

ToolWhat it doesWhere it runs
TrivyScans images, filesystems, repos, Kubernetes for CVEs, misconfigurations, secrets, licences; reads VEXCI, laptop, operator in cluster
GrypeScans images, filesystems and SBOMs for known vulnerabilities; OpenVEX filtering; EPSS/KEV prioritisationCI, laptop
Docker ScoutBuilds an SBOM of an image and matches it against a continuously updated database; VEX exceptionsDocker Hub, Docker CLI, dashboard
SyftGenerates SBOMs (SPDX, CycloneDX)CI
cosign (Sigstore)Signs and verifies images and attestations; keyless with Fulcio and RekorCI (sign), admission (verify)
KyvernoKubernetes-native policy engine; CEL ValidatingPolicy, ImageValidatingPolicyAdmission webhook + background scans
OPA GatekeeperValidating and mutating webhook enforcing CRD-based policies written in RegoAdmission webhook + audit
FalcoRuntime threat detection from kernel events (default driver: modern eBPF probe)DaemonSet on every node
govulncheckReports only vulnerabilities your Go code actually reachesCI, inside the Docker build
Docker Bench for SecurityAutomated checks based on the CIS Docker BenchmarkThe Docker host
Layers an attacker must pass after a bug gives them code executionBefore starttrusted base, scan, SBOM,signature, admissionAttackerRCE in the app process(upload, deserialisation)1 non-root USER, runAsNonRoot2 cap_drop ALL + no-new-privileges3 seccomp (RuntimeDefault or custom)4 AppArmor / SELinux (MCS labels)5 read-only rootfs + tmpfs, limits6 user namespace (rootless, hostUsers)7 network policy: no lateral moveswhat each layer removesUID 0 powerscapabilities, setuid gainsrare syscalls (mount, bpf)paths and mounts by labelpersistence, fork bombshost root after an escapereach to DB, API, metadataShared host kernelA kernel or runtime bug can skip several layers at once (runc CVE-2024-21626: leaked fd).runc CVE-2019-5736 needed a command run as root in the container: a non-root USER blocks that path.Each layer is independent: a mistake in one is caught by the next. Falco (eBPF) watches all.A sandbox runtime (gVisor, Kata) adds a second kernel between layer 6 and the host kernel.

Why it exists ​

A virtual machine gives a guest its own kernel; a container does not. Every container on a node makes system calls into the same kernel, sees the same devices unless the runtime hides them, and is separated from its neighbours only by kernel bookkeeping: namespaces decide what it can see, cgroups how much it can use, and a set of permission checks what it may do. Docker's own security page lists the four areas to review: "The intrinsic security of the kernel and its support for namespaces and cgroups", "The attack surface of the Docker daemon itself", "Loopholes in the container configuration profile", and the kernel's "hardening" features and how they interact with containers.

That design is why the defaults matter so much and why they are not enough. Out of the box, Docker already drops most capabilities, attaches a seccomp filter and an AppArmor profile, so "root" in a Docker container is weaker than real root. But the process is still UID 0 against any file the kernel lets it see, a kernel bug reachable through an allowed syscall still runs in the one shared kernel, and a single --privileged or -v /var/run/docker.sock:/var/run/docker.sock undoes everything. Kubernetes is weaker by default: without the kubelet's --seccomp-default, Pods run Unconfined, and allowPrivilegeEscalation "will default to true".

Simpler choiceHardened choiceWhat you buyWhat you pay
Image runs as rootNumeric non-root USERBugs give an unprivileged UID, runAsNonRoot passesFix file ownership, ports ≥ 1024
Default capability set (14)cap_drop ALL (+ one if needed)No CHOWN, NET_RAW, SETUID ... to abuseFind out which capability, if any, the app needs
Writable root filesystem--read-only + tmpfsNo persistence, no web shell, no binary dropsList every writable path the app needs
Default seccomp onlyDefault + LSM + custom profileFewer reachable syscalls and pathsProfiles to maintain per image
Rootful daemonRootless engine / user namespacesAn escape lands as an unprivileged host UIDPort, storage and networking quirks
latest from anywhereTrusted minimal base, scanned, signed, pinned digestKnown contents, known originA pipeline and an admission policy
No cluster policyPSA restricted + policy engineBad Pods never startExemptions for infrastructure workloads

The analogy used through this page: an apartment building with one shared foundation. Every tenant (container) has their own front door and walls (namespaces), a utility meter (cgroups) and house rules (capabilities, seccomp, AppArmor/SELinux). The building's foundation and plumbing (the kernel) are shared: a tenant who cracks the foundation affects everyone, so the house rules forbid touching the boiler room at all (seccomp blocks the syscalls), give no tenant a master key (no capabilities), and the tenant who believes they are the landlord (UID 0) is, on the building register, just flat 100000 (user namespace). The --privileged flag hands a tenant the building's master keys and the boiler-room door; mounting the Docker socket hands them the landlord's phone.

Three common misunderstandings, up front ​

  1. "Containers are a security boundary like VMs." They are a boundary of a different strength. NIST SP 800-190 says the shared kernel "invariably results in a larger inter-object attack surface than seen with hypervisors"; runc CVE-2024-21626 allowed "a container escape by giving access to the host filesystem" through a leaked file descriptor. Hardening narrows what an attacker can reach; a sandbox runtime (gVisor, Kata) adds a second kernel when the workload is truly untrusted (Containers Under the Hood).
  2. "Restricted Pod Security means my pod is hardened." Restricted does not require a read-only root filesystem, resource limits, network policies, a trusted registry or signed images. It is a floor; a policy engine and the pipeline add the rest.
  3. "Zero scanner findings means the image is safe." A scanner matches package versions against advisories. It does not see your own code, a binary you curled in, or a zero-day; it says nothing about how the container runs. Scanning and runtime hardening answer different questions.

Where it comes from ​

WhenWhat happenedSource
Linux 2.2Root's privileges split into capabilities; "Capabilities are a per-thread attribute"capabilities(7)
2006 / kernel 2.6.24Control groups "started in 2006, and initially merged in kernel 2.6.24"Docker Engine security page
Kernels 2.6.15 to 2.6.26 (July 2008)Kernel namespaces arrive; since July 2008 the code "has been exercised and scrutinized on a large number of production systems"Docker Engine security page
Linux 3.5The no_new_privs bit: "Once the bit is set, it is inherited across fork, clone, and execve and cannot be unset"kernel no_new_privs doc
Linux 4.3Ambient capability setcapabilities(7)
4 Feb 2016Docker Engine 1.10: default seccomp profile "used when none is passed and if the container is not run as privileged", user namespaces, authorization pluginsDocker blog "Docker Engine 1.10 security"
September 2017NIST SP 800-190 Application Container Security Guidecsrc.nist.gov
11 Feb 2019CVE-2019-5736: runc "allows attackers to overwrite the host runc binary (and consequently obtain host root access)"CVE record
Kubernetes v1.19seccomp in the Pod API is stableKubernetes seccomp tutorial (feature state)
Kubernetes v1.21PodSecurityPolicy deprecatedKubernetes v1.25 release blog
July 2022VEX status justification labels published by the VEX Working GroupOpenVEX specification
23 Aug 2022, Kubernetes v1.25"PodSecurityPolicy is removed; Pod Security Admission graduates to Stable"Kubernetes v1.25 release blog
Kubernetes v1.27kubelet --seccomp-default (RuntimeDefault for every Pod) is stableKubernetes seccomp tutorial
31 Jan 2024CVE-2024-21626 (runc ≤ 1.1.11, fd leak, container escape), fixed in 1.1.12; CVSS 3.1 base 8.6 HighCVE record, runc advisory
Kubernetes v1.30AppArmor moves from annotations to the appArmorProfile fieldKubernetes AppArmor tutorial
Kubernetes v1.36User namespaces for Pods stable ("first available in the v1.28 release")Kubernetes user namespaces page
Docker Engine 29.8The daemon can be configured to generate a customised default AppArmor profileDocker AppArmor page
2026CIS Docker Benchmark listed at version 1.9.0; Docker Bench for Security automates v1.6.0 checkscisecurity.org, docker-bench-security README

Two lineages meet here. The kernel side grew piece by piece (namespaces, cgroups, capabilities, seccomp, LSMs) for general Linux hardening long before containers used them together; Docker's 1.10 release is where the combination became a default. The supply-chain side grew after incidents moved attackers upstream: SBOMs, SLSA provenance levels, Sigstore's keyless signing and VEX all appeared to answer "what is in this image, who built it, and does this CVE matter here?". Kubernetes went through one false start, PodSecurityPolicy, which was removed because "the updates required to improve its usability would have introduced breaking changes"; its replacement splits the problem into a fixed set of standards (PSS) checked by a simple built-in plugin (PSA), with policy engines for everything custom.

The concept catalogue ​

Each block follows the same order: plain words, the common misunderstanding, the definition, a sequence, real scenarios, what each product does, and the fix.

Threat model: shared kernel, container escape, kernel attack surface Must-know ​

In plain words: Assume the attacker already runs code inside your container (an RCE in the app, a malicious dependency, a poisoned image). The question is what that code can do next: to the host, to other containers on the node, and to the network.

Common misunderstanding: "If the app is not vulnerable, container hardening is wasted effort." The threat model starts after the first bug, because the first bug is the one you do not know about. Hardening is what turns an RCE into an incident with a small blast radius instead of a node compromise.

Definition: A container escape is any path from inside the container's namespaces to the host's: a kernel vulnerability reached through an allowed syscall, a runtime bug (runc CVE-2019-5736 overwrote the host runc binary "related to /proc/self/exe"; CVE-2024-21626 gave a process "a working directory in the host filesystem namespace"), or a misconfiguration that hands over the host directly (--privileged, the Docker socket, a hostPath of /). The kernel attack surface is the set of kernel code a container can reach: every allowed syscall, every visible /proc and /sys file, every device. The shared kernel is the reason one container's escape is every container's problem. NIST SP 800-190 groups the risks into image, registry, orchestrator, container and host OS risks; its countermeasure for the last is to keep containerized and non-containerized workloads on separate hosts.

text
Attacker with RCE in the api container: what decides the next step
1  whoami          -> UID 0 or 65532?                    (USER, runAsNonRoot)
2  is UID 0 real?  -> host UID 0 or 100000?              (user namespace, rootless)
3  mount, raw socket, ptrace?  -> EPERM?                 (capabilities, seccomp, LSM)
4  write a binary to /usr/local/bin and run it?          (read-only rootfs, noexec tmpfs)
5  fork 100000 processes?                                (pids limit)
6  curl the database, the API server, 169.254.169.254?   (NetworkPolicy, no SA token)
7  exploit a kernel bug in an allowed syscall            (seccomp narrows it; sandbox runtime removes it)

Real scenarios:

  • A deserialisation RCE in a PHP app running as root with a writable root filesystem: the attacker drops a web shell into public/ and it survives until the container is replaced.
  • A CI job mounts /var/run/docker.sock to build images; a malicious pull request runs docker run -v /:/host --privileged against the host daemon.
  • A kernel bug in a rarely used subsystem is exploitable only through one syscall; the default seccomp profile already blocks it (Docker blocks io_uring_* because of "security vulnerabilities that can be exploited to break out of containers").
  • A compromised pod calls the cloud metadata endpoint and steals the node's credentials.
IsolationKernel shared with host?Typical escape pathUse for
Plain container (runc, crun)YesKernel or runtime bug, misconfigurationYour own trusted code, hardened
Container + user namespace / rootlessYes, but root is unmappedKernel bug, then unprivileged on hostDefault for shared hosts and CI
Sandbox runtime (gVisor)Syscalls served by a user-space kernelBug in the sandbox, then hostMulti-tenant, untrusted code
MicroVM (Kata, Firecracker)No, a guest kernel per podHypervisor bugHostile tenants

Fix: write the threat model per workload (who might run code in it, what it can reach), then apply every runtime layer on this page; for untrusted tenants choose a sandbox runtime as described in Containers Under the Hood.

Root in container and user namespaces Must-know ​

In plain words: Without a user namespace, UID 0 in the container is UID 0 on the host, only with fewer capabilities. A user namespace keeps the container's view ("I am root") but tells the kernel that this root is really an ordinary host user.

Common misunderstanding: "Docker uses user namespaces by default." It does not: Docker's security page says the feature "is available but not enabled by default". Without userns-remap or a rootless engine, a container's root is the host's root as far as file ownership on bind mounts and a kernel escape are concerned.

Definition: user_namespaces(7): "a process can have a normal unprivileged user ID outside a user namespace while at the same time having a user ID of 0 inside the namespace; in other words, the process has full privileges for operations inside the user namespace, but is unprivileged for operations outside the namespace." The mapping is in /proc/<pid>/uid_map, one line per range (inside, outside, count); the initial namespace shows 0 0 4294967295. Docker's userns-remap maps container UIDs to a subordinate range from /etc/subuid (for example testuser:231072:65536), so container root becomes host UID 231072 and the mapped range has "no privileges on the host machine itself"; with it, "the Docker daemon still runs as root". Kubernetes enables a user namespace per Pod with hostUsers: false (stable since v1.36), and documents that "There are several security vulnerabilities rated either HIGH or CRITICAL that were not exploitable when user namespaces is active.".

text
docker run with userns-remap=default, /etc/subuid: dockremap:100000:65536
1  container process: id -u -> 0             (inside the namespace)
2  /proc/self/uid_map -> 0 100000 65536      (inside 0 = host 100000)
3  writes /data/file on a bind mount         -> owned by UID 100000 on the host
4  hypothetical escape to the host           -> an ordinary user, no capabilities there
5  --privileged / --pid=host / --network=host -> incompatible unless --userns=host for that container

Real scenarios: a shared CI host where every job is root in its container; a bind-mounted volume that suddenly becomes unreadable after enabling remapping because file ownership must be "pre-arranged"; an image that insists on running as root (old vendor software) where user namespaces are the only mitigation; Kubernetes nodes on Linux ≥ 6.3, because the idmap mounts needed for hostUsers: false require it ("tmpfs started supporting idmap mounts in that version").

PlatformUser namespace optionKnown limits
Docker (rootful)dockerd --userns-remap=default or "userns-remap" in daemon.json; per-container opt-out --userns=hostNot with --pid=host, --network=host, or --privileged without --userns=host; volume ownership
Docker rootlessAlways (daemon and containers in a user namespace)See rootless engines
PodmanRootless by default for non-root users; --userns optionsSame kernel limits
Kubernetesspec.hostUsers: falseNo hostNetwork/hostPID/hostIPC; filesystems need idmap mounts
containerd / CRI-OImplement the Kubernetes fieldRuntime and kernel versions

Fix: turn user namespaces on where the platform supports them (rootless on build and dev hosts, hostUsers: false on Kubernetes ≥ 1.36 with a recent kernel) and still run as non-root: the two controls protect against different things. The kernel mechanics are in Containers Under the Hood.

Rootless engines: rootless Docker and rootless Podman Important ​

In plain words: In rootless mode, the engine itself (dockerd or Podman) runs as your normal user, so neither a bug in the daemon nor an escape from a container gives anyone host root.

Common misunderstanding: "Rootless Docker is the same as userns-remap." Docker's docs draw the line exactly: "with userns-remap mode, the daemon itself is running with root privileges, whereas in rootless mode, both the daemon and the container are running without root privileges."

Definition: Docker: "Rootless mode executes the Docker daemon and containers inside a user namespace." It needs newuidmap/newgidmap (the only setuid helpers it uses) and "at least 65,536 subordinate UIDs/GIDs" in /etc/subuid and /etc/subgid; dockerd-rootless-setuptool.sh install creates a user systemd unit and a rootless CLI context, with the socket at unix:///run/user/1000/docker.sock, and docker info then lists rootless under Security Options. Podman is daemonless and rootless by design for non-root users; its rootless networking uses pasta. The kernel still applies its rules: "Podman can not create containers that bind to ports < 1024", because "the kernel does not allow processes without CAP_NET_BIND_SERVICE to bind to low ports"; the documented workaround is the net.ipv4.ip_unprivileged_port_start sysctl.

text
Rootless Docker for user testuser (UID 1001, subuid 231072:65536)
1  dockerd runs as UID 1001 inside a user namespace (systemctl --user)
2  container root (UID 0) -> host UID 1001; container UID 1 -> host 231072
3  docker run -p 80:80 nginx        -> fails: no privileged ports without the sysctl
4  docker run -p 8080:8080 ...      -> works
5  escape from the container        -> a shell as testuser, not root

Real scenarios: developer laptops and shared Linux build hosts; GitLab or GitHub self-hosted runners that must build images without --privileged; Podman on RHEL/Fedora servers with systemd units per service; images that bind port 80 and break under rootless engines.

EngineDaemon userContainer root maps toNotes
Docker rootfulroothost root (unless userns-remap)The docker group "grants root-level privileges to the user"
Docker + userns-remaprootsubordinate UIDDaemon bugs still root
Docker rootlessthe userthe user, then subordinate UIDsdockerd-rootless-setuptool.sh, docker info shows rootless
Podman rootlessno daemon; the userthe user, then subordinate UIDspasta networking, ports < 1024 need the sysctl
Rootless BuildKit / Buildahthe userthe userGitLab documents both for CI without privileged mode

Fix: use rootless engines wherever a human or CI job controls the engine; on production nodes use the orchestrator's equivalents (hostUsers: false, non-root runAsUser). Keep services on ports ≥ 1024 so rootless and capability-free operation costs nothing.

USER instruction and non-root images Must-know ​

In plain words: Decide in the image which unprivileged user the app runs as, by number, and make sure the files it must write belong to that user and nothing else does.

Common misunderstanding: "Kubernetes can always just set runAsUser." The Kubernetes security checklist warns that "the file permissions in the image layers might make it impossible to just start the process with a new unprivileged user without image modification." The image has to be built for non-root.

Definition: The Dockerfile USER instruction sets the default user and group for later instructions and the container (Images & Dockerfiles covers the instruction itself). For runAsNonRoot: true, the kubelet "will validate the image at runtime to ensure that it does not run as UID 0 (root) and fail to start the container if it does"; a numeric USER 65532:65532 makes that check unambiguous. The Compose user key "overrides the user used to run the container process"; "If it's not set, then root." Distroless publishes :nonroot variants (UID 65532); nginxinc/nginx-unprivileged moves Nginx to port 8080 and its PID and temp files to /tmp.

text
Kubernetes starts a pod with runAsNonRoot: true
1  image config User = ""            -> UID 0 -> kubelet refuses: container fails to start
2  image config User = "www-data"    -> name, not number: set runAsUser: 33 as well
3  image config User = "65532:65532" -> numeric, non-zero -> starts
4  app writes /var/www/html/storage  -> EACCES unless the directory is owned by 65532 (or fsGroup)

Real scenarios: a Laravel image whose whole tree is owned by www-data (so an RCE can rewrite PHP files); an Nginx container failing with open() "/var/run/nginx.pid" failed (13: Permission denied) after switching users (the unprivileged image moves the PID file to /tmp/nginx.pid); a Go binary on scratch that runs as root because scratch has no /etc/passwd and nobody set USER.

Image familyDefault userNon-root path
gcr.io/distroless/static-debian13:nonroot65532Use it for static Go
php:*-fpmmaster root, workers www-data (UID 33)USER www-data; code owned by root, storage/ by www-data
nginxmaster rootnginxinc/nginx-unprivileged (port 8080, PID in /tmp)
golang, debian, alpinerootuseradd/adduser + numeric USER
scratchroot (UID 0, no passwd)USER 65532:65532 works without a passwd file

Fix: numeric USER in every runtime stage; code owned by root and read-only to the app user; writable directories created and owned explicitly; ports ≥ 1024.

Linux capabilities: cap_drop ALL, cap_add, CAP_NET_BIND_SERVICE Must-know ​

In plain words: Root's power is split into about forty separate permissions. Containers get a short list by default; a well-built service needs none of them.

Common misunderstanding: "--cap-add NET_BIND_SERVICE lets my non-root app bind port 80." For a non-root process the capability must reach the effective set, and the bounding set only says it may. A non-root process gains it through file capabilities on the binary or ambient capabilities. File capabilities do not apply under no_new_privs ("file capabilities will not add to the permitted set"); ambient capabilities are different: no_new_privs only restricts what execve grants, and capabilities(7) carries the ambient set into the new permitted set (P'(permitted) = ... | P'(ambient)) for an unprivileged program, so a runtime that sets ambient capabilities still works with no_new_privs. The simplest correct design is a port ≥ 1024 and no capability at all.

Definition: capabilities(7): "Starting with Linux 2.2, Linux divides the privileges traditionally associated with superuser into distinct units, known as capabilities". Each thread has five sets: permitted ("a limiting superset for the effective capabilities"), inheritable, effective ("the set of capabilities used by the kernel to perform permission checks"), bounding ("used to limit the capabilities that are gained during execve(2)") and ambient (since Linux 4.3, preserved across execve of a non-privileged program). When a process changes from UID 0 to non-zero, "all capabilities are cleared from the permitted, effective, and ambient capability sets". CAP_NET_BIND_SERVICE lets a process "Bind a socket to Internet domain privileged ports (port numbers less than 1024)". CAP_SYS_ADMIN is what the man page says "can plausibly be called" the new root. Docker's default list is 14 capabilities ("an allowlist instead of a denylist approach"), and its advice is "to remove all capabilities except those explicitly required for their processes."

text
Capability check for bind(0.0.0.0:80) in three containers
1  docker run (root, default caps)             CapEff has NET_BIND_SERVICE -> bind OK
2  --user 65532 --cap-drop ALL                 CapEff = 0, CapBnd = 0      -> EACCES
3  --user 65532 --cap-drop ALL --cap-add NET_BIND_SERVICE
                                               CapBnd = NET_BIND_SERVICE, CapEff = 0
                                               -> still EACCES without file or ambient caps
4  any of them, PORT=8080                      no capability needed          -> bind OK

Real scenarios: Docker's default list includes NET_RAW (packet crafting, ARP spoofing on the bridge) and CHOWN/DAC_OVERRIDE (bypass file permissions as root); an "it needs SYS_ADMIN" request that turns out to be a FUSE mount better done on the host; a debugging container with SYS_PTRACE left in production; Kubernetes baseline allowing 13 default-like capabilities while restricted requires dropping ALL.

PlatformDefault setHow to dropHow to add
Docker Engine14 (moby DefaultCapabilities: CHOWN, DAC_OVERRIDE, FSETID, FOWNER, MKNOD, NET_RAW, SETGID, SETUID, SETFCAP, SETPCAP, NET_BIND_SERVICE, SYS_CHROOT, KILL, AUDIT_WRITE)--cap-drop ALL--cap-add NET_BIND_SERVICE
ComposeEngine defaultcap_drop: [ALL]cap_add: [...]
KubernetesRuntime default (containerd, CRI-O)capabilities.drop: ["ALL"]capabilities.add; restricted allows only NET_BIND_SERVICE
PodmanIts own default list--cap-drop all--cap-add
--privilegedAll capabilitiesn/an/a

Fix: cap_drop ALL everywhere; add back a capability only with a written reason; prefer redesign (high port, init container on the host side) over a capability. The Go tool secreport decodes the sets from /proc/self/status so you can see the result.

no-new-privileges and allowPrivilegeEscalation Must-know ​

In plain words: A one-way switch: once set, no program the container runs can come out with more privileges than the process that ran it, so su, sudo and setuid binaries stop working as escalation paths.

Common misunderstanding: "My image has no setuid binaries, so this flag does nothing." Base images often carry some (su, passwd, mount), and an attacker can try to bring one. The flag also has a second effect: unprivileged processes may only install seccomp filters when it is set.

Definition: Kernel docs: "With no_new_privs set, execve() promises not to grant the privilege to do anything that could not have been done without the execve call. For example, the setuid and setgid bits will no longer change the uid or gid; file capabilities will not add to the permitted set, and LSMs will not relax constraints after execve." It exists "since Linux 3.5", and "Once the bit is set, it is inherited across fork, clone, and execve and cannot be unset." Note what it does not do: it blocks privilege gains through execve, it does not strip capabilities the process already holds, including the ambient set (capabilities(7) carries P(ambient) across execve of an unprivileged program). Docker: --security-opt no-new-privileges means "commands that raise privileges such as su or sudo no longer work". Kubernetes: allowPrivilegeEscalation "directly controls whether the no_new_privs flag gets set on the container process", it "will default to true" if undefined, and false cannot be combined with a container that "is run as privileged" or "has the capability CAP_SYS_ADMIN". /proc/<pid>/status shows the bit as NoNewPrivs: (since Linux 4.10).

text
Attacker in a non-root container finds /usr/bin/passwd (setuid root)
1  without no_new_privs: execve(passwd) -> euid 0 for that process -> exploit a passwd bug -> root
2  with no_new_privs:    execve(passwd) -> runs as the caller, setuid bit ignored
3  file capabilities on a copied-in binary -> also ignored
4  the bit survives fork/exec and cannot be cleared from inside

Real scenarios: an Alpine-based image whose BusyBox su is the only escalation path; a Kubernetes namespace where restricted PSA rejects pods missing allowPrivilegeEscalation: false; a service that used setcap cap_net_bind_service+ep on its binary and stops binding port 80 when the flag is added.

WhereSettingDefault
Docker per container--security-opt no-new-privileges[=true]off
Docker daemon--no-new-privileges / "no-new-privileges": truefalse
Composesecurity_opt: [no-new-privileges:true]off
KubernetesallowPrivilegeEscalation: falsetrue
OCI runtime configprocess.noNewPrivilegesfalse

Fix: set it in every runtime and as the daemon default; drop setcap tricks in favour of high ports.

seccomp: the default seccomp profile and a custom seccomp profile Must-know ​

In plain words: A filter in front of the kernel's front door. Every system call the container makes is checked against a list; calls not on the list fail immediately, before any kernel code that might have a bug runs.

Common misunderstanding: "Kubernetes applies Docker's default seccomp profile." Only if asked: the restricted standard requires RuntimeDefault or Localhost to be set explicitly, and the kubelet uses RuntimeDefault for every Pod only with --seccomp-default (stable since v1.27); otherwise Pods run "Unconfined (seccomp disabled)". The second misunderstanding is that seccomp is a sandbox; the kernel docs say "System call filtering isn't a sandbox. It provides a clearly defined mechanism for minimizing the exposed kernel surface."

Definition: seccomp in filter mode attaches a BPF program that sees each syscall number and its arguments and returns an action (SCMP_ACT_ALLOW, SCMP_ACT_ERRNO, SCMP_ACT_LOG, kill, trace, user notification). A task may install a filter only after prctl(PR_SET_NO_NEW_PRIVS, 1) or with CAP_SYS_ADMIN. Docker's default profile "disables around 44 system calls out of 300+. It is moderately protective while providing wide application compatibility"; it is an allowlist with defaultAction SCMP_ACT_ERRNO, so a blocked call gets a "Permission Denied" error. Docker recommends: "It is not recommended to change the default seccomp profile." A custom seccomp profile is passed with --security-opt seccomp=/path/profile.json (read by the CLI and sent to the daemon) or, in Kubernetes, as seccompProfile: {type: Localhost, localhostProfile: profiles/x.json} relative to the kubelet's seccomp directory.

text
Go service calls unshare(CLONE_NEWNS) after an RCE
1  syscall enters the kernel; seccomp filter runs first
2  default profile: unshare is allowed only in the rule that "includes": {"caps": ["CAP_SYS_ADMIN"]}
3  container has no CAP_SYS_ADMIN -> rule not applied -> defaultAction SCMP_ACT_ERRNO
4  unshare returns EPERM; the namespace code never runs
5  with the chapter's derived profile, unshare is removed from every rule: EPERM even with SYS_ADMIN

Real scenarios: the default profile blocking io_uring_* because of known escapes, keyctl/add_key to "Prevent containers from using the kernel keyring, which is not namespaced", open_by_handle_at as the "Cause of an old container breakout"; a profiler that needs perf_event_open failing inside a container; an engineer debugging with seccomp=unconfined and forgetting to remove it; a custom profile that worked on amd64 but forgot the arch map for arm64 nodes.

PlatformDefaultCustomOff
Dockermoby profiles/seccomp/default.json ("builtin")--security-opt seccomp=p.json, daemon --seccomp-profileseccomp=unconfined
PodmanIts default profile--security-opt seccomp=p.jsonunconfined
KubernetesUnconfined unless --seccomp-defaultLocalhost + localhostProfileUnconfined (forbidden by baseline)
containerd / CRI-OTheir own RuntimeDefault ("default profiles differ between container runtimes")via CRIvia CRI
One syscall, independent checks (simplified order): mount()processeuid, CapEff,NoNewPrivs1 seccompBPF on syscall numberand arguments2 capabilitySYS_ADMIN in CapEff,in which userns?3 LSMAppArmor orSELinux labelkerneldoes theworkEPERM (Docker usesSCMP_ACT_ERRNO),or log, or killEPERM: dropped, orheld only in a childuser namespaceEACCES +audit record(deny mount)Who sets each inputseccomp: --security-opt seccomp=..., seccompProfile.type RuntimeDefault or Localhostcapabilities: --cap-drop ALL / --cap-add, securityContext.capabilities;the default seccomp profile allows mount only when CAP_SYS_ADMIN is grantedeuid and userns: USER, --user, runAsUser; rootless engine or hostUsers: falsemaps container UID 0 to an unprivileged host UIDLSM: docker-default AppArmor or container_t:s0:c1,c2, set by the runtime, not the imageno_new_privs: no-new-privileges, allowPrivilegeEscalation: false; execve adds nothing--privileged turns off 1 and 3 and fills 2: every capability, no seccomp, no AppArmor,SELinux label disabled, all host devices, /sys and cgroup mounts read-write

Fix: always set RuntimeDefault (pod-level seccompProfile) and turn on --seccomp-default; for high-value services, derive a tighter profile from the maintained default instead of writing an allowlist by hand, run tests under a SCMP_ACT_LOG copy, then enforce. The seccomp snippet does exactly that.

AppArmor and SELinux: MAC profiles and MCS labels Important ​

In plain words: A second rulebook enforced by the kernel that ignores who you are (UID, capabilities) and asks only what label or profile you carry: "processes with this profile may read these paths and may never mount".

Common misunderstanding: "Root bypasses AppArmor/SELinux like it bypasses file permissions." Mandatory access control applies to root too; Red Hat's description of SELinux: it "cares only about labels". Its weakness is the opposite: it is easy to switch off (--privileged, label=disable, apparmor=unconfined).

Definition: AppArmor attaches a path-based profile to a program. Docker "automatically generates and loads a default profile for containers named docker-default", generated in tmpfs from a template and "moderately protective while providing wide application compatibility"; custom profiles are loaded with apparmor_parser -r -W and selected with --security-opt apparmor=<name>. Kubernetes uses securityContext.appArmorProfile (since v1.30; annotations before), and baseline forbids overriding or disabling the default. SELinux labels every process and file user:role:type:level; a container process is typically system_u:system_r:container_t:s0:c940,c967 and type enforcement rules such as allow container_t container_file_t:file {getattr open read}; decide access. MCS (Multi-Category Security) adds categories (c940,c967) so that two containers with the same type container_t still cannot read each other's files: each gets a unique pair, and its files carry the same pair. Podman's :z relabels a volume with a shared label, :Z with a private one ("Only the current container can use a private volume").

text
SELinux MCS keeps container A away from container B's volume
1  container A runs as container_t:s0:c1,c2 ; its volume is container_file_t:s0:c1,c2
2  container B runs as container_t:s0:c3,c4
3  B (even as root, even with a capability) opens A's file
4  type rule allows container_t -> container_file_t, but categories c3,c4 do not dominate c1,c2
5  EACCES + AVC denial in the audit log

Real scenarios: a bind mount that "works on Ubuntu but not on Fedora" (AppArmor host vs SELinux host; the fix is :Z, not disabling SELinux); a container that must manage iptables getting NET_ADMIN but still blocked by the LSM; udica generating an SELinux policy from a container's inspect output; Kubernetes baseline allowing only container_t, container_init_t, container_kvm_t and container_engine_t as SELinux types.

Host / platformLSMDefault for containersCustom
Ubuntu, Debian, SUSE + DockerAppArmordocker-defaultapparmor_parser, --security-opt apparmor=
RHEL, Fedora + Podman/CRI-OSELinuxcontainer_t + random MCS pairudica, label=type:..., :z/:Z
KubernetesWhatever the node hasRuntimeDefault AppArmor; runtime's SELinux labelappArmorProfile: Localhost, seLinuxOptions
Docker Desktop / macOSInside the Linux VMVM's defaultsSame flags

Fix: never disable the LSM to fix a volume (relabel it); keep runtime defaults on; write a custom AppArmor profile for exposed services, as in the snippet.

Read-only root filesystem and tmpfs for writable paths Must-know ​

In plain words: Make the container's own filesystem unchangeable. Give the app small scratch areas in memory for temp files, and real volumes for real data.

Common misunderstanding: "A read-only root breaks everything." It breaks only what writes to the image, and that list is short and knowable: /tmp, a PID file, a cache directory. Each becomes an explicit tmpfs or volume, which also documents the app's state.

Definition: Docker's --read-only "mounts the container's root filesystem as read only prohibiting writes to locations other than the specified volumes for the container"; --tmpfs /run:rw,noexec,nosuid,size=65536k adds an in-memory mount with mount options. Compose has read_only: true and tmpfs: (options mode, uid, gid); Kubernetes has readOnlyRootFilesystem: true plus an emptyDir (with medium: Memory it is a tmpfs counted against the memory limit). In the OCI config it is root.readonly: "If true then the root filesystem MUST be read-only inside the container".

text
RCE in a PHP container, before and after
Before (writable root, code owned by www-data):
1  attacker writes public/shell.php           -> served by Nginx on the next request
2  attacker edits vendor/autoload.php         -> backdoor runs on every request until redeploy
After (read-only root, code owned by root, tmpfs for caches):
1  write public/shell.php                     -> EROFS: Read-only file system
2  write /tmp/x.php                           -> allowed, but /tmp is noexec and not under the web root
3  container restart                          -> tmpfs is empty again

Real scenarios: Nginx needing /var/cache/nginx and its PID path writable (the unprivileged image uses /tmp); Laravel's bootstrap/cache and storage/framework/*; a Go binary that writes nothing at all; Java or Python apps that write bytecode caches next to the code.

PlatformRead-only rootWritable scratchDurable data
Docker--read-only--tmpfs /tmp:size=64m,noexec,nosuid-v / --mount type=volume
Composeread_only: truetmpfs: [/tmp]volumes:
KubernetesreadOnlyRootFilesystem: trueemptyDir (medium: Memory)PVC
Restricted PSSnot requiredn/an/a

Fix: turn it on for every service and list the tmpfs paths next to it; enforce it with a policy engine, because PSS will not.

Privileged containers, docker socket exposure and Docker-in-Docker Must-know ​

In plain words: Three ways to give a container the host. --privileged turns off the sandbox; the Docker socket lets the container ask the host daemon to start any container it likes; Docker-in-Docker usually needs one of the two.

Common misunderstanding: "Mounting the socket read-only (:ro) is safe." The ro flag stops writes to the socket file, not API calls over it. Whoever can talk to the daemon can run docker run -v /:/host --privileged; Docker says only trusted users should control it, and its post-install guide warns that "The docker group grants root-level privileges to the user."

Definition: Docker's reference lists what --privileged does: "Enables all Linux kernel capabilities", "Disables the default seccomp profile", "Disables the default AppArmor profile", "Disables the SELinux process label", "Grants access to all host devices", "Makes /sys read-write", "Makes cgroups mounts read-write", and warns: "A container with --privileged is not a securely sandboxed process. Containers in this mode can get a root shell on the host and take control over the system." The Docker-in-Docker image states "--privileged is required for Docker-in-Docker to function properly" and that running it "is generally not recommended". GitLab's documentation compares the CI options: Docker-in-Docker needs privileged mode; Docker socket binding does not, but "When you share the Docker daemon, you effectively disable the container's security mechanisms and expose your host to privilege escalation." Compose's newer use_api_socket mounts the engine socket and your credentials so "the container acts as a pure delegate for your commands".

text
A CI job with /var/run/docker.sock mounted
1  job runs: docker run --rm -v /:/host --privileged alpine chroot /host sh
2  host dockerd (root) creates the container: all caps, no seccomp, host / mounted
3  the job now has a root shell on the CI host
4  every other job, every cached credential and the runner token are exposed

Real scenarios: CI runners with the socket mounted for docker build; monitoring agents (cAdvisor-style) asking for the socket; "it needs privileged" for a network tool that only needs NET_ADMIN; Kubernetes privileged: true DaemonSets for CNI or storage, which is what the privileged PSS level exists for.

NeedDangerous waySafer way
Build images in CISocket mount or docker:dind --privilegedRootless BuildKit, Buildah, Kaniko-style builders, remote builders
One kernel feature--privileged--cap-add the single capability + a profile
Access one device--privileged--device /dev/xyz
Inspect other containersSocket mountRuntime metrics APIs, read-only exporters
Kubernetes node agentprivileged: true everywhereDedicated namespace at PSS privileged, everything else restricted

Fix: no socket mounts and no --privileged in application workloads; build images with rootless builders; isolate the few infrastructure workloads that need privilege in their own namespaces and nodes.

Resource limits as security: PID limits and fork bombs Important ​

In plain words: Limits are a security control because exhaustion is an attack: a container that can create unlimited processes or eat all memory can take down every neighbour and the node agents.

Common misunderstanding: "A memory limit also stops a fork bomb." The kernel's cgroup docs say the opposite: "a fork bomb is likely to exhaust the number of tasks before hitting memory restrictions", which is why the pids controller exists.

Definition: The cgroup v2 pids controller "is used to allow a cgroup to stop any new tasks from being fork()'d or clone()'d after a specified limit is reached"; its file pids.max defaults to max, and the limit counts threads (TIDs). Docker: --pids-limit ("set -1 for unlimited"), Compose pids_limit. Kubernetes sets it per node, not per Pod spec: --pod-max-pids or PodPidsLimit in the kubelet configuration, because "It is trivial to hit the task limit without hitting any other resource limits, which can then cause instability to a host machine." Docker's security page frames cgroups the same way: they ensure "a single container cannot bring the system down by exhausting one of those resources."

text
Fork bomb in a container, pids.max = 128
1  :(){ :|:& };:  starts doubling processes
2  task 129 -> fork() returns EAGAIN inside that cgroup only
3  pids.events max counter increments (visible to monitoring)
4  other containers and kubelet keep forking normally
without a limit: node-wide pid_max (e.g. 32768) is exhausted, sshd, kubelet, runtime cannot fork

Real scenarios: a Go service with a goroutine-per-request bug is not a fork bomb (goroutines are not threads), but a cgo-heavy one can be; PHP-FPM pm.max_children misconfigured; a compromised container used for crypto-mining (CPU limit); log flooding filling the node disk (log rotation, ephemeral-storage limits).

ResourceDocker / ComposeKubernetesWhat it stops
Processes/threads--pids-limit, pids_limitkubelet PodPidsLimit, node PID reservationFork bombs, thread leaks
Memory--memory, mem_limitresources.limits.memoryNode OOM, noisy neighbours
CPU--cpus, cpusresources.limits.cpu / requestsMining, starvation
Disklog driver rotation, --storage-optephemeral-storage limits, emptyDir.sizeLimitNode disk exhaustion

Fix: set pids, memory and CPU limits on every container, and kubelet PID limits on every node. Sizing is Resources, Scheduling & Autoscaling; the cgroup mechanics are Containers Under the Hood.

Image provenance: trusted base images, minimal images, distroless Must-know ​

In plain words: Know where every byte of your image came from, and ship as few bytes as possible: every extra package is something to patch, scan and possibly exploit.

Common misunderstanding: "A popular image on Docker Hub is trustworthy." Popularity is not provenance. NIST lists "Use of untrusted images" among the image risks: running externally provided images "results in the same types of risks that external software traditionally has, such as introducing malware, leaking data, or including components with vulnerabilities."

Definition: Image provenance is the verifiable record of who built an image, from which source and base. A trusted base image comes from a publisher you have decided to trust (official images, a vendor's signed images, your platform team's golden images), pinned by digest and rebuilt when it changes. Minimal images contain only what the program needs; "Distroless" images "contain only your application and its runtime dependencies. They do not contain package managers, shells or any other programs you would expect to find in a standard Linux distribution." The Kubernetes checklist: "image used in production should not contain shells or debugging utilities, as an ephemeral debug container can be used for troubleshooting."

text
Choosing the base for the api service
1  golang:1.27 (full toolchain, Debian)        -> hundreds of packages in the runtime: no
2  debian:trixie-slim + binary                 -> shell, apt, libc: patchable, still a shell
3  gcr.io/distroless/static-debian13:nonroot    -> CA certs, tzdata, passwd, no shell, UID 65532
4  scratch + binary                            -> nothing at all, but also no CA bundle
5  pin: FROM ...@sha256:<digest>; rebuild on base updates; record base digest in a label

Real scenarios: a typosquatted image name (ngnix); an abandoned community image with a two-year-old OpenSSL; a "debug" tag with a shell shipped to production; a vendor image signed with cosign that you can verify at admission.

SourceTrust signalWatch out for
Docker Official ImagesCurated, rebuilt for security updatesTags move; pin digests
Vendor images (distroless, Chainguard-style, Red Hat UBI)Signatures, SBOMs, published provenanceVerify the identity, not just "signed"
Your golden base imagesBuilt by your CI, signed by your identityMust actually be rebuilt on CVEs
Random community imagesNoneTyposquats, abandonment, embedded malware

Fix: a short allowlist of base images, pinned by digest, rebuilt automatically, enforced by an admission policy that checks registry and digest. Image construction details are in Images & Dockerfiles.

Image scanning: Trivy, Grype, Docker Scout; CVE, CVSS, VEX Must-know ​

In plain words: A scanner lists the packages in an image and looks each version up in vulnerability databases. It tells you what is known to be broken, how bad it is, and whether a fix exists.

Common misunderstanding: "CVSS 9.8 means drop everything." CVSS base scores describe the vulnerability in general, not in your image. CVSS v4.0 itself says the Environmental and Threat metrics "is the responsibility of the CVSS consumer", and databases such as NVD "typically provide only the Base Scores". Whether the vulnerable function is even reachable is what VEX and tools like govulncheck answer.

Definition: A CVE is a public identifier for one vulnerability. CVSS scores it; the v4.0 qualitative scale is None 0.0, Low 0.1–3.9, Medium 4.0–6.9, High 7.0–8.9, Critical 9.0–10.0, with nomenclature CVSS-B (base), -BT, -BE, -BTE. VEX (Vulnerability Exploitability eXchange) is a statement by the producer about one CVE in one product, with status not_affected, affected, fixed or under_investigation; a not_affected statement "MUST include either a status justification or an impact_statement", the justifications being fixed labels such as component_not_present, vulnerable_code_not_present and vulnerable_code_not_in_execute_path. Trivy has "scanners that look for security issues, and targets where it can find those issues" (container images, filesystems, Git repositories, VM images, Kubernetes; CVEs, misconfigurations, secrets, licences) and reads VEX with --vex. Grype scans "container images, filesystems, and SBOMs", supports EPSS/KEV prioritisation and OpenVEX. Docker Scout compiles an SBOM and matches it "against a continuously updated vulnerability database"; docker scout cves --exit-code returns "exit code '2' if vulnerabilities are detected", and it accepts VEX with --vex-location.

text
Pipeline gate for one image digest
1  trivy image --scanners vuln,secret --severity HIGH,CRITICAL --ignore-unfixed --exit-code 1 @D
2  finding: CVE in a Go module, High, fix available       -> fail the build, bump the module
3  finding: CVE in a module, govulncheck: no call path    -> write VEX not_affected +
                                                             vulnerable_code_not_in_execute_path
4  re-run with --vex api.openvex.json                      -> finding suppressed, with a reason on record
5  nightly: re-scan every running digest (databases change daily, images do not)

Real scenarios: a distroless Go image with zero OS findings but one finding in the Go standard library (rebuild with a patched Go); a Debian base with hundreds of "unfixed" low findings (--ignore-unfixed keeps the gate meaningful); two scanners disagreeing because they use different databases; a Laravel image whose Composer vendor/ is scanned because the lock file is inside.

ScannerInputsGate flagsVEX
Trivyimage, fs, repo, VM, Kubernetes, SBOM--severity, --exit-code, --ignore-unfixed, --scanners--vex <file>, --vex repo, --vex oci, --vex sbom-ref
Grypeimage, filesystem, SBOM (grype sbom:./sbom.json)scan-action: fail-build, severity-cutoff (default fails at medium)OpenVEX
Docker Scoutimage, SBOM--exit-code, --only-severity, --only-fixed--vex-location, --only-vex-affected
govulncheckGo source or binarynon-zero exit on reachable vulnerabilitiesn/a (it is the reachability check)
Registry scanners (ECR, GHCR, Harbor)images on push / continuousregistry policyvaries

Fix: scan in CI on the pushed digest, fail on fixable High/Critical, record exceptions as VEX with a justification, and re-scan running digests on a schedule. SAST/SCA policy belongs to Secure SDLC.

SBOM, SLSA and cosign signing Important ​

In plain words: An SBOM is the ingredients list; provenance is the "made in this factory, from this recipe" label; a signature is the tamper-evident seal with the maker's name on it.

Common misunderstanding: "A signed image is a safe image." A signature proves who vouches for a digest and that it was not changed since. It says nothing about whether the content is good; verification must also check which identity signed it.

Definition: An SBOM (Software Bill of Materials) lists every component (SPDX or CycloneDX); BuildKit attaches one as an attestation with --sbom=true (Images & Dockerfiles). SLSA "is a set of incrementally adoptable guidelines for supply chain security"; its build track levels are L0 (none), L1 "Provenance showing how the package was built", L2 "Signed provenance, generated by a hosted build platform" (against "Tampering after the build") and L3 "Hardened build platform" (against "Tampering during the build"). cosign signs an image digest; keyless signing authenticates "with an OIDC (OpenID Connect) protocol", Sigstore's CA Fulcio issues a short-lived certificate bound to that identity, and the signature is recorded in Rekor, "an immutable, append-only ledger"; "the private key is discarded after a single signing". cosign verify takes --certificate-identity and --certificate-oidc-issuer; cosign attest / verify-attestation do the same for SBOMs and provenance.

text
Keyless signing from GitHub Actions, verification at admission
1  workflow requests an OIDC token (permissions: id-token: write)
2  cosign generates an ephemeral key pair, sends the public key + token to Fulcio
3  Fulcio issues a certificate: subject = .../secure-build.yml@refs/heads/main, issuer = token.actions...
4  cosign signs the digest, uploads signature + certificate to the registry, entry to Rekor
5  Kyverno at Pod admission: signature valid? certificate identity == expected workflow? in Rekor? -> admit

Real scenarios: a registry credential leak used to push a backdoored :latest (admission rejects it: no signature from the workflow identity); an auditor asking which builds contain a given library (SBOM query); proving an image was built by CI and not on a laptop (provenance, SLSA L2+).

ArtefactProduced byVerified by
SBOMBuildKit --sbom, Syft, Docker ScoutScanners (Trivy, Grype read SBOMs), inventory tools
ProvenanceBuildKit --provenance=mode=max, SLSA generatorscosign verify-attestation, policy engines
Signaturecosign sign (key, KMS, or keyless)cosign verify, Kyverno ImageValidatingPolicy
VEXvexctl, vendor feeds, attestationsTrivy, Grype, Docker Scout
From commit to running pod: where each supply-chain control sits1 source + depsgo.sum, composer.lockcanonical private repoGOPRIVATE paths2 hosted buildpinned trusted basesecrets as mountstoken: contents read3 artefactsdigest sha256:...SBOM (SPDX)SLSA provenance4 scan gateTrivy, Grype, ScoutCVE, CVSS, fixableminus VEX entries8 node runtimepull @sha256securityContextFalco watches (eBPF)7 admissionPSA restrictedKyverno, Gatekeepersigned, digest, repo6 registryimage + signature+ attestationspull needs a login5 signcosign keyless: OIDC-> Fulcio certificate-> Rekor log entryWhat each control proves, and what it does notSBOM: what is inside. Scanner: which parts have known CVEs today (re-scan daily).VEX: the producer says a CVE is not exploitable here, with a machine-readable reason.Provenance (SLSA): which builder and source made this digest. Signature: who vouches.Admission: only verified digests start. None of this stops a zero-day in your code.Weakest links in practice: a CI token that can push any tag, a self-hosted runnershared with pull requests, and a tag deployed instead of a digest.

Fix: sign every pushed digest in CI with keyless cosign, attach SBOM and provenance, and verify identity plus digest at admission.

Secrets handling: no secrets in images, build secrets, runtime secret files Must-know ​

In plain words: Images are copied, cached, shared and scanned by many parties; anything inside them is effectively public. Secrets must arrive at build time through mounts that leave no trace, and at run time as files or environment injected by the platform.

Common misunderstanding: "I deleted the .env in a later layer." Earlier layers still contain it. NIST: when secrets are embedded in the image file system, "anyone with access to the image can easily parse it to learn these secrets."

Definition: Docker's build docs: "Build arguments and environment variables are inappropriate for passing secrets to your build, because they persist in the final image." Build secrets use RUN --mount=type=secret,id=... (optionally env=), which makes the secret "temporarily available inside the build container, for the duration of the build instruction", or SSH mounts for Git. At run time, Compose "Secrets are mounted as a file in /run/secrets/<secret_name>"; official images follow the *_FILE convention (MYSQL_PASSWORD_FILE). Kubernetes Secrets "are, by default, stored unencrypted in the API server's underlying data store (etcd)", and "anyone who is authorized to create a Pod in a namespace can use that access to read any Secret in that namespace"; encryption at rest and RBAC are the first steps (Kubernetes Config, Secrets & Storage).

text
Where a token ends up, by mechanism
1  ARG NPM_TOKEN / --build-arg      -> docker history, max-mode provenance
2  ENV NPM_TOKEN                     -> image config, every container's environment, /proc/1/environ
3  COPY .npmrc + RUN rm .npmrc       -> still in the COPY layer
4  RUN --mount=type=secret,id=npm    -> only in that RUN's mount namespace; not in any layer
5  runtime: /run/secrets/x (0400)    -> readable by the app user only; rotate without rebuilding

Real scenarios: a Laravel image built with .env inside (scanners with secret detection find APP_KEY); a Go service logging its config struct with the DB password; an environment variable leaked through a crash dump or /debug/vars; a Kubernetes Secret read by anyone who can create a Deployment in the namespace.

StageWrongRight
BuildARG, ENV, COPY of credentials--mount=type=secret, --mount=type=ssh
Image.env, keys, auth.json in the context.dockerignore + secret scanning (Trivy --scanners secret)
Run (Docker/Compose)-e PASSWORD=... on the command linesecrets: files, *_FILE variables
Run (Kubernetes)Plain Secret + broad RBACEncryption at rest, least-privilege RBAC, external secret store, volume mounts over env

Fix: secret mounts at build time, secret files at run time, secret scanning in CI, rotation that does not need a rebuild. Laravel's APP_KEY is worked through in Laravel.

Kubernetes Pod Security Standards and Pod Security Admission Must-know ​

In plain words: Kubernetes ships three named security levels for Pods and a built-in gatekeeper that applies one of them to each namespace, rejecting, warning about or logging Pods that do not meet it.

Common misunderstanding: "PSA checks my Deployments." In enforce mode it checks Pods only: "audit and warning modes are applied to the workload resources. However, enforce mode is not applied to workload resources, only to the resulting pod objects." A non-compliant Deployment is accepted, and then its ReplicaSet silently fails to create Pods.

Definition: The Pod Security Standards "define three different policies to broadly cover the security spectrum. These policies are cumulative": Privileged, "Unrestricted policy, providing the widest possible level of permissions"; Baseline, "Minimally restrictive policy which prevents known privilege escalations"; Restricted, "Heavily restricted policy, following current Pod hardening best practices." Baseline forbids host namespaces, privileged, hostPath, host ports, capabilities beyond 13 default-like ones, non-default /proc mounts, unconfined seccomp, overriding AppArmor, custom SELinux types/users/roles and unsafe sysctls. Restricted adds: volume types limited to configMap, csi, downwardAPI, emptyDir, ephemeral, persistentVolumeClaim, projected and secret; allowPrivilegeEscalation: false; runAsNonRoot: true and runAsUser not 0; seccomp RuntimeDefault or Localhost ("Both the Unconfined profile and the absence of a profile are prohibited"); "Containers must drop ALL capabilities, and are only permitted to add back the NET_BIND_SERVICE capability". Pod Security Admission (stable since v1.25) reads namespace labels pod-security.kubernetes.io/<MODE>: <LEVEL> and optional <MODE>-version: <VERSION>, with modes enforce (reject), audit (annotate the audit event) and warn (user-facing warning). Exemptions by username, RuntimeClass or namespace live in the admission configuration. For Pods with hostUsers: false, the runAsNonRoot and runAsUser checks are relaxed, because root there "is never mapped to a privileged user on the host".

Pod Security Standards: three cumulative levels, applied per namespaceprivilegedno restrictions: CNI, storage and node agents onlybaseline: prevents known escalationsno hostNetwork / hostPID / hostIPC, no privilegedno hostPath volumes, no hostPort, default /proccapabilities.add only from 13 default-like onesseccomp not Unconfined; AppArmor not overriddenrestricted: hardening best practiceallowPrivilegeEscalation: falserunAsNonRoot: true, runAsUser not 0drop includes ALL; add only NET_BIND_SERVICEseccompProfile: RuntimeDefault or Localhostvolumes: configMap, secret, emptyDir, PVC ...not required: read-only rootfs, limits,signatures: add a policy enginePod SecurityAdmissionbuilt in, stable v1.25(PSP removed)labels, prefixpod-security.kubernetes.io/enforce: restrictedenforce-version: v1.37warn: restrictedaudit: restrictedenforce: reject the podaudit: annotate eventwarn: warn the clientenforce checks Pods only;audit and warn alsocheck pod templatesexempt: users,runtimeClasses, nsBefore enforcing: kubectl label --dry-run=server --overwrite ns --all \pod-security.kubernetes.io/enforce=restricted
text
Rolling out restricted on an existing namespace
1  kubectl label --dry-run=server --overwrite ns shop pod-security.kubernetes.io/enforce=restricted
   -> the server prints warnings for existing pods that would violate it
2  label warn=restricted, audit=restricted (enforce stays baseline) -> teams see warnings on apply
3  fix manifests: allowPrivilegeEscalation, drop ALL, runAsNonRoot, seccompProfile
4  label enforce=restricted, enforce-version=v1.37 (pinned)
5  new non-compliant pods are rejected; existing pods keep running until replaced

Real scenarios: the warning would violate PodSecurity "restricted:latest": allowPrivilegeEscalation != false ... on kubectl apply; a Helm chart from a vendor that needs a values override (securityContext: blocks) before it can run in a restricted namespace; CNI and CSI DaemonSets in kube-system labelled privileged; a cluster upgrade that changes the meaning of latest.

NeedMechanismNotes
The three standard levelsPSA namespace labelsBuilt in, no CRDs
Cluster-wide defaultPodSecurity admission configuration (defaults, exemptions)API server flag file
Rules PSS does not haveKyverno, Gatekeeper, ValidatingAdmissionPolicySee policy engines
Migrating from PodSecurityPolicyPSP removed in v1.25Map PSPs to levels, then labels
RBAC, ServiceAccounts, audit policyKubernetes SecuritySeparate chapter

Fix: label every application namespace enforce: restricted with a pinned version, warn/audit at latest; keep privileged workloads in their own namespaces. The namespace snippet shows the labels.

securityContext: runAsNonRoot, allowPrivilegeEscalation, readOnlyRootFilesystem, drop capabilities, seccompProfile RuntimeDefault Must-know ​

In plain words: The securityContext blocks in a Pod spec are where every runtime control on this page is written down for Kubernetes: once for the Pod, once per container.

Common misunderstanding: "Setting it at Pod level covers everything." Some fields exist only at container level (allowPrivilegeEscalation, capabilities, readOnlyRootFilesystem, privileged), and container values override Pod values where both exist.

Definition: Kubernetes describes security contexts as runtime parameters, distinct from security profiles: "Security Contexts configure Pods and Containers at runtime", while "Security profiles are control plane mechanisms to enforce specific settings in the Security Context." Pod level: runAsUser, runAsGroup, runAsNonRoot, fsGroup (volume group ownership; "all processes of the container are also part of the supplementary group"), supplementalGroups, supplementalGroupsPolicy: Strict, seccompProfile, appArmorProfile, seLinuxOptions, sysctls. Container level: the same identity and profile fields plus allowPrivilegeEscalation, capabilities, privileged, readOnlyRootFilesystem ("Mounts the container's root filesystem as read-only") and procMount. Pod spec fields next to it: hostUsers, automountServiceAccountToken, hostNetwork/hostPID/hostIPC.

text
Minimal restricted-compliant container, field by field
1  pod.securityContext.runAsNonRoot: true          kubelet refuses UID 0
2  pod.securityContext.seccompProfile.type: RuntimeDefault
3  container.securityContext.allowPrivilegeEscalation: false   -> no_new_privs = 1
4  container.securityContext.capabilities.drop: ["ALL"]        -> CapBnd = 0
5  (not required, added) readOnlyRootFilesystem: true + emptyDir for /tmp
6  (not required, added) automountServiceAccountToken: false, hostUsers: false, limits

Real scenarios: an init container that chowns a volume and therefore needs CHOWN (use fsGroup instead); a sidecar from a mesh that violates restricted until its own securityContext is set; procMount: Unmasked requested by a nested-container tool (baseline forbids it); fsGroup on a large volume slowing start-up (the fsGroupChangePolicy field addresses it).

FieldLevelRestricted requiresOur Deployment
runAsNonRootPod/containertruetrue (pod)
runAsUserPod/containernot 065532
allowPrivilegeEscalationcontainerfalsefalse
capabilities.dropcontainerincludes ALL["ALL"]
seccompProfile.typePod/containerRuntimeDefault or LocalhostRuntimeDefault
readOnlyRootFilesystemcontainernotrue
appArmorProfilePod/containerbaseline: not unconfinedRuntimeDefault
hostUsersPodnofalse
automountServiceAccountTokenPodnofalse

Fix: copy the Deployment snippet as the template for every chart; Helm charts expose the two blocks as podSecurityContext / securityContext values.

Admission control and policy engines: Kyverno, OPA Gatekeeper Important ​

In plain words: Admission control is the last check before an object is stored in the cluster. Policy engines let you write your own checks ("images only from our registry", "read-only root filesystem required", "must be signed") and reject what fails.

Common misunderstanding: "A policy engine replaces PSA." They overlap; PSA is built in and cannot be bypassed by a crashed webhook. Use PSA for the standard levels and the engine for everything else, so a misconfigured webhook (failurePolicy: Ignore) does not silently remove the baseline.

Definition: Admission webhooks run "whenever a resource is created, updated or deleted". OPA Gatekeeper "is a validating and mutating webhook that enforces CRD-based policies executed by Open Policy Agent", with ConstraintTemplates in Rego and an audit function showing "what resources are currently violating any given policy". Kyverno policies are Kubernetes resources; its current types are ValidatingPolicy, MutatingPolicy, GeneratingPolicy, DeletingPolicy and ImageValidatingPolicy (API policies.kyverno.io/v1), written in CEL. "A ValidatingPolicy is a superset of a ValidatingAdmissionPolicy" (the in-tree CEL admission type). ImageValidatingPolicy verifies cosign or Notary signatures and attestations and can rewrite tags to digests: "Using an image digest has the benefit of making image references immutable." Kyverno's policy library ships PSS equivalents (for example "Containers must drop ALL capabilities"). Two matching details decide whether a policy can be bypassed: check every container list (containers, initContainers, ephemeralContainers), and match the pods/ephemeralcontainers subresource as well as pods, because "Ephemeral containers are created using a special ephemeralcontainers handler in the API rather than by adding them directly to pod.spec" and the admission rule docs state that "*" matches all resources, but not subresources (a rule for pods does not see them either). The chapter's policies do both, and k8s/kyverno-test/ holds CLI fixtures whose only violation is the init container.

text
kubectl apply of a Deployment in namespace shop
1  API server: authentication, RBAC
2  mutating admission: Kyverno ImageValidatingPolicy rewrites ghcr.io/acme/api:1.0 -> @sha256:D
3  validating admission: PodSecurity (built in) checks the pod template in warn/audit
4  Kyverno ValidatingPolicy: readOnlyRootFilesystem? registry ghcr.io/acme? digest?
5  object stored; ReplicaSet creates the Pod -> PodSecurity enforce + Kyverno image verification
6  Kyverno background scan reports existing violators in PolicyReports

Real scenarios: a team pulling bitnami/... images directly (registry policy); an image without signature after a manual hotfix (rejected; the hotfix goes through CI); policies rolled out in Audit first, reviewed through PolicyReports, then switched to Deny; GitOps with Argo CD where policy violations show as sync failures.

EngineLanguageStrengthsCost
PSA (built in)fixed levelsAlways on, no webhookOnly the PSS controls
ValidatingAdmissionPolicy (built in)CELNo webhook, fastNo image verification, no background reports
KyvernoCEL (and legacy JMESPath)Kubernetes-native YAML, image verification, mutation, generation, reportsA webhook to operate
OPA GatekeeperRegoSame engine as OPA elsewhere (Terraform, CI), mature auditRego learning curve

Fix: PSA for the floor; one engine for registry, digest, signature, read-only root and labels; policies in Git, tested in CI, rolled out Audit then Deny. The Kyverno snippet has three such policies.

Network policies Important ​

In plain words: Firewall rules between pods. Without them, every pod can talk to every other pod and to the outside world.

Common misunderstanding: "Creating a NetworkPolicy protects my pods." Only if the cluster's network plugin implements them: "Creating a NetworkPolicy resource without a controller that implements it will have no effect."

Definition: "By default, a pod is non-isolated for egress; all outbound connections are allowed" and likewise for ingress. A pod becomes isolated in a direction once any NetworkPolicy selecting it lists that direction in policyTypes; allowed traffic is then the union of all policies' rules. The standard first step is a namespace-wide default deny (podSelector: {} with both policy types), then explicit allows, including DNS egress. Docker's equivalent is user-defined networks with internal: true and "icc": false on the daemon.

text
Default deny + allow in namespace shop
1  default-deny-all: podSelector {} , policyTypes [Ingress, Egress]  -> every pod isolated
2  api-allow ingress from namespace ingress-nginx on TCP 8080
3  api-allow egress to kube-dns on UDP/TCP 53
4  compromised api pod: curl postgres:5432 -> dropped; curl 169.254.169.254 -> dropped

Real scenarios: an RCE pivoting to the database or to the cloud metadata endpoint; a forgotten DNS egress rule breaking every lookup after default deny; a CNI that does not enforce policies until a feature flag is set.

LayerToolScope
Pod to pod (L3/L4)NetworkPolicy (Calico, Cilium, ...)Namespace / labels
L7, identityService mesh authorisation, Cilium L7 policiesService identity
Docker hostuser-defined networks, internal: true, icc: falseHost
Node / cloudSecurity groups, iptables/nftablesFirewalls

Fix: default deny per namespace, allow lists per workload, egress included; the NetworkPolicy snippet is the template.

Runtime security: Falco, eBPF, audit logging Important ​

In plain words: Prevention fails sometimes. Runtime security watches what containers actually do (programs started, files opened, connections made) and alerts on what should never happen.

Common misunderstanding: "Falco blocks attacks." Falco detects and alerts; blocking is done by the controls above (or by response tooling acting on the alert). Detection is only useful if someone receives and acts on the alerts.

Definition: Falco's components are a userspace program, configuration, a driver that "sends a stream of kernel events" (the default is the "Modern eBPF probe (CO-RE paradigm and more)", alternatively a kernel module), plugins and falcoctl. Rules are YAML: "Rules are the conditions under which an alert should be generated"; the default Terminal shell in container rule combines macros spawned_process (evt.type in (execve, execveat)), container and shell_procs. eBPF lets such tools run verified programs in the kernel without modules. Audit logging complements it: the Kubernetes API server records requests at levels None, Metadata, Request and RequestResponse (policy in Kubernetes Security), PSA's audit mode annotates those events, and LSMs write AVC/AppArmor denials to the kernel audit log.

text
Shell spawned in the distroless api container
1  attacker's exploit runs execve("/tmp/sh")       (copied in; image has no shell)
2  eBPF probe emits the execve event with container id, image, pod
3  rule "Shell in distroless acme container" matches -> CRITICAL alert
4  falcosidekick forwards to the on-call channel / SIEM
5  responder isolates the pod (NetworkPolicy), captures it, replaces it from the signed digest

Real scenarios: kubectl exec into production flagged and correlated with the API audit log; a crypto-miner's outbound connection to a mining pool; writes below /etc in a running container; an AppArmor denial burst after a deploy (profile too tight or attack).

SignalSourceTool
Process, file, network syscallseBPF / kernel moduleFalco and other eBPF agents
Kubernetes API actionsAPI server audit logSIEM, Falco k8saudit plugin
LSM denialsKernel audit (dmesg, auditd)auditd, journald
Image driftRead-only rootfs + write attemptsFalco rule on open_write

Fix: run Falco as a DaemonSet with the default rules plus local rules for your images (snippet), ship alerts somewhere watched, and keep API audit logs. Debugging with eBPF tools is Linux Debugging.

Supply chain: dependency confusion, registry authentication, least privilege for CI runners Important ​

In plain words: The image is only as trustworthy as everything that made it: the packages it pulls, the registry it is stored in and the CI machine that built and pushed it.

Common misunderstanding: "Private packages cannot be hijacked because they are private." If the resolver also looks at the public registry, a public package with the same name and a higher version wins. Composer's documentation describes exactly this: "if someone publishes foo/bar 2.999 to packagist.org, suddenly Composer will pick that package as it has a higher version than your latest release".

Definition: Dependency confusion is an attacker publishing a public package with the name of your internal one; the defence is a resolver that treats the private source as authoritative. Composer repositories are canonical by default: "if the private repository is canonical, that 2.999 version from packagist.org will not be considered at all"; in Go, GOPRIVATE/GONOPROXY/GONOSUMDB route private module paths away from the public proxy and checksum database, and go.sum pins hashes. Registry authentication means pulls and pushes need credentials scoped per repository (pull-only on nodes, push only from CI), with immutable tags or digests. Least privilege for CI runners: GitHub recommends "to set the default permission for the GITHUB_TOKEN to read access only for repository contents", pinning actions "to a full-length commit SHA", and warns that "self-hosted runners should almost never be used for public repositories"; GitHub-hosted runners run in "ephemeral and clean isolated virtual machines".

text
How a CI job becomes a supply-chain attack, and what stops each step
1  PR from a fork runs on a self-hosted runner      -> ephemeral GitHub-hosted or JIT runners
2  job reads a long-lived registry password         -> OIDC, short-lived, per-repo push scope
3  job pushes ghcr.io/acme/api:latest               -> immutable tags; deploy by digest
4  job uses third-party action @v4 that was hijacked -> pin by commit SHA
5  image deployed                                    -> admission: signature identity = main-branch workflow

Real scenarios: an internal npm/Composer package name published on the public registry with a post-install script; a long-lived Docker Hub token in a CI variable copied by a malicious workflow; a tag on a popular action moved to a malicious commit; a node pull secret with push rights.

ControlGitHub ActionsRegistry
Token scopepermissions: per job, default read-onlypull-only credentials on nodes, push only from CI
Short-lived cloud credsOIDC id-token: writeIAM roles trusted for the CI identity
Runner isolationGitHub-hosted (ephemeral VMs), JIT self-hosted runnersn/a
Third-party codePin actions by full commit SHAMirror and scan base images, pin digests
Dependency confusionGOPRIVATE, canonical Composer repos, lock filesPrivate proxy registry for packages
Build without the daemonHosted buildersGitLab: rootless BuildKit or Buildah instead of Docker-in-Docker

Fix: the CI snippet applies all of it to one workflow; runners, OIDC and environments are taught in CI/CD Pipelines.

Benchmarks: CIS Docker Benchmark and NIST SP 800-190 Good to know ​

In plain words: Two reference documents that list, control by control, what a secure container setup looks like; auditors and checklists are built from them.

Common misunderstanding: "Passing Docker Bench means we are secure." It checks configuration against the benchmark; it knows nothing about your images' contents, your Kubernetes policies or your application.

Definition: The CIS Docker Benchmark "is the product of a community consensus process and consists of secure configuration guidelines developed for Docker"; cisecurity.org lists version 1.9.0, and Docker Bench for Security "is a script that checks for dozens of common best-practices around deploying Docker containers in production", based on CIS Docker Benchmark v1.6.0. NIST SP 800-190 (September 2017) organises risks into image risks (vulnerabilities, configuration defects, embedded malware, "Embedded clear text secrets", untrusted images), registry risks, orchestrator risks, container risks and host OS risks, each with countermeasures; it recommends container-specific host OSs and not mixing containerized and non-containerized workloads on one host.

text
Using the benchmarks in a quarterly review
1  run docker-bench-security on each Docker host        -> list of WARN items
2  map each to this page's controls (userns, no-new-privileges, logging, limits)
3  walk NIST 800-190 section 4 countermeasures for images, registry, orchestrator, containers, host
4  record exceptions with an owner and a date

Real scenarios: a compliance audit asking for evidence per CIS control; a hardening sprint prioritised by NIST's risk groups; a Kubernetes cluster audited with the separate CIS Kubernetes Benchmark (not covered here).

DocumentScopeForm
CIS Docker Benchmark 1.9.0Docker host, daemon, images, runtimePDF (free for non-commercial use), automated by Docker Bench
NIST SP 800-190Whole container stack, technology-neutralGuide, risks and countermeasures
Kubernetes security checklistCluster, Pods, images, admissionkubernetes.io checklist
Pod Security StandardsPod spec fieldsThree levels, enforced by PSA

Fix: use the benchmarks as audit checklists after the controls on this page are in place, not as the design.

Mechanics ​

What the flags become: the OCI runtime config ​

Docker, Podman, containerd and CRI-O all end in the same place: an OCI config.json that runc (or crun) applies before it runs the process. This excerpt shows the fields the hardened docker run and the Kubernetes Deployment on this page produce (shape from the OCI runtime spec; values for our api container):

json
{
  "process": {
    "user": { "uid": 65532, "gid": 65532 },
    "noNewPrivileges": true,
    "capabilities": { "bounding": [], "effective": [], "permitted": [], "ambient": [] },
    "apparmorProfile": "api-restricted"
  },
  "root": { "path": "rootfs", "readonly": true },
  "mounts": [
    { "destination": "/tmp", "type": "tmpfs", "source": "tmpfs", "options": ["nosuid", "noexec", "size=65536k"] }
  ],
  "linux": {
    "resources": { "pids": { "limit": 128 }, "memory": { "limit": 268435456 } },
    "seccomp": { "defaultAction": "SCMP_ACT_ERRNO", "defaultErrnoRet": 1, "syscalls": ["... 50 rules ..."] },
    "maskedPaths": ["/proc/kcore", "/proc/keys", "..."],
    "readonlyPaths": ["/proc/sys", "/proc/sysrq-trigger", "..."]
  }
}

The spec's own wording for the key fields: noNewPrivileges "prevents the process from gaining additional privileges"; capabilities.bounding is "an array of bounding capabilities that are kept for the process"; maskedPaths "will mask over the provided paths inside the container so that they cannot be read"; readonlyPaths "will set the provided paths as readonly inside the container". The default masks are why a plain container cannot read /proc/kcore; --privileged and procMount: Unmasked remove them.

The default seccomp profile is capability-aware ​

Docker's default.json is not one flat list. Its first rule allows 359 syscall names unconditionally; other rules allow syscalls only when a capability is present, or only with specific arguments. Two real rules from the saved profile:

json
{
  "names": ["bpf", "clone", "clone3", "fanotify_init", "fsconfig", "...", "mount", "perf_event_open", "setns", "umount2", "unshare"],
  "action": "SCMP_ACT_ALLOW",
  "includes": { "caps": ["CAP_SYS_ADMIN"] }
}
json
{
  "names": ["personality"],
  "action": "SCMP_ACT_ALLOW",
  "args": [{ "index": 0, "value": 0, "op": "SCMP_CMP_EQ" }]
}

So --cap-drop ALL shrinks the seccomp allowlist too: without CAP_SYS_ADMIN, mount and unshare are not just refused by the capability check, they never pass the filter. The chapter's derived profile goes further and removes 18 names from every rule (output of running the script on the saved profile):

py
#!/usr/bin/env python3
"""Derive a tighter seccomp profile for the api service from Docker's default.

Usage: python3 derive.py <moby default.json> <out-dir>
Writes api-seccomp.json (default minus DENY) and api-seccomp-log.json (same
allowlist, but unlisted syscalls are logged instead of refused: run the test
suite under it first and read the audit log before enforcing).

Starting from the maintained default keeps its argument filters and the
capability-conditional rules ("includes": {"caps": [...]}) that Docker uses to
re-allow mount/unshare/... only when CAP_SYS_ADMIN is granted.
"""
import json, sys, os

# A static Go HTTP server never needs these. Each removal is a syscall an
# attacker with code execution in the container can no longer reach.
DENY = {
    "ptrace", "process_vm_readv", "process_vm_writev", "kcmp",   # inspect other processes
    "personality",                                               # execution domains
    "chroot", "pivot_root", "mount", "umount", "umount2",        # filesystem tree changes
    "unshare", "setns",                                          # new or foreign namespaces
    "bpf", "perf_event_open",                                    # kernel programs and tracing
    "add_key", "keyctl", "request_key",                          # kernel keyring (not namespaced)
    "userfaultfd",                                               # common exploit primitive
    "open_by_handle_at", "name_to_handle_at",                    # the classic "shocker" escape path
    "syslog", "acct", "quotactl",
}

def derive(src, out_dir):
    prof = json.load(open(src))
    removed, rules = set(), []
    for rule in prof["syscalls"]:
        keep = [n for n in rule["names"] if n not in DENY]
        removed |= set(rule["names"]) - set(keep)
        if keep:
            rule = dict(rule, names=keep)
            rules.append(rule)
    prof["syscalls"] = rules
    enforce = os.path.join(out_dir, "api-seccomp.json")
    with open(enforce, "w") as f:
        json.dump(prof, f, indent=2); f.write("\n")
    log = dict(prof, defaultAction="SCMP_ACT_LOG")
    log.pop("defaultErrnoRet", None)
    with open(os.path.join(out_dir, "api-seccomp-log.json"), "w") as f:
        json.dump(log, f, indent=2); f.write("\n")
    allowed = sorted({n for r in rules if r["action"] == "SCMP_ACT_ALLOW" for n in r["names"]})
    print(f"default rules: {len(json.load(open(src))['syscalls'])}, derived rules: {len(rules)}")
    print(f"removed from allow rules ({len(removed)}): {' '.join(sorted(removed))}")
    print(f"in DENY but never allowed by the default ({len(DENY - removed)}): {' '.join(sorted(DENY - removed))}")
    print(f"distinct syscall names still allowed by some rule: {len(allowed)}")
    print(f"defaultAction: enforce={prof['defaultAction']} log={log['defaultAction']}")

if __name__ == "__main__":
    derive(sys.argv[1], sys.argv[2])
text
default rules: 62, derived rules: 50
removed from allow rules (18): acct bpf chroot kcmp mount name_to_handle_at open_by_handle_at perf_event_open personality process_vm_readv process_vm_writev ptrace quotactl setns syslog umount umount2 unshare
in DENY but never allowed by the default (5): add_key keyctl pivot_root request_key userfaultfd
distinct syscall names still allowed by some rule: 408
defaultAction: enforce=SCMP_ACT_ERRNO log=SCMP_ACT_LOG

The script writes api-seccomp.json (enforce) and api-seccomp-log.json (same allowlist, defaultAction: SCMP_ACT_LOG, the mode the Kubernetes seccomp tutorial uses for its audit profile). Run the service's tests under the log profile, read the kernel log for logged syscalls, and only then enforce. The profile is derived and JSON-validated but has not been run against a kernel in this environment.

The AppArmor profile ​

text
# AppArmor profile for the api container (modelled on the docker-nginx example
# in Docker's AppArmor docs). Not loaded in the build environment.
# Load:  sudo apparmor_parser -r -W /etc/apparmor.d/containers/api-restricted
# Use:   docker run --security-opt apparmor=api-restricted ...
#        Kubernetes: securityContext.appArmorProfile {type: Localhost, localhostProfile: api-restricted}
#include <tunables/global>

profile api-restricted flags=(attach_disconnected,mediate_deleted) {
  #include <abstractions/base>

  # TCP/UDP for the HTTP server and DNS; no raw or packet sockets (no spoofing, no sniffing).
  network inet tcp,
  network inet udp,
  network inet6 tcp,
  network inet6 udp,
  deny network raw,
  deny network packet,

  # The binaries this image ships, mapped and executed in this profile.
  /usr/local/bin/api mrix,
  /usr/local/bin/secreport mrix,

  # Read-only view of the image; CA bundle, zoneinfo and passwd for os/user.
  /etc/ssl/certs/** r,
  /usr/share/zoneinfo/** r,
  /etc/passwd r,
  /etc/group r,

  # The only writable path (a tmpfs at run time) and the mounted secret.
  /tmp/ r,
  /tmp/** rw,
  /run/secrets/signing_key r,

  # The runtime reads its own limits and status.
  @{PROC}/*/status r,
  @{PROC}/*/uid_map r,
  @{PROC}/sys/kernel/osrelease r,
  /sys/fs/cgroup/** r,

  # Never: shells, mounts, kernel interfaces.
  deny /bin/** mrwklx,
  deny /usr/bin/** mrwklx,
  deny mount,
  deny @{PROC}/sysrq-trigger rwklx,
  deny @{PROC}/kcore rwklx,
  deny /sys/firmware/** rwklx,
  deny /sys/kernel/security/** rwklx,

  # No capability rules: the container runs with --cap-drop ALL.
}

It follows the structure of the docker-nginx example in Docker's AppArmor docs (attach_disconnected,mediate_deleted, deny network raw, deny mount, explicit deny for /proc and /sys knobs). Load it on every node (or with a DaemonSet such as the Kubernetes AppArmor tutorial suggests) before any Pod references it; "If any of the specified profiles are not loaded in the kernel, the kubelet will reject the Pod" (the event reads apparmor profile not found).

Reading the result from inside: /proc/self/status ​

The kernel reports the result of all of the above per process (proc_pid_status(5)):

LineMeaningHardened api container
Uid:real, effective, saved set, filesystem UID65532 65532 65532 65532
CapPrm: / CapEff:permitted / effective capability masks (hex)0000000000000000
CapBnd:bounding set ("since Linux 2.6.26")0000000000000000 after cap_drop ALL
CapAmb:ambient set ("since Linux 4.3")0000000000000000
NoNewPrivs:"Value of the no_new_privs bit" (since Linux 4.10)1
Seccomp:"0 means SECCOMP_MODE_DISABLED; 1 means SECCOMP_MODE_STRICT; 2 means SECCOMP_MODE_FILTER"2
Seccomp_filters:number of attached filters (since Linux 5.9)1
/proc/self/uid_mapuser namespace mapping0 100000 65536 with hostUsers: false

Docker's default capability list decodes to the mask 00000000a80425fb (bits 0, 1, 3, 4, 5, 6, 7, 8, 10, 13, 18, 27, 29, 31); --privileged on a kernel whose last capability is CAP_CHECKPOINT_RESTORE (40) shows 000001ffffffffff. The Go package below computes and tests both values.

Kubernetes manifests ​

yaml
# Pod Security Admission: the built-in admission plugin (stable since v1.25)
# reads these labels. Enforce restricted, pinned to a minor version so a cluster
# upgrade cannot tighten (or loosen) the rules under running teams; warn and
# audit at `latest` to see what the next version would reject.
apiVersion: v1
kind: Namespace
metadata:
  name: shop
  labels:
    pod-security.kubernetes.io/enforce: restricted
    pod-security.kubernetes.io/enforce-version: v1.37
    pod-security.kubernetes.io/warn: restricted
    pod-security.kubernetes.io/warn-version: latest
    pod-security.kubernetes.io/audit: restricted
    pod-security.kubernetes.io/audit-version: latest
yaml
# The api Deployment: passes the restricted Pod Security Standard and adds the
# controls the standard does not require (read-only root filesystem, no
# service-account token, resource limits, a user namespace).
apiVersion: apps/v1
kind: Deployment
metadata:
  name: api
  namespace: shop
spec:
  replicas: 2
  selector:
    matchLabels: {app: api}
  template:
    metadata:
      labels: {app: api}
    spec:
      automountServiceAccountToken: false     # the api never calls the Kubernetes API
      hostUsers: false                        # user namespace: UID 0 inside is not root on the node
      securityContext:                        # pod level: inherited by every container
        runAsNonRoot: true
        runAsUser: 65532
        runAsGroup: 65532
        fsGroup: 65532
        seccompProfile:
          type: RuntimeDefault                # restricted requires RuntimeDefault or Localhost
      containers:
        - name: api
          # Digest, not tag: what was scanned and signed is what runs.
          image: ghcr.io/acme/api@sha256:0000000000000000000000000000000000000000000000000000000000000000
          ports:
            - containerPort: 8080             # >= 1024: no NET_BIND_SERVICE needed
          env:
            - name: SIGNING_KEY_FILE
              value: /run/secrets/signing_key
          securityContext:                    # container level
            allowPrivilegeEscalation: false   # sets no_new_privs
            readOnlyRootFilesystem: true      # not required by restricted; we add it
            privileged: false
            capabilities:
              drop: ["ALL"]
            appArmorProfile:
              type: RuntimeDefault            # or Localhost + localhostProfile: api-restricted
          resources:
            requests: {cpu: 100m, memory: 128Mi}
            limits: {memory: 256Mi}
          readinessProbe:
            httpGet: {path: /healthz, port: 8080}
          volumeMounts:
            - {name: tmp, mountPath: /tmp}
            - {name: signing-key, mountPath: /run/secrets, readOnly: true}
      volumes:
        - name: tmp
          emptyDir:
            medium: Memory                    # tmpfs, counted against the memory limit
            sizeLimit: 64Mi
        - name: signing-key
          secret:
            secretName: api-signing-key
            defaultMode: 0440                 # group-readable; the API notes the mode interacts with fsGroup (65532 here)
            items:
              - {key: signing_key, path: signing_key}
yaml
# Default deny for the namespace, then allow only what the api needs.
# Needs a network plugin that implements NetworkPolicy (Calico, Cilium, ...):
# without one these objects are accepted and have no effect.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny-all
  namespace: shop
spec:
  podSelector: {}
  policyTypes: [Ingress, Egress]
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: api-allow
  namespace: shop
spec:
  podSelector:
    matchLabels: {app: api}
  policyTypes: [Ingress, Egress]
  ingress:
    - from:
        - namespaceSelector:
            matchLabels:
              kubernetes.io/metadata.name: ingress-nginx
      ports:
        - {protocol: TCP, port: 8080}
  egress:
    - to:                                   # DNS only; no route to the internet or the API server
        - namespaceSelector:
            matchLabels:
              kubernetes.io/metadata.name: kube-system
          podSelector:
            matchLabels: {k8s-app: kube-dns}
      ports:
        - {protocol: UDP, port: 53}
        - {protocol: TCP, port: 53}
yaml
# Kyverno CEL policies (policies.kyverno.io/v1, Kyverno 1.20+) for what the
# restricted Pod Security Standard does not check. Start in Audit, move to Deny
# once the policy reports are clean. Each policy matches pods and the
# pods/ephemeralcontainers subresource (kubectl debug adds containers there).
apiVersion: policies.kyverno.io/v1
kind: ValidatingPolicy
metadata:
  name: require-readonly-rootfs
spec:
  validationActions: [Deny]
  matchConstraints:
    resourceRules:
      - apiGroups: [""]
        apiVersions: [v1]
        operations: [CREATE, UPDATE]
        resources: [pods]
      # Ephemeral containers arrive through this subresource, not through a pod
      # UPDATE; "pods" alone does not match subresources.
      - apiGroups: [""]
        apiVersions: [v1]
        operations: [UPDATE]
        resources: [pods/ephemeralcontainers]
  variables:
    - name: allContainers
      expression: >-
        object.spec.containers + object.spec.?initContainers.orValue([]) +
        object.spec.?ephemeralContainers.orValue([])
  validations:
    - expression: >-
        variables.allContainers.all(c,
          c.?securityContext.?readOnlyRootFilesystem.orValue(false) == true)
      message: "Every container must set securityContext.readOnlyRootFilesystem: true (mount an emptyDir for writable paths)."
---
apiVersion: policies.kyverno.io/v1
kind: ValidatingPolicy
metadata:
  name: allowed-registries
spec:
  validationActions: [Deny]
  matchConstraints:
    resourceRules:
      - apiGroups: [""]
        apiVersions: [v1]
        operations: [CREATE, UPDATE]
        resources: [pods]
      # Ephemeral containers arrive through this subresource, not through a pod
      # UPDATE; "pods" alone does not match subresources.
      - apiGroups: [""]
        apiVersions: [v1]
        operations: [UPDATE]
        resources: [pods/ephemeralcontainers]
  # Every container list: an init or ephemeral container is as dangerous as the main one.
  variables:
    - name: allContainers
      expression: >-
        object.spec.containers + object.spec.?initContainers.orValue([]) +
        object.spec.?ephemeralContainers.orValue([])
  validations:
    - expression: >-
        variables.allContainers.all(c, c.image.startsWith('ghcr.io/acme/') && c.image.contains('@sha256:'))
      message: "Images (including init and ephemeral containers) must come from ghcr.io/acme/ and be referenced by digest."
---
# Keyless cosign verification, modelled on the kyverno/policies sample
# verify-cosign-keyless: only images signed by our release workflow run.
apiVersion: policies.kyverno.io/v1
kind: ImageValidatingPolicy
metadata:
  name: verify-acme-signatures
spec:
  validationActions: [Deny]
  matchConstraints:
    resourceRules:
      - apiGroups: [""]
        apiVersions: ["v1"]
        operations: ["CREATE", "UPDATE"]
        resources: ["pods"]
      - apiGroups: [""]
        apiVersions: ["v1"]
        operations: ["UPDATE"]
        resources: ["pods/ephemeralcontainers"]
  matchImageReferences:
    - glob: ghcr.io/acme/*
  validationConfigurations:
    mutateDigest: true
    required: true
  attestors:
    - name: release
      cosign:
        keyless:
          identities:
            - issuer: https://token.actions.githubusercontent.com
              subject: https://github.com/acme/api/.github/workflows/secure-build.yml@refs/heads/main
        ctlog:
          url: https://rekor.sigstore.dev
  # Same list combination as the kyverno/policies verify-cosign-keyless sample.
  variables:
    - name: allImages
      expression: >-
        images.?containers.orValue([]) + images.?initContainers.orValue([]) +
        images.?ephemeralContainers.orValue([])
  validations:
    - expression: >-
        variables.allImages.map(image, verifyImageSignatures(image, [attestors.release])).all(n, n > 0)
      message: "Images (including init and ephemeral containers) must be signed by the acme release workflow."

The Kyverno file uses the CEL policy types (policies.kyverno.io/v1); the image policy is modelled on the verify-cosign-keyless sample in the kyverno/policies repository (identity = issuer + subject, Rekor URL). All four files parse as YAML; none was applied to a cluster here.

Falco rules ​

yaml
# Local Falco rules for the shop namespace, loaded after the default
# falco_rules.yaml so the macros spawned_process, container and shell_procs exist.
# The api image has no shell at all, so any shell is an intrusion, not a debug session.
- list: acme_distroless_images
  items: [ghcr.io/acme/api]

- rule: Shell in distroless acme container
  desc: >
    A shell ran in an image that ships none: someone copied a binary in or
    exploited the process. Default Falco only flags shells with a terminal;
    this rule flags every shell in these images.
  condition: >
    spawned_process
    and container
    and shell_procs
    and container.image.repository in (acme_distroless_images)
  output: >
    Shell in distroless container (user=%user.name uid=%user.uid
    command=%proc.cmdline parent=%proc.pname image=%container.image.repository
    container=%container.name k8s_ns=%k8s.ns.name k8s_pod=%k8s.pod.name)
  priority: CRITICAL
  tags: [container, shell, acme, mitre_execution]

- rule: Write below root in read-only acme container
  desc: >
    A write was attempted outside /tmp. With readOnlyRootFilesystem it fails
    with EROFS; the attempt itself is the signal.
  condition: >
    open_write
    and container
    and container.image.repository in (acme_distroless_images)
    and not fd.name startswith /tmp/
  output: >
    Write outside /tmp (file=%fd.name command=%proc.cmdline
    image=%container.image.repository k8s_pod=%k8s.pod.name)
  priority: WARNING
  tags: [container, filesystem, acme]

The fields (container.image.repository, k8s.ns.name, k8s.pod.name, fd.name) are from Falco's supported-fields reference and the macros from the default falco_rules.yaml.

The CI workflow ​

yml
# .github/workflows/secure-build.yml: build, gate, sign. Expected, not run.
# Every action is pinned to the full commit SHA of the release named in the
# comment (resolved 2026-11-29 from the GitHub API; Dependabot keeps them current).
name: secure-build
on:
  push:
    branches: [main]

# Least privilege: the token can read the repo and nothing else by default ...
permissions:
  contents: read

jobs:
  build:
    runs-on: ubuntu-latest            # GitHub-hosted: a fresh VM per job, nothing persists
    # ... and this job gets exactly what it needs: push to GHCR, mint an OIDC token for cosign.
    permissions:
      contents: read
      packages: write
      id-token: write
    outputs:
      digest: ${{ steps.build.outputs.digest }}
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
        with:
          persist-credentials: false

      - name: govulncheck (reachable vulnerabilities in Go code)
        uses: golang/govulncheck-action@032d45514ae346b1db93c04b0c90b841c370344f # v1.1.0
        with:
          go-version-input: "1.27"
          work-dir: go
          go-package: ./...

      - uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1

      - uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - id: build
        uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0
        with:
          context: go
          target: runtime
          platforms: linux/amd64,linux/arm64
          push: true
          tags: ghcr.io/acme/api:${{ github.sha }}
          sbom: true                  # SPDX SBOM attestation in the image index
          provenance: mode=max        # SLSA provenance (no secrets are passed as build args)

      - name: Trivy (OS + language packages, secrets) on the pushed digest
        uses: aquasecurity/trivy-action@ed142fd0673e97e23eac54620cfb913e5ce36c25 # v0.36.0
        with:
          image-ref: ghcr.io/acme/api@${{ steps.build.outputs.digest }}
          scanners: vuln,secret
          severity: HIGH,CRITICAL
          ignore-unfixed: true
          exit-code: "1"

      - name: Grype (second opinion, different database)
        uses: anchore/scan-action@11983a512817154c80a9db660c1a184be7513ed6 # v7.4.3
        with:
          image: ghcr.io/acme/api@${{ steps.build.outputs.digest }}
          fail-build: true
          severity-cutoff: critical

      - uses: sigstore/cosign-installer@881c63bd87e38389154debd8331404ce7ca8a3ab # v4.1.4

      - name: Sign the digest keyless (Fulcio certificate for this workflow, logged in Rekor)
        env:
          DIGEST: ${{ steps.build.outputs.digest }}
        run: cosign sign --yes "ghcr.io/acme/api@${DIGEST}"

Each uses: is pinned to the commit SHA that the release tag in the comment pointed to on 2026-11-29 (resolved through the GitHub API; two of the tags, trivy-action v0.36.0 and scan-action v7.4.3, are annotated tags and were dereferenced to their commits). The token is read-only at workflow level and gains packages: write and id-token: write only in the job that pushes and signs.

Knobs ​

KnobWhereDefaultHardened
userns-remapdaemon.json"" (off)"default" (creates dockremap)
no-new-privilegesdaemon.jsonfalsetrue
iccdaemon.jsontruefalse (no inter-container traffic on the default bridge)
seccomp-profiledaemon.json / dockerd --seccomp-profilebuiltinbuiltin or a derived profile
--pids-limitdocker rununlimited128 to 512
--read-onlydocker runoffon
--seccomp-defaultkubeletoff (Unconfined)on (RuntimeDefault)
PodPidsLimit / --pod-max-pidskubeletunlimitede.g. 1000 per Pod (node's pid_max / Pods)
pod-security.kubernetes.io/enforceNamespace labelnone (privileged)restricted
pod-security.kubernetes.io/enforce-versionNamespace labellatestpinned minor, e.g. v1.37
allowPrivilegeEscalationcontainer securityContexttruefalse
automountServiceAccountTokenPod / ServiceAccounttruefalse unless the app calls the API
net.ipv4.ip_unprivileged_port_startsysctl1024lower only for rootless hosts that must serve 80/443
Trivy --ignore-unfixedCLIoffon for gates (unfixed findings tracked separately)
/etc/subuid rangehostnone≥ 65,536 per rootless user

Error messages you will actually see ​

MessageMeaningFix
mount: permission denied (in a default container)No CAP_SYS_ADMIN; Docker's reference uses this exact exampleDo the mount on the host or in a volume definition
Operation not permitted / EPERM from a syscallseccomp SCMP_ACT_ERRNO or missing capabilityCheck Seccomp: and CapEff:; add one capability or adjust the profile (log mode first)
Read-only file system / EROFS--read-only / readOnlyRootFilesystem and no writable mountAdd a tmpfs/emptyDir for that path
listen tcp :80: bind: permission deniedNon-root without CAP_NET_BIND_SERVICE effectiveListen on 8080
bash: /bin/sh: Permission deniedAppArmor profile denies the shell (Docker's nginx example)Expected; the profile works
Warning: would violate PodSecurity "restricted:latest": allowPrivilegeEscalation != false ...PSA warn mode (Kubernetes namespace-level tutorial output)Set the listed securityContext fields
Error: failed to get container spec opts: failed to generate apparmor spec opts: apparmor profile not foundPod names a Localhost AppArmor profile the node has not loadedLoad the profile on every node first
nginx: [emerg] open() "/var/run/nginx.pid" failed (13: Permission denied)Nginx as non-root with the stock configpid /tmp/nginx.pid; or the unprivileged image
runtime-check: APP_KEY is not set ... (this chapter's Laravel image)Secret not mountedMount the app_key secret
refusing to run as host root ... (this chapter's Go api)Container started as UID 0 without user namespaceSet USER/runAsUser

Go ​

The Go side has two jobs: be the easiest possible workload to sandbox (a static binary that needs no capability, no shell and no writable root), and check its own sandbox at startup so a mis-deployed container fails loudly instead of running as root.

Before ​

dockerfile
# Before: the image works, and every line below is a finding in this chapter.
# 1. Mutable tag, full distribution + toolchain at runtime: hundreds of packages to scan and patch.
FROM golang:latest
# 2. A build secret passed as ARG/ENV: visible in `docker history` and in every container's environment.
ARG GITHUB_TOKEN
ENV GITHUB_TOKEN=${GITHUB_TOKEN}
WORKDIR /app
COPY . .
# 3. Piping a remote script into a shell: no checksum, no provenance.
RUN curl -fsSL https://example.com/install-tool.sh | sh
# 4. Dynamic binary (cgo default when gcc is present), built and run in the same image.
RUN go build -o /app/api ./cmd/api
# 5. The signing key baked into a layer: anyone who can pull the image can read it.
COPY signing_key /run/secrets/signing_key
# 6. No USER: the process runs as UID 0, and as host UID 0 unless the engine uses user namespaces.
# 7. Port 80 needs CAP_NET_BIND_SERVICE, one more reason the container keeps capabilities.
ENV PORT=80
EXPOSE 80
CMD /app/api

After ​

The procstatus package decodes /proc/self/status and uid_map into findings; its tests pin Docker's default mask, the privileged mask, the user-namespace mapping and the NET_BIND_SERVICE subtlety to fixture files.

go
// Package procstatus reads the security-relevant lines of /proc/<pid>/status
// (proc_pid_status(5)) and /proc/<pid>/uid_map (user_namespaces(7)) and turns
// them into hardening findings: who the process is, which capabilities it
// holds, whether no_new_privs is set and whether a seccomp filter is attached.
//
// It is the same information `docker run ... cat /proc/self/status` shows,
// decoded, so a container can check its own sandbox at startup.
package procstatus

import (
	"bufio"
	"errors"
	"fmt"
	"io"
	"math/bits"
	"os"
	"sort"
	"strconv"
	"strings"
)

// SeccompMode is the value of the "Seccomp:" line.
type SeccompMode int

// Values documented in proc_pid_status(5).
const (
	SeccompUnknown  SeccompMode = -1 // line absent (kernel without CONFIG_SECCOMP)
	SeccompDisabled SeccompMode = 0  // SECCOMP_MODE_DISABLED
	SeccompStrict   SeccompMode = 1  // SECCOMP_MODE_STRICT
	SeccompFilter   SeccompMode = 2  // SECCOMP_MODE_FILTER (Docker, containerd, CRI-O profiles)
)

func (m SeccompMode) String() string {
	switch m {
	case SeccompDisabled:
		return "disabled"
	case SeccompStrict:
		return "strict"
	case SeccompFilter:
		return "filter"
	}
	return "unknown"
}

// Status holds the parsed security fields of one process.
type Status struct {
	UID            [4]int // real, effective, saved set, filesystem
	GID            [4]int
	CapInh         uint64
	CapPrm         uint64
	CapEff         uint64
	CapBnd         uint64
	CapAmb         uint64
	NoNewPrivs     bool
	Seccomp        SeccompMode
	SeccompFilters int // -1 when the line is absent (kernels before 5.9)
}

// capNames is indexed by capability number, from include/uapi/linux/capability.h
// (CAP_CHOWN = 0 ... CAP_CHECKPOINT_RESTORE = 40 = CAP_LAST_CAP).
var capNames = [...]string{
	"CAP_CHOWN", "CAP_DAC_OVERRIDE", "CAP_DAC_READ_SEARCH", "CAP_FOWNER",
	"CAP_FSETID", "CAP_KILL", "CAP_SETGID", "CAP_SETUID", "CAP_SETPCAP",
	"CAP_LINUX_IMMUTABLE", "CAP_NET_BIND_SERVICE", "CAP_NET_BROADCAST",
	"CAP_NET_ADMIN", "CAP_NET_RAW", "CAP_IPC_LOCK", "CAP_IPC_OWNER",
	"CAP_SYS_MODULE", "CAP_SYS_RAWIO", "CAP_SYS_CHROOT", "CAP_SYS_PTRACE",
	"CAP_SYS_PACCT", "CAP_SYS_ADMIN", "CAP_SYS_BOOT", "CAP_SYS_NICE",
	"CAP_SYS_RESOURCE", "CAP_SYS_TIME", "CAP_SYS_TTY_CONFIG", "CAP_MKNOD",
	"CAP_LEASE", "CAP_AUDIT_WRITE", "CAP_AUDIT_CONTROL", "CAP_SETFCAP",
	"CAP_MAC_OVERRIDE", "CAP_MAC_ADMIN", "CAP_SYSLOG", "CAP_WAKE_ALARM",
	"CAP_BLOCK_SUSPEND", "CAP_AUDIT_READ", "CAP_PERFMON", "CAP_BPF",
	"CAP_CHECKPOINT_RESTORE",
}

// DockerDefault is the capability list Docker Engine grants a container that
// sets no --cap-add/--cap-drop (moby daemon/pkg/oci/caps/defaults.go).
var DockerDefault = []string{
	"CAP_CHOWN", "CAP_DAC_OVERRIDE", "CAP_FSETID", "CAP_FOWNER", "CAP_MKNOD",
	"CAP_NET_RAW", "CAP_SETGID", "CAP_SETUID", "CAP_SETFCAP", "CAP_SETPCAP",
	"CAP_NET_BIND_SERVICE", "CAP_SYS_CHROOT", "CAP_KILL", "CAP_AUDIT_WRITE",
}

// dangerous capabilities: each one alone has been enough for a container
// escape or host-wide damage in practice. CAP_SYS_ADMIN is "the new root"
// (capabilities(7)).
var dangerous = []string{
	"CAP_SYS_ADMIN", "CAP_SYS_MODULE", "CAP_SYS_PTRACE", "CAP_SYS_RAWIO",
	"CAP_DAC_READ_SEARCH", "CAP_NET_ADMIN", "CAP_BPF", "CAP_PERFMON",
	"CAP_SYS_BOOT", "CAP_MAC_ADMIN", "CAP_MAC_OVERRIDE",
}

// CapNames returns the names of the bits set in mask, in bit order.
// Unknown bits (newer kernels) are reported as "cap_<n>".
func CapNames(mask uint64) []string {
	var out []string
	for mask != 0 {
		i := bits.TrailingZeros64(mask)
		mask &^= 1 << i
		if i < len(capNames) {
			out = append(out, capNames[i])
		} else {
			out = append(out, "cap_"+strconv.Itoa(i))
		}
	}
	return out
}

// Mask builds a capability mask from names with or without the CAP_ prefix,
// in any case ("NET_BIND_SERVICE", "cap_chown"), as Docker and Kubernetes accept them.
func Mask(names ...string) (uint64, error) {
	var m uint64
	for _, n := range names {
		n = strings.ToUpper(n)
		if !strings.HasPrefix(n, "CAP_") {
			n = "CAP_" + n
		}
		i := indexOf(n)
		if i < 0 {
			return 0, fmt.Errorf("unknown capability %q", n)
		}
		m |= 1 << i
	}
	return m, nil
}

func indexOf(name string) int {
	for i, c := range capNames {
		if c == name {
			return i
		}
	}
	return -1
}

// Parse reads a /proc/<pid>/status stream.
func Parse(r io.Reader) (Status, error) {
	s := Status{Seccomp: SeccompUnknown, SeccompFilters: -1}
	seen := map[string]bool{}
	sc := bufio.NewScanner(r)
	for sc.Scan() {
		key, val, ok := strings.Cut(sc.Text(), ":")
		if !ok {
			continue
		}
		val = strings.TrimSpace(val)
		var err error
		switch key {
		case "Uid":
			s.UID, err = ids(val)
		case "Gid":
			s.GID, err = ids(val)
		case "CapInh":
			s.CapInh, err = strconv.ParseUint(val, 16, 64)
		case "CapPrm":
			s.CapPrm, err = strconv.ParseUint(val, 16, 64)
		case "CapEff":
			s.CapEff, err = strconv.ParseUint(val, 16, 64)
		case "CapBnd":
			s.CapBnd, err = strconv.ParseUint(val, 16, 64)
		case "CapAmb":
			s.CapAmb, err = strconv.ParseUint(val, 16, 64)
		case "NoNewPrivs":
			s.NoNewPrivs = val == "1"
		case "Seccomp":
			var n int
			n, err = strconv.Atoi(val)
			s.Seccomp = SeccompMode(n)
		case "Seccomp_filters":
			s.SeccompFilters, err = strconv.Atoi(val)
		default:
			continue
		}
		if err != nil {
			return Status{}, fmt.Errorf("procstatus: %s: %w", key, err)
		}
		seen[key] = true
	}
	if err := sc.Err(); err != nil {
		return Status{}, err
	}
	for _, k := range []string{"Uid", "CapEff", "CapBnd"} {
		if !seen[k] {
			return Status{}, fmt.Errorf("procstatus: missing %s line (not a Linux /proc status file?)", k)
		}
	}
	return s, nil
}

func ids(v string) ([4]int, error) {
	var out [4]int
	f := strings.Fields(v)
	if len(f) != 4 {
		return out, fmt.Errorf("want 4 ids, got %d", len(f))
	}
	for i, x := range f {
		n, err := strconv.Atoi(x)
		if err != nil {
			return out, err
		}
		out[i] = n
	}
	return out, nil
}

// ReadFile parses a status file such as /proc/self/status.
func ReadFile(path string) (Status, error) {
	f, err := os.Open(path)
	if err != nil {
		return Status{}, err
	}
	defer f.Close()
	return Parse(f)
}

// Mapping is one line of /proc/<pid>/uid_map: IDs [Inside, Inside+Count)
// in this namespace are IDs [Outside, Outside+Count) in the parent namespace.
type Mapping struct{ Inside, Outside, Count uint64 }

// ParseUIDMap reads a uid_map (or gid_map) stream.
func ParseUIDMap(r io.Reader) ([]Mapping, error) {
	var out []Mapping
	sc := bufio.NewScanner(r)
	for sc.Scan() {
		f := strings.Fields(sc.Text())
		if len(f) == 0 {
			continue
		}
		if len(f) != 3 {
			return nil, fmt.Errorf("uid_map: want 3 fields, got %q", sc.Text())
		}
		var m Mapping
		var err error
		for i, p := range []*uint64{&m.Inside, &m.Outside, &m.Count} {
			if *p, err = strconv.ParseUint(f[i], 10, 64); err != nil {
				return nil, fmt.Errorf("uid_map: %w", err)
			}
		}
		out = append(out, m)
	}
	return out, sc.Err()
}

// HostID translates an ID inside the namespace to the parent namespace.
// ok is false when the ID is unmapped.
func HostID(maps []Mapping, id uint64) (host uint64, ok bool) {
	for _, m := range maps {
		if id >= m.Inside && id < m.Inside+m.Count {
			return m.Outside + (id - m.Inside), true
		}
	}
	return 0, false
}

// Severity orders findings.
type Severity int

// Severities, lowest first.
const (
	Info Severity = iota
	Medium
	High
	Critical
)

func (s Severity) String() string {
	return [...]string{"INFO", "MEDIUM", "HIGH", "CRITICAL"}[s]
}

// Finding is one hardening observation.
type Finding struct {
	Severity Severity `json:"-"`
	Level    string   `json:"severity"`
	Check    string   `json:"check"`
	Detail   string   `json:"detail"`
}

// Findings evaluates the sandbox. maps may be nil (uid_map unreadable): the
// process is then assumed to be in the initial user namespace, the
// conservative choice.
func (s Status) Findings(maps []Mapping) []Finding {
	var out []Finding
	add := func(sev Severity, check, format string, a ...any) {
		out = append(out, Finding{Severity: sev, Level: sev.String(), Check: check, Detail: fmt.Sprintf(format, a...)})
	}
	euid := s.UID[1]
	if euid == 0 {
		host, ok := uint64(0), true
		if maps != nil {
			host, ok = HostID(maps, 0)
		}
		switch {
		case ok && host == 0:
			add(Critical, "root", "effective UID 0 and it is host UID 0 (no user namespace): an escape lands as host root")
		case ok:
			add(Info, "root", "UID 0 inside a user namespace, mapped to unprivileged host UID %d", host)
		default:
			add(Medium, "root", "UID 0 is not mapped in uid_map")
		}
	}
	for _, name := range dangerous {
		m, _ := Mask(name)
		if s.CapEff&m != 0 {
			sev := High
			if name == "CAP_SYS_ADMIN" {
				sev = Critical
			}
			add(sev, "capabilities", "%s is in the effective set", name)
		}
	}
	nbs, _ := Mask("NET_BIND_SERVICE")
	if extra := s.CapBnd &^ nbs; extra != 0 {
		add(Medium, "cap_drop", "bounding set still holds %d capabilities (%s); drop ALL and add back only what is needed",
			bits.OnesCount64(extra), strings.Join(CapNames(extra), ","))
	}
	if euid != 0 && s.CapBnd&nbs != 0 && s.CapEff&nbs == 0 && s.CapAmb&nbs == 0 {
		add(Info, "cap_add", "CAP_NET_BIND_SERVICE is allowed by the bounding set but not effective: a non-root process needs file or ambient capabilities to use it; listen on a port >= 1024 instead")
	}
	if !s.NoNewPrivs {
		add(Medium, "no_new_privs", "no_new_privs is 0: setuid binaries and file capabilities can still raise privileges on execve")
	}
	switch s.Seccomp {
	case SeccompDisabled:
		add(High, "seccomp", "no seccomp filter (Unconfined): the whole syscall table is reachable")
	case SeccompUnknown:
		add(Medium, "seccomp", "kernel reports no Seccomp line")
	}
	if s.CapAmb != 0 {
		add(Info, "ambient", "ambient capabilities set: %s", strings.Join(CapNames(s.CapAmb), ","))
	}
	sort.SliceStable(out, func(i, j int) bool { return out[i].Severity > out[j].Severity })
	return out
}

// Worst returns the highest severity in fs, or -1 when fs is empty.
func Worst(fs []Finding) Severity {
	w := Severity(-1)
	for _, f := range fs {
		if f.Severity > w {
			w = f.Severity
		}
	}
	return w
}

// ErrNotLinux is returned by Self on systems without /proc/self/status.
var ErrNotLinux = errors.New("procstatus: /proc/self/status not available (not Linux)")

// Self reads the current process. uid_map errors are tolerated (maps = nil).
func Self() (Status, []Mapping, error) {
	s, err := ReadFile("/proc/self/status")
	if errors.Is(err, os.ErrNotExist) {
		return Status{}, nil, ErrNotLinux
	}
	if err != nil {
		return Status{}, nil, err
	}
	var maps []Mapping
	if f, err := os.Open("/proc/self/uid_map"); err == nil {
		maps, _ = ParseUIDMap(f)
		f.Close()
	}
	return s, maps, nil
}
go
package procstatus

import (
	"os"
	"path/filepath"
	"slices"
	"strings"
	"testing"
)

func load(t *testing.T, name string) Status {
	t.Helper()
	s, err := ReadFile(filepath.Join("testdata", name))
	if err != nil {
		t.Fatal(err)
	}
	return s
}

func loadMap(t *testing.T, name string) []Mapping {
	t.Helper()
	f, err := os.Open(filepath.Join("testdata", name))
	if err != nil {
		t.Fatal(err)
	}
	defer f.Close()
	m, err := ParseUIDMap(f)
	if err != nil {
		t.Fatal(err)
	}
	return m
}

func checks(fs []Finding) []string {
	var out []string
	for _, f := range fs {
		out = append(out, f.Level+":"+f.Check)
	}
	return out
}

// The mask in the docker-default fixture must be exactly moby's default list.
func TestDockerDefaultMask(t *testing.T) {
	want, err := Mask(DockerDefault...)
	if err != nil {
		t.Fatal(err)
	}
	if want != 0xa80425fb {
		t.Fatalf("Docker default mask = %#x, want 0xa80425fb", want)
	}
	s := load(t, "docker-default-root.status")
	if s.CapEff != want || s.CapBnd != want {
		t.Fatalf("fixture CapEff=%#x CapBnd=%#x, want %#x", s.CapEff, s.CapBnd, want)
	}
	got := CapNames(want)
	if len(got) != len(DockerDefault) {
		t.Fatalf("CapNames returned %d names, want %d: %v", len(got), len(DockerDefault), got)
	}
	for _, n := range DockerDefault {
		if !slices.Contains(got, n) {
			t.Errorf("CapNames misses %s", n)
		}
	}
}

func TestMaskAcceptsDockerAndKubernetesSpelling(t *testing.T) {
	a, _ := Mask("NET_BIND_SERVICE")
	b, _ := Mask("cap_net_bind_service")
	if a != 1<<10 || a != b {
		t.Fatalf("got %#x and %#x, want %#x", a, b, 1<<10)
	}
	if _, err := Mask("CAP_TELEPORT"); err == nil {
		t.Fatal("unknown capability accepted")
	}
}

func TestPrivilegedHasEveryCapability(t *testing.T) {
	s := load(t, "privileged.status")
	if n := len(CapNames(s.CapEff)); n != 41 {
		t.Fatalf("privileged CapEff decodes to %d capabilities, want 41 (0..CAP_LAST_CAP=40)", n)
	}
	fs := s.Findings(loadMap(t, "host.uid_map"))
	if Worst(fs) != Critical {
		t.Fatalf("worst = %v, want CRITICAL", Worst(fs))
	}
	c := checks(fs)
	for _, want := range []string{"CRITICAL:root", "CRITICAL:capabilities", "HIGH:seccomp", "MEDIUM:no_new_privs", "MEDIUM:cap_drop"} {
		if !slices.Contains(c, want) {
			t.Errorf("missing %s in %v", want, c)
		}
	}
}

func TestDockerDefaultAsRoot(t *testing.T) {
	s := load(t, "docker-default-root.status")
	if s.Seccomp != SeccompFilter || s.SeccompFilters != 1 {
		t.Fatalf("seccomp = %v/%d, want filter/1", s.Seccomp, s.SeccompFilters)
	}
	c := checks(s.Findings(loadMap(t, "host.uid_map")))
	want := []string{"CRITICAL:root", "MEDIUM:cap_drop", "MEDIUM:no_new_privs"}
	if !slices.Equal(c, want) {
		t.Fatalf("findings = %v, want %v", c, want)
	}
}

func TestUserNamespaceTurnsRootIntoInfo(t *testing.T) {
	s := load(t, "docker-default-root.status")
	maps := loadMap(t, "userns.uid_map")
	if h, ok := HostID(maps, 0); !ok || h != 100000 {
		t.Fatalf("HostID(0) = %d,%v want 100000,true", h, ok)
	}
	if _, ok := HostID(maps, 65536); ok {
		t.Fatal("UID 65536 should be unmapped with a 65536-wide range")
	}
	fs := s.Findings(maps)
	if fs[len(fs)-1].Check != "root" || fs[len(fs)-1].Severity != Info {
		t.Fatalf("root finding should be INFO under userns: %v", checks(fs))
	}
	if !strings.Contains(fs[len(fs)-1].Detail, "100000") {
		t.Errorf("detail should name the host UID: %q", fs[len(fs)-1].Detail)
	}
}

func TestHardenedNonRootIsClean(t *testing.T) {
	s := load(t, "hardened-nonroot.status")
	if s.UID != [4]int{65532, 65532, 65532, 65532} || !s.NoNewPrivs {
		t.Fatalf("unexpected parse: %+v", s)
	}
	if fs := s.Findings(nil); len(fs) != 0 {
		t.Fatalf("hardened fixture produced findings: %v", checks(fs))
	}
}

func TestNetBindServiceNeedsMoreThanCapAdd(t *testing.T) {
	s := load(t, "netbind-nonroot.status")
	fs := s.Findings(nil)
	if c := checks(fs); !slices.Equal(c, []string{"INFO:cap_add"}) {
		t.Fatalf("findings = %v, want only INFO:cap_add", c)
	}
}

func TestParseRejectsNonStatus(t *testing.T) {
	if _, err := Parse(strings.NewReader("hello: world\n")); err == nil {
		t.Fatal("expected error for a file without Uid/CapEff/CapBnd")
	}
	if _, err := Parse(strings.NewReader("Uid:\t0 0\nCapEff:\t0\nCapBnd:\t0\n")); err == nil {
		t.Fatal("expected error for a short Uid line")
	}
}

secreport is the same check as a command, used in the Lab:

go
// Command secreport prints what the kernel says about the current process's
// sandbox: UIDs, capabilities, no_new_privs, seccomp. Run it as the entrypoint
// of a throwaway container to see what a given set of docker/kubectl flags
// really produces:
//
//	docker run --rm --cap-drop ALL --security-opt no-new-privileges secreport
//
// On a non-Linux host, point it at a saved status file with -status.
package main

import (
	"encoding/json"
	"flag"
	"fmt"
	"io"
	"os"
	"strings"

	"academy/container-security/procstatus"
)

func main() { os.Exit(run(os.Args[1:], os.Stdout, os.Stderr)) }

func run(args []string, stdout, stderr io.Writer) int {
	fl := flag.NewFlagSet("secreport", flag.ContinueOnError)
	fl.SetOutput(stderr)
	statusPath := fl.String("status", "/proc/self/status", "status file to read")
	mapPath := fl.String("uidmap", "/proc/self/uid_map", "uid_map file to read (optional)")
	asJSON := fl.Bool("json", false, "print JSON")
	strict := fl.Bool("strict", false, "exit 1 if any finding is MEDIUM or worse")
	if err := fl.Parse(args); err != nil {
		return 2
	}
	s, err := procstatus.ReadFile(*statusPath)
	if err != nil {
		fmt.Fprintln(stderr, "secreport:", err)
		return 2
	}
	var maps []procstatus.Mapping
	if f, err := os.Open(*mapPath); err == nil {
		maps, _ = procstatus.ParseUIDMap(f)
		f.Close()
	}
	fs := s.Findings(maps)
	if *asJSON {
		enc := json.NewEncoder(stdout)
		enc.SetIndent("", "  ")
		_ = enc.Encode(map[string]any{
			"uid":          s.UID,
			"capEff":       procstatus.CapNames(s.CapEff),
			"capBnd":       procstatus.CapNames(s.CapBnd),
			"noNewPrivs":   s.NoNewPrivs,
			"seccomp":      s.Seccomp.String(),
			"findings":     fs,
			"findingCount": len(fs),
		})
	} else {
		fmt.Fprintf(stdout, "uid=%d euid=%d seccomp=%s filters=%d no_new_privs=%t\n",
			s.UID[0], s.UID[1], s.Seccomp, s.SeccompFilters, s.NoNewPrivs)
		fmt.Fprintf(stdout, "effective: %s\n", list(procstatus.CapNames(s.CapEff)))
		fmt.Fprintf(stdout, "bounding:  %s\n", list(procstatus.CapNames(s.CapBnd)))
		for _, f := range fs {
			fmt.Fprintf(stdout, "%-8s %-13s %s\n", f.Level, f.Check, f.Detail)
		}
		if len(fs) == 0 {
			fmt.Fprintln(stdout, "OK       no findings")
		}
	}
	if *strict && procstatus.Worst(fs) >= procstatus.Medium {
		return 1
	}
	return 0
}

func list(names []string) string {
	if len(names) == 0 {
		return "(none)"
	}
	return strings.Join(names, ",")
}

The service refuses host root, listens on 8080, writes only to TMPDIR and reads its key from a secret file:

go
// Command api is the small service that the hardened Dockerfile, Compose file
// and Kubernetes Deployment on this page run. Its security-relevant choices:
//
//   - it refuses to start as host root, or when it cannot inspect its own
//     sandbox (fail closed), unless ALLOW_ROOT=1 / SKIP_SANDBOX_CHECK=1;
//   - it listens on 8080, an unprivileged port, so it needs no capability at all;
//   - it writes only below TMPDIR, which is a tmpfs/emptyDir when the root
//     filesystem is read-only;
//   - it reads its signing key from a file (a Docker/Kubernetes secret mount),
//     never from the image and never into a log line.
package main

import (
	"context"
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"errors"
	"fmt"
	"io"
	"log/slog"
	"net/http"
	"os"
	"os/signal"
	"strings"
	"syscall"
	"time"

	"academy/container-security/procstatus"
)

// errHostRoot is returned when the process would run as UID 0 on the host.
var errHostRoot = errors.New("refusing to run as host root: set USER/runAsUser to a non-zero UID (or ALLOW_ROOT=1 for a debug image)")

// startupCheck fails closed on the one setting that turns any bug into a host
// compromise, and logs the rest as warnings.
func startupCheck(s procstatus.Status, maps []procstatus.Mapping, allowRoot bool, log *slog.Logger) error {
	for _, f := range s.Findings(maps) {
		if f.Check == "root" && f.Severity == procstatus.Critical && !allowRoot {
			return errHostRoot
		}
		log.Warn("sandbox", "severity", f.Level, "check", f.Check, "detail", f.Detail)
	}
	return nil
}

// errNoSandboxInfo is returned when the sandbox cannot be inspected.
var errNoSandboxInfo = errors.New("cannot inspect the sandbox (/proc/self/status); refusing to start (set SKIP_SANDBOX_CHECK=1 only for non-Linux development)")

// sandboxGate runs the startup check and fails closed: if the process cannot
// read its own status it does not start, unless skip is explicitly set.
func sandboxGate(self func() (procstatus.Status, []procstatus.Mapping, error), allowRoot, skip bool, log *slog.Logger) error {
	s, maps, err := self()
	if err != nil {
		if skip {
			log.Warn("sandbox check skipped by SKIP_SANDBOX_CHECK=1", "err", err)
			return nil
		}
		return fmt.Errorf("%w: %v", errNoSandboxInfo, err)
	}
	return startupCheck(s, maps, allowRoot, log)
}

// readSecret reads a mounted secret file (for example /run/secrets/signing_key).
func readSecret(path string) ([]byte, error) {
	b, err := os.ReadFile(path)
	if err != nil {
		return nil, fmt.Errorf("secret %s: %w", path, err)
	}
	b = []byte(strings.TrimSpace(string(b)))
	if len(b) < 32 {
		return nil, fmt.Errorf("secret %s: %d bytes, want at least 32", path, len(b))
	}
	return b, nil
}

func newMux(tmpDir string, key []byte) *http.ServeMux {
	mux := http.NewServeMux()
	mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) {
		io.WriteString(w, "ok\n")
	})
	// POST /reports stores an upload in TMPDIR and returns its HMAC: the only
	// writable path in the container, and the key never leaves the process.
	mux.HandleFunc("POST /reports", func(w http.ResponseWriter, r *http.Request) {
		f, err := os.CreateTemp(tmpDir, "report-*.bin")
		if err != nil {
			http.Error(w, "storage unavailable", http.StatusInternalServerError)
			return
		}
		defer f.Close()
		mac := hmac.New(sha256.New, key)
		if _, err := io.Copy(io.MultiWriter(f, mac), http.MaxBytesReader(w, r.Body, 1<<20)); err != nil {
			os.Remove(f.Name())
			http.Error(w, "upload too large or interrupted", http.StatusRequestEntityTooLarge)
			return
		}
		w.WriteHeader(http.StatusCreated)
		fmt.Fprintf(w, "%s\n", hex.EncodeToString(mac.Sum(nil)))
	})
	return mux
}

func main() {
	log := slog.New(slog.NewJSONHandler(os.Stderr, nil))
	if err := sandboxGate(procstatus.Self, os.Getenv("ALLOW_ROOT") == "1", os.Getenv("SKIP_SANDBOX_CHECK") == "1", log); err != nil {
		log.Error("startup", "err", err)
		os.Exit(1)
	}
	key, err := readSecret(envOr("SIGNING_KEY_FILE", "/run/secrets/signing_key"))
	if err != nil {
		log.Error("startup", "err", err)
		os.Exit(1)
	}
	srv := &http.Server{
		Addr:              ":" + envOr("PORT", "8080"),
		Handler:           newMux(os.TempDir(), key),
		ReadHeaderTimeout: 5 * time.Second,
	}
	ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, os.Interrupt)
	defer stop()
	go func() {
		<-ctx.Done()
		sctx, cancel := context.WithTimeout(context.Background(), 8*time.Second)
		defer cancel()
		_ = srv.Shutdown(sctx)
	}()
	log.Info("listening", "addr", srv.Addr, "tmp", os.TempDir())
	if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
		log.Error("serve", "err", err)
		os.Exit(1)
	}
}

func envOr(k, def string) string {
	if v := os.Getenv(k); v != "" {
		return v
	}
	return def
}
go
package main

import (
	"bytes"
	"errors"
	"io"
	"log/slog"
	"net/http"
	"net/http/httptest"
	"os"
	"path/filepath"
	"strings"
	"testing"

	"academy/container-security/procstatus"
)

const td = "../../procstatus/testdata/"

func quiet() *slog.Logger { return slog.New(slog.NewTextHandler(io.Discard, nil)) }

func status(t *testing.T, name string) procstatus.Status {
	t.Helper()
	s, err := procstatus.ReadFile(td + name)
	if err != nil {
		t.Fatal(err)
	}
	return s
}

func TestStartupRefusesHostRoot(t *testing.T) {
	err := startupCheck(status(t, "docker-default-root.status"), nil, false, quiet())
	if !errors.Is(err, errHostRoot) {
		t.Fatalf("err = %v, want errHostRoot", err)
	}
	if err := startupCheck(status(t, "docker-default-root.status"), nil, true, quiet()); err != nil {
		t.Fatalf("ALLOW_ROOT=1 should only warn, got %v", err)
	}
}

func TestStartupAllowsRootInUserNamespace(t *testing.T) {
	maps := []procstatus.Mapping{{Inside: 0, Outside: 100000, Count: 65536}}
	if err := startupCheck(status(t, "docker-default-root.status"), maps, false, quiet()); err != nil {
		t.Fatalf("root mapped to host UID 100000 should start (with warnings): %v", err)
	}
}

func TestStartupHardenedLogsNothing(t *testing.T) {
	var buf bytes.Buffer
	log := slog.New(slog.NewTextHandler(&buf, nil))
	if err := startupCheck(status(t, "hardened-nonroot.status"), nil, false, log); err != nil || buf.Len() != 0 {
		t.Fatalf("err=%v log=%q", err, buf.String())
	}
}

func TestReadSecret(t *testing.T) {
	dir := t.TempDir()
	short := filepath.Join(dir, "short")
	os.WriteFile(short, []byte("abc\n"), 0o400)
	if _, err := readSecret(short); err == nil {
		t.Fatal("a 3-byte key must be rejected")
	}
	good := filepath.Join(dir, "good")
	os.WriteFile(good, []byte(strings.Repeat("k", 32)+"\n"), 0o400)
	b, err := readSecret(good)
	if err != nil || len(b) != 32 {
		t.Fatalf("len=%d err=%v", len(b), err)
	}
}

func TestReportsWriteOnlyToTmpDir(t *testing.T) {
	dir := t.TempDir()
	mux := newMux(dir, bytes.Repeat([]byte("k"), 32))
	rec := httptest.NewRecorder()
	mux.ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/reports", strings.NewReader("hello")))
	if rec.Code != http.StatusCreated || len(strings.TrimSpace(rec.Body.String())) != 64 {
		t.Fatalf("code=%d body=%q", rec.Code, rec.Body.String())
	}
	files, _ := filepath.Glob(filepath.Join(dir, "report-*.bin"))
	if len(files) != 1 {
		t.Fatalf("want 1 file in TMPDIR, got %v", files)
	}
}

func TestReportsFailWhenTmpDirIsNotWritable(t *testing.T) {
	// Simulates --read-only without a tmpfs for TMPDIR.
	mux := newMux(filepath.Join(t.TempDir(), "missing"), bytes.Repeat([]byte("k"), 32))
	rec := httptest.NewRecorder()
	mux.ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/reports", strings.NewReader("x")))
	if rec.Code != http.StatusInternalServerError {
		t.Fatalf("code=%d, want 500", rec.Code)
	}
}

func TestReportsRejectLargeUpload(t *testing.T) {
	dir := t.TempDir()
	mux := newMux(dir, bytes.Repeat([]byte("k"), 32))
	rec := httptest.NewRecorder()
	mux.ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/reports", bytes.NewReader(make([]byte, 2<<20))))
	if rec.Code != http.StatusRequestEntityTooLarge {
		t.Fatalf("code=%d", rec.Code)
	}
	if files, _ := filepath.Glob(filepath.Join(dir, "*")); len(files) != 0 {
		t.Fatalf("partial upload left behind: %v", files)
	}
}

func TestHealthz(t *testing.T) {
	rec := httptest.NewRecorder()
	newMux(t.TempDir(), bytes.Repeat([]byte("k"), 32)).ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/healthz", nil))
	if rec.Code != 200 || rec.Body.String() != "ok\n" {
		t.Fatalf("code=%d body=%q", rec.Code, rec.Body.String())
	}
}

func TestSandboxGateFailsClosedWhenStatusUnreadable(t *testing.T) {
	broken := func() (procstatus.Status, []procstatus.Mapping, error) {
		return procstatus.Status{}, nil, procstatus.ErrNotLinux
	}
	err := sandboxGate(broken, false, false, quiet())
	if !errors.Is(err, errNoSandboxInfo) {
		t.Fatalf("err = %v, want errNoSandboxInfo", err)
	}
	if err := sandboxGate(broken, false, true, quiet()); err != nil {
		t.Fatalf("SKIP_SANDBOX_CHECK=1 should start, got %v", err)
	}
}

func TestSandboxGatePassesStatusThrough(t *testing.T) {
	root := func() (procstatus.Status, []procstatus.Mapping, error) {
		return status(t, "docker-default-root.status"), nil, nil
	}
	if err := sandboxGate(root, false, true, quiet()); !errors.Is(err, errHostRoot) {
		t.Fatalf("skip must not bypass the root check: err = %v", err)
	}
}
text
module academy/container-security

go 1.24

The hardened image and the matching run configuration:

dockerfile
# syntax=docker/dockerfile:1
#
# api: static Go binary on distroless "nonroot"; needs no capability, no shell,
# no writable root filesystem. Run it with the flags in ../docker/run-hardened.sh
# or the securityContext in ../k8s/deployment.yaml.
# Pin both FROM lines by digest in production, e.g. golang:1.27-trixie@sha256:<digest>
# (docker buildx imagetools inspect golang:1.27-trixie prints it).

ARG GO_VERSION=1.27

FROM --platform=$BUILDPLATFORM golang:${GO_VERSION}-trixie AS build
WORKDIR /src
COPY go.mod ./
RUN --mount=type=cache,target=/go/pkg/mod go mod download
COPY . .
ARG TARGETOS TARGETARCH
# CGO_ENABLED=0: no libc in the image means no libc CVEs to patch and nothing for
# a dynamic loader to be tricked into loading.
RUN --mount=type=cache,target=/go/pkg/mod \
    --mount=type=cache,target=/root/.cache/go-build \
    CGO_ENABLED=0 GOOS=$TARGETOS GOARCH=$TARGETARCH \
    go build -trimpath -ldflags="-s -w" -o /out/api ./cmd/api \
 && CGO_ENABLED=0 GOOS=$TARGETOS GOARCH=$TARGETARCH \
    go build -trimpath -ldflags="-s -w" -o /out/secreport ./cmd/secreport

# Vulnerability gate inside the build: fails the build if reachable code calls a
# function with a known vulnerability (govulncheck exits non-zero on findings).
# It writes a marker that the runtime stage copies, so `--target runtime` cannot
# skip this stage: BuildKit only runs stages the target depends on.
FROM build AS vulncheck
RUN --mount=type=cache,target=/go/pkg/mod \
    go install golang.org/x/vuln/cmd/govulncheck@v1.10.0 \
 && govulncheck ./... \
 && mkdir -p /out && echo "govulncheck v1.10.0: no reachable vulnerabilities" > /out/vulncheck.txt

FROM gcr.io/distroless/static-debian13:nonroot AS runtime
LABEL org.opencontainers.image.title="api" \
      org.opencontainers.image.source="https://github.com/acme/api"
COPY --from=build /out/api /out/secreport /usr/local/bin/
# The dependency edge that makes the gate mandatory for this target.
COPY --from=vulncheck /out/vulncheck.txt /usr/local/share/doc/api/vulncheck.txt
# Numeric UID:GID so runAsNonRoot can be verified without reading /etc/passwd.
USER 65532:65532
# >= 1024: binding needs no CAP_NET_BIND_SERVICE, so cap_drop ALL costs nothing.
ENV PORT=8080
EXPOSE 8080
# The key arrives at run time as a secret file, never as a layer or an ENV.
ENV SIGNING_KEY_FILE=/run/secrets/signing_key
ENTRYPOINT ["/usr/local/bin/api"]
bash
#!/bin/sh
# Run the api image with every runtime control from this chapter.
# Expected, not run (no Docker daemon in the build environment).
set -eu

IMAGE=${IMAGE:-ghcr.io/acme/api@sha256:<digest-from-the-build>}

# The signing key lives in a file outside the image, bind-mounted read-only. Host
# ownership applies inside: chown 65532 secrets/signing_key && chmod 0400 (with
# userns-remap, chown to the remapped UID instead, e.g. 100000 + 65532).
docker run -d --name api \
  --user 65532:65532 \
  --cap-drop ALL \
  --security-opt no-new-privileges=true \
  --security-opt seccomp=../seccomp/api-seccomp.json \
  --security-opt apparmor=api-restricted \
  --read-only \
  --tmpfs /tmp:rw,noexec,nosuid,size=64m \
  --pids-limit 128 \
  --memory 256m --cpus 1 \
  --mount type=bind,src="$PWD/secrets/signing_key",dst=/run/secrets/signing_key,readonly \
  -p 127.0.0.1:8080:8080 \
  "$IMAGE"

# The same image, inspected by its own tool instead of the server.
docker run --rm --user 65532:65532 --cap-drop ALL \
  --security-opt no-new-privileges=true --read-only \
  --entrypoint /usr/local/bin/secreport "$IMAGE" -strict
json
{
  "icc": false,
  "live-restore": true,
  "no-new-privileges": true,
  "userns-remap": "default"
}

The Go angle ​

  • Go static binaries and security. With CGO_ENABLED=0 the binary has no libc and no dynamic loader, so it runs on distroless static or scratch: no shell for an attacker to use, no OS packages for a scanner to flag, nothing for LD_PRELOAD-style tricks. The cross-compiled build in this chapter reports statically linked ... stripped from file, and go version -m shows CGO_ENABLED=0, -trimpath=true (Lab, step 2).
  • Vulnerabilities live in the module graph, not the OS. For a distroless Go image the meaningful scanner is govulncheck, which "analyzes your codebase and only surfaces vulnerabilities that actually affect you, based on which functions in your code are transitively calling vulnerable functions"; the Dockerfile has a vulncheck stage that the runtime stage depends on (it copies the stage's marker file, so BuildKit cannot skip the gate for --target runtime), and the CI job also runs golang/govulncheck-action. Keeping the Go toolchain current matters as much: standard library fixes ship in Go point releases.
  • No capability needed. net/http on :8080 needs nothing; there is no reason to add NET_BIND_SERVICE or to run as root. A Service or ingress maps 80/443 to 8080.
  • Read-only root. os.TempDir() honours TMPDIR; mount a tmpfs at /tmp and nothing else is written. os.CreateTemp gives unique names and "The file is created with mode 0o600 (before umask)."
  • Secrets from files. Reading /run/secrets/<name> (Compose) or a mounted Secret (Kubernetes) keeps the key out of /proc/1/environ and crash dumps; never log the config struct.
  • Self-check at startup. procstatus.Self() costs one file read; failing closed on host root catches the "someone ran it with --user 0" mistake that no image setting can prevent. If the status file cannot be read at all, the service also refuses to start; SKIP_SANDBOX_CHECK=1 is the explicit opt-out for non-Linux development, and it never bypasses the root check when the status is readable.
  • Goroutines are not processes. A goroutine leak does not hit pids.max (the runtime multiplexes them onto a few threads), but cgo calls and blocking syscalls create threads that do; keep --pids-limit above the runtime's thread count with headroom.
  • Build flags and module hygiene: Project Layout, Linting & Build.

Laravel ​

Before ​

The usual Laravel image: the whole tree owned by www-data (every PHP file writable by the process that serves requests), .env copied in with APP_KEY, root at start-up, writable root filesystem.

dockerfile
FROM php:8.4-fpm
COPY . /var/www/html
# .env (with APP_KEY and DB_PASSWORD) is now in a layer of every copy of this image
RUN chown -R www-data:www-data /var/www/html
RUN php artisan config:cache
CMD ["php-fpm"]

After ​

Code owned by root and read-only for www-data; only storage/ and bootstrap/cache/ owned by www-data and mounted as tmpfs or volumes at run time; APP_KEY injected at start from a secret file; a start-up check that refuses unsafe states.

dockerfile
# syntax=docker/dockerfile:1
#
# Laravel 13 php-fpm image hardened for a read-only root filesystem.
# Builds on the multi-stage Dockerfile of the Images & Dockerfiles chapter;
# only the runtime stage differs. Build context: a Laravel application root.
#   docker buildx build --target app -t ghcr.io/acme/shop-app:1.8.0 .
# Expected, not built here (no Laravel app or Docker daemon in the build environment).

ARG PHP_VERSION=8.4

FROM php:${PHP_VERSION}-fpm-trixie AS base
RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \
    --mount=type=cache,target=/var/lib/apt,sharing=locked \
    apt-get update \
 && apt-get install -y --no-install-recommends libpq-dev libicu-dev libzip-dev unzip \
 && docker-php-ext-install -j"$(nproc)" pdo_pgsql intl zip pcntl bcmath
RUN mv "$PHP_INI_DIR/php.ini-production" "$PHP_INI_DIR/php.ini"
WORKDIR /var/www/html

FROM base AS vendor
COPY --from=composer:2 /usr/bin/composer /usr/bin/composer
COPY composer.json composer.lock ./
# A private Composer repository token arrives as a build secret: never an ARG,
# never in a layer, never in provenance.
RUN --mount=type=secret,id=composer_auth,env=COMPOSER_AUTH \
    composer install --no-dev --no-scripts --no-autoloader --prefer-dist --no-interaction
COPY . .
RUN composer dump-autoload --no-dev --optimize --classmap-authoritative --no-interaction \
 && rm -f .env .env.* auth.json

FROM base AS app
# Code is owned by root and read-only for www-data: a compromised worker cannot
# rewrite PHP files (no web shell via a writable public/ or app/).
COPY --from=vendor --chown=root:root --chmod=u=rwX,go=rX /var/www/html /var/www/html
# Only the paths Laravel writes are owned by www-data (UID 33). At run time they
# are tmpfs or volumes, because the root filesystem is mounted read-only.
RUN install -d -o www-data -g www-data -m 0750 \
      storage/app storage/framework/cache storage/framework/sessions \
      storage/framework/views storage/logs bootstrap/cache
COPY --chmod=0755 docker/entrypoint.sh /usr/local/bin/app-entrypoint
COPY --chmod=0644 docker/runtime-check.php /usr/local/lib/runtime-check.php
# No APP_KEY here: it is injected at run time (secret file or env), so the same
# image runs in every environment and leaking the image does not leak the key.
USER www-data
ENTRYPOINT ["app-entrypoint"]
CMD ["php-fpm"]
bash
#!/bin/sh
# Container start for the hardened Laravel image.
set -eu

# 1. APP_KEY from a mounted secret file (Compose/Kubernetes secret), if given.
#    Laravel reads only the APP_KEY environment variable, so export it for
#    this process tree and never echo it.
if [ -n "${APP_KEY_FILE:-}" ]; then
  APP_KEY=$(cat "$APP_KEY_FILE")
  export APP_KEY
  unset APP_KEY_FILE
fi

# 2. Fail closed: refuse root, a missing or malformed key, and code that is
#    writable by the PHP user.
php /usr/local/lib/runtime-check.php

# 3. Caches are built now, into the tmpfs at bootstrap/cache, with the real
#    environment (never at build time).
php artisan optimize

exec docker-php-entrypoint "$@"
php
<?php
// Startup assertions for a Laravel container. Exit 1 (container fails to
// start) instead of serving traffic in an unsafe state.

declare(strict_types=1);

$root = '/var/www/html';
$problems = [];

// 1. Not root. posix is compiled into the official php images; guard anyway.
if (function_exists('posix_geteuid') && posix_geteuid() === 0) {
    $problems[] = 'running as UID 0: set USER www-data / runAsUser';
}

// 2. APP_KEY present, not the example key, and 32 bytes for AES-256-CBC.
$key = getenv('APP_KEY') ?: '';
if ($key === '') {
    $problems[] = 'APP_KEY is not set (mount it as a secret, never bake it into the image)';
} else {
    $raw = str_starts_with($key, 'base64:') ? base64_decode(substr($key, 7), true) : $key;
    if ($raw === false || strlen($raw) !== 32) {
        $problems[] = 'APP_KEY must decode to 32 bytes (php artisan key:generate --show)';
    }
}

// 3. Writable where Laravel writes, read-only everywhere else.
foreach (['storage/framework/cache', 'storage/framework/sessions', 'storage/framework/views', 'bootstrap/cache'] as $dir) {
    if (!is_writable("$root/$dir")) {
        $problems[] = "$dir is not writable: mount a tmpfs/emptyDir owned by www-data";
    }
}
foreach (['app', 'config', 'public', 'routes', 'vendor'] as $dir) {
    if (is_dir("$root/$dir") && is_writable("$root/$dir")) {
        $problems[] = "$dir is writable by the PHP user: code must be owned by root";
    }
}

// 4. Debug mode exposes configuration values to visitors.
if (filter_var(getenv('APP_DEBUG') ?: 'false', FILTER_VALIDATE_BOOL)) {
    $problems[] = 'APP_DEBUG=true in a production image';
}

foreach ($problems as $p) {
    fwrite(STDERR, "runtime-check: $p\n");
}
exit($problems === [] ? 0 : 1);

The Compose file runs the Go api, php-fpm and Nginx with the same hardening anchor:

yaml
# Hardened Compose stack: Go api + Laravel (php-fpm) + Nginx (unprivileged).
# Expected, not run. Images are referenced by digest in production; tags here for readability.
name: shop

x-hardening: &hardening
  read_only: true
  cap_drop: [ALL]
  security_opt:
    - no-new-privileges:true
  pids_limit: 256
  restart: unless-stopped

services:
  api:
    <<: *hardening
    image: ghcr.io/acme/api:1.0.0
    user: "65532:65532"
    tmpfs:
      - /tmp:size=64m,mode=1777
    secrets:
      - source: signing_key
        target: signing_key          # -> /run/secrets/signing_key
    environment:
      SIGNING_KEY_FILE: /run/secrets/signing_key
    mem_limit: 256m
    cpus: 1.0
    networks: [backend]

  app:                                 # php-fpm, image from ../laravel/Dockerfile
    <<: *hardening
    image: ghcr.io/acme/shop-app:1.8.0
    user: "www-data:www-data"
    tmpfs:
      # Regenerated at start by `php artisan optimize` (entrypoint): safe to lose.
      - /var/www/html/bootstrap/cache:uid=33,gid=33,mode=0750
      - /var/www/html/storage/framework/views:uid=33,gid=33,mode=0750
      # Only used as fallbacks: sessions and cache live in Redis (below).
      - /var/www/html/storage/framework/cache:uid=33,gid=33,mode=0750
      - /var/www/html/storage/framework/sessions:uid=33,gid=33,mode=0750
      - /tmp:size=64m,mode=1777
    volumes:
      # Durable user uploads only; sessions/cache go to Redis, logs to stderr.
      - uploads:/var/www/html/storage/app
    secrets:
      - app_key
    environment:
      APP_ENV: production
      APP_DEBUG: "false"
      LOG_CHANNEL: stderr
      SESSION_DRIVER: redis
      CACHE_STORE: redis
      APP_KEY_FILE: /run/secrets/app_key   # read by docker/entrypoint.sh, not by Laravel itself
    mem_limit: 512m
    networks: [backend]

  web:
    <<: *hardening
    image: ghcr.io/acme/shop-web:1.8.0     # nginx-unprivileged based: listens on 8080, pid and temp files in /tmp
    tmpfs:
      - /tmp:size=16m
    ports:
      - "127.0.0.1:8080:8080"
    depends_on: [app]
    networks: [frontend, backend]

networks:
  frontend: {}
  backend:
    internal: true                     # no route to the internet from api/app

volumes:
  uploads: {}

# Compose bind-mounts each secret file, so HOST ownership applies inside the
# container: make each file readable by the container's UID and nobody else,
#   chown 65532 secrets/signing_key && chmod 0400 secrets/signing_key   (api)
#   chown 33    secrets/app_key     && chmod 0400 secrets/app_key       (www-data)
# With userns-remap the host owner is the remapped UID (subordinate base + UID).
secrets:
  signing_key:
    file: ./secrets/signing_key
  app_key:
    file: ./secrets/app_key

The Laravel angle ​

  • Laravel file permissions and APP_KEY handling in containers. Laravel's deployment guide: "Laravel will need to write to the bootstrap/cache and storage directories, so you should ensure the web server process owner has permission to write to these directories." Exactly those, and nothing else: COPY --chown=root:root --chmod=u=rwX,go=rX makes the code read-only to www-data (symbolic --chmod needs Dockerfile syntax 1.14+), install -d -o www-data creates the writable directories, and the runtime mounts tmpfs over the caches.
  • What lives where with a read-only root. bootstrap/cache and storage/framework/views are rebuilt by php artisan optimize at start, so tmpfs is fine; sessions and cache go to Redis (SESSION_DRIVER=redis, CACHE_STORE=redis); logs go to stderr (LOG_CHANNEL=stderr); only storage/app (user uploads) needs a volume, or better object storage.
  • APP_KEY. "This configuration value is driven by the APP_KEY environment variable", generated with php artisan key:generate ("PHP's secure random bytes generator"); values are encrypted with AES-256-CBC, so the key is 32 bytes (base64: prefix plus 44 characters). Laravel reads only the environment variable, so the entrypoint exports it from APP_KEY_FILE; it is never in the image, never in Git (".env file should not be committed to your application's source control"), never in a log.
  • Rotation. Changing the key logs every user out and makes old ciphertext unreadable, unless the old key is kept in APP_PREVIOUS_KEYS ("Laravel will try all previous keys until one of the keys is able to decrypt the value"). Mount both from the secret store and rotate without rebuilding.
  • APP_DEBUG. "If the APP_DEBUG variable is set to true in production, you risk exposing sensitive configuration values to your application's end users", so the runtime check refuses it.
  • Build-time secrets. A private Composer repository token goes through --mount=type=secret,id=composer_auth,env=COMPOSER_AUTH, and auth.json and .env* are removed from the vendor stage and excluded by .dockerignore.
  • Dependency confusion in Composer. Keep private repositories canonical (the default) so a public foo/bar 2.999 never shadows your private foo/bar.
  • Workers. Queue workers and the scheduler reuse the same image with the same securityContext; none of them needs a capability.

Solving the classic problems ​

ProblemSolutionHowAdvantageCost / limit
App runs as rootNumeric non-root userUSER 65532:65532, runAsNonRootRCE gets an unprivileged UIDFix file ownership, high ports
Root needed by legacy imageUser namespaceuserns-remap, rootless, hostUsers: falseRoot inside is nobody outsideVolume ownership, kernel ≥ 6.3 on Kubernetes
Too many capabilitiesDrop allcap_drop ALL, add one with a reasonRemoves NET_RAW, CHOWN, ...Find the one the app needs
setuid escalationno_new_privsno-new-privileges, allowPrivilegeEscalation: falsesu/sudo/file caps inertsetcap tricks stop working
Kernel bug exposureseccomp + LSMRuntimeDefault everywhere, derived profile for exposed servicesFewer reachable syscalls and pathsProfiles to maintain
Persistence / web shellsRead-only root--read-only + tmpfs, code owned by rootNothing survives a restartList writable paths
CI needs DockerRootless buildersrootless BuildKit/Buildah, no socketNo host root from a PRBuilder setup
Vulnerable or unknown imageScan, sign, admitTrivy/Grype gate, cosign, Kyverno verifyOnly known digests runPipeline and policy upkeep
Secrets in imagesMounts and filesbuild secrets, /run/secrets, *_FILEImage leak ≠ secret leakEntrypoint glue

"It needs root" ​

Ask what for. Binding port 80: listen on 8080. Writing to /var/www: own only the writable directories. Installing packages at start-up: move it to the build. chown of a volume: fsGroup or tmpfs uid=. What is left is rare enough for a user namespace.

"It needs privileged" ​

Find the single kernel feature: a device (--device), one capability (NET_ADMIN for a VPN client), a sysctl (namespaced sysctls can be set per Pod). Grant that, keep seccomp and the LSM on, and put the workload in its own namespace at the PSS level it needs.

A seccomp profile that does not break production ​

Start from the runtime default, remove what the service provably never calls, run the full test suite and a canary under the SCMP_ACT_LOG copy, read the logged syscalls, then enforce. Keep the arch map from the default so arm64 nodes work.

Building images in CI without the Docker socket ​

Use a rootless BuildKit (or Buildah) running as an unprivileged user, or the hosted builder of your CI; give the job push rights to one repository through OIDC, never a long-lived password.

A CVE in the base image, every week ​

Switch to a minimal base (distroless/static for Go), rebuild automatically when the base digest changes, gate on fixable High/Critical only, write VEX for the ones that cannot affect you, and re-scan running digests nightly.

Rolling out restricted Pod Security without an outage ​

Dry-run the label server-side, turn on warn and audit, fix charts, then enforce with a pinned version; existing Pods are not evicted, so the change bites only on the next rollout.

Choosing ​

Which engine mode ​

SituationChooseWhy
Developer laptop, LinuxRootless Docker or PodmanNo root daemon to abuse
Shared build host / self-hosted CIRootless BuildKit or Podman, ephemeral runnersPR code never reaches host root
Production Docker hostRootful + userns-remap + no-new-privileges default, or rootlessCompatibility with volumes and ports
Kubernetes nodescontainerd/CRI-O with --seccomp-default, hostUsers: false where supportedCluster-wide defaults
Hostile multi-tenant codegVisor or Kata RuntimeClassSecond kernel boundary

Which isolation level per workload ​

WorkloadPSS levelExtra
Web APIs, workers (Go, Laravel)restrictedread-only root, default-deny network, signed images
Databases, stateful setsrestricted (usually possible)fsGroup, PVCs
Ingress controllersrestricted or baseline (high ports inside)NET_BIND_SERVICE only if binding < 1024
CNI, CSI, node exporters, Falcoprivileged, own namespaceDedicated nodes if possible
User-submitted code, CI jobsrestricted + sandbox RuntimeClassNo service-account token, egress deny

Which policy engine ​

NeedChoose
Only the standard levelsPSA alone
A few custom CEL rules, no extra componentsValidatingAdmissionPolicy
Image signature verification, mutation, reports, Kubernetes-native YAMLKyverno
One policy language across Kubernetes, Terraform and CIOPA Gatekeeper (Rego)

Which scanner ​

NeedChoose
One tool for images, repos, IaC, secrets, KubernetesTrivy
SBOM-first workflow with Syft, EPSS/KEV prioritisationGrype
Already on Docker Hub / Docker Desktop, policy dashboardsDocker Scout
Go reachabilitygovulncheck (in addition)
Defence in depthTwo scanners with different databases on the release digest

In architecture: from a single process to a distributed system ​

Container security is not one setting but a property of the path from source to running process. The architecture questions are: where is each control enforced, who owns it, and how does it scale from one host to many clusters without depending on every team remembering it.

Monolith: one host, a few containers ​

A Laravel monolith on one VM with Compose: the controls are in the Compose file (the x-hardening anchor applied to every service), the daemon config (no-new-privileges, userns-remap, icc: false), the host (CIS Docker Benchmark via Docker Bench, unattended kernel and runc updates) and the image build (non-root, read-only-ready, no secrets). Secrets are Compose secret files; Compose bind-mounts them, so host ownership applies inside the container: each file is owned by the UID that reads it (65532 for the api, 33 for www-data; the remapped UID under userns-remap) with mode 0400. The single biggest risk at this size is a human: an operator adding the Docker socket to "just one" container or running docker run --privileged to debug.

Modular monolith: one repository, several images ​

The web, worker and Go sidecar images share a base and a pipeline. Centralise: one base image per language with the non-root user and writable paths already defined, one reusable CI workflow (scan, SBOM, provenance, sign), one Compose/Helm template with the securityContext. The services differ only in the writable paths and the one capability (if any) each needs, which are reviewed like code.

Microservices: many images, many teams ​

Twenty services in Kubernetes: per-team diligence does not scale, so the platform makes the secure path the default and the insecure path impossible.

text
1  golden base images (distroless/static, php-fpm hardened) built and signed by the platform team
2  reusable CI workflow: govulncheck/composer audit -> build -> Trivy + Grype -> SBOM, provenance -> cosign keyless
3  GitOps (Argo CD) applies Helm charts whose default values carry the restricted securityContext
4  every app namespace: PSA enforce=restricted (pinned), default-deny NetworkPolicy
5  Kyverno: registry ghcr.io/acme/*, digest, signature identity, readOnlyRootFilesystem, limits
6  Falco DaemonSet + API audit logs -> SIEM; nightly re-scan of running digests

Provisioning (registries, IAM roles for CI OIDC, node pools with sandbox runtimes) is Terraform; packaging is Helm (Packaging for Kubernetes); delivery is Argo CD or Flux (GitOps). Ingress (for example ingress-nginx) terminates 80/443 so no application Pod needs a low port.

Distributed data: registries, caches and policy across regions ​

At several clusters and regions the trust data must travel with the images: signatures and attestations replicate with the image (OCI referrers or cosign's tag scheme), or admission in the far region rejects a perfectly good digest; Rekor and Fulcio availability (or a private Sigstore) becomes part of the deployment path, so set the webhook failurePolicy deliberately; vulnerability databases are mirrored for air-gapped clusters (Trivy supports skipping DB updates against a pre-downloaded DB); policy bundles are versioned and rolled out like code. Stateful services keep PVCs, so fsGroup and SELinux relabelling time matter on large volumes.

Scaling path: 1x, 10x, 100x ​

ScaleImage trustRuntimeCluster policyDetection
1x (one VM)Official/distroless bases pinned, Trivy in CICompose hardening anchor, daemon defaultsn/aHost logs, Docker Bench quarterly
10x (one cluster)Golden bases, SBOM + provenance, cosign keylessRestricted securityContext in chart defaults, --seccomp-defaultPSA restricted, Kyverno registry/digest/signatureFalco, API audit
100x (many clusters)Private registry mirrors, replicated signatures, VEX feeds, SLSA L3 buildershostUsers: false, sandbox RuntimeClasses for untrusted code, derived seccomp/AppArmor for exposed tiersPolicies as versioned bundles, exceptions with expiryCentral SIEM, nightly fleet re-scan, incident runbooks

Lab ​

Label: steps 1 to 3 ran on the host (macOS, Go 1.27.4 darwin/arm64) and show real output. Every docker, kubectl, trivy, grype, cosign, apparmor_parser and govulncheck command after that is expected, not run: there is no Docker daemon, Kubernetes cluster or Linux kernel in this build environment (AUTHORING cost rule), and a govulncheck run was not permitted in the build session. Their outputs are placeholders or quotes from the saved documentation, never invented results.

1. Test the Go module (ran on the host) ​

bash
REPO=$PWD                     # run from the repository root; later steps cd from here
cd "$REPO/docs/snippets/platform/container-security/go"
gofmt -l .                   # (no output)
go vet ./...                 # (no output)
go test -race -count=1 ./...
# ok  	academy/container-security/cmd/api	1.664s
# ok  	academy/container-security/cmd/secreport	1.646s
# ok  	academy/container-security/procstatus	1.632s
GOOS=linux GOARCH=amd64 go vet ./...    # (no output: the Linux build is clean too)

2. A static Linux binary (ran on the host) ​

bash
GOOS=linux GOARCH=arm64 CGO_ENABLED=0 go build -trimpath -ldflags "-s -w" -o api-linux ./cmd/api
file api-linux
# api-linux: ELF 64-bit LSB executable, ARM aarch64, version 1 (SYSV), statically linked, Go BuildID=..., stripped
go version -m api-linux | grep -E "CGO|GOOS|GOARCH|trimpath"
# 	build	-trimpath=true
# 	build	CGO_ENABLED=0
# 	build	GOARCH=arm64
# 	build	GOOS=linux

3. What the kernel would report, decoded (ran on the host, fixture files) ​

The fixtures hold the /proc/self/status lines that the corresponding docker run would produce: Docker's default capability list (a80425fb), all 41 capabilities for --privileged, and the hardened set. The tool's output is real; the fixture values are derived from moby's default list and capability.h, not captured from a container. Long capability lists and repeated lines are abbreviated below (...); the full output is in the saved lab log.

bash
go build -o secreport ./cmd/secreport
./secreport -strict -status procstatus/testdata/docker-default-root.status -uidmap procstatus/testdata/host.uid_map; echo exit=$?
# uid=0 euid=0 seccomp=filter filters=1 no_new_privs=false
# effective: CAP_CHOWN,CAP_DAC_OVERRIDE,CAP_FOWNER,CAP_FSETID,CAP_KILL,CAP_SETGID,CAP_SETUID,CAP_SETPCAP,CAP_NET_BIND_SERVICE,CAP_NET_RAW,CAP_SYS_CHROOT,CAP_MKNOD,CAP_AUDIT_WRITE,CAP_SETFCAP
# bounding:  (the same 14; lines abbreviated here, full text in the saved lab log)
# CRITICAL root          effective UID 0 and it is host UID 0 (no user namespace): an escape lands as host root
# MEDIUM   cap_drop      bounding set still holds 13 capabilities (CAP_CHOWN,...,CAP_SETFCAP); drop ALL and add back only what is needed
# MEDIUM   no_new_privs  no_new_privs is 0: setuid binaries and file capabilities can still raise privileges on execve
# exit=1
./secreport -strict -status procstatus/testdata/hardened-nonroot.status -uidmap procstatus/testdata/host.uid_map; echo exit=$?
# uid=65532 euid=65532 seccomp=filter filters=1 no_new_privs=true
# effective: (none)
# bounding:  (none)
# OK       no findings
# exit=0
./secreport -strict -status procstatus/testdata/netbind-nonroot.status -uidmap procstatus/testdata/host.uid_map; echo exit=$?
# ...
# bounding:  CAP_NET_BIND_SERVICE
# INFO     cap_add       CAP_NET_BIND_SERVICE is allowed by the bounding set but not effective: a non-root process needs file or ambient capabilities to use it; listen on a port >= 1024 instead
# exit=0
./secreport -status procstatus/testdata/docker-default-root.status -uidmap procstatus/testdata/userns.uid_map
# ...
# INFO     root          UID 0 inside a user namespace, mapped to unprivileged host UID 100000
./secreport; echo exit=$?            # macOS has no /proc
# secreport: open /proc/self/status: no such file or directory
# exit=2

The privileged fixture prints 41 effective capabilities, CRITICAL capabilities CAP_SYS_ADMIN is in the effective set, ten HIGH capability lines and HIGH seccomp no seccomp filter (Unconfined) (full output in the saved lab log).

4. The same check inside real containers (expected, not run) ​

bash
cd "$REPO/docs/snippets/platform/container-security/go"     # REPO = the repository root
docker build -t api:hardened .        # runs the vulncheck stage too (the runtime stage copies its marker)
docker run --rm --entrypoint /usr/local/bin/secreport api:hardened -strict ; echo exit=$?
# image USER is 65532, default caps in the bounding set, no_new_privs 0:
# MEDIUM cap_drop ..., MEDIUM no_new_privs ...        exit=1
docker run --rm --cap-drop ALL --security-opt no-new-privileges --read-only \
  --entrypoint /usr/local/bin/secreport api:hardened -strict ; echo exit=$?
# OK no findings                                      exit=0
docker run --rm --privileged --user 0 --entrypoint /usr/local/bin/secreport api:hardened
# CRITICAL root ..., CRITICAL capabilities CAP_SYS_ADMIN ..., HIGH seccomp ...
docker run --rm -t -i ubuntu bash -c 'mount -t tmpfs none /mnt'
# mount: permission denied            (Docker's own reference example)

5. Read-only root and tmpfs (expected, not run) ​

bash
cd "$REPO/docs/snippets/platform/container-security/docker"
mkdir -p secrets && (umask 077 && head -c 32 /dev/urandom | base64 > secrets/signing_key.src)   # your copy, mode 0600
# the copy the container mounts: owned by its UID (host ownership applies inside), mode 0400
sudo install -o 65532 -m 0400 secrets/signing_key.src secrets/signing_key
docker run -d --name api --user 65532:65532 --cap-drop ALL --security-opt no-new-privileges \
  --read-only --tmpfs /tmp:rw,noexec,nosuid,size=64m --pids-limit 128 \
  --mount type=bind,src="$PWD/secrets/signing_key",dst=/run/secrets/signing_key,readonly \
  -p 127.0.0.1:8080:8080 api:hardened
curl -s -X POST --data-binary @compose.hardened.yaml localhost:8080/reports   # 201 + 64 hex chars (HMAC)
docker exec api /usr/local/bin/secreport -strict                              # OK no findings
docker run --rm --read-only --entrypoint /usr/local/bin/api api:hardened
# without the secret mount the process exits 1 after a JSON log line: "msg":"startup","err":"secret /run/secrets/signing_key: open ...: no such file or directory"

6. Push, take the real digest, deploy under Pod Security Admission (expected, not run; warning text from the Kubernetes tutorial) ​

bash
cd "$REPO/docs/snippets/platform/container-security"
docker buildx build --target runtime --platform linux/amd64,linux/arm64 -t ghcr.io/acme/api:dev --push go
DIGEST=$(docker buildx imagetools inspect ghcr.io/acme/api:dev --format '{{json .Manifest}}' | jq -r .digest)
echo "$DIGEST"                                  # sha256:<64 hex> (index digest; placeholder here)
kubectl apply -f k8s/namespace.yaml
kubectl label --dry-run=server --overwrite ns --all pod-security.kubernetes.io/enforce=restricted
kubectl -n shop run nginx --image=nginx
# Warning: would violate PodSecurity "restricted:latest": allowPrivilegeEscalation != false
#   (container "nginx" must set securityContext.allowPrivilegeEscalation=false), unrestricted capabilities ...
#   (enforce=restricted rejects the pod with an error naming the same controls)
# from your readable copy, not the 65532-owned file (which this user cannot read)
kubectl -n shop create secret generic api-signing-key --from-file=signing_key=docker/secrets/signing_key.src
sed "s|ghcr.io/acme/api@sha256:0\{64\}|ghcr.io/acme/api@${DIGEST}|" k8s/deployment.yaml \
  | kubectl apply -f - -f k8s/networkpolicy.yaml        # pod starts (signature policies not yet installed)
kubectl -n shop exec deploy/api -- /usr/local/bin/secreport
# uid=65532 ... seccomp=filter ... no_new_privs=true
kubectl apply -f k8s/kyverno-policies.yaml               # needs Kyverno 1.20+ in the cluster
kyverno test k8s/kyverno-test                            # foreign-init and unsigned-init fail only because of their init containers

7. Scan, VEX, sign, verify (expected, not run) ​

bash
cd "$REPO/docs/snippets/platform/container-security"
trivy image --scanners vuln,secret --severity HIGH,CRITICAL --ignore-unfixed --exit-code 1 "ghcr.io/acme/api@${DIGEST}"
trivy image --vex vex/api.openvex.json "ghcr.io/acme/api@${DIGEST}"     # CVE-0000-00000 no longer listed
docker buildx imagetools inspect "ghcr.io/acme/api@${DIGEST}" --format '{{json .SBOM}}' > sbom.json
grype sbom:./sbom.json
docker scout cves --only-fixed --exit-code "ghcr.io/acme/api@${DIGEST}"   # exit 2 if vulnerabilities
cosign sign --yes "ghcr.io/acme/api@${DIGEST}"            # in CI: keyless with the workflow identity
cosign verify "ghcr.io/acme/api@${DIGEST}" \
  --certificate-identity=https://github.com/acme/api/.github/workflows/secure-build.yml@refs/heads/main \
  --certificate-oidc-issuer=https://token.actions.githubusercontent.com
json
{
  "@context": "https://openvex.dev/ns/v0.2.0",
  "@id": "https://github.com/acme/api/vex/2026-11-29-1",
  "author": "acme security team <security@acme.example>",
  "role": "Document Creator",
  "timestamp": "2026-11-29T09:00:00Z",
  "version": 1,
  "statements": [
    {
      "vulnerability": { "name": "CVE-0000-00000" },
      "products": [
        {
          "@id": "pkg:oci/api@sha256%3A0000000000000000000000000000000000000000000000000000000000000000?repository_url=ghcr.io/acme/api",
          "subcomponents": [ { "@id": "pkg:golang/example.com/somelib@v1.2.3" } ]
        }
      ],
      "status": "not_affected",
      "justification": "vulnerable_code_not_in_execute_path",
      "impact_statement": "govulncheck reports the module but no call path from api to the vulnerable symbol."
    }
  ]
}

8. Load the AppArmor profile and the seccomp profile (expected, not run) ​

bash
cd "$REPO/docs/snippets/platform/container-security"
sudo apparmor_parser -r -W apparmor/api-restricted
sudo aa-status | grep api-restricted
python3 seccomp/derive.py "$REPO/pipeline/sources/container-security/moby-seccomp-default.txt" seccomp   # this one ran on the host
docker run --rm --security-opt seccomp="$PWD/seccomp/api-seccomp-log.json" --entrypoint /usr/local/bin/secreport api:hardened
# then read the kernel log for logged syscalls: dmesg | grep -i seccomp

Common misconceptions ​

BeliefReality
Containers isolate like VMsOne shared kernel; NIST: "a larger inter-object attack surface than seen with hypervisors"
Root in a container is harmlessUID 0 against mounted files and after any escape; user namespaces are off by default in Docker
Rootless Docker equals userns-remapWith userns-remap "the daemon itself is running with root privileges"
--cap-add NET_BIND_SERVICE lets a non-root app bind 80Bounding set only; the process needs file capabilities (ignored under no_new_privs) or ambient capabilities (which no_new_privs does not remove). Listen on 8080
Kubernetes uses a seccomp profile by defaultUnconfined unless the kubelet runs with --seccomp-default or the Pod sets one
seccomp is a sandboxKernel docs: "System call filtering isn't a sandbox"
A read-only :ro Docker socket mount is safeAPI calls still work; docker access "grants root-level privileges"
Restricted PSS = hardenedNo read-only root, limits, network policy, registry or signature checks
PSA enforce rejects bad DeploymentsEnforce checks Pods; Deployments only get warn/audit
A NetworkPolicy always applies"without a controller that implements it will have no effect"
Memory limits stop fork bombs"a fork bomb is likely to exhaust the number of tasks before hitting memory restrictions"
A high CVSS score means exploitable hereBase score is context-free; VEX and reachability decide
Signed means safeA signature binds an identity to a digest; verify the identity, scan the content
Kubernetes Secrets are encrypted"stored unencrypted in the API server's underlying data store (etcd)" by default
Falco prevents attacksIt detects and alerts; prevention is the other controls

Cheat sheet ​

TopicRemember
Threat modelAssume RCE inside; limit what it reaches: host, neighbours, network
IdentityNumeric non-root USER; user namespaces (rootless, userns-remap, hostUsers: false)
Capabilitiescap_drop ALL; add one with a reason; Docker default is 14; SYS_ADMIN is "the new root"
no_new_privsno-new-privileges / allowPrivilegeEscalation: false; default true in Kubernetes
seccompDocker default blocks ~44 of 300+; Kubernetes: set RuntimeDefault, enable --seccomp-default
LSMAppArmor docker-default, SELinux container_t + MCS pair; relabel with :z/:Z, never disable
Filesystem--read-only + tmpfs; code owned by root; volumes only for real data
Never--privileged, Docker socket, hostPath: / in application workloads
Limitspids (fork bombs), memory, CPU, disk on every container; kubelet PodPidsLimit
ImagesTrusted minimal base by digest; distroless for Go; rebuild on base updates
ScanningTrivy/Grype/Scout on the digest; fixable High/Critical gate; VEX for exceptions; re-scan nightly
Supply chainSBOM + provenance + keyless cosign; verify identity at admission; pin actions by SHA
SecretsBuild: --mount=type=secret; run: /run/secrets files; never ARG/ENV/COPY
Pod SecurityLabels enforce: restricted + pinned version; warn/audit latest; policy engine for the rest
NetworkDefault-deny NetworkPolicy + DNS egress; CNI must enforce it
DetectionFalco (eBPF) + API audit logs + LSM denials, routed to someone

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — An attacker gets code execution in a container started with plain docker run image. List what limits them by default and the three biggest gaps. Must-know ​

Answer

Answer: By default Docker drops all but 14 capabilities, applies the default seccomp profile (about 44 of 300+ syscalls blocked) and the docker-default AppArmor profile, and masks parts of /proc. The gaps: the process is probably UID 0 and, without userns-remap or rootless mode, host UID 0 after an escape; no_new_privs is off, so setuid binaries can raise privileges; the root filesystem is writable and there are no PID or memory limits. Fix with a numeric USER, --cap-drop ALL, no-new-privileges, --read-only with tmpfs and limits. See Threat model.

2 — Why does --cap-add NET_BIND_SERVICE not let a non-root process bind port 80, and what is the right fix? Must-know ​

Answer

Answer: --cap-add puts the capability in the bounding (and permitted) sets of the container's initial process, but for a non-root user the kernel clears permitted and effective capabilities on the UID change, so the process's effective set stays empty. It would need file capabilities on the binary (ignored once no_new_privs is set) or ambient capabilities set by the runtime (not removed by no_new_privs, which only stops execve from granting new privileges). The right fix is to listen on 8080 and map 80 to it in the Service, ingress or -p 80:8080, which needs no capability at all. See Capabilities.

3 — What exactly does --privileged change, and what would you grant instead for a container that needs to configure network interfaces? Must-know ​

Answer

Answer: It enables all capabilities, disables the default seccomp and AppArmor profiles and the SELinux label, grants all host devices, and makes /sys and the cgroup mounts read-write; Docker warns such a container "can get a root shell on the host". For interface configuration grant only --cap-add NET_ADMIN, keep seccomp and the LSM on, run as non-root where possible, and isolate it in its own namespace or host. See Privileged containers.

4 — Explain the difference between rootless Docker, userns-remap and Kubernetes hostUsers: false. Must-know ​

Answer

Answer: All three map container UIDs to unprivileged host UIDs through a user namespace. With userns-remap the daemon still runs as root (daemon bugs are root bugs); rootless Docker runs the daemon and containers as an ordinary user inside a user namespace, with limits on low ports and some networking; hostUsers: false gives each Kubernetes Pod its own user namespace (stable since v1.36, needs idmap-capable filesystems, Linux 6.3+ for tmpfs) and cannot be combined with host namespaces. See User namespaces and Rootless engines.

5 — A namespace enforces restricted Pod Security. Which fields must every Pod set, and which important controls are still missing? Must-know ​

Answer

Answer: allowPrivilegeEscalation: false, runAsNonRoot: true (and no runAsUser: 0), capabilities.drop containing ALL (only NET_BIND_SERVICE may be added), seccompProfile.type RuntimeDefault or Localhost, plus everything in baseline (no host namespaces, no privileged, no hostPath, allowed volume types only). Still missing: read-only root filesystem, resource limits, network policies, registry and digest rules, image signatures and service-account token policy; add them with a policy engine and the chart template. See Pod Security Standards.

6 — Your Deployment applies cleanly in a restricted namespace, but no Pods appear. Why, and how do you find out? Important ​

Answer

Answer: PSA enforce mode checks Pods, not workload objects; for the Deployment it only warns and audits. The ReplicaSet controller's Pod creations are rejected, so the error is in the ReplicaSet's events (kubectl describe rs) rather than in kubectl apply. The warn label would have printed the violations at apply time; fix the pod template's securityContext. See Pod Security Standards.

7 — Why is mounting /var/run/docker.sock into a CI job equivalent to giving it root on the host, even with :ro? Must-know ​

Answer

Answer: The socket is the Docker API of a daemon that runs as root. :ro only prevents writes to the socket file, not API requests over it, so the job can ask the daemon to start docker run -v /:/host --privileged ... and get a root shell on the host; GitLab's docs say that when you share the daemon "you effectively disable the container's security mechanisms". Build with rootless BuildKit/Buildah or a remote builder instead. See Privileged containers and the socket.

8 — Why does Kubernetes need the kubelet's --seccomp-default, and what does RuntimeDefault mean? Important ​

Answer

Answer: Without it, a Pod that does not set seccompProfile runs Unconfined, unlike Docker which applies its default profile. --seccomp-default (stable since v1.27) makes the kubelet use RuntimeDefault for every Pod: the default profile of the node's container runtime (containerd or CRI-O), which may differ between runtimes and versions. Restricted PSS still requires the field to be set explicitly. See seccomp.

9 — Your scanner reports a Critical CVE in a Go module inside a distroless image. Walk through the decision. Important ​

Answer

Answer: Check whether a fixed version exists; if so, bump the module, rebuild and redeploy the new digest. If not, run govulncheck: if no call path reaches the vulnerable symbol, publish a VEX statement with status not_affected and justification vulnerable_code_not_in_execute_path and feed it to the scanner (trivy --vex), so the gate passes with a recorded reason; if reachable, mitigate (disable the feature, WAF rule, network policy) and track it. CVSS base score alone does not decide. See Image scanning.

10 — What does a keyless cosign signature prove, and what must the verifier check besides "valid signature"? Important ​

Answer

Answer: It proves that the holder of an OIDC identity (for CI, a specific workflow on a specific ref) signed exactly this digest, with a short-lived Fulcio certificate and an entry in the Rekor transparency log. The verifier must check the certificate identity and issuer (--certificate-identity, --certificate-oidc-issuer, or Kyverno's identities), the digest (not a tag), and the transparency log entry; any valid signature from anyone proves nothing. See SBOM, SLSA and signing.

11 — How do you give a Laravel container a read-only root filesystem without breaking it? Important ​

Answer

Answer: Make code owned by root and read-only to www-data; create storage/framework/* and bootstrap/cache owned by www-data and mount tmpfs over them (they are rebuilt by php artisan optimize at start); send logs to stderr and sessions/cache to Redis; keep a volume (or object storage) only for storage/app; mount /tmp as tmpfs for uploads. Inject APP_KEY at start from a secret file, never in the image. See Laravel.

12 — Why are PID limits a security control, and where do you set them in Docker and Kubernetes? Good to know ​

Answer

Answer: A container that can create unlimited tasks can exhaust the node's PID space and stop the kubelet, the runtime and sshd from forking; the kernel notes that a fork bomb exhausts tasks before memory limits. Docker: --pids-limit or Compose pids_limit; Kubernetes: node-level kubelet --pod-max-pids/PodPidsLimit plus reserved PIDs for the node. See Resource limits.

13 — What is dependency confusion and how do Composer and Go defend against it? Good to know ​

Answer

Answer: An attacker publishes a public package with your internal package's name and a higher version; a resolver that consults both sources picks the attacker's. Composer treats repositories as canonical by default, so a package found in your private repository is never loaded from Packagist; Go routes private paths away from the public proxy and checksum database with GOPRIVATE/GONOPROXY/GONOSUMDB and pins hashes in go.sum. See Supply chain.

14 — What does SELinux MCS add on top of type enforcement for containers? Good to know ​

Answer

Answer: Type enforcement lets every container_t process access every container_file_t file, so on its own it does not separate containers from each other. MCS gives each container a unique category pair (s0:c1,c2) and labels its files with the same pair; a process can access only files whose categories it dominates, so container B cannot read container A's volume even as root. Podman's :Z applies such a private label to a volume. See AppArmor and SELinux.

Glossary ​

TermMeaning
Threat modelThe assumed attacker, their starting point and the assets to protect; here: code execution inside a container
Container escapeGaining access to the host (or another container) from inside a container's namespaces
Kernel attack surfaceKernel code reachable from a container: allowed syscalls, visible /proc//sys files, devices
Shared kernelAll containers on a host use one kernel; the root difference from VMs
Root in containerUID 0 inside the container; host root unless a user namespace remaps it
User namespaceNamespace that maps UIDs/GIDs, so root inside can be unprivileged outside (uid_map)
userns-remapDocker daemon option mapping container UIDs to a subordinate range; daemon stays root
Rootless Docker / rootless PodmanEngine and containers run as an ordinary user inside a user namespace
hostUsers: falsePod field that gives the Pod its own user namespace
USER instructionDockerfile instruction setting the default user; numeric for runAsNonRoot checks
Non-root imageImage whose default user is not UID 0 and whose writable paths are owned by that user
Linux capabilitiesPer-thread units of root privilege (41 up to CAP_CHECKPOINT_RESTORE)
Capability setsPermitted, inheritable, effective, bounding, ambient
cap_drop ALL / cap_addRemove every capability / add one back (Docker, Compose, Kubernetes spellings vary)
CAP_NET_BIND_SERVICECapability to bind ports below 1024
CAP_SYS_ADMINOverloaded capability; "the new root"
no_new_privsProcess bit that stops execve from granting privileges; no-new-privileges, allowPrivilegeEscalation: false
seccompKernel syscall filtering (BPF in filter mode)
Default seccomp profileRuntime-provided allowlist (Docker: blocks ~44 syscalls); RuntimeDefault in Kubernetes
Custom seccomp profileProfile JSON passed with seccomp= or Localhost
SCMP_ACT_ERRNO / SCMP_ACT_LOGRefuse with an error / allow and log
LSMLinux Security Module: AppArmor, SELinux, ...
AppArmorPath-based MAC; Docker's docker-default profile
SELinuxLabel-based MAC: user:role:type:level
MCS labelsSELinux categories (s0:c1,c2) that separate containers of the same type
Privileged containerContainer with all capabilities and no seccomp/LSM confinement
Docker socket exposureGiving a container access to the daemon API, equivalent to host root
Docker-in-DockerRunning dockerd inside a container; needs --privileged
Read-only root filesystemContainer's own filesystem mounted read-only
tmpfsIn-memory filesystem used for writable scratch paths
PID limitcgroup pids.max: cap on tasks per container/Pod
Fork bombProcess that replicates until the task table is exhausted
Image provenanceVerifiable record of how and from what an image was built
Trusted base imageBase from an approved publisher, pinned by digest, rebuilt on updates
DistrolessImages with only the app and its runtime dependencies; no shell or package manager
CVEPublic identifier of a vulnerability
CVSSScoring system; v4.0 groups Base, Threat, Environmental, Supplemental
VEXProducer statement on whether a CVE affects a product (not_affected + justification)
SBOMSoftware Bill of Materials (SPDX, CycloneDX)
SLSASupply-chain levels; Build L1 provenance, L2 signed hosted, L3 hardened
cosignSigstore tool to sign and verify images and attestations
Fulcio / RekorSigstore certificate authority / transparency log
Trivy / Grype / Docker ScoutImage and SBOM vulnerability scanners
govulncheckGo tool reporting only reachable vulnerabilities
Admission controlAPI-server stage that validates or mutates objects before storage
Pod Security StandardsKubernetes levels privileged, baseline, restricted
Pod Security AdmissionBuilt-in admission plugin applying PSS by namespace labels (enforce, audit, warn)
securityContextPod/container fields that configure the runtime controls
Policy engineKyverno, OPA Gatekeeper: custom admission and audit policies
ValidatingAdmissionPolicyIn-tree CEL admission policy type
NetworkPolicyKubernetes L3/L4 pod traffic rules, enforced by the CNI
FalcoRuntime threat detection from kernel events
eBPFVerified in-kernel programs used by tracing and security agents
Audit loggingRecords of API requests (Kubernetes) and security denials (kernel audit)
Dependency confusionPublic package shadowing an internal package name
Registry authenticationScoped credentials for pull/push on a registry
CIS Docker BenchmarkConsensus configuration guideline for Docker (v1.9.0)
NIST SP 800-190NIST Application Container Security Guide (2017)

References ​

Built by Morteza Negahi