Skip to content

OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security

fix(runtime): batch Windows credential ACL inspection (#2349)

Dipesh Babu1c53c04a3f97
diff --git a/sdk/typescript/src/runtime.ts b/sdk/typescript/src/runtime.ts
index 2f5f2071a..4ca9d1749 100644
--- a/sdk/typescript/src/runtime.ts
+++ b/sdk/typescript/src/runtime.ts
@@ -967,12 +967,18 @@ async function secureWindowsCredentialHome(path: string): Promise<void> {
const treePath = win32.toNamespacedPath(path);
const systemRoot = process.env["SystemRoot"] ?? "C:\\Windows";
const systemDirectory = join(systemRoot, "System32");
- const powershell = join(
+ const powershellDirectory = join(
systemDirectory,
"WindowsPowerShell",
"v1.0",
- "powershell.exe",
);
+ const powershell = join(powershellDirectory, "powershell.exe");
+ const powershellArgs = [
+ "-NoLogo",
+ "-NoProfile",
+ "-NonInteractive",
+ "-Command",
+ ];
const inheritedEnvironment = Object.fromEntries(
Object.entries(process.env).filter(
([name]) => name.toUpperCase() !== "PSMODULEPATH",
@@ -983,12 +989,7 @@ async function secureWindowsCredentialHome(path: string): Promise<void> {
...inheritedEnvironment,
CODEX_SECURITY_CREDENTIAL_ACL_PATH: path,
CODEX_SECURITY_CREDENTIAL_TREE_PATH: treePath,
- PSModulePath: join(
- systemDirectory,
- "WindowsPowerShell",
- "v1.0",
- "Modules",
- ),
+ PSModulePath: join(powershellDirectory, "Modules"),
},
encoding: "utf8" as const,
windowsHide: true,
@@ -1013,7 +1014,11 @@ async function secureWindowsCredentialHome(path: string): Promise<void> {
const script = [
"$ErrorActionPreference = 'Stop'",
"$script:descriptorCount = 0",
- "function Write-CredentialAcl($path) { $descriptor = Microsoft.PowerShell.Security\\Get-Acl -LiteralPath $path | Microsoft.PowerShell.Utility\\Select-Object -ExpandProperty Sddl; if (-not $descriptor) { throw 'Windows credential ACL could not be verified' }; $script:descriptorCount += 1; $descriptor }",
+ "function Write-CredentialAcl($path) {",
+ " $descriptors = @(Microsoft.PowerShell.Security\\Get-Acl -LiteralPath $path | Microsoft.PowerShell.Utility\\Select-Object -ExpandProperty Sddl)",
+ " if ($descriptors.Count -ne @($path).Count) { throw 'Windows credential ACL could not be verified' }",
+ " foreach ($descriptor in $descriptors) { if (-not $descriptor) { throw 'Windows credential ACL could not be verified' }; $script:descriptorCount += 1; $descriptor }",
+ "}",
"function Read-CredentialDescendants($path) {",
" try { $entries = @(Microsoft.PowerShell.Management\\Get-ChildItem -LiteralPath $path -Force) } catch {",
// A child can disappear while an existing directory is being enumerated.
@@ -1022,23 +1027,34 @@ async function secureWindowsCredentialHome(path: string): Promise<void> {
" if ($path -ne $env:CODEX_SECURITY_CREDENTIAL_TREE_PATH -and $_.CategoryInfo.Category -eq 'ObjectNotFound') { return }",
" throw",
" }",
- " foreach ($entry in $entries) {",
+ " $children = @(foreach ($entry in $entries) {",
" if (($entry.Attributes -band 1024) -and ($entry.LinkType -in @('SymbolicLink', 'Junction'))) { throw 'Windows credential home contains a symbolic link or junction' }",
" if ($entry.PSObject.TypeNames -notcontains 'System.IO.DirectoryInfo' -and $entry.PSObject.TypeNames -notcontains 'System.IO.FileInfo') { throw 'Windows credential home contains an unsafe entry' }",
// Keep the extended-length path when Windows PowerShell returns child names.
- ' $child = "$path\\$($entry.Name)"',
- " try { Write-CredentialAcl $child } catch {",
- // A descendant can disappear inside Get-Acl after it was enumerated.
- ` if ($_.FullyQualifiedErrorId -eq 'System.IO.FileNotFoundException,Microsoft.PowerShell.Commands.GetAclCommand' -or $_.FullyQualifiedErrorId -eq 'GetAcl_PathNotFound_Exception,Microsoft.PowerShell.Commands.GetAclCommand') { exit ${WINDOWS_CREDENTIAL_DESCENDANTS_CHANGED_EXIT_CODE} }`,
- " if ($_.FullyQualifiedErrorId -like 'GetAcl_PathNotFound,*') { continue }",
- " throw",
+ ' "$path\\$($entry.Name)"',
+ " })",
+ " if ($children.Count -eq 0) { return }",
+ " try { Write-CredentialAcl $children } catch {",
+ // A vanished path is the only reason to retry the batch one child at a time.
+ " if ($_.FullyQualifiedErrorId -notlike 'GetAcl_PathNotFound,*') { throw }",
+ " for ($i = 0; $i -lt $children.Count; $i++) {",
+ " try { Write-CredentialAcl $children[$i] } catch {",
+ " if ($_.FullyQualifiedErrorId -notlike 'GetAcl_PathNotFound,*') { throw }",
+ " $children[$i] = $null",
+ " }",
" }",
- " if ($entry.PSIsContainer) { Read-CredentialDescendants $child }",
+ " }",
+ " for ($i = 0; $i -lt $children.Count; $i++) {",
+ " if ($children[$i] -and $entries[$i].PSIsContainer) { Read-CredentialDescendants $children[$i] }",
" }",
"}",
ancestorAclScript,
"Write-CredentialAcl $env:CODEX_SECURITY_CREDENTIAL_ACL_PATH",
- "Read-CredentialDescendants $env:CODEX_SECURITY_CREDENTIAL_TREE_PATH",
+ "try { Read-CredentialDescendants $env:CODEX_SECURITY_CREDENTIAL_TREE_PATH } catch {",
+ // Either a batch or a single-child Get-Acl may report an incomplete listing.
+ ` if ($_.FullyQualifiedErrorId -in @('System.IO.FileNotFoundException,Microsoft.PowerShell.Commands.GetAclCommand', 'GetAcl_PathNotFound_Exception,Microsoft.PowerShell.Commands.GetAclCommand')) { exit ${WINDOWS_CREDENTIAL_DESCENDANTS_CHANGED_EXIT_CODE} }`,
+ " throw",
+ "}",
`"${WINDOWS_CREDENTIAL_ACL_COMPLETE_PREFIX}$script:descriptorCount"`,
].join("\n");
const resolvePrincipalScript = [
@@ -1047,6 +1063,13 @@ async function secureWindowsCredentialHome(path: string): Promise<void> {
"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",
].join("; ");
const resolvedAliases: Record<string, string> = {};
+ function requireNumericSid(value: string): string {
+ if (!WINDOWS_SID.test(value))
+ throw new Error(
+ "Windows credential ACL contains an unresolvable identity",
+ );
+ return value;
+ }
const resolvePrincipal = async (principal: string): Promise<void> => {
if (
!/^[A-Z]{2}$/u.test(principal) ||
@@ -1057,13 +1080,7 @@ async function secureWindowsCredentialHome(path: string): Promise<void> {
}
const resolved = await execFile(
powershell,
- [
- "-NoLogo",
- "-NoProfile",
- "-NonInteractive",
- "-Command",
- resolvePrincipalScript,
- ],
+ [...powershellArgs, resolvePrincipalScript],
{
...processOptions,
env: {
@@ -1072,13 +1089,7 @@ async function secureWindowsCredentialHome(path: string): Promise<void> {
},
},
);
- const numeric = resolved.stdout.trim();
- if (!WINDOWS_SID.test(numeric)) {
- throw new Error(
- "Windows credential ACL contains an unresolvable identity",
- );
- }
- resolvedAliases[principal] = numeric;
+ resolvedAliases[principal] = requireNumericSid(resolved.stdout.trim());
};
const resolveDescriptorAliases = async (
descriptor: string,
@@ -1098,7 +1109,7 @@ async function secureWindowsCredentialHome(path: string): Promise<void> {
const readAcl = async (): Promise<WindowsCredentialAcl> => {
const snapshot = await inspectWindowsCredentialAclSnapshot(path, sid, {
command: powershell,
- args: ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", script],
+ args: [...powershellArgs, script],
environment: processOptions.env,
resolvedAliases,
resolveDescriptorAliases,
@@ -1107,28 +1118,28 @@ async function secureWindowsCredentialHome(path: string): Promise<void> {
return snapshot.home;
};
- const icacls = join(systemDirectory, "icacls.exe");
- const installTrustedAcl = async (target = path): Promise<void> => {
- await execFile(
- icacls,
- [
- target,
- "/inheritance:r",
- "/grant:r",
- `*${sid}:(OI)(CI)F`,
- `*${WINDOWS_SYSTEM_SID}:(OI)(CI)F`,
- `*${WINDOWS_ADMINISTRATORS_SID}:(OI)(CI)F`,
- ],
+ const icacls = (target: string, ...args: string[]) =>
+ execFile(
+ join(systemDirectory, "icacls.exe"),
+ [target, ...args],
processOptions,
);
- };
+ const installTrustedAcl = () =>
+ icacls(
+ path,
+ "/inheritance:r",
+ "/grant:r",
+ `*${sid}:(OI)(CI)F`,
+ `*${WINDOWS_SYSTEM_SID}:(OI)(CI)F`,
+ `*${WINDOWS_ADMINISTRATORS_SID}:(OI)(CI)F`,
+ );
let existing: WindowsCredentialAcl | undefined;
for (let attempt = 0; existing === undefined && attempt < 3; attempt += 1) {
try {
existing = await readAcl();
} catch (error) {
if (error instanceof RepairableWindowsCredentialOwnerError) {
- await execFile(icacls, [path, "/setowner", `*${sid}`], processOptions);
+ await icacls(path, "/setowner", `*${sid}`);
} else if (error instanceof RepairableWindowsCredentialAclError) {
await installTrustedAcl();
} else {
@@ -1144,7 +1155,7 @@ async function secureWindowsCredentialHome(path: string): Promise<void> {
existing.untrustedPrincipals.length === 0 &&
!existing.protected
) {
- await execFile(icacls, [path, "/inheritance:d"], processOptions);
+ await icacls(path, "/inheritance:d");
existing = await readAcl();
}
@@ -1156,29 +1167,12 @@ async function secureWindowsCredentialHome(path: string): Promise<void> {
) {
await installTrustedAcl();
verified = await readAcl();
- for (const principal of verified.untrustedPrincipals) {
- if (!WINDOWS_SID.test(principal)) {
- throw new Error(
- "Windows credential ACL contains an unresolvable identity",
- );
- }
- await execFile(
- icacls,
- [path, "/remove:g", `*${principal}`],
- processOptions,
- );
- }
- for (const principal of verified.deniedPrincipals) {
- if (!WINDOWS_SID.test(principal)) {
- throw new Error(
- "Windows credential ACL contains an unresolvable identity",
- );
- }
- await execFile(
- icacls,
- [path, "/remove:d", `*${principal}`],
- processOptions,
- );
+ for (const [remove, principals] of [
+ ["/remove:g", verified.untrustedPrincipals],
+ ["/remove:d", verified.deniedPrincipals],
+ ] as const) {
+ for (const principal of principals)
+ await icacls(path, remove, `*${requireNumericSid(principal)}`);
}
if (
verified.untrustedPrincipals.length !== 0 ||
@@ -1199,11 +1193,7 @@ async function secureWindowsCredentialHome(path: string): Promise<void> {
throw new Error("Windows credential ACL grants access to another identity");
}
if (!descendantsArePrivate) {
- await execFile(
- icacls,
- [join(treePath, "*"), "/reset", "/t", "/q"],
- processOptions,
- );
+ await icacls(join(treePath, "*"), "/reset", "/t", "/q");
await readAcl();
if (!descendantsArePrivate) {
throw new Error("Windows credential descendants remain accessible");
diff --git a/sdk/typescript/tests-ts/runtime.test.ts b/sdk/typescript/tests-ts/runtime.test.ts
index b5db000ea..ede7d941b 100644
--- a/sdk/typescript/tests-ts/runtime.test.ts
+++ b/sdk/typescript/tests-ts/runtime.test.ts
@@ -142,6 +142,34 @@ function credentialAncestors(home: string, directory: string): string[] {
return ancestors;
}
+const credentialAclFunction = "function Write-CredentialAcl($path) {";
+
+function instrumentCredentialAcl(
+ home: string,
+ transform: (script: string) => string,
+) {
+ const originalSpawn = childProcess.spawn;
+ mock.module("node:child_process", () => ({
+ ...childProcess,
+ spawn: (...spawnArgs: Parameters<typeof childProcess.spawn>) => {
+ const [command, args, options] = spawnArgs;
+ if (
+ options?.env?.["CODEX_SECURITY_CREDENTIAL_ACL_PATH"] !== home ||
+ !Array.isArray(args)
+ )
+ return originalSpawn(...spawnArgs);
+ const index = args.indexOf("-Command") + 1;
+ const script = args[index];
+ if (typeof script !== "string" || !script.includes(credentialAclFunction))
+ return originalSpawn(...spawnArgs);
+ const instrumented = [...args];
+ instrumented[index] = transform(script);
+ return originalSpawn(command, instrumented, options);
+ },
+ }));
+ return () => restoreSpawn(originalSpawn);
+}
+
function windowsTestCommand(
tool: string,
args: readonly string[],
@@ -3671,6 +3699,7 @@ describe("runtime directories and plugin Python boundary", () => {
"transient missing descendant",
"persistent missing descendant",
"access denied",
+ "batch access denied",
"unexpected error",
"missing home",
"transient path-not-found descendant",
@@ -3689,66 +3718,41 @@ describe("runtime directories and plugin Python boundary", () => {
await requireSecureCredentialHome(home);
const descendant = join(home, ".auth-replay.tmp");
await writeFile(descendant, "synthetic credential\n", { mode: 0o600 });
+ const batchOnly = kind === "batch access denied";
+ if (batchOnly) await writeFile(join(home, "sibling.tmp"), "fixture\n");
+ const accessDenied = kind.endsWith("access denied");
const pathNotFound = kind.includes("path-not-found");
const missing = pathNotFound || kind.includes("missing");
const transient = kind.startsWith("transient ");
const persistent = kind.startsWith("persistent ");
- const exception = pathNotFound
- ? "System.Management.Automation.ItemNotFoundException"
+ const [exception, category] = pathNotFound
+ ? ["System.Management.Automation.ItemNotFoundException", "ObjectNotFound"]
: missing
- ? "System.IO.FileNotFoundException"
- : kind === "access denied"
- ? "System.UnauthorizedAccessException"
- : "System.InvalidOperationException";
- const errorId = pathNotFound
- ? "GetAcl_PathNotFound_Exception,Microsoft.PowerShell.Commands.GetAclCommand"
- : missing
- ? "System.IO.FileNotFoundException,Microsoft.PowerShell.Commands.GetAclCommand"
- : kind === "access denied"
- ? "System.UnauthorizedAccessException,Microsoft.PowerShell.Commands.GetAclCommand"
- : "SyntheticCredentialAclFailure";
- const category =
- kind === "access denied"
- ? "PermissionDenied"
- : missing && !pathNotFound
- ? "NotSpecified"
- : "ObjectNotFound";
+ ? ["System.IO.FileNotFoundException", "NotSpecified"]
+ : accessDenied
+ ? ["System.UnauthorizedAccessException", "PermissionDenied"]
+ : ["System.InvalidOperationException", "ObjectNotFound"];
+ const errorName = pathNotFound
+ ? "GetAcl_PathNotFound_Exception"
+ : exception;
+ const errorId =
+ missing || accessDenied
+ ? `${errorName},Microsoft.PowerShell.Commands.GetAclCommand`
+ : "SyntheticCredentialAclFailure";
const failurePath = kind.endsWith("home")
? home
: win32.toNamespacedPath(descendant);
// Replay the native error without relying on racing a filesystem deletion.
- const injection = `if ($path -eq '${failurePath.replaceAll("'", "''")}') { throw [System.Management.Automation.ErrorRecord]::new([${exception}]::new('synthetic credential ACL error'), '${errorId}', [System.Management.Automation.ErrorCategory]::${category}, $path) };`;
- const marker = "function Write-CredentialAcl($path) {";
- const originalSpawn = childProcess.spawn;
+ const injection = `if (@($path) -contains '${failurePath.replaceAll("'", "''")}'${batchOnly ? " -and @($path).Count -gt 1" : ""}) { throw [System.Management.Automation.ErrorRecord]::new([${exception}]::new('synthetic credential ACL error'), '${errorId}', [System.Management.Automation.ErrorCategory]::${category}, $path) };`;
let attempts = 0;
- mock.module("node:child_process", () => ({
- ...childProcess,
- spawn: (...spawnArgs: Parameters<typeof childProcess.spawn>) => {
- const [command, args, options] = spawnArgs;
- if (
- options?.env?.["CODEX_SECURITY_CREDENTIAL_ACL_PATH"] !== home ||
- !Array.isArray(args)
- ) {
- return originalSpawn(...spawnArgs);
- }
- const scriptIndex = args.indexOf("-Command") + 1;
- const script = args[scriptIndex];
- if (typeof script !== "string" || !script.includes(marker)) {
- return originalSpawn(...spawnArgs);
- }
- attempts += 1;
- if (transient && attempts > 1) {
- return originalSpawn(...spawnArgs);
- }
- expect(script.split(marker)).toHaveLength(2);
- const replayArgs = [...args];
- replayArgs[scriptIndex] = script.replace(
- marker,
- `${marker} ${injection}`,
- );
- return originalSpawn(command, replayArgs, options);
- },
- }));
+ const restore = instrumentCredentialAcl(home, (script) => {
+ attempts += 1;
+ if (transient && attempts > 1) return script;
+ return script.replace(
+ credentialAclFunction,
+ `${credentialAclFunction} ${injection}`,
+ );
+ });
try {
if (transient) {
await requireSecureCredentialHome(home);
@@ -3762,10 +3766,50 @@ describe("runtime directories and plugin Python boundary", () => {
expect(attempts).toBe(persistent ? 3 : 1);
}
} finally {
- restoreSpawn(originalSpawn);
+ restore();
}
});
+ for (const language of ["FullLanguage", "ConstrainedLanguage"] as const) {
+ const name = `batches Windows credential ACL queries without dropping files in ${language}`;
+ test.skipIf(process.platform !== "win32")(name, async () => {
+ if (runTestInSubprocess(import.meta.path, name)) return;
+ const { root, home } = await credentialHome(false);
+ await requireSecureCredentialHome(home);
+ const cache = join(home, "cache");
+ await mkdir(cache);
+ for (let index = 0; index < 8; index++)
+ await writeFile(join(cache, `entry-${index}.txt`), "fixture\n");
+ const trace = join(root, "acl-queries.txt");
+ const append = `Microsoft.PowerShell.Management\\Add-Content -LiteralPath '${trace.replaceAll("'", "''")}' -Value`;
+ const restore = instrumentCredentialAcl(home, (script) =>
+ [
+ language === "ConstrainedLanguage"
+ ? "$ExecutionContext.SessionState.LanguageMode = 'ConstrainedLanguage'"
+ : "",
+ script.replace(
+ credentialAclFunction,
+ `${credentialAclFunction} ${append} (@($path).Count);`,
+ ),
+ `${append} ('complete:' + $script:descriptorCount)`,
+ ].join("\n"),
+ );
+ try {
+ await requireSecureCredentialHome(home);
+ const rows = (await readFile(trace, "utf8")).trim().split(/\r?\n/u);
+ const expected = credentialAncestors(home, "").length + 10;
+ expect(rows.pop()).toBe(`complete:${expected}`);
+ const queries = rows.map(Number);
+ expect(queries).toContain(8);
+ expect(queries.reduce((total, count) => total + count, 0)).toBe(
+ expected,
+ );
+ } finally {
+ restore();
+ }
+ });
+ }
+
test("retries interrupted Windows credential ACL enumeration", async () => {
const root = await temporaryDirectory();
const home = join(root, "home");