diff --git a/src/daemon/connection-host.test.ts b/src/daemon/connection-host.test.ts index ee17d9ba1..68e2509eb 100644 --- a/src/daemon/connection-host.test.ts +++ b/src/daemon/connection-host.test.ts @@ -12,14 +12,150 @@ import { MemoryIpcTransport, MemoryLogSink, NodeFilesystem, + type AccessEntry, type IpcConnection, type IpcConnector, type IpcListenerFactory, } from "../ports/index.js"; -import { DaemonAlreadyRunningError, DaemonEndpointHost } from "./connection-host.js"; +import { + DaemonAlreadyRunningError, + DaemonEndpointHost, + prepareDataDirectory, +} from "./connection-host.js"; const endpoint = "/simlock/daemon.sock"; +const USER = "S-1-5-21-2160452881-2465010311-446649340-1001"; +const FULL = 0x1f01ff; +const MODIFY = 0x1301bf; +const READ_EXECUTE = 0x1200a9; +// why: the masks are the ones `Get-Acl` returned on Windows 11 for the default home under +// `C:\Users\` and for a new folder on `D:\`. +const OWNER_ONLY: readonly AccessEntry[] = [ + { sid: "S-1-5-18", name: "NT AUTHORITY\\SYSTEM", allow: true, rights: FULL }, + { sid: "S-1-5-32-544", name: "BUILTIN\\Administrators", allow: true, rights: FULL }, + { sid: USER, name: "DESKTOP\\Szymon", allow: true, rights: FULL }, + // why: `C:\Users\` also grants an app capability traverse only, which reads nothing. + { + sid: "S-1-15-3-65536-3852923496", + name: "S-1-15-3-65536-3852923496", + allow: true, + rights: 0x100020, + }, +]; +const OTHER_DRIVE: readonly AccessEntry[] = [ + { sid: "S-1-5-32-544", name: "BUILTIN\\Administrators", allow: true, rights: FULL }, + { sid: "S-1-5-18", name: "NT AUTHORITY\\SYSTEM", allow: true, rights: FULL }, + { sid: "S-1-5-11", name: "NT AUTHORITY\\Authenticated Users", allow: true, rights: MODIFY }, + { sid: "S-1-5-32-545", name: "BUILTIN\\Users", allow: true, rights: READ_EXECUTE }, +]; +// why: quoted, since PowerShell reads an unquoted `(OI)` as a command; cmd.exe takes it too. +const icaclsFix = (path: string): string => + `icacls "${path}" /inheritance:r /grant:r "*${USER}:(OI)(CI)F" "*S-1-5-18:(OI)(CI)F" "*S-1-5-32-544:(OI)(CI)F"`; +const readable = (entries: readonly AccessEntry[]) => ({ + read: () => Promise.resolve({ user: USER, entries }), +}); + +describe("prepareDataDirectory", () => { + it("on Windows warns from the folder's ACL only when another account can read or change it, names an icacls fix, and warns nothing when the ACL cannot be read; macOS and Linux keep the mode check", async () => { + // why: Node reports 0o666 for every writable folder on Windows, whatever its ACL says. + const cases = [ + { name: "default-home", platform: "win32", mode: 0o666, access: readable(OWNER_ONLY) }, + { name: "other-drive", platform: "win32", mode: 0o666, access: readable(OTHER_DRIVE) }, + { + name: "read-only", + platform: "win32", + mode: 0o666, + access: readable([ + ...OWNER_ONLY, + { sid: "S-1-5-32-545", name: "BUILTIN\\Users", allow: true, rights: 0x1 }, + ]), + }, + { + name: "change-only", + platform: "win32", + mode: 0o666, + access: readable([ + ...OWNER_ONLY, + { sid: "S-1-5-21-1-2-3-1002", name: "DESKTOP\\Guest", allow: true, rights: 0x2 }, + ]), + }, + { + name: "generic-read", + platform: "win32", + mode: 0o666, + access: readable([ + ...OWNER_ONLY, + { sid: "S-1-5-21-1-2-3-1003", name: "DESKTOP\\Reader", allow: true, rights: 0x80000000 }, + ]), + }, + { + name: "denied", + platform: "win32", + mode: 0o666, + access: readable([ + ...OWNER_ONLY, + { sid: "S-1-5-32-545", name: "BUILTIN\\Users", allow: false, rights: FULL }, + ]), + }, + { + name: "creator-owner", + platform: "win32", + mode: 0o666, + access: readable([ + ...OWNER_ONLY, + { sid: "S-1-3-0", name: "CREATOR OWNER", allow: true, rights: FULL }, + ]), + }, + { + name: "unreadable", + platform: "win32", + mode: 0o666, + access: { read: () => Promise.reject(new Error("powershell exited 1")) }, + }, + { name: "macos-open", platform: "darwin", mode: 0o755, access: readable(OWNER_ONLY) }, + { name: "linux-closed", platform: "linux", mode: 0o700, access: readable(OTHER_DRIVE) }, + ] as const; + const warnings: [string, string | undefined][] = []; + for (const testCase of cases) { + const filesystem = new MemoryFilesystem(); + const path = `/home/${testCase.name}`; + await filesystem.mkdirp(path); + await filesystem.chmod(path, testCase.mode); + const options = { platform: testCase.platform, directoryAccess: testCase.access }; + warnings.push([testCase.name, await prepareDataDirectory(filesystem, path, options)]); + } + + expect(warnings).toEqual([ + ["default-home", undefined], + [ + "other-drive", + `data directory /home/other-drive is accessible to other users (NT AUTHORITY\\Authenticated Users, BUILTIN\\Users); run ${icaclsFix("/home/other-drive")}`, + ], + [ + "read-only", + `data directory /home/read-only is accessible to other users (BUILTIN\\Users); run ${icaclsFix("/home/read-only")}`, + ], + [ + "change-only", + `data directory /home/change-only is accessible to other users (DESKTOP\\Guest); run ${icaclsFix("/home/change-only")}`, + ], + [ + "generic-read", + `data directory /home/generic-read is accessible to other users (DESKTOP\\Reader); run ${icaclsFix("/home/generic-read")}`, + ], + ["denied", undefined], + ["creator-owner", undefined], + ["unreadable", undefined], + [ + "macos-open", + "data directory /home/macos-open is accessible to other users (mode 755); run chmod 700 /home/macos-open", + ], + ["linux-closed", undefined], + ]); + }); +}); + describe("DaemonEndpointHost", () => { it("binds a fresh endpoint and removes only its owned entry on repeated stop", async () => { const filesystem = new MemoryFilesystem(); diff --git a/src/daemon/connection-host.ts b/src/daemon/connection-host.ts index 3b099d487..1da5e610f 100644 --- a/src/daemon/connection-host.ts +++ b/src/daemon/connection-host.ts @@ -1,6 +1,7 @@ import { dirname } from "node:path"; import type { + DirectoryAccessReader, Filesystem, IpcConnection, IpcConnector, @@ -42,22 +43,57 @@ export async function refuseWhenDaemonAnswers(options: { throw new DaemonAlreadyRunningError(options.endpoint); } +// why: SYSTEM, Administrators and CREATOR OWNER open every folder anyway; the user is the owner. +const TRUSTED_SIDS = new Set(["S-1-5-18", "S-1-5-32-544", "S-1-3-0"]); +// why: list, read, write and append data, delete, and change the ACL or owner, as bits and as the generic rights. +const READ_OR_CHANGE = 0x1 | 0x2 | 0x4 | 0x10000 | 0x40000 | 0x80000 | 0x10000000 | 0x40000000; +const GENERIC_READ = 0x80000000; + +export interface DataDirectoryOptions { + readonly platform: NodeJS.Platform; + readonly directoryAccess: DirectoryAccessReader; +} + /** * why: the daemon makes its data directory owner-only before anything writes into it (the log, * `state.db`, the socket). One that already exists is never chmod'ed, since the user chose its - * mode: this only returns the warning the daemon logs when the group or others can reach it. + * mode: this only returns the warning the daemon logs when others can reach it. On Windows Node + * makes the mode bits up from the read-only attribute, so the folder's ACL is read instead; an + * ACL that cannot be read warns nothing. */ export async function prepareDataDirectory( filesystem: Filesystem, path: string, + options: DataDirectoryOptions, ): Promise { await filesystem.mkdirp(path, { mode: DATA_DIRECTORY_MODE }); + if (options.platform === "win32") return windowsWarning(path, options.directoryAccess); const mode = ((await filesystem.stat(path)).mode ?? DATA_DIRECTORY_MODE) & 0o777; if ((mode & 0o077) === 0) return undefined; const octal = mode.toString(8).padStart(3, "0"); return `data directory ${path} is accessible to other users (mode ${octal}); run chmod 700 ${path}`; } +async function windowsWarning( + path: string, + reader: DirectoryAccessReader, +): Promise { + const access = await reader.read(path).catch(() => undefined); + if (access === undefined) return undefined; + const names = new Set(); + for (const entry of access.entries) { + if (!entry.allow || entry.sid === access.user || TRUSTED_SIDS.has(entry.sid)) continue; + if ((entry.rights & READ_OR_CHANGE) !== 0 || (entry.rights & GENERIC_READ) !== 0) { + names.add(entry.name); + } + } + if (names.size === 0) return undefined; + const grants = [access.user, "S-1-5-18", "S-1-5-32-544"] + .map((sid) => `"*${sid}:(OI)(CI)F"`) + .join(" "); + return `data directory ${path} is accessible to other users (${[...names].join(", ")}); run icacls "${path}" /inheritance:r /grant:r ${grants}`; +} + export interface DaemonEndpointHostOptions { readonly connector: IpcConnector; readonly endpoint: string; diff --git a/src/daemon/main.ts b/src/daemon/main.ts index 3aecd1c25..95ea3ce5e 100644 --- a/src/daemon/main.ts +++ b/src/daemon/main.ts @@ -48,6 +48,8 @@ import { type IpcListenerFactory, type Logger, NodeFilesystem, + PowerShellDirectoryAccessReader, + type DirectoryAccessReader, filterSqliteExperimentalWarning, NodeSqliteOpener, NodeHostInfo, @@ -142,6 +144,7 @@ export interface StartDaemonOptions extends WorkerOptions { readonly optionalModules?: readonly OptionalModuleDefinition[]; readonly role?: DaemonMode; readonly filesystem?: Filesystem; + readonly directoryAccess?: DirectoryAccessReader; readonly hostInfo?: HostInfo; readonly idGenerator?: IdGenerator; readonly ipc?: IpcConnector & IpcListenerFactory; @@ -229,7 +232,11 @@ async function composeDaemon( const tcpProbe = options.tcpProbe ?? new NodeTcpProbe(); const configPath = options.configPath ?? join(dataDirectory, "config.json"); const socketPath = options.socketPath ?? resolveDaemonSocketPath(dataDirectory); - const dataDirectoryWarning = await prepareDataDirectory(filesystem, dataDirectory); + const dataDirectoryWarning = await prepareDataDirectory(filesystem, dataDirectory, { + platform: process.platform, + directoryAccess: + options.directoryAccess ?? new PowerShellDirectoryAccessReader(baseProcessRunner), + }); const configWarnings: string[] = []; const moduleDefinitions = options.optionalModules ?? optionalModules; const { config, defaulted } = await loadConfigWithDefaults({ diff --git a/src/daemon/test-main.ts b/src/daemon/test-main.ts index bddfe153a..7be84b664 100644 --- a/src/daemon/test-main.ts +++ b/src/daemon/test-main.ts @@ -3,7 +3,13 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { connect } from "node:net"; import { FakeDriver, fakeDeviceDataTables } from "../core/testing.js"; -import { FakeClock, JsonLinesLogger, MemoryFilesystem, MemoryLogSink } from "../ports/index.js"; +import { + FakeClock, + FakeDirectoryAccessReader, + JsonLinesLogger, + MemoryFilesystem, + MemoryLogSink, +} from "../ports/index.js"; import { startDaemon, type StartDaemonOptions } from "./main.js"; import { startOnFreePort } from "../test-support/loopback-port.js"; import type { DaemonServer } from "./server.js"; @@ -38,6 +44,8 @@ export async function start( dataDirectory: directory, drivers: [new FakeDriver({ availableOsVersions: ["26.5"], clock, platform: "ios" })], deviceDataTables: fakeDeviceDataTables, + // why: on Windows the real reader would start PowerShell for every test daemon. + directoryAccess: new FakeDirectoryAccessReader({ user: "S-1-5-21-1-2-3-1001", entries: [] }), filesystem: new MemoryFilesystem(), hostLoadProbe: null, logger, diff --git a/src/ports/directory-access.test.ts b/src/ports/directory-access.test.ts new file mode 100644 index 000000000..29c3bf549 --- /dev/null +++ b/src/ports/directory-access.test.ts @@ -0,0 +1,59 @@ +import { describe, expect, it } from "vitest"; + +import { PowerShellDirectoryAccessReader, ScriptedProcessRunner } from "./index.js"; + +describe("PowerShellDirectoryAccessReader", () => { + const ARGS = ["-NoProfile", "-NonInteractive", "-Command", /Get-Acl/] as const; + + function runner(result: { readonly stdout: string; readonly code?: number | null }) { + return new ScriptedProcessRunner([ + { + match: { args: ARGS, command: "powershell.exe" }, + result: { code: result.code ?? 0, stderr: "", stdout: result.stdout }, + }, + ]); + } + + it("reads the folder's ACL in one bounded PowerShell call that takes the path from the environment and returns each entry's SID, allow flag and rights", async () => { + const processRunner = runner({ + stdout: JSON.stringify({ + user: "S-1-5-21-1", + entries: [ + { sid: "S-1-5-21-1", name: "PC\\me", allow: true, rights: 2_032_127 }, + { sid: "S-1-1-0", name: "Everyone", allow: false, rights: 2_147_483_648 }, + ], + }), + }); + + const access = await new PowerShellDirectoryAccessReader(processRunner).read("C:\\a'b\\data"); + + expect(access).toEqual({ + user: "S-1-5-21-1", + entries: [ + { sid: "S-1-5-21-1", name: "PC\\me", allow: true, rights: 2_032_127 }, + { sid: "S-1-1-0", name: "Everyone", allow: false, rights: 2_147_483_648 }, + ], + }); + expect(processRunner.calls).toHaveLength(1); + const [call] = processRunner.calls; + expect(call?.options.timeoutMs).toBe(10_000); + expect(call?.options.env?.SIMLOCK_ACL_PATH).toBe("C:\\a'b\\data"); + const script = call?.args.at(-1) ?? ""; + expect(script).toContain("-LiteralPath $env:SIMLOCK_ACL_PATH"); + expect(script).not.toMatch(/a'{1,2}b/); + }); + + it.each([ + ["a non-zero exit", { stdout: "", code: 1 }, /powershell exited 1/], + ["output that is not the expected shape", { stdout: '{"user":1}' }, /unexpected ACL output/], + [ + "an entry with a wrong field type", + { stdout: '{"user":"S-1","entries":[{"sid":"S-1","name":"x","allow":"yes","rights":1}]}' }, + /unexpected ACL entry/, + ], + ])("rejects %s, so the daemon warns nothing", async (_title, result, message) => { + await expect( + new PowerShellDirectoryAccessReader(runner(result)).read("C:\\data"), + ).rejects.toThrow(message); + }); +}); diff --git a/src/ports/directory-access.ts b/src/ports/directory-access.ts new file mode 100644 index 000000000..07e35bc32 --- /dev/null +++ b/src/ports/directory-access.ts @@ -0,0 +1,85 @@ +import type { ProcessRunner } from "./process-runner.js"; + +export interface AccessEntry { + readonly sid: string; + readonly name: string; + readonly allow: boolean; + /** why: the `FileSystemRights` mask of the entry, as Windows stores it. */ + readonly rights: number; +} + +export interface DirectoryAccess { + /** why: the SID of the account the process runs as; SIDs, since account names are localized. */ + readonly user: string; + readonly entries: readonly AccessEntry[]; +} + +/** why: who can open a directory on Windows, where Node's mode bits are made up from the read-only attribute and say nothing about it. */ +export interface DirectoryAccessReader { + read(path: string): Promise; +} + +const READ_TIMEOUT_MS = 10_000; +const PATH_VARIABLE = "SIMLOCK_ACL_PATH"; +// why: generic rights set the top bit, so the signed mask is widened and masked back to the unsigned value. +// why: the path travels in the environment, so no quoting of it can break out of the script. +const SCRIPT = [ + "$ErrorActionPreference = 'Stop'", + "$sid = [System.Security.Principal.SecurityIdentifier]", + `$acl = Get-Acl -LiteralPath $env:${PATH_VARIABLE}`, + "$entries = @($acl.Access | ForEach-Object { [ordered]@{", + " sid = $_.IdentityReference.Translate($sid).Value;", + " name = $_.IdentityReference.Value;", + " allow = ($_.AccessControlType -eq 'Allow');", + " rights = ([int64][int]$_.FileSystemRights) -band 4294967295 } })", + "[ordered]@{ user = [System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value; entries = $entries } | ConvertTo-Json -Compress -Depth 4", +].join("\n"); + +export class PowerShellDirectoryAccessReader implements DirectoryAccessReader { + constructor(private readonly processRunner: ProcessRunner) {} + + async read(path: string): Promise { + const result = await this.processRunner.run( + "powershell.exe", + ["-NoProfile", "-NonInteractive", "-Command", SCRIPT], + { timeoutMs: READ_TIMEOUT_MS, env: { ...process.env, [PATH_VARIABLE]: path } }, + ); + if (result.code !== 0) { + throw new Error(`powershell exited ${String(result.code ?? result.endedBy)}`); + } + return parseDirectoryAccess(result.stdout); + } +} + +function parseDirectoryAccess(output: string): DirectoryAccess { + const parsed = JSON.parse(output) as { user?: unknown; entries?: unknown }; + if (typeof parsed.user !== "string" || !Array.isArray(parsed.entries)) { + throw new Error("unexpected ACL output"); + } + const entries = parsed.entries.map((entry: Record): AccessEntry => { + const { sid, name, allow, rights } = entry; + if ( + typeof sid !== "string" || + typeof name !== "string" || + typeof allow !== "boolean" || + typeof rights !== "number" + ) { + throw new Error("unexpected ACL entry"); + } + return { sid, name, allow, rights }; + }); + return { user: parsed.user, entries }; +} + +export class FakeDirectoryAccessReader implements DirectoryAccessReader { + readonly reads: string[] = []; + + constructor(private readonly access: DirectoryAccess | Error) {} + + read(path: string): Promise { + this.reads.push(path); + return this.access instanceof Error + ? Promise.reject(this.access) + : Promise.resolve(this.access); + } +} diff --git a/src/ports/index.ts b/src/ports/index.ts index 821ff3ebf..ac0f8650f 100644 --- a/src/ports/index.ts +++ b/src/ports/index.ts @@ -147,6 +147,12 @@ export { type StreamingProcessHandle, type StreamingProcessResult, } from "./process-runner.js"; +export { + type AccessEntry, + type DirectoryAccessReader, + FakeDirectoryAccessReader, + PowerShellDirectoryAccessReader, +} from "./directory-access.js"; export { type CpuCounters, type CpuTimes, diff --git a/website/src/content/docs/docs/worker/running-the-daemon.mdx b/website/src/content/docs/docs/worker/running-the-daemon.mdx index 4c0715e0f..5c97e2654 100644 --- a/website/src/content/docs/docs/worker/running-the-daemon.mdx +++ b/website/src/content/docs/docs/worker/running-the-daemon.mdx @@ -146,7 +146,7 @@ Everything the worker keeps is under `~/.simlock`, or the folder `SIMLOCK_HOME` `~/.simlock/devices` can grow to tens of gigabytes. Do not delete folders in it by hand while the daemon runs. Use `simlock cleanup`, or [`simlock nuke`](/simlock/docs/worker/cleanup#reset-a-machine-with-nuke) to start over. -Anyone who can open `~/.simlock` can lease devices, so Simlock creates it readable by your user only. It does not change a folder that already exists. If other users can open it, the daemon log says so at each start, with the `chmod 700` command that fixes it. +Anyone who can open `~/.simlock` can lease devices, so Simlock creates it readable by your user only. It does not change a folder that already exists. If other users can open it, the daemon log says so at each start, with the command that fixes it: `chmod 700` on macOS and Linux, `icacls` on Windows. A gateway on the same machine keeps its own files in `~/.simlock/gateway` and runs its own daemon. Add `--gateway` to reach it, for example `simlock --gateway daemon status`. See [Set up a gateway](/simlock/docs/gateway/setup).