| new file mode 100644 |
| index 000000000..37ce99e76 |
| --- /dev/null |
| +++ b/internal/host/group_boot_staging_test.go |
| @@ -0,0 +1,444 @@ |
| +package host |
| + |
| +import ( |
| + "crypto/sha256" |
| + "encoding/hex" |
| + "fmt" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "regexp" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +const ( |
| + groupBootStaging = "/var/lib/carlos-group-boot" |
| + groupBootVerify = "python3 -I " + groupBootStaging + "/carlos_group_boot_verify.py" |
| +) |
| + |
| +func groupInitTemplate(t *testing.T) string { |
| + t.Helper() |
| + raw, err := os.ReadFile("../../infra/modules/region-host/group-init.sh.tftpl") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return string(raw) |
| +} |
| + |
| +// between returns the text between the first start marker and the next end marker. |
| +func between(t *testing.T, s, start, end string) string { |
| + t.Helper() |
| + _, rest, ok := strings.Cut(s, start) |
| + if !ok { |
| + t.Fatalf("missing %q", start) |
| + } |
| + body, _, ok := strings.Cut(rest, end) |
| + if !ok { |
| + t.Fatalf("missing %q", end) |
| + } |
| + return body |
| +} |
| + |
| +var groupBootTmpfs = regexp.MustCompile(`(^|[^A-Za-z0-9_./-])(/run|/tmp|/dev/shm|/var/tmp|/var/run)(/|$|[^A-Za-z0-9_.-])`) |
| + |
| +// checkGroupBootStaging inspects the paths the script stages, writes and |
| +// executes. Every bootstrap execution must be the line right after the shared |
| +// verification, and nothing may stage or run from a tmpfs default. |
| +func checkGroupBootStaging(s string) error { |
| + if n := strings.Count(s, "carlos-group-boot"); n != strings.Count(s, groupBootStaging) { |
| + return fmt.Errorf("staging name used outside %s", groupBootStaging) |
| + } |
| + if !strings.Contains(s, "WORK = '"+groupBootStaging+"'") || !strings.Contains(s, "work = '"+groupBootStaging+"/'") { |
| + return fmt.Errorf("staging constants are not %s", groupBootStaging) |
| + } |
| + // The one runtime directory the script names is a unit's ReadWritePaths. |
| + scan := strings.ReplaceAll(s, "ReadWritePaths=-/run/carlos-hairpin", "") |
| + if m := groupBootTmpfs.FindString(scan); m != "" { |
| + return fmt.Errorf("tmpfs path %q", strings.TrimSpace(m)) |
| + } |
| + for _, banned := range []string{"mktemp", "tempfile", "TMPDIR", "mkdtemp"} { |
| + if strings.Contains(s, banned) { |
| + return fmt.Errorf("default scratch location via %s", banned) |
| + } |
| + } |
| + lines := strings.Split(s, "\n") |
| + execs := 0 |
| + for i, line := range lines { |
| + if !strings.Contains(line, "bootstrap") || strings.Contains(line, "bootstrap.sha256") && !strings.Contains(line, "subprocess") { |
| + continue |
| + } |
| + prev := "" |
| + if i > 0 { |
| + prev = lines[i-1] |
| + } |
| + switch { |
| + case strings.HasPrefix(line, groupBootStaging+"/bootstrap "): |
| + execs++ |
| + if prev != groupBootVerify { |
| + return fmt.Errorf("line %d executes the bootstrap without the shared verification", i+1) |
| + } |
| + case strings.HasPrefix(line, "subprocess.check_call([work + 'bootstrap'"): |
| + execs++ |
| + if prev != "boot_verify.check()" { |
| + return fmt.Errorf("line %d executes the bootstrap without the shared verification", i+1) |
| + } |
| + case strings.Contains(line, "'get-object'") || strings.HasPrefix(line, "with open(work + 'bootstrap', 'rb')") || strings.HasPrefix(line, "os.chmod(work + 'bootstrap', 0o700)") || strings.HasPrefix(line, "write(work + 'bootstrap.sha256'") || strings.Contains(line, "bootstrap-object") || strings.Contains(line, "bootstrap-sha256") || strings.Contains(line, "BOOTSTRAP_") || strings.HasPrefix(line, "#") || strings.HasPrefix(line, "# ") || strings.Contains(line, "verified bootstrap") || strings.Contains(line, "regular(work + '/bootstrap"): |
| + default: |
| + return fmt.Errorf("line %d references the bootstrap outside the audited forms: %s", i+1, line) |
| + } |
| + } |
| + if execs != 3 { |
| + return fmt.Errorf("want 3 bootstrap executions, found %d", execs) |
| + } |
| + if strings.Count(s, groupBootVerify+"\n") != 2 || strings.Count(s, "boot_verify.check()\n") != 1 { |
| + return fmt.Errorf("verification call sites changed") |
| + } |
| + return nil |
| +} |
| + |
| +func TestGroupBootStagingGuard(t *testing.T) { |
| + good := groupInitTemplate(t) |
| + if err := checkGroupBootStaging(good); err != nil { |
| + t.Fatal(err) |
| + } |
| + install := groupBootStaging + "/bootstrap instance-control --group-hairpin-install" |
| + hostenv := groupBootStaging + "/bootstrap system host-env" |
| + mutants := map[string]func(string) string{ |
| + "run staging": func(s string) string { return strings.ReplaceAll(s, groupBootStaging, "/run/carlos-group-boot") }, |
| + "tmp staging": func(s string) string { return strings.ReplaceAll(s, groupBootStaging, "/tmp/carlos-group-boot") }, |
| + "dev shm staging": func(s string) string { return strings.ReplaceAll(s, groupBootStaging, "/dev/shm/carlos-group-boot") }, |
| + "var tmp staging": func(s string) string { return strings.ReplaceAll(s, groupBootStaging, "/var/tmp/carlos-group-boot") }, |
| + "var run staging": func(s string) string { return strings.ReplaceAll(s, groupBootStaging, "/var/run/carlos-group-boot") }, |
| + "one run exec": func(s string) string { |
| + return strings.Replace(s, install, "/run/carlos-group-boot/bootstrap instance-control --group-hairpin-install", 1) |
| + }, |
| + "python work only": func(s string) string { |
| + return strings.Replace(s, "work = '"+groupBootStaging+"/'", "work = '/run/carlos-group-boot/'", 1) |
| + }, |
| + "walker constant only": func(s string) string { |
| + return strings.Replace(s, "WORK = '"+groupBootStaging+"'", "WORK = '/dev/shm/carlos-group-boot'", 1) |
| + }, |
| + "chrony in tmp": func(s string) string { |
| + return strings.Replace(s, "> "+groupBootStaging+"/chrony.conf", "> /tmp/chrony.conf", 1) |
| + }, |
| + "mktemp scratch": func(s string) string { return strings.Replace(s, "umask 077\n", "umask 077\nD=$(mktemp -d)\n", 1) }, |
| + "install unverified": func(s string) string { return strings.Replace(s, groupBootVerify+"\n"+install, install, 1) }, |
| + "host-env unverified": func(s string) string { return strings.Replace(s, groupBootVerify+"\n"+hostenv, hostenv, 1) }, |
| + "python unverified": func(s string) string { |
| + return strings.Replace(s, "boot_verify.check()\nsubprocess.check_call([work", "subprocess.check_call([work", 1) |
| + }, |
| + "verify not adjacent": func(s string) string { |
| + return strings.Replace(s, groupBootVerify+"\n"+install, groupBootVerify+"\nsysctl -p /dev/null\n"+install, 1) |
| + }, |
| + "extra direct exec": func(s string) string { return s + groupBootStaging + "/bootstrap version\n" }, |
| + "extra shell wrapper": func(s string) string { return s + "sh " + groupBootStaging + "/bootstrap version\n" }, |
| + "extra python exec": func(s string) string { return s + "subprocess.run([work + 'bootstrap', 'x'])\n" }, |
| + "verify is not helper": func(s string) string { return strings.Replace(s, groupBootVerify+"\n"+install, "true\n"+install, 1) }, |
| + "python3 without -I": func(s string) string { |
| + return strings.Replace(s, groupBootVerify+"\n"+hostenv, "python3 "+strings.TrimPrefix(groupBootVerify, "python3 -I ")+"\n"+hostenv, 1) |
| + }, |
| + "other staging name": func(s string) string { |
| + return strings.Replace(s, groupBootStaging+"/chrony.conf", "/var/lib/carlos-group-boot-x/chrony.conf", 1) |
| + }, |
| + "var-run in rw paths": func(s string) string { return s + "ReadWritePaths=/var/run/x\n" }, |
| + "unlisted tmp argument": func(s string) string { return s + "cp x /tmp\n" }, |
| + } |
| + for name, mutate := range mutants { |
| + t.Run(name, func(t *testing.T) { |
| + bad := mutate(good) |
| + if bad == good { |
| + t.Fatal("mutation did not apply") |
| + } |
| + if err := checkGroupBootStaging(bad); err == nil { |
| + t.Fatal("guard accepted the mutant") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// walkerSource extracts the first Python block and points it at a scratch |
| +// root, expecting the current user in place of root. |
| +func walkerSource(t *testing.T, root string) string { |
| + t.Helper() |
| + src := between(t, groupInitTemplate(t), "python3 - <<'PY'\nimport os, stat\nWORK", "\nPY\n") |
| + src = "import os, stat\nWORK" + src |
| + for from, to := range map[string]string{ |
| + "os.open('/', os.O_RDONLY | os.O_DIRECTORY)": "os.open(" + fmt.Sprintf("%q", root) + ", os.O_RDONLY | os.O_DIRECTORY)", |
| + "st.st_uid != 0": fmt.Sprintf("st.st_uid != %d", os.Getuid()), |
| + "st.st_gid != 0": fmt.Sprintf("st.st_gid != %d", gidForTest(t)), |
| + } { |
| + if !strings.Contains(src, from) { |
| + t.Fatalf("walker no longer contains %q", from) |
| + } |
| + src = strings.ReplaceAll(src, from, to) |
| + } |
| + return src |
| +} |
| + |
| +func gidForTest(t *testing.T) int { |
| + t.Helper() |
| + return os.Getgid() |
| +} |
| + |
| +func runPython(t *testing.T, dir, code string) (string, error) { |
| + t.Helper() |
| + cmd := exec.Command("python3", "-I", "-c", code) |
| + cmd.Dir = dir |
| + out, err := cmd.CombinedOutput() |
| + return string(out), err |
| +} |
| + |
| +func TestGroupBootWalker(t *testing.T) { |
| + type tc struct { |
| + name string |
| + setup func(t *testing.T, root, work string) |
| + refuse string |
| + } |
| + cases := []tc{ |
| + {"fresh", func(t *testing.T, root, work string) {}, ""}, |
| + {"preexisting 0700", func(t *testing.T, root, work string) { mkdirMode(t, work, 0o700) }, ""}, |
| + {"preexisting 0755", func(t *testing.T, root, work string) { mkdirMode(t, work, 0o755) }, "group_boot_directory"}, |
| + {"preexisting 0750", func(t *testing.T, root, work string) { mkdirMode(t, work, 0o750) }, "group_boot_directory"}, |
| + {"preexisting 0710", func(t *testing.T, root, work string) { mkdirMode(t, work, 0o710) }, "group_boot_directory"}, |
| + {"preexisting 0600", func(t *testing.T, root, work string) { mkdirMode(t, work, 0o600) }, "group_boot_directory"}, |
| + {"final symlink", func(t *testing.T, root, work string) { |
| + target := filepath.Join(root, "elsewhere") |
| + mkdirMode(t, target, 0o700) |
| + if err := os.Symlink(target, work); err != nil { |
| + t.Fatal(err) |
| + } |
| + }, "ELOOP"}, |
| + {"parent symlink", func(t *testing.T, root, work string) { |
| + if err := os.RemoveAll(filepath.Join(root, "var", "lib")); err != nil { |
| + t.Fatal(err) |
| + } |
| + target := filepath.Join(root, "elsewhere") |
| + mkdirMode(t, target, 0o755) |
| + if err := os.Symlink(target, filepath.Join(root, "var", "lib")); err != nil { |
| + t.Fatal(err) |
| + } |
| + }, "ELOOP"}, |
| + {"dangling final symlink", func(t *testing.T, root, work string) { |
| + if err := os.Symlink(filepath.Join(root, "absent"), work); err != nil { |
| + t.Fatal(err) |
| + } |
| + }, "ELOOP"}, |
| + {"parent group writable", func(t *testing.T, root, work string) { |
| + if err := os.Chmod(filepath.Join(root, "var", "lib"), 0o775); err != nil { |
| + t.Fatal(err) |
| + } |
| + }, "group_boot_directory"}, |
| + } |
| + for _, c := range cases { |
| + t.Run(c.name, func(t *testing.T) { |
| + root := t.TempDir() |
| + mkdirMode(t, filepath.Join(root, "var"), 0o755) |
| + mkdirMode(t, filepath.Join(root, "var", "lib"), 0o755) |
| + work := filepath.Join(root, "var", "lib", "carlos-group-boot") |
| + c.setup(t, root, work) |
| + out, err := runPython(t, t.TempDir(), walkerSource(t, root)) |
| + if c.refuse == "" { |
| + if err != nil { |
| + t.Fatalf("refused: %v %s", err, out) |
| + } |
| + info, statErr := os.Lstat(work) |
| + if statErr != nil || !info.IsDir() || info.Mode().Perm() != 0o700 { |
| + t.Fatalf("work dir not 0700: %v %v", info, statErr) |
| + } |
| + return |
| + } |
| + if err == nil || !strings.Contains(out, c.refuse) && !strings.Contains(out, "Too many levels of symbolic links") { |
| + t.Fatalf("accepted: %v %s", err, out) |
| + } |
| + }) |
| + } |
| + t.Run("wrong group", func(t *testing.T) { |
| + root := t.TempDir() |
| + mkdirMode(t, filepath.Join(root, "var"), 0o755) |
| + mkdirMode(t, filepath.Join(root, "var", "lib"), 0o755) |
| + mkdirMode(t, filepath.Join(root, "var", "lib", "carlos-group-boot"), 0o700) |
| + src := strings.ReplaceAll(walkerSource(t, root), fmt.Sprintf("st.st_gid != %d", os.Getgid()), fmt.Sprintf("st.st_gid != %d", os.Getgid()+1)) |
| + out, err := runPython(t, t.TempDir(), src) |
| + if err == nil || !strings.Contains(out, "group_boot_directory") { |
| + t.Fatalf("foreign group accepted: %v %s", err, out) |
| + } |
| + }) |
| + t.Run("wrong owner", func(t *testing.T) { |
| + root := t.TempDir() |
| + mkdirMode(t, filepath.Join(root, "var"), 0o755) |
| + mkdirMode(t, filepath.Join(root, "var", "lib"), 0o755) |
| + mkdirMode(t, filepath.Join(root, "var", "lib", "carlos-group-boot"), 0o700) |
| + src := strings.ReplaceAll(walkerSource(t, root), fmt.Sprintf("st.st_uid != %d", os.Getuid()), fmt.Sprintf("st.st_uid != %d", os.Getuid()+1)) |
| + out, err := runPython(t, t.TempDir(), src) |
| + if err == nil || !strings.Contains(out, "group_boot_directory") { |
| + t.Fatalf("foreign owner accepted: %v %s", err, out) |
| + } |
| + }) |
| +} |
| + |
| +func mkdirMode(t *testing.T, path string, mode os.FileMode) { |
| + t.Helper() |
| + if err := os.Mkdir(path, mode); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.Chmod(path, mode); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func TestGroupBootVerifyHelper(t *testing.T) { |
| + template := groupInitTemplate(t) |
| + helper := between(t, template, "<<'PYVERIFY'\n", "\nPYVERIFY\n") + "\n" |
| + body := []byte("bootstrap bytes") |
| + sum := sha256.Sum256(body) |
| + digest := hex.EncodeToString(sum[:]) |
| + type tc struct { |
| + name string |
| + mutate func(t *testing.T, work string) |
| + noexec bool |
| + owner int |
| + want string |
| + } |
| + write := func(t *testing.T, path string, data []byte, mode os.FileMode) { |
| + t.Helper() |
| + if err := os.WriteFile(path, data, mode); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.Chmod(path, mode); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + cases := []tc{ |
| + {name: "intact"}, |
| + {name: "bootstrap bytes mutated", mutate: func(t *testing.T, w string) { write(t, w+"/bootstrap", []byte("bootstrap byteS"), 0o700) }, want: "group_boot_hash"}, |
| + {name: "bootstrap appended", mutate: func(t *testing.T, w string) { write(t, w+"/bootstrap", append(body, 0), 0o700) }, want: "group_boot_hash"}, |
| + {name: "digest file swapped", mutate: func(t *testing.T, w string) { write(t, w+"/bootstrap.sha256", []byte(strings.Repeat("0", 64)), 0o600) }, want: "group_boot_hash"}, |
| + {name: "digest malformed", mutate: func(t *testing.T, w string) { write(t, w+"/bootstrap.sha256", []byte("ABC"), 0o600) }, want: "group_boot_hash"}, |
| + {name: "digest uppercase", mutate: func(t *testing.T, w string) { write(t, w+"/bootstrap.sha256", []byte(strings.ToUpper(digest)), 0o600) }, want: "group_boot_hash"}, |
| + {name: "digest file mode 0644", mutate: func(t *testing.T, w string) { write(t, w+"/bootstrap.sha256", []byte(digest), 0o644) }, want: "group_boot_bootstrap"}, |
| + {name: "bootstrap mode 0755", mutate: func(t *testing.T, w string) { write(t, w+"/bootstrap", body, 0o755) }, want: "group_boot_bootstrap"}, |
| + {name: "bootstrap mode 0600", mutate: func(t *testing.T, w string) { write(t, w+"/bootstrap", body, 0o600) }, want: "group_boot_bootstrap"}, |
| + {name: "bootstrap hardlinked", mutate: func(t *testing.T, w string) { |
| + if err := os.Link(w+"/bootstrap", w+"/other"); err != nil { |
| + t.Fatal(err) |
| + } |
| + }, want: "group_boot_bootstrap"}, |
| + {name: "bootstrap symlink", mutate: func(t *testing.T, w string) { |
| + // A symlink to correct, correctly-moded bytes is still refused. |
| + write(t, w+"/real", body, 0o700) |
| + if err := os.Remove(w + "/bootstrap"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.Symlink(w+"/real", w+"/bootstrap"); err != nil { |
| + t.Fatal(err) |
| + } |
| + }, want: "Too many levels"}, |
| + {name: "digest symlink", mutate: func(t *testing.T, w string) { |
| + write(t, w+"/real", []byte(digest), 0o600) |
| + if err := os.Remove(w + "/bootstrap.sha256"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.Symlink(w+"/real", w+"/bootstrap.sha256"); err != nil { |
| + t.Fatal(err) |
| + } |
| + }, want: "Too many levels"}, |
| + {name: "bootstrap removed", mutate: func(t *testing.T, w string) { |
| + if err := os.Remove(w + "/bootstrap"); err != nil { |
| + t.Fatal(err) |
| + } |
| + }, want: "FileNotFoundError"}, |
| + {name: "bootstrap is directory", mutate: func(t *testing.T, w string) { |
| + if err := os.Remove(w + "/bootstrap"); err != nil { |
| + t.Fatal(err) |
| + } |
| + mkdirMode(t, w+"/bootstrap", 0o700) |
| + }, want: "group_boot_bootstrap"}, |
| + {name: "directory mode 0755", mutate: func(t *testing.T, w string) { |
| + if err := os.Chmod(w, 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + }, want: "group_boot_directory"}, |
| + {name: "directory mode 0500", mutate: func(t *testing.T, w string) { |
| + if err := os.Chmod(w, 0o500); err != nil { |
| + t.Fatal(err) |
| + } |
| + }, want: "group_boot_directory"}, |
| + {name: "foreign owner", owner: 1, want: "group_boot_directory"}, |
| + {name: "noexec mount", noexec: true, want: "group_boot_noexec"}, |
| + {name: "noexec wins over a bad hash", noexec: true, mutate: func(t *testing.T, w string) { write(t, w+"/bootstrap", []byte("x"), 0o700) }, want: "group_boot_noexec"}, |
| + } |
| + for _, c := range cases { |
| + t.Run(c.name, func(t *testing.T) { |
| + scratch := t.TempDir() |
| + write(t, scratch+"/carlos_group_boot_verify.py", []byte(helper), 0o600) |
| + work := filepath.Join(scratch, "work") |
| + mkdirMode(t, work, 0o700) |
| + write(t, work+"/bootstrap", body, 0o700) |
| + write(t, work+"/bootstrap.sha256", []byte(digest), 0o600) |
| + if c.mutate != nil { |
| + c.mutate(t, work) |
| + } |
| + stub := "" |
| + if c.noexec { |
| + stub = "os.statvfs = lambda path: type('V', (), {'f_flag': os.ST_NOEXEC})()\n" |
| + } |
| + code := fmt.Sprintf("import os, sys, traceback\nsys.dont_write_bytecode = True\nsys.path.insert(0, %q)\nimport carlos_group_boot_verify as v\n%s"+ |
| + "try:\n v.check(%q, (%d, %d))\nexcept SystemExit as err:\n print(err); sys.exit(3)\nexcept Exception:\n traceback.print_exc(); sys.exit(4)\n", |
| + scratch, stub, work, os.Getuid()+c.owner, os.Getgid()) |
| + out, err := runPython(t, scratch, code) |
| + if c.want == "" { |
| + if err != nil { |
| + t.Fatalf("refused: %v %s", err, out) |
| + } |
| + return |
| + } |
| + if err == nil || !strings.Contains(out, c.want) { |
| + t.Fatalf("want %s: %v %s", c.want, err, out) |
| + } |
| + }) |
| + } |
| + t.Run("default owner is root", func(t *testing.T) { |
| + if os.Getuid() == 0 { |
| + t.Skip("running as root") |
| + } |
| + scratch := t.TempDir() |
| + write(t, scratch+"/carlos_group_boot_verify.py", []byte(helper), 0o600) |
| + work := filepath.Join(scratch, "work") |
| + mkdirMode(t, work, 0o700) |
| + code := fmt.Sprintf("import sys\nsys.dont_write_bytecode = True\nsys.path.insert(0, %q)\nimport carlos_group_boot_verify as v\nv.check(%q)\n", scratch, work) |
| + out, err := runPython(t, scratch, code) |
| + if err == nil || !strings.Contains(out, "group_boot_directory") { |
| + t.Fatalf("non-root directory accepted by default: %v %s", err, out) |
| + } |
| + }) |
| + t.Run("each execution reverifies", func(t *testing.T) { |
| + // The three executions share one script. Mutating the bootstrap between |
| + // any two of them must fail the next one, so run the helper as a script |
| + // the way the shell does, three times, with a mutation before each. |
| + for target := 1; target <= 3; target++ { |
| + scratch := t.TempDir() |
| + write(t, scratch+"/carlos_group_boot_verify.py", []byte(strings.Replace(helper, " check()\n", fmt.Sprintf(" check(%q, (%d, %d))\n", scratch+"/work", os.Getuid(), os.Getgid()), 1)), 0o600) |
| + work := filepath.Join(scratch, "work") |
| + mkdirMode(t, work, 0o700) |
| + write(t, work+"/bootstrap", body, 0o700) |
| + write(t, work+"/bootstrap.sha256", []byte(digest), 0o600) |
| + for n := 1; n <= 3; n++ { |
| + if n == target { |
| + write(t, work+"/bootstrap", []byte("tampered"), 0o700) |
| + } |
| + cmd := exec.Command("python3", "-I", scratch+"/carlos_group_boot_verify.py") |
| + out, err := cmd.CombinedOutput() |
| + if n < target && err != nil { |
| + t.Fatalf("exec %d refused before mutation: %v %s", n, err, out) |
| + } |
| + if n == target { |
| + if err == nil || !strings.Contains(string(out), "group_boot_hash") { |
| + t.Fatalf("exec %d ran a mutated bootstrap: %v %s", n, err, out) |
| + } |
| + break |
| + } |
| + } |
| + } |
| + }) |
| +} |