Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 13 additions & 8 deletions apps/computer/local-daemon/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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")
Expand All @@ -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 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down Expand Up @@ -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)
}
})
}
}
Expand Down Expand Up @@ -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) {
Expand Down
Loading