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
114 changes: 106 additions & 8 deletions docker/kin-kvm/guest/kin-slot-agent
Original file line number Diff line number Diff line change
Expand Up @@ -594,6 +594,7 @@ class SlotAgentService:
handlers = {
"sync_file": self._op_sync_file,
"sync_preset_tz": self._op_sync_preset_tz,
"clear_slot_state": self._op_clear_slot_state,
"publish": self._op_publish,
"publish_universal": self._op_publish_universal,
"block": self._op_block,
Expand All @@ -616,22 +617,71 @@ class SlotAgentService:
# Never leak payload/credentials contents in error messages.
return {"id": req_id, "ok": False, "error": "internal_error", "message": type(exc).__name__}

def _resolve_claude_and_home_dirs(self) -> tuple[Path, Path]:
if self.cfg.claude_dir is not None:
return self.cfg.claude_dir, self.cfg.claude_dir.parent
return self.cfg.state_dir / "claude", self.cfg.state_dir / "home"

def _open_state_subdir(self, target_dir: Path, *, mode: int = 0o700) -> int:
try:
rel = target_dir.relative_to(self.cfg.state_dir)
dir_fd = open_dir_nofollow(self.cfg.state_dir, rel.parts, create_sub=True, mode=mode)
except ValueError:
dir_fd = open_dir_nofollow(target_dir.parent, (target_dir.name,), create_sub=True, mode=mode)
if os.geteuid() == 0:
os.fchown(dir_fd, self.cfg.kincli_uid, self.cfg.kincli_gid)
return dir_fd

def _op_sync_file(self, params: dict[str, Any]) -> dict[str, Any]:
target = params.get("target")
if target not in ("credentials", "kernel_config", "worker_config", "managed_preset"):
if target not in ("credentials", "kernel_config", "worker_config", "managed_preset", "claude_profile"):
raise RpcError("invalid_params", f"unsupported sync_file target: {target!r}")
raw, sha256_hex = decode_and_verify_payload(params.get("content_b64"), params.get("sha256"))

if target == "claude_profile":
try:
parsed = json.loads(raw.decode("utf-8"))
except Exception as exc:
raise RpcError("invalid_params", "claude_profile must be valid UTF-8 JSON") from exc
if not isinstance(parsed, dict):
raise RpcError("invalid_params", "claude_profile must be a JSON object")
claude_dir, home_dir = self._resolve_claude_and_home_dirs()
claude_fd = self._open_state_subdir(claude_dir, mode=0o700)
try:
atomic_write_in_dir(
claude_fd,
".claude.json",
raw,
mode=0o600,
uid=self.cfg.kincli_uid,
gid=self.cfg.kincli_gid,
)
finally:
os.close(claude_fd)
home_fd = self._open_state_subdir(home_dir, mode=0o700)
try:
atomic_write_in_dir(
home_fd,
".claude.json",
raw,
mode=0o600,
uid=self.cfg.kincli_uid,
gid=self.cfg.kincli_gid,
)
finally:
os.close(home_fd)
return {
"target": target,
"path": str(claude_dir / ".claude.json"),
"home_path": str(home_dir / ".claude.json"),
"sha256": sha256_hex,
"bytes": len(raw),
}

if target == "credentials":
if self.cfg.claude_dir is not None:
claude_dir = self.cfg.claude_dir
try:
rel = claude_dir.relative_to(self.cfg.state_dir)
dir_fd = open_dir_nofollow(self.cfg.state_dir, rel.parts, create_sub=True, mode=0o700)
except ValueError:
dir_fd = open_dir_nofollow(claude_dir.parent, (claude_dir.name,), create_sub=True, mode=0o700)
if os.geteuid() == 0:
os.fchown(dir_fd, self.cfg.kincli_uid, self.cfg.kincli_gid)
dir_fd = self._open_state_subdir(claude_dir, mode=0o700)
dest_path = claude_dir / "credentials.json"
else:
dir_fd = open_dir_nofollow(self.cfg.state_dir, ("claude",), create_sub=True, mode=0o700)
Expand Down Expand Up @@ -675,6 +725,54 @@ class SlotAgentService:
"bytes": len(raw),
}

def _remove_path_nofollow(self, target: Path, *, allow_dir: bool) -> bool:
try:
st = os.lstat(str(target))
except FileNotFoundError:
return False
if stat.S_ISLNK(st.st_mode) or not stat.S_ISDIR(st.st_mode):
os.unlink(str(target))
return True
if not allow_dir:
raise RpcError("unsafe_path", f"expected file, found directory: {target.name}")
# Restore write/exec bits on subdirectories (e.g. 0o555 sandbox .masks) before unlinking.
stack: list[Path] = [target]
dirs: list[Path] = []
while stack:
cur = stack.pop()
try:
os.chmod(str(cur), 0o700)
except OSError:
pass
dirs.append(cur)
with os.scandir(str(cur)) as it:
for entry in it:
entry_path = Path(entry.path)
if entry.is_dir(follow_symlinks=False):
stack.append(entry_path)
else:
os.unlink(str(entry_path))
for d in reversed(dirs):
os.rmdir(str(d))
return True
Comment on lines +728 to +757

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 Agentic Security Review
Severity: HIGH

新增的 _remove_path_nofollow 只对叶子做了 lstat/unlink,目录遍历仍用字符串路径上的 chmod/scandir/rmdir,没有沿用同文件里 open_dir_nofollow 的逐级 O_NOFOLLOW dirfd。路径解析会跟随中间目录软链;在 lstat 判定为目录之后,槽内非特权进程还可以把该路径换成软链,让以 root 运行的 kin-slot-agent 删除目标目录中的文件。

Impact: 账号换绑、清凭证或粘性重置触发 clear_slot_state 时,槽内用户可把删除操作导向客户机系统目录或 bind-mount 进来的宿主路径,破坏该槽明确的 nofollow 写入隔离。

Fix in Cursor Fix in Web

Reviewed by Cursor Security Reviewer for commit e9682cf. Configure here.


def _op_clear_slot_state(self, _params: dict[str, Any]) -> dict[str, Any]:
claude_dir, home_dir = self._resolve_claude_and_home_dirs()
targets: tuple[tuple[str, Path, bool], ...] = (
("credentials", claude_dir / "credentials.json", False),
("credentials_alias", claude_dir / ".credentials.json", False),
("claude_profile", claude_dir / ".claude.json", False),
("home_claude_profile", home_dir / ".claude.json", False),
("crag_v3_continuations", claude_dir / "crag-v3-continuations", True),
("telemetry", claude_dir / "telemetry", True),
("crag_sessions", self.cfg.run_dir / "work" / ".crag-sessions", True),
)
cleared: list[str] = []
for label, target_path, allow_dir in targets:
if self._remove_path_nofollow(target_path, allow_dir=allow_dir):
cleared.append(label)
return {"cleared": cleared}

def _op_sync_preset_tz(self, params: dict[str, Any]) -> dict[str, Any]:
tz_raw = params.get("timezone")
has_tz = tz_raw is not None and tz_raw != ""
Expand Down
99 changes: 99 additions & 0 deletions docker/kin-kvm/guest/test_kin_slot_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -939,6 +939,105 @@ def test_publish_skips_unchanged_inode_and_status_reports_digests(self) -> None:
self.assertEqual(st_final["result"]["crag_sync_pending"], {"license": False, "host": False})
self.assertEqual(st_final["result"]["crag_files_sha256"]["host"]["entitlement.code"], esha_2)

def test_sync_claude_profile_and_clear_slot_state(self) -> None:
custom_claude_dir = self.state_dir / "home" / ".claude"
custom_home_dir = self.state_dir / "home"
custom_cfg = agent.AgentConfig(
token=self.token,
state_dir=self.state_dir,
claude_dir=custom_claude_dir,
run_dir=self.run_dir,
crag_root=self.crag_root,
managed_preset_dir=self.managed_dir,
store_dir=self.store_dir,
machine_id_file=self.machine_id_file,
crag_pid_file=self.crag_pid_file,
dmi_dir=self.dmi_dir,
kincli_uid=os.getuid(),
kincli_gid=os.getgid(),
project_mounts=False,
)
svc = agent.SlotAgentService(custom_cfg)

# Sync credentials + claude_profile
creds = b'{"claudeAiOauth":{"accessToken":"tok-clear"}}\n'
cb64, csha = _b64_and_sha(creds)
r_cred = svc.handle_request({
"id": "c-cred",
"token": self.token,
"op": "sync_file",
"params": {"target": "credentials", "content_b64": cb64, "sha256": csha},
})
self.assertTrue(r_cred["ok"], r_cred)

profile = b'{"userID":"' + b"a" * 64 + b'","machineID":"' + b"b" * 64 + b'"}\n'
pb64, psha = _b64_and_sha(profile)
r_prof = svc.handle_request({
"id": "c-prof",
"token": self.token,
"op": "sync_file",
"params": {"target": "claude_profile", "content_b64": pb64, "sha256": psha},
})
self.assertTrue(r_prof["ok"], r_prof)
nested_profile = custom_claude_dir / ".claude.json"
home_profile = custom_home_dir / ".claude.json"
self.assertEqual(nested_profile.read_bytes(), profile)
self.assertEqual(home_profile.read_bytes(), profile)
self.assertEqual(stat.S_IMODE(nested_profile.stat().st_mode), 0o600)
self.assertEqual(stat.S_IMODE(home_profile.stat().st_mode), 0o600)

# Reject invalid JSON for claude_profile
bad_b64, bad_sha = _b64_and_sha(b"not-json")
r_bad = svc.handle_request({
"id": "c-prof-bad",
"token": self.token,
"op": "sync_file",
"params": {"target": "claude_profile", "content_b64": bad_b64, "sha256": bad_sha},
})
self.assertFalse(r_bad["ok"])
self.assertEqual(r_bad["error"], "invalid_params")

# Seed continuations, telemetry, and .crag-sessions with a 0o555 .masks directory
cont_dir = custom_claude_dir / "crag-v3-continuations"
cont_dir.mkdir(parents=True, exist_ok=True)
(cont_dir / "journal.log").write_text("entry\n", encoding="utf-8")
tel_dir = custom_claude_dir / "telemetry"
tel_dir.mkdir(parents=True, exist_ok=True)
(tel_dir / "batch.json").write_text("{}\n", encoding="utf-8")
masks_dir = self.run_dir / "work" / ".crag-sessions" / ".masks" / "m-1"
masks_dir.mkdir(parents=True, exist_ok=True)
(masks_dir / "stub").write_text("x", encoding="utf-8")
os.chmod(masks_dir, 0o555)
os.chmod(masks_dir.parent, 0o555)

r_clear = svc.handle_request({
"id": "c-clear",
"token": self.token,
"op": "clear_slot_state",
"params": {},
})
self.assertTrue(r_clear["ok"], r_clear)
cleared = set(r_clear["result"]["cleared"])
self.assertTrue(
{
"credentials",
"credentials_alias",
"claude_profile",
"home_claude_profile",
"crag_v3_continuations",
"telemetry",
"crag_sessions",
}.issubset(cleared),
cleared,
)
self.assertFalse((custom_claude_dir / "credentials.json").exists())
self.assertFalse((custom_claude_dir / ".credentials.json").is_symlink())
self.assertFalse(nested_profile.exists())
self.assertFalse(home_profile.exists())
self.assertFalse(cont_dir.exists())
self.assertFalse(tel_dir.exists())
self.assertFalse((self.run_dir / "work" / ".crag-sessions").exists())


if __name__ == "__main__":
unittest.main()
30 changes: 30 additions & 0 deletions docs/TELEMETRY.md
Original file line number Diff line number Diff line change
Expand Up @@ -253,3 +253,33 @@ isolation, refusal to claim success with a missing required file, and preservati
of node machine ID, OAuth config, internal token, and credentials. No production
account or telemetry switch was touched; real KVM and successful production-node
publication remain separate verification boundaries.

## Slot Machine Profile & Identity Controls

- **Per-install HMAC pepper (`KIN_MACHINE_PROFILE_PEPPER`)**:
Account-bound 3-OS machine profiles (`darwin` / `win32` / `linux`) derive
seeds via HMAC-SHA256. Operators may set `KIN_MACHINE_PROFILE_PEPPER` (recommended
for multi-instance deployments so all control-plane replicas share the same
pepper). When unset, the control plane auto-generates a 32-byte random hex
secret on first use and persists it in the DB `settings` table under
`slot_machine_profile_pepper` (matching `panel_2fa_challenge_secret`), never
falling back to a hardcoded source constant.
- **CRAG kernel capability gate (`slot_machine_profile_v1` / `>= 5.0.2`)**:
`run/kernel.json` top-level `machine_profile` and 3-OS `telemetry.identity`
overrides (which omit `dmi_dir`) are only emitted when the active CRAG v2
kernel advertises `slot_machine_profile_v1` or software version `>= 5.0.2`.
Older `crag-v2 <= 5.0.0` kernels retain legacy `telemetry.dmi_dir` and omit
`machine_profile`.
- **Legacy slot preservation & traits rotation**:
Pre-existing slots with a legacy `fingerprint.device_id` / Linux identity are
never lazily overwritten on the request hot path unless explicitly opted in
(`machine_profile_opt_in: true` or `machine_profile_mode: "3os"`). Newly
created Claude slots opt in automatically, and `traits` rebuilds rotate
`profile_generation` + `profile_reseed_nonce` + persisted `slot_epoch`.
- **One-way OS/Git persona rewrite (default OFF)**:
Reversible path/tool-ID/session-ID/commit-SHA isolation runs automatically on
slots with an active `machine_profile`, while one-way OS/Git persona text
rewriting (`Platform:`, `OS Version:`, `Shell:`, `Author:`, `Co-Authored-By:`,
`user.email=`, `# userEmail`) is OFF by default and requires explicit opt-in
(`KIN_SLOT_PERSONA_REWRITE=1`, `routing.slot_persona_rewrite: true`, or
`vm.machine_profile.persona_rewrite: true`).
61 changes: 42 additions & 19 deletions src/lib/admin/panel-api.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -298,35 +298,58 @@ export function publicPhysicalFeatures(vm) {
}
if (!vm || typeof vm !== 'object') return empty
const fp = vm.fingerprint && typeof vm.fingerprint === 'object' ? vm.fingerprint : {}
const hw = fp.hardware && typeof fp.hardware === 'object' ? fp.hardware : {}
const mp = vm.machine_profile && typeof vm.machine_profile === 'object' ? vm.machine_profile : {}
const mpHw = mp.hardware && typeof mp.hardware === 'object' ? mp.hardware : {}
const hw = fp.hardware && typeof fp.hardware === 'object' ? fp.hardware : mpHw
const machine = vm.machine && typeof vm.machine === 'object' ? vm.machine : {}
const runtime = vm.runtime && typeof vm.runtime === 'object' ? vm.runtime : {}
const specMiB = machine.memory ? memoryMiB(machine.memory) : 0
return {
observed_at:
presentText(hw.observed_at) || presentText(fp.collected_at) || presentText(runtime.identity_collected_at),
presentText(hw.observed_at) ||
presentText(mpHw.observed_at) ||
presentText(fp.collected_at) ||
presentText(runtime.identity_collected_at),
runtime_type: vm.runtime_type || runtimeKind(vm) || null,
hostname: presentText(fp.hostname),
os_id: presentText(fp.os_id),
os_pretty: presentText(fp.os_pretty),
kernel_release: presentText(fp.guest_kernel_release) || presentText(fp.kernel_release),
arch: presentText(fp.stainless_arch) || presentText(fp.arch),
hostname:
presentText(fp.display_hostname) ||
presentText(fp.hostname) ||
presentText(mp.display_hostname) ||
presentText(mp.hostname),
os_id: presentText(fp.os_id) || presentText(mp.os_id),
os_pretty: presentText(fp.os_pretty) || presentText(mp.os_pretty),
kernel_release:
presentText(fp.guest_kernel_release) || presentText(fp.kernel_release) || presentText(mp.kernel_release),
arch:
presentText(fp.stainless_arch) || presentText(fp.arch) || presentText(mp.stainless_arch) || presentText(mp.arch),
machine_id_present: !!(
presentText(fp.guest_machine_id) ||
presentText(fp.machine_id) ||
presentText(hw.machine_id)
presentText(hw.machine_id) ||
presentText(mp.device_id) ||
presentText(mp.machine_id)
),
timezone: presentText(fp.timezone) || presentText(vm.timezone),
locale: presentText(fp.locale) || presentText(vm.locale),
cpu_model: presentText(hw.cpu_model) || presentText(machine.cpu_model),
cpu_cores: presentInt(hw.cpu_cores) ?? presentInt(machine.vcpus),
memory_bytes: presentBytes(hw.memory_bytes) ?? (specMiB > 0 ? specMiB * 1024 * 1024 : null),
root_disk: presentText(hw.root_disk) || presentText(machine.disk_serial),
mac: presentText(hw.mac) || presentText(machine.mac),
dmi: publicDmi(hw, machine.smbios),
shell: presentList(hw.shell) || presentList(fp.shell),
package_managers: presentList(hw.package_managers) || presentList(fp.package_managers),
runtimes: presentList(hw.runtimes) || presentList(fp.runtimes),
timezone: presentText(fp.timezone) || presentText(mp.timezone) || presentText(vm.timezone),
locale: presentText(fp.locale) || presentText(mp.locale) || presentText(vm.locale),
cpu_model: presentText(hw.cpu_model) || presentText(mpHw.cpu_model) || presentText(machine.cpu_model),
cpu_cores: presentInt(hw.cpu_cores) ?? presentInt(mpHw.cpu_cores) ?? presentInt(machine.vcpus),
memory_bytes:
presentBytes(hw.memory_bytes) ?? presentBytes(mpHw.memory_bytes) ?? (specMiB > 0 ? specMiB * 1024 * 1024 : null),
root_disk: presentText(hw.root_disk) || presentText(mpHw.root_disk) || presentText(machine.disk_serial),
mac: presentText(hw.mac) || presentText(mpHw.mac) || presentText(machine.mac),
dmi: publicDmi(hw, mpHw.dmi || machine.smbios),
shell: presentList(hw.shell) || presentList(fp.shell) || presentList(mp.shell),
package_managers:
presentList(hw.package_managers) || presentList(fp.package_managers) || presentList(mp.package_managers),
runtimes: presentList(hw.runtimes) || presentList(fp.runtimes) || presentList(mp.runtimes),
...(mp.os_family
? {
os_family: presentText(mp.os_family),
stainless_os: presentText(mp.stainless_os),
os_version: presentText(mp.os_version),
machine_home: presentText(mp.machine_home),
}
: {}),
}
}

Expand Down
Loading
Loading