Find the secret in a layer that was deleted
Task
Build an image that copies in a credential and deletes it in a later step, then recover the credential from the finished image. This is the single most useful thing to prove to yourself about image layers, and reading it in a lesson is not the same as extracting the file.
Steps
- Create
lab/img/secret.txtcontaining the literal stringNOT-A-REAL-CREDENTIAL-lab-only. - Write a build file that copies
secret.txtinto the image in one instruction and deletes it in the next. Build it and tag itlayerdemo:v1. - Run a container from it and confirm the file is absent from the filesystem view.
- Export the image to a tar archive (
docker saveorpodman save) and unpack it. Search each LAYER for the file rather than the bytes for the string:for l in $(find . -type f); do tar -tf "$l" 2>/dev/null | grep -q secret.txt && echo "$l"; done, thentar -xOfthat layer to print the file. Layers may be stored compressed, so a plain grep across the files can miss a string that is there -- GNU tar reads them either way. Record which layer holds it inlab/layers.txt, and look at the layer the delete made: it holds only a whiteout entry,.wh.secret.txt. - Rebuild using a multi-stage build so the credential is never in the final image, export it again, and confirm the string is absent. Record both results.
Verify
grep -c 'NOT-A-REAL-CREDENTIAL' lab/layers.txt
grep -Eci 'multi-?stage' lab/layers.txt
grep -Eci 'absent|not found|zero' lab/layers.txt
lab/layers.txt must record finding the string in v1 and not finding it after the multi-stage rebuild. If both builds hide it, the first build did not actually copy the file in a separate layer.
Notes
The string is deliberately self-describing so that if this file ever escapes the lab it is obviously not a credential.
This is an independent study companion for CompTIA Cloud+ CV0-004 and is not produced by or endorsed by CompTIA.