Hardening and Scanning Images
Write a multi-stage, distroless, non-root Dockerfile for a static Go service, prove the runtime settings with a negative test, gate Dockerfiles on Trivy misconfiguration checks, compare the attack surface of three base images, and sign an SBOM with Cosign so that tampering is detected.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: Download Trivy and Cosign and check them
- Step 2: Write the service and two Dockerfiles
- Step 3: Build the binary and test the runtime settings
- Step 4: Scan the Dockerfiles for misconfigurations
- Step 5: Scan images for known vulnerabilities
- Step 6: Sign the SBOM and detect tampering
- Check your understanding
- Apply it
- Review prompt
Lessons of Container & Kubernetes Security
- What Containers Isolate and What They Do Not Concept · 15 min
- Hardening and Scanning Images Lab · 25 min
- Cluster Hardening: RBAC, Pod Security and Network Policy Lab · 30 min
- Admission Control for Trusted Workloads Worked example · 20 min
- Runtime Detection and Cluster Audit Logs Lab · 25 min
- Container & Kubernetes Security Check Knowledge check · 6 questions
What you will learn
- Build minimal, non-root container images, scan them for vulnerabilities and misconfigurations, and enforce signed or allow-listed images at admission.
Prerequisites: Kubernetes Fundamentals
01. Goal and setup
An image is the unit you ship, so it is where you remove what an intruder could use. In this lab you write two Dockerfiles for the same small service, one naive and one hardened. You check the runtime settings that the hardened image expects, scan both Dockerfiles for misconfigurations, scan three base images for known vulnerabilities, and sign the software bill of materials (SBOM) of an image so that any later change to it is detected.
The techniques this defends against are Implant Internal Image (T1525), where an intruder adds code to an image in your registry, and Malicious Image (T1204.003), where someone runs an image they should not trust. Small images, pinned digests and signatures make both harder and easier to spot.
You need: Linux on amd64 (for other platforms pick the matching release files), Docker, Python 3.10 or later, curl, and about 4 GB of free disk. Images: alpine:3.20, node:22-bookworm-slim and golang:1.26.11-bookworm; pull them first (together about 1.6 GB). Tools: Trivy 0.76.2 and Cosign 3.1.4, downloaded in step 1. Trivy downloads its vulnerability database on the first scan; unpacked in cache/, it took about 1.7 GB on 16 Nov 2026.
image-lab/
├── bin/ trivy, cosign (step 1)
├── app/ main.go, go.mod, Dockerfile.naive, Dockerfile (step 2)
├── out/selfcheck the static binary (step 3)
├── misconfig.tpl report template (step 4)
├── summarise.py scan summary (step 5)
├── cache/ Trivy database and cache
└── sbom.cdx.json, sbom.bundle.json, cosign.key, cosign.pub (step 6)02. Step 1: Download Trivy and Cosign and check them
Security tools are software you run with high trust, so check that you got the files the projects published. Each release lists SHA-256 checksums, and sha256sum -c compares your download with them.
mkdir -p bin cache
T=0.76.2; C=v3.1.4
TR=https://github.com/aquasecurity/trivy/releases/download/v$T
curl -sSLO $TR/trivy_${T}_Linux-64bit.tar.gz
curl -sSL $TR/trivy_${T}_checksums.txt | grep " trivy_${T}_Linux-64bit.tar.gz$" \
| sha256sum -c
tar xzf trivy_${T}_Linux-64bit.tar.gz -C bin trivy && rm trivy_${T}_Linux-64bit.tar.gz
CO=https://github.com/sigstore/cosign/releases/download/$C
curl -sSL -o bin/cosign $CO/cosign-linux-amd64
curl -sSL $CO/cosign_checksums.txt | grep " cosign-linux-amd64$" \
| sed 's| cosign-linux-amd64| bin/cosign|' | sha256sum -c
chmod +x bin/cosign
bin/trivy --version | head -1
bin/cosign version 2>&1 | grep GitVersiontrivy_0.76.2_Linux-64bit.tar.gz: OK
bin/cosign: OK
Version: 0.76.2
GitVersion: v3.1.403. Step 2: Write the service and two Dockerfiles
The service is a small Go program that reports the security context it runs in: its user, its effective capabilities, and whether it can write to / and to /tmp. Save these files in app/.
module example.com/selfcheck
go 1.26// selfcheck reports the security context it runs in: user, capabilities, writes.
package main
import (
"fmt"
"os"
"strings"
)
func capEff() string {
data, err := os.ReadFile("/proc/self/status")
if err != nil {
return "unknown"
}
for _, line := range strings.Split(string(data), "\n") {
if strings.HasPrefix(line, "CapEff:") {
return strings.TrimSpace(strings.TrimPrefix(line, "CapEff:"))
}
}
return "unknown"
}
func tryWrite(path string) string {
if err := os.WriteFile(path, []byte("probe\n"), 0o600); err != nil {
return "denied (" + err.Error() + ")"
}
os.Remove(path)
return "ok"
}
func main() {
fmt.Printf("uid=%d gid=%d\n", os.Getuid(), os.Getgid())
fmt.Printf("CapEff=%s\n", capEff())
fmt.Printf("write /probe: %s\n", tryWrite("/probe"))
fmt.Printf("write /tmp/probe: %s\n", tryWrite("/tmp/probe"))
}FROM golang:latest
WORKDIR /src
COPY . .
RUN apt-get update && apt-get install -y curl
RUN go build -o /selfcheck .
CMD ["/selfcheck"]# Digests pinned on 16 Nov 2026; update them when you update the tags.
ARG GO_DIGEST=sha256:dc40a13b61304647ed7e5d581d246b86413dfc29d63c6d018310feb93cd98fc0
ARG BASE_DIGEST=sha256:aafe993665bf6200db38a02c11a9351e782a84b6a45e7f33b6695638c88e3931
# Stage 1: build a static binary with a pinned toolchain.
FROM golang:1.26.11-bookworm@${GO_DIGEST} AS build
WORKDIR /src
COPY go.mod main.go ./
RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/selfcheck .
# Stage 2: only the binary, on a distroless base, as a non-root user.
FROM gcr.io/distroless/static-debian13:nonroot@${BASE_DIGEST}
COPY --from=build /out/selfcheck /selfcheck
USER 65532:65532
ENTRYPOINT ["/selfcheck"]The naive file builds and runs in one stage, so the final image carries the whole Go toolchain, a shell, a package manager and curl, all running as root. Each of those is something an intruder can use after a code execution bug.
The hardened file uses a multi-stage build. Stage 1 compiles the binary in a pinned Go image. With CGO_ENABLED=0 the binary is statically linked, so it needs no system libraries. Stage 2 starts from gcr.io/distroless/static-debian13:nonroot, a distroless image: it holds CA certificates, time zone data and a few files, and no shell or package manager. Only the binary is copied in. USER 65532:65532 matches the non-root user that the nonroot image defines. Both base images are pinned by digest, the SHA-256 of the image manifest. A tag such as latest can point to new content tomorrow, while a digest always names the same bytes; you update digests on purpose, for example with a dependency bot.
Build both images on your machine with the commands below. These three commands were not run when this lesson was tested, because the test host did not allow image builds, so no output is shown for them. The rest of the lab does not depend on them: step 3 runs the same build stage by hand and tests the binary with the hardened runtime settings, and step 5 scans the distroless base that the hardened image uses.
docker build -t selfcheck:naive -f app/Dockerfile.naive app
docker build -t selfcheck:hardened app
docker images selfcheck04. Step 3: Build the binary and test the runtime settings
Run stage 1 by hand with the same Go image, then run the binary inside alpine:3.20 twice: once with Docker defaults and once with the settings a hardened pod uses. The binary is mounted read-only from your folder.
mkdir -p out .gocache
docker run --rm --name seclab-build --user "$(id -u):$(id -g)" \
-v "$PWD/app":/src:ro -v "$PWD/out":/out -v "$PWD/.gocache":/gocache \
-w /src -e CGO_ENABLED=0 -e GOCACHE=/gocache -e GOPATH=/tmp/go \
golang:1.26.11-bookworm go build -trimpath -ldflags="-s -w" -o /out/selfcheck .
file -b out/selfcheck | cut -d, -f1,4ELF 64-bit LSB executable, statically linkedecho "== default settings"
docker run --rm --name seclab-check -v "$PWD/out/selfcheck":/selfcheck:ro \
alpine:3.20 /selfcheck
echo "== hardened settings"
docker run --rm --name seclab-check -v "$PWD/out/selfcheck":/selfcheck:ro \
--read-only --tmpfs /tmp:rw,noexec,nosuid,size=16m --user 65532:65532 \
--cap-drop ALL --security-opt no-new-privileges alpine:3.20 /selfcheck== default settings
uid=0 gid=0
CapEff=00000000a80425fb
write /probe: ok
write /tmp/probe: ok
== hardened settings
uid=65532 gid=65532
CapEff=0000000000000000
write /probe: denied (open /probe: read-only file system)
write /tmp/probe: okThe second run is the negative test: the write to / must fail, and it does, with read-only file system. The write to /tmp still works because a small tmpfs is mounted there. Each Docker flag has a field in a Kubernetes securityContext, which is what you will enforce in the next lab:
--user 65532:65532isrunAsUser: 65532withrunAsNonRoot: true;--cap-drop ALLiscapabilities: {drop: ["ALL"]};--security-opt no-new-privilegesisallowPrivilegeEscalation: false;--read-onlywith--tmpfs /tmpisreadOnlyRootFilesystem: truewith anemptyDirvolume on/tmp.
05. Step 4: Scan the Dockerfiles for misconfigurations
trivy config checks configuration files against a library of rules. The rules are bundled with each Trivy release; --skip-check-update keeps the bundled set, so the results below are fixed for version 0.76.2. Save this template, which prints one line per finding.
{{- range . }}{{ $t := .Target }}{{ range .Misconfigurations -}}
{{ $t }} {{ .ID }} {{ .Severity }} {{ .Title }}
{{ end }}{{ end -}}export TRIVY_CACHE_DIR=$PWD/cache
bin/trivy config -q --skip-check-update --format template --template @misconfig.tpl app
echo "== CI gate: fail the build on HIGH or CRITICAL findings"
for f in Dockerfile.naive Dockerfile; do
bin/trivy config -q --skip-check-update --severity HIGH,CRITICAL --exit-code 1 \
"app/$f" > /dev/null
echo "$f: exit code $?"
doneDockerfile DS-0026 LOW No HEALTHCHECK defined
Dockerfile.naive DS-0001 MEDIUM ':latest' tag used
Dockerfile.naive DS-0002 HIGH Image user should not be 'root'
Dockerfile.naive DS-0026 LOW No HEALTHCHECK defined
Dockerfile.naive DS-0029 HIGH 'apt-get' missing '--no-install-recommends'
== CI gate: fail the build on HIGH or CRITICAL findings
Dockerfile.naive: exit code 1
Dockerfile: exit code 0The naive file fails four checks. DS-0002 is the missing non-root USER, DS-0001 the latest tag and DS-0029 an apt-get install that pulls in recommended extra packages. The hardened file fails only DS-0026, a missing HEALTHCHECK. Kubernetes ignores the Dockerfile HEALTHCHECK and uses liveness and readiness probes instead, so you can accept that finding with a written reason. The loop shows how to use the scanner as a gate in CI (continuous integration): with --severity HIGH,CRITICAL --exit-code 1, the naive file stops the pipeline and the hardened one passes. Agree the threshold with your team and record the exceptions.
06. Step 5: Scan images for known vulnerabilities
trivy image lists the packages in an image and matches them against its vulnerability database. Save the summary script, then scan two local images and the distroless base from step 2. The distroless scan downloads that image (a few MB) into Trivy's cache, not into Docker.
"""summarise.py: packages and vulnerabilities per image from Trivy JSON reports."""
import json
import sys
from collections import Counter
for path in sys.argv[1:]:
report = json.load(open(path))
packages, severity, fixable = 0, Counter(), 0
for result in report.get("Results", []):
packages += len(result.get("Packages", []))
for vuln in result.get("Vulnerabilities", []):
severity[vuln["Severity"]] += 1
fixable += bool(vuln.get("FixedVersion"))
os_info = report["Metadata"].get("OS", {})
print(f'{report["ArtifactName"].split("@")[0]} ({os_info.get("Family")}'
f' {os_info.get("Name")})')
levels = ("CRITICAL", "HIGH", "MEDIUM", "LOW")
counts = " ".join(f"{level}={severity[level]}" for level in levels)
print(f" packages: {packages} vulnerabilities: {counts} with a fix: {fixable}")export TRIVY_CACHE_DIR=$PWD/cache
DISTROLESS=gcr.io/distroless/static-debian13:nonroot@sha256:\
aafe993665bf6200db38a02c11a9351e782a84b6a45e7f33b6695638c88e3931
bin/trivy image -q --scanners vuln --list-all-pkgs --format json -o alpine.json \
--image-src docker alpine:3.20
bin/trivy image -q --scanners vuln --list-all-pkgs --format json -o node.json \
--image-src docker node:22-bookworm-slim
bin/trivy image -q --scanners vuln --list-all-pkgs --format json -o distroless.json \
--image-src remote "$DISTROLESS"
python3 summarise.py alpine.json node.json distroless.jsonalpine:3.20 (alpine 3.20.10)
packages: 14 vulnerabilities: CRITICAL=0 HIGH=2 MEDIUM=0 LOW=0 with a fix: 2
node:22-bookworm-slim (debian 12.15)
packages: 286 vulnerabilities: CRITICAL=1 HIGH=48 MEDIUM=110 LOW=86 with a fix: 23
gcr.io/distroless/static-debian13:nonroot (debian 13.7)
packages: 6 vulnerabilities: CRITICAL=0 HIGH=0 MEDIUM=0 LOW=0 with a fix: 0export TRIVY_CACHE_DIR=$PWD/cache
bin/trivy image --scanners vuln --image-src docker alpine:3.20 2>&1 >/dev/null \
| grep 'no longer supported' | cut -f2- | tr '\t' '\n'WARN
This OS version is no longer supported by the distribution
family="alpine" version="3.20.10"Look at the package counts first, because for a given image they do not change: 286 packages in the Node image (system and npm packages together), 14 in Alpine and 6 in distroless. Every package is code that can have a vulnerability and a tool that an intruder can use. The counts of vulnerabilities do change. A scan is a match between the packages in an image and what the database knows today, so an image that passed last week can fail today without a single byte changing. Rescan images in the registry and images that are running on a schedule, not only at build time.
Read two more signals. "With a fix" counts vulnerabilities for which a fixed package version exists; those you can act on by rebuilding. And the warning says Alpine 3.20 has reached its end of support, so new vulnerabilities in it will not get fixed packages at all. Moving to a supported base, such as a newer Alpine release or distroless, removes more risk than any single patch.
07. Step 6: Sign the SBOM and detect tampering
An SBOM is a machine-readable list of the components in an image. Trivy writes one in the CycloneDX format. Cosign, from the Sigstore project, signs it here with a key pair on your disk. The empty signing configuration tells Cosign not to upload anything to the public transparency log, which suits a private lab key; for the same reason verification uses --insecure-ignore-tlog. In production you would sign the image itself with cosign sign in CI, usually keyless (tied to the CI identity) and recorded in the transparency log.
export TRIVY_CACHE_DIR=$PWD/cache COSIGN_PASSWORD=lab-only-password
bin/trivy image -q --format cyclonedx -o sbom.cdx.json --image-src docker alpine:3.20
bin/cosign generate-key-pair
bin/cosign signing-config create --out offline-signing.json
bin/cosign sign-blob --key cosign.key --signing-config offline-signing.json \
--bundle sbom.bundle.json sbom.cdx.json
bin/cosign verify-blob --key cosign.pub --insecure-ignore-tlog \
--bundle sbom.bundle.json sbom.cdx.json 2>&1 | fold -s -w 80Private key written to cosign.key
Public key written to cosign.pub
Using payload from: sbom.cdx.json
Signing artifact...
Wrote bundle to file sbom.bundle.json
WARNING: Skipping tlog verification is an insecure practice that lacks
transparency and auditability verification for the blob.
Verified OKNow pretend that someone edits the SBOM to claim that the vulnerable musl package is already patched, and verify again.
sed -i 's/"1.2.5-r3"/"1.2.5-r4"/g' sbom.cdx.json # pretend musl is patched
bin/cosign verify-blob --key cosign.pub --insecure-ignore-tlog \
--bundle sbom.bundle.json sbom.cdx.json 2>&1 | fold -s -w 80
echo "exit code ${PIPESTATUS[0]}"WARNING: Skipping tlog verification is an insecure practice that lacks
transparency and auditability verification for the blob.
Error: failed to verify signature: could not verify message: invalid signature
when validating ASN.1 encoded signature
error during command execution: failed to verify signature: could not verify
message: invalid signature when validating ASN.1 encoded signature
exit code 1The signature covers the exact bytes of the file, so any change, even one character, makes verification fail with a non-zero exit code. A signature tells you who produced an artefact and that it has not changed since. It does not tell you that the artefact is safe; that is the job of the scan. The lesson Admission Control for Trusted Workloads uses the same idea at admission, where the cluster refuses images that are not from your registry or not pinned by digest, and explains how signature checks are added.
08. Check your understanding
09. Apply it
Move towards the skill project:
- Take the application image you used in Kubernetes Fundamentals and rewrite its Dockerfile with a pinned build stage, a minimal non-root runtime stage and digests. Agree a threshold with yourself, for example no HIGH or CRITICAL finding that has a fix, and make
trivy imageandtrivy configenforce it with--exit-code 1. - Generate its SBOM and sign it as in step 6, then write down where the public key would live so that the cluster can verify it.
- Schedule a rescan of the same image digest every day for a week and note when the result changes.
10. Review prompt
Without looking back:
- What does each stage of the hardened Dockerfile contribute, and why is the binary built with
CGO_ENABLED=0? - Which four Docker flags from step 3 map to which
securityContextfields? - Why can the same image digest have more vulnerabilities next month than today?
- What does a valid signature on an SBOM prove, and what does it not prove?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.