Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 6 · Lab · 25 min · revision 2

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

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.

Folder layout at the end of the lab
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.

Terminal · in a new folder image-lab/
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 GitVersion
Expected output
trivy_0.76.2_Linux-64bit.tar.gz: OK
bin/cosign: OK
Version: 0.76.2
GitVersion:    v3.1.4

03. 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/.

app/go.mod
module example.com/selfcheck

go 1.26
Go · app/main.go
// 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"))
}
Dockerfile · app/Dockerfile.naive
FROM golang:latest
WORKDIR /src
COPY . .
RUN apt-get update && apt-get install -y curl
RUN go build -o /selfcheck .
CMD ["/selfcheck"]
Dockerfile · app/Dockerfile
# 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.

Terminal · not run when this lesson was tested (no image builds on the test host)
docker build -t selfcheck:naive -f app/Dockerfile.naive app
docker build -t selfcheck:hardened app
docker images selfcheck

04. 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.

Terminal
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,4
Expected output
ELF 64-bit LSB executable, statically linked
Terminal
echo "== 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
Expected output
== 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: ok

The 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:65532 is runAsUser: 65532 with runAsNonRoot: true;
  • --cap-drop ALL is capabilities: {drop: ["ALL"]};
  • --security-opt no-new-privileges is allowPrivilegeEscalation: false;
  • --read-only with --tmpfs /tmp is readOnlyRootFilesystem: true with an emptyDir volume 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.

Go template · misconfig.tpl
{{- range . }}{{ $t := .Target }}{{ range .Misconfigurations -}}
{{ $t }}  {{ .ID }}  {{ .Severity }}  {{ .Title }}
{{ end }}{{ end -}}
Terminal
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 $?"
done
Expected output
Dockerfile  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 0

The 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.

Python · summarise.py
"""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}")
Terminal
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.json
Illustrative output (vulnerability counts change with the database date; run on 16 Nov 2026)
alpine: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: 0
Terminal
export 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'
Expected output
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.

Terminal
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 80
Expected output
Private 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 OK

Now pretend that someone edits the SBOM to claim that the vulnerable musl package is already patched, and verify again.

Terminal
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]}"
Expected output
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 1

The 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

Practice check · 3 questions

Images, scans and signatures

Three questions about the lab.

Q1. A teammate changes the final stage of the hardened Dockerfile to `FROM gcr.io/distroless/static-debian13:latest`, without a digest. What does the CI gate from step 4 do?
Q2. After you add `--read-only`, a service stops at start-up with `open /var/cache/app/index: read-only file system`. What is the best fix?
Q3. You pretty-print `sbom.cdx.json` with `python3 -m json.tool`, changing no value, and run the verify command from step 6 again. What happens?
Practice only: not graded, not saved, not evidence.

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 image and trivy config enforce 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:

  1. What does each stage of the hardened Dockerfile contribute, and why is the binary built with CGO_ENABLED=0?
  2. Which four Docker flags from step 3 map to which securityContext fields?
  3. Why can the same image digest have more vulnerabilities next month than today?
  4. 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.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check