-
Notifications
You must be signed in to change notification settings - Fork 64
Expand file tree
/
Copy pathtrusted-executable.mts
More file actions
340 lines (316 loc) · 11.5 KB
/
Copy pathtrusted-executable.mts
File metadata and controls
340 lines (316 loc) · 11.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
/**
* PATH-trust-inverting executable resolution.
*
* The CLI routinely runs inside a repository checkout it did not author, so
* PATH is attacker-influenced: a hostile checkout can ship `./bin/git`,
* `node_modules/.bin/python`, or a `.venv/bin` shim and have a plain
* `spawn('git')` pick it up. This module inverts the usual trust assumption —
* anything that canonicalizes INSIDE the protected root is untrusted, and a
* PATH entry that produced such a hit is dropped from the environment handed
* to the child.
*
* Key Functions:
*
* - ResolveTrustedExecutable: Resolve a command name (or literal path) to a
* canonical executable outside the protected root, paired with an environment
* whose PATH has every poisoned entry removed.
* - DefaultProtectedRoot: The outermost `.git`-marked ancestor of a directory, so
* a nested worktree cannot escape protection by way of its parent.
* - ListExecutableProbes: The per-platform suffix table probed for a bare command
* name.
* - IsPathWithinRoot: Containment test used for every trust decision.
*
* Usage: Resolve once per spawn site, then spawn the returned absolute
* `executable` with the returned `environment` — never the bare name, which
* would re-consult the child's own PATH and undo the sanitization.
*/
import { constants as fsConstants, existsSync, promises as fs } from 'node:fs'
import path from 'node:path'
import { isWin32 } from '@socketsecurity/lib-stable/constants/platform'
export type ExecutableProbe = {
runnable: boolean
suffix: string
}
export type TrustedExecutable = {
environment: Record<string, string | undefined>
executable: string
}
export type TrustedExecutableOptions = {
/**
* Treat the host as Windows. Defaults to the real platform; an explicit
* value exists so the Windows probe table and the F_OK accessibility check
* are exercisable from a POSIX test run.
*/
windows?: boolean | undefined
}
// A Windows candidate that already carries an executable suffix must not have
// a second one appended (`python.exe` -> `python.exe.exe`).
// require-regex-comment: trailing Windows executable suffix, case-insensitive.
const WINDOWS_EXECUTABLE_SUFFIX_RE = /\.(?:com|exe)$/iu
/**
* Resolve a path to its canonical form, or undefined when it does not resolve.
*/
export async function canonicalizePath(
target: string,
): Promise<string | undefined> {
try {
return await fs.realpath(target)
} catch {
return undefined
}
}
/**
* The outermost `.git`-marked ancestor of `cwd` (realpathed), falling back to
* the realpath of `cwd` itself.
*
* Walking to the OUTERMOST marker rather than the nearest one matters for
* nested checkouts: protecting only the inner worktree would leave the parent
* repository's `node_modules/.bin` trusted, which is the exact escape hatch a
* hostile nested repository would use.
*/
export async function defaultProtectedRoot(cwd: string): Promise<string> {
const start = (await canonicalizePath(cwd)) ?? path.resolve(cwd)
const { root } = path.parse(start)
let outermost: string | undefined
let dir = start
// Check the starting directory itself before ascending, so a checkout root
// passed directly still matches.
do {
// A `.git` marker is a directory in a normal clone and a file in a
// worktree or submodule; either proves a repository boundary.
if (existsSync(path.join(dir, '.git'))) {
outermost = dir
}
if (dir === root) {
break
}
dir = path.dirname(dir)
} while (dir)
return outermost ?? start
}
/**
* Locate the PATH value in an environment, matching the key case-insensitively
* because Windows spells it `Path`.
*/
export function findEnvPathValue(
env: Readonly<Record<string, string | undefined>>,
): string | undefined {
const names = Object.keys(env)
for (let i = 0, { length } = names; i < length; i += 1) {
const name = names[i]!
if (name.toUpperCase() === 'PATH') {
return env[name]
}
}
return undefined
}
export function getTrustedExecutableLookups(
candidate: string,
entries: string[],
options?: TrustedExecutableOptions | undefined,
): Array<{ entry: string | undefined; runnable: boolean; target: string }> {
const { windows = isWin32() } = { __proto__: null, ...options }
const probes = listExecutableProbes(candidate, { windows })
// A candidate carrying a separator is a literal path, not a PATH lookup, so
// it is never attributed to a PATH entry.
const isPathLike = candidate.includes('/') || candidate.includes('\\')
const lookups: Array<{
entry: string | undefined
runnable: boolean
target: string
}> = []
if (isPathLike) {
lookups.push({
entry: undefined,
runnable: true,
target: path.resolve(candidate),
})
} else {
for (let i = 0, { length } = entries; i < length; i += 1) {
const entry = entries[i]!
for (let j = 0, { length: probeCount } = probes; j < probeCount; j += 1) {
const probe = probes[j]!
lookups.push({
entry,
runnable: probe.runnable,
target: path.join(entry, `${candidate}${probe.suffix}`),
})
}
}
}
return lookups
}
export async function getTrustedPathEntries(
env: Readonly<Record<string, string | undefined>>,
root: string,
): Promise<string[]> {
const pathValue = findEnvPathValue(env)
const rawEntries = pathValue ? pathValue.split(path.delimiter) : []
const entries: string[] = []
for (let i = 0, { length } = rawEntries; i < length; i += 1) {
const rawEntry = rawEntries[i]!
if (!rawEntry.length || !path.isAbsolute(rawEntry)) {
continue
}
const canonical = await canonicalizePath(rawEntry)
if (canonical === undefined || isPathWithinRoot(root, canonical)) {
continue
}
if (!entries.includes(canonical)) {
entries.push(canonical)
}
}
return entries
}
export async function inspectExecutableLookups(
lookups: Array<{
entry: string | undefined
runnable: boolean
target: string
}>,
root: string,
) {
const unsafeEntries = new Set<string>()
const hits: Array<{ canonical: string; entry: string | undefined }> = []
for (let i = 0, { length } = lookups; i < length; i += 1) {
const lookup = lookups[i]!
const canonical = await canonicalizePath(lookup.target)
if (canonical === undefined) {
continue
}
if (isPathWithinRoot(root, canonical)) {
// The hit itself is rejected AND its lookup directory is poisoned: a
// directory that can serve a repository-linked binary is not a
// directory the child should be allowed to search.
if (lookup.entry !== undefined) {
unsafeEntries.add(lookup.entry)
}
continue
}
if (lookup.runnable) {
hits.push({ canonical, entry: lookup.entry })
}
}
return { __proto__: null, unsafeEntries, hits }
}
/**
* Whether `target` is `root` itself or lives beneath it. Both arguments are
* expected to be canonical (realpathed) absolute paths.
*/
export function isPathWithinRoot(root: string, target: string): boolean {
const relativePath = path.relative(root, target)
return (
relativePath === '' ||
(relativePath !== '..' &&
!relativePath.startsWith(`..${path.sep}`) &&
!path.isAbsolute(relativePath))
)
}
/**
* Whether a canonical path is a regular file the current user may execute.
*
* POSIX asks for the exec bit (X_OK); Windows has no exec bit, so presence
* (F_OK) is the strongest signal available there.
*/
export async function isRunnableFile(
target: string,
options?: TrustedExecutableOptions | undefined,
): Promise<boolean> {
const opts = { __proto__: null, ...options } as TrustedExecutableOptions
const { windows = isWin32() } = opts
try {
// probes the exec bit (X_OK); existsSync cannot express a permission check.
// oxlint-disable-next-line socket/prefer-exists-sync -- probes X_OK
await fs.access(target, windows ? fsConstants.F_OK : fsConstants.X_OK)
// reads .isFile() metadata to reject directories and devices, not
// existence.
// oxlint-disable-next-line socket/prefer-exists-sync -- reads .size
const stats = await fs.stat(target)
return stats.isFile()
} catch {
return false
}
}
/**
* The suffix table probed for a bare command name.
*
* On Windows the `.bat`, `.cmd`, and extensionless entries are marked
* unrunnable: `execFile` cannot launch a batch file, so they can never be
* selected. They are probed anyway because a hit still proves the PATH entry
* is attacker-reachable, and a poisoned entry must be stripped from the child
* environment even when the eventual winner came from somewhere else.
*/
export function listExecutableProbes(
candidate: string,
options?: TrustedExecutableOptions | undefined,
): ExecutableProbe[] {
const opts = { __proto__: null, ...options } as TrustedExecutableOptions
const { windows = isWin32() } = opts
if (!windows || WINDOWS_EXECUTABLE_SUFFIX_RE.test(candidate)) {
return [{ runnable: true, suffix: '' }]
}
return [
{ runnable: true, suffix: '.exe' },
{ runnable: true, suffix: '.com' },
{ runnable: false, suffix: '.bat' },
{ runnable: false, suffix: '.cmd' },
{ runnable: false, suffix: '' },
]
}
/**
* Resolve `candidate` to a canonical executable that lives outside
* `protectedRoot`, paired with a sanitized copy of `env`.
*
* Returns undefined when nothing runnable resolves outside the protected root.
*
* A PATH entry is dropped up front when it is empty, relative, or does not
* resolve, and when its realpath lands inside the protected root — a hostile
* checkout's `./bin` cannot contribute a lookup directory. A surviving entry
* is dropped from the returned PATH when probing it produced a hit inside the
* protected root, because a directory holding a repository-linked shim is
* unsafe for the child to search on its own.
*/
export async function resolveTrustedExecutable(
candidate: string,
env: Readonly<Record<string, string | undefined>>,
protectedRoot: string,
options?: TrustedExecutableOptions | undefined,
): Promise<TrustedExecutable | undefined> {
const opts = { __proto__: null, ...options } as TrustedExecutableOptions
const { windows = isWin32() } = opts
const root =
(await canonicalizePath(protectedRoot)) ?? path.resolve(protectedRoot)
const entries = await getTrustedPathEntries(env, root)
const lookups = getTrustedExecutableLookups(candidate, entries, { windows })
// First pass decides which PATH entries are poisoned. Selection cannot
// happen in the same pass: a `.cmd` probe LATER in the same directory can
// condemn the entry that an earlier `.exe` probe already matched, and a
// binary served from a condemned directory must not win.
const { unsafeEntries, hits } = await inspectExecutableLookups(lookups, root)
let executable: string | undefined
for (let i = 0, { length } = hits; i < length; i += 1) {
const hit = hits[i]!
if (hit.entry !== undefined && unsafeEntries.has(hit.entry)) {
continue
}
if (await isRunnableFile(hit.canonical, { windows })) {
executable = hit.canonical
break
}
}
if (executable === undefined) {
return undefined
}
const environment: Record<string, string | undefined> = { ...env }
const names = Object.keys(environment)
for (let i = 0, { length } = names; i < length; i += 1) {
const name = names[i]!
if (name.toUpperCase() === 'PATH') {
delete environment[name]
}
}
environment['PATH'] = entries
.filter(entry => !unsafeEntries.has(entry))
.join(path.delimiter)
return { environment, executable }
}