Skip to content

Commit a32a887

Browse files
author
hzq
committed
Verify Windows profile permissions with structured ACL evidence
1 parent 0ba3684 commit a32a887

4 files changed

Lines changed: 108 additions & 34 deletions

File tree

‎.github/workflows/ci.yml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,4 +53,4 @@ jobs:
5353
- run: npm run check
5454
- run: npm run format:check
5555
- run: npm run build
56-
- run: node --import ./dist/test/setup-locale.js --test --test-concurrency=1 dist/test/release-plan.test.js dist/test/claude-sdk.test.js
56+
- run: node --import ./dist/test/setup-locale.js --test --test-concurrency=1 dist/test/release-plan.test.js dist/test/claude-sdk.test.js dist/test/profile-init.test.js

‎src/config/initial-files.ts‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,15 +5,16 @@ import { execFile } from 'node:child_process';
55
import path from 'node:path';
66
import { promisify } from 'node:util';
77
import { Fault, sha } from '../core/util.js';
8-
import { ownerControlsOrphanKey, restrictToOwner } from '../core/win-acl.js';
8+
import { orphanKeyPrivacy, restrictToOwner } from '../core/win-acl.js';
99

1010
const code = (error: unknown) => (error as NodeJS.ErrnoException).code;
1111
const alreadyInitialized = () =>
1212
Object.assign(new Error('config.json already exists; left unchanged.'), { code: 'EEXIST' });
13-
const unsafeKey = () =>
13+
const unsafeKey = (reason?: string) =>
1414
new Fault(
1515
'profile_key_conflict',
16-
'Cannot safely resume initialization from admin.token. The original was not replaced. Use a new private profile or inspect the existing one.',
16+
'Cannot safely resume initialization from admin.token. The original was not replaced. Use a new private profile or inspect the existing one.' +
17+
(reason ? ` (Windows ACL: ${reason}.)` : ''),
1718
409,
1819
);
1920
const same = (a: BigIntStats, b: BigIntStats) => a.dev === b.dev && a.ino === b.ino;
@@ -103,7 +104,10 @@ async function verifyOrphan(dir: string, file: string): Promise<void> {
103104
(uid !== undefined && (parent.uid !== BigInt(uid) || (parent.mode & 0o022n) !== 0n))
104105
)
105106
throw unsafeKey();
106-
if (process.platform === 'win32' && !(await ownerControlsOrphanKey(file, dir))) throw unsafeKey();
107+
if (process.platform === 'win32') {
108+
const privacy = await orphanKeyPrivacy(file, dir);
109+
if (privacy !== 'private') throw unsafeKey(privacy);
110+
}
107111
if (process.platform === 'darwin' && !(await darwinOrphanAclIsPrivate(dir))) throw unsafeKey();
108112
const handle = await open(
109113
file,

‎src/core/win-acl.ts‎

Lines changed: 78 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -8,44 +8,94 @@ import { execFile } from 'node:child_process';
88
import os from 'node:os';
99
import path from 'node:path';
1010

11-
// Only used when adopting an existing credential. Mode bits on Windows cannot establish ownership.
12-
export async function ownerControlsOrphanKey(file: string, dir: string): Promise<boolean> {
11+
/** Pass fixed application code intact to Windows PowerShell; paths remain ordinary environment values. */
12+
export async function runWindowsProfileScript(
13+
command: string,
14+
extraEnv: NodeJS.ProcessEnv,
15+
): Promise<string> {
1316
const system = process.env.SystemRoot;
14-
if (!system || !path.isAbsolute(system)) return false;
17+
if (!system || !path.isAbsolute(system)) throw new Error('Windows system directory unavailable.');
1518
const ps = path.join(system, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
16-
const command = `
17-
$ErrorActionPreference = 'Stop'
18-
$sid = [Security.Principal.SecurityIdentifier]
19-
$self = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value
20-
$trusted = @($self, 'S-1-5-18', 'S-1-5-32-544')
21-
foreach ($target in @($env:OAA_INIT_DIR, $env:OAA_INIT_KEY)) {
22-
$acl = Get-Acl -LiteralPath $target
23-
if ($trusted -notcontains $acl.GetOwner($sid).Value) { exit 1 }
24-
$rules = $acl.GetAccessRules($true, $true, $sid)
25-
if (!$rules.Count) { exit 1 }
26-
foreach ($ace in $rules) {
27-
if ($ace.AccessControlType -ne 'Allow' -or ($ace.PropagationFlags -band 2) -or
28-
$trusted -contains $ace.IdentityReference.Value) { continue }
29-
# Generic write/all, plus create, remove, change attributes, ACL or owner.
30-
if ($target -eq $env:OAA_INIT_KEY -or ([int64]$ace.FileSystemRights -band 0x500D0156)) { exit 1 }
31-
}
32-
}
33-
exit 0`;
34-
return new Promise((resolve) => {
35-
execFile(
19+
return new Promise((resolve, reject) => {
20+
const child = execFile(
3621
ps,
37-
['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', command],
22+
[
23+
'-NoLogo',
24+
'-NoProfile',
25+
'-NonInteractive',
26+
'-EncodedCommand',
27+
Buffer.from(command, 'utf16le').toString('base64'),
28+
],
3829
{
39-
env: { ...process.env, OAA_INIT_DIR: dir, OAA_INIT_KEY: file },
30+
env: { ...process.env, ...extraEnv },
4031
windowsHide: true,
41-
timeout: 5000,
42-
maxBuffer: 4096,
32+
timeout: 15000,
33+
maxBuffer: 128 * 1024,
4334
},
44-
(error) => resolve(!error),
35+
(error, stdout) =>
36+
error
37+
? reject(
38+
Object.assign(new Error('Windows profile operation failed.'), { code: error.code }),
39+
)
40+
: resolve(stdout.trim()),
4541
);
42+
child.stdin?.end();
4643
});
4744
}
4845

46+
type Ace = { who: string; kind: number; flags: number; rights: number };
47+
type Descriptor = { owner: string; rules: Ace[] };
48+
export function classifyWindowsProfileAcl(value: { user: string; items: Descriptor[] }): string {
49+
const sid = (s: unknown) => typeof s === 'string' && /^S-1-(?:\d+-)+\d+$/.test(s);
50+
if (!sid(value?.user) || !Array.isArray(value.items) || value.items.length !== 2)
51+
return 'unreadable';
52+
const trusted = new Set([value.user, 'S-1-5-18', 'S-1-5-32-544']);
53+
for (const [index, item] of value.items.entries()) {
54+
if (!item || !trusted.has(item.owner)) return index === 0 ? 'directory-owner' : 'key-owner';
55+
if (!Array.isArray(item.rules) || !item.rules.length) return 'empty-acl';
56+
for (const ace of item.rules) {
57+
if (
58+
!ace ||
59+
!sid(ace.who) ||
60+
![0, 1].includes(ace.kind) ||
61+
!Number.isInteger(ace.flags) ||
62+
!Number.isInteger(ace.rights)
63+
)
64+
return 'unreadable';
65+
if (ace.kind === 1 || (ace.flags & 2) !== 0 || trusted.has(ace.who)) continue;
66+
if (index === 1) return 'shared-key';
67+
// Generic write/all, plus create, remove, change attributes, ACL or owner.
68+
if ((ace.rights & 0x500d0156) !== 0) return 'shared-directory';
69+
}
70+
}
71+
return 'private';
72+
}
73+
74+
// Only used for an existing credential. Do not print SIDs, paths or ACL text in a diagnostic.
75+
export async function orphanKeyPrivacy(file: string, dir: string): Promise<string> {
76+
const script = `
77+
$ErrorActionPreference = 'Stop'
78+
try {
79+
$sid = [System.Security.Principal.SecurityIdentifier]
80+
$list = @(foreach ($target in @($env:OAA_INIT_DIR, $env:OAA_INIT_KEY)) {
81+
$acl = Get-Acl -LiteralPath $target
82+
$rules = @(foreach ($ace in $acl.GetAccessRules($true, $true, $sid)) {
83+
@{ who=$ace.IdentityReference.Value; kind=[int]$ace.AccessControlType; flags=[int]$ace.PropagationFlags; rights=[long]$ace.FileSystemRights }
84+
})
85+
@{ owner=($acl.GetOwner($sid)).Value; rules=$rules }
86+
})
87+
$result = @{ user=[System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value; items=$list }
88+
[Console]::Out.Write((ConvertTo-Json -InputObject $result -Compress -Depth 6))
89+
} catch { [Console]::Out.Write('acl-query-error'); exit 1 }`;
90+
try {
91+
return classifyWindowsProfileAcl(
92+
JSON.parse(await runWindowsProfileScript(script, { OAA_INIT_DIR: dir, OAA_INIT_KEY: file })),
93+
);
94+
} catch (e) {
95+
const code = (e as NodeJS.ErrnoException).code;
96+
return typeof code === 'number' ? `acl-query-exit-${code}` : 'acl-query-unavailable';
97+
}
98+
}
4999
/** The `icacls` argument list that limits `file` to `user`; exported for tests. */
50100
export function icaclsArgs(file: string, user: string): string[] {
51101
return [file, '/inheritance:r', '/grant:r', `${user}:F`, '/q'];

‎test/profile-init.test.ts‎

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,27 @@ import {
1919
import os from 'node:os';
2020
import path from 'node:path';
2121
import { initialize, loadConfig } from '../src/config/config.js';
22-
import { restrictToOwner } from '../src/core/win-acl.js';
22+
import { classifyWindowsProfileAcl, restrictToOwner } from '../src/core/win-acl.js';
23+
24+
test('Windows owner-key decisions distinguish readable directories from writable directories or shared keys', () => {
25+
const self = 'S-1-5-21-123-1001',
26+
everyone = 'S-1-1-0';
27+
const own = { who: self, kind: 0, flags: 0, rights: 0x1f01ff };
28+
const shared = (rights: number, flags = 0) => ({ who: everyone, kind: 0, flags, rights });
29+
const check = (dir = own, key = own) =>
30+
classifyWindowsProfileAcl({
31+
user: self,
32+
items: [
33+
{ owner: 'S-1-5-32-544', rules: [own, dir] },
34+
{ owner: self, rules: [own, key] },
35+
],
36+
});
37+
assert.equal(check(shared(0x20089)), 'private');
38+
assert.equal(check(shared(0x40000000)), 'shared-directory');
39+
assert.equal(check(own, shared(1)), 'shared-key');
40+
assert.equal(check(shared(0x10000000, 2)), 'private');
41+
assert.equal(classifyWindowsProfileAcl({ user: self, items: [] }), 'unreadable');
42+
});
2343

2444
async function profile(t: TestContext) {
2545
const root = await mkdtemp(path.join(os.tmpdir(), 'oaa-init-test-'));

0 commit comments

Comments
 (0)