Skip to content
Open
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
138 changes: 137 additions & 1 deletion src/daemon/connection-host.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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\<user>` 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\<user>` 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();
Expand Down
38 changes: 37 additions & 1 deletion src/daemon/connection-host.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { dirname } from "node:path";

import type {
DirectoryAccessReader,
Filesystem,
IpcConnection,
IpcConnector,
Expand Down Expand Up @@ -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<string | undefined> {
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<string | undefined> {
const access = await reader.read(path).catch(() => undefined);
if (access === undefined) return undefined;
const names = new Set<string>();
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;
Expand Down
9 changes: 8 additions & 1 deletion src/daemon/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ import {
type IpcListenerFactory,
type Logger,
NodeFilesystem,
PowerShellDirectoryAccessReader,
type DirectoryAccessReader,
filterSqliteExperimentalWarning,
NodeSqliteOpener,
NodeHostInfo,
Expand Down Expand Up @@ -142,6 +144,7 @@ export interface StartDaemonOptions extends WorkerOptions {
readonly optionalModules?: readonly OptionalModuleDefinition<unknown>[];
readonly role?: DaemonMode;
readonly filesystem?: Filesystem;
readonly directoryAccess?: DirectoryAccessReader;
readonly hostInfo?: HostInfo;
readonly idGenerator?: IdGenerator;
readonly ipc?: IpcConnector & IpcListenerFactory;
Expand Down Expand Up @@ -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({
Expand Down
10 changes: 9 additions & 1 deletion src/daemon/test-main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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,
Expand Down
59 changes: 59 additions & 0 deletions src/ports/directory-access.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});
Loading
Loading