Docker image and runtime hardening lab
Runs an insecure and a hardened configuration of the same small service, measures the difference from inside the containers, and exercises a static policy gate, a derived seccomp profile, image scanning, SBOM generation and local-only signing.
Cloud Security 18 min read
Implementation
labs/docker-security/hardened/compose.yaml
1# HARDENED counterpart for labs/docker-security.
2name: dockerlab-hardened
3
4services:
5 app:
6 build:
7 context: ../app
8 dockerfile: ../hardened/Dockerfile
9 image: dockerlab/posture:hardened
10 user: "65532:65532"
11 read_only: true
12 tmpfs:
13 - /tmp:rw,noexec,nosuid,nodev,size=8m,mode=1777
14 cap_drop:
15 - ALL
16 security_opt:
17 - no-new-privileges:true
18 - seccomp=./seccomp.json
19 mem_limit: 128m
20 memswap_limit: 128m
21 cpus: 0.5
22 pids_limit: 64
23 # healthcheck is inherited from the image's HEALTHCHECK instruction.
24 restart: "no"
25 stop_grace_period: 5s
26 networks:
27 - isolated
28
29 # Present so the probe can show that the isolated app cannot reach it. It gets
30 # the same container-level hardening so the static policy gate covers it too.
31 canary:
32 image: busybox:1.37@sha256:a7dbc319b1438115a207e11930dc4bb3e643dcb3ec0bdd694bb36cd8fad289ec
33 command: ["httpd", "-f", "-p", "9000", "-h", "/www"]
34 user: "65534:65534"
35 read_only: true
36 tmpfs:
37 - /www:rw,noexec,nosuid,nodev,size=1m,mode=1777
38 cap_drop:
39 - ALL
40 security_opt:
41 - no-new-privileges:true
42 mem_limit: 32m
43 memswap_limit: 32m
44 cpus: 0.25
45 pids_limit: 16
46 restart: "no"
47 networks:
48 - reachable
49
50networks:
51 isolated:
52 internal: true
53 reachable: {}
1{
2 "comment": "Generated by scripts/gen-seccomp.sh from strace observations of the shipped binary. Default action is ERRNO (EPERM), not KILL, so a missed syscall degrades visibly instead of killing PID 1.",
3 "defaultAction": "SCMP_ACT_ERRNO",
4 "defaultErrnoRet": 1,
5 "archMap": [
6 {
7 "architecture": "SCMP_ARCH_X86_64",
8 "subArchitectures": [
9 "SCMP_ARCH_X86",
10 "SCMP_ARCH_X32"
11 ]
12 }
13 ],
14 "syscalls": [
15 {
16 "names": [
17 "accept4",
18 "arch_prctl",
19 "bind",
20 "close",
21 "connect",
22 "epoll_create1",
23 "epoll_ctl",
24 "epoll_pwait",
25 "eventfd2",
26 "execve",
27 "exit_group",
28 "fcntl",
29 "fstat",
30 "futex",
31 "getdents64",
32 "getgid",
33 "getpeername",
34 "getpid",
35 "getsockname",
36 "getsockopt",
37 "gettid",
38 "getuid",
39 "listen",
40 "madvise",
41 "mmap",
42 "nanosleep",
43 "openat",
44 "pread64",
45 "prlimit64",
46 "read",
47 "rt_sigaction",
48 "rt_sigprocmask",
49 "rt_sigreturn",
50 "sched_getaffinity",
51 "sched_yield",
52 "setsockopt",
53 "sigaltstack",
54 "socket",
55 "tgkill",
56 "uname",
57 "write"
58 ],
59 "action": "SCMP_ACT_ALLOW"
60 },
61 {
62 "names": [
63 "fstatfs",
64 "statfs",
65 "statx"
66 ],
67 "action": "SCMP_ACT_ALLOW"
68 },
69 {
70 "names": [
71 "dup3",
72 "mkdirat",
73 "newfstatat",
74 "pidfd_open",
75 "pidfd_send_signal",
76 "pipe2",
77 "readlinkat",
78 "unlinkat",
79 "waitid"
80 ],
81 "action": "SCMP_ACT_ALLOW"
82 },
83 {
84 "names": [
85 "clone"
86 ],
87 "action": "SCMP_ACT_ALLOW",
88 "args": [
89 {
90 "index": 0,
91 "value": 2114060288,
92 "valueTwo": 0,
93 "op": "SCMP_CMP_MASKED_EQ"
94 }
95 ]
96 },
97 {
98 "names": [
99 "clone3"
100 ],
101 "action": "SCMP_ACT_ERRNO",
102 "errnoRet": 38
103 }
104 ]
105}
1// Command posture is the workload for labs/docker-security.
2//
3// It is a deliberately tiny HTTP service plus a set of bounded, benign
4// "can I do X?" probes. The probes exist so the lab can OBSERVE container
5// runtime posture from inside a running container instead of inferring it from
6// configuration files. Every probe either succeeds or reports the errno the
7// kernel returned; none of them tries to escape the container, modify the host
8// outside an explicitly mounted lab canary directory, or persist anything.
9//
10// Subcommands:
11//
12// serve (default) HTTP server on :8080 with /healthz and a passive /posture
13// probe print passive posture plus active probe results as JSON
14// healthcheck GET /healthz on loopback; exit 0 on 200, 1 otherwise
15// sleep <seconds> sleep, then exit (child process for forktest)
16// forktest <n> start up to n sleeping children; report where the kernel said no
17// memtest <MiB> touch MiB of memory in 1 MiB steps (OOM-kill target)
18// k8sprobe in-cluster identity and authorization probe (labs/kubernetes-security)
19// tcpcheck host:port one TCP connect attempt, reported as JSON (labs/kubernetes-security)
20//
21// Only the Go standard library is used so the image has no module download step.
22package main
23
24import (
25 "bufio"
26 "bytes"
27 "context"
28 "crypto/tls"
29 "crypto/x509"
30 "encoding/base64"
31 "encoding/json"
32 "errors"
33 "fmt"
34 "io"
35 "net"
36 "net/http"
37 "os"
38 "os/exec"
39 "os/signal"
40 "runtime"
41 "strconv"
42 "strings"
43 "syscall"
44 "time"
45)
46
47// capNames maps capability bit numbers to names (capabilities(7)).
48var capNames = []string{
49 "CHOWN", "DAC_OVERRIDE", "DAC_READ_SEARCH", "FOWNER", "FSETID", "KILL",
50 "SETGID", "SETUID", "SETPCAP", "LINUX_IMMUTABLE", "NET_BIND_SERVICE",
51 "NET_BROADCAST", "NET_ADMIN", "NET_RAW", "IPC_LOCK", "IPC_OWNER",
52 "SYS_MODULE", "SYS_RAWIO", "SYS_CHROOT", "SYS_PTRACE", "SYS_PACCT",
53 "SYS_ADMIN", "SYS_BOOT", "SYS_NICE", "SYS_RESOURCE", "SYS_TIME",
54 "SYS_TTY_CONFIG", "MKNOD", "LEASE", "AUDIT_WRITE", "AUDIT_CONTROL",
55 "SETFCAP", "MAC_OVERRIDE", "MAC_ADMIN", "SYSLOG", "WAKE_ALARM",
56 "BLOCK_SUSPEND", "AUDIT_READ", "PERFMON", "BPF", "CHECKPOINT_RESTORE",
57}
58
59// Posture is the passive view: values read from procfs and cgroupfs only.
60type Posture struct {
61 UID int `json:"uid"`
62 GID int `json:"gid"`
63 CapEffHex string `json:"cap_eff_hex"`
64 CapEff []string `json:"cap_eff"`
65 CapBndHex string `json:"cap_bnd_hex"`
66 NoNewPrivs string `json:"no_new_privs"`
67 SeccompMode string `json:"seccomp_mode"`
68 SeccompFilters string `json:"seccomp_filters"`
69 RootReadOnly bool `json:"root_fs_mounted_read_only"`
70 MemoryLimit string `json:"memory_limit"`
71 PidsLimit string `json:"pids_limit"`
72 CPUQuota string `json:"cpu_quota"`
73 PID1Comm string `json:"pid1_comm"`
74 VisibleProcs int `json:"visible_process_count"`
75 GoVersion string `json:"go_version"`
76}
77
78// ProbeResult is one active probe outcome.
79type ProbeResult struct {
80 Name string `json:"name"`
81 Allowed bool `json:"allowed"`
82 Errno string `json:"errno,omitempty"`
83 Detail string `json:"detail,omitempty"`
84}
85
86// Report is the full `probe` output.
87type Report struct {
88 Posture Posture `json:"posture"`
89 Probes []ProbeResult `json:"probes"`
90}
91
92func main() {
93 cmd := "serve"
94 if len(os.Args) > 1 {
95 cmd = os.Args[1]
96 }
97 switch cmd {
98 case "serve":
99 os.Exit(serve())
100 case "probe":
101 os.Exit(probe())
102 case "healthcheck":
103 os.Exit(healthcheck())
104 case "sleep":
105 secs, _ := strconv.Atoi(arg(2, "1"))
106 time.Sleep(time.Duration(secs) * time.Second)
107 case "forktest":
108 n, _ := strconv.Atoi(arg(2, "10"))
109 os.Exit(forktest(n))
110 case "memtest":
111 mib, _ := strconv.Atoi(arg(2, "16"))
112 os.Exit(memtest(mib))
113 case "k8sprobe":
114 os.Exit(k8sprobe())
115 case "tcpcheck":
116 os.Exit(tcpcheck(arg(2, "")))
117 default:
118 fmt.Fprintf(os.Stderr, "unknown subcommand %q\n", cmd)
119 os.Exit(2)
120 }
121}
122
123func arg(i int, def string) string {
124 if len(os.Args) > i {
125 return os.Args[i]
126 }
127 return def
128}
129
130// listenAddr lets the lab run the service on a different port when 8080 is taken
131// (for example while tracing on the host). Default matches the image's EXPOSE.
132func listenAddr() string {
133 if v := os.Getenv("LISTEN_ADDR"); v != "" {
134 return v
135 }
136 return ":8080"
137}
138
139func serve() int {
140 mux := http.NewServeMux()
141 mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
142 if r.Method != http.MethodGet {
143 http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
144 return
145 }
146 w.Header().Set("Content-Type", "text/plain; charset=utf-8")
147 _, _ = io.WriteString(w, "ok\n")
148 })
149 mux.HandleFunc("/posture", func(w http.ResponseWriter, r *http.Request) {
150 if r.Method != http.MethodGet {
151 http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
152 return
153 }
154 w.Header().Set("Content-Type", "application/json")
155 _ = json.NewEncoder(w).Encode(passivePosture())
156 })
157 srv := &http.Server{
158 Addr: listenAddr(),
159 Handler: mux,
160 ReadHeaderTimeout: 5 * time.Second,
161 ReadTimeout: 10 * time.Second,
162 WriteTimeout: 10 * time.Second,
163 IdleTimeout: 30 * time.Second,
164 MaxHeaderBytes: 8 << 10,
165 }
166 stop := make(chan os.Signal, 1)
167 signal.Notify(stop, syscall.SIGTERM, syscall.SIGINT)
168 errc := make(chan error, 1)
169 go func() { errc <- srv.ListenAndServe() }()
170 select {
171 case err := <-errc:
172 fmt.Fprintln(os.Stderr, "server error:", err)
173 return 1
174 case <-stop:
175 ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
176 defer cancel()
177 _ = srv.Shutdown(ctx)
178 return 0
179 }
180}
181
182func healthcheck() int {
183 client := &http.Client{Timeout: 2 * time.Second}
184 _, port, err := net.SplitHostPort(listenAddr())
185 if err != nil {
186 return 1
187 }
188 resp, err := client.Get("http://127.0.0.1:" + port + "/healthz")
189 if err != nil {
190 return 1
191 }
192 defer resp.Body.Close()
193 if resp.StatusCode != http.StatusOK {
194 return 1
195 }
196 return 0
197}
198
199// statusFields parses "Key:\tvalue" lines of /proc/self/status.
200func statusFields() map[string]string {
201 fields := map[string]string{}
202 f, err := os.Open("/proc/self/status")
203 if err != nil {
204 return fields
205 }
206 defer f.Close()
207 sc := bufio.NewScanner(f)
208 for sc.Scan() {
209 k, v, ok := strings.Cut(sc.Text(), ":")
210 if ok {
211 fields[k] = strings.TrimSpace(v)
212 }
213 }
214 return fields
215}
216
217func decodeCaps(hex string) []string {
218 v, err := strconv.ParseUint(hex, 16, 64)
219 if err != nil {
220 return []string{"<unparsable>"}
221 }
222 names := []string{}
223 for bit := 0; bit < 64; bit++ {
224 if v&(1<<uint(bit)) == 0 {
225 continue
226 }
227 if bit < len(capNames) {
228 names = append(names, capNames[bit])
229 } else {
230 names = append(names, "CAP_"+strconv.Itoa(bit))
231 }
232 }
233 return names
234}
235
236func readTrim(path string) string {
237 b, err := os.ReadFile(path)
238 if err != nil {
239 return "unavailable"
240 }
241 return strings.TrimSpace(string(b))
242}
243
244// firstReadable returns the first readable file's trimmed content so the same
245// binary reports cgroup v1 and v2 hosts. The first matching path is included
246// so a reader can tell which hierarchy answered.
247func firstReadable(paths ...string) string {
248 for _, p := range paths {
249 if b, err := os.ReadFile(p); err == nil {
250 return strings.TrimSpace(string(b)) + " (" + p + ")"
251 }
252 }
253 return "unavailable"
254}
255
256func rootReadOnly() bool {
257 f, err := os.Open("/proc/self/mountinfo")
258 if err != nil {
259 return false
260 }
261 defer f.Close()
262 sc := bufio.NewScanner(f)
263 for sc.Scan() {
264 parts := strings.Fields(sc.Text())
265 // mountinfo: id parent major:minor root mountpoint options ...
266 if len(parts) > 5 && parts[4] == "/" {
267 for _, opt := range strings.Split(parts[5], ",") {
268 if opt == "ro" {
269 return true
270 }
271 }
272 return false
273 }
274 }
275 return false
276}
277
278func visibleProcs() int {
279 entries, err := os.ReadDir("/proc")
280 if err != nil {
281 return -1
282 }
283 n := 0
284 for _, e := range entries {
285 if _, err := strconv.Atoi(e.Name()); err == nil {
286 n++
287 }
288 }
289 return n
290}
291
292func passivePosture() Posture {
293 st := statusFields()
294 capEff := strings.TrimSpace(st["CapEff"])
295 return Posture{
296 UID: os.Getuid(),
297 GID: os.Getgid(),
298 CapEffHex: capEff,
299 CapEff: decodeCaps(capEff),
300 CapBndHex: strings.TrimSpace(st["CapBnd"]),
301 NoNewPrivs: st["NoNewPrivs"],
302 SeccompMode: st["Seccomp"],
303 SeccompFilters: st["Seccomp_filters"],
304 RootReadOnly: rootReadOnly(),
305 MemoryLimit: firstReadable(
306 "/sys/fs/cgroup/memory.max",
307 "/sys/fs/cgroup/memory/memory.limit_in_bytes"),
308 PidsLimit: firstReadable(
309 "/sys/fs/cgroup/pids.max",
310 "/sys/fs/cgroup/pids/pids.max"),
311 CPUQuota: firstReadable(
312 "/sys/fs/cgroup/cpu.max",
313 "/sys/fs/cgroup/cpu/cpu.cfs_quota_us"),
314 PID1Comm: readTrim("/proc/1/comm"),
315 VisibleProcs: visibleProcs(),
316 GoVersion: runtime.Version(),
317 }
318}
319
320func errnoName(err error) string {
321 var e syscall.Errno
322 if errors.As(err, &e) {
323 switch e {
324 case syscall.EPERM:
325 return "EPERM"
326 case syscall.EACCES:
327 return "EACCES"
328 case syscall.EROFS:
329 return "EROFS"
330 case syscall.ENOENT:
331 return "ENOENT"
332 case syscall.EAGAIN:
333 return "EAGAIN"
334 case syscall.EINVAL:
335 return "EINVAL"
336 case syscall.ECONNREFUSED:
337 return "ECONNREFUSED"
338 }
339 return "errno_" + strconv.Itoa(int(e))
340 }
341 return "error"
342}
343
344func result(name string, err error, detail string) ProbeResult {
345 if err == nil {
346 return ProbeResult{Name: name, Allowed: true, Detail: detail}
347 }
348 return ProbeResult{Name: name, Allowed: false, Errno: errnoName(err), Detail: detail}
349}
350
351func runProbes() []ProbeResult {
352 var out []ProbeResult
353
354 // 1. Can the process write to the image filesystem?
355 {
356 path := "/probe-rootfs"
357 f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_EXCL, 0o600)
358 if err == nil {
359 f.Close()
360 _ = os.Remove(path)
361 }
362 out = append(out, result("write_root_filesystem", err, ""))
363 }
364
365 // 2. Is there a writable scratch area at all (a hardened image must still work)?
366 tmp := "/tmp/probe-tmp"
367 {
368 f, err := os.OpenFile(tmp, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o600)
369 if err == nil {
370 f.Close()
371 }
372 out = append(out, result("write_tmp_scratch", err, ""))
373 }
374
375 // 3. CAP_CHOWN: hand a file to an unrelated uid.
376 out = append(out, result("chown_to_other_uid (CAP_CHOWN)", os.Chown(tmp, 12345, 12345), ""))
377 _ = os.Remove(tmp)
378
379 // 4. CAP_MKNOD: create a character device node (1,3 is the /dev/null number).
380 {
381 path := "/tmp/probe-null"
382 err := syscall.Mknod(path, syscall.S_IFCHR|0o600, 1<<8|3)
383 if err == nil {
384 _ = os.Remove(path)
385 }
386 out = append(out, result("mknod_char_device (CAP_MKNOD)", err, ""))
387 }
388
389 // 5. CAP_NET_RAW: open a raw ICMP socket.
390 {
391 fd, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_RAW, syscall.IPPROTO_ICMP)
392 if err == nil {
393 _ = syscall.Close(fd)
394 }
395 out = append(out, result("raw_socket (CAP_NET_RAW)", err, ""))
396 }
397
398 // 6. CAP_SYS_ADMIN: mount a tmpfs inside the container's mount namespace.
399 {
400 dir := "/tmp/probe-mnt"
401 _ = os.MkdirAll(dir, 0o700)
402 err := syscall.Mount("tmpfs", dir, "tmpfs", 0, "size=1m")
403 if err == nil {
404 _ = syscall.Unmount(dir, 0)
405 }
406 _ = os.Remove(dir)
407 out = append(out, result("mount_tmpfs (CAP_SYS_ADMIN)", err, ""))
408 }
409
410 // 7. Seccomp-attributable: creating a user namespace needs no capability on
411 // most kernels, so a denial here points at the seccomp filter. unshare(2)
412 // cannot be used because it returns EINVAL for any multithreaded process
413 // (every Go program); clone(2) with CLONE_NEWUSER via os/exec can.
414 {
415 self, _ := os.Executable()
416 c := exec.Command(self, "sleep", "0")
417 c.SysProcAttr = &syscall.SysProcAttr{Cloneflags: syscall.CLONE_NEWUSER}
418 // errnoName unwraps *os.PathError to the underlying syscall.Errno.
419 err := c.Run()
420 out = append(out, result("clone_new_user_namespace (seccomp-attributable)", err, ""))
421 }
422
423 // 8. Is a container-runtime socket mounted, and does it answer a read-only ping?
424 {
425 const sock = "/var/run/docker.sock"
426 if _, err := os.Stat(sock); err != nil {
427 out = append(out, ProbeResult{Name: "docker_socket_present", Allowed: false, Errno: errnoName(err)})
428 } else {
429 conn, err := net.DialTimeout("unix", sock, 2*time.Second)
430 if err != nil {
431 out = append(out, result("docker_socket_reachable", err, "socket path exists"))
432 } else {
433 _ = conn.SetDeadline(time.Now().Add(2 * time.Second))
434 _, _ = io.WriteString(conn, "GET /_ping HTTP/1.0\r\n\r\n")
435 buf := make([]byte, 256)
436 n, _ := conn.Read(buf)
437 conn.Close()
438 line, _, _ := strings.Cut(string(buf[:n]), "\r\n")
439 out = append(out, ProbeResult{Name: "docker_socket_reachable", Allowed: true,
440 Detail: "GET /_ping only; status line: " + line})
441 }
442 }
443 }
444
445 // 9. Is a host-side lab canary directory mounted, and is it writable?
446 {
447 const dir = "/mnt/host-canary"
448 if _, err := os.Stat(dir); err != nil {
449 out = append(out, ProbeResult{Name: "host_canary_mounted", Allowed: false, Errno: errnoName(err)})
450 } else {
451 _, readErr := os.ReadFile(dir + "/canary.txt")
452 out = append(out, result("host_canary_read", readErr, "content not printed"))
453 w := dir + "/written-by-container.txt"
454 f, werr := os.OpenFile(w, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o600)
455 if werr == nil {
456 f.Close()
457 }
458 out = append(out, result("host_canary_write", werr, ""))
459 }
460 }
461
462 // 10. Network reachability of a lab canary service (topology, not firewalling).
463 if target := os.Getenv("PROBE_TCP_TARGET"); target != "" {
464 conn, err := net.DialTimeout("tcp", target, 2*time.Second)
465 if err == nil {
466 conn.Close()
467 }
468 detail := "target=" + target
469 var dnsErr *net.DNSError
470 if errors.As(err, &dnsErr) {
471 detail += " (name resolution failed)"
472 }
473 out = append(out, result("tcp_connect_canary", err, detail))
474 }
475
476 return out
477}
478
479func probe() int {
480 rep := Report{Posture: passivePosture(), Probes: runProbes()}
481 enc := json.NewEncoder(os.Stdout)
482 enc.SetIndent("", " ")
483 if err := enc.Encode(rep); err != nil {
484 return 1
485 }
486 return 0
487}
488
489func forktest(n int) int {
490 self, err := os.Executable()
491 if err != nil {
492 fmt.Fprintln(os.Stderr, "cannot locate self:", err)
493 return 1
494 }
495 started := 0
496 firstErr := ""
497 var kids []*exec.Cmd
498 for i := 0; i < n; i++ {
499 c := exec.Command(self, "sleep", "3")
500 if err := c.Start(); err != nil {
501 firstErr = errnoName(errors.Unwrap(err))
502 if firstErr == "error" {
503 firstErr = err.Error()
504 }
505 break
506 }
507 kids = append(kids, c)
508 started++
509 }
510 for _, c := range kids {
511 _ = c.Wait()
512 }
513 out := map[string]any{"requested": n, "started": started, "first_error": firstErr}
514 _ = json.NewEncoder(os.Stdout).Encode(out)
515 return 0
516}
517
518func memtest(mib int) int {
519 chunks := make([][]byte, 0, mib)
520 for i := 1; i <= mib; i++ {
521 b := make([]byte, 1<<20)
522 for j := 0; j < len(b); j += 4096 {
523 b[j] = 1
524 }
525 chunks = append(chunks, b)
526 if i%16 == 0 || i == mib {
527 fmt.Printf("{\"touched_mib\":%d}\n", i)
528 }
529 }
530 runtime.KeepAlive(chunks)
531 return 0
532}
533
534// ---- Kubernetes workload-identity probe ---------------------------------------
535
536// K8sCall is one API request outcome. Only the HTTP status and, for a list, the
537// number of items are recorded: never object names or contents, so running the
538// probe against an over-privileged identity does not print secret material.
539type K8sCall struct {
540 Name string `json:"name"`
541 Status int `json:"status"`
542 Items *int `json:"items,omitempty"`
543 Error string `json:"error,omitempty"`
544}
545
546// K8sReport is the full `k8sprobe` output.
547type K8sReport struct {
548 TokenMounted bool `json:"token_mounted"`
549 Namespace string `json:"namespace,omitempty"`
550 Claims map[string]interface{} `json:"token_claims,omitempty"`
551 Calls []K8sCall `json:"api_calls,omitempty"`
552 Access map[string]bool `json:"self_subject_access_review,omitempty"`
553 Note string `json:"note,omitempty"`
554}
555
556// jwtClaims decodes the payload of a service-account JWT WITHOUT verifying it.
557// It is informational (what the pod was handed); the API server is the verifier.
558func jwtClaims(token string) map[string]interface{} {
559 parts := strings.Split(token, ".")
560 if len(parts) != 3 {
561 return nil
562 }
563 raw, err := base64.RawURLEncoding.DecodeString(parts[1])
564 if err != nil {
565 return nil
566 }
567 var all map[string]interface{}
568 if json.Unmarshal(raw, &all) != nil {
569 return nil
570 }
571 out := map[string]interface{}{"sub": all["sub"], "aud": all["aud"], "iss": all["iss"]}
572 if exp, ok := all["exp"].(float64); ok {
573 out["seconds_until_expiry"] = int64(exp) - time.Now().Unix()
574 }
575 if iat, ok := all["iat"].(float64); ok {
576 out["token_age_seconds"] = time.Now().Unix() - int64(iat)
577 }
578 // A bound token carries the pod it was issued to; a legacy secret-based token does not.
579 if kube, ok := all["kubernetes.io"].(map[string]interface{}); ok {
580 _, bound := kube["pod"]
581 out["bound_to_pod"] = bound
582 } else {
583 out["bound_to_pod"] = false
584 }
585 return out
586}
587
588func k8sprobe() int {
589 const dir = "/var/run/secrets/kubernetes.io/serviceaccount"
590 rep := K8sReport{}
591 emit := func() int {
592 enc := json.NewEncoder(os.Stdout)
593 enc.SetIndent("", " ")
594 _ = enc.Encode(rep)
595 return 0
596 }
597 tokenBytes, err := os.ReadFile(dir + "/token")
598 if err != nil {
599 rep.Note = "no service-account token mounted at " + dir
600 return emit()
601 }
602 rep.TokenMounted = true
603 token := strings.TrimSpace(string(tokenBytes))
604 rep.Namespace = readTrim(dir + "/namespace")
605 rep.Claims = jwtClaims(token)
606
607 caPEM, err := os.ReadFile(dir + "/ca.crt")
608 pool := x509.NewCertPool()
609 if err != nil || !pool.AppendCertsFromPEM(caPEM) {
610 rep.Note = "cannot load cluster CA"
611 return emit()
612 }
613 host, port := os.Getenv("KUBERNETES_SERVICE_HOST"), os.Getenv("KUBERNETES_SERVICE_PORT")
614 if host == "" || port == "" {
615 rep.Note = "KUBERNETES_SERVICE_HOST/PORT not set"
616 return emit()
617 }
618 base := "https://" + net.JoinHostPort(host, port)
619 client := &http.Client{
620 Timeout: 3 * time.Second,
621 Transport: &http.Transport{TLSClientConfig: &tls.Config{RootCAs: pool, MinVersion: tls.VersionTLS12}},
622 }
623 do := func(method, path string, body []byte) (int, []byte, error) {
624 req, _ := http.NewRequest(method, base+path, bytes.NewReader(body))
625 req.Header.Set("Authorization", "Bearer "+token)
626 if body != nil {
627 req.Header.Set("Content-Type", "application/json")
628 }
629 resp, err := client.Do(req)
630 if err != nil {
631 return 0, nil, err
632 }
633 defer resp.Body.Close()
634 data, _ := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
635 return resp.StatusCode, data, nil
636 }
637
638 ns := rep.Namespace
639 reads := []struct{ name, path string }{
640 {"get_configmap_app_config_own_ns", "/api/v1/namespaces/" + ns + "/configmaps/app-config"},
641 {"list_configmaps_own_ns", "/api/v1/namespaces/" + ns + "/configmaps"},
642 {"list_secrets_own_ns", "/api/v1/namespaces/" + ns + "/secrets"},
643 {"list_secrets_kube_system", "/api/v1/namespaces/kube-system/secrets"},
644 {"list_pods_all_namespaces", "/api/v1/pods"},
645 {"list_nodes", "/api/v1/nodes"},
646 }
647 for _, r := range reads {
648 status, data, err := do(http.MethodGet, r.path, nil)
649 call := K8sCall{Name: r.name, Status: status}
650 if err != nil {
651 call.Error = errnoName(errors.Unwrap(err))
652 if call.Error == "error" {
653 call.Error = "request failed (network or TLS)"
654 }
655 } else if status == http.StatusOK {
656 var list struct {
657 Items []json.RawMessage `json:"items"`
658 }
659 if json.Unmarshal(data, &list) == nil && list.Items != nil {
660 n := len(list.Items)
661 call.Items = &n
662 }
663 }
664 rep.Calls = append(rep.Calls, call)
665 }
666
667 // Write permissions are checked with SelfSubjectAccessReview: asks the API
668 // server whether the action WOULD be allowed, and creates nothing.
669 rep.Access = map[string]bool{}
670 reviews := []struct{ name, verb, group, resource, sub, namespace string }{
671 {"create_pods_own_ns", "create", "", "pods", "", ns},
672 {"create_pods_exec_own_ns", "create", "", "pods", "exec", ns},
673 {"get_secrets_any_namespace", "get", "", "secrets", "", ""},
674 {"create_rolebindings_own_ns", "create", "rbac.authorization.k8s.io", "rolebindings", "", ns},
675 {"escalate_clusterroles", "escalate", "rbac.authorization.k8s.io", "clusterroles", "", ""},
676 {"impersonate_users", "impersonate", "", "users", "", ""},
677 }
678 for _, rv := range reviews {
679 attrs := map[string]string{"verb": rv.verb, "group": rv.group, "resource": rv.resource}
680 if rv.sub != "" {
681 attrs["subresource"] = rv.sub
682 }
683 if rv.namespace != "" {
684 attrs["namespace"] = rv.namespace
685 }
686 body, _ := json.Marshal(map[string]interface{}{
687 "apiVersion": "authorization.k8s.io/v1", "kind": "SelfSubjectAccessReview",
688 "spec": map[string]interface{}{"resourceAttributes": attrs},
689 })
690 status, data, err := do(http.MethodPost, "/apis/authorization.k8s.io/v1/selfsubjectaccessreviews", body)
691 allowed := false
692 if err == nil && status == http.StatusCreated {
693 var out struct {
694 Status struct {
695 Allowed bool `json:"allowed"`
696 } `json:"status"`
697 }
698 if json.Unmarshal(data, &out) == nil {
699 allowed = out.Status.Allowed
700 }
701 }
702 rep.Access[rv.name] = allowed
703 }
704 return emit()
705}
706
707// tcpcheck makes one TCP connection attempt and reports it. The distroless image
708// has no shell, nc or curl, so reachability tests need to live in the binary.
709func tcpcheck(target string) int {
710 out := map[string]interface{}{"target": target, "connected": false}
711 conn, err := net.DialTimeout("tcp", target, 3*time.Second)
712 if err == nil {
713 conn.Close()
714 out["connected"] = true
715 } else {
716 var dnsErr *net.DNSError
717 var netErr net.Error
718 switch {
719 case errors.As(err, &dnsErr):
720 out["error"] = "name resolution failed"
721 case errors.As(err, &netErr) && netErr.Timeout():
722 out["error"] = "timeout"
723 default:
724 out["error"] = errnoName(errors.Unwrap(errors.Unwrap(err)))
725 }
726 }
727 _ = json.NewEncoder(os.Stdout).Encode(out)
728 return 0
729}
1#!/usr/bin/env node
2"use strict";
3
4/**
5 * Static policy gate for Dockerfiles and Compose files (no Docker required).
6 *
7 * This is deliberately a small, readable rule set that encodes the control
8 * decisions in the lab README. It is NOT a replacement for a maintained
9 * misconfiguration scanner; the lab runs Trivy as well and records where the
10 * two disagree. Every rule has a positive and a negative test in
11 * policy-check.test.js.
12 *
13 * Usage: node policy-check.js <dir-or-file>... (exit 1 when any finding exists)
14 */
15
16const fs = require("node:fs");
17const path = require("node:path");
18const YAML = require("yaml");
19
20const DANGEROUS_CAPS = new Set([
21 "ALL", "SYS_ADMIN", "NET_ADMIN", "SYS_PTRACE", "SYS_MODULE", "SYS_RAWIO",
22 "DAC_READ_SEARCH", "SYS_BOOT", "MAC_ADMIN", "BPF", "PERFMON",
23]);
24const SENSITIVE_HOST_PATHS = ["/", "/etc", "/proc", "/sys", "/dev", "/root", "/home", "/var/lib/docker", "/var/run", "/run"];
25const SECRET_NAME = /(PASSWORD|PASSWD|SECRET|TOKEN|API_?KEY|PRIVATE_?KEY|ACCESS_?KEY)/i;
26
27/** Logical Dockerfile instructions (line continuations joined, comments dropped). */
28function parseDockerfile(source) {
29 const lines = source.split(/\r?\n/);
30 const out = [];
31 let buffer = "";
32 let startLine = 0;
33 lines.forEach((raw, index) => {
34 const trimmed = raw.trim();
35 if (!buffer && (trimmed === "" || trimmed.startsWith("#"))) return;
36 if (!buffer) startLine = index + 1;
37 const continued = trimmed.endsWith("\\");
38 buffer += (buffer ? " " : "") + (continued ? trimmed.slice(0, -1).trim() : trimmed);
39 if (!continued) {
40 const space = buffer.search(/\s/);
41 const instruction = (space === -1 ? buffer : buffer.slice(0, space)).toUpperCase();
42 const args = space === -1 ? "" : buffer.slice(space + 1).trim();
43 out.push({ instruction, args, line: startLine });
44 buffer = "";
45 }
46 });
47 return out;
48}
49
50function analyzeDockerfile(source, file = "Dockerfile") {
51 const findings = [];
52 const add = (rule, line, message) => findings.push({ file, rule, line, message });
53 const items = parseDockerfile(source);
54 const froms = items.filter((item) => item.instruction === "FROM");
55
56 for (const from of froms) {
57 const ref = from.args.replace(/^--platform=\S+\s+/, "").split(/\s+/)[0];
58 const stageRefs = froms.map((candidate) => (candidate.args.match(/\bAS\s+(\S+)/i) || [])[1]).filter(Boolean);
59 if (stageRefs.includes(ref) || ref === "scratch") continue;
60 if (!ref.includes("@sha256:")) add("DF001", from.line, `base image ${ref} is not pinned by digest`);
61 const tag = ref.split("@")[0].split("/").pop();
62 if (!tag.includes(":") || tag.endsWith(":latest")) add("DF002", from.line, `base image ${ref} uses latest or an implicit tag`);
63 }
64
65 if (froms.length) {
66 const finalStart = items.indexOf(froms[froms.length - 1]);
67 const finalStage = items.slice(finalStart);
68 const users = finalStage.filter((item) => item.instruction === "USER");
69 const lastUser = users.length ? users[users.length - 1].args.split(/\s+/)[0].split(":")[0] : null;
70 if (!lastUser || lastUser === "root" || lastUser === "0") add("DF003", froms[froms.length - 1].line, "final stage runs as root (no non-root USER)");
71 if (!finalStage.some((item) => item.instruction === "HEALTHCHECK")) add("DF006", froms[froms.length - 1].line, "final stage defines no HEALTHCHECK");
72 for (const item of finalStage) {
73 if ((item.instruction === "CMD" || item.instruction === "ENTRYPOINT") && !item.args.startsWith("[")) {
74 add("DF007", item.line, `${item.instruction} uses shell form; PID 1 will be a shell that does not forward signals`);
75 }
76 }
77 if (froms.length === 1 && items.some((item) => item.instruction === "RUN" && /\b(go build|npm (ci|install)|pip3? install|apt-get install|apk add|make|gcc)\b/.test(item.args))) {
78 add("DF009", froms[0].line, "single-stage build: compiler or package manager ships in the runtime image");
79 }
80 }
81
82 for (const item of items) {
83 if ((item.instruction === "ENV" || item.instruction === "ARG")) {
84 const match = item.args.match(/^([A-Za-z_][A-Za-z0-9_]*)(?:=|\s+)(.+)$/);
85 if (match && SECRET_NAME.test(match[1]) && match[2].replace(/["']/g, "").trim() !== "") {
86 add("DF004", item.line, `${item.instruction} ${match[1]} carries a literal value; it persists in image metadata`);
87 }
88 }
89 if (item.instruction === "RUN" && /\bchmod\b[^;&|]*\b(-R\s+)?(0?777|a\+rwx)\b/.test(item.args)) add("DF005", item.line, "world-writable permissions set in the image");
90 if (item.instruction === "ADD" && /^(--\S+\s+)*https?:\/\//.test(item.args)) add("DF008", item.line, "ADD from a remote URL is neither pinned nor verified");
91 if (item.instruction === "RUN" && /(curl|wget)[^|;&]*\|\s*(sudo\s+)?(sh|bash)\b/.test(item.args)) add("DF008", item.line, "pipes a downloaded script into a shell");
92 }
93 return findings;
94}
95
96function asList(value) {
97 if (value === undefined || value === null) return [];
98 return Array.isArray(value) ? value : Object.entries(value).map(([k, v]) => `${k}=${v}`);
99}
100
101/** Split "source:target[:mode]" where source may be a ${VAR:?message} expression. */
102function splitVolume(spec) {
103 const match = spec.match(/^(\$\{[^}]*\}|[^:]+):(.*)$/);
104 return match ? { source: match[1], rest: match[2] } : { source: spec, rest: "" };
105}
106
107function normalizeCap(cap) {
108 return String(cap).toUpperCase().replace(/^CAP_/, "");
109}
110
111function analyzeCompose(source, file = "compose.yaml") {
112 const findings = [];
113 const document = YAML.parse(source) || {};
114 const services = document.services || {};
115 for (const [name, service] of Object.entries(services)) {
116 const add = (rule, message) => findings.push({ file, service: name, rule, message });
117 const local = service.build !== undefined;
118 const image = service.image || "";
119
120 if (service.privileged === true) add("DC001", "privileged: true grants all capabilities and device access");
121 const capAdd = asList(service.cap_add).map(normalizeCap);
122 for (const cap of capAdd) if (DANGEROUS_CAPS.has(cap)) add("DC002", `cap_add ${cap}`);
123 const capDrop = asList(service.cap_drop).map(normalizeCap);
124 if (!capDrop.includes("ALL")) add("DC003", "cap_drop does not include ALL");
125
126 const securityOpt = asList(service.security_opt).map(String);
127 if (securityOpt.some((opt) => /^(seccomp|apparmor)[=:]unconfined$/.test(opt))) add("DC004", "seccomp or AppArmor confinement disabled");
128 if (!securityOpt.some((opt) => /^no-new-privileges(:|=)true$/.test(opt) || opt === "no-new-privileges")) add("DC005", "no-new-privileges is not set");
129
130 for (const volume of asList(service.volumes)) {
131 const spec = typeof volume === "string" ? volume : `${volume.source}:${volume.target}${volume.read_only ? ":ro" : ""}`;
132 const { source, rest } = splitVolume(spec);
133 if (/(docker|podman|containerd|crio)\.sock(:|$)/.test(spec)) add("DC006", "container runtime socket mounted (host-root equivalent; :ro on a socket file does not restrict API calls)");
134 else if (source.startsWith("/") || source.startsWith("${") || source.startsWith(".")) {
135 const normalized = path.posix.normalize(source);
136 if (SENSITIVE_HOST_PATHS.includes(normalized)) add("DC007", `sensitive host path ${normalized} bind-mounted`);
137 else if (!/(^|:)ro(,|$)/.test(rest.split(":").slice(1).join(":"))) add("DC007", `host bind mount ${source} is writable`);
138 }
139 }
140
141 for (const key of ["pid", "ipc", "uts", "userns_mode", "network_mode"]) {
142 if (service[key] === "host") add("DC008", `${key}: host shares a host namespace`);
143 }
144
145 const user = service.user === undefined ? "" : String(service.user);
146 if (!user || user === "root" || user.split(":")[0] === "0") add("DC009", "container user is root or unset");
147 if (service.read_only !== true) add("DC010", "root filesystem is writable (read_only is not true)");
148 const limits = (service.deploy && service.deploy.resources && service.deploy.resources.limits) || {};
149 if (!service.mem_limit && !limits.memory) add("DC011", "no memory limit");
150 if (!service.pids_limit && !limits.pids) add("DC012", "no PID limit");
151 if (!service.cpus && !limits.cpus && !service.cpu_quota) add("DC013", "no CPU limit");
152
153 for (const port of asList(service.ports)) {
154 const spec = typeof port === "string" ? port : `${port.host_ip || ""}:${port.published}:${port.target}`;
155 const parts = spec.split(":");
156 const hostIp = parts.length >= 3 ? parts[0] : "";
157 if (hostIp !== "127.0.0.1" && hostIp !== "::1") add("DC014", `published port ${spec} binds all interfaces`);
158 }
159
160 if (!local && image && !image.includes("@sha256:")) add("DC015", `external image ${image} is not pinned by digest`);
161 if (!local && /:latest$/.test(image)) add("DC016", `external image ${image} uses latest`);
162 }
163 return findings;
164}
165
166function collect(target) {
167 const stat = fs.statSync(target);
168 if (stat.isDirectory()) {
169 return fs.readdirSync(target).sort().flatMap((entry) => collect(path.join(target, entry)));
170 }
171 return [target];
172}
173
174function analyzePath(target) {
175 const findings = [];
176 for (const file of collect(target)) {
177 const base = path.basename(file);
178 const text = () => fs.readFileSync(file, "utf8");
179 if (base === "Dockerfile" || base.startsWith("Dockerfile.")) findings.push(...analyzeDockerfile(text(), file));
180 else if (/^(docker-)?compose(\.[\w-]+)?\.ya?ml$/.test(base)) findings.push(...analyzeCompose(text(), file));
181 }
182 return findings;
183}
184
185module.exports = { analyzeCompose, analyzeDockerfile, analyzePath, parseDockerfile };
186
187if (require.main === module) {
188 const targets = process.argv.slice(2);
189 if (!targets.length) {
190 console.error("usage: policy-check.js <dir-or-file>...");
191 process.exit(2);
192 }
193 const findings = targets.flatMap(analyzePath);
194 for (const f of findings) {
195 const where = f.line ? `${f.file}:${f.line}` : `${f.file} [${f.service}]`;
196 console.log(`${f.rule} ${where} ${f.message}`);
197 }
198 console.log(`${findings.length} finding(s)`);
199 process.exit(findings.length ? 1 : 0);
200}
1"use strict";
2
3const assert = require("node:assert/strict");
4const path = require("node:path");
5const test = require("node:test");
6const { analyzeCompose, analyzeDockerfile, analyzePath } = require("./policy-check");
7
8const lab = path.resolve(__dirname, "..");
9const ids = (findings) => [...new Set(findings.map((f) => f.rule))].sort();
10
11// A compliant service used as the base for single-rule mutations.
12const GOOD_SERVICE = `
13services:
14 app:
15 build: .
16 user: "65532:65532"
17 read_only: true
18 cap_drop: [ALL]
19 security_opt: ["no-new-privileges:true"]
20 mem_limit: 64m
21 pids_limit: 32
22 cpus: 0.5
23 ports: ["127.0.0.1:8080:8080"]
24`;
25
26function composeWith(extra) {
27 return GOOD_SERVICE.replace(" build: .\n", ` build: .\n${extra}`);
28}
29
30test("the compliant base service has no findings", () => {
31 assert.deepEqual(analyzeCompose(GOOD_SERVICE), []);
32});
33
34// ---- Compose rules: each is triggered by exactly its own mutation ----------
35const composeCases = [
36 ["DC001", " privileged: true\n"],
37 ["DC002", " cap_add: [SYS_ADMIN]\n"],
38 ["DC002", " cap_add: [CAP_NET_ADMIN]\n"],
39 ["DC004", " security_opt: [\"seccomp=unconfined\"]\n"],
40 ["DC006", " volumes: [\"/var/run/docker.sock:/var/run/docker.sock:ro\"]\n"],
41 ["DC006", " volumes: [\"/var/run/docker.sock:/var/run/docker.sock\"]\n"],
42 ["DC006", " volumes: [\"/run/containerd/containerd.sock:/run/containerd/containerd.sock\"]\n"],
43 ["DC007", " volumes: [\"/etc:/host-etc:ro\"]\n"],
44 ["DC007", " volumes: [\"/srv/data:/data\"]\n"],
45 ["DC008", " pid: host\n"],
46 ["DC008", " network_mode: host\n"],
47 ["DC014", " ports: [\"8080:8080\"]\n"],
48 ["DC014", " ports: [\"0.0.0.0:8080:8080\"]\n"],
49];
50for (const [rule, mutation] of composeCases) {
51 test(`${rule} fires for ${mutation.trim()}`, () => {
52 // Mutations that replace an existing key are applied by overriding via text edit.
53 let source = composeWith(mutation);
54 if (mutation.startsWith(" security_opt")) source = GOOD_SERVICE.replace(/ security_opt:.*\n/, mutation);
55 if (mutation.startsWith(" ports")) source = GOOD_SERVICE.replace(/ ports:.*\n/, mutation);
56 assert.ok(ids(analyzeCompose(source)).includes(rule), JSON.stringify(analyzeCompose(source)));
57 });
58}
59
60test("a read-only bind mount of a non-sensitive path is accepted", () => {
61 assert.deepEqual(analyzeCompose(composeWith(" volumes: [\"/srv/data:/data:ro\"]\n")), []);
62});
63
64test("DC007 handles ${VAR:?message} sources without splitting on the colon", () => {
65 const findings = analyzeCompose(composeWith(" volumes: [\"${DIR:?set me}:/data\"]\n"));
66 assert.deepEqual(ids(findings), ["DC007"]);
67 assert.match(findings[0].message, /\$\{DIR:\?set me\}/);
68});
69
70test("each missing hardening attribute is reported independently", () => {
71 const bare = analyzeCompose("services:\n app:\n build: .\n");
72 assert.deepEqual(ids(bare), ["DC003", "DC005", "DC009", "DC010", "DC011", "DC012", "DC013"]);
73});
74
75test("external images must be digest-pinned; locally built images are exempt", () => {
76 const withImage = (image) => composeWith("").replace(" build: .\n", ` image: ${image}\n`);
77 assert.ok(ids(analyzeCompose(withImage("busybox:1.37"))).includes("DC015"));
78 assert.ok(ids(analyzeCompose(withImage("busybox:latest"))).includes("DC016"));
79 assert.deepEqual(analyzeCompose(withImage(`busybox:1.37@sha256:${"a".repeat(64)}`)), []);
80 assert.deepEqual(analyzeCompose(GOOD_SERVICE), []);
81});
82
83// ---- Dockerfile rules --------------------------------------------------------
84const PINNED = `sha256:${"b".repeat(64)}`;
85const GOOD_DOCKERFILE = `
86FROM golang:1.27-alpine@${PINNED} AS build
87RUN go build -o /out/app .
88FROM gcr.io/distroless/static-debian12:nonroot@${PINNED}
89COPY --from=build /out/app /app/app
90USER 65532:65532
91HEALTHCHECK CMD ["/app/app", "healthcheck"]
92ENTRYPOINT ["/app/app"]
93`;
94
95test("the compliant Dockerfile has no findings", () => {
96 assert.deepEqual(analyzeDockerfile(GOOD_DOCKERFILE), []);
97});
98
99const dockerfileCases = [
100 ["DF001", GOOD_DOCKERFILE.replace(`golang:1.27-alpine@${PINNED}`, "golang:1.27-alpine")],
101 ["DF002", GOOD_DOCKERFILE.replace(`golang:1.27-alpine@${PINNED}`, `golang:latest@${PINNED}`)],
102 ["DF002", GOOD_DOCKERFILE.replace(`golang:1.27-alpine@${PINNED}`, `golang@${PINNED}`)],
103 ["DF003", GOOD_DOCKERFILE.replace("USER 65532:65532\n", "")],
104 ["DF003", GOOD_DOCKERFILE.replace("USER 65532:65532", "USER root")],
105 ["DF004", GOOD_DOCKERFILE.replace("USER 65532:65532", "USER 65532:65532\nENV DB_PASSWORD=<placeholder>")],
106 ["DF004", GOOD_DOCKERFILE.replace("USER 65532:65532", "USER 65532:65532\nARG NPM_TOKEN=<placeholder>")],
107 ["DF005", GOOD_DOCKERFILE.replace("go build", "chmod -R 777 /src && go build")],
108 ["DF006", GOOD_DOCKERFILE.replace(/HEALTHCHECK.*\n/, "")],
109 ["DF007", GOOD_DOCKERFILE.replace('ENTRYPOINT ["/app/app"]', "ENTRYPOINT /app/app")],
110 ["DF008", GOOD_DOCKERFILE.replace("go build", "curl -fsSL https://example.invalid/i.sh | sh && go build")],
111 ["DF008", GOOD_DOCKERFILE.replace("COPY --from", "ADD https://example.invalid/x.tgz /x\nCOPY --from")],
112 ["DF009", `FROM golang:1.27-alpine@${PINNED}\nUSER 65532\nHEALTHCHECK CMD [\"x\"]\nRUN go build -o /app .\nENTRYPOINT [\"/app\"]\n`],
113];
114for (const [rule, source] of dockerfileCases) {
115 test(`${rule} fires on its Dockerfile mutation`, () => {
116 assert.ok(ids(analyzeDockerfile(source)).includes(rule), JSON.stringify(analyzeDockerfile(source)));
117 });
118}
119
120test("a stage reference in FROM is not mistaken for an unpinned external image", () => {
121 const source = `${GOOD_DOCKERFILE}\nFROM build AS extra\nUSER 1\nHEALTHCHECK CMD [\"x\"]\nENTRYPOINT [\"x\"]\n`;
122 assert.deepEqual(ids(analyzeDockerfile(source)).filter((id) => id === "DF001" || id === "DF002"), []);
123});
124
125test("a non-secret-looking ENV is not reported as a secret", () => {
126 const source = GOOD_DOCKERFILE.replace("USER 65532:65532", "USER 65532:65532\nENV LOG_LEVEL=info\nENV TOKEN_TTL_SECONDS=");
127 assert.deepEqual(ids(analyzeDockerfile(source)).filter((id) => id === "DF004"), []);
128});
129
130test("line continuations are joined before rules are applied", () => {
131 const source = GOOD_DOCKERFILE.replace("go build -o /out/app .", "go build \\\n -o /out/app . \\\n && chmod -R 777 /src");
132 assert.ok(ids(analyzeDockerfile(source)).includes("DF005"));
133});
134
135// ---- The two real stacks -------------------------------------------------------
136test("the insecure stack violates every rule the hardened stack is designed to satisfy", () => {
137 const found = ids(analyzePath(path.join(lab, "insecure")));
138 for (const required of [
139 "DF001", "DF003", "DF004", "DF005", "DF006", "DF007", "DF009",
140 "DC001", "DC002", "DC003", "DC004", "DC005", "DC006", "DC007", "DC008",
141 "DC009", "DC010", "DC011", "DC012", "DC013", "DC014", "DC015",
142 ]) {
143 assert.ok(found.includes(required), `insecure stack should trigger ${required}; got ${found.join(",")}`);
144 }
145});
146
147test("the hardened stack has zero findings", () => {
148 assert.deepEqual(analyzePath(path.join(lab, "hardened")), []);
149});
150
151test("the hardened stack's seccomp profile is default-deny and does not allow escape-relevant syscalls", () => {
152 const profile = require(path.join(lab, "hardened", "seccomp.json"));
153 assert.equal(profile.defaultAction, "SCMP_ACT_ERRNO");
154 const allowed = new Set(
155 profile.syscalls.filter((rule) => rule.action === "SCMP_ACT_ALLOW").flatMap((rule) => rule.names),
156 );
157 for (const name of [
158 "mount", "umount2", "setns", "unshare", "ptrace", "bpf", "keyctl", "perf_event_open",
159 "userfaultfd", "kexec_load", "init_module", "finit_module", "open_by_handle_at",
160 "pivot_root", "chroot", "reboot", "mknodat", "fchownat", "fsopen", "fsmount", "move_mount",
161 ]) {
162 assert.ok(!allowed.has(name), `${name} must not be allowlisted`);
163 }
164 // clone is allowed only with a namespace-flag mask; clone3 must fall back via ENOSYS.
165 const cloneRule = profile.syscalls.find((rule) => rule.names.includes("clone"));
166 assert.equal(cloneRule.args[0].op, "SCMP_CMP_MASKED_EQ");
167 assert.equal(cloneRule.args[0].value, 0x7e020000);
168 assert.equal(cloneRule.args[0].valueTwo, 0);
169 const clone3Rule = profile.syscalls.find((rule) => rule.names.includes("clone3"));
170 assert.equal(clone3Rule.action, "SCMP_ACT_ERRNO");
171 assert.equal(clone3Rule.errnoRet, 38);
172 // The service must still be able to serve: sockets and the runtime hand-off set.
173 for (const name of ["socket", "bind", "listen", "accept4", "fstatfs", "statx", "execve"]) {
174 assert.ok(allowed.has(name), `${name} must be allowlisted for the service to start`);
175 }
176});
1#!/usr/bin/env python3
2"""Assert the OBSERVED runtime results of the Docker lab. Usage: runtime_check.py <outdir>
3
4Reads the JSON that scripts/run-lab.sh wrote and fails (exit 1) when any claimed
5control is not what the running container actually reported. Supply-chain
6assertions run only when those steps executed; otherwise they print SKIP with the
7recorded reason - a skip is never reported as a pass.
8"""
9import json
10import pathlib
11import sys
12
13out = pathlib.Path(sys.argv[1])
14failures = []
15passes = 0
16
17
18def load(rel):
19 path = out / rel
20 return json.loads(path.read_text()) if path.exists() else None
21
22
23def check(name, condition, detail=""):
24 global passes
25 if condition:
26 passes += 1
27 print(f"PASS {name}")
28 else:
29 failures.append(name)
30 print(f"FAIL {name} {detail}")
31
32
33def probes(report):
34 return {p["name"].split(" ")[0]: p for p in report["probes"]}
35
36
37def read_exit(rel):
38 path = out / rel
39 return int(path.read_text().strip()) if path.exists() else None
40
41
42# ---- insecure baseline: every dangerous capability is observable --------------
43ins = load("runtime/insecure-probe.json")
44check("insecure: probe output exists", ins is not None)
45if ins:
46 p, pr = ins["posture"], probes(ins)
47 check("insecure: runs as uid 0", p["uid"] == 0, p["uid"])
48 check("insecure: large effective capability set (privileged)", len(p["cap_eff"]) >= 30, len(p["cap_eff"]))
49 check("insecure: SYS_ADMIN present", "SYS_ADMIN" in p["cap_eff"])
50 check("insecure: no_new_privs off", p["no_new_privs"] == "0", p["no_new_privs"])
51 check("insecure: seccomp off", p["seccomp_mode"] == "0", p["seccomp_mode"])
52 check("insecure: root filesystem writable", p["root_fs_mounted_read_only"] is False)
53 check("insecure: no memory limit", "9223372036854771712" in p["memory_limit"] or p["memory_limit"].startswith("max"), p["memory_limit"])
54 check("insecure: no pids limit", p["pids_limit"].startswith("max"), p["pids_limit"])
55 check("insecure: host PID namespace visible", p["pid1_comm"] != "posture" and p["visible_process_count"] > 10, (p["pid1_comm"], p["visible_process_count"]))
56 for name in ("write_root_filesystem", "write_tmp_scratch", "chown_to_other_uid", "mknod_char_device",
57 "raw_socket", "mount_tmpfs", "clone_new_user_namespace", "docker_socket_reachable",
58 "host_canary_read", "host_canary_write", "tcp_connect_canary"):
59 check(f"insecure: {name} allowed", pr.get(name, {}).get("allowed") is True, pr.get(name))
60 check("insecure: docker API answered /_ping", "200 OK" in pr.get("docker_socket_reachable", {}).get("detail", ""))
61 fork = load("runtime/insecure-forktest.json")
62 check("insecure: all 200 children started (no PID limit)", bool(fork) and fork["started"] == fork["requested"], fork)
63 check("insecure: 512 MiB allocation succeeds (no memory limit)", read_exit("runtime/insecure-memtest.exit") == 0)
64 owner = (out / "runtime/insecure-host-canary-owner.txt")
65 check("insecure: file written into the bind-mounted host directory is owned by uid 0",
66 owner.exists() and owner.read_text().split()[0] == "0", owner.read_text() if owner.exists() else None)
67
68# ---- hardened: the same probes are refused -------------------------------------
69har = load("runtime/hardened-probe.json")
70check("hardened: probe output exists", har is not None)
71if har:
72 p, pr = har["posture"], probes(har)
73 check("hardened: runs as uid 65532", p["uid"] == 65532, p["uid"])
74 check("hardened: effective capability set is empty", p["cap_eff"] == [], p["cap_eff"])
75 check("hardened: no_new_privs on", p["no_new_privs"] == "1", p["no_new_privs"])
76 check("hardened: seccomp filter active", p["seccomp_mode"] == "2" and p["seccomp_filters"] == "1", (p["seccomp_mode"], p["seccomp_filters"]))
77 check("hardened: root filesystem read-only", p["root_fs_mounted_read_only"] is True)
78 check("hardened: memory limit 128 MiB", p["memory_limit"].startswith("134217728"), p["memory_limit"])
79 check("hardened: pids limit 64", p["pids_limit"].startswith("64"), p["pids_limit"])
80 check("hardened: cpu quota 0.5 CPU", p["cpu_quota"].startswith("50000"), p["cpu_quota"])
81 check("hardened: own PID namespace (app is PID 1, few processes)", p["pid1_comm"] == "posture" and p["visible_process_count"] < 10, (p["pid1_comm"], p["visible_process_count"]))
82 expect_denied = {
83 "write_root_filesystem": "EROFS", "chown_to_other_uid": "EPERM", "mknod_char_device": "EPERM",
84 "raw_socket": "EPERM", "mount_tmpfs": "EPERM", "clone_new_user_namespace": "EPERM",
85 "docker_socket_present": "ENOENT", "host_canary_mounted": "ENOENT",
86 }
87 for name, errno in expect_denied.items():
88 got = pr.get(name, {})
89 check(f"hardened: {name} denied with {errno}", got.get("allowed") is False and got.get("errno") == errno, got)
90 check("hardened: scratch tmpfs still writable (the app is not broken)", pr["write_tmp_scratch"]["allowed"] is True)
91 canary = pr.get("tcp_connect_canary", {})
92 check("hardened: canary unreachable and name not resolvable (network topology)", canary.get("allowed") is False and "name resolution failed" in canary.get("detail", ""), canary)
93 health = out / "runtime/hardened-health-before.txt"
94 check("hardened: container reported healthy via image HEALTHCHECK", health.exists() and health.read_text().strip() == "healthy")
95 fork = load("runtime/hardened-forktest.json")
96 check("hardened: PID limit stops child creation with EAGAIN", bool(fork) and fork["started"] < fork["requested"] and fork["first_error"] == "EAGAIN", fork)
97 mem = read_exit("runtime/hardened-memtest.exit")
98 check("hardened: 512 MiB allocation is OOM-killed under a 128 MiB limit (exit 137)", mem == 137, mem)
99
100# ---- seccomp attribution controls (same hardening, different seccomp setting) ---
101for label, mode, clone_allowed in (("unconfined", "0", True), ("default", "2", False), ("custom", "2", False)):
102 ctl = load(f"runtime/hardened-seccomp-{label}-probe.json")
103 check(f"control seccomp={label}: probe output exists", ctl is not None)
104 if ctl:
105 clone = probes(ctl)["clone_new_user_namespace"]
106 check(f"control seccomp={label}: seccomp_mode {mode}", ctl["posture"]["seccomp_mode"] == mode, ctl["posture"]["seccomp_mode"])
107 check(f"control seccomp={label}: user-namespace clone {'allowed' if clone_allowed else 'denied'}",
108 clone["allowed"] is clone_allowed, clone)
109 check(f"control seccomp={label}: capabilities still empty (so the denial is not a capability effect)", ctl["posture"]["cap_eff"] == [])
110
111# ---- attack surface of the image filesystems ---------------------------------------
112inv_i, inv_h = load("runtime/insecure-inventory.json"), load("runtime/hardened-inventory.json")
113check("inventory: both images inventoried", inv_i is not None and inv_h is not None)
114if inv_i and inv_h:
115 check("inventory: insecure image ships a shell", bool(inv_i["shells"]), inv_i["shells"])
116 check("inventory: insecure image ships a package manager", bool(inv_i["package_managers"]), inv_i["package_managers"])
117 check("inventory: insecure image ships a compiler/toolchain", "usr/local/go/bin/go" in inv_i["compilers_or_interpreters"], inv_i["compilers_or_interpreters"])
118 check("inventory: hardened image ships no shell", inv_h["shells"] == [], inv_h["shells"])
119 check("inventory: hardened image ships no package manager", inv_h["package_managers"] == [], inv_h["package_managers"])
120 check("inventory: hardened image ships no compiler or interpreter", inv_h["compilers_or_interpreters"] == [], inv_h["compilers_or_interpreters"])
121 check("inventory: hardened image has no setuid/setgid files", inv_h["setuid_or_setgid"] == [], inv_h["setuid_or_setgid"])
122 check("inventory: hardened image has far fewer executable files", inv_h["executables"] * 5 < inv_i["executables"], (inv_h["executables"], inv_i["executables"]))
123 print(f"INFO inventory: executables insecure={inv_i['executables']} hardened={inv_h['executables']}; "
124 f"size insecure={inv_i['size_bytes']} hardened={inv_h['size_bytes']} bytes (file content)")
125
126# ---- supply chain (only when executed) -----------------------------------------
127scan = load("scan/summary.json")
128if scan and scan.get("trivy", {}).get("version"):
129 imgs = scan["images"]
130 ins_n = imgs["insecure"]["unique_cve_package_pairs"]
131 har_n = imgs["hardened"]["unique_cve_package_pairs"]
132 # Deliberately NOT asserting hardened < insecure: CVE counts do not rank
133 # attack surface (the observed result is the opposite - see README).
134 print(f"INFO scan: unique CVE/package findings insecure={ins_n} hardened={har_n} "
135 "(a count of known CVEs is not an attack-surface measure)")
136 for variant in ("insecure", "hardened"):
137 entry = imgs[variant]
138 check(f"scan: {variant} summary is internally consistent",
139 entry["raw_findings"] >= entry["unique_cve_package_pairs"] and sum(entry["unique_by_severity"].values()) == entry["unique_cve_package_pairs"], entry)
140 check("scan: SBOM-only scan agrees with the image scan for both variants",
141 all(scan["sbom"][v]["unique_findings_from_sbom_only"] == imgs[v]["unique_cve_package_pairs"] for v in ("insecure", "hardened") if v in scan["sbom"]),
142 {v: (scan["sbom"][v]["unique_findings_from_sbom_only"], imgs[v]["unique_cve_package_pairs"]) for v in scan["sbom"]})
143 mis_i = scan["dockerfile_misconfigurations"].get("insecure", [])
144 mis_h = scan["dockerfile_misconfigurations"].get("hardened", [])
145 check("scan: Trivy flags the insecure Dockerfile (root user, no HEALTHCHECK, secret in ENV)",
146 {"DS-0002", "DS-0026", "DS-0031"} <= {m["id"] for m in mis_i}, mis_i)
147 check("scan: Trivy reports nothing for the hardened Dockerfile", mis_h == [], mis_h)
148 check("scan: Trivy DB timestamp recorded", bool(scan["trivy"].get("db_updated_at")), scan["trivy"])
149else:
150 print("SKIP scan: Trivy was not executed (see scan/status.json)")
151if scan and scan.get("sbom"):
152 for variant, sbom in scan["sbom"].items():
153 check(f"sbom: {variant} CycloneDX document has components", sbom["components"] > 0 and sbom["format"] == "CycloneDX", sbom)
154else:
155 print("SKIP sbom: Syft was not executed (see sbom/status.json)")
156
157sign = load("signing/summary.json")
158if sign and sign.get("executed"):
159 for key, want in (("signed", True), ("verify_signed_digest", True), ("unsigned_rejected", True),
160 ("wrong_key_rejected", True), ("tag_before_substitution_ok", True),
161 ("tag_substitution_rejected", True), ("attestation_verified", True),
162 ("wrong_predicate_rejected", True)):
163 if key in sign["results"]:
164 check(f"signing: {key}", sign["results"][key] is want, sign["results"][key])
165else:
166 print("SKIP signing: cosign was not executed (see signing/status.json)")
167
168print(f"\n{passes} passed, {len(failures)} failed")
169sys.exit(1 if failures else 0)
Run it
node --test labs/docker-security/tests/policy-check.test.jsbash labs/docker-security/scripts/run-lab.sh
Status: partially tested. The static policy gate runs anywhere and is part of npm run validate.
The runtime, scanning, SBOM and signing steps ran on one disposable VM on 2026-11-05 (85 of 85 assertions passed)
and are not wired into CI. AppArmor, rootless Docker, user-namespace remapping and a production signing trust
root were not executed (see What was not tested).
Evidence labels used on this page:
| Label | Meaning | Closest tier in the evidence standards |
|---|---|---|
tested locally |
I ran it in this lab and kept the output in evidence/ |
T2/T3, T4 where the same case ran on both stacks |
source-reviewed |
I read it in the named primary source; not executed here | T0 |
policy model |
A rule set evaluated by a local test, not enforced by the real system | T1 |
requires-review |
No independent reviewer has checked it against its sources | review status of this page |
Scope¶
One service, two configurations, one question: what can code running inside the container do, and what changes when the
controls are on? The service is a Go program of about 730 lines (standard library only) (app/main.go)
with an HTTP endpoint and a probe subcommand that tries a fixed list of benign operations (write the root filesystem,
chown, mknod, open a raw socket, mount, create a user namespace, reach the Docker socket, write a bind-mounted
directory, open a TCP connection) and reports the errno the kernel returned. Observing denials from inside the container
is the point; reading a Compose file and assuming it took effect is how hardening claims go wrong.
In scope: image build, base-image choice, user, filesystem, capabilities, no-new-privileges, seccomp, resource limits,
network topology, image scanning, SBOM, signing and verification by digest.
Out of scope: Kubernetes (see the Kubernetes lab), runtime detection tooling, registry operations, host hardening and anything that targets systems I do not own. Nothing here contacts a real cloud account, production system or third-party service other than downloading base images and the Trivy vulnerability database.
Safety. The insecure stack runs
privileged: true,pid: hostand mounts the Docker socket on purpose. Runrun-lab.shonly on a throwaway VM or CI runner. The probe sends one read-onlyGET /_pingto the socket and nothing else; it creates no containers and changes no host state outside a temp directory the script owns.
What I built¶
| Path | Purpose |
|---|---|
app/ |
Go (stdlib only) service with probe, healthcheck, forktest, memtest subcommands, plus k8sprobe and tcpcheck, which the Kubernetes lab reuses |
insecure/Dockerfile, insecure/compose.yaml |
Deliberately bad baseline; every line maps to a rule the gate must report |
hardened/Dockerfile, hardened/compose.yaml |
Same service, controls on |
hardened/seccomp.json |
Allowlist profile derived from strace of the shipped binary |
scripts/gen-seccomp.sh |
Derives the profile; prints which syscalls were service, harness, hand-off or removed |
scripts/run-lab.sh |
Builds, runs both stacks, runs controls, scans, signs, asserts, optionally publishes evidence |
scripts/scan.sh, scripts/sign-verify.sh |
Trivy + Syft; local registry + cosign with an ephemeral key |
tests/policy-check.js (+ .test.js) |
Static Dockerfile/Compose gate; 38 tests, a positive and a negative case per rule |
tests/runtime_check.py, inventory.py, summarize_scan.py |
Assertions on observed output, image attack-surface inventory, scan dedup |
evidence/ |
Sanitized output of the run described below |
flowchart LR
subgraph BUILD["Build"]
SRC["app source"] --> B1["builder stage<br/>digest-pinned Go image"]
B1 --> IMG["static binary on<br/>distroless nonroot"]
end
subgraph ASSURE["Scan and sign"]
IMG --> SG["static policy gate<br/>Dockerfile and Compose"]
IMG --> TR["Trivy image scan<br/>Dockerfile misconfig"]
IMG --> SY["Syft SBOM<br/>CycloneDX"]
SY --> TS["Trivy SBOM-only scan"]
IMG --> CS["cosign sign by digest"]
SY --> CA["cosign attest SBOM"]
end
subgraph DEPLOY["Deploy"]
CS --> VF{"verify digest<br/>before run"}
CA --> VF
VF -->|"signature missing or key wrong"| STOP["reject"]
VF -->|"ok"| RUN["compose up"]
end
subgraph RUNTIME["Runtime enforcement"]
RUN --> U["non-root uid 65532"]
RUN --> C["cap_drop ALL"]
RUN --> N["no-new-privileges"]
RUN --> S["seccomp allowlist"]
RUN --> R["read-only rootfs + tmpfs"]
RUN --> L["memory, PIDs, CPU limits"]
RUN --> NET["internal network"]
end
Status: the pipeline in this diagram is a design diagram. Every box except "verify digest before run" was executed by
run-lab.sh; verification was executed as a command (cosign verify) but nothing in this lab refuses to start an
unsigned image. Enforcement at deploy time needs an admission controller or a deploy wrapper; the
Kubernetes lab models that decision.
Attack surface and threat model¶
| Element | Declared scope |
|---|---|
| Actor | Code running as the container's main process: a compromised dependency, an RCE in the service, or a malicious image layer |
| Assets | The host kernel and filesystem, the Docker daemon, neighbouring containers, the service's own data |
| Entry points | Anything the process can call: syscalls, mounted paths, sockets, network |
| Trust boundary | Container process → kernel (namespaces, capabilities, seccomp, cgroups) → host |
| Not in scope | A kernel vulnerability or runc escape; hardening reduces reachable kernel surface but cannot make a shared kernel a hard multi-tenant boundary |
The insecure configuration is built to expose each of these at once: root, full capability set, no syscall filter, host PID namespace, Docker socket, writable bind mount, writable root filesystem, no limits, all-interface port.
Control decisions¶
Each row names what the control prevents and what it does not. The last column is the cost I would expect to pay.
| Control | Insecure | Hardened | Stops | Does not stop | Cost / false-positive risk |
|---|---|---|---|---|---|
| Base image | golang:1.27-alpine (toolchain, apk, shell ship in runtime), tag only |
distroless static-debian12:nonroot, tag + digest |
Post-exploitation tooling: no shell, package manager or compiler | Vulnerable code in the binary itself | No shell means no docker exec sh; debug with an ephemeral debug container or a separate debug image |
| User | root (uid 0) | 65532:65532 |
Writing root-owned files, binding <1024 without caps | Kernel bugs reachable by unprivileged users | Bind-mounted volumes must be writable by that uid; fails at start, visibly |
| Capabilities | 40 effective (privileged) | cap_drop: ALL, CapEff=0 |
chown, mknod, raw sockets, mount via CAP_* checks |
Anything that needs no capability | Needs NET_BIND_SERVICE for port 80/443 unless you remap ports; ping needs NET_RAW |
no-new-privileges |
NoNewPrivs: 0 |
NoNewPrivs: 1 |
setuid/file-capability privilege gain on execve |
A process that is already privileged | Breaks legitimate setuid helpers (sudo, ping on some images) |
| Seccomp | none (Seccomp: 0) |
allowlist, default ERRNO |
Namespace creation via clone, mount, ptrace, bpf, module loading, open_by_handle_at |
Abuse of syscalls that remain allowed | Highest false-positive risk of any control here; see Seccomp profile |
| Root filesystem | writable | read_only: true + 8 MiB noexec tmpfs on /tmp |
Persisting a payload or tampering with binaries in the image layer | Memory-only attacks; writes to any mounted volume | Every writable path must be enumerated; apps that write to /var/cache break at runtime |
| Resource limits | none | 128 MiB (no swap), 64 PIDs, 0.5 CPU | Memory exhaustion, fork exhaustion, CPU starvation of neighbours | Network or disk-bandwidth exhaustion | An undersized limit is an availability incident, not a security event; size from measured peaks |
| Namespaces | pid: host |
own PID namespace | Enumerating and signalling host processes | — | None for this app |
| Socket / mounts | Docker socket, writable host dir | none | Daemon API access (host-root equivalent), host file tampering | — | CI runners and reverse proxies often want the socket; give them a socket proxy or a rootless daemon instead |
| Network | default bridge, 0.0.0.0:8080 |
internal: true, no published port |
Egress to anything outside the network; reachability of the canary | Abuse of what the app is allowed to talk to | An internal-only service needs a second hop for ingress (a proxy on both networks) |
| Supply chain | unpinned tag, no signature | digest pins, SBOM, cosign signature + attestation | Tag substitution; unverified bytes | A compromised build pipeline that signs bad bytes | Digest pins stop receiving base-image fixes until bumped (observed below) |
Seccomp profile¶
I did not copy a profile. scripts/gen-seccomp.sh extracts /app/posture from the built image, runs it under
strace -f for the service workload and the lab-harness subcommands, removes a fixed deny list the probe attempts on
purpose (strace records an attempt even when the kernel refuses it, so without this step the profile would learn the
attacks), and emits a default-ERRNO allowlist. Observed on this run:
service syscalls allowed : 41
runtime hand-off allowed : 3 ['fstatfs', 'statfs', 'statx']
harness-only allowed : 9 ['dup3', 'mkdirat', 'newfstatat', 'pidfd_open', 'pidfd_send_signal', 'pipe2', 'readlinkat', 'unlinkat', 'waitid']
observed but removed : 4 ['fchownat', 'mknodat', 'mount', 'umount2']
Status: tested locally. The output above is from the run that generated the committed hardened/seccomp.json.
Three things I learned the hard way, all observed:
- An application trace is not enough. The first profile left the container unable to start:
runc inititself issues syscalls after the filter is loaded and beforeexecve. On runc 1.5.2 the failure walked fromfstatfstostatxbefore the container came up. That "hand-off" set is runtime-version dependent; re-derive it when runc changes. cloneneeds an argument filter, not an allow. The profile allowscloneonly whenflags & 0x7E020000 == 0(the namespace flags) and returnsENOSYSforclone3, because seccomp cannot inspect theclone3flags struct and libc/Go fall back toclone. This matches the structure of Moby's default profile (source-reviewed:moby/profilesseccomp/default.json, which uses the same2114060288mask anderrnoRet: 38forclone3whenCAP_SYS_ADMINis absent).- A denial is only evidence if you know which layer produced it.
mount,chown,mknodand raw sockets are refused by capability checks as well, so they cannot show that seccomp works. User-namespace creation throughclone(CLONE_NEWUSER)needs no capability (Docker's seccomp documentation calls this out), so it is the discriminating probe. I also triedunshare(CLONE_NEWUSER)first and gotEINVALeven with every restriction off (tested locally).unshare(2)documentsEINVALforCLONE_NEWUSERwhen the caller is multithreaded (source-reviewed), and a Go program is always multithreaded. A probe that fails for an unrelated reason would have looked like a pass.
The default action is ERRNO, not KILL. A missed syscall then degrades one request instead of killing PID 1 and
restart-looping the service. The cost is that a blocked syscall can be swallowed by code that ignores errors.
Image scanning: what the numbers say, and what they do not¶
This is where my expectation was wrong, so I am recording it as found. tested locally, Trivy 0.76.1, vulnerability DB
updated 2026-11-04 19:02 UTC, both images built from golang:1.27-alpine (Go 1.27.3):
| Measure | insecure (alpine 3.24.3 + toolchain) |
hardened (debian 12.15 distroless) |
|---|---|---|
| Unique CVE/package findings | 0 | 4 (all UNKNOWN severity: Debian LTS advisories against ca-certificates and tzdata; fixed versions exist) |
SBOM-only scan (trivy sbom on the Syft CycloneDX file) |
0 | 4 (agrees with the image scan) |
| SBOM components by type | 39 library, 213 file, 1 application, 1 OS | 7 library, 950 file, 1 OS |
| Executable files in the image | 86 | 10 |
| Shell / package manager / compiler | ash+sh / apk / go |
none / none / none |
| Image content size | 356,984,047 bytes | 9,404,585 bytes |
Reading it correctly:
- A CVE count did not rank these images by risk. The image with a shell, a package manager and a compiler had no known
vulnerabilities on the day it was scanned; the hardened image had four. The hardened image's attack surface is far
smaller, which is why the lab measures it directly (
tests/inventory.pywalks the exported filesystem) instead of trusting scan counts. - The hardened image is older on purpose, and that is a trade. Pinning the distroless base by digest makes the build reproducible and stops a registry-side tag move from changing what you run. It also freezes the base at the digest I pinned, so Debian updates that landed afterwards show up as findings. Digest pinning only works with automation that bumps the digest (Renovate/Dependabot or a scheduled rebuild) and re-scans. I did not build that automation here.
- Raw counts mislead; deduplicate. An earlier scan of the same two images built from
golang:1.24-alpinereported 976 raw findings for the insecure image, which collapse to 116 unique CVE/package pairs because the same Go standard-library CVEs repeat for every Go binary in the toolchain. The hardened image, then, carried 23 HIGH findings from the toolchain's standard library. Those two scans are kept as a clearly-labeled one-off record,observation-go124-toolchain-scan.json, and cannot be regenerated: the images no longer exist and the DB moves daily. Moving the builder to a supported toolchain removed them. The lesson is that "distroless" does not mean "no findings": a statically linked Go binary carries its toolchain's standard library. - SBOM totals are not comparable. 958 vs 254 components looks like the opposite of the truth; file-level components
(every zoneinfo file in
tzdata) dominate. Compare package-level components. - Trivy's Dockerfile checks agreed with my gate on the big items. It flagged the insecure Dockerfile for root user
(
DS-0002, HIGH), noHEALTHCHECK(DS-0026) and the secret-shapedENV(DS-0031, CRITICAL) and reported nothing for the hardened one. My gate reports 30 findings vs 0 because it also covers Compose.
Signing: what local-only signing proves¶
scripts/sign-verify.sh runs a registry:2 container on loopback, generates an ephemeral key pair with a random
one-time password (never written to disk or committed), and signs with an empty signing config (no Fulcio, Rekor or TSA).
cosign v3 deprecates --tlog-upload=false; an explicit empty signing config is the supported way to say "no transparency
service". Results (tested locally, evidence/signing__summary.json):
| Case | Expected | Observed |
|---|---|---|
| Verify the signed hardened digest, right key | accept | accepted |
| Verify the unsigned insecure digest | reject | rejected (no signatures found) |
| Verify the signed digest with an unrelated key | reject | rejected |
| Verify by tag, then re-point the tag at different content and verify again | accept, then reject | accepted, then rejected |
Verify the SBOM attestation (cyclonedx) |
accept | accepted |
Verify the same digest as slsaprovenance |
reject | rejected |
This proves the mechanics: a signature binds to a digest, so tag substitution fails verification. It does not prove:
who signed (the key is anonymous), when (no transparency log or timestamp), or that the signer was your pipeline. Production
needs keyless signing bound to a CI workload identity or a KMS/HSM key, a transparency log, and verification at admission
against a pinned identity. The existing Kubernetes lab contains the admission-side
ImageValidatingPolicy and its offline model; neither is exercised against a real signature here.
Validation¶
All commands run from the repository root. Environment for the recorded run (evidence/versions.txt): Linux kernel
6.18.44, Docker Engine 29.9.2 (overlayfs snapshotter, cgroup v1), Compose 5.6.1, runc 1.5.2, Trivy 0.76.1, Syft 1.56.0,
cosign v3.1.4, strace 6.8. docker info listed only seccomp under security options.
node --test labs/docker-security/tests/policy-check.test.js # no Docker needed
bash labs/docker-security/scripts/run-lab.sh --publish-evidence # needs a disposable Docker host
Static gate (tested locally, no Docker)¶
node labs/docker-security/tests/policy-check.js labs/docker-security/insecure → 30 findings, exit 1.
... hardened → 0 findings, exit 0. 38 unit tests pass: one positive and one negative case per rule, plus the cases
below. Writing them found a real defect in my own rule: docker.sock:ro evaded the socket rule because the regex anchored
on end-of-string. A read-only mount of a socket file does not restrict API calls, so the rule now matches :ro,
containerd.sock, podman.sock and crio.sock as well.
Runtime comparison (tested locally)¶
Observed from inside the running service containers via docker compose exec ... probe (evidence/runtime__*-probe.json):
| Observation | Insecure | Hardened |
|---|---|---|
| Effective uid | 0 | 65532 |
CapEff |
000001fffeffffff (40 capabilities, no SYS_RESOURCE because this VM drops it) |
0000000000000000 |
NoNewPrivs / Seccomp |
0 / 0 (off) | 1 / 2 (filter, 1 filter) |
| Root filesystem | writable | read-only |
| Memory / PIDs / CPU | unlimited / unlimited / unlimited | 134217728 / 64 / 50000 µs per 100000 |
| Visible processes, PID 1 | 96, the VM's init (host PID namespace) |
2, posture |
write_root_filesystem |
allowed | EROFS |
write_tmp_scratch |
allowed | allowed (the app still works) |
chown_to_other_uid, mknod_char_device, raw_socket, mount_tmpfs |
allowed | EPERM each |
clone_new_user_namespace |
allowed | EPERM |
| Docker socket | present, GET /_ping → HTTP/1.0 200 OK |
ENOENT |
| Bind-mounted host directory | read and write allowed; file written by the container is owned by uid 0 on the host | ENOENT |
| TCP to the canary service | allowed | blocked, name does not resolve (different network) |
Seccomp attribution controls (same user, caps dropped, no-new-privileges, read-only; only --security-opt seccomp
varies, evidence/runtime__hardened-seccomp-*-probe.json):
| seccomp setting | Seccomp mode |
clone(CLONE_NEWUSER) |
|---|---|---|
unconfined |
0 | allowed |
| Docker default profile | 2 | EPERM |
| this lab's derived profile | 2 | EPERM |
With capabilities already empty, the only thing that changes between rows is the seccomp setting. That is what makes the denial attributable to the filter.
Resource limits:
| Test | Insecure | Hardened |
|---|---|---|
forktest 200 (bounded: sleeping children, then exit) |
200 started | 13 started, EAGAIN (Go runtime threads count against the 64-PID limit) |
memtest 512 (touch 512 MiB) |
exit 0 | killed, exit 137; last progress line touched_mib: 112 |
After the hardened OOM kill, Docker reported running oom_killed=true health=healthy. The kernel killed the exec'd test
process, not PID 1, so the service stayed up. That is OOM victim selection, not a guarantee: a leak in the service itself
would be the victim, and Docker's own documentation notes the kernel kills processes in a container when it hits its
limit. Treat limits as availability controls.
What the lab asserts¶
run-lab.sh ends by running tests/runtime_check.py, which exits nonzero when any observed value differs from the claims
above: 85 passed, 0 failed on the recorded run. Supply-chain assertions print SKIP with the recorded reason when
Trivy, Syft or cosign are absent, never a silent pass.
What was not tested¶
- AppArmor / SELinux profiles.
docker infoshowedname=seccomponly;/sys/kernel/security/lsmdoes not exist on this VM kernel, so no LSM profile could be loaded. Not executed. Docker's security documentation describes AppArmor and SELinux as an additional layer; whatever a production host adds on top of the controls measured here is unmeasured. - Rootless Docker and
userns-remap. Not executed. These change what "uid 0 in the container" means and are the control I would add for workloads that must run as root. - cgroup v2. The run was on cgroup v1. The probe reads both layouts, but the v2 paths were not exercised.
- Windows, macOS/Docker Desktop, Podman, containerd-direct.
- Hosted CI.
run-lab.shis not part ofnpm run verify:native-labs; adding a privileged-container job to the gating workflow without a hosted-runner trial would risk blocking publication. Static tests are innpm run validate. - Keyless signing, Rekor, a transparency-log-backed verification, KMS keys. Local ephemeral key only.
- Runtime detection (Falco, Tetragon, auditd) for the behaviours the probe exercises. See the Linux telemetry lab for synthetic detection logic.
- Escape techniques. The lab does not attempt container escapes, and a passing run is not a claim that none exist.
- Reproducible builds. The two images rebuild with different digests each time;
-trimpathand a pinned builder narrow the gap but I did not verify bit-for-bit reproducibility.
Production considerations¶
Rollout. Do not enable everything at once. Order by blast radius and ease of rollback: (1) digest pins and non-root,
(2) no-new-privileges and cap_drop: ALL with a measured add-back list, (3) read-only root with a tmpfs inventory,
(4) resource limits from observed peaks plus headroom, (5) seccomp last, in a lower environment first.
For seccomp, ship SCMP_ACT_LOG (needs auditd/journald) for at least one full release cycle and review the denied
syscalls before switching to ERRNO; this lab went straight to ERRNO because its workload is fully enumerated.
False positives. The things that break first are exactly the things hardening removes: apps that write outside
declared paths (EROFS), images that expect root-owned volumes (EACCES), services that silently ignore EPERM
from a blocked syscall, setuid helpers, JIT runtimes and anything calling clone3. A seccomp profile learned from a
bounded workload will miss rare paths (a reload handler, a crash dumper, a TLS renegotiation path); mitigate with
staged LOG mode, a regression test that exercises every code path, and a per-service exception process.
Detection. Alert on the configuration, not only the behaviour: privileged, cap_add, docker.sock mounts,
pid: host, seccomp=unconfined and writable host bind mounts at CI/admission time (this lab's gate is a starting point).
At runtime, a container that performs mount, namespace creation or writes to a read-only path is a signal only if you collect
the denial; EPERM from seccomp is silent unless you configure logging. I did not test a runtime sensor.
Operability. Debugging a shell-less image needs a documented procedure (ephemeral debug container sharing the PID
namespace, or a debug tag of the image that is never deployed to production). Health checks must not assume curl.
Exit 137 after a limit change is the OOM killer, not a crash loop. Track image age: a digest-pinned base that nobody bumps
becomes the scan finding you are paying to avoid.
Blast radius. Even fully hardened, containers share the host kernel. The controls here shrink reachable kernel surface and what an attacker can do post-exploit; they do not make this safe for hostile multi-tenant code. For that, add a user-namespaced or VM-isolated runtime (gVisor, Kata, Firecracker) and say so in the threat model.
Rollback. Everything is declarative: revert the image digest or the Compose file. Keep the previous profile versioned
beside the image tag. The break-glass setting seccomp=unconfined is dangerous precisely because it works; make it a
time-boxed exception that alerts, never a default fix for a failing deploy.
Reproduce¶
Prerequisites: Docker Engine with Compose v2, Node.js 22+ (npm ci --ignore-scripts for the yaml dependency),
Python 3. Optional, each recorded as not executed when absent: trivy, syft, cosign (versions above), and strace
only to regenerate the profile.
npm ci --ignore-scripts
node --test labs/docker-security/tests/policy-check.test.js
bash labs/docker-security/scripts/run-lab.sh # raw output in .artifacts/research/docker-security/
bash labs/docker-security/scripts/gen-seccomp.sh # optional: regenerate hardened/seccomp.json
Expect Trivy results to differ from the table above: the vulnerability database changes daily, and Docker Hub may rate-limit base-image pulls (I hit HTTP 429 once during development; a retry succeeded).
Teardown. run-lab.sh removes both stacks, the registry container, the canary directory and its temp key material on
exit. Images (dockerlab/posture:*) and the base-image cache remain; remove them with docker image rm.
References¶
Only sources I read while building this lab. The vendor documentation sites were not reachable from the build environment, so documentation is cited at its source repository, which is the file I actually read.
- Docker documentation source, seccomp security profiles: default profile is an allowlist, 44 syscalls blocked out of 300+,
clonenamespace gating and theCLONE_NEWUSERexception. - Moby, default seccomp profile:
cloneargument mask2114060288,clone3→errnoRet: 38withoutCAP_SYS_ADMIN. - Docker documentation source, resource constraints: OOM behaviour,
--memory-swapsemantics. - Docker documentation source, Docker Engine security (AppArmor/SELinux as an additional layer) and build best practices (multi-stage builds, minimal base images, pinning to a digest, updating pins on a schedule).
- Linux man-pages, unshare(2):
EINVALforCLONE_NEWUSERfrom a multithreaded caller. - Linux kernel documentation, seccomp BPF filters and no_new_privs: a filter requires
no_new_privsorCAP_SYS_ADMIN. - Sigstore, cosign sign reference. Flag behaviour for v3.1.4 (signing config, deprecated
--tlog-upload) was read from the binary's own error text andsigning-config create --help. - Trivy, Syft, cosign, Docker, runc and Compose versions: the tools' own
versionoutput, recorded inevidence/versions.txt.