Address Cody review round 4: CODY-006 state-directory ownership
The state directory must now be owned by the bridge's effective uid. A directory owned by anyone else is refused with StateDirectoryError before any file is created or opened, and is left exactly as found, even when its mode is already 0700. Mode enforcement (exactly 0700) is unchanged and runs after the ownership check. Tests: the real /root as an unprivileged user; a deterministic injected-uid case proving no database/WAL/SHM is created and the directory is not mutated; a foreign-owned loose-mode directory left unmodified; a user- namespace fixture using the unmodified production path. Checks: typecheck clean; npm test 198 passed; client build ok; test:real-stt 11 passed; test:real-hermes 9 passed; test:simulator 6 passed; git diff --check clean. Not reviewed. No physical-device, droplet or production evidence. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
+21
-10
@@ -93,21 +93,29 @@ export class StateDirectoryError extends Error {
|
||||
}
|
||||
|
||||
/**
|
||||
* Make the directory that holds the database owner-only (0700), whether it was just created
|
||||
* or already existed, and confirm it. A directory that cannot be restricted (not ours, or on
|
||||
* a filesystem without permissions) is refused: the bridge does not keep credentials where
|
||||
* other users can list or replace files.
|
||||
* Make sure the directory that holds the database is the bridge's own: owned by the user the
|
||||
* bridge runs as, and owner-only (0700), whether it was just created or already existed.
|
||||
*
|
||||
* Ownership is checked first and is never "fixed": "0700" only means private if the owner is
|
||||
* us. A directory that belongs to anyone else is refused exactly as found, even when its mode
|
||||
* is already 0700, and nothing is created in it. There is no trusted-other-owner option.
|
||||
*/
|
||||
export function secureStateDir(dir: string): void {
|
||||
export function secureStateDir(dir: string, effectiveUid: number | undefined = process.geteuid?.()): void {
|
||||
if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: DIR_MODE });
|
||||
const who = effectiveUid === undefined ? 'the user it runs as' : `uid ${effectiveUid}, the user it runs as`;
|
||||
const explain = (why: string) =>
|
||||
new StateDirectoryError(
|
||||
`The state directory ${dir} ${why}. The bridge keeps device credentials there and needs a ` +
|
||||
`directory of its own, owned by the user it runs as, with mode 0700. ` +
|
||||
`Create one (for example: install -d -m 0700 ${dir}) or point HERMEVEN_DB_PATH at one.`,
|
||||
`directory of its own, owned by ${who}, with mode 0700. Create one (for example: ` +
|
||||
`install -d -m 0700 -o <service-user> -g <service-group> ${dir}) or point HERMEVEN_DB_PATH at one.`,
|
||||
);
|
||||
let info = statSync(dir);
|
||||
if (!info.isDirectory()) throw explain('is not a directory');
|
||||
// `effectiveUid` is undefined only on platforms without POSIX users, where there is no
|
||||
// ownership to compare.
|
||||
if (effectiveUid !== undefined && info.uid !== effectiveUid) {
|
||||
throw explain(`is owned by uid ${info.uid}, not by the bridge, and has been left untouched`);
|
||||
}
|
||||
if ((info.mode & 0o777) !== DIR_MODE) {
|
||||
try {
|
||||
chmodSync(dir, DIR_MODE);
|
||||
@@ -117,12 +125,15 @@ export function secureStateDir(dir: string): void {
|
||||
info = statSync(dir);
|
||||
if ((info.mode & 0o777) !== DIR_MODE) throw explain('did not keep mode 0700 after it was set');
|
||||
}
|
||||
// Re-checked after any change: the directory we are about to use is ours and private.
|
||||
if (effectiveUid !== undefined && info.uid !== effectiveUid) throw explain('changed owner while being secured');
|
||||
}
|
||||
|
||||
export function openDb(path: string): Db {
|
||||
export function openDb(path: string, options: { effectiveUid?: number } = {}): Db {
|
||||
if (path !== ':memory:') {
|
||||
// Before anything is created inside it.
|
||||
secureStateDir(dirname(path));
|
||||
// Before anything is created or opened inside it. `effectiveUid` exists for tests; the
|
||||
// bridge always uses the real effective uid of the process.
|
||||
secureStateDir(dirname(path), options.effectiveUid ?? process.geteuid?.());
|
||||
// Create the file ourselves, owner-only, BEFORE SQLite opens it. SQLite gives the WAL and
|
||||
// SHM files the same permissions as the database file, so they are never world-readable,
|
||||
// not even for a moment.
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { execFileSync, spawnSync } from 'node:child_process';
|
||||
import { mkdtempSync, rmSync, statSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { ConfigError, loadConfig } from '../src/config.ts';
|
||||
import { openDb, StateDirectoryError } from '../src/db.ts';
|
||||
import { openDb, secureStateDir, StateDirectoryError } from '../src/db.ts';
|
||||
import { Devices } from '../src/devices.ts';
|
||||
import { buildRunBody } from '../src/hermes/adapter.ts';
|
||||
import { mapRunStatus } from '../src/hermes/runsAdapter.ts';
|
||||
@@ -160,6 +160,128 @@ describe('state files are owner-only whatever the umask (CODY-006)', () => {
|
||||
expect(stat(shared).mode & 0o777).not.toBe(0o700); // and we did not change it
|
||||
});
|
||||
|
||||
describe('ownership: a 0700 directory is only private if it is ours', () => {
|
||||
const snapshotOf = (path: string) => {
|
||||
const s = statSync(path);
|
||||
return { mode: s.mode & 0o7777, uid: s.uid, gid: s.gid, mtimeMs: s.mtimeMs, ctimeMs: s.ctimeMs };
|
||||
};
|
||||
|
||||
it('a foreign-owned directory that is ALREADY 0700 is refused, nothing is created, and it is not touched (the real /root)', async () => {
|
||||
const { existsSync, readdirSync } = await import('node:fs');
|
||||
const foreign = '/root';
|
||||
const isFixture = existsSync(foreign) && statSync(foreign).uid !== process.geteuid!() && (statSync(foreign).mode & 0o777) === 0o700;
|
||||
if (!isFixture) {
|
||||
console.info('[units] NOT RUN on the real /root: it is not a foreign-owned 0700 directory here (the namespace and injected-uid tests below still cover this)');
|
||||
return;
|
||||
}
|
||||
const before = snapshotOf(foreign);
|
||||
const dbPath = join(foreign, `hermeven-foreign-owner-test-${process.pid}.sqlite`);
|
||||
expect(() => secureStateDir(foreign)).toThrow(StateDirectoryError);
|
||||
let error: unknown;
|
||||
try {
|
||||
openDb(dbPath).close();
|
||||
} catch (err) {
|
||||
error = err;
|
||||
}
|
||||
expect(error).toBeInstanceOf(StateDirectoryError);
|
||||
expect((error as Error).message).toContain('/root');
|
||||
expect((error as Error).message).toMatch(/owned by uid 0, not by the bridge/);
|
||||
expect((error as Error).message).toMatch(/left untouched/);
|
||||
expect((error as Error).message).toMatch(/install -d -m 0700/);
|
||||
expect(snapshotOf(foreign)).toEqual(before);
|
||||
// We cannot list /root, which is the point; the refusal happened before any create call.
|
||||
expect(() => readdirSync(foreign)).toThrow();
|
||||
});
|
||||
|
||||
it('deterministic everywhere: a 0700 directory with a different owner uid is refused before SQLite creates or opens anything, and is not mutated', async () => {
|
||||
const { chmodSync, mkdirSync, readdirSync, writeFileSync, existsSync } = await import('node:fs');
|
||||
const root = mkdtempSync(join(tmpdir(), 'hermeven-owner-'));
|
||||
const stateDir = join(root, 'state');
|
||||
mkdirSync(stateDir);
|
||||
chmodSync(stateDir, 0o700);
|
||||
const dbPath = join(stateDir, 'hermeven.sqlite');
|
||||
const someoneElse = process.geteuid!() + 1; // the bridge "runs as" a uid that does not own the directory
|
||||
try {
|
||||
const before = snapshotOf(stateDir);
|
||||
expect(() => secureStateDir(stateDir, someoneElse)).toThrow(StateDirectoryError);
|
||||
let error: unknown;
|
||||
try {
|
||||
openDb(dbPath, { effectiveUid: someoneElse }).close();
|
||||
} catch (err) {
|
||||
error = err;
|
||||
}
|
||||
expect(error).toBeInstanceOf(StateDirectoryError);
|
||||
expect((error as Error).message).toMatch(new RegExp(`owned by uid ${process.geteuid!()}, not by the bridge`));
|
||||
expect(readdirSync(stateDir)).toEqual([]); // no database, WAL, SHM or anything else
|
||||
expect(existsSync(dbPath)).toBe(false);
|
||||
expect(snapshotOf(stateDir)).toEqual(before);
|
||||
|
||||
// An existing database in a foreign-owned directory is not opened either.
|
||||
writeFileSync(dbPath, '');
|
||||
const withFile = snapshotOf(stateDir);
|
||||
expect(() => openDb(dbPath, { effectiveUid: someoneElse })).toThrow(StateDirectoryError);
|
||||
expect(readdirSync(stateDir)).toEqual(['hermeven.sqlite']);
|
||||
expect(statSync(dbPath).size).toBe(0); // SQLite never wrote a header into it
|
||||
expect(snapshotOf(stateDir)).toEqual(withFile);
|
||||
|
||||
// Sanity: the same directory is accepted for its real owner.
|
||||
openDb(dbPath).close();
|
||||
} finally {
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it('a foreign-owned directory with a LOOSE mode is refused without being chmod-ed', async () => {
|
||||
const { chmodSync, mkdirSync, readdirSync } = await import('node:fs');
|
||||
const root = mkdtempSync(join(tmpdir(), 'hermeven-owner-'));
|
||||
const stateDir = join(root, 'state');
|
||||
mkdirSync(stateDir);
|
||||
chmodSync(stateDir, 0o755);
|
||||
try {
|
||||
expect(() => openDb(join(stateDir, 'hermeven.sqlite'), { effectiveUid: process.geteuid!() + 1 })).toThrow(/left untouched/);
|
||||
expect(mode(stateDir)).toBe(0o755); // not "fixed" on someone else's behalf
|
||||
expect(readdirSync(stateDir)).toEqual([]);
|
||||
} finally {
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it('isolated user fixture: inside a user namespace, with the real process uid and no injection, a foreign-owned 0700 directory is refused', () => {
|
||||
// In `unshare -r` this process is uid 0 and the real root's /root appears as owned by the
|
||||
// overflow uid: a genuine foreign owner, checked by the unmodified production code path.
|
||||
const script = `
|
||||
const fs = await import('node:fs');
|
||||
const { openDb, StateDirectoryError } = await import(${JSON.stringify(fileURLToPath(new URL('../src/db.ts', import.meta.url)))});
|
||||
const dir = '/root';
|
||||
const st = fs.statSync(dir);
|
||||
const before = { mode: st.mode & 0o7777, uid: st.uid, mtimeMs: st.mtimeMs, ctimeMs: st.ctimeMs };
|
||||
let outcome = 'ACCEPTED_FOREIGN_OWNER';
|
||||
let message = '';
|
||||
try { openDb(dir + '/hermeven-ns-test.sqlite').close(); } catch (err) { outcome = err instanceof StateDirectoryError ? 'StateDirectoryError' : 'other:' + err.name; message = err.message; }
|
||||
const st2 = fs.statSync(dir);
|
||||
const after = { mode: st2.mode & 0o7777, uid: st2.uid, mtimeMs: st2.mtimeMs, ctimeMs: st2.ctimeMs };
|
||||
console.log(JSON.stringify({ euid: process.geteuid(), dirUid: st.uid, dirMode: (st.mode & 0o777).toString(8), outcome, message, unchanged: JSON.stringify(before) === JSON.stringify(after) }));
|
||||
`;
|
||||
const run = spawnSync('unshare', ['-r', process.execPath, '--import', 'tsx', '--input-type=module', '-e', script], {
|
||||
encoding: 'utf8',
|
||||
cwd: fileURLToPath(new URL('..', import.meta.url)),
|
||||
timeout: 60_000,
|
||||
});
|
||||
if (run.error || run.status !== 0) {
|
||||
console.info(`[units] NOT RUN: user namespaces unavailable (${(run.stderr || String(run.error)).trim().slice(0, 120)})`);
|
||||
return;
|
||||
}
|
||||
const out = JSON.parse(run.stdout.trim().split('\n').at(-1)!);
|
||||
if (out.dirUid === out.euid || out.dirMode !== '700') {
|
||||
console.info(`[units] NOT RUN: /root is not a foreign-owned 0700 directory in the namespace (${JSON.stringify(out)})`);
|
||||
return;
|
||||
}
|
||||
expect(out.outcome).toBe('StateDirectoryError');
|
||||
expect(out.message).toMatch(/not by the bridge/);
|
||||
expect(out.unchanged).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
it('a path whose parent is a file is refused clearly', async () => {
|
||||
const { writeFileSync } = await import('node:fs');
|
||||
const root = mkdtempSync(join(tmpdir(), 'hermeven-perm-'));
|
||||
|
||||
Reference in New Issue
Block a user