diff --git a/server/execpriv_unix.go b/server/execpriv_unix.go index 9c6d730..f28bad9 100644 --- a/server/execpriv_unix.go +++ b/server/execpriv_unix.go @@ -302,12 +302,20 @@ func PrepareExecPrivilege(p *ExecPrivilege, dataDir, keyDir, configPath string) } path := filepath.Join(keyDir, name) if _, err := os.Stat(path); err == nil { + if err := ownByRoot(path); err != nil { + return fmt.Errorf("restrict %s to root: %w", path, err) + } if err := os.Chmod(path, 0o600); err != nil { return fmt.Errorf("restrict %s to root: %w", path, err) } } } if configPath != "" { + if _, err := os.Stat(configPath); err == nil { + if err := ownByRoot(configPath); err != nil { + return fmt.Errorf("restrict %s to root: %w", configPath, err) + } + } if fi, err := os.Stat(configPath); err == nil && fi.Mode().Perm()&0o077 != 0 { if err := os.Chmod(configPath, 0o600); err != nil { return fmt.Errorf("restrict %s to root: %w", configPath, err) @@ -322,6 +330,26 @@ func PrepareExecPrivilege(p *ExecPrivilege, dataDir, keyDir, configPath string) return nil } +// ownByRoot makes root the owner of a key or config file that another user owns: +// mode 0600 alone leaves the file readable by its owner, which could be the +// executor uid (a file created by an agent process, or on the host under the uid +// the executor has in the container). +func ownByRoot(path string) error { + fi, err := os.Stat(path) + if err != nil { + return err + } + st, ok := fi.Sys().(*syscall.Stat_t) + if !ok || st.Uid == 0 { + return nil + } + if err := os.Chown(path, 0, -1); err != nil { + return err + } + log.Printf("[exec] %s was owned by uid %d; it is now owned by root", path, st.Uid) + return nil +} + // runDirMode is the mode of a run directory: group-writable, and setgid so what is // created in it keeps the executor group. const runDirMode = 0o775 | os.ModeSetgid diff --git a/server/isolation_root_linux_test.go b/server/isolation_root_linux_test.go index 04c751c..1302287 100644 --- a/server/isolation_root_linux_test.go +++ b/server/isolation_root_linux_test.go @@ -4,9 +4,11 @@ package server import ( "os" + "os/exec" "path/filepath" "strconv" "strings" + "syscall" "testing" ) @@ -34,11 +36,11 @@ func newIsolationRootFixture(t *testing.T) *isolationRootFixture { t.Fatal(err) } } - config := filepath.Join(keyDir, "..", filepath.Base(f.data)+"-config.json") + // The config file lives in a root-only directory too (/app in the image). + config := filepath.Join(keyDir, "config.json") if err := os.WriteFile(config, []byte(`{"database":{"dsn":"postgres://u:pw@h/db"}}`), 0o600); err != nil { t.Fatal(err) } - t.Cleanup(func() { os.Remove(config) }) return &isolationRootFixture{execRootFixture: f, keyDir: keyDir, config: config} } @@ -87,6 +89,100 @@ func TestIsolationSelfTestDetectsMissingShimAsRoot(t *testing.T) { } } +// A key file and a config file owned by the executor uid stay readable by it after a +// chmod 0600: PrepareExecPrivilege makes root their owner, and the executor can then +// read neither (the self-test passes, and a direct read as the executor is denied). +func TestPrepareExecPrivilegeOwnsKeysAndConfigAsRoot(t *testing.T) { + f := newExecRootFixture(t) + keyDir := filepath.Join(f.tmp, "keys") + if err := os.Mkdir(keyDir, 0o755); err != nil { + t.Fatal(err) + } + key, config := filepath.Join(keyDir, "jwt.key"), filepath.Join(keyDir, "config.json") + for _, p := range []string{key, config} { + if err := os.WriteFile(p, []byte("secret-"+filepath.Base(p)), 0o644); err != nil { + t.Fatal(err) + } + if err := os.Chown(p, DefaultExecUID, DefaultExecGID); err != nil { + t.Fatal(err) + } + } + if err := PrepareExecPrivilege(&f.priv, f.data, keyDir, config); err != nil { + t.Fatal(err) + } + for _, p := range []string{key, config} { + fi, err := os.Stat(p) + if err != nil { + t.Fatal(err) + } + if st := fi.Sys().(*syscall.Stat_t); st.Uid != 0 || fi.Mode().Perm() != 0o600 { + t.Errorf("%s: uid %d mode %v, want root 0600", p, st.Uid, fi.Mode().Perm()) + } + } + c := exec.Command("sh", "-c", `for f in "$@"; do if cat "$f" >/dev/null 2>&1; then echo "read $f"; fi; done; echo done`, "sh", key, config) + applyExecCredential(c, f.priv) + out, err := c.CombinedOutput() + if err != nil || string(out) != "done\n" { + t.Fatalf("executor read of the key and config: %v\n%s", err, out) + } + if err := InstallBashShim(f.priv); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { os.RemoveAll(filepath.SplitList(os.Getenv("PATH"))[0]) }) + if err := IsolationSelfTest(f.priv, IsolationTargets{DataDir: f.data, KeyDir: keyDir, ConfigPath: config}); err != nil { + t.Fatalf("self-test after PrepareExecPrivilege: %v", err) + } +} + +// A data, key or config directory the executor can write fails the self-test: an +// agent process could plant a key, a config or a data tree for the next start. +func TestIsolationSelfTestDetectsWritableDirsAsRoot(t *testing.T) { + f := newIsolationRootFixture(t) + if err := os.Chmod(f.data, 0o777); err != nil { + t.Fatal(err) + } + err := IsolationSelfTest(f.priv, f.targets()) + if err == nil || !strings.Contains(err.Error(), "Bash can create files in "+f.data) { + t.Fatalf("self-test with a world-writable data directory: %v", err) + } + if err := os.Chmod(f.data, 0o755); err != nil { + t.Fatal(err) + } + if err := os.Chown(f.keyDir, DefaultExecUID, 0); err != nil { + t.Fatal(err) + } + err = IsolationSelfTest(f.priv, f.targets()) + if err == nil || !strings.Contains(err.Error(), "Bash can create files in "+f.keyDir) { + t.Fatalf("self-test with a key directory owned by the executor: %v", err) + } + if entries, _ := os.ReadDir(f.keyDir); len(entries) != 3 { + t.Fatalf("the probe left an entry in the key directory: %v", entries) + } +} + +// A data directory whose parent the executor can write (not sticky) can be renamed +// and replaced: the self-test reports it. +func TestIsolationSelfTestDetectsReplaceableParentAsRoot(t *testing.T) { + f := newIsolationRootFixture(t) + open := filepath.Join(f.tmp, "open-parent") + if err := os.Mkdir(open, 0o755); err != nil { + t.Fatal(err) + } + if err := os.Chmod(open, 0o777); err != nil { + t.Fatal(err) + } + data := filepath.Join(open, "data") + if err := os.Mkdir(data, 0o755); err != nil { + t.Fatal(err) + } + tg := f.targets() + tg.DataDir = data + err := IsolationSelfTest(f.priv, tg) + if err == nil || !strings.Contains(err.Error(), "an agent process can replace "+data) { + t.Fatalf("self-test with a replaceable data directory: %v", err) + } +} + // A database that lets the server's user in without a password fails the self-test: // the probe, as the executor, opens a session on it. func TestIsolationSelfTestDetectsPasswordlessDatabaseAsRoot(t *testing.T) { diff --git a/server/isolation_unix.go b/server/isolation_unix.go index 1fc90c3..54918f3 100644 --- a/server/isolation_unix.go +++ b/server/isolation_unix.go @@ -12,8 +12,10 @@ import ( "os" "os/exec" "path/filepath" + "slices" "strconv" "strings" + "syscall" "time" "github.com/jackc/pgx/v5" @@ -63,6 +65,7 @@ func IsolationSelfTest(p ExecPrivilege, t IsolationTargets) error { } spec := isolationSpec(p, t) failures := fileToolIsolationFailures(spec.Unreadable) + failures = append(failures, replaceableDirFailures(spec.Unwritable, p.UID, p.GID)...) rep, err := runIsolationProbe(spec) if err != nil { failures = append(failures, fmt.Sprintf("the probe did not run through the Bash shim: %v", err)) @@ -87,6 +90,14 @@ func isolationSpec(p ExecPrivilege, t IsolationTargets) isolationProbeSpec { if t.DataDir != "" { spec.Unreadable = append(spec.Unreadable, filepath.Join(t.DataDir, "traffic", "_ca", "mitmproxy-ca.pem")) } + // The directories of the keys, the config and the data: an agent process that + // can create an entry there can plant a key, a config or a whole data tree that + // the server uses at its next start. + for _, dir := range []string{t.DataDir, t.KeyDir, configDir(t.ConfigPath)} { + if dir != "" && !slices.Contains(spec.Unwritable, dir) { + spec.Unwritable = append(spec.Unwritable, dir) + } + } if t.DSN != "" { if cfg, err := pgx.ParseConfig(t.DSN); err == nil { spec.DB = &isolationProbeDB{Host: cfg.Host, Port: cfg.Port, User: cfg.User, Database: cfg.Database} @@ -95,6 +106,54 @@ func isolationSpec(p ExecPrivilege, t IsolationTargets) isolationProbeSpec { return spec } +func configDir(configPath string) string { + if configPath == "" { + return "" + } + return filepath.Dir(configPath) +} + +// replaceableDirFailures reports each directory whose parent lets the executor +// rename it and put another in its place: the parent is owned by the executor, or +// the executor can write in it and it is not sticky. The probe checks the +// directories themselves; their parents are checked here from the owners and mode +// bits, since a sticky world-writable parent such as /tmp is writable yet safe. +func replaceableDirFailures(dirs []string, execUID, execGID uint32) []string { + var failures []string + for _, dir := range dirs { + abs, err := filepath.Abs(dir) + if err != nil { + continue + } + parent := filepath.Dir(abs) + fi, err := os.Stat(parent) + if err != nil { + continue + } + st, ok := fi.Sys().(*syscall.Stat_t) + if !ok { + continue + } + if why := parentReplaceable(fi.Mode(), st.Uid, st.Gid, execUID, execGID); why != "" { + failures = append(failures, fmt.Sprintf("an agent process can replace %s: its parent %s %s", dir, parent, why)) + } + } + return failures +} + +// parentReplaceable is the decision of replaceableDirFailures for one parent. +func parentReplaceable(mode fs.FileMode, uid, gid, execUID, execGID uint32) string { + if uid == execUID { + return fmt.Sprintf("is owned by the executor uid %d", execUID) + } + if mode&fs.ModeSticky == 0 { + if why := normaTaskDirExecWrite(mode.Perm(), uid, gid, execUID, execGID); why != "" { + return "is writable by the executor and not sticky (" + why + ")" + } + } + return "" +} + // fileToolIsolationFailures opens each existing secret through the file tool // identity (agent/filetools_identity.go): the open must be refused. func fileToolIsolationFailures(secrets []string) []string { @@ -209,8 +268,6 @@ func checkIsolationAsExecutor(spec isolationProbeSpec) []string { f.Close() os.Remove(name) fail("Bash can create files in %s", dir) - } else if !errors.Is(err, fs.ErrPermission) && !errors.Is(err, fs.ErrNotExist) { - fail("Bash write check of %s: %v", dir, err) } } for _, kv := range os.Environ() { diff --git a/server/isolation_unix_test.go b/server/isolation_unix_test.go index 579581b..3ef6680 100644 --- a/server/isolation_unix_test.go +++ b/server/isolation_unix_test.go @@ -4,6 +4,7 @@ package server import ( "errors" + "io/fs" "net" "os" "path/filepath" @@ -143,6 +144,30 @@ func TestConnectWithoutPasswordRealPG(t *testing.T) { t.Logf("refused as expected: SQLSTATE %s", pgErr.Code) } +// The parent rule: owned by the executor, or writable by it without the sticky bit, +// lets it replace the directory; a sticky world-writable parent (/tmp) does not. +func TestParentReplaceable(t *testing.T) { + const u, g = 10001, 10001 + for _, c := range []struct { + name string + mode fs.FileMode + uid, gid uint32 + want bool + }{ + {"root 0755", fs.ModeDir | 0o755, 0, 0, false}, + {"owned by the executor", fs.ModeDir | 0o700, u, 0, true}, + {"group-writable executor gid", fs.ModeDir | 0o775, 0, g, true}, + {"group-writable other gid", fs.ModeDir | 0o775, 0, 0, false}, + {"world-writable", fs.ModeDir | 0o777, 0, 0, true}, + {"world-writable sticky", fs.ModeDir | fs.ModeSticky | 0o777, 0, 0, false}, + {"host user 0755", fs.ModeDir | 0o755, 1000, 1000, false}, + } { + if got := parentReplaceable(c.mode, c.uid, c.gid, u, g) != ""; got != c.want { + t.Errorf("%s: replaceable=%v, want %v", c.name, got, c.want) + } + } +} + // The spec carries the server's paths and the database name, never its password. func TestIsolationSpecHasNoPassword(t *testing.T) { spec := isolationSpec(ExecPrivilege{Enabled: true, UID: 10001, GID: 10002}, IsolationTargets{