Repository navigation
Expand file tree
/
Copy pathruntime.ts
More file actions
3630 lines (3465 loc) · 112 KB
/
Copy pathruntime.ts
File metadata and controls
3630 lines (3465 loc) · 112 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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { forwardExternalImportSetting } from "./external-imports-feature.js";
import { executablePathForSpawn } from "./executable-path.js";
export { executablePathForSpawn } from "./executable-path.js";
import { resolveBundledCodexExecutable } from "./codex-sdk-environment.js";
import { gitProtectionRoots } from "./targets.js";
import { isNonEmptyString, notify } from "./value.js";
import {
execFile as execFileCallback,
spawn,
type ChildProcessWithoutNullStreams,
type SpawnOptionsWithoutStdio,
} from "node:child_process";
import { randomUUID } from "node:crypto";
import {
chmodSync,
close as closeCallback,
constants,
createWriteStream,
fstat as fstatCallback,
open as openCallback,
read as readCallback,
type BigIntStats,
type Stats,
} from "node:fs";
import {
chmod,
cp,
copyFile,
link,
lstat,
mkdir,
mkdtemp,
open,
readFile,
readdir,
realpath,
rename,
rm,
rmdir,
stat,
utimes,
writeFile,
} from "node:fs/promises";
import { homedir, tmpdir } from "node:os";
import { createRequire } from "node:module";
import {
basename,
dirname,
extname,
isAbsolute,
join,
relative,
resolve,
sep,
win32,
} from "node:path";
import { fileURLToPath } from "node:url";
import { promisify } from "node:util";
import { pipeline } from "node:stream/promises";
import { crc32 } from "node:zlib";
import { setTimeout as delay } from "node:timers/promises";
import { fromFdPromise, type ZipFile } from "yauzl";
import { parse } from "smol-toml";
import {
CodexSecurityError,
OutputDirectoryError,
OutputDirectoryNotEmptyError,
OutputInsideProtectedRootError,
PluginBootstrapError,
LocalPluginBootstrapError,
PluginPythonUnavailableError,
type ProtectedScanPathKind,
SandboxUnavailableError,
errorMessage,
abortReason,
} from "./errors.js";
import type { JsonObject } from "./config.js";
import { isRecord } from "./record.js";
import {
isWithin,
resolveTrustedExecutable,
type InspectedExecutable,
} from "./trusted-executable.js";
import {
isWindowsUnsafePathComponent,
windowsUnsafePathComponent,
} from "./windows-path.js";
const execFile = promisify(execFileCallback);
export type StartCodex = (
command: string,
args: readonly string[],
options: SpawnOptionsWithoutStdio & { stdio: ["pipe", "pipe", "pipe"] },
) => ChildProcessWithoutNullStreams;
export const MARKETPLACE_NAME = "codex-security-sdk";
export const PLUGIN_NAME = "codex-security";
const MARKETPLACE_MANIFEST = `${JSON.stringify(
{
name: MARKETPLACE_NAME,
interface: { displayName: "Codex Security SDK" },
plugins: [
{
name: PLUGIN_NAME,
source: { source: "local", path: `./plugins/${PLUGIN_NAME}` },
policy: { installation: "AVAILABLE", authentication: "ON_INSTALL" },
category: "Security",
},
],
},
null,
2,
)}\n`;
const MAX_ZIP_ENTRIES = 4_096;
const MAX_ZIP_CENTRAL_DIRECTORY = 16 * 1024 * 1024;
const MAX_ZIP_ENTRY_SIZE = 128 * 1024 * 1024;
const MAX_ZIP_EXPANDED_SIZE = 512 * 1024 * 1024;
const MODEL_UNSAFE_PATH = /[\u0000-\u001f\u007f-\u009f\u2028\u2029]/u;
const CREDENTIAL_LOCK_NAME = ".codex-security-scan.lock";
const CREDENTIAL_LOCK_DATABASE = ".codex-security-scan.sqlite3";
const CREDENTIAL_LOGOUT_MARKER = ".codex-security-logged-out";
const CREDENTIAL_LOCK_HEARTBEAT_MILLISECONDS = 5_000;
const CREDENTIAL_LOCK_POLL_MILLISECONDS = 25;
const INCOMPLETE_CREDENTIAL_LOCK_MILLISECONDS = 30_000;
const MAX_PROCESS_ID = 2_147_483_647;
const SANDBOX_PROBE_TIMEOUT_MILLISECONDS = 10_000;
const PLUGIN_HELPER_SECRET_ENVIRONMENT_VARIABLES = new Set([
"OPENAI_API_KEY",
"CODEX_API_KEY",
"OPENROUTER_API_KEY",
"FIREWORKS_API_KEY",
"CHEAPER_INFERENCE_API_KEY",
]);
const PREPARE_SCAN_ARTIFACT_RESTORER_PROGRAM = `
from pathlib import Path
from runpy import run_path
import json
import sys
module = run_path(sys.argv[1])
canonical_path, root_identity = module["scan_root_identity"](Path(sys.argv[2]))
print(json.dumps({
"canonicalPath": str(canonical_path),
"dev": str(root_identity[0]),
"ino": str(root_identity[1]),
}, ensure_ascii=False))
`.trim();
const RESTORE_SCAN_ARTIFACT_PROGRAM = `
from pathlib import Path
from runpy import run_path
import sys
module = run_path(sys.argv[1])
try:
module["write_scan_local_bytes"](
Path(sys.argv[2]),
sys.argv[3],
sys.stdin.buffer.read(),
expected_root_identity=(int(sys.argv[4]), int(sys.argv[5])),
)
except (module["ContractError"], OSError) as error:
raise SystemExit(str(error))
`.trim();
const WINDOWS_CREDENTIAL_ACL_COMPLETE_PREFIX = "CODEX_SECURITY_ACL_COMPLETE:";
const WINDOWS_CREDENTIAL_DESCENDANTS_CHANGED_EXIT_CODE = 2;
export interface PluginInstall {
pluginRoot: string;
marketplaceRoot: string;
installedRoot: string;
marketplaceName: typeof MARKETPLACE_NAME;
name: typeof PLUGIN_NAME;
version: string;
}
export interface CodexCommand {
command: string;
args?: readonly string[];
}
interface CodexCommandResult {
success: boolean;
exitCode: number | null;
stdout: string;
stderr: string;
}
export type ProcessEnvironment = Record<string, string | undefined>;
export interface PluginPythonOptions {
configuredPath?: string;
environment?: ProcessEnvironment;
homeDirectory?: string;
managedRuntimeRoots?: readonly string[];
protectedRoot?: string | readonly string[];
currentDirectory?: string;
signal?: AbortSignal;
}
export interface WorkbenchCommandOptions {
python: string;
pluginRoot: string;
environment: ProcessEnvironment;
stateDirectory?: string;
protectedRoot?: string | readonly string[];
currentDirectory?: string;
signal?: AbortSignal;
failureMessage?: string;
}
export interface ScanArtifactRestorer {
restore(relativePath: string, contents: Uint8Array): Promise<void>;
}
function environmentValue(
environment: ProcessEnvironment,
requested: string,
preserveWhitespace = false,
): string | undefined {
const exact = environment[requested];
const value = exact?.trim()
? exact
: Object.entries(environment).find(
([name, value]) => name.toUpperCase() === requested && value?.trim(),
)?.[1];
return preserveWhitespace ? value : value?.trim();
}
export function codexSecurityStateDirectory(
environment: ProcessEnvironment = process.env,
): string {
const configured = environmentValue(environment, "CODEX_SECURITY_STATE_DIR");
const path =
configured !== undefined
? resolve(expandHome(configured, environment))
: resolve(
expandHome(
environmentValue(environment, "CODEX_HOME", true) ??
join(homedir(), ".codex"),
environment,
),
"state",
"plugins",
"codex-security",
);
requireModelSafeOutputDir(path);
return path;
}
export function codexSecurityCredentialHome(
environment: ProcessEnvironment = process.env,
): string {
return join(codexSecurityStateDirectory(environment), "codex-home");
}
export async function prepareCodexSecurityCredentialHome(
environment: ProcessEnvironment = process.env,
validateLocation?: (path: string) => void,
): Promise<string> {
const path = codexSecurityCredentialHome(environment);
try {
try {
await mkdir(path, { recursive: true, mode: 0o700 });
} catch (error) {
if (nodeErrorCode(error) === "EEXIST") {
if ((await lstat(path).catch(() => null))?.isDirectory() === false) {
throw new OutputDirectoryError(
`Codex Security credential home is not a directory: ${path}`,
{ cause: error },
);
}
}
throw error;
}
if ((process.umask() & 0o700) !== 0) await chmod(path, 0o700);
const metadata = await lstat(path, { bigint: true });
if (!metadata.isDirectory()) {
throw new OutputDirectoryError(
`Codex Security credential home is not a directory: ${path}`,
);
}
const canonical = await realpath(path);
requireModelSafeOutputDir(canonical);
validateLocation?.(canonical);
await requireSecureCredentialHome(canonical, {
metadata,
});
return canonical;
} catch (error) {
if (error instanceof OutputDirectoryError) throw error;
throw new OutputDirectoryError(
`Unable to prepare the Codex Security credential home: ${path}`,
{ cause: error },
);
}
}
/**
* Re-verify the credential home before every use.
*
* Durable cross-process `(st_dev, st_ino)` pins are deferred: there is no
* workbench row for credential homes, and path+mode+trusted-ancestry checks on
* each use already close the cross-user rename/replace class. Lock acquisition
* still pins identity for the duration of a single lock session.
*/
export async function requireSecureCredentialHome(
path: string,
options: Parameters<typeof requirePrivateDirectory>[3] & {
metadata?: BigIntStats;
expectedDevice?: bigint;
expectedInode?: bigint;
validateWindowsAcl?: boolean;
} = {},
): Promise<BigIntStats> {
const platform = options.platform ?? process.platform;
let metadata = options.metadata;
if (metadata === undefined) {
try {
metadata = await lstat(path, { bigint: true });
} catch (error) {
throw new OutputDirectoryError(
`Unable to inspect the Codex Security credential home: ${path}`,
{ cause: error },
);
}
}
if (!metadata.isDirectory() || metadata.isSymbolicLink()) {
throw new OutputDirectoryError(
`Codex Security credential home is not a directory: ${path}`,
);
}
const canonical = await realpath(path);
requireModelSafeOutputDir(canonical);
const canonicalMetadata = await lstat(canonical, { bigint: true });
if (
canonicalMetadata.dev !== metadata.dev ||
canonicalMetadata.ino !== metadata.ino
) {
throw new OutputDirectoryError(
`Codex Security credential home was replaced: ${canonical}`,
);
}
metadata = canonicalMetadata;
if (!metadata.isDirectory()) {
throw new OutputDirectoryError(
`Codex Security credential home is not a directory: ${path}`,
);
}
if (
options.expectedDevice !== undefined &&
options.expectedInode !== undefined &&
(metadata.dev !== options.expectedDevice ||
metadata.ino !== options.expectedInode)
) {
throw new OutputDirectoryError(
`Codex Security credential home was replaced: ${canonical}`,
);
}
if (platform !== "win32" || options.validateWindowsAcl !== false) {
await requirePrivateCredentialHome(
{ mode: Number(metadata.mode), uid: Number(metadata.uid) },
canonical,
{
platform,
secureWindowsHome: options.secureWindowsHome,
},
);
}
if (platform !== "win32") {
await requireSecureOutputAncestry(canonical);
}
return metadata;
}
export async function requirePrivateCredentialHome(
metadata: Pick<Stats, "mode" | "uid">,
path: string,
options: Parameters<typeof requirePrivateDirectory>[3] = {},
): Promise<void> {
await requirePrivateDirectory(metadata, path, "credential home", options);
}
export async function preparePolicyOutputDirectory(
path: string,
options: Parameters<typeof requirePrivateDirectory>[3] = {},
): Promise<void> {
const metadata = await lstat(path);
if ((options.platform ?? process.platform) !== "win32") {
requireOutputDirectoryOwnership(metadata, path);
return;
}
await requirePrivateDirectory(
metadata,
path,
"policy output directory",
options,
);
}
async function requirePrivateDirectory(
metadata: Pick<Stats, "mode" | "uid">,
path: string,
description: string,
options: {
platform?: NodeJS.Platform;
secureWindowsHome?: (path: string) => Promise<void>;
},
): Promise<void> {
if ((options.platform ?? process.platform) !== "win32") {
requirePrivateOutputDirectory(metadata, path);
return;
}
try {
await (options.secureWindowsHome ?? secureWindowsCredentialHome)(path);
} catch (error) {
const detail = windowsCredentialAclFailure(error);
throw new OutputDirectoryError(
`Unable to create a private Windows ${description}: ${path}${detail}`,
{ cause: error },
);
}
}
function windowsCredentialAclFailure(error: unknown): string {
const stderr =
typeof error === "object" && error !== null && "stderr" in error
? error.stderr
: undefined;
const detail =
typeof stderr === "string" && stderr.trim() !== ""
? stderr
: errorMessage(error);
const normalized = errorMessage(detail).replace(/\s+/gu, " ").trim();
return normalized === "" ? "" : `. ${normalized}`;
}
const WINDOWS_SYSTEM_SID = "S-1-5-18";
const WINDOWS_ADMINISTRATORS_SID = "S-1-5-32-544";
const WINDOWS_TRUSTED_INSTALLER_SID =
"S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464";
const WINDOWS_LOCAL_SERVICE_SID = "S-1-5-19";
const WINDOWS_NETWORK_SERVICE_SID = "S-1-5-20";
const WINDOWS_EVERYONE_SID = "S-1-1-0";
const WINDOWS_AUTHENTICATED_USERS_SID = "S-1-5-11";
const WINDOWS_USERS_SID = "S-1-5-32-545";
const WINDOWS_CREATOR_OWNER_SID = "S-1-3-0";
const WINDOWS_CREATOR_GROUP_SID = "S-1-3-1";
const WINDOWS_OWNER_RIGHTS_SID = "S-1-3-4";
const WINDOWS_ALL_APPLICATION_PACKAGES_SID = "S-1-15-2-1";
const WINDOWS_PRINCIPAL_ALIASES: Readonly<Record<string, string>> = {
SY: WINDOWS_SYSTEM_SID,
BA: WINDOWS_ADMINISTRATORS_SID,
LS: WINDOWS_LOCAL_SERVICE_SID,
NS: WINDOWS_NETWORK_SERVICE_SID,
WD: WINDOWS_EVERYONE_SID,
AU: WINDOWS_AUTHENTICATED_USERS_SID,
BU: WINDOWS_USERS_SID,
CO: WINDOWS_CREATOR_OWNER_SID,
CG: WINDOWS_CREATOR_GROUP_SID,
OW: WINDOWS_OWNER_RIGHTS_SID,
AC: WINDOWS_ALL_APPLICATION_PACKAGES_SID,
AN: "S-1-5-7",
IU: "S-1-5-4",
NU: "S-1-5-2",
SU: "S-1-5-6",
RC: "S-1-5-12",
ED: "S-1-5-9",
BG: "S-1-5-32-546",
PU: "S-1-5-32-547",
AO: "S-1-5-32-548",
SO: "S-1-5-32-549",
PO: "S-1-5-32-550",
BO: "S-1-5-32-551",
RE: "S-1-5-32-552",
RU: "S-1-5-32-554",
RD: "S-1-5-32-555",
NO: "S-1-5-32-556",
MU: "S-1-5-32-558",
LU: "S-1-5-32-559",
IS: "S-1-5-32-568",
CY: "S-1-5-32-569",
ER: "S-1-5-32-573",
CD: "S-1-5-32-574",
RA: "S-1-5-32-575",
ES: "S-1-5-32-576",
HA: "S-1-5-32-578",
AA: "S-1-5-32-579",
};
const WINDOWS_SID = /^S-1-(?:\d+-)*\d+$/u;
const WINDOWS_GUID =
/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu;
const WINDOWS_SDDL_SID = "(?:S-1-(?:\\d+-)*\\d+|[A-Z]{2})";
const WINDOWS_SECURITY_DESCRIPTOR = new RegExp(
`^O:(${WINDOWS_SDDL_SID})(?:G:${WINDOWS_SDDL_SID})?D:([A-Z_]*)(.*)$`,
"u",
);
export interface WindowsCredentialAcl {
owner: string;
protected: boolean;
grantsCurrentUserAccess: boolean;
untrustedPrincipals: string[];
deniedPrincipals: string[];
}
class UntrustedWindowsCredentialOwnerError extends Error {
public constructor(owner: string) {
super(`Windows credential ACL owner is not a trusted principal: ${owner}`);
}
}
class RepairableWindowsCredentialAclError extends Error {
public constructor(cause: unknown) {
super("Windows credential ACL requires repair", { cause });
}
}
class RepairableWindowsCredentialOwnerError extends Error {
public constructor(cause: UntrustedWindowsCredentialOwnerError) {
super(cause.message, { cause });
}
}
class WindowsCredentialDescendantsChangedError extends Error {}
/** Inspect a Windows DACL without translating locale-specific account names. */
export function inspectWindowsCredentialAcl(
descriptor: string,
currentUserSid: string,
options: {
resolvedAliases?: Readonly<Record<string, string>>;
scope?: "directory" | "file" | "ancestor";
} = {},
): WindowsCredentialAcl {
if (!WINDOWS_SID.test(currentUserSid)) {
throw new Error("Unable to identify the current Windows user SID");
}
const match = WINDOWS_SECURITY_DESCRIPTOR.exec(descriptor.trim());
if (match === null) {
throw new Error("Windows credential ACL has no owner or DACL");
}
const principalAliases: Readonly<Record<string, string>> = {
...WINDOWS_PRINCIPAL_ALIASES,
...options.resolvedAliases,
};
const trustedPrincipals = new Set([
currentUserSid,
WINDOWS_SYSTEM_SID,
WINDOWS_ADMINISTRATORS_SID,
principalAliases["LA"] ?? "LA",
]);
if (options.scope === "ancestor") {
trustedPrincipals.add(WINDOWS_TRUSTED_INSTALLER_SID);
}
const normalizePrincipal = (principal: string): string =>
principalAliases[principal] ?? principal;
const trustedPrincipal = (principal: string): boolean =>
trustedPrincipals.has(principal);
const owner = normalizePrincipal(match[1]!);
if (!trustedPrincipal(owner)) {
throw new UntrustedWindowsCredentialOwnerError(owner);
}
const flags = match[2]!;
if (flags.includes("NO_ACCESS_CONTROL")) {
throw new Error("Windows credential ACL grants unrestricted access");
}
let remaining = match[3]!;
let grantsCurrentDirectoryAccess = false;
let grantsCurrentFileAccess = false;
let grantsCurrentContainerAccess = false;
let hasAccessRules = false;
const untrustedPrincipals = new Set<string>();
const deniedPrincipals = new Set<string>();
while (remaining.startsWith("(")) {
const { rule, rest } = windowsSecurityDescriptorRule(remaining);
const fields = rule.split(";");
const callback = ["XA", "XD", "ZA"].includes(fields[0]!);
if ((callback && fields.length < 7) || (!callback && fields.length !== 6)) {
throw new Error("Windows credential ACL has a malformed access rule");
}
const [
type,
inheritance,
rights,
objectGuid,
inheritObjectGuid,
rawPrincipal,
] = fields;
if (!["A", "OA", "D", "OD", "XA", "XD", "ZA"].includes(type!)) {
throw new Error("Windows credential ACL has an unsupported access rule");
}
if (rawPrincipal === "" || rights === "") {
throw new Error("Windows credential ACL has an incomplete access rule");
}
const objectRule = type === "OA" || type === "OD" || type === "ZA";
for (const guid of [objectGuid!, inheritObjectGuid!]) {
if (guid !== "" && (!objectRule || !WINDOWS_GUID.test(guid))) {
throw new Error("Windows credential ACL has a malformed object rule");
}
}
const inheritanceFlags = windowsAceFlags(inheritance!);
hasAccessRules = true;
const principal = normalizePrincipal(rawPrincipal!);
if (type === "A" || type === "OA" || type === "XA" || type === "ZA") {
if (!trustedPrincipal(principal)) {
if (
options.scope !== "ancestor" ||
windowsAceAllowsAncestorReplacement(rights!, inheritanceFlags)
) {
untrustedPrincipals.add(principal);
}
} else if (
!callback &&
objectGuid === "" &&
inheritObjectGuid === "" &&
principal === currentUserSid &&
windowsAceGrantsFullControl(rights!)
) {
if (!inheritanceFlags.has("IO")) {
grantsCurrentDirectoryAccess = true;
}
if (inheritanceFlags.has("OI") && !inheritanceFlags.has("NP")) {
grantsCurrentFileAccess = true;
}
if (inheritanceFlags.has("CI") && !inheritanceFlags.has("NP")) {
grantsCurrentContainerAccess = true;
}
}
} else {
deniedPrincipals.add(principal);
}
remaining = rest;
}
if (!hasAccessRules || (remaining !== "" && !remaining.startsWith("S:"))) {
throw new Error("Windows credential ACL has an invalid access-rule list");
}
return {
owner,
protected: flags.includes("P"),
grantsCurrentUserAccess:
grantsCurrentDirectoryAccess &&
(options.scope === "file" ||
(grantsCurrentFileAccess && grantsCurrentContainerAccess)) &&
deniedPrincipals.size === 0,
untrustedPrincipals: [...untrustedPrincipals],
deniedPrincipals: [...deniedPrincipals],
};
}
function windowsSecurityDescriptorRule(value: string) {
let depth = 0;
let quoted = false;
let escaped = false;
for (let index = 0; index < value.length; index += 1) {
const character = value[index]!;
if (quoted) {
if (!escaped && character === '"') quoted = false;
escaped = character === "\\" && !escaped;
continue;
}
if (character === '"') {
quoted = true;
} else if (character === "(") {
depth += 1;
} else if (character === ")") {
depth -= 1;
if (depth === 0) {
return { rule: value.slice(1, index), rest: value.slice(index + 1) };
}
}
}
throw new Error("Windows credential ACL has a malformed rule");
}
function windowsAceFlags(value: string): ReadonlySet<string> {
if (value.length % 2 !== 0) {
throw new Error("Windows credential ACL has malformed inheritance flags");
}
const flags = new Set<string>();
for (let offset = 0; offset < value.length; offset += 2) {
const flag = value.slice(offset, offset + 2);
if (!["OI", "CI", "NP", "IO", "ID"].includes(flag)) {
throw new Error(
"Windows credential ACL has unsupported inheritance flags",
);
}
flags.add(flag);
}
return flags;
}
function windowsAceGrantsFullControl(rights: string): boolean {
if (rights === "FA" || rights === "GA") return true;
if (!/^0x[\da-f]+$/iu.test(rights)) return false;
const mask = BigInt(rights);
return (mask & 0x1f01ffn) === 0x1f01ffn || (mask & 0x10000000n) !== 0n;
}
function windowsAceAllowsAncestorReplacement(
rights: string,
inheritanceFlags: ReadonlySet<string>,
): boolean {
if (inheritanceFlags.has("IO")) return false;
if (/^0x[\da-f]+$/iu.test(rights)) {
return (BigInt(rights) & 0x100d0040n) !== 0n;
}
// Rights tokens stay aligned to pairs of UTF-16 code units.
for (const [right] of rights.matchAll(/[\s\S]{2}/g)) {
if (["FA", "GA", "FW", "GW", "SD", "WD", "WO", "DC", "DT"].includes(right))
return true;
}
return false;
}
export async function streamWindowsCredentialAclDescriptors(
command: string,
args: readonly string[],
inspectDescriptor: (descriptor: string) => Promise<void>,
options: { environment?: NodeJS.ProcessEnv } = {},
): Promise<void> {
const child = spawn(command, [...args], {
env: options.environment,
stdio: ["ignore", "pipe", "pipe"],
windowsHide: true,
});
let stderr = "";
child.stderr.setEncoding("utf8");
child.stderr.on("data", (chunk: string) => {
stderr += chunk;
});
let descendantsChanged = false;
const completion = new Promise<void>((resolve, reject) => {
child.once("error", reject);
child.once("close", (code, signal) => {
if (code === 0) {
resolve();
return;
}
if (code === WINDOWS_CREDENTIAL_DESCENDANTS_CHANGED_EXIT_CODE) {
descendantsChanged = true;
resolve();
return;
}
const reason = signal === null ? `exit code ${code}` : `signal ${signal}`;
reject(
Object.assign(
new Error(`Windows credential ACL inspection failed with ${reason}`),
{ code, signal, stderr },
),
);
});
});
try {
await Promise.all([
completion,
(async () => {
// Consume chunks directly: readline can resume its queued-line
// iterator after EOF and throw instead of draining the last lines.
child.stdout.setEncoding("utf8");
let pending = "";
for await (const chunk of child.stdout) {
const lines = (pending + chunk).split(/[\r\n]/u);
pending = lines.pop()!;
for (const descriptor of lines) {
if (descriptor === "") continue;
await inspectDescriptor(descriptor);
}
}
if (pending !== "") {
await inspectDescriptor(pending);
}
})(),
]);
} catch (error) {
if (child.exitCode === null && child.signalCode === null) child.kill();
throw error;
}
if (descendantsChanged) {
// Finish descriptor callbacks before allowing another snapshot attempt.
throw new WindowsCredentialDescendantsChangedError(
"Windows credential descendants changed during ACL inspection",
);
}
}
export async function inspectWindowsCredentialAclSnapshot(
path: string,
currentUserSid: string,
options: {
command: string;
args: readonly string[];
environment?: NodeJS.ProcessEnv;
resolvedAliases?: Readonly<Record<string, string>>;
resolveDescriptorAliases?: (descriptor: string) => Promise<void>;
},
): Promise<{
home: WindowsCredentialAcl;
descendantsArePrivate: boolean;
}> {
const ancestors: string[] = [];
for (let ancestor = dirname(path); ; ancestor = dirname(ancestor)) {
ancestors.push(ancestor);
if (ancestor === dirname(ancestor)) break;
}
for (let attempt = 0; attempt < 3; attempt += 1) {
let home: WindowsCredentialAcl | undefined;
let descendantsArePrivate = true;
let inspected = 0;
let completed = false;
try {
await streamWindowsCredentialAclDescriptors(
options.command,
options.args,
async (descriptor) => {
if (completed) {
throw new Error(
"Windows credential ACL inspection continued after completion",
);
}
if (descriptor.startsWith(WINDOWS_CREDENTIAL_ACL_COMPLETE_PREFIX)) {
if (
descriptor !==
`${WINDOWS_CREDENTIAL_ACL_COMPLETE_PREFIX}${inspected}`
) {
throw new Error(
"Windows credential descendants could not be verified",
);
}
completed = true;
return;
}
const index = inspected;
inspected += 1;
await options.resolveDescriptorAliases?.(descriptor);
if (index < ancestors.length) {
const ancestorPath = ancestors[index]!;
try {
const ancestor = inspectWindowsCredentialAcl(
descriptor,
currentUserSid,
{
resolvedAliases: options.resolvedAliases,
scope: "ancestor",
},
);
if (ancestor.untrustedPrincipals.length !== 0) {
throw new Error(
"Windows credential-home ancestor allows another identity to replace the directory",
);
}
} catch (error) {
const guidance =
ancestorPath === dirname(ancestorPath)
? "This volume root is unsupported. Choose a location on a volume with trusted ancestry; another directory on the same volume will not resolve this."
: "Choose a location outside this ancestor with trusted ownership and permissions.";
throw new Error(
`Windows private-directory ancestor could not be trusted: ${ancestorPath}. ${errorMessage(error)}. ${guidance}`,
{ cause: error },
);
}
return;
}
if (index === ancestors.length) {
try {
home = inspectWindowsCredentialAcl(descriptor, currentUserSid, {
resolvedAliases: options.resolvedAliases,
});
} catch (error) {
if (error instanceof UntrustedWindowsCredentialOwnerError) {
throw new RepairableWindowsCredentialOwnerError(error);
}
throw new RepairableWindowsCredentialAclError(error);
}
return;
}
const descendant = inspectWindowsCredentialAcl(
descriptor,
currentUserSid,
{
resolvedAliases: options.resolvedAliases,
scope: "file",
},
);
if (
!descendant.grantsCurrentUserAccess ||
descendant.untrustedPrincipals.length !== 0
) {
descendantsArePrivate = false;
}
},
{ environment: options.environment },
);
} catch (error) {
if (error instanceof WindowsCredentialDescendantsChangedError) continue;
throw error;
}
if (inspected <= ancestors.length) {
throw new Error("Windows credential-home ancestry could not be verified");
}
if (!completed) {
throw new Error("Windows credential descendants could not be verified");
}
if (home === undefined) {
throw new Error("Windows credential ACL could not be verified");
}
return { home, descendantsArePrivate };
}
throw new Error("Windows credential descendants could not be verified");
}
async function secureWindowsCredentialHome(path: string): Promise<void> {
const systemRoot = process.env["SystemRoot"] ?? "C:\\Windows";
const systemDirectory = join(systemRoot, "System32");
const powershell = join(
systemDirectory,
"WindowsPowerShell",
"v1.0",
"powershell.exe",
);
const inheritedEnvironment = Object.fromEntries(
Object.entries(process.env).filter(
([name]) => name.toUpperCase() !== "PSMODULEPATH",
),
);
const processOptions = {
env: {
...inheritedEnvironment,
CODEX_SECURITY_CREDENTIAL_ACL_PATH: path,
PSModulePath: join(
systemDirectory,
"WindowsPowerShell",
"v1.0",
"Modules",
),
},
encoding: "utf8" as const,
windowsHide: true,
maxBuffer: 1024 * 1024,
};
const identity = await execFile(
join(systemDirectory, "whoami.exe"),
["/user", "/fo", "csv", "/nh"],
processOptions,
);
const sid = /^"(?:[^"]|"")*","(S-1-(?:\d+-)*\d+)"$/u.exec(
identity.stdout.trim(),
)?.[1];
if (sid === undefined) {
throw new Error("Unable to identify the current Windows user SID");
}
// Signed built-in cmdlets remain available under ConstrainedLanguage;
// arbitrary .NET constructors, static methods, and SID translation do not.
// Enumerate and count ACLs in the same process: parallel startup can create
// or remove private cache and lock files while this traversal is running.
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 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.
// 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 }",
" 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 {",
// 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 }",
" }",
"}",
"$path = $env:CODEX_SECURITY_CREDENTIAL_ACL_PATH",
"while ($true) { $parent = Microsoft.PowerShell.Management\\Split-Path -Path $path -Parent; if (-not $parent -or $parent -eq $path) { break }; Write-CredentialAcl $parent; $path = $parent }",
"Write-CredentialAcl $env:CODEX_SECURITY_CREDENTIAL_ACL_PATH",
"Read-CredentialDescendants $env:CODEX_SECURITY_CREDENTIAL_ACL_PATH",
`"${WINDOWS_CREDENTIAL_ACL_COMPLETE_PREFIX}$script:descriptorCount"`,
].join("\n");
const resolvePrincipalScript = [
"$ErrorActionPreference = 'Stop'",