OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security
TypeScript ai-securityapplication-securityclicode-scanningcodexcodex-securitycybersecuritydevsecopsnodejsnpmopenaisdksecuritytypescriptvulnerability-scanning
fix(windows): inspect long credential-home descendant paths (#2294)
Michael D'Angelo0ad515bc5224
diff --git a/sdk/typescript/src/runtime.ts b/sdk/typescript/src/runtime.tsindex bab01f806..bf1526db1 100644--- a/sdk/typescript/src/runtime.ts+++ b/sdk/typescript/src/runtime.ts@@ -964,6 +964,7 @@ export async function inspectWindowsCredentialAclSnapshot(async function secureWindowsCredentialHome(path: string): Promise<void> {const ancestorAclScript = windowsCredentialAncestorAclScript(path);+ const treePath = win32.toNamespacedPath(path);const systemRoot = process.env["SystemRoot"] ?? "C:\\Windows";const systemDirectory = join(systemRoot, "System32");const powershell = join(@@ -981,6 +982,7 @@ async function secureWindowsCredentialHome(path: string): Promise<void> {env: {...inheritedEnvironment,CODEX_SECURITY_CREDENTIAL_ACL_PATH: path,+ CODEX_SECURITY_CREDENTIAL_TREE_PATH: treePath,PSModulePath: join(systemDirectory,"WindowsPowerShell",@@ -1017,24 +1019,26 @@ async function secureWindowsCredentialHome(path: string): Promise<void> {// A child can disappear while an existing directory is being enumerated.// Retry that incomplete listing before accepting a vanished descendant.` if ($_.FullyQualifiedErrorId -eq 'System.IO.FileNotFoundException,Microsoft.PowerShell.Commands.GetChildItemCommand') { exit ${WINDOWS_CREDENTIAL_DESCENDANTS_CHANGED_EXIT_CODE} }`,- " if ($path -ne $env:CODEX_SECURITY_CREDENTIAL_ACL_PATH -and $_.CategoryInfo.Category -eq 'ObjectNotFound') { return }",+ " if ($path -ne $env:CODEX_SECURITY_CREDENTIAL_TREE_PATH -and $_.CategoryInfo.Category -eq 'ObjectNotFound') { return }"," throw"," }"," 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' }",- " try { Write-CredentialAcl $entry.FullName } catch {",+ // 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"," }",- " if ($entry.PSIsContainer) { Read-CredentialDescendants $entry.FullName }",+ " if ($entry.PSIsContainer) { Read-CredentialDescendants $child }"," }","}",ancestorAclScript,"Write-CredentialAcl $env:CODEX_SECURITY_CREDENTIAL_ACL_PATH",- "Read-CredentialDescendants $env:CODEX_SECURITY_CREDENTIAL_ACL_PATH",+ "Read-CredentialDescendants $env:CODEX_SECURITY_CREDENTIAL_TREE_PATH",`"${WINDOWS_CREDENTIAL_ACL_COMPLETE_PREFIX}$script:descriptorCount"`,].join("\n");const resolvePrincipalScript = [@@ -1197,7 +1201,7 @@ async function secureWindowsCredentialHome(path: string): Promise<void> {if (!descendantsArePrivate) {await execFile(icacls,- [join(path, "*"), "/reset", "/t", "/q"],+ [join(treePath, "*"), "/reset", "/t", "/q"],processOptions,);await readAcl();diff --git a/sdk/typescript/tests-ts/runtime.test.ts b/sdk/typescript/tests-ts/runtime.test.tsindex 1b116b013..f0b8a5894 100644--- a/sdk/typescript/tests-ts/runtime.test.ts+++ b/sdk/typescript/tests-ts/runtime.test.ts@@ -185,6 +185,35 @@ function inspectWindowsTestAcl();}+function grantReadToEveryone(...credentials: string[]) {+ const sid = windowsUserSid();+ for (const credential of credentials) {+ const grant = windowsTestCommand("icacls.exe", [+ credential,+ "/inheritance:r",+ "/grant:r",+ `*${sid}:F`,+ "*S-1-1-0:R",+ ]);+ expect(grant.status, grant.stderr).toBe(0);+ }+}++function expectNoEveryoneGrant(credential: string) {+ const inspection = inspectWindowsTestAcl(+ [+ "$ErrorActionPreference = 'Stop'",+ '$env:PSModulePath = "$PSHOME\\Modules"',+ "$acl = Microsoft.PowerShell.Security\\Get-Acl -LiteralPath $env:CODEX_SECURITY_TEST_ACL_PATH",+ "$everyone = @($acl.Access | Where-Object { $_.AccessControlType -eq 'Allow' -and $_.IdentityReference.Translate([System.Security.Principal.SecurityIdentifier]).Value -eq 'S-1-1-0' })",+ "$everyone.Count",+ ],+ { ...process.env, CODEX_SECURITY_TEST_ACL_PATH: credential },+ );+ expect(inspection.status, inspection.stderr).toBe(0);+ expect(inspection.stdout.trim()).toBe("0");+}+function windowsCredentialAclOutput(descriptors: readonly string[]): string {return `${descriptors.join("\n")}\nCODEX_SECURITY_ACL_COMPLETE:${descriptors.length}\n`;}@@ -3680,7 +3709,9 @@ describe("runtime directories and plugin Python boundary", () => {: missing && !pathNotFound? "NotSpecified": "ObjectNotFound";- const failurePath = kind.endsWith("home") ? home : descendant;+ 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) {";@@ -5167,18 +5198,7 @@ describe("runtime directories and plugin Python boundary", () => {await writeFile(auth, '{"token":"synthetic-root"}\n');await writeFile(nestedAuth, '{"token":"synthetic-nested"}\n');- const sid = windowsUserSid();-- for (const credential of [auth, nestedAuth]) {- const unsafe = windowsTestCommand("icacls.exe", [- credential,- "/inheritance:r",- "/grant:r",- `*${sid}:F`,- "*S-1-1-0:R",- ]);- expect(unsafe.status).toBe(0);- }+ grantReadToEveryone(auth, nestedAuth);expect(await prepareCodexSecurityCredentialHome({@@ -5186,25 +5206,32 @@ describe("runtime directories and plugin Python boundary", () => {}),).toBe(await realpath(home));- const inspection = inspectWindowsTestAcl(- [- "$paths = @($env:CODEX_SECURITY_TEST_AUTH_PATH, $env:CODEX_SECURITY_TEST_NESTED_AUTH_PATH)",- "$unexpected = @($paths | ForEach-Object { $acl = Get-Acl -LiteralPath $_; $acl.Access | Where-Object { $_.AccessControlType -eq 'Allow' -and $_.IdentityReference.Translate([System.Security.Principal.SecurityIdentifier]).Value -eq 'S-1-1-0' } })",- "[pscustomobject]@{ unexpected = $unexpected.Count } | ConvertTo-Json -Compress",- ],- {- ...process.env,- CODEX_SECURITY_TEST_AUTH_PATH: auth,- CODEX_SECURITY_TEST_NESTED_AUTH_PATH: nestedAuth,- },- );- expect(inspection.status).toBe(0);- expect(JSON.parse(inspection.stdout)).toEqual({ unexpected: 0 });+ expectNoEveryoneGrant(auth);+ expectNoEveryoneGrant(nestedAuth);expect(await readFile(auth, "utf8")).toContain("synthetic-root");expect(await readFile(nestedAuth, "utf8")).toContain("synthetic-nested");},);+ test.skipIf(process.platform !== "win32")(+ "repairs an unsafe ACL on a Windows credential file beyond MAX_PATH",+ async () => {+ const { home } = await credentialHome(true);+ const nested = win32.toNamespacedPath(+ join(home, "sessions", "a".repeat(130), "b".repeat(130)),+ );+ await mkdir(nested, { recursive: true });+ const credential = join(nested, "credentials.json");+ await writeFile(credential, '{"token":"synthetic-nested"}\n');++ grantReadToEveryone(credential);+ await requireSecureCredentialHome(home);++ expectNoEveryoneGrant(credential);+ expect(await readFile(credential, "utf8")).toContain("synthetic-nested");+ },+ );+test("derives persistent state from the ambient home or explicit override", async () => {const root = await temporaryDirectory();expect(codexSecurityStateDirectory({ CODEX_HOME: root })).toBe(