carlos / platform Public

Fix group bootstrap staging on noexec Debian mounts

Move the verified bootstrap and chrony staging to a root-only directory on the root disk. Refuse noexec and recheck the pinned hash before all three executions.
Co-Authored-By: GPT-6 Astra <noreply@openai.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 1a4a565c25cd1f000e3364bd0c1ff9145fe34a57 parent f6f91e2
4 files changed, +530 −19
  • infra/modules/region-host/group-init.sh.tftpl +59 −13
  • internal/host/group_boot_budget_test.go +26 −5
  • internal/host/group_boot_staging_test.go +444 −0
  • internal/host/group_boot_test.go +1 −1
diff --git a/infra/modules/region-host/group-init.sh.tftpl b/infra/modules/region-host/group-init.sh.tftpl
index df4abd22c..df68e9b9c 100644
--- a/infra/modules/region-host/group-init.sh.tftpl
+++ b/infra/modules/region-host/group-init.sh.tftpl
@@ -16,27 +16,66 @@ fi
export DEBIAN_FRONTEND=noninteractive AWS_MAX_ATTEMPTS=1 AWS_RETRY_MODE=standard
# Only root-owned real directories may hold boot inputs or executed bytes.
+# Staging is on the root disk, never a tmpfs, which may be mounted noexec.
python3 - <<'PY'
import os, stat
-for path in ['/etc/apt/apt.conf.d', '/etc/needrestart/conf.d', '/etc/carlos', '/etc/chrony/conf.d', '/etc/systemd/system/carlos-edge.service.d', '/run/carlos-group-boot']:
+WORK = '/var/lib/carlos-group-boot'
+for path in ['/etc/apt/apt.conf.d', '/etc/needrestart/conf.d', '/etc/carlos', '/etc/chrony/conf.d', '/etc/systemd/system/carlos-edge.service.d', WORK]:
fd = os.open('/', os.O_RDONLY | os.O_DIRECTORY)
try:
- for part in path.strip('/').split('/'):
+ parts = path.strip('/').split('/')
+ for n, part in enumerate(parts):
+ final = path == WORK and n == len(parts) - 1
+ mode = 0o700 if final else 0o755
try:
- os.mkdir(part, 0o755, dir_fd=fd)
- os.chmod(part, 0o755, dir_fd=fd, follow_symlinks=False)
+ os.mkdir(part, mode, dir_fd=fd)
+ os.chmod(part, mode, dir_fd=fd, follow_symlinks=False)
except FileExistsError:
pass
child = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=fd)
os.close(fd)
fd = child
st = os.fstat(fd)
- if st.st_uid != 0 or st.st_mode & 0o022:
+ if final:
+ if st.st_uid != 0 or st.st_gid != 0 or stat.S_IMODE(st.st_mode) != 0o700:
+ raise SystemExit('group_boot_directory')
+ elif st.st_uid != 0 or st.st_mode & 0o022:
raise SystemExit('group_boot_directory')
finally:
os.close(fd)
PY
+# Every execution of the bootstrap is preceded by this check of the staging
+# directory, the noexec flag and the bootstrap bytes against the SSM digest.
+# noclobber makes the redirect fail on an existing file or symlink.
+( set -C; cat > /var/lib/carlos-group-boot/carlos_group_boot_verify.py <<'PYVERIFY'
+import hashlib, os, re, stat, sys
+WORK = '/var/lib/carlos-group-boot'
+def regular(path, mode, owner):
+ fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)
+ f = os.fdopen(fd, 'rb')
+ st = os.fstat(fd)
+ if not stat.S_ISREG(st.st_mode) or (st.st_uid, st.st_gid) != owner or stat.S_IMODE(st.st_mode) != mode or st.st_nlink != 1:
+ raise SystemExit('group_boot_bootstrap')
+ return f
+def check(work=WORK, owner=(0, 0)):
+ st = os.lstat(work)
+ if not stat.S_ISDIR(st.st_mode) or (st.st_uid, st.st_gid) != owner or stat.S_IMODE(st.st_mode) != 0o700:
+ raise SystemExit('group_boot_directory')
+ if os.statvfs(work).f_flag & os.ST_NOEXEC:
+ raise SystemExit('group_boot_noexec')
+ with regular(work + '/bootstrap.sha256', 0o600, owner) as f:
+ want = f.read(65).decode()
+ if not re.fullmatch('[0-9a-f]{64}', want):
+ raise SystemExit('group_boot_hash')
+ with regular(work + '/bootstrap', 0o700, owner) as f:
+ if hashlib.file_digest(f, 'sha256').hexdigest() != want:
+ raise SystemExit('group_boot_hash')
+if __name__ == '__main__':
+ check()
+PYVERIFY
+)
+
# disable unattended updates
systemctl disable --now apt-daily.timer apt-daily-upgrade.timer
systemctl mask --now apt-daily.timer apt-daily-upgrade.timer apt-daily.service apt-daily-upgrade.service unattended-upgrades.service
@@ -101,8 +140,8 @@ systemctl restart nftables.service
nft list table inet carlos_group_imds >/dev/null
# configure chrony
-printf '%s\n' 'server 169.254.169.123 prefer iburst minpoll 4 maxpoll 4' > /run/carlos-group-boot/chrony.conf
-install -o root -g root -m 0644 /run/carlos-group-boot/chrony.conf /etc/chrony/conf.d/carlos-group.conf
+printf '%s\n' 'server 169.254.169.123 prefer iburst minpoll 4 maxpoll 4' > /var/lib/carlos-group-boot/chrony.conf
+install -o root -g root -m 0644 /var/lib/carlos-group-boot/chrony.conf /etc/chrony/conf.d/carlos-group.conf
systemctl enable chrony.service
systemctl restart chrony.service
python3 - <<'PYCHRONY'
@@ -129,9 +168,9 @@ chronyc waitsync 20 2
# no published floor. Root binds this choice in group.json's config_digest;
# a published floor is always verified. Box roles cannot write this SSM value.
python3 - <<'PY'
-import base64, datetime, hashlib, ipaddress, json, os, re, subprocess, time, urllib.request
+import base64, datetime, hashlib, ipaddress, json, os, re, subprocess, sys, time, urllib.request
E = os.environ
-work = '/run/carlos-group-boot/'
+work = '/var/lib/carlos-group-boot/'
prefix = '/carlos/' + E['CARLOS_DEPLOYMENT'] + '/' + E['CARLOS_REGION'] + '/boot/'
def aws(*args, region=None):
return json.loads(subprocess.check_output(['aws', '--region', region or E['AWS_REGION'], '--cli-connect-timeout', '2', '--cli-read-timeout', '60', *args, '--output', 'json'], timeout=90))
@@ -164,7 +203,11 @@ aws('s3api', 'get-object', '--bucket', E['CARLOS_DEPLOYMENT_BUCKET'], '--key', o
with open(work + 'bootstrap', 'rb') as f:
if hashlib.file_digest(f, 'sha256').hexdigest() != sha:
raise SystemExit('group_boot_hash')
-os.chmod(work + 'bootstrap', 0o755)
+os.chmod(work + 'bootstrap', 0o700)
+write(work + 'bootstrap.sha256', sha.encode(), 0o600)
+sys.dont_write_bytecode = True
+sys.path.insert(0, work)
+import carlos_group_boot_verify as boot_verify
# Seven IMDS requests, reused through root snapshots. No runtime address poll.
class NoMetadataRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, request, response, code, message, headers, target):
@@ -228,6 +271,7 @@ marker['config_digest'] = hashlib.sha256(json.dumps(marker, sort_keys=True, sepa
write('/etc/carlos/group.json', json.dumps(marker, separators=(',', ':')).encode())
# Verify the signed document against the root marker before publishing the
# address snapshot. The public-IP leaf's provenance is protected IMDSv2.
+boot_verify.check()
subprocess.check_call([work + 'bootstrap', 'instance-control', '--group-hairpin-verify-identity'], timeout=10)
write('/etc/carlos/group-ingress.json', json.dumps(dict(v=1, region=E['CARLOS_REGION'], public_ips=ips, public_ipv4=public_ip, primary_ipv4=primary_ip, private_cidr=private_cidr, boot_id=boot_id, account=identity['accountId'], iid=iid), separators=(',', ':')).encode())
PY
@@ -254,7 +298,8 @@ for path, body in files.items():
os.fsync(f.fileno())
PYHAIRPIN
sysctl -p /etc/sysctl.d/99-carlos-hairpin.conf
-/run/carlos-group-boot/bootstrap instance-control --group-hairpin-install
+python3 -I /var/lib/carlos-group-boot/carlos_group_boot_verify.py
+/var/lib/carlos-group-boot/bootstrap instance-control --group-hairpin-install
# Persist only the dormant owned tables; never persist assigned EIPs or an
# exemption. On reboot the reset operation refuses a stale boot snapshot.
python3 - <<'PYHAIRPIN'
@@ -273,11 +318,12 @@ PYHAIRPIN
test "$(cat /etc/systemd/system/carlos-edge.service.d/50-group.conf)" = "$(printf '[Unit]\nRequires=nftables.service\nAfter=nftables.service\n\n[Service]\nRestart=no')"
# bootstrap and install channel
-/run/carlos-group-boot/bootstrap system host-env write --group --deployment "$CARLOS_DEPLOYMENT" --region "$CARLOS_REGION" --aws-region "$AWS_REGION" --install
+python3 -I /var/lib/carlos-group-boot/carlos_group_boot_verify.py
+/var/lib/carlos-group-boot/bootstrap system host-env write --group --deployment "$CARLOS_DEPLOYMENT" --region "$CARLOS_REGION" --aws-region "$AWS_REGION" --install
# host.env is parsed as data by the verified binary; it is never sourced.
# start guarded agent
systemctl daemon-reload
test "$(systemctl show carlos-edge.service --property=Restart --value)" = no
systemctl start carlos-edge.service
-rm -rf /run/carlos-group-boot
+rm -rf /var/lib/carlos-group-boot
diff --git a/internal/host/group_boot_budget_test.go b/internal/host/group_boot_budget_test.go
index ed6567e27..2e6cbbf49 100644
--- a/internal/host/group_boot_budget_test.go
+++ b/internal/host/group_boot_budget_test.go
@@ -279,6 +279,16 @@ func groupBootstrapBudget(t *testing.T) {
import ast, builtins, io, json, os, subprocess, hashlib, urllib.request, datetime
source = SOURCE
floor = FLOOR
+failcheck = FAILCHECK
+import sys, types
+checks = 0
+verifier = types.ModuleType('carlos_group_boot_verify')
+def check(*args, **kwargs):
+ global checks
+ checks += 1
+ if failcheck: raise SystemExit('group_boot_hash')
+verifier.check = check
+sys.modules['carlos_group_boot_verify'] = verifier
root='/carlos/dev/ie/boot/'
os.environ.update(dict(CARLOS_DEPLOYMENT='dev',CARLOS_REGION='ie',AWS_REGION='eu-west-1',CARLOS_BOOTSTRAP_OBJECT_KEY=root+'bootstrap-object',CARLOS_BOOTSTRAP_HASH_KEY=root+'bootstrap-sha256',CARLOS_TERMINATION_QUEUE_URL='queue',CARLOS_DEPLOYMENT_BUCKET='deploy',CARLOS_GROUP_ACCOUNT='123456789012',CARLOS_PLACEMENT_REGION='ie',CARLOS_INGRESS_KEY=root+'ingress',CARLOS_GROUP_DATA_BUCKET='data',CARLOS_GROUP_NAME='dev-ie',CARLOS_LAUNCH_HOOK_NAME='carlos-initial-launch',CARLOS_POOLS='hapair',CARLOS_RELEASE='v1.2.3'))
calls=[];decryptions=0;metadata=[]
@@ -316,12 +326,13 @@ urllib.request.build_opener=lambda *args:type("Opener",(),{"open":staticmethod(u
verified_identity=False
def verify_identity(args,timeout):
global verified_identity
- assert args==['/run/carlos-group-boot/bootstrap','instance-control','--group-hairpin-verify-identity'] and timeout==10
+ assert args==['/var/lib/carlos-group-boot/bootstrap','instance-control','--group-hairpin-verify-identity'] and timeout==10
+ assert checks==1, 'bootstrap executed without the shared verification'
verified_identity=True
subprocess.check_call=verify_identity
realopen=builtins.open
def fakeopen(path,*args,**kwargs):
- if path=='/run/carlos-group-boot/bootstrap':return io.BytesIO(b'bootstrap')
+ if path=='/var/lib/carlos-group-boot/bootstrap':return io.BytesIO(b'bootstrap')
if path=='/proc/sys/kernel/random/boot_id':return io.StringIO('boot')
raise AssertionError('unexpected file '+path)
builtins.open=fakeopen
@@ -329,6 +340,8 @@ os.chmod=lambda *args:None
writes=[];marker=None
def write(path,body,mode=0o644):
global marker
+ if path=='/var/lib/carlos-group-boot/bootstrap.sha256':
+ assert body==hashlib.sha256(b'bootstrap').hexdigest().encode() and mode==0o600
if path=='/etc/carlos/group.json':
marker=json.loads(body)
assert marker['floor']==floor
@@ -344,24 +357,32 @@ tree.body=[n for n in tree.body if not isinstance(n,ast.FunctionDef) or n.name!=
try:
exec(compile(tree,'group-init.sh.tftpl','exec'))
except SystemExit as err:
+ if failcheck:
+ assert str(err)=='group_boot_hash' and checks==1 and not verified_identity and '/etc/carlos/group-ingress.json' not in writes,(err,writes)
+ print('mutated bootstrap refused before exec')
+ raise SystemExit(0)
assert floor not in ('required','absent-expected') and str(err)=='group_boot_object',err
assert len(calls)==1 and not metadata and not writes,(calls,metadata,writes)
print('invalid floor refused before bootstrap fetch')
raise SystemExit(0)
assert floor in ('required','absent-expected'), 'invalid floor accepted'
assert len(calls)==3 and decryptions==4 and len(metadata)==7,(calls,decryptions,metadata)
-assert len(writes)==4,writes
+assert not failcheck and checks==1 and len(writes)==5,(checks,writes)
print(json.dumps(marker))
`
source, _ := json.Marshal(string(raw)[start : start+end])
program = strings.Replace(program, "SOURCE", string(source), 1)
- for _, floor := range []string{"absent-expected", "required", "", "none", "missing"} {
+ for _, floor := range []string{"absent-expected", "required", "", "none", "missing", "hash-mutation"} {
t.Run(floor, func(t *testing.T) {
value := fmt.Sprintf("%q", floor)
+ failcheck := "False"
if floor == "missing" {
value = "None"
}
- cmd := exec.Command("python3", "-c", strings.Replace(program, "FLOOR", value, 1))
+ if floor == "hash-mutation" {
+ value, failcheck = `"required"`, "True"
+ }
+ cmd := exec.Command("python3", "-c", strings.Replace(strings.Replace(program, "FAILCHECK", failcheck, 1), "FLOOR", value, 1))
cmd.Dir = t.TempDir()
out, err := cmd.CombinedOutput()
if err != nil {
diff --git a/internal/host/group_boot_staging_test.go b/internal/host/group_boot_staging_test.go
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
+ }
+ }
+ }
+ })
+}
diff --git a/internal/host/group_boot_test.go b/internal/host/group_boot_test.go
index 7e533a022..32d9b25d0 100644
--- a/internal/host/group_boot_test.go
+++ b/internal/host/group_boot_test.go
@@ -218,7 +218,7 @@ func assertGroupClockOrder(t *testing.T, s string) {
t.Helper()
last := -1
for _, command := range []string{
- "apt-get -y -q install", "install -o root -g root -m 0644 /run/carlos-group-boot/chrony.conf",
+ "apt-get -y -q install", "install -o root -g root -m 0644 /var/lib/carlos-group-boot/chrony.conf",
"systemctl restart chrony.service", "['chronyc', '-n', 'sources']", "chronyc waitsync 20 2", "response = aws('ssm'",
} {
n := strings.Index(s, command)