diff --git a/changelog.d/security-claude-settings-hive-owned.md b/changelog.d/security-claude-settings-hive-owned.md new file mode 100644 index 0000000000..5e8a211b35 --- /dev/null +++ b/changelog.d/security-claude-settings-hive-owned.md @@ -0,0 +1 @@ +- The shared Claude Code user settings file (`/data/home/.claude/settings.json`, which every interactive claude agent reads through its per-agent `~/.claude/settings.json` bridge) is now hive-owned and kept read-only to agent UIDs. Before each claude launch the manager checks that the file is a regular file owned by the hive; a symlink or a file owned by another uid is moved aside to `settings.json.rejected` and the file is re-seeded, and group/other write is removed from a hive-owned copy. The entrypoint sweeps and the permissions watcher no longer widen this file to group write. Settings keys such as `hooks` and `apiKeyHelper` run commands in every agent's session, so one agent can no longer change them for the rest of the fleet; operators who keep extra keys there (for example `enabledPlugins`) and find the file moved aside after upgrading can re-apply them from the rejected copy as the hive user (#17059). diff --git a/src/crux/agent/claude_remote_control.go b/src/crux/agent/claude_remote_control.go index 9057361e49..4896dbb16a 100644 --- a/src/crux/agent/claude_remote_control.go +++ b/src/crux/agent/claude_remote_control.go @@ -2,8 +2,10 @@ package agent import ( "encoding/json" + "fmt" "os" "path/filepath" + "syscall" ) // remoteControlSettingKey is the Claude Code settings key that controls @@ -41,6 +43,7 @@ func claudeBypassConsentSeed() map[string]any { // claude-backend agent reads: each per-agent ~/.claude is a REAL directory // (perAgentCLIHomes) whose settings.json symlinks to // sharedAgentHome/.claude/settings.json, so one file governs the whole fleet. +// Hive owns that file; see ensureClaudeRemoteControlDefault. func sharedClaudeSettingsFile() string { return filepath.Join(sharedAgentHome, claudeHomeDirName, claudeSettingsFileName) } @@ -52,6 +55,12 @@ func sharedClaudeSettingsFile() string { // the same posture as ensureBobAuthSettings for bob's shared settings. The // bypass-consent suppressor (claudeBypassConsentSeed) is seeded the same way. // +// The shared file is hive-owned (hivecommons/hive#17059): before seeding, a +// settings.json that is a symlink or owned by another uid is moved aside and +// recreated from the seed; after seeding, the file is verified again and +// group/other write is removed. A file that still fails verification is moved +// aside so the launch never reads agent-writable settings. +// // Semantics: // - key absent -> written as false (the pin; this is the whole fix) // - key present -> left untouched, true OR false (operator intent wins); @@ -68,13 +77,26 @@ func (m *Manager) ensureClaudeRemoteControlDefault(agent *AgentProcess) { // credential) before the hive starts. If it is missing there is no login // and therefore no bridge entitlement either, so skip rather than invent a // directory whose modes the entrypoint owns. - if _, err := os.Lstat(filepath.Dir(path)); err != nil { + dirInfo, err := os.Lstat(filepath.Dir(path)) + if err != nil { m.logger.Debug("shared claude settings dir absent; skipping remote-control pin", "agent", agent.Name, "dir", filepath.Dir(path), "error", err) return } + if !dirInfo.IsDir() { + m.logger.Warn("shared claude settings dir is not a real directory; not writing hive settings through it", + "agent", agent.Name, "dir", filepath.Dir(path), "mode", dirInfo.Mode().String()) + return + } + m.rejectUntrustedSharedClaudeSettings(agent.Name, path) m.seedJSONFile(agent.Name, path, claudeRemoteControlSeed()) m.seedJSONFile(agent.Name, path, claudeBypassConsentSeed()) + if reason := lockSharedClaudeSettings(path); reason != "" { + m.logger.Warn("shared claude settings.json could not be brought to a hive-owned state after seeding", + "agent", agent.Name, "path", path, "reason", reason) + m.moveSharedClaudeSettingsAside(agent.Name, path, reason) + return + } if enabled, explicit := readRemoteControlSetting(path); explicit && enabled { // Receipt, not an error: the operator opted in and hive honored it. m.logger.Info("claude remote control left ON by explicit operator setting", @@ -123,3 +145,114 @@ func (m *Manager) remoteControlBridgeUsed(home string) bool { used, _ := session[remoteControlUsedKey].(bool) return used } + +// sharedClaudeSettingsFileMode is the widest mode the hive-owned shared Claude +// settings.json may have: readable by every agent UID, writable only by the +// hive. +// Claude Code user settings carry "hooks", "apiKeyHelper", "env" and other +// keys that run commands inside every agent's Claude session, so a file any +// agent could rewrite would be a cross-agent execution channel +// (hivecommons/hive#17059). +const sharedClaudeSettingsFileMode os.FileMode = 0o644 + +// sharedClaudeSettingsRejectedSuffix names where an untrusted shared +// settings.json is moved before hive re-seeds the file, so an operator can +// review it and re-apply any keys they want back. Only the latest rejected +// copy is kept. +const sharedClaudeSettingsRejectedSuffix = ".rejected" + +// sharedClaudeSettingsOwnerTrusted reports whether uid may own the shared +// Claude settings.json: root, the hive's own uid, or DevUID (the uid the +// permissions watcher hands root-owned entries to). Agent UIDs never qualify. +func sharedClaudeSettingsOwnerTrusted(uid uint32) bool { + return uid == 0 || int(uid) == os.Geteuid() || int(uid) == DevUID +} + +// untrustedSharedClaudeSettingsReason returns why the entry described by info +// (from Lstat) cannot be the hive-owned shared settings.json, or "" when its +// type and owner are acceptable. The mode is checked separately because a +// hive-owned file that is merely group-writable can be tightened in place. +func untrustedSharedClaudeSettingsReason(info os.FileInfo) string { + if info.Mode()&os.ModeSymlink != 0 { + return "symlink" + } + if !info.Mode().IsRegular() { + return "not a regular file" + } + st, ok := info.Sys().(*syscall.Stat_t) + if !ok { + return "owner unknown" + } + if !sharedClaudeSettingsOwnerTrusted(st.Uid) { + return fmt.Sprintf("owned by uid %d, not the hive", st.Uid) + } + return "" +} + +// rejectUntrustedSharedClaudeSettings moves the shared settings.json aside +// when it is a symlink, not a regular file, or owned by a uid other than the +// hive's. /data/home/.claude stays group-writable (agents replace the shared +// OAuth credential by temp-file-and-rename there), so any agent can +// rename-replace settings.json; checking ownership before every claude launch +// is what keeps a replaced file from reaching the next session. The seeders +// that run next recreate the file from the hive seed. +func (m *Manager) rejectUntrustedSharedClaudeSettings(agentName, path string) { + info, err := os.Lstat(path) + if os.IsNotExist(err) { + return + } + if err != nil { + m.logger.Warn("failed to inspect shared claude settings.json", + "agent", agentName, "path", path, "error", err) + return + } + if reason := untrustedSharedClaudeSettingsReason(info); reason != "" { + m.moveSharedClaudeSettingsAside(agentName, path, reason) + } +} + +// moveSharedClaudeSettingsAside renames the shared settings.json (or the +// symlink standing in its place — rename never follows it) to the rejected +// path, replacing any earlier rejected copy. +func (m *Manager) moveSharedClaudeSettingsAside(agentName, path, reason string) { + rejected := path + sharedClaudeSettingsRejectedSuffix + if err := os.Rename(path, rejected); err != nil { + if os.IsNotExist(err) { + return + } + m.logger.Warn("shared claude settings.json failed the hive ownership check and could not be moved aside", + "agent", agentName, "path", path, "reason", reason, "error", err) + return + } + m.logger.Warn("shared claude settings.json failed the hive ownership check; moved aside so it is re-seeded by hive", + "agent", agentName, "path", path, "reason", reason, "rejected", rejected) +} + +// lockSharedClaudeSettings verifies the shared settings.json through a +// descriptor opened without following symlinks (and without blocking on a +// planted FIFO), and removes group/other write from a hive-owned file (the +// entrypoint and the permissions watcher historically opened the whole shared +// tree to the agents group). Returns "" when the file is hive-owned and not +// writable by agents, otherwise the reason it is not. +func lockSharedClaudeSettings(path string) string { + f, err := os.OpenFile(path, os.O_RDONLY|syscall.O_NOFOLLOW|syscall.O_NONBLOCK, 0) + if err != nil { + return fmt.Sprintf("open: %v", err) + } + defer func() { _ = f.Close() }() // read-only fd; nothing to lose on close error + info, err := f.Stat() + if err != nil { + return fmt.Sprintf("stat: %v", err) + } + if reason := untrustedSharedClaudeSettingsReason(info); reason != "" { + return reason + } + perm := info.Mode().Perm() + if perm&0o022 == 0 { + return "" + } + if err := f.Chmod(perm & sharedClaudeSettingsFileMode); err != nil { + return fmt.Sprintf("group- or world-writable (%v) and chmod failed: %v", perm, err) + } + return "" +} diff --git a/src/crux/agent/claude_remote_control_test.go b/src/crux/agent/claude_remote_control_test.go index 366ff7ba54..954806960e 100644 --- a/src/crux/agent/claude_remote_control_test.go +++ b/src/crux/agent/claude_remote_control_test.go @@ -12,7 +12,10 @@ import ( "encoding/json" "os" "path/filepath" + "strings" + "syscall" "testing" + "time" "github.com/hivecommons/hive/crux/config" ) @@ -188,3 +191,205 @@ func TestRemoteControlBridgeUsed(t *testing.T) { t.Fatal("session with hasUsedRemoteControl:true should report bridge used — this is the launch-time evidence log for #5607") } } + +// --- hive-owned shared settings (#17059) ------------------------------------- +// +// The shared settings.json carries hooks/apiKeyHelper, so it must be a regular +// file owned by the hive and not writable by the agents group before any +// claude launch reads it. + +const hookPayload = `{"hooks":{"SessionStart":[{"hooks":[{"type":"command","command":"touch /tmp/should-not-run"}]}]}}` + +func assertNoHooks(t *testing.T, path string) { + t.Helper() + if _, ok := readSettingsMap(t, path)["hooks"]; ok { + t.Fatalf("%s still carries the planted hooks key", path) + } +} + +func assertNotAgentWritable(t *testing.T, path string) { + t.Helper() + info, err := os.Lstat(path) + if err != nil { + t.Fatal(err) + } + if !info.Mode().IsRegular() { + t.Fatalf("%s is %v, want a regular file", path, info.Mode()) + } + if perm := info.Mode().Perm(); perm&0o022 != 0 { + t.Fatalf("%s mode = %v, want no group/other write", path, perm) + } +} + +func TestEnsureClaudeRemoteControlDefault_ReplacesSymlinkedSettings(t *testing.T) { + path := withSharedClaudeDir(t) + planted := filepath.Join(t.TempDir(), "planted.json") + if err := os.WriteFile(planted, []byte(hookPayload), 0o666); err != nil { + t.Fatal(err) + } + if err := os.Symlink(planted, path); err != nil { + t.Fatal(err) + } + + quietManager().ensureClaudeRemoteControlDefault(rcTestAgent()) + + assertNotAgentWritable(t, path) + assertNoHooks(t, path) + assertRemoteControlOff(t, path) + rejected, err := os.Lstat(path + sharedClaudeSettingsRejectedSuffix) + if err != nil || rejected.Mode()&os.ModeSymlink == 0 { + t.Fatalf("swapped-in symlink should be kept aside as %s (err=%v)", sharedClaudeSettingsRejectedSuffix, err) + } + if data, _ := os.ReadFile(planted); string(data) != hookPayload { + t.Fatalf("symlink target was written through: %s", data) + } +} + +func TestEnsureClaudeRemoteControlDefault_TightensGroupWritableSettings(t *testing.T) { + path := withSharedClaudeDir(t) + if err := os.WriteFile(path, []byte(`{"theme":"dark"}`), 0o666); err != nil { + t.Fatal(err) + } + if err := os.Chmod(path, 0o666); err != nil { + t.Fatal(err) + } + + quietManager().ensureClaudeRemoteControlDefault(rcTestAgent()) + + assertNotAgentWritable(t, path) + if got := readSettingsMap(t, path)["theme"]; got != "dark" { + t.Fatalf("hive-owned settings were not kept: theme = %v", got) + } + if _, err := os.Lstat(path + sharedClaudeSettingsRejectedSuffix); !os.IsNotExist(err) { + t.Fatalf("a hive-owned file must be tightened in place, not rejected (err=%v)", err) + } +} + +func TestEnsureClaudeRemoteControlDefault_SeededSettingsNotGroupWritable(t *testing.T) { + path := withSharedClaudeDir(t) + old := syscall.Umask(0) + t.Cleanup(func() { syscall.Umask(old) }) + + quietManager().ensureClaudeRemoteControlDefault(rcTestAgent()) + + assertNotAgentWritable(t, path) + assertRemoteControlOff(t, path) +} + +func TestEnsureClaudeRemoteControlDefault_ReplacesForeignOwnedSettings(t *testing.T) { + if os.Geteuid() != 0 { + t.Skip("chowning the fixture to another uid requires root; the owner check is covered by TestUntrustedSharedClaudeSettingsReason") + } + path := withSharedClaudeDir(t) + if err := os.WriteFile(path, []byte(hookPayload), 0o644); err != nil { + t.Fatal(err) + } + if err := os.Chown(path, foreignSettingsUID(), -1); err != nil { + t.Fatal(err) + } + + quietManager().ensureClaudeRemoteControlDefault(rcTestAgent()) + + assertNotAgentWritable(t, path) + assertNoHooks(t, path) + assertRemoteControlOff(t, path) + if data, err := os.ReadFile(path + sharedClaudeSettingsRejectedSuffix); err != nil || string(data) != hookPayload { + t.Fatalf("foreign-owned settings should be kept aside for review (err=%v, data=%s)", err, data) + } +} + +// foreignSettingsUID returns a uid that is neither root, the test's euid nor +// DevUID — i.e. what an agent UID looks like to the owner check. +func foreignSettingsUID() int { + uid := os.Geteuid() + 4242 + for uid == DevUID || uid == 0 { + uid++ + } + return uid +} + +type fakeSettingsInfo struct { + mode os.FileMode + uid uint32 +} + +func (f fakeSettingsInfo) Name() string { return claudeSettingsFileName } +func (f fakeSettingsInfo) Size() int64 { return 0 } +func (f fakeSettingsInfo) Mode() os.FileMode { return f.mode } +func (f fakeSettingsInfo) ModTime() time.Time { return time.Time{} } +func (f fakeSettingsInfo) IsDir() bool { return f.mode.IsDir() } +func (f fakeSettingsInfo) Sys() any { return &syscall.Stat_t{Uid: f.uid} } + +func TestUntrustedSharedClaudeSettingsReason(t *testing.T) { + self := uint32(os.Geteuid()) + cases := []struct { + name string + info fakeSettingsInfo + trusted bool + }{ + {"hive-owned regular file", fakeSettingsInfo{mode: 0o644, uid: self}, true}, + {"root-owned regular file", fakeSettingsInfo{mode: 0o644, uid: 0}, true}, + {"dev-owned regular file", fakeSettingsInfo{mode: 0o644, uid: uint32(DevUID)}, true}, + {"agent-owned regular file", fakeSettingsInfo{mode: 0o644, uid: uint32(foreignSettingsUID())}, false}, + {"symlink", fakeSettingsInfo{mode: os.ModeSymlink | 0o777, uid: self}, false}, + {"directory", fakeSettingsInfo{mode: os.ModeDir | 0o755, uid: self}, false}, + } + for _, tc := range cases { + reason := untrustedSharedClaudeSettingsReason(tc.info) + if (reason == "") != tc.trusted { + t.Errorf("%s: reason = %q, want trusted=%v", tc.name, reason, tc.trusted) + } + } + if reason := untrustedSharedClaudeSettingsReason(fakeSettingsInfo{mode: 0o644, uid: uint32(foreignSettingsUID())}); !strings.Contains(reason, "uid") { + t.Errorf("foreign-owner reason should name the uid, got %q", reason) + } +} + +func TestIsSharedClaudeSettingsFile(t *testing.T) { + cases := map[string]bool{ + "/data/home/.claude/settings.json": true, + "/data/home/.claude/settings.json.rejected": false, + "/data/home/.claude/projects/settings.json": false, + "/data/home/.gemini/settings.json": false, + } + for path, want := range cases { + if got := isSharedClaudeSettingsFile(path); got != want { + t.Errorf("isSharedClaudeSettingsFile(%q) = %v, want %v", path, got, want) + } + } +} + +// TestFixEntryLeavesSharedClaudeSettingsMode runs fixEntry as the watcher's +// own uid (so its chmod arm is reachable) and checks the shared settings file +// is not widened while a sibling in the same directory still is. +func TestFixEntryLeavesSharedClaudeSettingsMode(t *testing.T) { + origDev, origNode := DevUID, NodeGID + DevUID, NodeGID = os.Getuid(), os.Getgid() + t.Cleanup(func() { DevUID, NodeGID = origDev, origNode }) + + dir := filepath.Join(t.TempDir(), claudeHomeDirName) + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + settings := filepath.Join(dir, claudeSettingsFileName) + sibling := filepath.Join(dir, "sibling.json") + for _, p := range []string{settings, sibling} { + if err := os.WriteFile(p, []byte(`{}`), 0o644); err != nil { + t.Fatal(err) + } + if err := os.Chmod(p, 0o644); err != nil { + t.Fatal(err) + } + fi, err := os.Lstat(p) + if err != nil { + t.Fatal(err) + } + fixEntry(p, fi, quietLogger()) + } + if got := statMode(t, settings); got != 0o644 { + t.Errorf("shared settings.json mode = %v, want 0644 untouched", got) + } + if got := statMode(t, sibling); got&0o020 == 0 { + t.Errorf("sibling mode = %v; fixEntry's chmod arm was not exercised", got) + } +} diff --git a/src/crux/agent/permissions_watcher.go b/src/crux/agent/permissions_watcher.go index 01ba2ef3ff..d8b5fbb394 100644 --- a/src/crux/agent/permissions_watcher.go +++ b/src/crux/agent/permissions_watcher.go @@ -139,6 +139,14 @@ func isSharedGroupReadableFile(path string) bool { filepath.Base(geminiDir) == ".gemini" } +// isSharedClaudeSettingsFile reports whether path is the shared Claude user +// settings file (.claude/settings.json directly under a watched home). Matched +// by name like isAgyCLILog, so the check follows WatchedHomeDirs in tests. +func isSharedClaudeSettingsFile(path string) bool { + return filepath.Base(path) == claudeSettingsFileName && + filepath.Base(filepath.Dir(path)) == claudeHomeDirName +} + // isAgyCLILog reports whether path is an Antigravity CLI session log // (.gemini/antigravity-cli/log/cli-*.log). agy recreates/rewrites these with // its own 0640 mode on every run, so widening them to group-write just made @@ -595,6 +603,13 @@ func fixEntry(path string, fi os.FileInfo, logger *slog.Logger) { return } + // The shared Claude settings.json is hive-owned and must never be widened + // to group write (hivecommons/hive#17059); see + // ensureClaudeRemoteControlDefault. + if !fi.IsDir() && isSharedClaudeSettingsFile(path) { + return + } + // Only fix permissions on files we own or just chowned. // Skipping files owned by other users avoids "operation not permitted" // spam when agents create files as their own users. diff --git a/src/deploy/entrypoint.sh b/src/deploy/entrypoint.sh index d460ba691c..e66123aaac 100644 --- a/src/deploy/entrypoint.sh +++ b/src/deploy/entrypoint.sh @@ -124,6 +124,8 @@ hive_run_uid_isolation_migration() { if [ "${HIVE_HOME_MODE_REPAIR_NEEDED:-false}" = "true" ]; then chmod -R g+rwX /data/home 2>/dev/null \ || echo "[entrypoint] WARN: chmod -R g+rwX /data/home failed — is CAP_FOWNER in the pod's capabilities.add? Continuing; agents may hit EACCES under /data/home" + # The shared Claude settings.json stays hive-owned and not group-writable (#17059). + [ -L /data/home/.claude/settings.json ] || chmod go-w /data/home/.claude/settings.json 2>/dev/null || true find /data/home -type d -exec chmod g+s {} + 2>/dev/null \ || echo "[entrypoint] WARN: chmod g+s on /data/home dirs failed — is CAP_FOWNER/CAP_FSETID in the pod's capabilities.add? Continuing" fi @@ -1687,12 +1689,16 @@ if [ "$(id -u)" = "0" ]; then # no-follow guarantee -- chmod has no no-follow form, so an entry an agent # swaps for a link between enumeration and the chmod is still followed (the # same window `chmod -R` has). `chown -h` never follows. + # + # The shared Claude settings.json is excluded: it carries hooks and + # apiKeyHelper, so it is hive-owned and never group-writable (#17059). The + # manager verifies and tightens it before every claude launch. hive_fix_walk() { [ -d "$1" ] || return 0 _walk_root="$1"; shift _regroup_sh="$(hive_fix_regroup_sh)" _reown_sh="$(hive_fix_reown_sh)" - find "$_walk_root" ! -type l "$@" \( -type d -uid 0 -exec sh -c "$_reown_sh" sh g+rwxs {} + -o -type d -exec sh -c "$_regroup_sh" sh g+rwxs {} + -o -uid 0 -exec sh -c "$_reown_sh" sh g+rwX {} + -o -exec sh -c "$_regroup_sh" sh g+rwX {} + \) 2>/dev/null || true + find "$_walk_root" ! -type l ! -path /data/home/.claude/settings.json "$@" \( -type d -uid 0 -exec sh -c "$_reown_sh" sh g+rwxs {} + -o -type d -exec sh -c "$_regroup_sh" sh g+rwxs {} + -o -uid 0 -exec sh -c "$_reown_sh" sh g+rwX {} + -o -exec sh -c "$_regroup_sh" sh g+rwX {} + \) 2>/dev/null || true return 0 } diff --git a/src/deploy/test_entrypoint_perm_guard.sh b/src/deploy/test_entrypoint_perm_guard.sh index bf19f84631..857dfce8dd 100755 --- a/src/deploy/test_entrypoint_perm_guard.sh +++ b/src/deploy/test_entrypoint_perm_guard.sh @@ -571,6 +571,29 @@ case "$race_group_digit" in "mode is $race_mode — this is the dev-owned-0600 lockout from #9226" ;; esac +# ── 13. The shared Claude settings.json is never opened to the group ──────── +# It carries hooks and apiKeyHelper, so a group-writable copy lets any agent +# run a command in every other agent's Claude session (#17059). The sweeps +# must leave it hive-owned and owner-write-only while still repairing its +# siblings. +SETTINGS="$HOMEDIR/.claude/settings.json" +SIBLING="$HOMEDIR/.claude/sibling.json" +for repair in hive_fix_tree_recent hive_fix_tree; do + printf '{}\n' > "$SETTINGS" + printf '{}\n' > "$SIBLING" + chmod 0644 "$SETTINGS" "$SIBLING" + sh -c 'set -e; . "$1"; '"$repair"' "$2" 10' sh "$WORK/guards.local.sh" "$HOMEDIR/.claude" >/dev/null 2>&1 + settings_mode="$(stat -c '%a' "$SETTINGS" 2>/dev/null || stat -f '%Lp' "$SETTINGS")" + sibling_mode="$(stat -c '%a' "$SIBLING" 2>/dev/null || stat -f '%Lp' "$SIBLING")" + if [ "$settings_mode" = "644" ] && group_rw "$sibling_mode"; then + ok "$repair: shared .claude/settings.json stays 644 while its siblings are repaired" + else + bad "$repair: shared .claude/settings.json stays 644 while its siblings are repaired" \ + "settings.json mode $settings_mode, sibling mode $sibling_mode" + fi +done +rm -f "$SETTINGS" "$SIBLING" + echo "" echo "Results: $PASS passed, $FAIL failed" [ "$FAIL" -eq 0 ] || exit 1