Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/security-claude-settings-hive-owned.md
Original file line number Diff line number Diff line change
@@ -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).
135 changes: 134 additions & 1 deletion src/crux/agent/claude_remote_control.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ package agent

import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"syscall"
)

// remoteControlSettingKey is the Claude Code settings key that controls
Expand Down Expand Up @@ -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)
}
Expand All @@ -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);
Expand All @@ -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",
Expand Down Expand Up @@ -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 ""
}
205 changes: 205 additions & 0 deletions src/crux/agent/claude_remote_control_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,10 @@ import (
"encoding/json"
"os"
"path/filepath"
"strings"
"syscall"
"testing"
"time"

"github.com/hivecommons/hive/crux/config"
)
Expand Down Expand Up @@ -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)
}
}
Loading
Loading