diff --git a/apps/computer/local-daemon/README.md b/apps/computer/local-daemon/README.md index 0121835ac..aeeac45f2 100644 --- a/apps/computer/local-daemon/README.md +++ b/apps/computer/local-daemon/README.md @@ -588,15 +588,20 @@ the current SID and ACL, not POSIX permission bits. Writing a separate credentia does not change the permissions of an existing parent directory. The installer and the Daemon refuse a private path when another account can -replace one of its parent directories. One exception applies: the Codex Windows -sandbox may hold that right on a parent, such as AppData. The sandbox acts +replace one of its parent directories, naming the offending ancestor path and +SID. Ancestors trust the current user, `SYSTEM`, `BUILTIN\Administrators`, +`TrustedInstaller`, built-in Administrator/Domain/Enterprise Admin SIDs +(`S-1-5-21-*-*-*-500|512|519`), and direct individual/domain/Entra members of +local `BUILTIN\Administrators` (excluding broad well-known groups). One +additional exception applies on ancestor access rules: the Codex Windows +sandbox may hold replace rights on a parent, such as AppData. The sandbox acts through the `CodexSandboxUsers` group and the capability SIDs in -`%USERPROFILE%\.codex\cap_sid`. A sandboxed Codex command can therefore replace -such a parent; Linger accepts this so it installs beside Codex. Private paths -themselves still grant access only to the current user and SYSTEM. Their -owner is the current user or, when that user is an administrator, -Administrators, which owns what an elevated process (Run as administrator, -the built-in Administrator) creates. +`%USERPROFILE%\.codex\cap_sid` (or `%CODEX_HOME%\cap_sid`). A sandboxed Codex +command can therefore replace such a parent; Linger accepts this so it installs +beside Codex. Private paths themselves still grant access only to the current +user and SYSTEM. Their owner is the current user or, when that user is an +administrator, Administrators, which owns what an elevated process (Run as +administrator, the built-in Administrator) creates. Process recovery uses the creation time and a held process handle, so a reused process ID is never mistaken for the original. Ordinary tasks are held by a Job diff --git a/apps/computer/local-daemon/internal/platform/privatefs/privatefs_windows.go b/apps/computer/local-daemon/internal/platform/privatefs/privatefs_windows.go index a46715d03..d4cadcf64 100644 --- a/apps/computer/local-daemon/internal/platform/privatefs/privatefs_windows.go +++ b/apps/computer/local-daemon/internal/platform/privatefs/privatefs_windows.go @@ -69,8 +69,16 @@ func pinParents(path string) (func(), error) { parent = next } handles := []windows.Handle{} - // One walk reads the Codex sandbox principals at most once, and only when - // an ancestor grants replace rights to an otherwise untrusted SID. + // One walk queries local Administrators members and Codex sandbox + // principals at most once, and only when an ancestor names an otherwise + // untrusted SID. + var adminMembers map[string]bool + adminMemberSIDs := func() map[string]bool { + if adminMembers == nil { + adminMembers = localAdminMemberSIDs() + } + return adminMembers + } var sandbox map[string]bool sandboxSIDs := func() map[string]bool { if sandbox == nil { @@ -102,15 +110,15 @@ func pinParents(path string) (func(), error) { } if info.FileAttributes&windows.FILE_ATTRIBUTE_REPARSE_POINT != 0 || info.FileAttributes&windows.FILE_ATTRIBUTE_DIRECTORY == 0 { closeAll() - return nil, errors.New("private path has an unsafe ancestor") + return nil, fmt.Errorf("private path has an unsafe ancestor (%s)", paths[i]) } sd, err := windows.GetSecurityInfo(handle, windows.SE_FILE_OBJECT, windows.OWNER_SECURITY_INFORMATION|windows.DACL_SECURITY_INFORMATION) if err == nil { - err = validateAncestorDescriptor(sd, filepath.Dir(paths[i]) == paths[i], sandboxSIDs) + err = validateAncestorDescriptor(sd, filepath.Dir(paths[i]) == paths[i], adminMemberSIDs, sandboxSIDs) } if err != nil { closeAll() - return nil, fmt.Errorf("unsafe private path ancestor: %w", err) + return nil, fmt.Errorf("unsafe private path ancestor %s: %w", paths[i], err) } } return closeAll, nil @@ -233,19 +241,33 @@ func validateDescriptor(sd *windows.SECURITY_DESCRIPTOR, ownerOnly bool) error { // Ancestors need not be private, but another account must not be able to // replace an existing component. The default C:\ ACL allows creating new // directories; that does not grant removal or replacement of an owned child. -func validateAncestorDescriptor(sd *windows.SECURITY_DESCRIPTOR, volumeRoot bool, sandboxSIDs func() map[string]bool) error { +func validateAncestorDescriptor( + sd *windows.SECURITY_DESCRIPTOR, + volumeRoot bool, + adminMemberSIDs func() map[string]bool, + sandboxSIDs func() map[string]bool, +) error { user, err := CurrentSID() if err != nil { return err } - trusted := func(sid *windows.SID) bool { - return sid != nil && (windows.EqualSid(sid, user) || sid.IsWellKnown(windows.WinLocalSystemSid) || sid.IsWellKnown(windows.WinBuiltinAdministratorsSid) || - sid.String() == "S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464") // Windows TrustedInstaller + userSID := user.String() + trustedStatic := func(sid *windows.SID, allowRuleOnly bool) bool { + return sid != nil && isTrustedAncestorSID(sid.String(), userSID, nil, nil, allowRuleOnly) } owner, _, err := sd.Owner() - if err != nil || !trusted(owner) { + if err != nil || owner == nil { return errors.New("ancestor is owned by another user") } + if !trustedStatic(owner, false) { + var members map[string]bool + if adminMemberSIDs != nil { + members = adminMemberSIDs() + } + if !isTrustedAncestorSID(owner.String(), userSID, members, nil, false) { + return fmt.Errorf("ancestor is owned by another user (%s)", owner.String()) + } + } dacl, _, err := sd.DACL() if err != nil || dacl == nil { return errors.New("ancestor has no access restriction") @@ -270,27 +292,114 @@ func validateAncestorDescriptor(sd *windows.SECURITY_DESCRIPTOR, volumeRoot bool if volumeRoot { replaceMask &^= windows.DELETE } - if trusted(sid) || ace.Mask&replaceMask == 0 { + if ace.Mask&replaceMask == 0 || trustedStatic(sid, true) { + continue + } + sidValue := sid.String() + var members map[string]bool + if adminMemberSIDs != nil { + members = adminMemberSIDs() + } + if isTrustedAncestorSID(sidValue, userSID, members, nil, true) { continue } - if !sandboxSIDs()[sid.String()] { - return fmt.Errorf("ancestor permits another user (%s) to replace private paths", sid.String()) + var sandbox map[string]bool + if sandboxSIDs != nil { + sandbox = sandboxSIDs() + } + if !isTrustedAncestorSID(sidValue, userSID, nil, sandbox, true) { + return fmt.Errorf("ancestor permits another user (%s) to replace private paths", sidValue) } } return nil } +var ( + modNetapi32 = windows.NewLazySystemDLL("netapi32.dll") + procNetLocalGroupGetMembers = modNetapi32.NewProc("NetLocalGroupGetMembers") +) + +type localGroupMembersInfo0 struct { + SID *windows.SID +} + +// localAdminMemberSIDs returns direct member SIDs of the local +// BUILTIN\Administrators group (filtered to eligible individual/domain/Entra +// SIDs). Failures return an empty set so ancestor validation fails closed. +func localAdminMemberSIDs() map[string]bool { + sids := map[string]bool{} + adminGroup, err := windows.CreateWellKnownSid(windows.WinBuiltinAdministratorsSid) + if err != nil { + return sids + } + groupName, _, _, err := adminGroup.LookupAccount("") + if err != nil || groupName == "" { + return sids + } + groupNamePtr, err := windows.UTF16PtrFromString(groupName) + if err != nil { + return sids + } + const ( + maxPreferredLength = ^uint32(0) + errorMoreData = 234 + maxPages = 16 + ) + var resumeHandle uintptr + for page := 0; page < maxPages; page++ { + var buf *byte + var entriesRead, totalEntries uint32 + r1, _, _ := procNetLocalGroupGetMembers.Call( + 0, + uintptr(unsafe.Pointer(groupNamePtr)), + 0, + uintptr(unsafe.Pointer(&buf)), + uintptr(maxPreferredLength), + uintptr(unsafe.Pointer(&entriesRead)), + uintptr(unsafe.Pointer(&totalEntries)), + uintptr(unsafe.Pointer(&resumeHandle)), + ) + if buf != nil { + if r1 == 0 || r1 == errorMoreData { + entries := unsafe.Slice((*localGroupMembersInfo0)(unsafe.Pointer(buf)), int(entriesRead)) + for _, entry := range entries { + if entry.SID == nil { + continue + } + value := entry.SID.String() + if isEligibleAdminMemberSID(value) { + sids[value] = true + } + } + } + _ = windows.NetApiBufferFree(buf) + } + if r1 != errorMoreData { + break + } + } + return sids +} + // codexSandboxSIDs returns the principals the Codex Windows sandbox grants on // its writable roots: the sandbox users group and the capability SIDs Codex -// records in its default home. Linger accepts that a sandboxed Codex command -// may replace an ancestor such as AppData; private paths themselves stay -// owner-only. +// records in its default home or active CODEX_HOME. Linger accepts that a +// sandboxed Codex command may replace an ancestor such as AppData; private +// paths themselves stay owner-only. func codexSandboxSIDs() map[string]bool { sids := map[string]bool{} - profile, err := windows.GetCurrentProcessToken().GetUserProfileDirectory() - if err == nil { - if data, err := os.ReadFile(filepath.Join(profile, ".codex", "cap_sid")); err == nil { - sids = parseCodexCapSIDs(data) + var capFiles []string + if profile, err := windows.GetCurrentProcessToken().GetUserProfileDirectory(); err == nil && profile != "" { + capFiles = append(capFiles, filepath.Join(profile, ".codex", "cap_sid")) + } + if codexHome := strings.TrimSpace(os.Getenv("CODEX_HOME")); codexHome != "" && filepath.IsAbs(codexHome) { + capFiles = append(capFiles, filepath.Join(codexHome, "cap_sid")) + } + for _, capFile := range capFiles { + if data, err := os.ReadFile(capFile); err == nil { + for sid := range parseCodexCapSIDs(data) { + sids[sid] = true + } } } if sid, _, _, err := windows.LookupSID("", "CodexSandboxUsers"); err == nil { diff --git a/apps/computer/local-daemon/internal/platform/privatefs/privatefs_windows_test.go b/apps/computer/local-daemon/internal/platform/privatefs/privatefs_windows_test.go index df006248b..d0326e003 100644 --- a/apps/computer/local-daemon/internal/platform/privatefs/privatefs_windows_test.go +++ b/apps/computer/local-daemon/internal/platform/privatefs/privatefs_windows_test.go @@ -35,7 +35,7 @@ func TestWindowsAncestorDeleteRightsRespectVolumeRoot(t *testing.T) { if err != nil { t.Fatal(err) } - err = validateAncestorDescriptor(sd, test.volumeRoot, func() map[string]bool { return nil }) + err = validateAncestorDescriptor(sd, test.volumeRoot, nil, func() map[string]bool { return nil }) if (err == nil) != test.allowed { t.Fatalf("allowed = %v, error = %v", test.allowed, err) } @@ -75,30 +75,48 @@ func TestWindowsPrivateOwnerIsUserOrAdministrators(t *testing.T) { } } -func TestWindowsAncestorTrustsOnlyCodexSandboxSIDs(t *testing.T) { +func TestWindowsAncestorTrustsBuiltinAdminAndAdminMembersAndCodexSandboxSIDs(t *testing.T) { sid, err := CurrentSID() if err != nil { t.Fatal(err) } - const sandbox = "S-1-5-21-1158770811-2547671072-1736395728-810166692" + const ( + builtinAdmin = "S-1-5-21-3623811015-3361044348-30300820-500" + domainAdmins = "S-1-5-21-3623811015-3361044348-30300820-512" + localAdmin = "S-1-5-21-3623811015-3361044348-30300820-1006" + sandbox = "S-1-5-21-1158770811-2547671072-1736395728-810166692" + nonAdmin = "S-1-5-21-1-2-3-1007" + ) + adminMembers := func() map[string]bool { return map[string]bool{localAdmin: true, "S-1-1-0": true} } sandboxSIDs := func() map[string]bool { return map[string]bool{sandbox: true} } for _, test := range []struct { name string + owner string grantee string allowed bool }{ - {"Codex sandbox modify", sandbox, true}, - {"other account modify", "S-1-5-21-1-2-3-4", false}, + {"built-in Administrator RID 500 ACE", sid.String(), builtinAdmin, true}, + {"built-in Administrator RID 500 owner", builtinAdmin, sid.String(), true}, + {"Domain Admins RID 512 ACE", sid.String(), domainAdmins, true}, + {"direct local admin member ACE", sid.String(), localAdmin, true}, + {"direct local admin member owner", localAdmin, sid.String(), true}, + {"Codex sandbox modify", sid.String(), sandbox, true}, + {"other non-admin account modify", sid.String(), nonAdmin, false}, + {"other non-admin account owner", nonAdmin, sid.String(), false}, + {"Everyone modify rejected", sid.String(), "WD", false}, } { t.Run(test.name, func(t *testing.T) { - sd, err := windows.SecurityDescriptorFromString("O:" + sid.String() + "D:P(A;;FA;;;" + sid.String() + ")(A;OICI;0x1301ff;;;" + test.grantee + ")") + sd, err := windows.SecurityDescriptorFromString("O:" + test.owner + "D:P(A;;FA;;;" + sid.String() + ")(A;OICI;0x1301ff;;;" + test.grantee + ")") if err != nil { t.Fatal(err) } - err = validateAncestorDescriptor(sd, false, sandboxSIDs) + err = validateAncestorDescriptor(sd, false, adminMembers, sandboxSIDs) if (err == nil) != test.allowed { t.Fatalf("allowed = %v, error = %v", test.allowed, err) } + if !test.allowed && test.grantee == nonAdmin && !strings.Contains(err.Error(), nonAdmin) { + t.Fatalf("error = %v, want offending SID %s", err, nonAdmin) + } }) } } @@ -249,9 +267,13 @@ func TestWindowsPrivateWriteRejectsReplaceableAncestor(t *testing.T) { if err := windows.SetNamedSecurityInfo(root, windows.SE_FILE_OBJECT, windows.DACL_SECURITY_INFORMATION|windows.PROTECTED_DACL_SECURITY_INFORMATION, nil, nil, acl, nil); err != nil { t.Fatal(err) } - if err := WriteFile(filepath.Join(private, "secret"), []byte("private"), true); err == nil { + err = WriteFile(filepath.Join(private, "secret"), []byte("private"), true) + if err == nil { t.Fatal("credential published through replaceable ancestor") } + if !strings.Contains(err.Error(), root) || !strings.Contains(err.Error(), "S-1-1-0") { + t.Fatalf("error = %v, want offending ancestor path %q and SID S-1-1-0", err, root) + } } func TestWindowsOwnerOnlyDescriptor(t *testing.T) { diff --git a/apps/computer/local-daemon/internal/platform/privatefs/trusted_sid.go b/apps/computer/local-daemon/internal/platform/privatefs/trusted_sid.go new file mode 100644 index 000000000..aacbf0b9f --- /dev/null +++ b/apps/computer/local-daemon/internal/platform/privatefs/trusted_sid.go @@ -0,0 +1,115 @@ +package privatefs + +import ( + "strconv" + "strings" +) + +const ( + localSystemSID = "S-1-5-18" + builtinAdminsSID = "S-1-5-32-544" + creatorOwnerSID = "S-1-3-0" + ownerRightsSID = "S-1-3-4" + trustedInstallerSID = "S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464" + ridBuiltinAdmin = 500 + ridDomainAdmins = 512 + ridEnterpriseAdmins = 519 + minDynamicAccountRID = 1000 +) + +func parseCanonicalUint32(token string) (uint32, bool) { + if token == "" { + return 0, false + } + if len(token) > 1 && token[0] == '0' { + return 0, false + } + value, err := strconv.ParseUint(token, 10, 32) + if err != nil { + return 0, false + } + return uint32(value), true +} + +// isWindowsBuiltinAdminSID reports whether value is a canonical Windows domain +// or local SAM built-in administrator principal: built-in Administrator +// (RID 500), Domain Admins (RID 512), or Enterprise Admins (RID 519). +func isWindowsBuiltinAdminSID(value string) bool { + parts := strings.Split(value, "-") + if len(parts) != 8 || strings.Join(parts[:4], "-") != "S-1-5-21" { + return false + } + for _, part := range parts[4:7] { + if _, ok := parseCanonicalUint32(part); !ok { + return false + } + } + rid, ok := parseCanonicalUint32(parts[7]) + if !ok { + return false + } + return rid == ridBuiltinAdmin || rid == ridDomainAdmins || rid == ridEnterpriseAdmins +} + +// isEligibleAdminMemberSID reports whether value has the shape of an +// individual or domain/Entra account SID that may be trusted on an ancestor +// when currently listed as a direct member of BUILTIN\Administrators. Broad +// well-known groups (Everyone, Authenticated Users, Users, Domain Users, +// Guest) are always excluded. +func isEligibleAdminMemberSID(value string) bool { + parts := strings.Split(value, "-") + if len(parts) != 8 { + return false + } + prefix := strings.Join(parts[:4], "-") + switch prefix { + case "S-1-5-21": + for _, part := range parts[4:7] { + if _, ok := parseCanonicalUint32(part); !ok { + return false + } + } + rid, ok := parseCanonicalUint32(parts[7]) + return ok && rid >= minDynamicAccountRID + case "S-1-12-1": + for _, part := range parts[4:8] { + if _, ok := parseCanonicalUint32(part); !ok { + return false + } + } + return true + default: + return false + } +} + +// isTrustedAncestorSID reports whether sid may own or hold replace rights on +// an ancestor directory of a private Windows path. +func isTrustedAncestorSID( + sid string, + currentUserSID string, + adminMemberSIDs map[string]bool, + sandboxSIDs map[string]bool, + allowRuleOnlySIDs bool, +) bool { + if sid == "" { + return false + } + if (currentUserSID != "" && sid == currentUserSID) || + sid == localSystemSID || + sid == builtinAdminsSID || + sid == trustedInstallerSID || + isWindowsBuiltinAdminSID(sid) { + return true + } + if adminMemberSIDs != nil && isEligibleAdminMemberSID(sid) && adminMemberSIDs[sid] { + return true + } + if !allowRuleOnlySIDs { + return false + } + if sid == creatorOwnerSID || sid == ownerRightsSID { + return true + } + return sandboxSIDs != nil && sandboxSIDs[sid] +} diff --git a/apps/computer/local-daemon/internal/platform/privatefs/trusted_sid_test.go b/apps/computer/local-daemon/internal/platform/privatefs/trusted_sid_test.go new file mode 100644 index 000000000..5d670ed82 --- /dev/null +++ b/apps/computer/local-daemon/internal/platform/privatefs/trusted_sid_test.go @@ -0,0 +1,115 @@ +package privatefs + +import "testing" + +func TestIsWindowsBuiltinAdminSID(t *testing.T) { + for _, tc := range []struct { + name string + sid string + want bool + }{ + {"local built-in Administrator RID 500", "S-1-5-21-3623811015-3361044348-30300820-500", true}, + {"Domain Admins RID 512", "S-1-5-21-3623811015-3361044348-30300820-512", true}, + {"Enterprise Admins RID 519", "S-1-5-21-3623811015-3361044348-30300820-519", true}, + {"zero domain subauthorities RID 500", "S-1-5-21-0-0-0-500", true}, + {"max uint32 subauthorities RID 500", "S-1-5-21-4294967295-4294967295-4294967295-500", true}, + {"Guest RID 501", "S-1-5-21-3623811015-3361044348-30300820-501", false}, + {"Domain Users RID 513", "S-1-5-21-3623811015-3361044348-30300820-513", false}, + {"Domain Guests RID 514", "S-1-5-21-3623811015-3361044348-30300820-514", false}, + {"Domain Computers RID 515", "S-1-5-21-3623811015-3361044348-30300820-515", false}, + {"ordinary user RID 1001", "S-1-5-21-3623811015-3361044348-30300820-1001", false}, + {"Everyone", "S-1-1-0", false}, + {"Authenticated Users", "S-1-5-11", false}, + {"BUILTIN Users", "S-1-5-32-545", false}, + {"extra trailing subauthority", "S-1-5-21-1-2-3-500-1", false}, + {"missing domain subauthority", "S-1-5-21-1-2-500", false}, + {"uint32 overflow", "S-1-5-21-4294967296-2-3-500", false}, + {"leading zero subauthority", "S-1-5-21-01-2-3-500", false}, + {"empty string", "", false}, + } { + t.Run(tc.name, func(t *testing.T) { + if got := isWindowsBuiltinAdminSID(tc.sid); got != tc.want { + t.Fatalf("isWindowsBuiltinAdminSID(%q) = %v, want %v", tc.sid, got, tc.want) + } + }) + } +} + +func TestIsEligibleAdminMemberSID(t *testing.T) { + for _, tc := range []struct { + name string + sid string + want bool + }{ + {"secondary local user RID 1006", "S-1-5-21-3623811015-3361044348-30300820-1006", true}, + {"Entra ID account SID", "S-1-12-1-123456789-234567890-345678901-456789012", true}, + {"Everyone is excluded", "S-1-1-0", false}, + {"Authenticated Users is excluded", "S-1-5-11", false}, + {"BUILTIN Users is excluded", "S-1-5-32-545", false}, + {"Domain Users RID 513 is excluded", "S-1-5-21-1-2-3-513", false}, + {"Guest RID 501 is excluded", "S-1-5-21-1-2-3-501", false}, + {"malformed Entra SID", "S-1-12-1-1-2-3", false}, + {"overflow Entra SID", "S-1-12-1-4294967296-2-3-4", false}, + } { + t.Run(tc.name, func(t *testing.T) { + if got := isEligibleAdminMemberSID(tc.sid); got != tc.want { + t.Fatalf("isEligibleAdminMemberSID(%q) = %v, want %v", tc.sid, got, tc.want) + } + }) + } +} + +func TestIsTrustedAncestorSID(t *testing.T) { + const ( + currentUser = "S-1-5-21-100-200-300-1001" + builtinAdm = "S-1-5-21-100-200-300-500" + domainAdm = "S-1-5-21-999-888-777-512" + localAdmMem = "S-1-5-21-100-200-300-1006" + entraAdmMem = "S-1-12-1-11-22-33-44" + otherUser = "S-1-5-21-100-200-300-1007" + sandboxSID = "S-1-5-21-1158770811-2547671072-1736395728-473538918" + ) + // Even if a broken machine listed Everyone or Users in adminMembers, they + // must never be trusted. + adminMembers := map[string]bool{ + localAdmMem: true, + entraAdmMem: true, + "S-1-1-0": true, + "S-1-5-11": true, + "S-1-5-32-545": true, + } + sandbox := map[string]bool{sandboxSID: true} + + for _, tc := range []struct { + name string + sid string + allowRuleOnly bool + want bool + }{ + {"current user owner", currentUser, false, true}, + {"SYSTEM", localSystemSID, false, true}, + {"BUILTIN Administrators", builtinAdminsSID, false, true}, + {"TrustedInstaller", trustedInstallerSID, false, true}, + {"built-in Admin RID 500 owner", builtinAdm, false, true}, + {"built-in Admin RID 500 ACE", builtinAdm, true, true}, + {"Domain Admins RID 512", domainAdm, true, true}, + {"direct local admin member owner", localAdmMem, false, true}, + {"direct Entra admin member ACE", entraAdmMem, true, true}, + {"CREATOR OWNER on ACE", creatorOwnerSID, true, true}, + {"CREATOR OWNER as owner rejected", creatorOwnerSID, false, false}, + {"OWNER RIGHTS on ACE", ownerRightsSID, true, true}, + {"Codex sandbox SID on ACE", sandboxSID, true, true}, + {"Codex sandbox SID as owner rejected", sandboxSID, false, false}, + {"non-admin local user rejected", otherUser, true, false}, + {"Everyone rejected even if in adminMembers", "S-1-1-0", true, false}, + {"Authenticated Users rejected even if in adminMembers", "S-1-5-11", true, false}, + {"BUILTIN Users rejected even if in adminMembers", "S-1-5-32-545", true, false}, + {"empty SID rejected", "", true, false}, + } { + t.Run(tc.name, func(t *testing.T) { + if got := isTrustedAncestorSID(tc.sid, currentUser, adminMembers, sandbox, tc.allowRuleOnly); got != tc.want { + t.Fatalf("isTrustedAncestorSID(%q, allowRuleOnly=%v) = %v, want %v", tc.sid, tc.allowRuleOnly, got, tc.want) + } + }) + } +} diff --git a/apps/desktop/AGENTS.md b/apps/desktop/AGENTS.md index b425ee037..aaa7feff0 100644 --- a/apps/desktop/AGENTS.md +++ b/apps/desktop/AGENTS.md @@ -83,7 +83,11 @@ Gateway and runs Agents. The daemon exits with the app. status summary, tray menu and tray icons, drawn from the logo PNGs in `resources/tray/` with a status badge. - `src/main/local-server.ts`: LocalServer, the setup page's Quick Install - path. It fetches the pinned Node runtime (sources in the download region's + path. On Windows, install preflight checks both the install home and the + Computer daemon directory (`/computer`) non-destructively via + `windowsPrivateLocation` before fetching Node or unpacking, so ancestor ACL + refusals fail immediately with the offending ancestor path and SID instead of + after enrollment. It fetches the pinned Node runtime (sources in the download region's order, `scripts/installs/README.md`) and unpacks the linger source package into the install location (the default home, or a folder picked under Customize; tar runs inside the target with relative paths, and the diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.ts index a5c0b27b9..24b5da5f8 100644 --- a/apps/desktop/src/main/index.ts +++ b/apps/desktop/src/main/index.ts @@ -177,6 +177,7 @@ async function main(): Promise { }; const localServer = new LocalServerModule({ home, + daemonDirectory, version: VERSION, macosVersion: () => process.getSystemVersion(), installerDirectory: path.join(here, "../installer"), diff --git a/apps/desktop/src/main/local-server.test.ts b/apps/desktop/src/main/local-server.test.ts index 0a3d376f4..15790ae06 100644 --- a/apps/desktop/src/main/local-server.test.ts +++ b/apps/desktop/src/main/local-server.test.ts @@ -3107,6 +3107,116 @@ describe("LocalServerModule", () => { await f.host.stop("quit"); } }); + + it("pre-checks both the install home and Computer daemon directory on Windows before unpacking", async () => { + const checked: string[] = []; + const daemonDir = "C:\\Users\\me\\AppData\\Roaming\\Linger\\computer"; + const winCheckout = (home: string) => { + checkout(home); + writeFileSync( + path.join(path.dirname(home), "installer", "distribution.json"), + JSON.stringify({ + platform: "win32", + arch: "x64", + nativeSources: [{ target: "win32-x64" }], + }), + ); + }; + const f = fixture( + (home) => ({ + ...withCheckout(home), + platform: "win32", + arch: "x64", + daemonDirectory: daemonDir, + checkPrivateLocation: async (directory) => { + checked.push(directory); + if (directory === daemonDir) { + throw Object.assign( + new Error( + `Windows private path validation failed: ${daemonDir} is inside a folder other accounts on this computer can rename or replace (ancestor: C:\\Users\\me\\AppData\\Roaming, sid: S-1-5-21-1-2-3-1007).`, + ), + { + code: "WINDOWS_PRIVATE_PATH_UNSAFE", + reason: "UNSAFE_PARENT_ACCESS", + }, + ); + } + }, + }), + {}, + winCheckout, + ); + await f.host.start(); + try { + await expect(f.module.begin()).rejects.toThrow( + `Desktop Computer directory validation failed: Windows private path validation failed: ${daemonDir}`, + ); + expect(checked).toEqual([f.home, daemonDir]); + expect(f.module.status()).toMatchObject({ + phase: "failed", + step: "prepare", + }); + // Daemon directory refusal must not masquerade as an install-location refusal. + expect(f.module.status().refusal).toBeUndefined(); + // Installer never launched because preflight stopped in prepare. + expect(existsSync(path.join(f.home, "installer", "args.json"))).toBe( + false, + ); + } finally { + await f.host.stop("quit"); + } + }); + + it("preserves the Windows private-path refusal when home preflight fails", async () => { + const winCheckout = (home: string) => { + checkout(home); + writeFileSync( + path.join(path.dirname(home), "installer", "distribution.json"), + JSON.stringify({ + platform: "win32", + arch: "x64", + nativeSources: [{ target: "win32-x64" }], + }), + ); + }; + const f = fixture( + (home) => ({ + ...withCheckout(home), + platform: "win32", + arch: "x64", + daemonDirectory: "C:\\Users\\me\\AppData\\Roaming\\Linger\\computer", + checkPrivateLocation: async () => { + throw Object.assign( + new Error( + "Windows private path validation failed: home is inside a folder other accounts on this computer can rename or replace (ancestor: C:\\Users\\me, sid: S-1-5-21-1-2-3-1007).", + ), + { + code: "WINDOWS_PRIVATE_PATH_UNSAFE", + reason: "UNSAFE_PARENT_ACCESS", + }, + ); + }, + }), + {}, + winCheckout, + ); + await f.host.start(); + try { + await expect(f.module.begin()).rejects.toThrow( + "Windows private path validation failed", + ); + expect(f.module.status()).toMatchObject({ + phase: "failed", + step: "prepare", + refusal: { + code: "WINDOWS_PRIVATE_PATH_UNSAFE", + reason: "UNSAFE_PARENT_ACCESS", + }, + }); + } finally { + await f.host.stop("quit"); + } + }); }); describe("LocalServerModule install location", () => { @@ -5031,6 +5141,7 @@ describe("LocalServerModule on Windows", () => { const f = fixture( { platform: "win32", + checkPrivateLocation: async () => {}, sourceArchive: { file, sha256: archive.sha256 }, rename: async (from, to) => { moves.push(path.basename(to)); @@ -5082,6 +5193,7 @@ describe("LocalServerModule on Windows", () => { const f = fixture( { platform: "win32", + checkPrivateLocation: async () => {}, sourceArchive: { file, sha256: archive.sha256 }, rename: async () => { moves++; diff --git a/apps/desktop/src/main/local-server.ts b/apps/desktop/src/main/local-server.ts index 74a065d6d..59b3102a0 100644 --- a/apps/desktop/src/main/local-server.ts +++ b/apps/desktop/src/main/local-server.ts @@ -64,6 +64,7 @@ import { import { redact } from "@linger/local-installation/redaction"; import { isInkling2MiniModelId } from "@linger/service-kit/featured-models"; import { + windowsPrivateLocation, windowsPrivateRefusal, type WindowsPrivateRefusal, } from "@linger/local-installation/windows-private"; @@ -391,6 +392,13 @@ export interface LocalServerOptions { readonly pollMs?: number; // The free space a picked folder needs; LOCATION_FREE_BYTES by default. readonly freeBytes?: number; + // Where the Desktop Computer daemon stores its config and state + // (/computer); validated on Windows during setup preflight so + // ancestor ACL refusals fail immediately instead of after installation. + readonly daemonDirectory?: string; + // Checks Windows private-path safety for a candidate directory without + // creating it or mutating ACLs; windowsPrivateLocation by default on Windows. + readonly checkPrivateLocation?: (directory: string) => Promise; // How long setup waits for the Another Me; AGENTS_TIMEOUT_MS by default. readonly agentsTimeoutMs?: number; // Opens the runtime's sign-in page in the browser. @@ -1247,6 +1255,34 @@ export class LocalServerModule implements Module { ); if (error) throw new Error(error); } + // On Windows, pre-check both the install home and the Computer daemon + // directory (/computer) before unpacking so ancestor ACL + // refusals fail immediately instead of after installation and enrollment. + if ((this.#options.platform ?? process.platform) === "win32") { + const checkPrivate = + this.#options.checkPrivateLocation ?? windowsPrivateLocation; + await this.#timed("private_paths", async () => { + await checkPrivate(home); + const daemonDirectory = this.#options.daemonDirectory; + if ( + daemonDirectory && + path.resolve(daemonDirectory) !== path.resolve(home) + ) { + try { + await checkPrivate(daemonDirectory); + } catch (error) { + // Do not tag a daemon-directory refusal as an install-location + // refusal; moving the install folder does not move . + const detail = + error instanceof Error ? error.message : String(error); + throw new Error( + `Desktop Computer directory validation failed: ${detail}`, + { cause: error }, + ); + } + } + }); + } const node = await this.#timed("node", () => this.#ensureNode(signal)); const keysChanged = Object.keys(plan.keys ?? {}).length > 0; if (keysChanged) @@ -1413,7 +1449,9 @@ export class LocalServerModule implements Module { this.#set( "failed", message, - windowsPrivateRefusal((error as { refusal?: unknown } | null)?.refusal), + windowsPrivateRefusal( + (error as { refusal?: unknown } | null)?.refusal ?? error, + ), localServerFailure((error as { code?: unknown } | null)?.code), ); throw error; diff --git a/packages/local-installation/AGENTS.md b/packages/local-installation/AGENTS.md index dcef349ba..93a2538b7 100644 --- a/packages/local-installation/AGENTS.md +++ b/packages/local-installation/AGENTS.md @@ -19,15 +19,26 @@ ancestor counts as well, because its holder can rename that folder, except on a volume root, which can be neither renamed nor removed. A folder directly on a data drive with the stock root ACL therefore passes, and a folder nested in one that inherits Modify for Authenticated Users does not. The Daemon's -`privatefs` treats the volume root the same way. A refusal leaves the -installer as its code and reason (`windowsPrivateRefusal`), never as its -words: in the `startFailure` line on stdout when the installer manager cannot -start, and in the `--user-keys` outcome. The Desktop setup page branches on -`UNSAFE_PARENT_ACCESS` to say where to install instead. Repair skips propagation when the protected -DACL already grants inheritable FullControl to the owner and SYSTEM on a -directory, or FullControl to both on a file. Private paths with partial rights -still receive the full repair. Rewriting a directory DACL propagates to its -existing children and can time out on a large cache tree. +`privatefs` treats the volume root and trusted ancestor principals the same +way: ancestors trust the current user, `SYSTEM`, `BUILTIN\Administrators`, +`TrustedInstaller`, built-in Administrator/Domain/Enterprise Admin SIDs +(`S-1-5-21-*-*-*-500|512|519`), direct individual/domain/Entra members of local +`BUILTIN\Administrators` (never broad groups such as `Everyone`, `Users`, or +`Authenticated Users`), and Codex Windows sandbox principals on access rules. +Private targets themselves remain strictly owner-only. `windowsPrivateLocation` +runs the same check non-destructively without creating folders or changing +ACLs. The PowerShell script checks `$ExecutionContext.SessionState.LanguageMode` +first, emits Win32 P/Invoke stubs in memory via `Reflection.Emit` instead of +compiling C# through `Add-Type`, and reports the offending ancestor path and SID +or sanitized exception/worker diagnostics (never raw stderr prose). A refusal leaves the installer as its code and reason +(`windowsPrivateRefusal`), never as its words: in the `startFailure` line on +stdout when the installer manager cannot start, and in the `--user-keys` +outcome. The Desktop setup page branches on `UNSAFE_PARENT_ACCESS` to say where +to install instead. Repair skips propagation when the protected DACL already +grants inheritable FullControl to the owner and SYSTEM on a directory, or +FullControl to both on a file. Private paths with partial rights still receive +the full repair. Rewriting a directory DACL propagates to its existing children +and can time out on a large cache tree. Launch the fixed private-path scripts with PowerShell `-Command`. Encoding the whole script lengthens the Windows command line and can stall startup. diff --git a/packages/local-installation/src/windows-private-ancestors.test.ts b/packages/local-installation/src/windows-private-ancestors.test.ts index ffa520fd1..7f350d307 100644 --- a/packages/local-installation/src/windows-private-ancestors.test.ts +++ b/packages/local-installation/src/windows-private-ancestors.test.ts @@ -2,12 +2,12 @@ import { describe, expect, it } from "vitest"; import { WINDOWS_PRIVATE_SCRIPT } from "./windows-private.js"; // PowerShell does not run on every development machine, so these tests read -// the rights the ancestor rule names out of the fixed script. Get-Acl, the -// owner check and the walk itself run only in windows-private.native.test.ts -// on Windows. +// the rights and trusted-principal hooks out of the fixed script. Get-Acl, the +// owner check and the walk itself run in windows-private.native.test.ts on +// Windows. const ANCESTORS = WINDOWS_PRIVATE_SCRIPT.slice( WINDOWS_PRIVATE_SCRIPT.indexOf("while ($parent)"), - WINDOWS_PRIVATE_SCRIPT.indexOf("if ($request.repair)"), + WINDOWS_PRIVATE_SCRIPT.indexOf("if ($request.kind -ne 'location')"), ); const names = (pattern: RegExp) => (pattern.exec(ANCESTORS)?.[1] ?? "").split(",").filter(Boolean); @@ -34,9 +34,11 @@ const mask = (rights: string[]) => // Modify, the right Windows gives Authenticated Users on every data drive it // formats, and which folders made on that drive inherit. const MODIFY = 0x1301bf; +// FullControl, the right stock secondary NTFS drives grant Everyone:(OI)(CI)(F). +const FULL_CONTROL = 0x1f01ff; describe("the ancestor rule in the fixed ACL program", () => { - it("counts Delete only on a folder that has a parent", () => { + it("counts Delete only on a folder that has a parent and aligns trusted ancestor SIDs with privatefs", () => { expect(EVERYWHERE).toEqual([ "DeleteSubdirectoriesAndFiles", "ChangePermissions", @@ -46,13 +48,20 @@ describe("the ancestor rule in the fixed ACL program", () => { expect(ANCESTORS).toContain( "[Security.AccessControl.FileSystemRights]$replace", ); + expect(WINDOWS_PRIVATE_SCRIPT).toContain(TRUSTED_INSTALLER); expect(ANCESTORS).toContain( - `-notin @($sid.Value, $system, $admins, 'S-1-3-0', '${TRUSTED_INSTALLER}')`, + "$ruleSid -in @($sid.Value, $system, $admins, 'S-1-3-0', 'S-1-3-4', $trustedInstaller)", ); + expect(ANCESTORS).toContain("Test-BuiltinAdminSid"); + expect(ANCESTORS).toContain("Get-LocalAdminMemberSids"); + expect(ANCESTORS).toContain("Get-CodexSandboxSids"); + expect(ANCESTORS).toContain("$failAncestor = $parent.FullName"); + expect(ANCESTORS).toContain("$failSid = $ruleSid"); }); - it("lets others hold Modify on a data drive's root but not on a folder in it", () => { + it("lets others hold Modify on a data drive's root but rejects Modify below it and FullControl everywhere", () => { expect(MODIFY & mask(EVERYWHERE)).toBe(0); expect(MODIFY & mask([...BELOW_ROOT, ...EVERYWHERE])).toBe(RIGHTS.Delete); + expect(FULL_CONTROL & mask(EVERYWHERE)).toBe(mask(EVERYWHERE)); }); }); diff --git a/packages/local-installation/src/windows-private.native.test.ts b/packages/local-installation/src/windows-private.native.test.ts index fd2b20ae2..b621a6cfb 100644 --- a/packages/local-installation/src/windows-private.native.test.ts +++ b/packages/local-installation/src/windows-private.native.test.ts @@ -4,9 +4,11 @@ import { tmpdir } from "node:os"; import path from "node:path"; import { closeWindowsPrivateWorker, + parseWindowsPrivateFailure, WINDOWS_PRIVATE_PREAMBLE, WINDOWS_PRIVATE_SCRIPT, windowsPowerShellArguments, + windowsPrivateLocation, windowsPrivatePath, } from "./windows-private.js"; import { runProcess } from "./process.js"; @@ -238,7 +240,10 @@ it.skipIf(process.platform !== "win32")( }, ); expect(restricted.code).toBe(1); - expect(restricted.stdout.trim()).toBe("UNSAFE_OWNER"); + expect(parseWindowsPrivateFailure(restricted.stdout)).toMatchObject({ + reason: "UNSAFE_OWNER", + sid: "S-1-5-32-544", + }); }, ); it.skipIf(process.platform !== "win32")( @@ -332,24 +337,57 @@ it.skipIf(process.platform !== "win32")( ); // Elevated runners return from Test-Administrator before the linked-token -// check, so this compiles and calls it directly. +// check, so this builds and calls both Test-Administrator and +// Test-LinkedTokenAdministrator directly, plus the PowerShell SID classifiers. it.skipIf(process.platform !== "win32")( - "compiles the linked-token administrator check through the production launch arguments", + "runs Test-Administrator, the in-memory linked-token check without Add-Type, and the PowerShell SID classifiers", async () => { - expect(WINDOWS_PRIVATE_PREAMBLE).toContain('DllImport("advapi32.dll")'); + expect(WINDOWS_PRIVATE_PREAMBLE).not.toContain("Add-Type"); + expect(WINDOWS_PRIVATE_PREAMBLE).toContain("DefinePInvokeMethod"); const powershell = path.win32.join( process.env.SystemRoot ?? "C:\\Windows", "System32/WindowsPowerShell/v1.0/powershell.exe", ); + const probe = [ + WINDOWS_PRIVATE_PREAMBLE, + "$res = [ordered]@{", + " admin = (Test-Administrator).GetType().FullName", + " linked = (Test-LinkedTokenAdministrator).GetType().FullName", + " rid500 = Test-BuiltinAdminSid 'S-1-5-21-3623811015-3361044348-30300820-500'", + " rid512 = Test-BuiltinAdminSid 'S-1-5-21-3623811015-3361044348-30300820-512'", + " rid513 = Test-BuiltinAdminSid 'S-1-5-21-3623811015-3361044348-30300820-513'", + " everyone = Test-EligibleAdminMemberSid 'S-1-1-0'", + " member1006 = Test-EligibleAdminMemberSid 'S-1-5-21-3623811015-3361044348-30300820-1006'", + " entra = Test-EligibleAdminMemberSid 'S-1-12-1-11-22-33-44'", + "}", + "[Console]::Out.Write(($res | ConvertTo-Json -Compress))", + ].join("\n"); const result = await runProcess( powershell, - windowsPowerShellArguments( - `${WINDOWS_PRIVATE_PREAMBLE}\n[Console]::Out.Write((Test-LinkedTokenAdministrator).GetType().FullName)`, - ), + windowsPowerShellArguments(probe), { timeoutMs: 30_000 }, ); expect(result.code, result.stderr).toBe(0); - expect(result.stdout).toBe("System.Boolean"); + expect(JSON.parse(result.stdout)).toEqual({ + admin: "System.Boolean", + linked: "System.Boolean", + rid500: true, + rid512: true, + rid513: false, + everyone: false, + member1006: true, + entra: true, + }); }, 60_000, ); +it.skipIf(process.platform !== "win32")( + "validates existing and missing candidate directories with windowsPrivateLocation without creating them", + async () => { + const root = await fixture(); + const pending = path.join(root, "not-created-yet", "computer"); + await expect(windowsPrivateLocation(root)).resolves.toBeUndefined(); + await expect(windowsPrivateLocation(pending)).resolves.toBeUndefined(); + }, + 30_000, +); diff --git a/packages/local-installation/src/windows-private.test.ts b/packages/local-installation/src/windows-private.test.ts index d57f710de..379baf4fe 100644 --- a/packages/local-installation/src/windows-private.test.ts +++ b/packages/local-installation/src/windows-private.test.ts @@ -4,13 +4,17 @@ import { PassThrough } from "node:stream"; import { expect, it, vi } from "vitest"; import { createWindowsPrivateClient, + parseWindowsPrivateFailure, + windowsPrivateLocation, windowsPrivatePath, windowsPrivateRefusal, WINDOWS_PRIVATE_PATH_UNSAFE, + WINDOWS_PRIVATE_PREAMBLE, WINDOWS_PRIVATE_SCRIPT, WINDOWS_PRIVATE_WORKER_SCRIPT, } from "./windows-private.js"; -it("sends paths through stdin and launches a fixed PowerShell command", async () => { + +it("sends paths through stdin and launches a fixed PowerShell command without Add-Type", async () => { const run = vi.fn().mockResolvedValue({ code: 0, stdout: "", stderr: "" }); await windowsPrivatePath( "C:\\Users\\person\\private's", @@ -30,12 +34,31 @@ it("sends paths through stdin and launches a fixed PowerShell command", async () kind: "directory", repair: true, }); + expect(WINDOWS_PRIVATE_PREAMBLE).not.toContain("Add-Type"); + expect(WINDOWS_PRIVATE_PREAMBLE).not.toContain("$identity.Groups"); + expect(WINDOWS_PRIVATE_PREAMBLE).toContain("DefinePInvokeMethod"); + expect(WINDOWS_PRIVATE_SCRIPT).toContain("SessionState.LanguageMode"); expect(WINDOWS_PRIVATE_SCRIPT).toContain("[Console]::InputEncoding"); + expect(WINDOWS_PRIVATE_SCRIPT).toContain("[Console]::OutputEncoding"); expect(WINDOWS_PRIVATE_SCRIPT).toContain("ReparsePoint"); expect(WINDOWS_PRIVATE_SCRIPT).toContain("GetCurrent().User"); expect(WINDOWS_PRIVATE_SCRIPT).toContain("AccessControlSections]::Access"); }); -it("fails closed without disclosing command diagnostics", async () => { + +it("checks candidate locations non-destructively with kind location and repair false", async () => { + const run = vi.fn().mockResolvedValue({ code: 0, stdout: "", stderr: "" }); + await windowsPrivateLocation( + "C:\\Users\\person\\AppData\\Roaming\\Linger\\computer", + run, + ); + expect(JSON.parse(run.mock.calls[0]![2].input)).toEqual({ + path: path.resolve("C:\\Users\\person\\AppData\\Roaming\\Linger\\computer"), + kind: "location", + repair: false, + }); +}); + +it("fails closed without disclosing raw command diagnostics", async () => { const run = vi .fn() .mockResolvedValue({ code: 1, stdout: "", stderr: "sensitive path" }); @@ -49,7 +72,8 @@ it("fails closed without disclosing command diagnostics", async () => { reason: "UNCHECKED", }); }); -it("names the path and why it is not private", async () => { + +it("names the path, offending ancestor, offending SID, and sanitized UNCHECKED diagnostics", async () => { const file = "C:\\Users\\person\\.simplexai\\instances\\desktop\\native.env.1.tmp"; const owned = vi @@ -65,16 +89,114 @@ it("names the path and why it is not private", async () => { }); expect(error?.message).toContain(path.resolve(file)); expect(error?.message).toContain("owned by another account"); - // Only the script's fixed codes pass; anything else is unchecked. + + const ancestorFail = vi.fn().mockResolvedValue({ + code: 1, + stdout: JSON.stringify({ + code: "UNSAFE_PARENT_ACCESS", + ancestor: "C:\\Users\\person\\AppData\\Roaming", + sid: "S-1-5-21-1-2-3-1007", + }), + stderr: "", + }); + const parentError = await windowsPrivateLocation( + "C:\\Users\\person\\AppData\\Roaming\\Linger\\computer", + ancestorFail, + ).catch( + (failure: unknown) => + failure as Error & { ancestor?: string; sid?: string }, + ); + expect(parentError).toMatchObject({ + code: "WINDOWS_PRIVATE_PATH_UNSAFE", + reason: "UNSAFE_PARENT_ACCESS", + ancestor: "C:\\Users\\person\\AppData\\Roaming", + sid: "S-1-5-21-1-2-3-1007", + }); + expect(parentError?.message).toContain( + "ancestor: C:\\Users\\person\\AppData\\Roaming", + ); + expect(parentError?.message).toContain("sid: S-1-5-21-1-2-3-1007"); + expect(windowsPrivateRefusal(parentError)).toEqual({ + code: WINDOWS_PRIVATE_PATH_UNSAFE, + reason: "UNSAFE_PARENT_ACCESS", + }); + + const uncheckedFail = vi.fn().mockResolvedValue({ + code: 1, + stdout: JSON.stringify({ + code: "UNCHECKED", + stage: "ancestor", + errorType: "UnauthorizedAccessException", + hresult: "0x80070005", + }), + stderr: "", + }); + const uncheckedError = await windowsPrivatePath( + file, + "file", + false, + uncheckedFail, + ).catch((failure: unknown) => failure as Error & { diagnostic?: string }); + expect(uncheckedError).toMatchObject({ + code: "WINDOWS_PRIVATE_PATH_UNSAFE", + reason: "UNCHECKED", + diagnostic: + "stage=ancestor, type=UnauthorizedAccessException, hresult=0x80070005", + }); + expect(uncheckedError?.message).toContain( + "stage=ancestor, type=UnauthorizedAccessException, hresult=0x80070005", + ); + + // Only the script's fixed codes pass; anything else is unchecked without leaking text. const other = vi.fn().mockResolvedValue({ code: 1, stdout: "Access denied to C:\\x", stderr: "", }); - await expect( - windowsPrivatePath(file, "file", false, other), - ).rejects.toMatchObject({ reason: "UNCHECKED" }); + const otherError = await windowsPrivatePath(file, "file", false, other).catch( + (failure: unknown) => failure as Error, + ); + expect(otherError).toMatchObject({ reason: "UNCHECKED" }); + expect(otherError?.message).not.toContain("Access denied to C:\\x"); +}); + +it("validates structured failure payloads including language mode checks", () => { + expect( + parseWindowsPrivateFailure( + JSON.stringify({ + code: "UNCHECKED", + stage: "language_mode", + errorType: "ConstrainedLanguage", + }), + ), + ).toEqual({ + reason: "UNCHECKED", + diagnostic: "stage=language_mode, type=ConstrainedLanguage", + }); + expect( + parseWindowsPrivateFailure( + JSON.stringify({ + code: "UNSAFE_PARENT_OWNER", + ancestor: "C:\\Users\\person", + sid: "not-a-sid", + }), + ), + ).toEqual({ + reason: "UNSAFE_PARENT_OWNER", + ancestor: "C:\\Users\\person", + }); + expect( + parseWindowsPrivateFailure( + JSON.stringify({ + code: "UNCHECKED", + stage: "bad;stage", + errorType: "bad type with spaces", + hresult: "not-hex", + }), + ), + ).toEqual({ reason: "UNCHECKED" }); }); + it("gives every failure in the ACL program a fixed reason code", () => { const thrown = [...WINDOWS_PRIVATE_SCRIPT.matchAll(/throw '([^']*)'/g)].map( (match) => match[1], @@ -82,10 +204,11 @@ it("gives every failure in the ACL program a fixed reason code", () => { expect(thrown.length).toBeGreaterThan(5); for (const code of thrown) expect(code).toMatch(/^[A-Z][A-Z_]+$/); }); + it("ignores inherit-only ACEs only for effective ancestor permissions", () => { const ancestors = WINDOWS_PRIVATE_SCRIPT.slice( WINDOWS_PRIVATE_SCRIPT.indexOf("while ($parent)"), - WINDOWS_PRIVATE_SCRIPT.indexOf("if ($request.repair)"), + WINDOWS_PRIVATE_SCRIPT.indexOf("if ($request.kind -ne 'location')"), ); const target = WINDOWS_PRIVATE_SCRIPT.slice( WINDOWS_PRIVATE_SCRIPT.indexOf("$currentAllowed = $false"), @@ -101,17 +224,18 @@ it("ignores inherit-only ACEs only for effective ancestor permissions", () => { expect(WINDOWS_PRIVATE_WORKER_SCRIPT).toContain( "$env:PSModulePath = [IO.Path]::Combine($PSHOME, 'Modules')", ); + expect(WINDOWS_PRIVATE_WORKER_SCRIPT).toContain("SessionState.LanguageMode"); expect(WINDOWS_PRIVATE_WORKER_SCRIPT).toContain("ReparsePoint"); expect(WINDOWS_PRIVATE_WORKER_SCRIPT).toContain("SHARED_ACCESS"); expect(WINDOWS_PRIVATE_WORKER_SCRIPT).toContain("Test-Administrator"); - expect(WINDOWS_PRIVATE_WORKER_SCRIPT).toContain( - "if (-not ('LingerLinkedToken' -as [type]))", - ); + expect(WINDOWS_PRIVATE_WORKER_SCRIPT).toContain("Ensure-LingerWin32Native"); + expect(WINDOWS_PRIVATE_WORKER_SCRIPT).not.toContain("Add-Type"); expect(WINDOWS_PRIVATE_WORKER_SCRIPT).toContain("$script:isAdministrator"); expect(WINDOWS_PRIVATE_WORKER_SCRIPT).toContain( "$replace = 'DeleteSubdirectoriesAndFiles,ChangePermissions,TakeOwnership'", ); }); + it("hands on the code and reason of a refusal, and nothing else", async () => { const run = vi.fn().mockResolvedValue({ code: 1, @@ -145,7 +269,12 @@ it("hands on the code and reason of a refusal, and nothing else", async () => { }); function fakeWorker( - onLine: (line: string, stdout: PassThrough, emitClose: () => void) => void, + onLine: ( + line: string, + stdout: PassThrough, + emitClose: (code?: number | null) => void, + emitError: (error: Error) => void, + ) => void, ) { const emitter = new EventEmitter(); const stdin = new PassThrough(); @@ -160,7 +289,12 @@ function fakeWorker( if (nl < 0) break; const line = buffer.slice(0, nl); buffer = buffer.slice(nl + 1); - onLine(line, stdout, () => emitter.emit("close")); + onLine( + line, + stdout, + (code = 1) => emitter.emit("close", code, null), + (error) => emitter.emit("error", error), + ); } }); stdin.on("finish", () => { @@ -173,15 +307,14 @@ function fakeWorker( kill: () => { killed = true; }, - on: (event: "close" | "error", listener: () => void) => - emitter.on(event, listener), + on: emitter.on.bind(emitter), }, wasKilled: () => killed, wasEnded: () => ended, }; } -it("reuses one persistent worker across concurrent requests and respawns cleanly after failures", async () => { +it("reuses one persistent worker across concurrent requests, captures sanitized worker diagnostics, and respawns cleanly", async () => { vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); const workers: Array> = []; let count = 0; @@ -190,14 +323,24 @@ it("reuses one persistent worker across concurrent requests and respawns cleanly timeoutMs: 200, spawnWorker: () => { const id = ++count; - const w = fakeWorker((line, stdout, emitClose) => { + const w = fakeWorker((line, stdout, emitClose, emitError) => { const req = JSON.parse(line) as { path: string }; if (req.path === "ok-1" || req.path === "ok-2") stdout.write("__LINGER_ACL_OK__\n"); else if (req.path === "bad-owner") stdout.write("__LINGER_ACL_ERR__:UNSAFE_OWNER\n"); - else if (req.path === "crash") emitClose(); - else if (req.path === "desync") stdout.write("unexpected output\n"); + else if (req.path === "clm") { + stdout.write( + '__LINGER_ACL_ERR__:{"code":"UNCHECKED","stage":"language_mode","errorType":"ConstrainedLanguage"}\n', + ); + emitClose(1); + } else if (req.path === "crash") { + emitClose(5); + } else if (req.path === "spawn-fail") { + emitError( + Object.assign(new Error("spawn ENOENT"), { code: "ENOENT" }), + ); + } else if (req.path === "desync") stdout.write("unexpected output\n"); else if (req.path === "hang" && id > 0) { // Intentionally never replies so the request timeout fires. } @@ -217,32 +360,55 @@ it("reuses one persistent worker across concurrent requests and respawns cleanly expect(r3).toEqual({ code: 1, stdout: "UNSAFE_OWNER" }); expect(workers).toHaveLength(1); - // Unexpected close fails closed and respawns on the next request. - expect(await client.execute(JSON.stringify({ path: "crash" }))).toEqual({ + // Structured Constrained Language Mode refusal passes through and respawns. + const clm = await client.execute(JSON.stringify({ path: "clm" })); + expect( + parseWindowsPrivateFailure(clm.stdout, clm.workerDiagnostic), + ).toEqual({ + reason: "UNCHECKED", + diagnostic: "stage=language_mode, type=ConstrainedLanguage", + }); + + // Unexpected close fails closed with exit code, then respawns. + const crashed = await client.execute(JSON.stringify({ path: "crash" })); + expect(crashed).toEqual({ code: 1, stdout: "", + workerDiagnostic: "worker=exit:5", }); expect(await client.execute(JSON.stringify({ path: "ok-1" }))).toEqual({ code: 0, stdout: "", }); - expect(workers).toHaveLength(2); + expect(workers).toHaveLength(3); + + // Spawn error reports sanitized errno code. + const spawnFailed = await client.execute( + JSON.stringify({ path: "spawn-fail" }), + ); + expect(spawnFailed).toEqual({ + code: 1, + stdout: "", + workerDiagnostic: "worker=spawn:ENOENT", + }); - // Unexpected stdout kills the worker and fails closed. + // Unexpected stdout kills the worker and fails closed with desync diagnostic. expect(await client.execute(JSON.stringify({ path: "desync" }))).toEqual({ code: 1, stdout: "", + workerDiagnostic: "worker=desync", }); - expect(workers[1]!.wasKilled()).toBe(true); + expect(workers[3]!.wasKilled()).toBe(true); - // Timeout kills a hung worker and fails closed. + // Timeout kills a hung worker and fails closed with timeout diagnostic. const timedOut = client.execute(JSON.stringify({ path: "hang" })); await vi.advanceTimersByTimeAsync(200); expect(await timedOut).toEqual({ code: 1, stdout: "", + workerDiagnostic: "worker=timeout", }); - expect(workers[2]!.wasKilled()).toBe(true); + expect(workers[4]!.wasKilled()).toBe(true); } finally { client.close(); vi.useRealTimers(); diff --git a/packages/local-installation/src/windows-private.ts b/packages/local-installation/src/windows-private.ts index 6c0a88f13..01a079670 100644 --- a/packages/local-installation/src/windows-private.ts +++ b/packages/local-installation/src/windows-private.ts @@ -3,73 +3,240 @@ import path from "node:path"; import { createInterface } from "node:readline"; import { runProcess } from "./process.js"; +const TRUSTED_INSTALLER_SID = + "S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464"; + export const WINDOWS_PRIVATE_PREAMBLE = String.raw`$ErrorActionPreference = 'Stop' # This fixed Windows PowerShell script uses only its own built-in modules. # A caller's PowerShell 7 modules can prevent Get-Acl from loading. $env:PSModulePath = [IO.Path]::Combine($PSHOME, 'Modules') [Console]::InputEncoding = [Text.UTF8Encoding]::new($false) -# Administrators enabled in this token, or in the elevated token UAC links to -# it (an administrator running without elevation). Only the rare second case -# compiles the check, at most once per process. +[Console]::OutputEncoding = [Text.UTF8Encoding]::new($false) $script:isAdministrator = $null +function Test-Uint32Token([string]$Token) { + if ($Token -cnotmatch '^(0|[1-9][0-9]{0,9})$') { return $false } + $n = [uint32]0 + return [uint32]::TryParse($Token, [Globalization.NumberStyles]::None, [Globalization.CultureInfo]::InvariantCulture, [ref]$n) +} +# Canonical built-in Administrator (RID 500), Domain Admins (RID 512), and +# Enterprise Admins (RID 519). Ordinary accounts start at RID 1000. +function Test-BuiltinAdminSid([string]$Value) { + $parts = $Value -split '-' + if ($parts.Count -ne 8 -or ($parts[0..3] -join '-') -cne 'S-1-5-21') { return $false } + foreach ($p in $parts[4..6]) { if (-not (Test-Uint32Token $p)) { return $false } } + return $parts[7] -in @('500', '512', '519') +} +# Individual/domain (RID >= 1000) or Entra ID SIDs eligible when listed as +# direct members of BUILTIN\Administrators. Broad groups are never admitted. +function Test-EligibleAdminMemberSid([string]$Value) { + $parts = $Value -split '-' + if ($parts.Count -ne 8) { return $false } + $prefix = $parts[0..3] -join '-' + if ($prefix -ceq 'S-1-5-21') { + foreach ($p in $parts[4..7]) { if (-not (Test-Uint32Token $p)) { return $false } } + return [uint32]$parts[7] -ge 1000 + } + if ($prefix -ceq 'S-1-12-1') { + foreach ($p in $parts[4..7]) { if (-not (Test-Uint32Token $p)) { return $false } } + return $true + } + return $false +} +function Test-CodexCapSid([string]$Value) { + $parts = $Value -split '-' + if ($parts.Count -ne 8 -or ($parts[0..3] -join '-') -cne 'S-1-5-21') { return $false } + foreach ($p in $parts[4..7]) { if (-not (Test-Uint32Token $p)) { return $false } } + return [uint32]$parts[7] -ge 1000 +} +# Emit Win32 P/Invoke stubs directly in memory without invoking csc.exe or +# writing temporary assemblies that AV/WDAC/AppLocker may block. +function Ensure-LingerWin32Native { + if ('LingerWin32Native' -as [type]) { return } + $asm = [Reflection.Emit.AssemblyBuilder]::DefineDynamicAssembly( + [Reflection.AssemblyName]::new('LingerWin32'), + [Reflection.Emit.AssemblyBuilderAccess]::Run + ) + $mod = $asm.DefineDynamicModule('LingerWin32') + $tb = $mod.DefineType('LingerWin32Native', [Reflection.TypeAttributes]'Public,Abstract,Sealed') + $ma = [Reflection.MethodAttributes]'Public,Static,HideBySig,PinvokeImpl' + $cc = [Runtime.InteropServices.CallingConvention]::Winapi + $cs = [Runtime.InteropServices.CharSet]::Unicode + foreach ($def in @( + @('OpenProcessToken', 'advapi32.dll', [bool], @([IntPtr], [uint32], [IntPtr].MakeByRefType())), + @('GetTokenInformation', 'advapi32.dll', [bool], @([IntPtr], [int], [IntPtr].MakeByRefType(), [int], [int].MakeByRefType())), + @('CheckTokenMembership', 'advapi32.dll', [bool], @([IntPtr], [byte[]], [bool].MakeByRefType())), + @('GetCurrentProcess', 'kernel32.dll', [IntPtr], [Type]::EmptyTypes), + @('CloseHandle', 'kernel32.dll', [bool], @([IntPtr])), + @('NetLocalGroupGetMembers', 'netapi32.dll', [uint32], @([IntPtr], [string], [uint32], [IntPtr].MakeByRefType(), [uint32], [uint32].MakeByRefType(), [uint32].MakeByRefType(), [IntPtr].MakeByRefType())), + @('NetApiBufferFree', 'netapi32.dll', [uint32], @([IntPtr])) + )) { + $m = $tb.DefinePInvokeMethod($def[0], $def[1], $ma, [Reflection.CallingConventions]::Standard, $def[2], [Type[]]$def[3], $cc, $cs) + $m.SetImplementationFlags($m.GetMethodImplementationFlags() -bor [Reflection.MethodImplAttributes]::PreserveSig) + } + $null = $tb.CreateType() +} +function Test-LinkedTokenAdministrator { + Ensure-LingerWin32Native + $administrators = [Security.Principal.SecurityIdentifier]::new('S-1-5-32-544') + $binary = [byte[]]::new($administrators.BinaryLength) + $administrators.GetBinaryForm($binary, 0) + $token = [IntPtr]::Zero + if (-not [LingerWin32Native]::OpenProcessToken([LingerWin32Native]::GetCurrentProcess(), [uint32]0x0008, [ref]$token)) { return $false } + $linked = [IntPtr]::Zero + $returned = 0 + try { + if (-not [LingerWin32Native]::GetTokenInformation($token, 19, [ref]$linked, [IntPtr]::Size, [ref]$returned)) { return $false } + } finally { + $null = [LingerWin32Native]::CloseHandle($token) + } + try { + $member = $false + $checked = [LingerWin32Native]::CheckTokenMembership($linked, $binary, [ref]$member) + return [bool]($checked -and $member) + } finally { + $null = [LingerWin32Native]::CloseHandle($linked) + } +} +# Administrators enabled in this token, or in the elevated token UAC links to +# it (an administrator running without elevation). Standard users lack a linked +# token, so GetTokenInformation(TokenLinkedToken) fails and returns false. function Test-Administrator { if ($null -ne $script:isAdministrator) { return $script:isAdministrator } - if ([Security.Principal.WindowsPrincipal]::new([Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { + $identity = [Security.Principal.WindowsIdentity]::GetCurrent() + if ([Security.Principal.WindowsPrincipal]::new($identity).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { $script:isAdministrator = $true return $true } $script:isAdministrator = Test-LinkedTokenAdministrator return $script:isAdministrator } -function Test-LinkedTokenAdministrator { - if (-not ('LingerLinkedToken' -as [type])) { - Add-Type -TypeDefinition @' -using System; -using System.Runtime.InteropServices; -public static class LingerLinkedToken { - [DllImport("advapi32.dll")] static extern bool OpenProcessToken(IntPtr process, uint access, out IntPtr token); - [DllImport("advapi32.dll")] static extern bool GetTokenInformation(IntPtr token, int infoClass, out IntPtr info, int length, out int returned); - [DllImport("advapi32.dll")] static extern bool CheckTokenMembership(IntPtr token, byte[] sid, out bool member); - [DllImport("kernel32.dll")] static extern IntPtr GetCurrentProcess(); - [DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr handle); - public static bool IsAdministrator(byte[] administrators) { - IntPtr token, linked; - int returned; - bool member; - if (!OpenProcessToken(GetCurrentProcess(), 0x0008, out token)) return false; - bool found = GetTokenInformation(token, 19, out linked, IntPtr.Size, out returned); - CloseHandle(token); - if (!found) return false; - bool checkedMember = CheckTokenMembership(linked, administrators, out member); - CloseHandle(linked); - return checkedMember && member; +function Get-LocalAdminMemberSids { + $sids = @{} + try { + Ensure-LingerWin32Native + $groupName = ([Security.Principal.SecurityIdentifier]::new('S-1-5-32-544')).Translate([Security.Principal.NTAccount]).Value + $slash = $groupName.IndexOf('\') + if ($slash -ge 0) { $groupName = $groupName.Substring($slash + 1) } + $resume = [IntPtr]::Zero + for ($page = 0; $page -lt 16; $page++) { + $buf = [IntPtr]::Zero + $read = [uint32]0 + $total = [uint32]0 + $status = [LingerWin32Native]::NetLocalGroupGetMembers([IntPtr]::Zero, $groupName, [uint32]0, [ref]$buf, [uint32]::MaxValue, [ref]$read, [ref]$total, [ref]$resume) + try { + if ($buf -ne [IntPtr]::Zero -and ($status -eq 0 -or $status -eq 234)) { + for ($i = 0; $i -lt [int]$read; $i++) { + $sidPtr = [Runtime.InteropServices.Marshal]::ReadIntPtr($buf, $i * [IntPtr]::Size) + if ($sidPtr -ne [IntPtr]::Zero) { + $memberSid = [Security.Principal.SecurityIdentifier]::new($sidPtr).Value + if (Test-EligibleAdminMemberSid $memberSid) { $sids[$memberSid] = $true } + } + } + } + } finally { + if ($buf -ne [IntPtr]::Zero) { $null = [LingerWin32Native]::NetApiBufferFree($buf) } + } + if ($status -ne 234) { break } + } + } catch {} + return $sids +} +function Get-CodexSandboxSids { + $sids = @{} + try { + $groupSid = ([Security.Principal.NTAccount]::new('CodexSandboxUsers')).Translate([Security.Principal.SecurityIdentifier]).Value + if ($groupSid) { $sids[$groupSid] = $true } + } catch {} + $capFiles = @() + $profile = [Environment]::GetFolderPath('UserProfile') + if ($profile) { $capFiles += [IO.Path]::Combine($profile, '.codex', 'cap_sid') } + if ($env:CODEX_HOME -and [IO.Path]::IsPathRooted($env:CODEX_HOME)) { $capFiles += [IO.Path]::Combine($env:CODEX_HOME, 'cap_sid') } + foreach ($capFile in $capFiles) { + try { + if (-not (Test-Path -LiteralPath $capFile -PathType Leaf)) { continue } + $caps = [IO.File]::ReadAllText($capFile) | ConvertFrom-Json + $values = @([string]$caps.workspace) + foreach ($roots in @($caps.workspace_by_cwd, $caps.writable_root_by_path)) { + if ($roots) { $values += @($roots.PSObject.Properties | ForEach-Object { [string]$_.Value }) } + } + foreach ($value in $values) { + if (Test-CodexCapSid $value) { $sids[$value] = $true } + } + } catch {} } + return $sids } -'@ +function Format-PrivateFailure([string]$Code, [string]$Stage, [string]$Ancestor, [string]$Sid, $Exception) { + try { + if ($Code -cmatch '^[A-Z][A-Z_]+$') { + if (-not $Ancestor -and -not $Sid) { return $Code } + $out = [ordered]@{ code = $Code } + if ($Ancestor) { $out.ancestor = $Ancestor } + if ($Sid) { $out.sid = $Sid } + return ($out | ConvertTo-Json -Compress) + } + $out = [ordered]@{ code = 'UNCHECKED' } + if ($Stage) { $out.stage = $Stage } + if ($null -ne $Exception) { + $out.errorType = $Exception.GetType().Name + $out.hresult = ('0x{0:X8}' -f $Exception.HResult) + } + return ($out | ConvertTo-Json -Compress) + } catch { + return 'UNCHECKED' } - $administrators = [Security.Principal.SecurityIdentifier]::new('S-1-5-32-544') - $binary = [byte[]]::new($administrators.BinaryLength) - $administrators.GetBinaryForm($binary, 0) - return [LingerLinkedToken]::IsAdministrator($binary) }`; -const WINDOWS_PRIVATE_CHECK_BODY = String.raw` $item = Get-Item -LiteralPath $request.path -Force - if (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -or ($item.PSIsContainer -ne ($request.kind -eq 'directory'))) { throw 'UNSAFE_TYPE' } - $acl = Get-Acl -LiteralPath $item.FullName - # What an elevated process (Run as administrator, the built-in - # Administrator) creates is owned by Administrators. For an administrator - # that owner counts as the user, as in Git for Windows: the ancestor check - # below already lets the group own and replace every parent folder, and an - # administrator can take ownership of any file, so it trusts no one new. - $owner = $acl.GetOwner([Security.Principal.SecurityIdentifier]).Value - if ($owner -ne $sid.Value -and !($owner -eq $admins -and (Test-Administrator))) { throw 'UNSAFE_OWNER' } - $parent = $item.Directory - if ($item.PSIsContainer) { $parent = $item.Parent } +const WINDOWS_PRIVATE_CHECK_BODY = String.raw` $stage = 'target' + $failAncestor = '' + $failSid = '' + $adminMembers = $null + $codexSids = $null + if ([string]$request.path -like '\\*') { throw 'UNSAFE_TYPE' } + if ($request.kind -eq 'location') { + if (Test-Path -LiteralPath $request.path) { + $item = Get-Item -LiteralPath $request.path -Force + if (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -or !$item.PSIsContainer -or !$item.Parent) { throw 'UNSAFE_TYPE' } + $stage = 'owner' + $acl = Get-Acl -LiteralPath $item.FullName + $owner = $acl.GetOwner([Security.Principal.SecurityIdentifier]).Value + if ($owner -ne $sid.Value -and !($owner -eq $admins -and (Test-Administrator))) { $failSid = $owner; throw 'UNSAFE_OWNER' } + $parent = $item.Parent + } else { + $probe = [IO.Path]::GetDirectoryName($request.path) + while ($probe -and !(Test-Path -LiteralPath $probe)) { + $next = [IO.Path]::GetDirectoryName($probe) + if ($next -eq $probe) { $probe = $null; break } + $probe = $next + } + if (!$probe) { throw 'UNSAFE_TYPE' } + $parent = Get-Item -LiteralPath $probe -Force + if (!$parent.PSIsContainer) { throw 'UNSAFE_TYPE' } + } + } else { + $item = Get-Item -LiteralPath $request.path -Force + if (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -or ($item.PSIsContainer -ne ($request.kind -eq 'directory'))) { throw 'UNSAFE_TYPE' } + $stage = 'owner' + $acl = Get-Acl -LiteralPath $item.FullName + # What an elevated process (Run as administrator, the built-in + # Administrator) creates is owned by Administrators. For an administrator + # that owner counts as the user, as in Git for Windows: the ancestor check + # below already lets the group own and replace every parent folder, and an + # administrator can take ownership of any file, so it trusts no one new. + $owner = $acl.GetOwner([Security.Principal.SecurityIdentifier]).Value + if ($owner -ne $sid.Value -and !($owner -eq $admins -and (Test-Administrator))) { $failSid = $owner; throw 'UNSAFE_OWNER' } + $parent = $item.Directory + if ($item.PSIsContainer) { $parent = $item.Parent } + } + $stage = 'ancestor' while ($parent) { - if ($parent.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw 'UNSAFE_PARENT_LINK' } + if ($parent.Attributes -band [IO.FileAttributes]::ReparsePoint) { $failAncestor = $parent.FullName; throw 'UNSAFE_PARENT_LINK' } $parentAcl = Get-Acl -LiteralPath $parent.FullName $owner = $parentAcl.GetOwner([Security.Principal.SecurityIdentifier]).Value - if ($owner -notin @($sid.Value, $system, $admins, 'S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464')) { throw 'UNSAFE_PARENT_OWNER' } + if ($owner -notin @($sid.Value, $system, $admins, $trustedInstaller) -and -not (Test-BuiltinAdminSid $owner)) { + if ($null -eq $adminMembers) { $adminMembers = Get-LocalAdminMemberSids } + if (-not $adminMembers.ContainsKey($owner)) { $failAncestor = $parent.FullName; $failSid = $owner; throw 'UNSAFE_PARENT_OWNER' } + } # An ancestor is unsafe when another account can put a different folder # where the private one is. Delete lets its holder rename or remove the # folder that grants it; a volume root can be neither, and its stock ACL @@ -81,11 +248,22 @@ const WINDOWS_PRIVATE_CHECK_BODY = String.raw` $item = Get-Item -LiteralPath $r # InheritOnly ACEs do not authorize mutation of this ancestor. They are # still checked below when present on the private target itself. if ($rule.PropagationFlags -band [Security.AccessControl.PropagationFlags]::InheritOnly) { continue } - if ($rule.AccessControlType -eq 'Allow' -and $rule.IdentityReference.Value -notin @($sid.Value, $system, $admins, 'S-1-3-0', 'S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464') -and - ($rule.FileSystemRights -band [Security.AccessControl.FileSystemRights]$replace)) { throw 'UNSAFE_PARENT_ACCESS' } + if ($rule.AccessControlType -ne 'Allow') { continue } + if (-not ($rule.FileSystemRights -band [Security.AccessControl.FileSystemRights]$replace)) { continue } + $ruleSid = $rule.IdentityReference.Value + if ($ruleSid -in @($sid.Value, $system, $admins, 'S-1-3-0', 'S-1-3-4', $trustedInstaller) -or (Test-BuiltinAdminSid $ruleSid)) { continue } + if ($null -eq $adminMembers) { $adminMembers = Get-LocalAdminMemberSids } + if ($adminMembers.ContainsKey($ruleSid)) { continue } + if ($null -eq $codexSids) { $codexSids = Get-CodexSandboxSids } + if ($codexSids.ContainsKey($ruleSid)) { continue } + $failAncestor = $parent.FullName + $failSid = $ruleSid + throw 'UNSAFE_PARENT_ACCESS' } $parent = $parent.Parent } + if ($request.kind -ne 'location') { + $stage = 'repair' if ($request.repair) { # Only the DACL that repair would install can skip propagation. Compare # the rules because Windows may add flags to the persisted descriptor. @@ -112,30 +290,39 @@ const WINDOWS_PRIVATE_CHECK_BODY = String.raw` $item = Get-Item -LiteralPath $r $acl = Get-Acl -LiteralPath $item.FullName } } + $stage = 'verify' if ($request.kind -eq 'directory' -and !$acl.AreAccessRulesProtected) { throw 'INHERITED_ACCESS' } $currentAllowed = $false foreach ($rule in $acl.GetAccessRules($true, $true, [Security.Principal.SecurityIdentifier])) { if ($rule.AccessControlType -eq 'Allow') { - if ($rule.IdentityReference.Value -notin @($sid.Value, $system)) { throw 'SHARED_ACCESS' } + if ($rule.IdentityReference.Value -notin @($sid.Value, $system)) { $failSid = $rule.IdentityReference.Value; throw 'SHARED_ACCESS' } if ($rule.IdentityReference.Value -eq $sid.Value) { $currentAllowed = $true } } } - if (!$currentAllowed) { throw 'MISSING_OWNER_ACCESS' }`; + if (!$currentAllowed) { throw 'MISSING_OWNER_ACCESS' } + }`; // The program is fixed. Only a path and operation travel over stdin; no file // contents, user-controlled PowerShell, or credentials appear in argv/output. export const WINDOWS_PRIVATE_SCRIPT = ` +if ("$($ExecutionContext.SessionState.LanguageMode)" -ne 'FullLanguage') { + Write-Output ('{"code":"UNCHECKED","stage":"language_mode","errorType":"' + "$($ExecutionContext.SessionState.LanguageMode)" + '"}') + exit 1 +} ${WINDOWS_PRIVATE_PREAMBLE} +$stage = 'init' +$failAncestor = '' +$failSid = '' try { $request = [Console]::In.ReadToEnd() | ConvertFrom-Json $sid = [Security.Principal.WindowsIdentity]::GetCurrent().User - $system = 'S-1-5-18'; $admins = 'S-1-5-32-544' + $system = 'S-1-5-18'; $admins = 'S-1-5-32-544'; $trustedInstaller = '${TRUSTED_INSTALLER_SID}' ${WINDOWS_PRIVATE_CHECK_BODY} exit 0 } catch { - # Only this program's own reason codes leave it; never a system message. - $code = [string]$_.Exception.Message - if ($code -cmatch '^[A-Z][A-Z_]+$') { [Console]::Out.Write($code) } + # Only allowlisted reason codes, offending ancestor/SID, or exception + # type/HRESULT leave the script; never raw system error prose. + [Console]::Out.Write((Format-PrivateFailure ([string]$_.Exception.Message) $stage $failAncestor $failSid $_.Exception)) exit 1 } `; @@ -146,21 +333,26 @@ const WORKER_ERR = "__LINGER_ACL_ERR__:"; // Reuses one PowerShell process across sequential ACL checks instead of paying // a full .NET CLR startup (~1s) for every private directory and file. export const WINDOWS_PRIVATE_WORKER_SCRIPT = ` +if ("$($ExecutionContext.SessionState.LanguageMode)" -ne 'FullLanguage') { + Write-Output ('${WORKER_ERR}{"code":"UNCHECKED","stage":"language_mode","errorType":"' + "$($ExecutionContext.SessionState.LanguageMode)" + '"}') + exit 1 +} ${WINDOWS_PRIVATE_PREAMBLE} $sid = [Security.Principal.WindowsIdentity]::GetCurrent().User -$system = 'S-1-5-18'; $admins = 'S-1-5-32-544' +$system = 'S-1-5-18'; $admins = 'S-1-5-32-544'; $trustedInstaller = '${TRUSTED_INSTALLER_SID}' while ($true) { $line = [Console]::In.ReadLine() if ($null -eq $line) { break } if ($line.Length -eq 0) { continue } + $stage = 'init' + $failAncestor = '' + $failSid = '' try { $request = $line | ConvertFrom-Json ${WINDOWS_PRIVATE_CHECK_BODY} [Console]::Out.WriteLine('${WORKER_OK}') } catch { - $code = [string]$_.Exception.Message - if ($code -cmatch '^[A-Z][A-Z_]+$') { [Console]::Out.WriteLine('${WORKER_ERR}' + $code) } - else { [Console]::Out.WriteLine('${WORKER_ERR}UNCHECKED') } + [Console]::Out.WriteLine('${WORKER_ERR}' + (Format-PrivateFailure ([string]$_.Exception.Message) $stage $failAncestor $failSid $_.Exception)) } [Console]::Out.Flush() } @@ -169,9 +361,105 @@ ${WINDOWS_PRIVATE_CHECK_BODY} const REQUEST_TIMEOUT_MS = 30_000; const WORKER_IDLE_MS = 5_000; +const SID_PATTERN = /^S-1-\d+(?:-\d+)*$/; +const STAGE_PATTERN = /^[a-z_]{1,32}$/; +const ERROR_TYPE_PATTERN = /^[A-Za-z0-9_.]{1,80}$/; +const HRESULT_PATTERN = /^0x[0-9A-Fa-f]{8}$/; +const WORKER_DIAGNOSTIC_PATTERN = /^[a-z0-9_:=., -]{1,160}$/i; + +export interface ParsedWindowsPrivateFailure { + readonly reason: WindowsPrivateReason; + readonly ancestor?: string; + readonly sid?: string; + readonly diagnostic?: string; +} + +function sanitizeAncestor(value: unknown): string | undefined { + if (typeof value !== "string") return undefined; + const trimmed = value.trim(); + if (!trimmed || trimmed.length > 512) return undefined; + for (let i = 0; i < trimmed.length; i++) { + const code = trimmed.charCodeAt(i); + if (code < 0x20 || code === 0x7f) return undefined; + } + return trimmed; +} + +/** + * Parses the fixed ACL script's structured stdout and worker lifecycle + * diagnostics, admitting only allowlisted reason codes, validated SIDs, + * offending ancestor paths, and sanitized exception/worker tokens. + */ +export function parseWindowsPrivateFailure( + stdout: string, + workerDiagnostic?: string, +): ParsedWindowsPrivateFailure { + const trimmed = stdout.trim(); + if (Object.hasOwn(WINDOWS_PRIVATE_REASONS, trimmed)) { + return { reason: trimmed as WindowsPrivateReason }; + } + if (trimmed.startsWith("{")) { + try { + const parsed = JSON.parse(trimmed) as Record; + const rawCode = typeof parsed.code === "string" ? parsed.code.trim() : ""; + const reason: WindowsPrivateReason = Object.hasOwn( + WINDOWS_PRIVATE_REASONS, + rawCode, + ) + ? (rawCode as WindowsPrivateReason) + : "UNCHECKED"; + const sid = + typeof parsed.sid === "string" && SID_PATTERN.test(parsed.sid) + ? parsed.sid + : undefined; + const ancestor = reason.startsWith("UNSAFE_PARENT_") + ? sanitizeAncestor(parsed.ancestor) + : undefined; + const diagParts: string[] = []; + if ( + typeof parsed.stage === "string" && + STAGE_PATTERN.test(parsed.stage) + ) { + diagParts.push(`stage=${parsed.stage}`); + } + if ( + typeof parsed.errorType === "string" && + ERROR_TYPE_PATTERN.test(parsed.errorType) + ) { + diagParts.push(`type=${parsed.errorType}`); + } + if ( + typeof parsed.hresult === "string" && + HRESULT_PATTERN.test(parsed.hresult) + ) { + diagParts.push(`hresult=${parsed.hresult}`); + } + const diagnostic = + diagParts.length > 0 ? diagParts.join(", ") : undefined; + return { + reason, + ...(ancestor ? { ancestor } : {}), + ...(sid ? { sid } : {}), + ...(diagnostic ? { diagnostic } : {}), + }; + } catch { + // Fall through to fail-closed UNCHECKED with sanitized worker info. + } + } + const diagnostic = + workerDiagnostic && WORKER_DIAGNOSTIC_PATTERN.test(workerDiagnostic.trim()) + ? workerDiagnostic.trim() + : undefined; + return { + reason: "UNCHECKED", + ...(diagnostic ? { diagnostic } : {}), + }; +} + interface WorkerResponse { code: number; stdout: string; + workerDiagnostic?: string; } interface Refable { @@ -183,8 +471,11 @@ interface WorkerProcess extends Refable { stdin: NodeJS.WritableStream & Refable & { end(): void }; stdout: NodeJS.ReadableStream & Refable; kill(): void; - on(event: "close", listener: () => void): unknown; - on(event: "error", listener: () => void): unknown; + on( + event: "close", + listener: (code?: number | null, signal?: NodeJS.Signals | null) => void, + ): unknown; + on(event: "error", listener: (error?: Error) => void): unknown; } export interface WindowsPrivateWorkerOptions { @@ -227,6 +518,13 @@ function spawnDefaultWorker(): WorkerProcess { ); } +function sanitizeErrnoCode(error: unknown): string { + const code = (error as NodeJS.ErrnoException | undefined)?.code; + return typeof code === "string" && /^[A-Za-z0-9_]{1,32}$/.test(code) + ? code + : "unknown"; +} + export function createWindowsPrivateClient( options: WindowsPrivateWorkerOptions = {}, ) { @@ -251,7 +549,7 @@ export function createWindowsPrivateClient( } }; - const reset = (kill: boolean) => { + const reset = (kill: boolean, workerDiagnostic?: string) => { clearIdle(); const current = active; if (!current) return; @@ -266,7 +564,11 @@ export function createWindowsPrivateClient( } catch { // The worker has already exited. } - pending?.({ code: 1, stdout: "" }); + pending?.({ + code: 1, + stdout: "", + ...(workerDiagnostic ? { workerDiagnostic } : {}), + }); }; const scheduleIdle = () => { @@ -283,9 +585,6 @@ export function createWindowsPrivateClient( return active; } const child = spawnWorker(); - child.stdin.on("error", () => { - if (active?.child === child) reset(true); - }); const lines = createInterface({ input: child.stdout }); const onExit = () => { try { @@ -300,11 +599,15 @@ export function createWindowsPrivateClient( pending: undefined as ((response: WorkerResponse) => void) | undefined, onExit, }; + child.stdin.on("error", (error?: Error) => { + if (active?.child === child) + reset(true, `worker=stdin:${sanitizeErrnoCode(error)}`); + }); lines.on("line", (raw) => { const line = raw.trim().replace(/^\ufeff/, ""); const pending = instance.pending; if (!pending) { - if (active === instance) reset(true); + if (active === instance) reset(true, "worker=desync"); return; } instance.pending = undefined; @@ -317,14 +620,27 @@ export function createWindowsPrivateClient( return; } // Unexpected output indicates stream desynchronization; fail closed. - if (active === instance) reset(true); - pending({ code: 1, stdout: "" }); + if (active === instance) reset(true, "worker=desync"); + pending({ + code: 1, + stdout: "", + workerDiagnostic: "worker=desync", + }); }); - child.on("close", () => { - if (active === instance) reset(false); + child.on("close", (code, signal) => { + if (active === instance) { + const diag = + typeof code === "number" + ? `worker=exit:${code}` + : signal + ? `worker=signal:${signal}` + : "worker=closed"; + reset(false, diag); + } }); - child.on("error", () => { - if (active === instance) reset(true); + child.on("error", (error) => { + if (active === instance) + reset(true, `worker=spawn:${sanitizeErrnoCode(error)}`); }); process.once("exit", onExit); active = instance; @@ -348,16 +664,21 @@ export function createWindowsPrivateClient( resolve(response); }; const timer = setTimeout(() => { - if (active === instance) reset(true); - finish({ code: 1, stdout: "" }); + if (active === instance) reset(true, "worker=timeout"); + finish({ + code: 1, + stdout: "", + workerDiagnostic: "worker=timeout", + }); }, timeoutMs); timer.unref(); instance.pending = finish; try { instance.child.stdin.write(`${payload}\n`); - } catch { - if (active === instance) reset(true); - finish({ code: 1, stdout: "" }); + } catch (error) { + const diag = `worker=write:${sanitizeErrnoCode(error)}`; + if (active === instance) reset(true, diag); + finish({ code: 1, stdout: "", workerDiagnostic: diag }); } }), ); @@ -378,19 +699,30 @@ export function closeWindowsPrivateWorker(): void { defaultWorker.close(); } -function privatePathError(file: string, stdout: string): Error { - const reason: WindowsPrivateReason = Object.hasOwn( - WINDOWS_PRIVATE_REASONS, - stdout.trim(), - ) - ? (stdout.trim() as WindowsPrivateReason) - : "UNCHECKED"; +function privatePathError(file: string, response: WorkerResponse): Error { + const parsed = parseWindowsPrivateFailure( + response.stdout, + response.workerDiagnostic, + ); const target = path.resolve(file); + const details: string[] = []; + if (parsed.ancestor) details.push(`ancestor: ${parsed.ancestor}`); + if (parsed.sid) details.push(`sid: ${parsed.sid}`); + if (parsed.reason === "UNCHECKED" && parsed.diagnostic) + details.push(parsed.diagnostic); + const detailSuffix = details.length > 0 ? ` (${details.join(", ")})` : ""; return Object.assign( new Error( - `Windows private path validation failed: ${target} ${WINDOWS_PRIVATE_REASONS[reason]}. Use a current-user owned local directory without links or shared access.`, + `Windows private path validation failed: ${target} ${WINDOWS_PRIVATE_REASONS[parsed.reason]}${detailSuffix}. Use a current-user owned local directory without links or shared access.`, ), - { code: WINDOWS_PRIVATE_PATH_UNSAFE, reason, path: target }, + { + code: WINDOWS_PRIVATE_PATH_UNSAFE, + reason: parsed.reason, + path: target, + ...(parsed.ancestor ? { ancestor: parsed.ancestor } : {}), + ...(parsed.sid ? { sid: parsed.sid } : {}), + ...(parsed.diagnostic ? { diagnostic: parsed.diagnostic } : {}), + }, ); } @@ -401,7 +733,35 @@ export async function windowsPrivatePath( run?: typeof runProcess, ): Promise { const payload = JSON.stringify({ path: path.resolve(file), kind, repair }); - const result = run + const result: WorkerResponse = run + ? await run( + powershellPath(), + windowsPowerShellArguments(WINDOWS_PRIVATE_SCRIPT), + { + input: payload, + timeoutMs: REQUEST_TIMEOUT_MS, + }, + ) + : await defaultWorker.execute(payload); + if (result.code !== 0) throw privatePathError(file, result); +} + +/** + * Checks whether a candidate Windows install or state directory can host + * private state without creating it or changing any ACLs. When the directory + * already exists, verifies its type, owner, and ancestors; otherwise verifies + * the nearest existing ancestor and every directory above it. + */ +export async function windowsPrivateLocation( + directory: string, + run?: typeof runProcess, +): Promise { + const payload = JSON.stringify({ + path: path.resolve(directory), + kind: "location", + repair: false, + }); + const result: WorkerResponse = run ? await run( powershellPath(), windowsPowerShellArguments(WINDOWS_PRIVATE_SCRIPT), @@ -411,8 +771,9 @@ export async function windowsPrivatePath( }, ) : await defaultWorker.execute(payload); - if (result.code !== 0) throw privatePathError(file, result.stdout); + if (result.code !== 0) throw privatePathError(directory, result); } + /** The code of an error from windowsPrivatePath; its reason says why. */ export const WINDOWS_PRIVATE_PATH_UNSAFE = "WINDOWS_PRIVATE_PATH_UNSAFE"; // The ACL program's reason codes, worded for the error message.