@deepseek-ai/dsh-sandbox-windows-acl 0.2.2-alpha.3 → 0.2.2-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/runner.ts ADDED
@@ -0,0 +1,229 @@
1
+ /**
2
+ * The windows-acl confinement runner: the argv-prefix wrapper the sandbox
3
+ * seam spawns in place of the caller's command. It creates the
4
+ * WRITE_RESTRICTED token with the workspace write-SID allowlist, spawns the
5
+ * wrapped argv under it with the CALLER'S stdio inherited (bytes flow
6
+ * straight through), mirrors the child's exit code, and revokes its temp
7
+ * grant on exit (workspace ACEs stay standing as the reuse cache).
8
+ *
9
+ * Stable argv contract (the seam builds it; a native-exe replacement would
10
+ * keep the same contract):
11
+ * [node, runner.js, '--workspace', <dir>, '--temp', <dir>,
12
+ * '--mode', <read-only|workspace-write>,
13
+ * ['--write-sid', <S-1-4-…>,
14
+ * '--temp-write-sid', <S-1-4-…>], '--', <argv...>]
15
+ *
16
+ * Modes:
17
+ * - workspace-write: the workspace and temp directories carry distinct
18
+ * capability-SID Write grants; other ACL-addressable writes are denied
19
+ * except for the documented Everyone and hard-link boundaries.
20
+ * - read-only: no capability-SID grants; the restricting list carries no
21
+ * capability SID, so a standing grant ACE from an earlier
22
+ * workspace-write period stays inert. BOTH modes drop Authenticated Users
23
+ * (CIM unavailable — documented in README) and INTERACTIVE/LOCAL (the
24
+ * Public tree writes are denied); the two lists share the keep-alive group
25
+ * (logon SID, EVERYONE) and differ only by the capabilities.
26
+ *
27
+ * `--write-sid` + `--temp-write-sid`: the seam's grant contract — the
28
+ * CALLER has already materialized distinct workspace and private-temp ACEs
29
+ * and owns their revocation, so the runner neither grants nor revokes
30
+ * (`manageDacls: false`). Both values are checked against their owning paths.
31
+ * Without the pair (standalone/agentless use), workspace-write treats
32
+ * `--temp` as a ROOT, creates a random private child directory, derives its
33
+ * own temp SID, and removes that directory after the child exits. In both
34
+ * flows the runner rewrites TMP/TEMP in its OWN environment to the private
35
+ * directory before spawning; the child inherits that block (`lpEnvironment`
36
+ * NULL; an explicit block through koffi trips ERROR_INVALID_PARAMETER in
37
+ * CreateProcessAsUserW, verified empirically). Read-only leaves the ambient
38
+ * temp entries untouched (writes there are denied anyway).
39
+ *
40
+ * Failure contract: every runner-side failure (bad args, missing
41
+ * directories, token/grant/spawn errors) prints `windows-acl-run: <detail>`
42
+ * to stderr and exits 127 — the seam's RUNNER_FAILURE_RULES matches that
43
+ * signature. The child is NEVER spawned unrestricted.
44
+ * @module @deepseek-ai/dsh-sandbox-windows-acl/runner
45
+ */
46
+
47
+ import { SUBPROCESS_CONTROL_ENV, SUBPROCESS_CONTROL_FD } from '@deepseek-ai/dsh-subprocess/control'
48
+ import { closeSync, existsSync, mkdtempSync, rmSync, statSync } from 'node:fs'
49
+ import { join } from 'node:path'
50
+
51
+ import { win32 } from './ffi.ts'
52
+ import { AclSandbox, assertTempRootOutsideWorkspace } from './index.ts'
53
+ import { tempWriteSid, workspaceWriteSid } from './workspace-sid.ts'
54
+
55
+ const RUNNER_SIGNATURE = 'windows-acl-run'
56
+ const RUNNER_FAILURE_EXIT = 127
57
+
58
+ class RunnerFailure extends Error {}
59
+
60
+ /** Print the runner-failure signature line and unwind. */
61
+ function fail(detail: string): never {
62
+ process.stderr.write(`${RUNNER_SIGNATURE}: ${detail}\n`)
63
+ throw new RunnerFailure(detail)
64
+ }
65
+
66
+ interface ParsedArgs {
67
+ workspace: string
68
+ temp: string
69
+ mode: 'read-only' | 'workspace-write'
70
+ writeSid: string | undefined
71
+ tempWriteSid: string | undefined
72
+ command: string
73
+ args: string[]
74
+ }
75
+
76
+ function parseArgs(raw: string[]): ParsedArgs {
77
+ let workspace: string | undefined
78
+ let temp: string | undefined
79
+ let mode: string | undefined
80
+ let writeSid: string | undefined
81
+ let parsedTempWriteSid: string | undefined
82
+ let index = 0
83
+ for (; index < raw.length; index++) {
84
+ const token = raw[index]
85
+ if (token === '--') {
86
+ index++
87
+ break
88
+ }
89
+ index++
90
+ const value = raw[index]
91
+ if (value === undefined) fail(`missing value after ${token}`)
92
+ switch (token) {
93
+ case '--workspace': workspace = value; break
94
+ case '--temp': temp = value; break
95
+ case '--mode': mode = value; break
96
+ case '--write-sid': writeSid = value; break
97
+ case '--temp-write-sid': parsedTempWriteSid = value; break
98
+ default: fail(`unknown argument: ${token}`)
99
+ }
100
+ }
101
+ if (workspace === undefined) fail('missing --workspace')
102
+ if (temp === undefined) fail('missing --temp')
103
+ if (mode !== 'read-only' && mode !== 'workspace-write') fail(`unknown mode: ${String(mode)}`)
104
+ const argv = raw.slice(index)
105
+ const command = argv[0]
106
+ if (command === undefined) fail('missing command after --')
107
+ return { workspace, temp, mode, writeSid, tempWriteSid: parsedTempWriteSid, command, args: argv.slice(1) }
108
+ }
109
+
110
+ function requireDirectory(label: string, path: string): void {
111
+ if (!existsSync(path) || !statSync(path).isDirectory()) {
112
+ fail(`${label} is not an existing directory: ${path}`)
113
+ }
114
+ }
115
+
116
+ async function main(): Promise<number> {
117
+ const parsed = parseArgs(process.argv.slice(2))
118
+ // Both directories are validated in both modes: a provider bug that passes
119
+ // a bogus root must fail loudly at the runner boundary, never mid-child.
120
+ requireDirectory('--workspace', parsed.workspace)
121
+ requireDirectory('--temp', parsed.temp)
122
+
123
+ const seamManaged = parsed.writeSid !== undefined || parsed.tempWriteSid !== undefined
124
+ if (parsed.mode === 'read-only' && seamManaged) {
125
+ fail('read-only does not accept --write-sid or --temp-write-sid')
126
+ }
127
+ if (parsed.mode === 'workspace-write' && (parsed.writeSid === undefined) !== (parsed.tempWriteSid === undefined)) {
128
+ fail('workspace-write requires --write-sid and --temp-write-sid together')
129
+ }
130
+ if (parsed.mode === 'workspace-write') {
131
+ assertTempRootOutsideWorkspace(parsed.workspace, parsed.temp)
132
+ }
133
+
134
+ const api = await win32()
135
+ // Ignore this process's own CTRL+C: the confined child (same console) keeps
136
+ // handling its own; the runner must survive to revoke grants and mirror the
137
+ // child's exit code.
138
+ if (api.setConsoleCtrlHandler(null, 1) === 0) {
139
+ fail(`SetConsoleCtrlHandler failed (Win32 ${api.getLastError()})`)
140
+ }
141
+
142
+ let ownedTempDir: string | undefined
143
+ let sandbox: AclSandbox | undefined
144
+ let initialized = false
145
+ try {
146
+ let privateTempDir: string | null = null
147
+ let writeSid: string | undefined
148
+ let privateTempSid: string | undefined
149
+ if (parsed.mode === 'workspace-write') {
150
+ writeSid = workspaceWriteSid(parsed.workspace)
151
+ if (seamManaged) {
152
+ if (parsed.writeSid !== writeSid) fail('--write-sid does not match --workspace')
153
+ privateTempDir = parsed.temp
154
+ privateTempSid = tempWriteSid(privateTempDir)
155
+ if (parsed.tempWriteSid !== privateTempSid) fail('--temp-write-sid does not match --temp')
156
+ } else {
157
+ ownedTempDir = mkdtempSync(join(parsed.temp, 'dsh-'))
158
+ privateTempDir = ownedTempDir
159
+ privateTempSid = tempWriteSid(privateTempDir)
160
+ }
161
+ }
162
+ sandbox = new AclSandbox({
163
+ writableDirs: parsed.mode === 'workspace-write' ? [parsed.workspace] : [],
164
+ tempDir: privateTempDir,
165
+ mode: parsed.mode,
166
+ ...writeSid === undefined ? {} : { writeSid },
167
+ ...privateTempSid === undefined ? {} : { tempWriteSid: privateTempSid },
168
+ manageDacls: !seamManaged,
169
+ })
170
+ await sandbox.init()
171
+ initialized = true
172
+
173
+ if (privateTempDir !== null) {
174
+ if (api.setEnvironmentVariableW('TMP', privateTempDir) === 0) {
175
+ fail(`SetEnvironmentVariableW TMP failed (Win32 ${api.getLastError()})`)
176
+ }
177
+ if (api.setEnvironmentVariableW('TEMP', privateTempDir) === 0) {
178
+ fail(`SetEnvironmentVariableW TEMP failed (Win32 ${api.getLastError()})`)
179
+ }
180
+ }
181
+
182
+ const child = sandbox.spawn({
183
+ command: parsed.command,
184
+ args: parsed.args,
185
+ stdio: 'inherit',
186
+ ...process.env[SUBPROCESS_CONTROL_ENV] === 'pipe' ? { controlFileDescriptor: SUBPROCESS_CONTROL_FD } : {},
187
+ })
188
+ if (process.env[SUBPROCESS_CONTROL_ENV] === 'pipe') closeSync(SUBPROCESS_CONTROL_FD)
189
+ const result = await child.wait()
190
+ return result.exitCode
191
+ } finally {
192
+ // Cleanup failures must not mask the child's exit code: report and keep going.
193
+ if (initialized) {
194
+ try {
195
+ sandbox?.dispose()
196
+ } catch (error) {
197
+ process.stderr.write(`${RUNNER_SIGNATURE}: cleanup: ${error instanceof Error ? error.message : String(error)}\n`)
198
+ }
199
+ }
200
+ if (ownedTempDir !== undefined) {
201
+ try {
202
+ rmSync(ownedTempDir, { recursive: true, force: true })
203
+ } catch (error) {
204
+ process.stderr.write(`${RUNNER_SIGNATURE}: cleanup: ${error instanceof Error ? error.message : String(error)}\n`)
205
+ }
206
+ }
207
+ }
208
+ }
209
+
210
+ main().then(
211
+ (exitCode) => {
212
+ // Exit-code mirroring is full-width on Windows, verified empirically on
213
+ // this machine (Windows 11 build 26200, Node 24): a child that exits
214
+ // with the NTSTATUS 0xC0000005 (STATUS_ACCESS_VIOLATION) is read back
215
+ // by GetExitCodeProcess as the uint32 3221225477, and after
216
+ // process.exitCode = 3221225477 the parent observes exactly
217
+ // 3221225477 (spawnSync status). PowerShell's $LASTEXITCODE and cmd
218
+ // print the signed view (-1073741819), but no truncation or masking
219
+ // happens anywhere in the chain — the mirror contract holds for the
220
+ // full 32-bit range, so no re-mapping is needed.
221
+ process.exitCode = exitCode
222
+ },
223
+ (error: unknown) => {
224
+ if (!(error instanceof RunnerFailure)) {
225
+ process.stderr.write(`${RUNNER_SIGNATURE}: ${error instanceof Error ? error.message : String(error)}\n`)
226
+ }
227
+ process.exitCode = RUNNER_FAILURE_EXIT
228
+ },
229
+ )
package/src/spawn.ts ADDED
@@ -0,0 +1,60 @@
1
+ /** Restricted-token adapters over the shared Win32 process owner. */
2
+
3
+ import {
4
+ spawnInheritedJobProcess,
5
+ spawnPipedProcess,
6
+ waitForProcessExit,
7
+ } from '@deepseek-ai/dsh-win32-process'
8
+ import type {
9
+ NativePtr,
10
+ SpawnedJobProcess,
11
+ SpawnedPipedProcess,
12
+ } from '@deepseek-ai/dsh-win32-process'
13
+ import type { Win32Bindings } from './ffi.ts'
14
+
15
+ export { drainPipe } from '@deepseek-ai/dsh-win32-process'
16
+
17
+ /** Restricted-token child with piped stdio resources. */
18
+ export interface SpawnedNative extends SpawnedPipedProcess {}
19
+ /** Restricted-token child assigned to a kill-on-close Job. */
20
+ export interface SpawnedInherited extends SpawnedJobProcess {}
21
+
22
+ /**
23
+ * Spawn a restricted-token child with piped stdout/stderr.
24
+ * @param api - ACL/token binding table.
25
+ * @param token - restricted primary token.
26
+ * @param options - command, args, and working directory.
27
+ * @returns process and caller-owned pipe handles.
28
+ */
29
+ export function spawnSandboxed(
30
+ api: Win32Bindings,
31
+ token: NativePtr,
32
+ options: { command: string; args: readonly string[]; cwd: string },
33
+ ): SpawnedNative {
34
+ return spawnPipedProcess(api, { ...options, token })
35
+ }
36
+
37
+ /**
38
+ * Spawn a restricted-token child in a kill-on-close Job with inherited stdio.
39
+ * @param api - ACL/token binding table.
40
+ * @param token - restricted primary token.
41
+ * @param options - command, args, and working directory.
42
+ * @returns process and Job handles after assignment and resume.
43
+ */
44
+ export function spawnSandboxedInherited(
45
+ api: Win32Bindings,
46
+ token: NativePtr,
47
+ options: { command: string; args: readonly string[]; cwd: string; controlFileDescriptor?: 7 },
48
+ ): SpawnedInherited {
49
+ return spawnInheritedJobProcess(api, { ...options, token })
50
+ }
51
+
52
+ /**
53
+ * Wait for a restricted child and close its process handle.
54
+ * @param api - ACL/token binding table.
55
+ * @param process - caller-owned process handle.
56
+ * @returns direct process exit code.
57
+ */
58
+ export function waitForExit(api: Win32Bindings, process: NativePtr): number {
59
+ return waitForProcessExit(api, process)
60
+ }
package/src/token.ts ADDED
@@ -0,0 +1,243 @@
1
+ /**
2
+ * Restricted-token construction: open the current process token, extract its
3
+ * logon SID, build the well-known SIDs, and call CreateRestrictedToken with
4
+ * the POC's restricting-SID allowlist. Every API call is checked; any failure
5
+ * throws with the API name and the exact Win32 code — the original POC ignored
6
+ * all of these and silently ran children with the FULL, unrestricted token.
7
+ * @module @deepseek-ai/dsh-sandbox-windows-acl/token
8
+ */
9
+
10
+ import { allocBytes, allocPtrSlot, allocUint32, decodePtr, decodePtrAt, decodeUint32, encodeUint32, isNullPtr, ptrAddress, throwLastError, throwWin32 } from './ffi.ts'
11
+ import type { NativePtr, Win32Bindings } from './ffi.ts'
12
+ import { buildExplicitAccess } from './acl.ts'
13
+ import * as abi from './win32-abi.ts'
14
+
15
+ /**
16
+ * Open the current process's access token with the rights
17
+ * CreateRestrictedToken requires (the POC's OpenProcessToken call; the token
18
+ * handle is obtained through a real OpenProcess handle because the
19
+ * GetCurrentProcess() pseudo-handle is not addressable through koffi).
20
+ * @param api - the binding table.
21
+ * @returns the opened token handle.
22
+ */
23
+ export function openCurrentProcessToken(api: Win32Bindings): NativePtr {
24
+ const processHandle = api.openProcess(abi.PROCESS_QUERY_INFORMATION, 0, process.pid)
25
+ if (isNullPtr(processHandle)) throwLastError(api, 'OpenProcess', `pid ${process.pid}`)
26
+
27
+ const tokenSlot = allocPtrSlot()
28
+ const opened = api.openProcessToken(
29
+ processHandle,
30
+ abi.TOKEN_QUERY | abi.TOKEN_DUPLICATE | abi.TOKEN_ADJUST_DEFAULT | abi.TOKEN_ASSIGN_PRIMARY,
31
+ tokenSlot,
32
+ )
33
+ if (opened === 0) {
34
+ const win32Code = api.getLastError()
35
+ api.closeHandle(processHandle) // best-effort on the error path
36
+ throwWin32(api, 'OpenProcessToken', win32Code, `pid ${process.pid}`)
37
+ }
38
+ if (api.closeHandle(processHandle) === 0) throwLastError(api, 'CloseHandle', 'OpenProcess process handle')
39
+ const token = decodePtr(tokenSlot)
40
+ if (token === null) throwWin32(api, 'OpenProcessToken', api.getLastError(), 'null token handle')
41
+ return token
42
+ }
43
+
44
+ /**
45
+ * Find and copy the token's logon session SID (S-1-5-5-x-y, attribute
46
+ * SE_GROUP_LOGON_ID). The restricted token needs it for WinSta0/desktop and
47
+ * other per-logon objects; the POC extracts it the same way.
48
+ * @param api - the binding table.
49
+ * @param token - the token whose groups are scanned.
50
+ * @returns a copied logon SID (thrown when the token carries none).
51
+ */
52
+ export function findLogonSid(api: Win32Bindings, token: NativePtr): NativePtr {
53
+ const neededSlot = allocUint32()
54
+ api.getTokenInformation(token, abi.TokenGroups, null, 0, neededSlot) // expected to fail with ERROR_INSUFFICIENT_BUFFER
55
+ const needed = decodeUint32(neededSlot)
56
+ if (needed === 0) throwLastError(api, 'GetTokenInformation', 'TokenGroups size query')
57
+ if (needed < abi.TOKEN_GROUPS_OFFSET) throwWin32(api, 'GetTokenInformation', api.getLastError(), `implausible TokenGroups size ${needed}`)
58
+
59
+ const groups = Buffer.alloc(needed)
60
+ if (api.getTokenInformation(token, abi.TokenGroups, groups, groups.length, neededSlot) === 0) {
61
+ throwLastError(api, 'GetTokenInformation', 'TokenGroups')
62
+ }
63
+ const groupCount = groups.readUInt32LE(0)
64
+ for (let index = 0; index < groupCount; index++) {
65
+ const sidPtr = decodePtrAt(groups, abi.TOKEN_GROUPS_OFFSET + index * abi.SID_AND_ATTRIBUTES_SIZE)
66
+ const attributes = groups.readUInt32LE(abi.TOKEN_GROUPS_OFFSET + index * abi.SID_AND_ATTRIBUTES_SIZE + 8)
67
+ // >>> 0: JS bitwise & is signed 32-bit; SE_GROUP_LOGON_ID has bit 31 set.
68
+ const isLogonId = ((attributes & abi.SE_GROUP_LOGON_ID) >>> 0) === (abi.SE_GROUP_LOGON_ID >>> 0)
69
+ if (sidPtr === null || !isLogonId) continue
70
+ const sidLength = api.getLengthSid(sidPtr)
71
+ if (sidLength === 0) throwLastError(api, 'GetLengthSid', `logon SID group ${index}`)
72
+ const copy = allocBytes(sidLength)
73
+ if (api.copySid(sidLength, copy, sidPtr) === 0) throwLastError(api, 'CopySid', `logon SID group ${index}`)
74
+ return copy
75
+ }
76
+ throw new Error(`CreateRestrictedToken prerequisite failed: no logon SID found among ${groupCount} token groups`)
77
+ }
78
+
79
+ /**
80
+ * Create one well-known SID (68-byte buffer) and assert its validity.
81
+ * @param api - the binding table.
82
+ * @param type - the WELL_KNOWN_SID_TYPE to create.
83
+ * @returns the created SID pointer.
84
+ */
85
+ export function makeWellKnownSid(api: Win32Bindings, type: number): NativePtr {
86
+ const sid = allocBytes(abi.SECURITY_MAX_SID_SIZE)
87
+ const sizeSlot = allocUint32()
88
+ encodeUint32(sizeSlot, abi.SECURITY_MAX_SID_SIZE)
89
+ if (api.createWellKnownSid(type, null, sid, sizeSlot) === 0) {
90
+ throwLastError(api, 'CreateWellKnownSid', `type ${type}`)
91
+ }
92
+ if (api.isValidSid(sid) === 0) throwLastError(api, 'IsValidSid', `CreateWellKnownSid type ${type}`)
93
+ return sid
94
+ }
95
+
96
+ /**
97
+ * Merge one full-access allow ACE for `sidPtr` into the token's DEFAULT DACL
98
+ * — the DACL every NEW object the token holder creates (without an explicit
99
+ * security descriptor) takes. The restricted token inherits the user's
100
+ * default DACL verbatim, which names no restricting SID: a new anonymous pipe
101
+ * (child stdio) therefore fails the write pass-2 check at creation
102
+ * (ERROR_ACCESS_DENIED; Node surfaces it as spawn EPERM), breaking every
103
+ * piped-stdio grandchild spawn. The merged ACE names a RESTRICTING SID (the
104
+ * write SID under workspace-write, Everyone under read-only), so each new
105
+ * object's own DACL passes pass-2 while object creation itself stays gated by
106
+ * the parent container's DACL (files outside the granted trees remain
107
+ * uncreatable). Fails closed: any Win32 failure throws before the spawn.
108
+ * @param api - the binding table.
109
+ * @param token - the restricted token to adjust (requires TOKEN_ADJUST_DEFAULT).
110
+ * @param sidPtr - the restricting SID whose full-access ACE joins the default DACL.
111
+ */
112
+ export function setTokenDefaultDaclGrant(api: Win32Bindings, token: NativePtr, sidPtr: NativePtr): void {
113
+ const neededSlot = allocUint32()
114
+ api.getTokenInformation(token, abi.TokenDefaultDacl, null, 0, neededSlot) // expected to fail with ERROR_INSUFFICIENT_BUFFER
115
+ const needed = decodeUint32(neededSlot)
116
+ if (needed === 0) throwLastError(api, 'GetTokenInformation', 'TokenDefaultDacl size query')
117
+ const buffer = Buffer.alloc(needed)
118
+ if (api.getTokenInformation(token, abi.TokenDefaultDacl, buffer, buffer.length, neededSlot) === 0) {
119
+ throwLastError(api, 'GetTokenInformation', 'TokenDefaultDacl')
120
+ }
121
+ const currentDacl = decodePtrAt(buffer, 0)
122
+ if (currentDacl === null) {
123
+ throw new Error('setTokenDefaultDaclGrant: the token carries no default DACL to extend')
124
+ }
125
+ const newDaclSlot = allocPtrSlot()
126
+ const result = api.setEntriesInAclW(
127
+ 1,
128
+ buildExplicitAccess(sidPtr, abi.GRANT_ACCESS, abi.FILE_ALL_ACCESS),
129
+ currentDacl,
130
+ newDaclSlot,
131
+ )
132
+ if (result !== abi.ERROR_SUCCESS) throwWin32(api, 'SetEntriesInAclW', result, 'default DACL merge')
133
+ const newDacl = decodePtr(newDaclSlot)
134
+ if (newDacl === null) throwWin32(api, 'SetEntriesInAclW', result, 'null merged default DACL')
135
+ // TOKEN_DEFAULT_DACL { PACL DefaultDacl; } — the struct is exactly the
136
+ // pointer; SetTokenInformation copies the ACL before returning.
137
+ const info = Buffer.alloc(8)
138
+ info.writeBigUInt64LE(newDacl, 0)
139
+ if (api.setTokenInformation(token, abi.TokenDefaultDacl, info, info.length) === 0) {
140
+ const win32Code = api.getLastError()
141
+ api.localFree(newDacl)
142
+ throwWin32(api, 'SetTokenInformation', win32Code, 'TokenDefaultDacl')
143
+ }
144
+ api.localFree(newDacl)
145
+ }
146
+
147
+ /**
148
+ * Lower the restricted token's integrity level to Low (S-1-16-4096), the level
149
+ * the mandatory labels `grantWrite` applies are matched against; a token left
150
+ * at Medium would ignore them. Requires TOKEN_ADJUST_DEFAULT on the token;
151
+ * fails closed before any child is spawned.
152
+ * @param api - the binding table.
153
+ * @param token - the restricted token to lower.
154
+ * @param lowLabelSidPtr - the Low integrity SID (S-1-16-4096).
155
+ */
156
+ export function restrictTokenIntegrity(api: Win32Bindings, token: NativePtr, lowLabelSidPtr: NativePtr): void {
157
+ const sidLength = api.getLengthSid(lowLabelSidPtr)
158
+ if (sidLength === 0) throwLastError(api, 'GetLengthSid', 'Low integrity label SID')
159
+ const info = Buffer.alloc(abi.TOKEN_MANDATORY_LABEL_SIZE + sidLength)
160
+ info.writeBigUInt64LE(ptrAddress(lowLabelSidPtr), 0) // Label.Sid
161
+ info.writeUInt32LE(abi.SE_GROUP_INTEGRITY, 8) // Label.Attributes
162
+ if (api.setTokenInformation(token, abi.TokenIntegrityLevel, info, info.length) === 0) {
163
+ throwLastError(api, 'SetTokenInformation', 'TokenIntegrityLevel (Low)')
164
+ }
165
+ }
166
+
167
+ /** Pack `SID_AND_ATTRIBUTES[count]` (16-byte stride; Attributes stay 0). */
168
+ function buildRestrictingSids(sids: readonly NativePtr[]): Buffer {
169
+ const buffer = Buffer.alloc(abi.SID_AND_ATTRIBUTES_SIZE * sids.length)
170
+ sids.forEach((sid, index) => {
171
+ buffer.writeBigUInt64LE(ptrAddress(sid), abi.SID_AND_ATTRIBUTES_SIZE * index)
172
+ })
173
+ return buffer
174
+ }
175
+
176
+ /** The well-known SID packed into every restricted token's restricting list. */
177
+ export interface RestrictingSidSet {
178
+ world: NativePtr
179
+ }
180
+
181
+ /**
182
+ * Create the write-restricted token with the mode-selected restricting list
183
+ * (verified on Win11 26200, see the POC-worktree restrict-variant harness):
184
+ * - read-only: [logon SID, EVERYONE]
185
+ * - workspace-write: [logon SID, EVERYONE, workspace SID, optional temp SID]
186
+ *
187
+ * The logon SID + EVERYONE keep-alive group is shared by both modes: early
188
+ * DLL init dies with 0xC0000142 and CNG (`\Device\CNG` write trustee —
189
+ * pwsh crashes 0xE0434352) fails without them. The write SIDs join ONLY
190
+ * workspace-write — read-only carries no write SID, so a standing grant ACE
191
+ * from an earlier workspace-write period (a `/permission` mode downgrade, or
192
+ * a crash-resumed session) stays INERT under read-only: the WRITE_RESTRICTED
193
+ * pass-2 check grants only what the restricting list carries, keeping that
194
+ * workspace grant inert under read-only while the unrevoked ACE keeps the
195
+ * re-upgrade free (the grant's exact-ACE skip — no re-propagation).
196
+ * Everyone's own ambient grants remain the documented partial boundary.
197
+ * Authenticated Users is absent from BOTH lists: the WMI
198
+ * namespace security check fails (0x80041003), so CIM is unavailable in
199
+ * every confined mode, and the C:\-root tree-creation escape (standing
200
+ * `AU:(AD)` + `AU:(OI)(CI)(IO)(M)` ACEs) is closed in both — documented in
201
+ * README. INTERACTIVE/LOCAL are absent from BOTH lists too — the host's
202
+ * Public tree grants write to INTERACTIVE, so removing it closes that
203
+ * escape. S-1-2-1 (console logon) is intentionally absent: the package
204
+ * README's "Console isolation is unavailable" entry records the verified
205
+ * failure modes. FAILS CLOSED: any failure throws — never
206
+ * spawn unrestricted.
207
+ * @param api - the binding table.
208
+ * @param currentToken - the process token to restrict.
209
+ * @param logonSid - the copied logon session SID.
210
+ * @param writeSids - the distinct write SIDs forming the workspace and
211
+ * optional temp allowlists (workspace-write only; empty under read-only).
212
+ * @param known - the well-known SIDs entering the restricting list.
213
+ * @param mode - selects the restricting list (workspace-write adds the capability SIDs).
214
+ * @returns the restricted token handle.
215
+ */
216
+ export function createRestrictedToken(
217
+ api: Win32Bindings,
218
+ currentToken: NativePtr,
219
+ logonSid: NativePtr,
220
+ writeSids: readonly NativePtr[],
221
+ known: RestrictingSidSet,
222
+ mode: 'read-only' | 'workspace-write',
223
+ ): NativePtr {
224
+ const restrictingSids = buildRestrictingSids(mode === 'read-only'
225
+ ? [logonSid, known.world]
226
+ : writeSids.length === 0
227
+ ? (() => { throw new Error('createRestrictedToken: workspace-write restricting list requires at least one write SID') })()
228
+ : [logonSid, known.world, ...writeSids])
229
+ const tokenSlot = allocPtrSlot()
230
+ const created = api.createRestrictedToken(
231
+ currentToken,
232
+ abi.DISABLE_MAX_PRIVILEGE | abi.WRITE_RESTRICTED,
233
+ 0, null, // no SIDs disabled
234
+ 0, null, // no privileges deleted
235
+ restrictingSids.length / abi.SID_AND_ATTRIBUTES_SIZE,
236
+ restrictingSids,
237
+ tokenSlot,
238
+ )
239
+ if (created === 0) throwLastError(api, 'CreateRestrictedToken', `restricting SIDs: ${restrictingSids.length / abi.SID_AND_ATTRIBUTES_SIZE}`)
240
+ const token = decodePtr(tokenSlot)
241
+ if (token === null) throwWin32(api, 'CreateRestrictedToken', api.getLastError(), 'null token handle')
242
+ return token
243
+ }
@@ -0,0 +1,131 @@
1
+ /** ACL/token-specific Win32 constants. */
2
+
3
+ /** OpenProcess access required to query the current process token. */
4
+ export const PROCESS_QUERY_INFORMATION = 0x0400
5
+ /** Token right required by CreateProcessAsUserW. */
6
+ export const TOKEN_ASSIGN_PRIMARY = 0x0001
7
+ /** Token right required by DuplicateTokenEx. */
8
+ export const TOKEN_DUPLICATE = 0x0002
9
+ /** Token right required to read token information. */
10
+ export const TOKEN_QUERY = 0x0008
11
+ /** Token right required to replace the token default DACL. */
12
+ export const TOKEN_ADJUST_DEFAULT = 0x0080
13
+ /** Group attribute identifying the token logon SID. */
14
+ export const SE_GROUP_LOGON_ID = 0xC0000000
15
+ /** Standard-rights portion excluded from the write capability grant. */
16
+ export const STANDARD_RIGHTS_WRITE = 0x00020000
17
+ /** Generic file write access bits. */
18
+ export const FILE_GENERIC_WRITE = 0x00120116
19
+ /** Delete or rename an object. */
20
+ export const DELETE = 0x00010000
21
+ /** Delete or rename a directory child. */
22
+ export const FILE_DELETE_CHILD = 0x0040
23
+ /**
24
+ * Capability-SID access mask granting write, delete, and child deletion.
25
+ * WRITE_DAC and WRITE_OWNER stay excluded so a confined child cannot rewrite
26
+ * DACLs or take ownership to escape the allowlist.
27
+ */
28
+ export const GRANT_MASK = (FILE_GENERIC_WRITE | DELETE | FILE_DELETE_CHILD) & ~STANDARD_RIGHTS_WRITE
29
+ /** Full access used in the restricted token default DACL. */
30
+ export const FILE_ALL_ACCESS = 0x1F01FF
31
+ /** CreateRestrictedToken flag that disables maximum privileges. */
32
+ export const DISABLE_MAX_PRIVILEGE = 0x1
33
+ /** CreateRestrictedToken limited-user flag. */
34
+ export const LUA_TOKEN = 0x4
35
+ /** Restrict write access to the listed restricting SIDs. */
36
+ export const WRITE_RESTRICTED = 0x8
37
+ /** WELL_KNOWN_SID_TYPE value for Everyone. */
38
+ export const WinWorldSid = 1
39
+ /** TOKEN_INFORMATION_CLASS value for token groups. */
40
+ export const TokenGroups = 2
41
+ /** TOKEN_INFORMATION_CLASS value for the token default DACL. */
42
+ export const TokenDefaultDacl = 6
43
+ /** SECURITY_INFORMATION flag selecting the DACL. */
44
+ export const DACL_SECURITY_INFORMATION = 0x00000004
45
+ /** SECURITY_INFORMATION flag selecting the mandatory integrity label. */
46
+ export const LABEL_SECURITY_INFORMATION = 0x00000010
47
+ /** ACE type carrying a mandatory integrity label. */
48
+ export const SYSTEM_MANDATORY_LABEL_ACE_TYPE = 0x11
49
+ /**
50
+ * Mandatory policy denying write-class access to higher-integrity objects.
51
+ * The kernel applies it inside the access check, so it also covers writes and
52
+ * deletes granted through a parent directory's FILE_DELETE_CHILD right —
53
+ * the path the write-restricted pass-2 intersection does not reach.
54
+ */
55
+ export const SYSTEM_MANDATORY_LABEL_NO_WRITE_UP = 0x00000001
56
+ /** TOKEN_INFORMATION_CLASS value for the token's integrity level. */
57
+ export const TokenIntegrityLevel = 25
58
+ /** Group attribute marking the integrity SID of a TOKEN_MANDATORY_LABEL. */
59
+ export const SE_GROUP_INTEGRITY = 0x00000020
60
+ /** WELL_KNOWN_SID_TYPE value for the Low mandatory level (S-1-16-4096). */
61
+ export const WinLowLabelSid = 66
62
+ /** x64 TOKEN_MANDATORY_LABEL byte size (the SID is referenced, not embedded). */
63
+ export const TOKEN_MANDATORY_LABEL_SIZE = 16
64
+ /** x64 ACL header byte size (AclRevision, Sbz1, AclSize, AceCount, Sbz2). */
65
+ export const ACL_HEADER_SIZE = 8
66
+ /** Bytes a SYSTEM_MANDATORY_LABEL_ACE occupies beyond the ACL header and its SID. */
67
+ export const MANDATORY_ACE_OVERHEAD = 8
68
+ /** ACL revision accepted by InitializeAcl and AddMandatoryAce. */
69
+ export const ACL_REVISION = 2
70
+ /** LocalAlloc flag selecting zero-initialized fixed memory (LMEM_FIXED | LMEM_ZEROINIT). */
71
+ export const LPTR = 0x0040
72
+ /** SE_OBJECT_TYPE value for filesystem objects. */
73
+ export const SE_FILE_OBJECT = 1
74
+ /** TRUSTEE_TYPE value used when trustee classification is unknown. */
75
+ export const TRUSTEE_IS_UNKNOWN = 0
76
+ /** TRUSTEE_FORM value indicating a SID pointer. */
77
+ export const TRUSTEE_IS_SID = 0
78
+ /** Trustee record has no chained trustee. */
79
+ export const NO_MULTIPLE_TRUSTEE = 0
80
+ /** EXPLICIT_ACCESS mode that grants access. */
81
+ export const GRANT_ACCESS = 1
82
+ /** EXPLICIT_ACCESS mode that denies access. */
83
+ export const DENY_ACCESS = 3
84
+ /** EXPLICIT_ACCESS mode that revokes access. */
85
+ export const REVOKE_ACCESS = 4
86
+ /** ACE inheritance flags for child containers and objects. */
87
+ export const SUB_CONTAINERS_AND_OBJECTS_INHERIT = 0x3
88
+ /** ACE inheritance flag for child containers only (directories; files do not inherit). */
89
+ export const CONTAINER_INHERIT_ACE = 0x2
90
+ /** Legacy Win32 maximum path character count used by GetTempPathW. */
91
+ export const MAX_PATH = 260
92
+ /** Successful Win32 status code. */
93
+ export const ERROR_SUCCESS = 0
94
+ /** Win32 error reported when an immediate byte-range lock cannot be obtained. */
95
+ export const ERROR_LOCK_VIOLATION = 33
96
+ /** Generic read access bit. */
97
+ export const GENERIC_READ = 0x80000000
98
+ /** Generic write access bit. */
99
+ export const GENERIC_WRITE = 0x40000000
100
+ /** CreateFile share-read flag. */
101
+ export const FILE_SHARE_READ = 0x00000001
102
+ /** CreateFile share-write flag. */
103
+ export const FILE_SHARE_WRITE = 0x00000002
104
+ /** CreateFile share-delete flag. */
105
+ export const FILE_SHARE_DELETE = 0x00000004
106
+ /** CreateFile disposition that opens or creates the file. */
107
+ export const OPEN_ALWAYS = 4
108
+ /** LockFileEx exclusive-lock flag. */
109
+ export const LOCKFILE_EXCLUSIVE_LOCK = 0x2
110
+ /** LockFileEx immediate-failure flag. */
111
+ export const LOCKFILE_FAIL_IMMEDIATELY = 0x1
112
+ /** ACE type for an allowed-access entry. */
113
+ export const ACCESS_ALLOWED_ACE_TYPE = 0
114
+ /** ACE type for a denied-access entry (shares the allowed ACE's Mask/SID layout). */
115
+ export const ACCESS_DENIED_ACE_TYPE = 1
116
+ /** Maximum SID sub-authority count. */
117
+ export const SID_MAX_SUB_AUTHORITIES = 15
118
+ /** ACE flag marking inherited entries. */
119
+ export const INHERITED_ACE = 0x10
120
+ /** Maximum SID allocation size in bytes. */
121
+ export const SECURITY_MAX_SID_SIZE = 68
122
+ /** x64 SID_AND_ATTRIBUTES byte size. */
123
+ export const SID_AND_ATTRIBUTES_SIZE = 16
124
+ /** x64 TOKEN_GROUPS offset of the first group entry. */
125
+ export const TOKEN_GROUPS_OFFSET = 8
126
+ /** x64 EXPLICIT_ACCESS_W byte size. */
127
+ export const EXPLICIT_ACCESS_W_SIZE = 48
128
+ /** x64 offset of TRUSTEE_W inside EXPLICIT_ACCESS_W. */
129
+ export const TRUSTEE_W_OFFSET = 16
130
+ /** x64 offset of ptstrName inside TRUSTEE_W. */
131
+ export const TRUSTEE_W_PTSTRNAME_OFFSET = 24