Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

Hardening a container image

After this lesson: I can build a container image that runs as a normal user and holds no secrets.

70 min lesson13 commandsKubernetes lab: a one-node k3s cluster for each student on a private Ubuntu VM

A quick check that you are not a bot, then your own lab opens on the interactive lesson.

Already have an account? Sign in

A key deleted, and still shipped

A developer copies the shop's payment key into an image to test it. Then they add a step that deletes it, and push the image.

Anyone who can pull that image can still read the key. Deleting a file in a later step does not take it out of the image.

The one rule

Warning

Everything in this module happens in the cluster of your own lab. Testing a cluster you do not own needs the owner's written permission. In the UK, without it, it can break the Computer Misuse Act 1990.

Quick check: the rule

Have a go

Quick check: the rule

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

By the end of this lesson

Note

I can build a container image that runs as a normal user and holds no secrets.

Key words

WordWhat it meansExample
Imagethe files and settings a container starts from
Layerone archive of files an image stacks on the last
Base imagethe image yours starts from
Whiteouta marker file that hides a file from lower layers.wh..env
Non-root usera user number that is not 010001
Image scana check of what an image holds

The cells students fill in are left blank in this preview.

Starter

Have a go

Starter

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

An image is layers and a config

An image is a stack of layers. Each layer is a tar archive of the files one build step added. A small JSON config says which user starts the program and what it runs.

A later layer cannot remove bytes from an earlier one. To delete a file it adds a whiteout, a marker named .wh. and the file's name. The file is hidden, but it is still there.

Try it: three layers

Code: python
layers = [
    ["bin/sh", "bin/httpd", "etc/passwd"],
    ["www/index.html", "app/.env"],
    ["app/.wh..env"],
]
for number, layer in enumerate(layers, start=1):
    for path in layer:
        print("layer", number, "holds", path)
# The third layer deletes app/.env. Which layer still holds it?

Make a free account to save your work and track your progress.

Check

Have a go

Check

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Your lab builds images by hand

Your lab has no Docker. Its container runtime, containerd, can import and export images but not build them. So you build one the way a builder does, with a short Python script.

The lab has no image scanner either. Trivy and Grype need installing and a vulnerability database from the internet. You write an offline check instead.

Export the lab's busybox image

Command
mkdir -p ~/ch && cd ~/ch && sudo k3s ctr images export busybox.tar docker.io/library/busybox:1.37.0 && sudo chown student busybox.tar && tar -tf busybox.tar

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the image builder, part 1

Command
mkdir -p ~/ch && printf '%s\n' 'import gzip' 'import hashlib' 'import io' 'import json' 'import os' 'import platform' 'import sys' 'import tarfile' '' 'ARCH = {"x86_64": "amd64", "aarch64": "arm64"}[platform.machine()]' 'LAYER = "application/vnd.oci.image.layer.v1.tar"' '' '' 'def read_json(archive, digest):' '    return json.load(archive.extractfile("blobs/sha256/" + digest.split(":")[1]))' '' '' 'def unpack(path, folder):' '    archive = tarfile.open(path)' '    index = json.load(archive.extractfile("index.json"))' '    inner = read_json(archive, index["manifests"][0]["digest"])' '    mine = [m for m in inner["manifests"] if m["platform"]["architecture"] == ARCH][0]' '    for layer in read_json(archive, mine["digest"])["layers"]:' '        data = archive.extractfile("blobs/sha256/" + layer["digest"].split(":")[1]).read()' '        tarfile.open(fileobj=io.BytesIO(gzip.decompress(data))).extractall(folder, filter="tar")' '    print("unpacked", ARCH, "into", folder)' '' '' > ~/ch/oci.py

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the image builder, part 2

Command
printf '%s\n' 'def reset(info):' '    info.uid = info.gid = 0' '    info.uname = info.gname = ""' '    info.mtime = 0' '    return info' '' '' 'def tar_folder(folder):' '    out = io.BytesIO()' '    with tarfile.open(fileobj=out, mode="w", format=tarfile.PAX_FORMAT) as layer:' '        for root, dirs, files in os.walk(folder):' '            dirs.sort()' '            for name in sorted(dirs) + sorted(files):' '                full = os.path.join(root, name)' '                layer.add(full, os.path.relpath(full, folder), recursive=False, filter=reset)' '    return out.getvalue()' '' '' 'def build(name, user, command, folders):' '    blobs = {}' '' '    def add(data, media):' '        digest = "sha256:" + hashlib.sha256(data).hexdigest()' '        blobs[digest] = data' '        return {"mediaType": media, "digest": digest, "size": len(data)}' '' '    layers = [add(tar_folder(f), LAYER) for f in folders]' '    config = {"architecture": ARCH, "os": "linux",' >> ~/ch/oci.py

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the image builder, part 3

Command
printf '%s\n' '              "config": {"User": user, "Cmd": command.split(), "WorkingDir": "/"},' '              "rootfs": {"type": "layers", "diff_ids": [x["digest"] for x in layers]},' '              "history": [{"created_by": "folder " + f} for f in folders]}' '    manifest = {"schemaVersion": 2, "mediaType": "application/vnd.oci.image.manifest.v1+json",' '                "config": add(json.dumps(config).encode(), "application/vnd.oci.image.config.v1+json"),' '                "layers": layers}' '    top = add(json.dumps(manifest).encode(), manifest["mediaType"])' '    top["annotations"] = {"io.containerd.image.name": "docker.io/" + name}' '    files = {"oci-layout": json.dumps({"imageLayoutVersion": "1.0.0"}).encode(),' '             "index.json": json.dumps({"schemaVersion": 2, "manifests": [top]}).encode()}' '    for digest, data in blobs.items():' '        files["blobs/sha256/" + digest.split(":")[1]] = data' >> ~/ch/oci.py

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the image builder, part 4

Command
printf '%s\n' '    out = name.split("/")[-1].replace(":", "-") + ".tar"' '    with tarfile.open(out, "w") as image:' '        for path, data in files.items():' '            info = tarfile.TarInfo(path)' '            info.size = len(data)' '            image.addfile(info, io.BytesIO(data))' '    print(out, len(layers), "layers", sum(x["size"] for x in layers) // 1024, "KiB")' '' '' 'if sys.argv[1] == "unpack":' '    unpack(sys.argv[2], sys.argv[3])' 'else:' '    build(sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5:])' >> ~/ch/oci.py

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Build the first image, with a deleted key

Command
cd ~/ch && rm -rf base app clean && python3 oci.py unpack busybox.tar base && mkdir -p app/www app/app clean/app && echo "<h1>Tuck shop</h1>" > app/www/index.html && echo PAYMENT_KEY=tuck_live_7d3f9a2c > app/app/.env && touch clean/app/.wh..env && python3 oci.py build lab/shop:fat 0 "httpd -f -p 8080 -h /www" base app clean

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the image check, part 1

Command
mkdir -p ~/ch && printf '%s\n' 'import io' 'import json' 'import sys' 'import tarfile' '' 'WORDS = ["KEY", "TOKEN", "PASSWORD", "SECRET"]' 'NAMES = [".env", "id_rsa", ".pem", "credentials"]' 'SHELLS = ["bin/sh", "bin/bash", "bin/busybox"]' '' '' 'def secret_lines(data):' '    found = []' '    if bytes(1) in data:' '        return found' '    for line in data.decode(errors="replace").splitlines():' '        name = line.split("=")[0].upper()' '        if "=" in line and any(word in name for word in WORDS):' '            found.append(name)' '    return found' '' '' 'archive = tarfile.open(sys.argv[1])' 'index = json.load(archive.extractfile("index.json"))' 'blob = lambda d: archive.extractfile("blobs/sha256/" + d.split(":")[1])' 'manifest = json.load(blob(index["manifests"][0]["digest"]))' 'config = json.load(blob(manifest["config"]["digest"]))["config"]' 'problems = 0' 'user = config.get("User") or "root"' 'if user in ["root", "0", "0:0"]:' > ~/ch/imgscan.py

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the image check, part 2

Command
printf '%s\n' '    print("FAIL config: runs as root (no USER)")' '    problems = problems + 1' 'else:' '    print("ok   config: runs as user", user)' 'for number, layer in enumerate(manifest["layers"], start=1):' '    files = tarfile.open(fileobj=io.BytesIO(blob(layer["digest"]).read()))' '    names = files.getnames()' '    print("     layer", number, ":", len(names), "entries,", layer["size"] // 1024, "KiB")' '    for item in files.getmembers():' '        base = item.name.split("/")[-1]' '        if base.startswith(".wh."):' '            hidden = item.name[: len(item.name) - len(base)] + base[4:]' '            print("     layer", number, ": deletes", hidden, "but an earlier layer still holds it")' '            continue' '        if item.mode & 0o6000:' '            print("FAIL layer", number, ":", item.name, "is setuid or setgid")' '            problems = problems + 1' '        keys = secret_lines(files.extractfile(item).read()) if item.isreg() else []' >> ~/ch/imgscan.py

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the image check, part 3

Command
printf '%s\n' '        if keys or any(base.endswith(n) for n in NAMES):' '            print("FAIL layer", number, ":", item.name, "looks like a secret", " ".join(keys))' '            problems = problems + 1' '    for name in names:' '        if name in SHELLS:' '            print("warn layer", number, ": has a shell,", name)' 'print(problems, "problems in", sys.argv[1])' >> ~/ch/imgscan.py

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Check the first image, then read the key

Command
cd ~/ch && python3 imgscan.py shop-fat.tar && mkdir -p fatx && tar -xf shop-fat.tar -C fatx && for l in fatx/blobs/sha256/*; do tar -xOf $l app/.env 2>/dev/null; done

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

A common mistake

Warning

Many people think a file deleted in a later step is gone from the image. It is only hidden, and anyone who pulls the image can unpack the earlier layer. Keep secrets out of every layer, and give them to the container when it runs.

Check

Have a go

Check

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Only what the program needs, as user 10001

The shop needs one program and its web page. So the slim image is one layer: busybox, the C library it loads, and the page. It has no key and no shell commands linked in.

Its config says user 10001. The number has no account behind it, and that is fine: the kernel only checks numbers.

Build and check the slim image

Command
cd ~/ch && rm -rf slim && mkdir -p slim/bin slim/www && cp base/bin/busybox slim/bin/ && cp -a base/lib base/lib64 slim/ && cp app/www/index.html slim/www/ && python3 oci.py build lab/shop:slim 10001:10001 "/bin/busybox httpd -f -p 8080 -h /www" slim && python3 imgscan.py shop-slim.tar

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Import both images and run them

Command
cd ~/ch && sudo k3s ctr images import shop-fat.tar && sudo k3s ctr images import shop-slim.tar && kubectl create namespace images; kubectl run fat -n images --image=lab/shop:fat --image-pull-policy=Never; kubectl run slim -n images --image=lab/shop:slim --image-pull-policy=Never; kubectl wait -n images --for=condition=Ready pod/fat pod/slim --timeout=120s

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Who runs, and is there a shell?

Command
kubectl exec -n images fat -- id; kubectl exec -n images fat -- ls -a /app; kubectl exec -n images slim -- /bin/busybox id; kubectl exec -n images slim -- sh -c id

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Check every image before it ships

Run a check like imgscan.py on every image a build makes, and fail the build on any problem. Add a vulnerability scanner such as Trivy where the build can reach its database.

Then the cluster can refuse what slips through: lesson 4 makes it refuse pods that run as root.

Assignment: check an image

Write three checks an image scanner makes.

runs_as_root(config) is True when the image starts as root: no User, "root", "0", or a user starting "0:" or "root:". secret_names(text) gives the names before = of lines whose name holds KEY, TOKEN, PASSWORD or SECRET, in capitals. left_behind(layers) gives, sorted, every path an earlier layer added and a later layer deleted with a .wh. file.

Code: python
def runs_as_root(config):
    # True when the image starts as root: no User, "root", "0", or a user "0:..." or "root:...".
    return False


def secret_names(text):
    # The names (before "=") of lines whose name holds KEY, TOKEN, PASSWORD or SECRET.
    # Names in capitals, in the order they appear.
    return []


def left_behind(layers):
    # layers: a list of layers, each a list of file paths.
    # A file named ".wh.NAME" deletes NAME in the same folder from the image.
    # Sorted: every path an earlier layer added and a later layer deleted.
    return []

Make a free account to save your work and track your progress.

Exit quiz

Have a go

Exit quiz

5 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Teaching a class? Set this module for your students with a teacher guide, marked assignments and a lab for every student.