@openai/codex-security 0.1.4 → 0.1.6
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/README.md +127 -13
- package/_bundled_plugin/.codex-plugin/plugin.json +1 -1
- package/_bundled_plugin/.mcp.json +8 -1
- package/_bundled_plugin/examples/completed-scan/findings.json +6 -0
- package/_bundled_plugin/examples/completed-scan/scan-manifest.json +1 -1
- package/_bundled_plugin/mcp/mcp-app.html.br +0 -0
- package/_bundled_plugin/mcp/server.mjs.br.part-000 +0 -0
- package/_bundled_plugin/mcp/server.mjs.br.part-001 +0 -0
- package/_bundled_plugin/preflight/capability-profiles.toml +0 -57
- package/_bundled_plugin/references/config-preflight.md +1 -1
- package/_bundled_plugin/references/final-report.md +15 -7
- package/_bundled_plugin/references/finding-detail-fields.md +10 -2
- package/_bundled_plugin/references/scan-artifacts.md +11 -9
- package/_bundled_plugin/references/scan-contract.md +3 -1
- package/_bundled_plugin/schemas/definitions/artifact-common.schema.json +42 -0
- package/_bundled_plugin/schemas/definitions/discovery-candidate.schema.json +100 -0
- package/_bundled_plugin/schemas/tools/candidate-attack-paths.schema.json +181 -0
- package/_bundled_plugin/schemas/tools/candidate-validations.schema.json +166 -0
- package/_bundled_plugin/schemas/tools/deep-reducer.schema.json +120 -0
- package/_bundled_plugin/schemas/tools/discovery-candidates.schema.json +83 -0
- package/_bundled_plugin/schemas/tools/review-items.schema.json +80 -0
- package/_bundled_plugin/schemas/tools/scan-draft.schema.json +572 -0
- package/_bundled_plugin/schemas/tools/worker-threat-model.schema.json +18 -0
- package/_bundled_plugin/scripts/deep_scan_config.py +11 -3
- package/_bundled_plugin/scripts/deep_scan_workbench.py +153 -133
- package/_bundled_plugin/scripts/finalize_scan_contract.py +39 -0
- package/_bundled_plugin/scripts/generate_in_scope_files.py +134 -0
- package/_bundled_plugin/scripts/workbench_cli.py +33 -1
- package/_bundled_plugin/scripts/workbench_db.py +181 -118
- package/_bundled_plugin/scripts/workbench_feedback.py +2 -0
- package/_bundled_plugin/scripts/workbench_native_indexes.py +5 -49
- package/_bundled_plugin/scripts/workbench_progress.py +86 -3
- package/_bundled_plugin/scripts/workbench_remediation.py +19 -1
- package/_bundled_plugin/scripts/workbench_scan_history.py +7 -1
- package/_bundled_plugin/scripts/workbench_scan_start.py +11 -5
- package/_bundled_plugin/scripts/workbench_scan_usage.py +557 -0
- package/_bundled_plugin/scripts/workbench_schema.py +501 -0
- package/_bundled_plugin/scripts/workbench_target.py +14 -1
- package/_bundled_plugin/scripts/workbench_validation.py +117 -13
- package/_bundled_plugin/skills/attack-path-analysis/SKILL.md +4 -4
- package/_bundled_plugin/skills/deep-security-scan/SKILL.md +34 -28
- package/_bundled_plugin/skills/finding-discovery/SKILL.md +1 -1
- package/_bundled_plugin/skills/security-diff-scan/SKILL.md +11 -8
- package/_bundled_plugin/skills/security-scan/SKILL.md +16 -9
- package/_bundled_plugin/skills/security-scan/references/repository-wide-scan.md +26 -14
- package/_bundled_plugin/skills/security-scan/references/scan-artifacts-and-ledger.md +1 -1
- package/_bundled_plugin/skills/threat-model/SKILL.md +2 -2
- package/_bundled_plugin/skills/validation/SKILL.md +5 -5
- package/_bundled_plugin/skills/vulnerability-writeup/SKILL.md +145 -227
- package/_bundled_plugin/skills/vulnerability-writeup/references/report-format.md +53 -68
- package/dist/api.d.ts +30 -8
- package/dist/api.d.ts.map +1 -1
- package/dist/api.js +438 -66
- package/dist/api.js.map +1 -1
- package/dist/auth.d.ts.map +1 -1
- package/dist/auth.js +262 -44
- package/dist/auth.js.map +1 -1
- package/dist/cli.d.ts +4 -3
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +713 -148
- package/dist/cli.js.map +1 -1
- package/dist/config.d.ts +28 -0
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +39 -2
- package/dist/config.js.map +1 -1
- package/dist/contract.d.ts.map +1 -1
- package/dist/contract.js +14 -0
- package/dist/contract.js.map +1 -1
- package/dist/cost.d.ts +7 -0
- package/dist/cost.d.ts.map +1 -1
- package/dist/cost.js +397 -26
- package/dist/cost.js.map +1 -1
- package/dist/errors.d.ts +2 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +48 -0
- package/dist/errors.js.map +1 -1
- package/dist/index.d.ts +3 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/multiscan.d.ts +1 -0
- package/dist/multiscan.d.ts.map +1 -1
- package/dist/multiscan.js +5 -7
- package/dist/multiscan.js.map +1 -1
- package/dist/runtime.d.ts +40 -1
- package/dist/runtime.d.ts.map +1 -1
- package/dist/runtime.js +742 -46
- package/dist/runtime.js.map +1 -1
- package/dist/scan-activity.d.ts +13 -0
- package/dist/scan-activity.d.ts.map +1 -0
- package/dist/scan-activity.js +319 -0
- package/dist/scan-activity.js.map +1 -0
- package/dist/scan-dashboard.d.ts +47 -0
- package/dist/scan-dashboard.d.ts.map +1 -0
- package/dist/scan-dashboard.js +444 -0
- package/dist/scan-dashboard.js.map +1 -0
- package/dist/scan-history-renderer.d.ts.map +1 -1
- package/dist/scan-history-renderer.js +4 -1
- package/dist/scan-history-renderer.js.map +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/version.js.map +1 -1
- package/dist/worker-progress.d.ts +7 -0
- package/dist/worker-progress.d.ts.map +1 -1
- package/dist/worker-progress.js +68 -0
- package/dist/worker-progress.js.map +1 -1
- package/package.json +3 -3
package/dist/runtime.js
CHANGED
|
@@ -1,17 +1,18 @@
|
|
|
1
|
-
import { execFile as execFileCallback } from "node:child_process";
|
|
1
|
+
import { execFile as execFileCallback, spawn } from "node:child_process";
|
|
2
2
|
import { createHash, randomUUID } from "node:crypto";
|
|
3
3
|
import { constants, existsSync } from "node:fs";
|
|
4
|
-
import { chmod, copyFile, lstat, mkdir, mkdtemp, open, readFile, readdir, realpath, rename, rm, rmdir, stat, writeFile, } from "node:fs/promises";
|
|
4
|
+
import { chmod, copyFile, link, lstat, mkdir, mkdtemp, open, opendir, readFile, readdir, realpath, rename, rm, rmdir, stat, writeFile, } from "node:fs/promises";
|
|
5
5
|
import { homedir, tmpdir } from "node:os";
|
|
6
6
|
import { createRequire } from "node:module";
|
|
7
7
|
import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep, } from "node:path";
|
|
8
|
+
import { createInterface } from "node:readline";
|
|
8
9
|
import { fileURLToPath } from "node:url";
|
|
9
10
|
import { promisify } from "node:util";
|
|
10
11
|
import { crc32 } from "node:zlib";
|
|
11
12
|
import { setTimeout as delay } from "node:timers/promises";
|
|
12
13
|
import extractZip from "extract-zip";
|
|
13
14
|
import { parse } from "smol-toml";
|
|
14
|
-
import { CodexSecurityError, OutputDirectoryError, PluginBootstrapError, PluginPythonUnavailableError, } from "./errors.js";
|
|
15
|
+
import { CodexSecurityError, OutputDirectoryError, PluginBootstrapError, PluginPythonUnavailableError, redactedErrorMessage, } from "./errors.js";
|
|
15
16
|
import { resolveTrustedExecutable } from "./trusted-executable.js";
|
|
16
17
|
const execFile = promisify(execFileCallback);
|
|
17
18
|
export const MARKETPLACE_NAME = "codex-security-sdk";
|
|
@@ -29,6 +30,7 @@ const CREDENTIAL_LOCK_NAME = ".codex-security-scan.lock";
|
|
|
29
30
|
const CREDENTIAL_LOGOUT_MARKER = ".codex-security-logged-out";
|
|
30
31
|
const CREDENTIAL_LOCK_POLL_MILLISECONDS = 25;
|
|
31
32
|
const INCOMPLETE_CREDENTIAL_LOCK_MILLISECONDS = 30_000;
|
|
33
|
+
const MAX_WINDOWS_CREDENTIAL_ACL_STDERR = 64 * 1024;
|
|
32
34
|
export function codexSecurityStateDirectory(environment = process.env) {
|
|
33
35
|
const environmentValue = (requested) => {
|
|
34
36
|
const exact = environment[requested]?.trim();
|
|
@@ -72,7 +74,9 @@ export async function prepareCodexSecurityCredentialHome(environment = process.e
|
|
|
72
74
|
const canonical = await realpath(path);
|
|
73
75
|
requireModelSafeOutputDir(canonical);
|
|
74
76
|
validateLocation?.(canonical);
|
|
75
|
-
await
|
|
77
|
+
await requireSecureCredentialHome(canonical, {
|
|
78
|
+
metadata,
|
|
79
|
+
});
|
|
76
80
|
return canonical;
|
|
77
81
|
}
|
|
78
82
|
catch (error) {
|
|
@@ -81,6 +85,58 @@ export async function prepareCodexSecurityCredentialHome(environment = process.e
|
|
|
81
85
|
throw new OutputDirectoryError(`Unable to prepare the Codex Security credential home: ${path}`, { cause: error });
|
|
82
86
|
}
|
|
83
87
|
}
|
|
88
|
+
/**
|
|
89
|
+
* Re-verify the credential home before every use.
|
|
90
|
+
*
|
|
91
|
+
* Durable cross-process `(st_dev, st_ino)` pins are deferred: there is no
|
|
92
|
+
* workbench row for credential homes, and path+mode+trusted-ancestry checks on
|
|
93
|
+
* each use already close the cross-user rename/replace class. Lock acquisition
|
|
94
|
+
* still pins identity for the duration of a single lock session.
|
|
95
|
+
*/
|
|
96
|
+
export async function requireSecureCredentialHome(path, options = {}) {
|
|
97
|
+
const platform = options.platform ?? process.platform;
|
|
98
|
+
let metadata = options.metadata;
|
|
99
|
+
if (metadata === undefined) {
|
|
100
|
+
try {
|
|
101
|
+
metadata = await lstat(path);
|
|
102
|
+
}
|
|
103
|
+
catch (error) {
|
|
104
|
+
throw new OutputDirectoryError(`Unable to inspect the Codex Security credential home: ${path}`, { cause: error });
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
if (!metadata.isDirectory() || metadata.isSymbolicLink()) {
|
|
108
|
+
throw new OutputDirectoryError(`Codex Security credential home is not a directory: ${path}`);
|
|
109
|
+
}
|
|
110
|
+
const canonical = await realpath(path);
|
|
111
|
+
requireModelSafeOutputDir(canonical);
|
|
112
|
+
const canonicalMetadata = await lstat(canonical);
|
|
113
|
+
if (canonicalMetadata.dev !== metadata.dev ||
|
|
114
|
+
canonicalMetadata.ino !== metadata.ino) {
|
|
115
|
+
throw new OutputDirectoryError(`Codex Security credential home was replaced: ${canonical}`);
|
|
116
|
+
}
|
|
117
|
+
metadata = canonicalMetadata;
|
|
118
|
+
if (!metadata.isDirectory() || metadata.isSymbolicLink()) {
|
|
119
|
+
throw new OutputDirectoryError(`Codex Security credential home is not a directory: ${path}`);
|
|
120
|
+
}
|
|
121
|
+
if (options.expectedDevice !== undefined &&
|
|
122
|
+
options.expectedInode !== undefined &&
|
|
123
|
+
(metadata.dev !== options.expectedDevice ||
|
|
124
|
+
metadata.ino !== options.expectedInode)) {
|
|
125
|
+
throw new OutputDirectoryError(`Codex Security credential home was replaced: ${canonical}`);
|
|
126
|
+
}
|
|
127
|
+
if (platform === "win32") {
|
|
128
|
+
if (options.validateWindowsAcl !== false) {
|
|
129
|
+
await requirePrivateCredentialHome(metadata, canonical, {
|
|
130
|
+
platform,
|
|
131
|
+
secureWindowsHome: options.secureWindowsHome,
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
return metadata;
|
|
135
|
+
}
|
|
136
|
+
await requirePrivateCredentialHome(metadata, canonical, { platform });
|
|
137
|
+
await requireSecureOutputAncestry(canonical);
|
|
138
|
+
return metadata;
|
|
139
|
+
}
|
|
84
140
|
export async function requirePrivateCredentialHome(metadata, path, options = {}) {
|
|
85
141
|
if ((options.platform ?? process.platform) !== "win32") {
|
|
86
142
|
requirePrivateOutputDirectory(metadata, path);
|
|
@@ -90,45 +146,581 @@ export async function requirePrivateCredentialHome(metadata, path, options = {})
|
|
|
90
146
|
await (options.secureWindowsHome ?? secureWindowsCredentialHome)(path);
|
|
91
147
|
}
|
|
92
148
|
catch (error) {
|
|
93
|
-
|
|
149
|
+
const detail = windowsCredentialAclFailure(error);
|
|
150
|
+
throw new OutputDirectoryError(`Unable to create a private Windows credential home: ${path}${detail}`, { cause: error });
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
function windowsCredentialAclFailure(error) {
|
|
154
|
+
const stderr = typeof error === "object" && error !== null && "stderr" in error
|
|
155
|
+
? error.stderr
|
|
156
|
+
: undefined;
|
|
157
|
+
const detail = typeof stderr === "string" && stderr.trim() !== ""
|
|
158
|
+
? stderr
|
|
159
|
+
: error instanceof Error
|
|
160
|
+
? error.message
|
|
161
|
+
: String(error);
|
|
162
|
+
const sanitized = redactedErrorMessage(detail)
|
|
163
|
+
.replace(/\s+/gu, " ")
|
|
164
|
+
.trim()
|
|
165
|
+
.slice(0, 512);
|
|
166
|
+
return sanitized === "" ? "" : `. ${sanitized}`;
|
|
167
|
+
}
|
|
168
|
+
const WINDOWS_SYSTEM_SID = "S-1-5-18";
|
|
169
|
+
const WINDOWS_ADMINISTRATORS_SID = "S-1-5-32-544";
|
|
170
|
+
const WINDOWS_TRUSTED_INSTALLER_SID = "S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464";
|
|
171
|
+
const WINDOWS_LOCAL_SERVICE_SID = "S-1-5-19";
|
|
172
|
+
const WINDOWS_NETWORK_SERVICE_SID = "S-1-5-20";
|
|
173
|
+
const WINDOWS_EVERYONE_SID = "S-1-1-0";
|
|
174
|
+
const WINDOWS_AUTHENTICATED_USERS_SID = "S-1-5-11";
|
|
175
|
+
const WINDOWS_USERS_SID = "S-1-5-32-545";
|
|
176
|
+
const WINDOWS_CREATOR_OWNER_SID = "S-1-3-0";
|
|
177
|
+
const WINDOWS_CREATOR_GROUP_SID = "S-1-3-1";
|
|
178
|
+
const WINDOWS_OWNER_RIGHTS_SID = "S-1-3-4";
|
|
179
|
+
const WINDOWS_ALL_APPLICATION_PACKAGES_SID = "S-1-15-2-1";
|
|
180
|
+
const WINDOWS_PRINCIPAL_ALIASES = {
|
|
181
|
+
SY: WINDOWS_SYSTEM_SID,
|
|
182
|
+
BA: WINDOWS_ADMINISTRATORS_SID,
|
|
183
|
+
LS: WINDOWS_LOCAL_SERVICE_SID,
|
|
184
|
+
NS: WINDOWS_NETWORK_SERVICE_SID,
|
|
185
|
+
WD: WINDOWS_EVERYONE_SID,
|
|
186
|
+
AU: WINDOWS_AUTHENTICATED_USERS_SID,
|
|
187
|
+
BU: WINDOWS_USERS_SID,
|
|
188
|
+
CO: WINDOWS_CREATOR_OWNER_SID,
|
|
189
|
+
CG: WINDOWS_CREATOR_GROUP_SID,
|
|
190
|
+
OW: WINDOWS_OWNER_RIGHTS_SID,
|
|
191
|
+
AC: WINDOWS_ALL_APPLICATION_PACKAGES_SID,
|
|
192
|
+
AN: "S-1-5-7",
|
|
193
|
+
IU: "S-1-5-4",
|
|
194
|
+
NU: "S-1-5-2",
|
|
195
|
+
SU: "S-1-5-6",
|
|
196
|
+
RC: "S-1-5-12",
|
|
197
|
+
ED: "S-1-5-9",
|
|
198
|
+
BG: "S-1-5-32-546",
|
|
199
|
+
PU: "S-1-5-32-547",
|
|
200
|
+
AO: "S-1-5-32-548",
|
|
201
|
+
SO: "S-1-5-32-549",
|
|
202
|
+
PO: "S-1-5-32-550",
|
|
203
|
+
BO: "S-1-5-32-551",
|
|
204
|
+
RE: "S-1-5-32-552",
|
|
205
|
+
RU: "S-1-5-32-554",
|
|
206
|
+
RD: "S-1-5-32-555",
|
|
207
|
+
NO: "S-1-5-32-556",
|
|
208
|
+
MU: "S-1-5-32-558",
|
|
209
|
+
LU: "S-1-5-32-559",
|
|
210
|
+
IS: "S-1-5-32-568",
|
|
211
|
+
CY: "S-1-5-32-569",
|
|
212
|
+
ER: "S-1-5-32-573",
|
|
213
|
+
CD: "S-1-5-32-574",
|
|
214
|
+
RA: "S-1-5-32-575",
|
|
215
|
+
ES: "S-1-5-32-576",
|
|
216
|
+
HA: "S-1-5-32-578",
|
|
217
|
+
AA: "S-1-5-32-579",
|
|
218
|
+
};
|
|
219
|
+
const WINDOWS_SID = /^S-1-(?:\d+-)*\d+$/u;
|
|
220
|
+
const WINDOWS_GUID = /^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu;
|
|
221
|
+
const WINDOWS_SDDL_SID = "(?:S-1-(?:\\d+-)*\\d+|[A-Z]{2})";
|
|
222
|
+
const WINDOWS_SECURITY_DESCRIPTOR = new RegExp(`^O:(${WINDOWS_SDDL_SID})(?:G:${WINDOWS_SDDL_SID})?D:([A-Z_]*)(.*)$`, "u");
|
|
223
|
+
class UntrustedWindowsCredentialOwnerError extends Error {
|
|
224
|
+
constructor(owner) {
|
|
225
|
+
super(`Windows credential ACL owner is not a trusted principal: ${owner}`);
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
class RepairableWindowsCredentialAclError extends Error {
|
|
229
|
+
constructor(cause) {
|
|
230
|
+
super("Windows credential ACL requires repair", { cause });
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
/** Inspect a Windows DACL without translating locale-specific account names. */
|
|
234
|
+
export function inspectWindowsCredentialAcl(descriptor, currentUserSid, options = {}) {
|
|
235
|
+
if (!WINDOWS_SID.test(currentUserSid)) {
|
|
236
|
+
throw new Error("Unable to identify the current Windows user SID");
|
|
237
|
+
}
|
|
238
|
+
const match = WINDOWS_SECURITY_DESCRIPTOR.exec(descriptor.trim());
|
|
239
|
+
if (match === null) {
|
|
240
|
+
throw new Error("Windows credential ACL has no owner or DACL");
|
|
241
|
+
}
|
|
242
|
+
const principalAliases = {
|
|
243
|
+
...WINDOWS_PRINCIPAL_ALIASES,
|
|
244
|
+
...options.resolvedAliases,
|
|
245
|
+
};
|
|
246
|
+
const trustedPrincipals = new Set([
|
|
247
|
+
currentUserSid,
|
|
248
|
+
WINDOWS_SYSTEM_SID,
|
|
249
|
+
WINDOWS_ADMINISTRATORS_SID,
|
|
250
|
+
principalAliases["LA"] ?? "LA",
|
|
251
|
+
]);
|
|
252
|
+
if (options.scope === "ancestor") {
|
|
253
|
+
trustedPrincipals.add(WINDOWS_TRUSTED_INSTALLER_SID);
|
|
254
|
+
}
|
|
255
|
+
const normalizePrincipal = (principal) => principalAliases[principal] ?? principal;
|
|
256
|
+
const trustedPrincipal = (principal) => trustedPrincipals.has(principal);
|
|
257
|
+
const owner = normalizePrincipal(match[1]);
|
|
258
|
+
if (!trustedPrincipal(owner)) {
|
|
259
|
+
throw new UntrustedWindowsCredentialOwnerError(owner);
|
|
260
|
+
}
|
|
261
|
+
const flags = match[2];
|
|
262
|
+
if (flags.includes("NO_ACCESS_CONTROL")) {
|
|
263
|
+
throw new Error("Windows credential ACL grants unrestricted access");
|
|
264
|
+
}
|
|
265
|
+
let remaining = match[3];
|
|
266
|
+
let grantsCurrentDirectoryAccess = false;
|
|
267
|
+
let grantsCurrentFileAccess = false;
|
|
268
|
+
let grantsCurrentContainerAccess = false;
|
|
269
|
+
let hasAccessRules = false;
|
|
270
|
+
const untrustedPrincipals = new Set();
|
|
271
|
+
const deniedPrincipals = new Set();
|
|
272
|
+
while (remaining.startsWith("(")) {
|
|
273
|
+
const { rule, rest } = windowsSecurityDescriptorRule(remaining);
|
|
274
|
+
const fields = rule.split(";");
|
|
275
|
+
const callback = ["XA", "XD", "ZA"].includes(fields[0]);
|
|
276
|
+
if ((callback && fields.length < 7) || (!callback && fields.length !== 6)) {
|
|
277
|
+
throw new Error("Windows credential ACL has a malformed access rule");
|
|
278
|
+
}
|
|
279
|
+
const [type, inheritance, rights, objectGuid, inheritObjectGuid, rawPrincipal,] = fields;
|
|
280
|
+
if (!["A", "OA", "D", "OD", "XA", "XD", "ZA"].includes(type)) {
|
|
281
|
+
throw new Error("Windows credential ACL has an unsupported access rule");
|
|
282
|
+
}
|
|
283
|
+
if (rawPrincipal === "" || rights === "") {
|
|
284
|
+
throw new Error("Windows credential ACL has an incomplete access rule");
|
|
285
|
+
}
|
|
286
|
+
const objectRule = type === "OA" || type === "OD" || type === "ZA";
|
|
287
|
+
for (const guid of [objectGuid, inheritObjectGuid]) {
|
|
288
|
+
if (guid !== "" && (!objectRule || !WINDOWS_GUID.test(guid))) {
|
|
289
|
+
throw new Error("Windows credential ACL has a malformed object rule");
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
const inheritanceFlags = windowsAceFlags(inheritance);
|
|
293
|
+
hasAccessRules = true;
|
|
294
|
+
const principal = normalizePrincipal(rawPrincipal);
|
|
295
|
+
if (type === "A" || type === "OA" || type === "XA" || type === "ZA") {
|
|
296
|
+
if (!trustedPrincipal(principal)) {
|
|
297
|
+
if (options.scope !== "ancestor" ||
|
|
298
|
+
windowsAceAllowsAncestorReplacement(rights, inheritanceFlags)) {
|
|
299
|
+
untrustedPrincipals.add(principal);
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
else if (!callback &&
|
|
303
|
+
objectGuid === "" &&
|
|
304
|
+
inheritObjectGuid === "" &&
|
|
305
|
+
principal === currentUserSid &&
|
|
306
|
+
windowsAceGrantsFullControl(rights)) {
|
|
307
|
+
if (!inheritanceFlags.has("IO")) {
|
|
308
|
+
grantsCurrentDirectoryAccess = true;
|
|
309
|
+
}
|
|
310
|
+
if (inheritanceFlags.has("OI") && !inheritanceFlags.has("NP")) {
|
|
311
|
+
grantsCurrentFileAccess = true;
|
|
312
|
+
}
|
|
313
|
+
if (inheritanceFlags.has("CI") && !inheritanceFlags.has("NP")) {
|
|
314
|
+
grantsCurrentContainerAccess = true;
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
else {
|
|
319
|
+
deniedPrincipals.add(principal);
|
|
320
|
+
}
|
|
321
|
+
remaining = rest;
|
|
322
|
+
}
|
|
323
|
+
if (!hasAccessRules || (remaining !== "" && !remaining.startsWith("S:"))) {
|
|
324
|
+
throw new Error("Windows credential ACL has an invalid access-rule list");
|
|
325
|
+
}
|
|
326
|
+
return {
|
|
327
|
+
owner,
|
|
328
|
+
protected: flags.includes("P"),
|
|
329
|
+
grantsCurrentUserAccess: grantsCurrentDirectoryAccess &&
|
|
330
|
+
(options.scope === "file" ||
|
|
331
|
+
(grantsCurrentFileAccess && grantsCurrentContainerAccess)) &&
|
|
332
|
+
deniedPrincipals.size === 0,
|
|
333
|
+
untrustedPrincipals: [...untrustedPrincipals],
|
|
334
|
+
deniedPrincipals: [...deniedPrincipals],
|
|
335
|
+
};
|
|
336
|
+
}
|
|
337
|
+
function windowsSecurityDescriptorRule(value) {
|
|
338
|
+
let depth = 0;
|
|
339
|
+
let quoted = false;
|
|
340
|
+
let escaped = false;
|
|
341
|
+
for (let index = 0; index < value.length; index += 1) {
|
|
342
|
+
const character = value[index];
|
|
343
|
+
if (quoted) {
|
|
344
|
+
if (!escaped && character === '"')
|
|
345
|
+
quoted = false;
|
|
346
|
+
escaped = character === "\\" && !escaped;
|
|
347
|
+
continue;
|
|
348
|
+
}
|
|
349
|
+
if (character === '"') {
|
|
350
|
+
quoted = true;
|
|
351
|
+
}
|
|
352
|
+
else if (character === "(") {
|
|
353
|
+
depth += 1;
|
|
354
|
+
}
|
|
355
|
+
else if (character === ")") {
|
|
356
|
+
depth -= 1;
|
|
357
|
+
if (depth === 0) {
|
|
358
|
+
return { rule: value.slice(1, index), rest: value.slice(index + 1) };
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
throw new Error("Windows credential ACL has a malformed rule");
|
|
363
|
+
}
|
|
364
|
+
function windowsAceFlags(value) {
|
|
365
|
+
if (value.length % 2 !== 0) {
|
|
366
|
+
throw new Error("Windows credential ACL has malformed inheritance flags");
|
|
367
|
+
}
|
|
368
|
+
const flags = new Set();
|
|
369
|
+
for (let offset = 0; offset < value.length; offset += 2) {
|
|
370
|
+
const flag = value.slice(offset, offset + 2);
|
|
371
|
+
if (!["OI", "CI", "NP", "IO", "ID"].includes(flag)) {
|
|
372
|
+
throw new Error("Windows credential ACL has unsupported inheritance flags");
|
|
373
|
+
}
|
|
374
|
+
flags.add(flag);
|
|
375
|
+
}
|
|
376
|
+
return flags;
|
|
377
|
+
}
|
|
378
|
+
function windowsAceGrantsFullControl(rights) {
|
|
379
|
+
if (rights === "FA" || rights === "GA")
|
|
380
|
+
return true;
|
|
381
|
+
if (!/^0x[\da-f]+$/iu.test(rights))
|
|
382
|
+
return false;
|
|
383
|
+
const mask = BigInt(rights);
|
|
384
|
+
return (mask & 0x1f01ffn) === 0x1f01ffn || (mask & 0x10000000n) !== 0n;
|
|
385
|
+
}
|
|
386
|
+
function windowsAceAllowsAncestorReplacement(rights, inheritanceFlags) {
|
|
387
|
+
if (inheritanceFlags.has("IO"))
|
|
388
|
+
return false;
|
|
389
|
+
if (/^0x[\da-f]+$/iu.test(rights)) {
|
|
390
|
+
return (BigInt(rights) & 0x100d0040n) !== 0n;
|
|
391
|
+
}
|
|
392
|
+
for (let index = 0; index < rights.length; index += 2) {
|
|
393
|
+
if (["FA", "GA", "FW", "GW", "SD", "WD", "WO", "DC", "DT"].includes(rights.slice(index, index + 2))) {
|
|
394
|
+
return true;
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
return false;
|
|
398
|
+
}
|
|
399
|
+
export async function verifyStableWindowsCredentialDescendants(path, inspectDescriptors) {
|
|
400
|
+
for (let attempt = 0; attempt < 3; attempt += 1) {
|
|
401
|
+
let descendants = 0;
|
|
402
|
+
const pending = [path];
|
|
403
|
+
while (pending.length !== 0) {
|
|
404
|
+
const current = pending.pop();
|
|
405
|
+
const directory = await opendir(current);
|
|
406
|
+
for await (const entry of directory) {
|
|
407
|
+
const child = join(current, entry.name);
|
|
408
|
+
const metadata = await lstat(child);
|
|
409
|
+
if (metadata.isSymbolicLink()) {
|
|
410
|
+
throw new Error("Windows credential home contains a symbolic link or junction");
|
|
411
|
+
}
|
|
412
|
+
if (!metadata.isDirectory() && !metadata.isFile()) {
|
|
413
|
+
throw new Error("Windows credential home contains an unsafe entry");
|
|
414
|
+
}
|
|
415
|
+
descendants += 1;
|
|
416
|
+
if (metadata.isDirectory())
|
|
417
|
+
pending.push(child);
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
if (descendants === 0)
|
|
421
|
+
return;
|
|
422
|
+
if ((await inspectDescriptors()) === descendants)
|
|
423
|
+
return;
|
|
424
|
+
}
|
|
425
|
+
throw new Error("Windows credential descendants could not be verified");
|
|
426
|
+
}
|
|
427
|
+
export async function streamWindowsCredentialAclDescriptors(command, args, inspectDescriptor, options = {}) {
|
|
428
|
+
const child = spawn(command, [...args], {
|
|
429
|
+
env: options.environment,
|
|
430
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
431
|
+
windowsHide: true,
|
|
432
|
+
});
|
|
433
|
+
let stderr = "";
|
|
434
|
+
child.stderr.setEncoding("utf8");
|
|
435
|
+
child.stderr.on("data", (chunk) => {
|
|
436
|
+
const remaining = MAX_WINDOWS_CREDENTIAL_ACL_STDERR - stderr.length;
|
|
437
|
+
if (remaining > 0)
|
|
438
|
+
stderr += chunk.slice(0, remaining);
|
|
439
|
+
});
|
|
440
|
+
const completion = new Promise((resolve, reject) => {
|
|
441
|
+
child.once("error", reject);
|
|
442
|
+
child.once("close", (code, signal) => {
|
|
443
|
+
if (code === 0) {
|
|
444
|
+
resolve();
|
|
445
|
+
return;
|
|
446
|
+
}
|
|
447
|
+
const reason = signal === null ? `exit code ${code}` : `signal ${signal}`;
|
|
448
|
+
reject(Object.assign(new Error(`Windows credential ACL inspection failed with ${reason}`), { code, signal, stderr }));
|
|
449
|
+
});
|
|
450
|
+
});
|
|
451
|
+
let descriptors = 0;
|
|
452
|
+
try {
|
|
453
|
+
await Promise.all([
|
|
454
|
+
completion,
|
|
455
|
+
(async () => {
|
|
456
|
+
const lines = createInterface({
|
|
457
|
+
input: child.stdout,
|
|
458
|
+
crlfDelay: Infinity,
|
|
459
|
+
});
|
|
460
|
+
for await (const descriptor of lines) {
|
|
461
|
+
if (descriptor === "")
|
|
462
|
+
continue;
|
|
463
|
+
await inspectDescriptor(descriptor);
|
|
464
|
+
descriptors += 1;
|
|
465
|
+
}
|
|
466
|
+
})(),
|
|
467
|
+
]);
|
|
468
|
+
}
|
|
469
|
+
catch (error) {
|
|
470
|
+
if (child.exitCode === null && child.signalCode === null)
|
|
471
|
+
child.kill();
|
|
472
|
+
throw error;
|
|
94
473
|
}
|
|
474
|
+
return descriptors;
|
|
95
475
|
}
|
|
96
476
|
async function secureWindowsCredentialHome(path) {
|
|
97
477
|
const systemRoot = process.env["SystemRoot"] ?? "C:\\Windows";
|
|
98
|
-
const
|
|
99
|
-
const
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
"$identity = [System.Security.Principal.WindowsIdentity]::GetCurrent()",
|
|
103
|
-
"if ($null -eq $identity.User) { throw 'Unable to identify the current Windows user' }",
|
|
104
|
-
"$acl = New-Object System.Security.AccessControl.DirectorySecurity",
|
|
105
|
-
"$acl.SetAccessRuleProtection($true, $false)",
|
|
106
|
-
"$inheritance = [System.Security.AccessControl.InheritanceFlags]::ContainerInherit -bor [System.Security.AccessControl.InheritanceFlags]::ObjectInherit",
|
|
107
|
-
"$rule = New-Object System.Security.AccessControl.FileSystemAccessRule($identity.User, [System.Security.AccessControl.FileSystemRights]::FullControl, $inheritance, [System.Security.AccessControl.PropagationFlags]::None, [System.Security.AccessControl.AccessControlType]::Allow)",
|
|
108
|
-
"$acl.SetOwner($identity.User)",
|
|
109
|
-
"$acl.SetAccessRule($rule)",
|
|
110
|
-
"[System.IO.Directory]::SetAccessControl($path, $acl)",
|
|
111
|
-
"$verified = [System.IO.Directory]::GetAccessControl($path)",
|
|
112
|
-
"if (-not $verified.AreAccessRulesProtected) { throw 'Credential ACL still inherits access rules' }",
|
|
113
|
-
"$unexpected = @($verified.Access | Where-Object { $_.AccessControlType -eq [System.Security.AccessControl.AccessControlType]::Allow -and $_.IdentityReference.Translate([System.Security.Principal.SecurityIdentifier]).Value -ne $identity.User.Value })",
|
|
114
|
-
"if ($unexpected.Count -ne 0) { throw 'Credential ACL grants access to another identity' }",
|
|
115
|
-
].join("; ");
|
|
116
|
-
await execFile(powershell, ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", script], {
|
|
478
|
+
const systemDirectory = join(systemRoot, "System32");
|
|
479
|
+
const powershell = join(systemDirectory, "WindowsPowerShell", "v1.0", "powershell.exe");
|
|
480
|
+
const inheritedEnvironment = Object.fromEntries(Object.entries(process.env).filter(([name]) => name.toUpperCase() !== "PSMODULEPATH"));
|
|
481
|
+
const processOptions = {
|
|
117
482
|
env: {
|
|
118
|
-
...
|
|
483
|
+
...inheritedEnvironment,
|
|
119
484
|
CODEX_SECURITY_CREDENTIAL_ACL_PATH: path,
|
|
485
|
+
PSModulePath: join(systemDirectory, "WindowsPowerShell", "v1.0", "Modules"),
|
|
120
486
|
},
|
|
121
487
|
encoding: "utf8",
|
|
122
488
|
windowsHide: true,
|
|
123
489
|
maxBuffer: 1024 * 1024,
|
|
124
|
-
}
|
|
490
|
+
};
|
|
491
|
+
const identity = await execFile(join(systemDirectory, "whoami.exe"), ["/user", "/fo", "csv", "/nh"], processOptions);
|
|
492
|
+
const sid = /^"(?:[^"]|"")*","(S-1-(?:\d+-)*\d+)"$/u.exec(identity.stdout.trim())?.[1];
|
|
493
|
+
if (sid === undefined) {
|
|
494
|
+
throw new Error("Unable to identify the current Windows user SID");
|
|
495
|
+
}
|
|
496
|
+
// Signed built-in cmdlets remain available under ConstrainedLanguage;
|
|
497
|
+
// arbitrary .NET constructors, static methods, and SID translation do not.
|
|
498
|
+
const script = [
|
|
499
|
+
"$ErrorActionPreference = 'Stop'",
|
|
500
|
+
"Microsoft.PowerShell.Security\\Get-Acl -LiteralPath $env:CODEX_SECURITY_CREDENTIAL_ACL_PATH | Microsoft.PowerShell.Utility\\Select-Object -ExpandProperty Sddl",
|
|
501
|
+
].join("; ");
|
|
502
|
+
const resolvePrincipalScript = [
|
|
503
|
+
"$ErrorActionPreference = 'Stop'",
|
|
504
|
+
"$descriptor = 'O:' + $env:CODEX_SECURITY_CREDENTIAL_PRINCIPAL + 'G:SYD:(A;;GA;;;SY)'",
|
|
505
|
+
"Microsoft.PowerShell.Utility\\ConvertFrom-SddlString -Sddl $descriptor | Microsoft.PowerShell.Utility\\Select-Object -ExpandProperty RawDescriptor | Microsoft.PowerShell.Utility\\Select-Object -ExpandProperty Owner | Microsoft.PowerShell.Utility\\Select-Object -ExpandProperty Value",
|
|
506
|
+
].join("; ");
|
|
507
|
+
const resolvedAliases = {};
|
|
508
|
+
const resolvePrincipal = async (principal) => {
|
|
509
|
+
if (!/^[A-Z]{2}$/u.test(principal) ||
|
|
510
|
+
WINDOWS_PRINCIPAL_ALIASES[principal] !== undefined ||
|
|
511
|
+
resolvedAliases[principal] !== undefined) {
|
|
512
|
+
return;
|
|
513
|
+
}
|
|
514
|
+
const resolved = await execFile(powershell, [
|
|
515
|
+
"-NoLogo",
|
|
516
|
+
"-NoProfile",
|
|
517
|
+
"-NonInteractive",
|
|
518
|
+
"-Command",
|
|
519
|
+
resolvePrincipalScript,
|
|
520
|
+
], {
|
|
521
|
+
...processOptions,
|
|
522
|
+
env: {
|
|
523
|
+
...processOptions.env,
|
|
524
|
+
CODEX_SECURITY_CREDENTIAL_PRINCIPAL: principal,
|
|
525
|
+
},
|
|
526
|
+
});
|
|
527
|
+
const numeric = resolved.stdout.trim();
|
|
528
|
+
if (!WINDOWS_SID.test(numeric)) {
|
|
529
|
+
throw new Error("Windows credential ACL contains an unresolvable identity");
|
|
530
|
+
}
|
|
531
|
+
resolvedAliases[principal] = numeric;
|
|
532
|
+
};
|
|
533
|
+
const resolveDescriptorAliases = async (descriptor) => {
|
|
534
|
+
const header = WINDOWS_SECURITY_DESCRIPTOR.exec(descriptor.trim());
|
|
535
|
+
if (header === null)
|
|
536
|
+
return;
|
|
537
|
+
await resolvePrincipal(header[1]);
|
|
538
|
+
let remaining = header[3];
|
|
539
|
+
while (remaining.startsWith("(")) {
|
|
540
|
+
const { rule, rest } = windowsSecurityDescriptorRule(remaining);
|
|
541
|
+
const principal = rule.split(";")[5];
|
|
542
|
+
if (principal !== undefined)
|
|
543
|
+
await resolvePrincipal(principal);
|
|
544
|
+
remaining = rest;
|
|
545
|
+
}
|
|
546
|
+
};
|
|
547
|
+
const readAcl = async () => {
|
|
548
|
+
const descriptor = await execFile(powershell, ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", script], processOptions);
|
|
549
|
+
try {
|
|
550
|
+
await resolveDescriptorAliases(descriptor.stdout);
|
|
551
|
+
return inspectWindowsCredentialAcl(descriptor.stdout, sid, {
|
|
552
|
+
resolvedAliases,
|
|
553
|
+
});
|
|
554
|
+
}
|
|
555
|
+
catch (error) {
|
|
556
|
+
if (error instanceof UntrustedWindowsCredentialOwnerError)
|
|
557
|
+
throw error;
|
|
558
|
+
throw new RepairableWindowsCredentialAclError(error);
|
|
559
|
+
}
|
|
560
|
+
};
|
|
561
|
+
const icacls = join(systemDirectory, "icacls.exe");
|
|
562
|
+
const installTrustedAcl = async (target = path) => {
|
|
563
|
+
await execFile(icacls, [
|
|
564
|
+
target,
|
|
565
|
+
"/inheritance:r",
|
|
566
|
+
"/grant:r",
|
|
567
|
+
`*${sid}:(OI)(CI)F`,
|
|
568
|
+
`*${WINDOWS_SYSTEM_SID}:(OI)(CI)F`,
|
|
569
|
+
`*${WINDOWS_ADMINISTRATORS_SID}:(OI)(CI)F`,
|
|
570
|
+
], processOptions);
|
|
571
|
+
};
|
|
572
|
+
const ancestorScript = [
|
|
573
|
+
"$ErrorActionPreference = 'Stop'",
|
|
574
|
+
"$path = $env:CODEX_SECURITY_CREDENTIAL_ACL_PATH",
|
|
575
|
+
"while ($true) { $parent = Microsoft.PowerShell.Management\\Split-Path -Path $path -Parent; if (-not $parent -or $parent -eq $path) { break }; Microsoft.PowerShell.Security\\Get-Acl -LiteralPath $parent | Microsoft.PowerShell.Utility\\Select-Object -ExpandProperty Sddl; $path = $parent }",
|
|
576
|
+
].join("; ");
|
|
577
|
+
const ancestorPaths = [];
|
|
578
|
+
for (let ancestor = dirname(path);; ancestor = dirname(ancestor)) {
|
|
579
|
+
ancestorPaths.push(ancestor);
|
|
580
|
+
if (ancestor === dirname(ancestor))
|
|
581
|
+
break;
|
|
582
|
+
}
|
|
583
|
+
const ancestry = await execFile(powershell, ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", ancestorScript], processOptions);
|
|
584
|
+
const ancestorDescriptors = ancestry.stdout
|
|
585
|
+
.split(/\r?\n/u)
|
|
586
|
+
.filter((descriptor) => descriptor !== "");
|
|
587
|
+
if (ancestorDescriptors.length !== ancestorPaths.length) {
|
|
588
|
+
throw new Error("Windows credential-home ancestry could not be verified");
|
|
589
|
+
}
|
|
590
|
+
for (const descriptor of ancestorDescriptors) {
|
|
591
|
+
await resolveDescriptorAliases(descriptor);
|
|
592
|
+
const ancestor = inspectWindowsCredentialAcl(descriptor, sid, {
|
|
593
|
+
resolvedAliases,
|
|
594
|
+
scope: "ancestor",
|
|
595
|
+
});
|
|
596
|
+
if (ancestor.untrustedPrincipals.length === 0)
|
|
597
|
+
continue;
|
|
598
|
+
throw new Error("Windows credential-home ancestor allows another identity to replace the directory");
|
|
599
|
+
}
|
|
600
|
+
const descendantsArePrivate = async () => {
|
|
601
|
+
const descendantScript = [
|
|
602
|
+
"$ErrorActionPreference = 'Stop'",
|
|
603
|
+
"Microsoft.PowerShell.Management\\Get-ChildItem -LiteralPath $env:CODEX_SECURITY_CREDENTIAL_ACL_PATH -Recurse -Force | Microsoft.PowerShell.Security\\Get-Acl | Microsoft.PowerShell.Utility\\Select-Object -ExpandProperty Sddl",
|
|
604
|
+
].join("; ");
|
|
605
|
+
let privateDescendants = true;
|
|
606
|
+
await verifyStableWindowsCredentialDescendants(path, async () => {
|
|
607
|
+
privateDescendants = true;
|
|
608
|
+
return streamWindowsCredentialAclDescriptors(powershell, [
|
|
609
|
+
"-NoLogo",
|
|
610
|
+
"-NoProfile",
|
|
611
|
+
"-NonInteractive",
|
|
612
|
+
"-Command",
|
|
613
|
+
descendantScript,
|
|
614
|
+
], async (descriptor) => {
|
|
615
|
+
await resolveDescriptorAliases(descriptor);
|
|
616
|
+
const descendant = inspectWindowsCredentialAcl(descriptor, sid, {
|
|
617
|
+
resolvedAliases,
|
|
618
|
+
scope: "file",
|
|
619
|
+
});
|
|
620
|
+
if (!descendant.grantsCurrentUserAccess ||
|
|
621
|
+
descendant.untrustedPrincipals.length !== 0) {
|
|
622
|
+
privateDescendants = false;
|
|
623
|
+
}
|
|
624
|
+
}, { environment: processOptions.env });
|
|
625
|
+
});
|
|
626
|
+
return privateDescendants;
|
|
627
|
+
};
|
|
628
|
+
let existing;
|
|
629
|
+
for (let attempt = 0; existing === undefined && attempt < 3; attempt += 1) {
|
|
630
|
+
try {
|
|
631
|
+
existing = await readAcl();
|
|
632
|
+
}
|
|
633
|
+
catch (error) {
|
|
634
|
+
if (error instanceof UntrustedWindowsCredentialOwnerError) {
|
|
635
|
+
await execFile(icacls, [path, "/setowner", `*${sid}`], processOptions);
|
|
636
|
+
}
|
|
637
|
+
else if (error instanceof RepairableWindowsCredentialAclError) {
|
|
638
|
+
await installTrustedAcl();
|
|
639
|
+
}
|
|
640
|
+
else {
|
|
641
|
+
throw error;
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
if (existing === undefined) {
|
|
646
|
+
throw new Error("Windows credential ACL could not be repaired");
|
|
647
|
+
}
|
|
648
|
+
if (existing.grantsCurrentUserAccess &&
|
|
649
|
+
existing.untrustedPrincipals.length === 0 &&
|
|
650
|
+
!existing.protected) {
|
|
651
|
+
await execFile(icacls, [path, "/inheritance:d"], processOptions);
|
|
652
|
+
existing = await readAcl();
|
|
653
|
+
}
|
|
654
|
+
let verified = existing;
|
|
655
|
+
if (!verified.protected ||
|
|
656
|
+
!verified.grantsCurrentUserAccess ||
|
|
657
|
+
verified.untrustedPrincipals.length !== 0) {
|
|
658
|
+
await installTrustedAcl();
|
|
659
|
+
verified = await readAcl();
|
|
660
|
+
for (const principal of verified.untrustedPrincipals) {
|
|
661
|
+
if (!WINDOWS_SID.test(principal)) {
|
|
662
|
+
throw new Error("Windows credential ACL contains an unresolvable identity");
|
|
663
|
+
}
|
|
664
|
+
await execFile(icacls, [path, "/remove:g", `*${principal}`], processOptions);
|
|
665
|
+
}
|
|
666
|
+
for (const principal of verified.deniedPrincipals) {
|
|
667
|
+
if (!WINDOWS_SID.test(principal)) {
|
|
668
|
+
throw new Error("Windows credential ACL contains an unresolvable identity");
|
|
669
|
+
}
|
|
670
|
+
await execFile(icacls, [path, "/remove:d", `*${principal}`], processOptions);
|
|
671
|
+
}
|
|
672
|
+
if (verified.untrustedPrincipals.length !== 0 ||
|
|
673
|
+
verified.deniedPrincipals.length !== 0) {
|
|
674
|
+
verified = await readAcl();
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
if (!verified.protected) {
|
|
678
|
+
throw new Error("Windows credential ACL still inherits access rules");
|
|
679
|
+
}
|
|
680
|
+
if (!verified.grantsCurrentUserAccess) {
|
|
681
|
+
throw new Error("Windows credential ACL does not grant the current user access");
|
|
682
|
+
}
|
|
683
|
+
if (verified.untrustedPrincipals.length !== 0) {
|
|
684
|
+
throw new Error("Windows credential ACL grants access to another identity");
|
|
685
|
+
}
|
|
686
|
+
if (!(await descendantsArePrivate())) {
|
|
687
|
+
await execFile(icacls, [join(path, "*"), "/reset", "/t", "/q"], processOptions);
|
|
688
|
+
if (!(await descendantsArePrivate())) {
|
|
689
|
+
throw new Error("Windows credential descendants remain accessible");
|
|
690
|
+
}
|
|
691
|
+
}
|
|
125
692
|
}
|
|
126
|
-
export async function acquireCodexSecurityCredentialHomeLock(codexHome, signal) {
|
|
693
|
+
export async function acquireCodexSecurityCredentialHomeLock(codexHome, signal, securityOptions = {}) {
|
|
694
|
+
const homeMetadata = await requireSecureCredentialHome(codexHome, securityOptions);
|
|
695
|
+
const expectedDevice = homeMetadata.dev;
|
|
696
|
+
const expectedInode = homeMetadata.ino;
|
|
127
697
|
const lock = join(codexHome, CREDENTIAL_LOCK_NAME);
|
|
128
698
|
const ownerPath = join(lock, "owner.json");
|
|
129
699
|
const token = randomUUID();
|
|
130
700
|
while (true) {
|
|
131
701
|
throwIfSignalAborted(signal);
|
|
702
|
+
await requireSecureCredentialHome(codexHome, {
|
|
703
|
+
...securityOptions,
|
|
704
|
+
expectedDevice,
|
|
705
|
+
expectedInode,
|
|
706
|
+
validateWindowsAcl: false,
|
|
707
|
+
});
|
|
708
|
+
const existingLock = await lstat(lock).catch((error) => {
|
|
709
|
+
if (nodeErrorCode(error) === "ENOENT")
|
|
710
|
+
return null;
|
|
711
|
+
throw error;
|
|
712
|
+
});
|
|
713
|
+
if (existingLock !== null) {
|
|
714
|
+
if (await recoverStaleCredentialHomeLock(lock))
|
|
715
|
+
continue;
|
|
716
|
+
await delay(CREDENTIAL_LOCK_POLL_MILLISECONDS, undefined, { signal });
|
|
717
|
+
continue;
|
|
718
|
+
}
|
|
719
|
+
await requireSecureCredentialHome(codexHome, {
|
|
720
|
+
...securityOptions,
|
|
721
|
+
expectedDevice,
|
|
722
|
+
expectedInode,
|
|
723
|
+
});
|
|
132
724
|
try {
|
|
133
725
|
await mkdir(lock, { mode: 0o700 });
|
|
134
726
|
}
|
|
@@ -151,6 +743,11 @@ export async function acquireCodexSecurityCredentialHomeLock(codexHome, signal)
|
|
|
151
743
|
return async () => {
|
|
152
744
|
if (released)
|
|
153
745
|
return;
|
|
746
|
+
await requireSecureCredentialHome(codexHome, {
|
|
747
|
+
...securityOptions,
|
|
748
|
+
expectedDevice,
|
|
749
|
+
expectedInode,
|
|
750
|
+
});
|
|
154
751
|
const owner = JSON.parse(await readFile(ownerPath, "utf8"));
|
|
155
752
|
if (owner.token !== token) {
|
|
156
753
|
throw new PluginBootstrapError("The Codex Security credential-home lock is no longer owned by this scan.");
|
|
@@ -214,6 +811,7 @@ async function recoverStaleCredentialHomeLock(lock) {
|
|
|
214
811
|
return true;
|
|
215
812
|
}
|
|
216
813
|
export async function setCodexSecurityCredentialLogout(codexHome, loggedOut) {
|
|
814
|
+
await requireSecureCredentialHome(codexHome);
|
|
217
815
|
const marker = join(codexHome, CREDENTIAL_LOGOUT_MARKER);
|
|
218
816
|
if (!loggedOut) {
|
|
219
817
|
await rm(marker, { force: true });
|
|
@@ -237,6 +835,7 @@ export async function setCodexSecurityCredentialLogout(codexHome, loggedOut) {
|
|
|
237
835
|
}
|
|
238
836
|
}
|
|
239
837
|
export async function codexSecurityCredentialAllowsAmbientImport(codexHome) {
|
|
838
|
+
await requireSecureCredentialHome(codexHome);
|
|
240
839
|
try {
|
|
241
840
|
const marker = await lstat(join(codexHome, CREDENTIAL_LOGOUT_MARKER));
|
|
242
841
|
if (!marker.isFile() || marker.isSymbolicLink()) {
|
|
@@ -251,6 +850,7 @@ export async function codexSecurityCredentialAllowsAmbientImport(codexHome) {
|
|
|
251
850
|
}
|
|
252
851
|
}
|
|
253
852
|
export async function codexSecurityHasStoredFileCredentials(codexHome) {
|
|
853
|
+
await requireSecureCredentialHome(codexHome);
|
|
254
854
|
const path = join(codexHome, "auth.json");
|
|
255
855
|
let metadata;
|
|
256
856
|
try {
|
|
@@ -264,8 +864,19 @@ export async function codexSecurityHasStoredFileCredentials(codexHome) {
|
|
|
264
864
|
if (!metadata.isFile() || metadata.isSymbolicLink()) {
|
|
265
865
|
throw new OutputDirectoryError(`Codex Security stored authentication is not a regular file: ${path}`);
|
|
266
866
|
}
|
|
867
|
+
requirePrivateCredentialFile(metadata, path);
|
|
267
868
|
return true;
|
|
268
869
|
}
|
|
870
|
+
export function requirePrivateCredentialFile(metadata, path, effectiveUid = process.geteuid?.()) {
|
|
871
|
+
if (process.platform === "win32")
|
|
872
|
+
return;
|
|
873
|
+
if ((metadata.mode & 0o077) !== 0) {
|
|
874
|
+
throw new OutputDirectoryError(`Codex Security stored authentication must not be accessible to other users: ${path}`);
|
|
875
|
+
}
|
|
876
|
+
if (effectiveUid !== undefined && metadata.uid !== effectiveUid) {
|
|
877
|
+
throw new OutputDirectoryError(`Codex Security stored authentication must be owned by the current user: ${path}`);
|
|
878
|
+
}
|
|
879
|
+
}
|
|
269
880
|
export async function preserveCodexSecurityPluginRegistration(codexHome, config) {
|
|
270
881
|
let existing;
|
|
271
882
|
try {
|
|
@@ -320,7 +931,9 @@ export async function runWorkbench(options, args) {
|
|
|
320
931
|
...args,
|
|
321
932
|
], {
|
|
322
933
|
env: Object.fromEntries(Object.entries(options.environment).filter(([name]) => name.toUpperCase() !== "OPENAI_API_KEY" &&
|
|
323
|
-
name.toUpperCase() !== "CODEX_API_KEY"
|
|
934
|
+
name.toUpperCase() !== "CODEX_API_KEY" &&
|
|
935
|
+
name.toUpperCase() !== "OPENROUTER_API_KEY" &&
|
|
936
|
+
name.toUpperCase() !== "FIREWORKS_API_KEY")),
|
|
324
937
|
encoding: "utf8",
|
|
325
938
|
maxBuffer: 4 * 1024 * 1024,
|
|
326
939
|
windowsHide: true,
|
|
@@ -390,6 +1003,7 @@ export async function validateOutputDir(outputDirectory, archiveExisting = false
|
|
|
390
1003
|
throw new OutputDirectoryError(`Scan output directory is not empty: ${path}. To keep the existing results and start a new scan, add --archive-existing.`);
|
|
391
1004
|
}
|
|
392
1005
|
requirePrivateOutputDirectory(metadata, path);
|
|
1006
|
+
await requireSecureOutputAncestry(path);
|
|
393
1007
|
const canonical = await realpath(path);
|
|
394
1008
|
requireModelSafeOutputDir(canonical);
|
|
395
1009
|
return canonical;
|
|
@@ -400,6 +1014,7 @@ export async function validateOutputDir(outputDirectory, archiveExisting = false
|
|
|
400
1014
|
if ((await stat(parent)).isDirectory()) {
|
|
401
1015
|
const canonical = resolve(await realpath(parent), relative(parent, path));
|
|
402
1016
|
requireModelSafeOutputDir(canonical);
|
|
1017
|
+
await requireSecureOutputAncestry(canonical);
|
|
403
1018
|
return canonical;
|
|
404
1019
|
}
|
|
405
1020
|
break;
|
|
@@ -507,6 +1122,7 @@ export async function validatePreparedOutputDir(path, validateLocation) {
|
|
|
507
1122
|
throw new OutputDirectoryError(`Scan output directory must be empty: ${path}`);
|
|
508
1123
|
}
|
|
509
1124
|
requirePrivateOutputDirectory(metadata, path);
|
|
1125
|
+
await requireSecureOutputAncestry(canonical);
|
|
510
1126
|
return canonical;
|
|
511
1127
|
}
|
|
512
1128
|
export function requirePrivateOutputDirectory(metadata, path, effectiveUid = process.geteuid?.()) {
|
|
@@ -519,6 +1135,57 @@ export function requirePrivateOutputDirectory(metadata, path, effectiveUid = pro
|
|
|
519
1135
|
throw new OutputDirectoryError(`Scan output directory must be owned by the current user: ${path}`);
|
|
520
1136
|
}
|
|
521
1137
|
}
|
|
1138
|
+
/** Reject shared parents whose owner can rename or replace private scan output. */
|
|
1139
|
+
export async function requireSecureOutputAncestry(path, effectiveUid = process.geteuid?.()) {
|
|
1140
|
+
if (process.platform === "win32")
|
|
1141
|
+
return;
|
|
1142
|
+
let current = dirname(resolve(path));
|
|
1143
|
+
while (true) {
|
|
1144
|
+
try {
|
|
1145
|
+
current = await realpath(current);
|
|
1146
|
+
break;
|
|
1147
|
+
}
|
|
1148
|
+
catch (error) {
|
|
1149
|
+
if (nodeErrorCode(error) !== "ENOENT") {
|
|
1150
|
+
throw new OutputDirectoryError(`Unable to inspect scan output parent directory: ${current}`, { cause: error });
|
|
1151
|
+
}
|
|
1152
|
+
const parent = dirname(current);
|
|
1153
|
+
if (parent === current) {
|
|
1154
|
+
throw new OutputDirectoryError(`Unable to inspect scan output parent directory: ${current}`, { cause: error });
|
|
1155
|
+
}
|
|
1156
|
+
current = parent;
|
|
1157
|
+
}
|
|
1158
|
+
}
|
|
1159
|
+
while (true) {
|
|
1160
|
+
let metadata;
|
|
1161
|
+
try {
|
|
1162
|
+
metadata = await lstat(current);
|
|
1163
|
+
}
|
|
1164
|
+
catch (error) {
|
|
1165
|
+
throw new OutputDirectoryError(`Unable to inspect scan output parent directory: ${current}`, { cause: error });
|
|
1166
|
+
}
|
|
1167
|
+
if (!metadata.isDirectory() || metadata.isSymbolicLink()) {
|
|
1168
|
+
throw new OutputDirectoryError(`Scan output parent must be a non-symlink directory: ${current}`);
|
|
1169
|
+
}
|
|
1170
|
+
requireTrustedOutputAncestor(metadata, current, effectiveUid);
|
|
1171
|
+
const parent = dirname(current);
|
|
1172
|
+
if (parent === current)
|
|
1173
|
+
return;
|
|
1174
|
+
current = parent;
|
|
1175
|
+
}
|
|
1176
|
+
}
|
|
1177
|
+
export function requireTrustedOutputAncestor(metadata, path, effectiveUid = process.geteuid?.()) {
|
|
1178
|
+
if (effectiveUid !== undefined &&
|
|
1179
|
+
metadata.uid !== 0 &&
|
|
1180
|
+
metadata.uid !== effectiveUid) {
|
|
1181
|
+
throw new OutputDirectoryError(`Scan output parent must have a trusted owner: ${path}`);
|
|
1182
|
+
}
|
|
1183
|
+
if ((metadata.mode & 0o022) === 0)
|
|
1184
|
+
return;
|
|
1185
|
+
if ((metadata.mode & 0o1000) === 0) {
|
|
1186
|
+
throw new OutputDirectoryError(`Scan output parent must not be group- or world-writable without the sticky bit: ${path}`);
|
|
1187
|
+
}
|
|
1188
|
+
}
|
|
522
1189
|
async function removeEmptyDirectories(path, root) {
|
|
523
1190
|
let current = path;
|
|
524
1191
|
while (true) {
|
|
@@ -562,6 +1229,9 @@ export async function importAmbientAuth(ambientHome, isolatedHome) {
|
|
|
562
1229
|
return false;
|
|
563
1230
|
}
|
|
564
1231
|
await mkdir(isolatedHome, { recursive: true, mode: 0o700 });
|
|
1232
|
+
if (process.platform !== "win32" && (process.umask() & 0o700) !== 0) {
|
|
1233
|
+
await chmod(isolatedHome, 0o700);
|
|
1234
|
+
}
|
|
565
1235
|
if (await codexSecurityHasStoredFileCredentials(isolatedHome))
|
|
566
1236
|
return true;
|
|
567
1237
|
const destination = join(isolatedHome, "auth.json");
|
|
@@ -570,7 +1240,15 @@ export async function importAmbientAuth(ambientHome, isolatedHome) {
|
|
|
570
1240
|
await copyFile(source, temporary, constants.COPYFILE_EXCL);
|
|
571
1241
|
await chmod(temporary, 0o600);
|
|
572
1242
|
try {
|
|
573
|
-
|
|
1243
|
+
try {
|
|
1244
|
+
await link(temporary, destination);
|
|
1245
|
+
}
|
|
1246
|
+
catch (error) {
|
|
1247
|
+
if (!["EPERM", "ENOTSUP", "EOPNOTSUPP", "EXDEV", "EMLINK"].includes(nodeErrorCode(error) ?? "")) {
|
|
1248
|
+
throw error;
|
|
1249
|
+
}
|
|
1250
|
+
await copyFile(temporary, destination, constants.COPYFILE_EXCL);
|
|
1251
|
+
}
|
|
574
1252
|
}
|
|
575
1253
|
catch (error) {
|
|
576
1254
|
if (nodeErrorCode(error) === "EEXIST" &&
|
|
@@ -802,20 +1480,21 @@ async function pluginProjectionFingerprint(root, signal) {
|
|
|
802
1480
|
else {
|
|
803
1481
|
paths = [];
|
|
804
1482
|
const pending = [canonical];
|
|
805
|
-
let entries =
|
|
1483
|
+
let entries = 1;
|
|
806
1484
|
while (pending.length > 0) {
|
|
807
1485
|
throwIfSignalAborted(signal);
|
|
808
1486
|
const path = pending.pop();
|
|
809
1487
|
const metadata = await lstat(path);
|
|
810
|
-
if (++entries > MAX_PLUGIN_COPY_ENTRIES) {
|
|
811
|
-
throw new PluginBootstrapError(`Plugin source exceeds the copy entry limit: ${path}`);
|
|
812
|
-
}
|
|
813
1488
|
if (metadata.isSymbolicLink()) {
|
|
814
1489
|
throw new PluginBootstrapError(`Plugin contains an unsafe source path: ${path}`);
|
|
815
1490
|
}
|
|
816
1491
|
if (metadata.isDirectory()) {
|
|
817
|
-
for (const entry of
|
|
818
|
-
|
|
1492
|
+
for await (const entry of pluginDirectoryEntries(path, signal)) {
|
|
1493
|
+
const child = join(path, entry);
|
|
1494
|
+
if (++entries > MAX_PLUGIN_COPY_ENTRIES) {
|
|
1495
|
+
throw new PluginBootstrapError(`Plugin source exceeds the copy entry limit: ${child}`);
|
|
1496
|
+
}
|
|
1497
|
+
pending.push(child);
|
|
819
1498
|
}
|
|
820
1499
|
}
|
|
821
1500
|
else if (metadata.isFile()) {
|
|
@@ -1179,7 +1858,7 @@ async function copyPluginTree(source, destination, signal) {
|
|
|
1179
1858
|
{ source, destination },
|
|
1180
1859
|
];
|
|
1181
1860
|
const directories = new Map();
|
|
1182
|
-
let entries =
|
|
1861
|
+
let entries = 1;
|
|
1183
1862
|
let size = 0;
|
|
1184
1863
|
await mkdir(dirname(destination), { recursive: true, mode: 0o700 });
|
|
1185
1864
|
try {
|
|
@@ -1188,26 +1867,26 @@ async function copyPluginTree(source, destination, signal) {
|
|
|
1188
1867
|
const current = pending.pop();
|
|
1189
1868
|
await requirePluginAncestors(source, current.source, directories, signal);
|
|
1190
1869
|
const metadata = await lstat(current.source);
|
|
1191
|
-
if (++entries > MAX_PLUGIN_COPY_ENTRIES) {
|
|
1192
|
-
throw new PluginBootstrapError(`Plugin source exceeds the copy entry limit: ${current.source}`);
|
|
1193
|
-
}
|
|
1194
1870
|
if (metadata.isSymbolicLink()) {
|
|
1195
1871
|
throw new PluginBootstrapError(`Plugin contains an unsafe source path: ${current.source}`);
|
|
1196
1872
|
}
|
|
1197
1873
|
if (metadata.isDirectory()) {
|
|
1198
|
-
const
|
|
1874
|
+
for await (const entry of pluginDirectoryEntries(current.source, signal)) {
|
|
1875
|
+
const childSource = join(current.source, entry);
|
|
1876
|
+
if (++entries > MAX_PLUGIN_COPY_ENTRIES) {
|
|
1877
|
+
throw new PluginBootstrapError(`Plugin source exceeds the copy entry limit: ${childSource}`);
|
|
1878
|
+
}
|
|
1879
|
+
pending.push({
|
|
1880
|
+
source: childSource,
|
|
1881
|
+
destination: join(current.destination, entry),
|
|
1882
|
+
});
|
|
1883
|
+
}
|
|
1199
1884
|
const afterRead = await lstat(current.source);
|
|
1200
1885
|
if (!samePluginFile(metadata, afterRead)) {
|
|
1201
1886
|
throw new PluginBootstrapError(`Plugin directory changed while it was being copied: ${current.source}`);
|
|
1202
1887
|
}
|
|
1203
1888
|
directories.set(current.source, afterRead);
|
|
1204
1889
|
await mkdir(current.destination, { mode: 0o700 });
|
|
1205
|
-
for (const child of children) {
|
|
1206
|
-
pending.push({
|
|
1207
|
-
source: join(current.source, child),
|
|
1208
|
-
destination: join(current.destination, child),
|
|
1209
|
-
});
|
|
1210
|
-
}
|
|
1211
1890
|
continue;
|
|
1212
1891
|
}
|
|
1213
1892
|
if (!metadata.isFile()) {
|
|
@@ -1253,6 +1932,23 @@ async function copyPluginTree(source, destination, signal) {
|
|
|
1253
1932
|
throw error;
|
|
1254
1933
|
}
|
|
1255
1934
|
}
|
|
1935
|
+
async function* pluginDirectoryEntries(path, signal) {
|
|
1936
|
+
throwIfSignalAborted(signal);
|
|
1937
|
+
const directory = await opendir(path);
|
|
1938
|
+
try {
|
|
1939
|
+
for (;;) {
|
|
1940
|
+
throwIfSignalAborted(signal);
|
|
1941
|
+
const entry = await directory.read();
|
|
1942
|
+
throwIfSignalAborted(signal);
|
|
1943
|
+
if (entry === null)
|
|
1944
|
+
return;
|
|
1945
|
+
yield entry.name;
|
|
1946
|
+
}
|
|
1947
|
+
}
|
|
1948
|
+
finally {
|
|
1949
|
+
await directory.close();
|
|
1950
|
+
}
|
|
1951
|
+
}
|
|
1256
1952
|
async function requirePluginAncestors(root, path, directories, signal) {
|
|
1257
1953
|
const relativePath = relative(root, path);
|
|
1258
1954
|
if (relativePath === ".." ||
|