The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu
Go agent-ai-cliagent-harnessesagent-securitybrowser-extensionciclaude-codecloudcodexcursordetection-engineeringjevknowledge-basememorymobile-device-managementobservabilitysecuritysecurity-information-and-event-managementsecurity-toolstelemetrytraces
Windows restricted mode: replace held-open files, and close every file in the log directory
Claudec1d80f376d75
diff --git a/cli/beacon/internal/endpoint/sysacl/restricted_windows.go b/cli/beacon/internal/endpoint/sysacl/restricted_windows.goindex 5146e627..4e2ee2aa 100644--- a/cli/beacon/internal/endpoint/sysacl/restricted_windows.go+++ b/cli/beacon/internal/endpoint/sysacl/restricted_windows.go@@ -14,11 +14,17 @@ import ()// SecureRestrictedLogDir gives the system log directory the restricted mode's protected DACL and-// resets its log family to match, the way SecureLogDir does for the shared mode: dir is created if-// missing and replaced if it is a link; every link among its direct children, and every file of the-// log family hard-linked elsewhere, is removed; every other file of the family gets Administrators-// ownership and exactly what a new file inherits, and the lock gets RestrictedLockDACL. Anything-// else in the directory keeps its own security.+// resets everything in it to match. dir is created if missing and replaced if it is a link. Below+// it, every link is removed, and so is every file of the log family that is hard-linked elsewhere;+// every other file and directory gets Administrators ownership and exactly what a new one there+// inherits, and the lock gets RestrictedLockDACL. A file outside the log family that is hard-linked+// elsewhere is left alone, since changing its security would change the other file's too.+//+// Everything, not only the log family: every account holds the right to bypass traverse checking,+// so a file that kept a grant from the shared mode -- the inventory log beside the runtime log, an+// operator's own file -- could still be opened by its full path once the directory itself is+// closed. In the shared mode files in this directory grant INTERACTIVE read and write, and that has+// to go with the mode.//// This changes what a new open is granted. A handle an account opened while the log was shared// keeps the access it was opened with, so the caller also replaces each file of the family with a@@ -29,53 +35,67 @@ func SecureRestrictedLogDir(dir, base, readersSID string) error {if err != nil {return err}- err = setSecurity(h, true, RestrictedLogDirDACL(readersSID))+ dacl := RestrictedLogDirDACL(readersSID)+ err = setSecurity(h, true, dacl)windows.CloseHandle(h)if err != nil {return fmt.Errorf("secure %s: %w", dir, err)}- entries, err := os.ReadDir(dir)+ return resetRestricted(dir, dacl, base)+ })+}++// resetRestricted gives everything below dir, which carries dacl, what it would inherit. base names+// the log family in the top directory and is empty below it.+func resetRestricted(dir string, dacl []ACE, base string) error {+ entries, err := os.ReadDir(dir)+ if err != nil {+ return err+ }+ var errs []error+ for _, entry := range entries {+ child := filepath.Join(dir, entry.Name())+ family := base != "" && IsLogFamily(entry.Name(), base)+ h, info, err := openNoFollow(child)+ if errors.Is(err, fs.ErrNotExist) {+ continue+ }if err != nil {- return err+ errs = append(errs, fmt.Errorf("open %s: %w", child, err))+ continue}- inherited := InheritedDACL(RestrictedLogDirDACL(readersSID), false)- var errs []error- for _, entry := range entries {- child := filepath.Join(dir, entry.Name())- family := IsLogFamily(entry.Name(), base)- h, info, err := openNoFollow(child)- if errors.Is(err, fs.ErrNotExist) {- continue- }- if err != nil {- errs = append(errs, fmt.Errorf("open %s: %w", child, err))- continue+ link := info.FileAttributes&windows.FILE_ATTRIBUTE_REPARSE_POINT != 0+ isDir := info.FileAttributes&windows.FILE_ATTRIBUTE_DIRECTORY != 0+ hardLinked := !isDir && info.NumberOfLinks > 1+ var childDACL []ACE+ switch {+ case link || (family && hardLinked):+ windows.CloseHandle(h)+ if err := os.Remove(child); err != nil && !errors.Is(err, fs.ErrNotExist) {+ errs = append(errs, fmt.Errorf("remove the link %s: %w", child, err))}- link := info.FileAttributes&windows.FILE_ATTRIBUTE_REPARSE_POINT != 0- dirEntry := info.FileAttributes&windows.FILE_ATTRIBUTE_DIRECTORY != 0- hardLinked := !dirEntry && info.NumberOfLinks > 1- switch {- case link || (family && hardLinked):- windows.CloseHandle(h)- if err := os.Remove(child); err != nil && !errors.Is(err, fs.ErrNotExist) {- errs = append(errs, fmt.Errorf("remove the link %s: %w", child, err))- }- case family && !dirEntry && strings.EqualFold(entry.Name(), base+".lock"):- if err := setSecurity(h, true, RestrictedLockDACL()); err != nil {- errs = append(errs, fmt.Errorf("secure %s: %w", child, err))- }- windows.CloseHandle(h)- case family && !dirEntry:- if err := setSecurity(h, false, inherited); err != nil {- errs = append(errs, fmt.Errorf("secure %s: %w", child, err))- }- windows.CloseHandle(h)- default:- windows.CloseHandle(h)+ continue+ case hardLinked:+ windows.CloseHandle(h)+ continue+ case family && strings.EqualFold(entry.Name(), base+".lock"):+ err = setSecurity(h, true, RestrictedLockDACL())+ default:+ childDACL = InheritedDACL(dacl, isDir)+ err = setSecurity(h, false, childDACL)+ }+ windows.CloseHandle(h)+ if err != nil {+ errs = append(errs, fmt.Errorf("secure %s: %w", child, err))+ continue+ }+ if isDir {+ if err := resetRestricted(child, childDACL, ""); err != nil {+ errs = append(errs, err)}}- return errors.Join(errs...)- })+ }+ return errors.Join(errs...)}// SecureRestrictedLock gives the lock at path RestrictedLockDACL, without following a link. The@@ -95,8 +115,9 @@ func SecureRestrictedLock(path string) error {})}-// InspectRestrictedLogDir reports every way the directory and its log family let an account other-// than SYSTEM, Administrators and the readers group reach the log (see RestrictedProblems). It reads+// InspectRestrictedLogDir reports every way the directory, and anything directly in it, lets an+// account other than SYSTEM, Administrators and the readers group reach the log (see+// RestrictedProblems). It reads// security only; what it cannot open -- an ordinary user cannot open anything there -- is reported// as an error rather than as a problem.func InspectRestrictedLogDir(dir, base, readersSID string) ([]string, error) {@@ -118,10 +139,8 @@ func InspectRestrictedLogDir(dir, base, readersSID string) ([]string, error) {if err != nil {return problems, err}+ // Every entry, not only the log family, for the reason SecureRestrictedLogDir resets them all.for _, entry := range entries {- if !IsLogFamily(entry.Name(), base) {- continue- }child := filepath.Join(dir, entry.Name())fobj, link, err := readObject(child)if errors.Is(err, fs.ErrNotExist) {diff --git a/cli/beacon/internal/endpoint/sysacl/restricted_windows_test.go b/cli/beacon/internal/endpoint/sysacl/restricted_windows_test.goindex 310d0d07..2b3fc980 100644--- a/cli/beacon/internal/endpoint/sysacl/restricted_windows_test.go+++ b/cli/beacon/internal/endpoint/sysacl/restricted_windows_test.go@@ -13,7 +13,7 @@ import (const backupOperators = "S-1-5-32-551"// A shared log directory, restricted, then shared again: each step reads back exactly as that-// mode sets it, and a file outside the log family is left alone throughout.+// mode sets it.func TestRestrictingAndSharingTheLogDirectory(t *testing.T) {requireElevated(t)dir := filepath.Join(t.TempDir(), "logs")@@ -25,7 +25,12 @@ func TestRestrictingAndSharingTheLogDirectory(t *testing.T) {t.Fatal(err)}}- notesBefore := mustRead(t, filepath.Join(dir, "operator-notes.txt"))+ if err := os.MkdirAll(filepath.Join(dir, "sub"), 0o755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(dir, "sub", "inside.txt"), []byte("x"), 0o666); err != nil {+ t.Fatal(err)+ }if err := SecureRestrictedLogDir(dir, "runtime.jsonl", backupOperators); err != nil {t.Fatalf("SecureRestrictedLogDir: %v", err)@@ -53,8 +58,15 @@ func TestRestrictingAndSharingTheLogDirectory(t *testing.T) {if lock := mustRead(t, filepath.Join(dir, "runtime.jsonl.lock")); !lock.Protected || !reflect.DeepEqual(lock.DACL, RestrictedLockDACL()) {t.Errorf("the lock carries %+v (protected %v), want only SYSTEM and Administrators", lock.DACL, lock.Protected)}- if notesAfter := mustRead(t, filepath.Join(dir, "operator-notes.txt")); !reflect.DeepEqual(notesBefore, notesAfter) {- t.Errorf("a file outside the log family was changed: %+v -> %+v", notesBefore, notesAfter)+ // Every other file and directory there is reset too: everyone may bypass traverse checking, so+ // a file that kept the shared mode's grant could still be opened by its full path.+ for _, name := range []string{"operator-notes.txt", filepath.Join("sub", "inside.txt")} {+ if problems := RestrictedProblems(mustRead(t, filepath.Join(dir, name)), backupOperators, false); len(problems) > 0 {+ t.Errorf("%s kept a grant from the shared mode: %v", name, problems)+ }+ }+ if problems := RestrictedProblems(mustRead(t, filepath.Join(dir, "sub")), backupOperators, false); len(problems) > 0 {+ t.Errorf("a subdirectory kept a grant from the shared mode: %v", problems)}// The collector re-creates the log on rotation: the new file inherits the restricted entries.diff --git a/cli/beacon/internal/endpoint/writer/logaccess_windows.go b/cli/beacon/internal/endpoint/writer/logaccess_windows.goindex b3fc4943..61a6715e 100644--- a/cli/beacon/internal/endpoint/writer/logaccess_windows.go+++ b/cli/beacon/internal/endpoint/writer/logaccess_windows.go@@ -12,6 +12,7 @@ import ("path/filepath""strings""time"+ "unsafe""golang.org/x/sys/windows"@@ -158,7 +159,7 @@ func replaceWithCopy(path string) error {}deadline := time.Now().Add(replaceWait)for {- err := os.Rename(tmpName, path)+ err := renameReplacing(tmpName, path)if err == nil {return nil}@@ -170,6 +171,59 @@ func replaceWithCopy(path string) error {}}+// fileRenameInfo is FILE_RENAME_INFO with its Flags member (FileRenameInfoEx).+type fileRenameInfo struct {+ Flags uint32+ RootDirectory windows.Handle+ FileNameLength uint32+ FileName [1]uint16+}++// renameReplacing renames from over to with POSIX semantics. MoveFileEx, which os.Rename uses,+// refuses to replace a file that is open at all, even by a process that allowed others to delete+// it; with POSIX semantics such a file is replaced and its handles stay on the old file, which is+// exactly what cuts off a handle opened while the log was shared. A file open without sharing+// delete still cannot be replaced, and that error is returned. File systems without POSIX renames+// fall back to os.Rename.+func renameReplacing(from, to string) error {+ p, err := windows.UTF16PtrFromString(from)+ if err != nil {+ return err+ }+ h, err := windows.CreateFile(p, windows.DELETE|windows.SYNCHRONIZE,+ windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE|windows.FILE_SHARE_DELETE, nil,+ windows.OPEN_EXISTING, windows.FILE_FLAG_OPEN_REPARSE_POINT, 0)+ if err != nil {+ return &os.LinkError{Op: "rename", Old: from, New: to, Err: err}+ }+ closed := false+ defer func() {+ if !closed {+ windows.CloseHandle(h)+ }+ }()+ name, err := windows.UTF16FromString(to)+ if err != nil {+ return err+ }+ size := int(unsafe.Offsetof(fileRenameInfo{}.FileName)) + len(name)*2+ buf := make([]uint64, (size+7)/8) // FILE_RENAME_INFO needs the alignment of its handle+ info := (*fileRenameInfo)(unsafe.Pointer(&buf[0]))+ info.Flags = windows.FILE_RENAME_REPLACE_IF_EXISTS | windows.FILE_RENAME_POSIX_SEMANTICS+ info.FileNameLength = uint32((len(name) - 1) * 2)+ copy(unsafe.Slice(&info.FileName[0], len(name)), name)+ err = windows.SetFileInformationByHandle(h, windows.FileRenameInfoEx, (*byte)(unsafe.Pointer(&buf[0])), uint32(size))+ if errors.Is(err, windows.ERROR_INVALID_PARAMETER) || errors.Is(err, windows.ERROR_NOT_SUPPORTED) || errors.Is(err, windows.ERROR_INVALID_FUNCTION) {+ windows.CloseHandle(h)+ closed = true+ return os.Rename(from, to)+ }+ if err != nil {+ return &os.LinkError{Op: "rename", Old: from, New: to, Err: err}+ }+ return nil+}+// copyInto copies the file at path into dst, closing its own handle before returning: Go opens// files without sharing delete, so a handle left open would block the rename that follows.func copyInto(dst *os.File, path string) error {