Skip to content

The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu

Windows: the restricted log access mode's ACL, marker and readers group

Claude314156761742
diff --git a/cli/beacon/internal/endpoint/loggroup/loggroup_other.go b/cli/beacon/internal/endpoint/loggroup/loggroup_other.go
index afe14982..087583dc 100644
--- a/cli/beacon/internal/endpoint/loggroup/loggroup_other.go
+++ b/cli/beacon/internal/endpoint/loggroup/loggroup_other.go
@@ -1,4 +1,4 @@
-//go:build !linux && !darwin
+//go:build !linux && !darwin && !windows
package loggroup
diff --git a/cli/beacon/internal/endpoint/loggroup/loggroup_windows.go b/cli/beacon/internal/endpoint/loggroup/loggroup_windows.go
new file mode 100644
index 00000000..40486acc
--- /dev/null
+++ b/cli/beacon/internal/endpoint/loggroup/loggroup_windows.go
@@ -0,0 +1,59 @@
+//go:build windows
+
+package loggroup
+
+import (
+ "errors"
+ "fmt"
+ "path/filepath"
+
+ "golang.org/x/sys/windows"
+)
+
+// On Windows the readers group is a local group. It has a SID rather than a gid: lookup reports
+// gid 0 when the group exists, and SID gives what the log directory's ACL names.
+
+// lookupLocal resolves name on this computer only. A bare name would also match a domain group of
+// the same name on a domain-joined machine, which a domain administrator rather than this machine's
+// controls, so the name is qualified with the computer's own and must resolve to a local group.
+var lookupLocal = func(name string) (sid string, found bool, err error) {
+ computer, err := windows.ComputerName()
+ if err != nil {
+ return "", false, fmt.Errorf("read the computer name: %w", err)
+ }
+ s, _, accType, err := windows.LookupSID("", computer+`\`+name)
+ if err != nil {
+ if errors.Is(err, windows.ERROR_NONE_MAPPED) {
+ return "", false, nil
+ }
+ return "", false, fmt.Errorf("look up %s: %w", name, err)
+ }
+ if accType != windows.SidTypeAlias {
+ return "", false, fmt.Errorf("%s exists on this computer but is not a local group", name)
+ }
+ return s.String(), true, nil
+}
+
+func lookup(name string) (int, bool, error) {
+ _, found, err := lookupLocal(name)
+ return 0, found, err
+}
+
+// SID returns the local group's SID and whether it exists.
+func SID(name string) (string, bool, error) {
+ if err := validName(name); err != nil {
+ return "", false, err
+ }
+ return lookupLocal(name)
+}
+
+// create adds the local group with net.exe from the system directory, never one found on PATH.
+func create(name string) error {
+ system, err := windows.GetSystemDirectory()
+ if err != nil {
+ return fmt.Errorf("find the system directory: %w", err)
+ }
+ _, err = run(filepath.Join(system, "net.exe"), "localgroup", name, "/add",
+ "/comment:Accounts that may read the Beacon system runtime log")
+ return err
+}
diff --git a/cli/beacon/internal/endpoint/loggroup/loggroup_windows_test.go b/cli/beacon/internal/endpoint/loggroup/loggroup_windows_test.go
new file mode 100644
index 00000000..3c3f9900
--- /dev/null
+++ b/cli/beacon/internal/endpoint/loggroup/loggroup_windows_test.go
@@ -0,0 +1,89 @@
+//go:build windows
+
+package loggroup
+
+import (
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "golang.org/x/sys/windows"
+)
+
+// fakeAccounts stands in for the local account database: lookups answer from groups, and net.exe
+// adds to it.
+func fakeAccounts(t *testing.T, groups map[string]string) *[]string {
+ t.Helper()
+ var calls []string
+ prevLookup, prevRun := lookupLocal, run
+ t.Cleanup(func() { lookupLocal, run = prevLookup, prevRun })
+ lookupLocal = func(name string) (string, bool, error) {
+ sid, ok := groups[name]
+ return sid, ok, nil
+ }
+ run = func(path string, args ...string) (string, error) {
+ calls = append(calls, filepath.Base(path)+" "+strings.Join(args, " "))
+ if !strings.EqualFold(filepath.Base(path), "net.exe") || !filepath.IsAbs(path) {
+ t.Fatalf("ran %s; want net.exe from the system directory", path)
+ }
+ groups[args[1]] = "S-1-5-21-1-2-3-1500"
+ return "", nil
+ }
+ return &calls
+}
+
+func TestEnsureCreatesTheLocalGroupOnce(t *testing.T) {
+ groups := map[string]string{}
+ calls := fakeAccounts(t, groups)
+ _, created, err := Ensure(Name)
+ if err != nil || !created {
+ t.Fatalf("Ensure = created %v, %v", created, err)
+ }
+ if len(*calls) != 1 || !strings.HasPrefix((*calls)[0], "net.exe localgroup "+Name+" /add") {
+ t.Fatalf("calls = %q", *calls)
+ }
+ sid, found, err := SID(Name)
+ if err != nil || !found || sid != "S-1-5-21-1-2-3-1500" {
+ t.Fatalf("SID = %q, %v, %v", sid, found, err)
+ }
+ if _, created, err := Ensure(Name); err != nil || created {
+ t.Fatalf("second Ensure = created %v, %v; want the existing group kept", created, err)
+ }
+ if len(*calls) != 1 {
+ t.Fatalf("net.exe ran again: %q", *calls)
+ }
+}
+
+// The real account database: a group that does not exist is not found, and Ensure creates a real
+// local group that lookups then find, once. Needs an elevated shell, which the Windows CI runner is.
+func TestEnsureAgainstThisMachine(t *testing.T) {
+ if _, found, err := lookupLocal("beacon-test-no-such-group"); err != nil || found {
+ t.Fatalf("missing group: found %v, %v", found, err)
+ }
+ token, err := windows.OpenCurrentProcessToken()
+ if err != nil {
+ t.Skip(err)
+ }
+ elevated := token.IsElevated()
+ token.Close()
+ if !elevated {
+ t.Skip("creating a local group needs an elevated shell")
+ }
+ name := fmt.Sprintf("beacon-test-%d", os.Getpid())
+ t.Cleanup(func() {
+ system, _ := windows.GetSystemDirectory()
+ _, _ = run(filepath.Join(system, "net.exe"), "localgroup", name, "/delete")
+ })
+ if _, created, err := Ensure(name); err != nil || !created {
+ t.Fatalf("Ensure = created %v, %v", created, err)
+ }
+ sid, found, err := SID(name)
+ if err != nil || !found || !strings.HasPrefix(sid, "S-1-5-21-") {
+ t.Fatalf("SID(%s) = %q, %v, %v; want a local account-domain SID", name, sid, found, err)
+ }
+ if _, created, err := Ensure(name); err != nil || created {
+ t.Fatalf("second Ensure = created %v, %v", created, err)
+ }
+}
diff --git a/cli/beacon/internal/endpoint/sysacl/restricted.go b/cli/beacon/internal/endpoint/sysacl/restricted.go
new file mode 100644
index 00000000..79acd44c
--- /dev/null
+++ b/cli/beacon/internal/endpoint/sysacl/restricted.go
@@ -0,0 +1,84 @@
+package sysacl
+
+import (
+ "fmt"
+ "strings"
+)
+
+// The restricted log access mode (`--log-access restricted`) on Windows.
+//
+// In the shared mode the log directory lets INTERACTIVE read and write the data of every file in
+// it, so any logged-on user can read every other user's prompts and command output, and overwrite
+// bytes already in the log. In the restricted mode the collector, running as SYSTEM, is the only
+// writer: hooks hand it their events over the local ingest pipe (package localingest), and the
+// directory grants ordinary users nothing at all. SYSTEM and Administrators keep full control, and
+// a local readers group (the beacon-log group, which install creates) may read, for log shippers
+// that do not run as SYSTEM and for people who should see every user's sessions.
+//
+// The lock is closer still: SYSTEM and Administrators only. Taking LockFileEx needs only a read
+// handle, so a reader that could open the lock could hold it and stall every write the collector
+// makes.
+
+// RestrictedLogDirDACL is the protected DACL on the system log directory in the restricted mode.
+// Every entry applies to the directory, its files and its subdirectories. readersSID may be empty,
+// which leaves the log to SYSTEM and Administrators alone.
+func RestrictedLogDirDACL(readersSID string) []ACE {
+ dacl := []ACE{
+ {Type: aceTypeAllowed, Flags: aceObjectInherit | aceContainerInherit, Mask: fileAllAccess, SID: sidSystem},
+ {Type: aceTypeAllowed, Flags: aceObjectInherit | aceContainerInherit, Mask: fileAllAccess, SID: sidAdministrators},
+ }
+ if readersSID != "" {
+ dacl = append(dacl, ACE{Type: aceTypeAllowed, Flags: aceObjectInherit | aceContainerInherit, Mask: readExecute, SID: readersSID})
+ }
+ return dacl
+}
+
+// RestrictedLockDACL is the protected DACL on a restricted log's lock: SYSTEM and Administrators.
+func RestrictedLockDACL() []ACE {
+ return []ACE{
+ {Type: aceTypeAllowed, Mask: fileAllAccess, SID: sidSystem},
+ {Type: aceTypeAllowed, Mask: fileAllAccess, SID: sidAdministrators},
+ }
+}
+
+// readerForbidden is everything a reader of the restricted log must not hold: any right to write,
+// append, remove, rename or re-secure.
+const readerForbidden = fileWriteData | fileAppendData | fileWriteEA | fileWriteAttributes | fileDeleteChild |
+ accessDelete | writeDAC | writeOwner | accessSystemSecurity | maximumAllowed | genericAll | genericWrite
+
+// RestrictedProblems lists every reason obj -- the restricted log directory, a file of its log
+// family, or the lock -- lets an account other than SYSTEM and Administrators reach the log, or
+// lets the readers group do more than read (and, on the lock, anything at all). Empty means it is
+// as the restricted mode sets it.
+//
+// Unlike Problems, any grant counts, reading included: keeping other accounts from reading the log
+// is half of what the mode is for. An entry counts wherever it applies, so a grant a directory
+// only passes on to new files is reported on the directory.
+func RestrictedProblems(obj Object, readersSID string, lock bool) []string {
+ var out []string
+ if !trustedPrincipal(obj.Owner) {
+ out = append(out, "owned by "+obj.Owner+", not SYSTEM or Administrators")
+ }
+ if obj.NullDACL {
+ return append(out, "has no DACL, which grants everyone full control")
+ }
+ for _, ace := range obj.DACL {
+ if ace.Type == aceTypeDenied || trustedPrincipal(ace.SID) {
+ continue
+ }
+ if ace.SID == sidCreatorOwner || ace.SID == sidCreatorGroup {
+ // Resolved to whoever creates the child, and only SYSTEM and Administrators can.
+ continue
+ }
+ if readersSID != "" && strings.EqualFold(ace.SID, readersSID) && !lock {
+ if bad := ace.Mask & readerForbidden; bad != 0 {
+ out = append(out, fmt.Sprintf("grants the log readers group %s rights 0x%x beyond reading", ace.SID, bad))
+ }
+ continue
+ }
+ if ace.Mask != 0 {
+ out = append(out, fmt.Sprintf("grants %s access (0x%x) to a log only SYSTEM, Administrators and the readers group may reach", ace.SID, ace.Mask))
+ }
+ }
+ return out
+}
diff --git a/cli/beacon/internal/endpoint/sysacl/restricted_test.go b/cli/beacon/internal/endpoint/sysacl/restricted_test.go
new file mode 100644
index 00000000..8a6f03a3
--- /dev/null
+++ b/cli/beacon/internal/endpoint/sysacl/restricted_test.go
@@ -0,0 +1,120 @@
+package sysacl
+
+import (
+ "strings"
+ "testing"
+)
+
+const readers = "S-1-5-21-1111111111-2222222222-3333333333-1500"
+
+func TestTheRestrictedPolicyIsSafeByItsOwnRules(t *testing.T) {
+ dir := RestrictedLogDirDACL(readers)
+ cases := []struct {
+ name string
+ obj Object
+ lock bool
+ }{
+ {"directory", Object{Owner: sidAdministrators, Protected: true, DACL: dir}, false},
+ {"the runtime log", Object{Owner: sidSystem, DACL: InheritedDACL(dir, false)}, false},
+ {"an archive", Object{Owner: sidAdministrators, DACL: InheritedDACL(dir, false)}, false},
+ {"the lock", Object{Owner: sidAdministrators, Protected: true, DACL: RestrictedLockDACL()}, true},
+ {"directory without a readers group", Object{Owner: sidAdministrators, Protected: true, DACL: RestrictedLogDirDACL("")}, false},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ if problems := RestrictedProblems(tc.obj, readers, tc.lock); len(problems) > 0 {
+ t.Fatalf("the restricted ACL fails its own check: %v", problems)
+ }
+ })
+ }
+}
+
+// The restricted directory passes nothing to ordinary users: no read, no append. Reading is half of
+// what the mode keeps from them.
+func TestTheRestrictedDirectoryGrantsOrdinaryUsersNothing(t *testing.T) {
+ for _, ace := range RestrictedLogDirDACL(readers) {
+ if coversInteractiveUsers(ace.SID) {
+ t.Fatalf("the restricted directory grants %s 0x%x", ace.SID, ace.Mask)
+ }
+ }
+ if CanAppend(RestrictedLogDirDACL(readers), false, true) {
+ t.Fatal("hooks could still append directly to a restricted log")
+ }
+ for _, ace := range RestrictedLogDirDACL(readers) {
+ if ace.SID == readers && ace.Mask&readerForbidden != 0 {
+ t.Fatalf("the readers group may do more than read: 0x%x", ace.Mask&readerForbidden)
+ }
+ }
+ for _, ace := range RestrictedLockDACL() {
+ if !trustedPrincipal(ace.SID) {
+ t.Fatalf("the lock grants %s, who could hold it and stall the collector", ace.SID)
+ }
+ }
+}
+
+func TestRestrictedProblemsCatchesWhatLeaksTheLog(t *testing.T) {
+ file := InheritedDACL(RestrictedLogDirDACL(readers), false)
+ cases := []struct {
+ name string
+ obj Object
+ lock bool
+ want string
+ }{
+ {"the shared grant left on a file",
+ Object{Owner: sidAdministrators, DACL: with(file, ACE{Type: aceTypeAllowed, Flags: aceInherited, Mask: logAppend, SID: sidInteractive})},
+ false, sidInteractive},
+ {"read for Users",
+ Object{Owner: sidAdministrators, DACL: with(file, ACE{Type: aceTypeAllowed, Mask: readExecute, SID: sidUsers})},
+ false, sidUsers},
+ {"read for one account",
+ Object{Owner: sidAdministrators, DACL: with(file, ACE{Type: aceTypeAllowed, Mask: fileReadData, SID: someUser})},
+ false, someUser},
+ {"the readers group may write",
+ Object{Owner: sidAdministrators, DACL: []ACE{{Type: aceTypeAllowed, Mask: logAppend, SID: readers}}},
+ false, "beyond reading"},
+ {"the readers group may read the lock",
+ Object{Owner: sidAdministrators, Protected: true, DACL: with(RestrictedLockDACL(), ACE{Type: aceTypeAllowed, Mask: readExecute, SID: readers})},
+ true, readers},
+ {"a grant the directory only passes on",
+ Object{Owner: sidAdministrators, Protected: true, DACL: with(RestrictedLogDirDACL(readers), ACE{Type: aceTypeAllowed, Flags: aceObjectInherit | aceInheritOnly, Mask: fileReadData, SID: sidAuthenticated})},
+ false, sidAuthenticated},
+ {"an ordinary owner",
+ Object{Owner: someUser, DACL: file},
+ false, "owned by"},
+ {"no DACL",
+ Object{Owner: sidAdministrators, NullDACL: true},
+ false, "no DACL"},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ problems := RestrictedProblems(tc.obj, readers, tc.lock)
+ if !strings.Contains(strings.Join(problems, "\n"), tc.want) {
+ t.Fatalf("problems = %v, want one naming %q", problems, tc.want)
+ }
+ })
+ }
+}
+
+// A deny never makes the log easier to reach, and the readers SID is compared without regard to
+// case, the way Windows prints SIDs.
+func TestRestrictedProblemsIgnoresDeniesAndCase(t *testing.T) {
+ obj := Object{Owner: sidAdministrators, DACL: with(InheritedDACL(RestrictedLogDirDACL(readers), false),
+ ACE{Type: aceTypeDenied, Mask: fileAllAccess, SID: sidEveryone},
+ ACE{Type: aceTypeAllowed, Mask: readExecute, SID: strings.ToLower(readers)})}
+ if problems := RestrictedProblems(obj, readers, false); len(problems) > 0 {
+ t.Fatalf("problems = %v", problems)
+ }
+}
+
+func TestRestrictedSDDLIsTheDocumentedACL(t *testing.T) {
+ got := SDDL(sidAdministrators, true, RestrictedLogDirDACL(readers))
+ want := "O:S-1-5-32-544D:PAI(A;OICI;0x1f01ff;;;S-1-5-18)(A;OICI;0x1f01ff;;;S-1-5-32-544)(A;OICI;0x1200a9;;;" + readers + ")"
+ if got != want {
+ t.Fatalf("SDDL = %s\nwant %s", got, want)
+ }
+}
+
+// with is dacl plus aces, in a slice of its own.
+func with(dacl []ACE, aces ...ACE) []ACE {
+ return append(append([]ACE(nil), dacl...), aces...)
+}
diff --git a/cli/beacon/internal/endpoint/sysacl/restricted_windows.go b/cli/beacon/internal/endpoint/sysacl/restricted_windows.go
new file mode 100644
index 00000000..5146e627
--- /dev/null
+++ b/cli/beacon/internal/endpoint/sysacl/restricted_windows.go
@@ -0,0 +1,143 @@
+//go:build windows
+
+package sysacl
+
+import (
+ "errors"
+ "fmt"
+ "io/fs"
+ "os"
+ "path/filepath"
+ "strings"
+
+ "golang.org/x/sys/windows"
+)
+
+// 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.
+//
+// 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
+// fresh copy (see writer.RestrictSystemLog).
+func SecureRestrictedLogDir(dir, base, readersSID string) error {
+ return withPrivileges(func() error {
+ h, err := ensureRealDir(dir)
+ if err != nil {
+ return err
+ }
+ err = setSecurity(h, true, RestrictedLogDirDACL(readersSID))
+ windows.CloseHandle(h)
+ if err != nil {
+ return fmt.Errorf("secure %s: %w", dir, err)
+ }
+ entries, err := os.ReadDir(dir)
+ if err != nil {
+ return err
+ }
+ 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
+ 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)
+ }
+ }
+ return errors.Join(errs...)
+ })
+}
+
+// SecureRestrictedLock gives the lock at path RestrictedLockDACL, without following a link. The
+// restricted mode replaces the lock with a fresh file, which inherits the directory's entries --
+// the readers group's among them -- so it is narrowed again afterwards.
+func SecureRestrictedLock(path string) error {
+ return withPrivileges(func() error {
+ h, info, err := openNoFollow(path)
+ if err != nil {
+ return err
+ }
+ defer windows.CloseHandle(h)
+ if info.FileAttributes&(windows.FILE_ATTRIBUTE_REPARSE_POINT|windows.FILE_ATTRIBUTE_DIRECTORY) != 0 || info.NumberOfLinks > 1 {
+ return fmt.Errorf("%s is not a plain file", path)
+ }
+ return setSecurity(h, true, RestrictedLockDACL())
+ })
+}
+
+// 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
+// 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) {
+ var problems []string
+ obj, isLink, err := readObject(dir)
+ if err != nil {
+ return nil, err
+ }
+ if isLink {
+ return []string{dir + " is a link, so writes to it land wherever it points"}, nil
+ }
+ if !obj.Protected {
+ problems = append(problems, dir+": inherits entries from its parent")
+ }
+ for _, p := range RestrictedProblems(obj, readersSID, false) {
+ problems = append(problems, dir+": "+p)
+ }
+ entries, err := os.ReadDir(dir)
+ if err != nil {
+ return problems, err
+ }
+ 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) {
+ continue
+ }
+ if err != nil {
+ return problems, err
+ }
+ if link {
+ problems = append(problems, child+" is a link, so writes to it land wherever it points")
+ continue
+ }
+ lock := strings.EqualFold(entry.Name(), base+".lock")
+ for _, p := range RestrictedProblems(fobj, readersSID, lock) {
+ problems = append(problems, child+": "+p)
+ }
+ }
+ return problems, nil
+}
diff --git a/cli/beacon/internal/endpoint/sysacl/restricted_windows_test.go b/cli/beacon/internal/endpoint/sysacl/restricted_windows_test.go
new file mode 100644
index 00000000..310d0d07
--- /dev/null
+++ b/cli/beacon/internal/endpoint/sysacl/restricted_windows_test.go
@@ -0,0 +1,126 @@
+//go:build windows
+
+package sysacl
+
+import (
+ "os"
+ "path/filepath"
+ "reflect"
+ "testing"
+)
+
+// backupOperators stands in for the beacon-log group: a real local group no test account is in.
+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.
+func TestRestrictingAndSharingTheLogDirectory(t *testing.T) {
+ requireElevated(t)
+ dir := filepath.Join(t.TempDir(), "logs")
+ if err := SecureLogDir(dir, "runtime.jsonl"); err != nil {
+ t.Fatal(err)
+ }
+ for _, name := range []string{"runtime.jsonl", "runtime.jsonl.lock", "runtime.jsonl.1", "operator-notes.txt"} {
+ if err := os.WriteFile(filepath.Join(dir, name), []byte("{}\n"), 0o666); err != nil {
+ t.Fatal(err)
+ }
+ }
+ notesBefore := mustRead(t, filepath.Join(dir, "operator-notes.txt"))
+
+ if err := SecureRestrictedLogDir(dir, "runtime.jsonl", backupOperators); err != nil {
+ t.Fatalf("SecureRestrictedLogDir: %v", err)
+ }
+ assertNoUserMayChange(t, dir)
+ problems, err := InspectRestrictedLogDir(dir, "runtime.jsonl", backupOperators)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(problems) > 0 {
+ t.Fatalf("the restricted directory reads back with problems: %v", problems)
+ }
+ if obj := mustRead(t, dir); !reflect.DeepEqual(obj.DACL, RestrictedLogDirDACL(backupOperators)) || !obj.Protected {
+ t.Fatalf("directory DACL %+v (protected %v), want %+v", obj.DACL, obj.Protected, RestrictedLogDirDACL(backupOperators))
+ }
+ for _, name := range []string{"runtime.jsonl", "runtime.jsonl.1"} {
+ obj := mustRead(t, filepath.Join(dir, name))
+ if want := InheritedDACL(RestrictedLogDirDACL(backupOperators), false); !reflect.DeepEqual(obj.DACL, want) {
+ t.Errorf("%s carries %+v, want exactly the inherited %+v", name, obj.DACL, want)
+ }
+ if CanAppend(obj.DACL, obj.NullDACL, false) {
+ t.Errorf("hooks could still append to %s directly", name)
+ }
+ }
+ 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)
+ }
+
+ // The collector re-creates the log on rotation: the new file inherits the restricted entries.
+ rotated := filepath.Join(dir, "runtime.jsonl.2")
+ if err := os.WriteFile(rotated, nil, 0o666); err != nil {
+ t.Fatal(err)
+ }
+ if problems := RestrictedProblems(mustRead(t, rotated), backupOperators, false); len(problems) > 0 {
+ t.Errorf("a newly created log inherits a grant: %v", problems)
+ }
+
+ // Back to shared: the shared ACL in full, the lock's protected DACL gone with the rest.
+ if err := SecureLogDir(dir, "runtime.jsonl"); err != nil {
+ t.Fatal(err)
+ }
+ state, err := InspectLogDir(dir, "runtime.jsonl")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(state.Problems) > 0 || !state.HooksCanAppend {
+ t.Fatalf("after sharing again: problems %v, hooks can append %v", state.Problems, state.HooksCanAppend)
+ }
+ if lock := mustRead(t, filepath.Join(dir, "runtime.jsonl.lock")); lock.Protected {
+ t.Error("the lock kept the restricted mode's protected DACL")
+ }
+}
+
+func TestInspectRestrictedLogDirReportsALeftoverGrant(t *testing.T) {
+ requireElevated(t)
+ dir := filepath.Join(t.TempDir(), "logs")
+ if err := os.MkdirAll(dir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ log := filepath.Join(dir, "runtime.jsonl")
+ if err := os.WriteFile(log, nil, 0o666); err != nil {
+ t.Fatal(err)
+ }
+ if err := SecureRestrictedLogDir(dir, "runtime.jsonl", backupOperators); err != nil {
+ t.Fatal(err)
+ }
+ icacls(t, log, "/grant", `*S-1-5-32-545:(R)`)
+ problems, err := InspectRestrictedLogDir(dir, "runtime.jsonl", backupOperators)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(problems) == 0 {
+ t.Fatal("a read grant to Users on the restricted log went unreported")
+ }
+}
+
+func TestSecureRestrictedLockRefusesALink(t *testing.T) {
+ requireElevated(t)
+ dir := t.TempDir()
+ target := filepath.Join(dir, "elsewhere")
+ if err := os.WriteFile(target, nil, 0o666); err != nil {
+ t.Fatal(err)
+ }
+ lock := filepath.Join(dir, "runtime.jsonl.lock")
+ if err := os.Link(target, lock); err != nil {
+ t.Skipf("hard links unavailable: %v", err)
+ }
+ before := mustRead(t, target)
+ if err := SecureRestrictedLock(lock); err == nil {
+ t.Fatal("secured a lock that is a hard link to another file")
+ }
+ if after := mustRead(t, target); !reflect.DeepEqual(before, after) {
+ t.Fatal("the link's target was changed")
+ }
+}
diff --git a/cli/beacon/internal/endpoint/sysacl/sysacl_other.go b/cli/beacon/internal/endpoint/sysacl/sysacl_other.go
index cbe95fd1..03a83a06 100644
--- a/cli/beacon/internal/endpoint/sysacl/sysacl_other.go
+++ b/cli/beacon/internal/endpoint/sysacl/sysacl_other.go
@@ -12,3 +12,9 @@ func SecureLogDir(dir, base string) error { return nil }
func InspectLogDir(dir, base string) (LogDirState, error) {
return LogDirState{HooksCanAppend: true}, nil
}
+
+func SecureRestrictedLogDir(dir, base, readersSID string) error { return nil }
+
+func SecureRestrictedLock(path string) error { return nil }
+
+func InspectRestrictedLogDir(dir, base, readersSID string) ([]string, error) { return nil, nil }
diff --git a/cli/beacon/internal/endpoint/writer/logaccess_other.go b/cli/beacon/internal/endpoint/writer/logaccess_other.go
index 3d94b784..e4249b00 100644
--- a/cli/beacon/internal/endpoint/writer/logaccess_other.go
+++ b/cli/beacon/internal/endpoint/writer/logaccess_other.go
@@ -1,11 +1,11 @@
-//go:build !unix
+//go:build !unix && !windows
package writer
import "errors"
-// RestrictSystemLog is unavailable here: the restricted mode needs the local ingest socket and
-// kernel peer credentials, which Beacon does not offer on Windows.
+// RestrictSystemLog is unavailable here: the restricted mode needs the local ingest channel and
+// the operating system's word on who sent each event, which Beacon has on Unix and Windows only.
func RestrictSystemLog(string, int) error {
return errors.New("the restricted log access mode is not available on this platform")
}
diff --git a/cli/beacon/internal/endpoint/writer/logaccess_windows.go b/cli/beacon/internal/endpoint/writer/logaccess_windows.go
new file mode 100644
index 00000000..b3fc4943
--- /dev/null
+++ b/cli/beacon/internal/endpoint/writer/logaccess_windows.go
@@ -0,0 +1,195 @@
+//go:build windows
+
+package writer
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "io/fs"
+ "os"
+ "path/filepath"
+ "strings"
+ "time"
+
+ "golang.org/x/sys/windows"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/loggroup"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/sysacl"
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/filelock"
+)
+
+var (
+ // logReadersSID is the SID of the local group that may read a restricted log. A variable so
+ // tests can name a group without creating one.
+ logReadersSID = func() (string, error) {
+ sid, found, err := loggroup.SID(loggroup.Name)
+ if err != nil {
+ return "", err
+ }
+ if !found {
+ return "", fmt.Errorf("the %s group does not exist", loggroup.Name)
+ }
+ return sid, nil
+ }
+ // restrictLockWait bounds how long RestrictSystemLog waits for the log's lock, and replaceWait
+ // how long it keeps retrying to replace a file another process has open.
+ restrictLockWait = 5 * time.Second
+ replaceWait = 5 * time.Second
+)
+
+// RestrictSystemLog puts the system log at path in the restricted access mode. The gid is ignored
+// on Windows, where the readers group is a local group named by its SID.
+//
+// The directory gets the restricted ACL first (sysacl.SecureRestrictedLogDir): SYSTEM and
+// Administrators, and read for the readers group, with nothing for anyone else. Then the marker
+// that tells the collector and the CLI the mode is written there, inheriting that ACL.
+//
+// A log that was shared is not left with the ACL change alone. Any logged-on user could open it,
+// its archives or its lock while INTERACTIVE held read and write data on them, and a handle keeps
+// the access it was opened with: it could go on reading new events, overwriting old ones, or hold
+// the lock. So each file is copied into a new file, which inherits the restricted ACL, and renamed
+// over the old one under the log's lock, which leaves any such handle on a file nothing writes or
+// reads any more. A rename over a file another process holds open without sharing delete fails; it
+// is retried for a few seconds, and then the call fails and names the file, so install rolls back
+// rather than reporting a restriction it could not make.
+func RestrictSystemLog(path string, _ int) error {
+ readers, err := logReadersSID()
+ if err != nil {
+ return fmt.Errorf("the log readers group: %w", err)
+ }
+ dir := filepath.Dir(path)
+ base := filepath.Base(path)
+ wasRestricted := asymptoteobserve.RuntimeLogAccessRestricted(path)
+ if err := sysacl.SecureRestrictedLogDir(dir, base, readers); err != nil {
+ return fmt.Errorf("secure the log directory %s: %w", dir, err)
+ }
+ if err := asymptoteobserve.SetRuntimeLogAccess(path, asymptoteobserve.LogAccessRestricted); err != nil {
+ return fmt.Errorf("record the restricted mode: %w", err)
+ }
+ lockPath := path + ".lock"
+ if !wasRestricted {
+ if err := replaceLogFamily(path); err != nil {
+ return err
+ }
+ }
+ // The lock and the log exist from here on, as a shared install leaves them: the lock narrowed
+ // to SYSTEM and Administrators, the log with what it inherits.
+ for _, name := range []string{lockPath, path} {
+ f, err := os.OpenFile(name, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o640)
+ if err != nil {
+ return err
+ }
+ _ = f.Close()
+ }
+ return sysacl.SecureRestrictedLock(lockPath)
+}
+
+// replaceLogFamily replaces the log and its archives with fresh copies while holding the log's lock
+// (bounded), so no line lands in an old file after its copy was taken, and then the lock itself.
+//
+// The lock is replaced after it is released: a hook already waiting for it holds it open, which
+// blocks the rename until that hook has taken and released it. No hook can open it afresh by
+// then, because the directory's ACL no longer lets ordinary users open anything in it.
+func replaceLogFamily(path string) error {
+ dir := filepath.Dir(path)
+ base := filepath.Base(path)
+ entries, err := os.ReadDir(dir)
+ if err != nil {
+ return err
+ }
+ var names []string
+ for _, entry := range entries {
+ if sysacl.IsLogFamily(entry.Name(), base) && !strings.EqualFold(entry.Name(), base+".lock") {
+ names = append(names, entry.Name())
+ }
+ }
+ var errs []error
+ func() {
+ if lock, err := os.OpenFile(path+".lock", os.O_RDWR, 0); err == nil {
+ defer lock.Close()
+ ctx, cancel := context.WithTimeout(context.Background(), restrictLockWait)
+ held, err := filelock.ExclusiveContext(ctx, lock)
+ cancel()
+ if err == nil {
+ defer held.Release()
+ }
+ }
+ for _, name := range names {
+ if err := replaceWithCopy(filepath.Join(dir, name)); err != nil {
+ errs = append(errs, err)
+ }
+ }
+ }()
+ if err := replaceWithCopy(path + ".lock"); err != nil {
+ errs = append(errs, err)
+ }
+ return errors.Join(errs...)
+}
+
+// replaceWithCopy copies the file at path into a new file beside it and renames that over it. A
+// file that is missing, or is not a plain file, is left alone; SecureRestrictedLogDir has already
+// removed any link where a log file belongs.
+func replaceWithCopy(path string) error {
+ info, err := os.Lstat(path)
+ if errors.Is(err, fs.ErrNotExist) {
+ return nil
+ }
+ if err != nil {
+ return err
+ }
+ if !info.Mode().IsRegular() {
+ return nil
+ }
+ tmp, err := os.CreateTemp(filepath.Dir(path), "."+filepath.Base(path)+".restrict-*")
+ if err != nil {
+ return err
+ }
+ tmpName := tmp.Name()
+ copyErr := copyInto(tmp, path)
+ if err := tmp.Close(); copyErr == nil {
+ copyErr = err
+ }
+ if copyErr != nil {
+ _ = os.Remove(tmpName)
+ return fmt.Errorf("copy %s: %w", path, copyErr)
+ }
+ deadline := time.Now().Add(replaceWait)
+ for {
+ err := os.Rename(tmpName, path)
+ if err == nil {
+ return nil
+ }
+ if !(errors.Is(err, windows.ERROR_SHARING_VIOLATION) || errors.Is(err, windows.ERROR_ACCESS_DENIED)) || time.Now().After(deadline) {
+ _ = os.Remove(tmpName)
+ return fmt.Errorf("replace %s: %w; another process holds it open, so access granted while the log was shared could outlive the restriction -- close it and run again", path, err)
+ }
+ time.Sleep(50 * time.Millisecond)
+ }
+}
+
+// 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 {
+ src, err := os.Open(path)
+ if err != nil {
+ return err
+ }
+ defer src.Close()
+ if _, err := io.Copy(dst, src); err != nil {
+ return err
+ }
+ return dst.Sync()
+}
+
+// ShareSystemLog returns the system log at path to the shared access mode: the marker goes, and
+// EnsureSystemLogWritable gives the directory and the log family the shared ACL again, the lock's
+// narrower one included.
+func ShareSystemLog(path string) error {
+ if err := asymptoteobserve.SetRuntimeLogAccess(path, asymptoteobserve.LogAccessShared); err != nil {
+ return fmt.Errorf("remove the restricted mode marker: %w", err)
+ }
+ return EnsureSystemLogWritable(path)
+}
diff --git a/cli/beacon/internal/endpoint/writer/logaccess_windows_test.go b/cli/beacon/internal/endpoint/writer/logaccess_windows_test.go
new file mode 100644
index 00000000..dfe07152
--- /dev/null
+++ b/cli/beacon/internal/endpoint/writer/logaccess_windows_test.go
@@ -0,0 +1,145 @@
+//go:build windows
+
+package writer
+
+import (
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "golang.org/x/sys/windows"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/sysacl"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/testenv"
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"
+)
+
+// backupOperators stands in for the beacon-log group, which the test does not create.
+const backupOperators = "S-1-5-32-551"
+
+// restrictFixture is a shared system log with a lock and an archive, outside the test's profile so
+// it reads as a system log, and the readers group pointed at backupOperators.
+func restrictFixture(t *testing.T) string {
+ t.Helper()
+ requireSystemACLRights(t)
+ testenv.SetHome(t, t.TempDir())
+ prev := logReadersSID
+ logReadersSID = func() (string, error) { return backupOperators, nil }
+ t.Cleanup(func() { logReadersSID = prev })
+ path := filepath.Join(t.TempDir(), "logs", "runtime.jsonl")
+ if err := EnsureSystemLogWritable(path); err != nil {
+ t.Fatal(err)
+ }
+ for name, content := range map[string]string{"runtime.jsonl": "{\"n\":1}\n", "runtime.jsonl.1": "{\"n\":0}\n"} {
+ if err := os.WriteFile(filepath.Join(filepath.Dir(path), name), []byte(content), 0o666); err != nil {
+ t.Fatal(err)
+ }
+ }
+ return path
+}
+
+func TestRestrictSystemLogOnWindows(t *testing.T) {
+ path := restrictFixture(t)
+ dir := filepath.Dir(path)
+ if err := RestrictSystemLog(path, 0); err != nil {
+ t.Fatalf("RestrictSystemLog: %v", err)
+ }
+ if !asymptoteobserve.RuntimeLogAccessRestricted(path) {
+ t.Fatal("the marker is missing or not trusted")
+ }
+ problems, err := sysacl.InspectRestrictedLogDir(dir, "runtime.jsonl", backupOperators)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(problems) > 0 {
+ t.Fatalf("the restricted log reads back with problems: %v", problems)
+ }
+ for name, want := range map[string]string{"runtime.jsonl": "{\"n\":1}\n", "runtime.jsonl.1": "{\"n\":0}\n"} {
+ got, err := os.ReadFile(filepath.Join(dir, name))
+ if err != nil || string(got) != want {
+ t.Fatalf("%s = %q, %v; the copy lost content", name, got, err)
+ }
+ }
+ entries, _ := os.ReadDir(dir)
+ for _, entry := range entries {
+ if strings.Contains(entry.Name(), ".restrict-") {
+ t.Fatalf("a temporary copy was left behind: %s", entry.Name())
+ }
+ }
+
+ // Already restricted: the files are not copied again.
+ before, _ := os.Stat(path)
+ if err := RestrictSystemLog(path, 0); err != nil {
+ t.Fatal(err)
+ }
+ after, _ := os.Stat(path)
+ if !os.SameFile(before, after) {
+ t.Fatal("a log that was already restricted was replaced again")
+ }
+
+ if err := ShareSystemLog(path); err != nil {
+ t.Fatalf("ShareSystemLog: %v", err)
+ }
+ if asymptoteobserve.RuntimeLogAccessRestricted(path) {
+ t.Fatal("still marked restricted after sharing")
+ }
+ state, err := CheckSystemLogACL(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(state.Problems) > 0 || !state.HooksCanAppend {
+ t.Fatalf("after sharing: problems %v, hooks can append %v", state.Problems, state.HooksCanAppend)
+ }
+}
+
+// A handle opened while the log was shared keeps the access it was opened with. Restricting must
+// leave it on a file nothing reads: what it writes afterwards does not reach the log.
+func TestAHandleOpenedWhileSharedDoesNotReachTheRestrictedLog(t *testing.T) {
+ path := restrictFixture(t)
+ p, _ := windows.UTF16PtrFromString(path)
+ // Shared for delete, as a process that wants to keep its handle across a rename would open it.
+ h, err := windows.CreateFile(p, windows.GENERIC_READ|windows.GENERIC_WRITE,
+ windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE|windows.FILE_SHARE_DELETE, nil, windows.OPEN_EXISTING, 0, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ held := os.NewFile(uintptr(h), path)
+ defer held.Close()
+
+ if err := RestrictSystemLog(path, 0); err != nil {
+ t.Fatalf("RestrictSystemLog: %v", err)
+ }
+ // Whether the orphaned file still takes the write depends on the file system's rename
+ // semantics; either way it must not land in the log.
+ if _, err := held.WriteAt([]byte("{\"forged\":true}\n"), 0); err != nil {
+ t.Logf("the old handle no longer writes: %v", err)
+ }
+ got, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if strings.Contains(string(got), "forged") {
+ t.Fatalf("a write through a handle opened while shared reached the restricted log: %q", got)
+ }
+}
+
+// A file another process holds open without sharing delete cannot be replaced, and the restriction
+// says so instead of reporting a log it could not close off.
+func TestRestrictSystemLogFailsWhileAHandleBlocksTheReplacement(t *testing.T) {
+ path := restrictFixture(t)
+ prev := replaceWait
+ replaceWait = 300 * time.Millisecond
+ t.Cleanup(func() { replaceWait = prev })
+ archive := path + ".1"
+ held, err := os.Open(archive) // Go opens without FILE_SHARE_DELETE
+ if err != nil {
+ t.Fatal(err)
+ }
+ err = RestrictSystemLog(path, 0)
+ _ = held.Close()
+ if err == nil || !strings.Contains(err.Error(), "holds it open") {
+ t.Fatalf("RestrictSystemLog = %v, want it to name the held file", err)
+ }
+}
diff --git a/pkg/asymptoteobserve/runtimelogaccess_other.go b/pkg/asymptoteobserve/runtimelogaccess_other.go
index 33bd2743..befa161b 100644
--- a/pkg/asymptoteobserve/runtimelogaccess_other.go
+++ b/pkg/asymptoteobserve/runtimelogaccess_other.go
@@ -1,8 +1,8 @@
-//go:build !unix
+//go:build !unix && !windows
package asymptoteobserve
-// readLogAccessMarker reports no marker off Unix: the restricted mode needs the local ingest
-// socket and kernel peer credentials, which Beacon does not offer on Windows, so the system log
-// there keeps the shared access its ACL grants.
+// readLogAccessMarker reports no marker here: the restricted mode needs the local ingest
+// channel and the operating system's word on who sent each event, which Beacon offers on Unix
+// and Windows only.
func readLogAccessMarker(string) string { return "" }
diff --git a/pkg/asymptoteobserve/runtimelogaccess_windows.go b/pkg/asymptoteobserve/runtimelogaccess_windows.go
new file mode 100644
index 00000000..ffc49517
--- /dev/null
+++ b/pkg/asymptoteobserve/runtimelogaccess_windows.go
@@ -0,0 +1,102 @@
+//go:build windows
+
+package asymptoteobserve
+
+import (
+ "io"
+ "os"
+ "runtime"
+ "strings"
+ "unsafe"
+
+ "golang.org/x/sys/windows"
+)
+
+// logAccessMarkerTrustedSID is one more owner a marker may have besides SYSTEM and Administrators;
+// tests that cannot create an Administrators-owned file set their own SID.
+var logAccessMarkerTrustedSID = ""
+
+// markerWriteRights are the rights no account other than SYSTEM, Administrators and TrustedInstaller
+// may hold on the marker: anything that could change what it says, replace it, or re-secure it.
+const markerWriteRights = windows.FILE_WRITE_DATA | windows.FILE_APPEND_DATA | windows.FILE_WRITE_EA |
+ windows.FILE_WRITE_ATTRIBUTES | windows.DELETE | windows.WRITE_DAC | windows.WRITE_OWNER |
+ windows.GENERIC_WRITE | windows.GENERIC_ALL | windows.MAXIMUM_ALLOWED | windows.ACCESS_SYSTEM_SECURITY
+
+// readLogAccessMarker reads the marker at path when it can only have been written by SYSTEM or an
+// administrator: a plain file (not a link, not hard-linked elsewhere), owned by SYSTEM or
+// Administrators, whose DACL gives no other account any right to change it. Anything else reads as
+// no marker, the way the Unix reader ignores one that root does not own.
+func readLogAccessMarker(path string) string {
+ p, err := windows.UTF16PtrFromString(path)
+ if err != nil {
+ return ""
+ }
+ h, err := windows.CreateFile(p, windows.GENERIC_READ|windows.READ_CONTROL,
+ 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 ""
+ }
+ f := os.NewFile(uintptr(h), path)
+ defer f.Close()
+ var info windows.ByHandleFileInformation
+ if err := windows.GetFileInformationByHandle(h, &info); err != nil {
+ return ""
+ }
+ if info.FileAttributes&(windows.FILE_ATTRIBUTE_REPARSE_POINT|windows.FILE_ATTRIBUTE_DIRECTORY) != 0 || info.NumberOfLinks != 1 {
+ return ""
+ }
+ if !markerSecurityTrusted(h) {
+ return ""
+ }
+ data, err := io.ReadAll(io.LimitReader(f, maxLogAccessMarkerBytes+1))
+ if err != nil || len(data) > maxLogAccessMarkerBytes {
+ return ""
+ }
+ return strings.TrimSpace(string(data))
+}
+
+func markerSecurityTrusted(h windows.Handle) bool {
+ sd, err := windows.GetSecurityInfo(h, windows.SE_FILE_OBJECT, windows.OWNER_SECURITY_INFORMATION|windows.DACL_SECURITY_INFORMATION)
+ if err != nil {
+ return false
+ }
+ defer runtime.KeepAlive(sd)
+ owner, _, err := sd.Owner()
+ if err != nil || owner == nil || !markerTrustedPrincipal(owner.String()) {
+ return false
+ }
+ dacl, _, err := sd.DACL()
+ if err != nil || dacl == nil {
+ return false // no DACL grants everyone everything
+ }
+ for i := uint32(0); i < uint32(dacl.AceCount); i++ {
+ var ace *windows.ACCESS_ALLOWED_ACE
+ if err := windows.GetAce(dacl, i, &ace); err != nil {
+ return false
+ }
+ switch ace.Header.AceType {
+ case windows.ACCESS_DENIED_ACE_TYPE:
+ continue
+ case windows.ACCESS_ALLOWED_ACE_TYPE:
+ sid := (*windows.SID)(unsafe.Pointer(&ace.SidStart)).String()
+ if markerTrustedPrincipal(sid) {
+ continue
+ }
+ if ace.Header.AceFlags&windows.INHERIT_ONLY_ACE == 0 && uint32(ace.Mask)&markerWriteRights != 0 {
+ return false
+ }
+ default:
+ return false // an entry this does not model is not trusted
+ }
+ }
+ return true
+}
+
+func markerTrustedPrincipal(sid string) bool {
+ switch sid {
+ case "S-1-5-18", "S-1-5-32-544", "S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464":
+ return true
+ }
+ return logAccessMarkerTrustedSID != "" && strings.EqualFold(sid, logAccessMarkerTrustedSID)
+}
diff --git a/pkg/asymptoteobserve/runtimelogaccess_windows_test.go b/pkg/asymptoteobserve/runtimelogaccess_windows_test.go
new file mode 100644
index 00000000..1d2a87ff
--- /dev/null
+++ b/pkg/asymptoteobserve/runtimelogaccess_windows_test.go
@@ -0,0 +1,112 @@
+//go:build windows
+
+package asymptoteobserve
+
+import (
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "golang.org/x/sys/windows"
+)
+
+// systemLogFixture is a log path outside this test's profile, so it reads as a system log rather
+// than the user's own, and a marker writer that trusts this test's account.
+func systemLogFixture(t *testing.T) string {
+ t.Helper()
+ t.Setenv("USERPROFILE", t.TempDir())
+ t.Setenv("HOME", os.Getenv("USERPROFILE"))
+ user, err := windows.GetCurrentProcessToken().GetTokenUser()
+ if err != nil {
+ t.Fatal(err)
+ }
+ prev := logAccessMarkerTrustedSID
+ logAccessMarkerTrustedSID = user.User.Sid.String()
+ t.Cleanup(func() { logAccessMarkerTrustedSID = prev })
+ dir, err := os.MkdirTemp("", "beacon-agent")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = os.RemoveAll(dir) })
+ return filepath.Join(dir, "runtime.jsonl")
+}
+
+func TestTheRestrictedMarkerOnWindows(t *testing.T) {
+ log := systemLogFixture(t)
+ if RuntimeLogIsPrivate(log) {
+ t.Fatal("fixture: the log reads as private")
+ }
+ if RuntimeLogAccessRestricted(log) {
+ t.Fatal("restricted before any marker")
+ }
+ if err := SetRuntimeLogAccess(log, LogAccessRestricted); err != nil {
+ t.Fatal(err)
+ }
+ if !RuntimeLogAccessRestricted(log) {
+ t.Fatal("the marker was not read")
+ }
+ if file, _, _ := RuntimeLogModes(log); file != RestrictedRuntimeLogFileMode {
+ t.Fatalf("RuntimeLogModes = %v, want the restricted mode", file)
+ }
+ if err := SetRuntimeLogAccess(log, LogAccessShared); err != nil {
+ t.Fatal(err)
+ }
+ if RuntimeLogAccessRestricted(log) {
+ t.Fatal("still restricted after the marker was removed")
+ }
+}
+
+// The marker counts only when no account but SYSTEM and Administrators could have written it. This
+// one sits in the test's temp directory, which gives the test's own account full control of its
+// files; once that account is no longer trusted the marker is ignored, whether or not the test runs
+// elevated (an elevated account's files are owned by Administrators, but the grant remains).
+func TestAMarkerAnOrdinaryAccountCouldWriteIsIgnored(t *testing.T) {
+ log := systemLogFixture(t)
+ if err := SetRuntimeLogAccess(log, LogAccessRestricted); err != nil {
+ t.Fatal(err)
+ }
+ logAccessMarkerTrustedSID = ""
+ if RuntimeLogAccessRestricted(log) {
+ t.Fatal("a marker an ordinary account can write was trusted")
+ }
+}
+
+func TestAMarkerOthersCanWriteIsIgnored(t *testing.T) {
+ log := systemLogFixture(t)
+ if err := SetRuntimeLogAccess(log, LogAccessRestricted); err != nil {
+ t.Fatal(err)
+ }
+ marker := LogAccessMarkerPath(log)
+ if out, err := exec.Command("icacls", marker, "/grant", "*S-1-5-32-545:(W)").CombinedOutput(); err != nil {
+ t.Fatalf("icacls: %v: %s", err, strings.TrimSpace(string(out)))
+ }
+ if RuntimeLogAccessRestricted(log) {
+ t.Fatal("a marker Users can write was trusted")
+ }
+}
+
+func TestAHardLinkedMarkerIsIgnored(t *testing.T) {
+ log := systemLogFixture(t)
+ other := filepath.Join(filepath.Dir(log), "elsewhere")
+ if err := os.WriteFile(other, []byte(LogAccessRestricted+"\n"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Link(other, LogAccessMarkerPath(log)); err != nil {
+ t.Skipf("hard links unavailable: %v", err)
+ }
+ if RuntimeLogAccessRestricted(log) {
+ t.Fatal("a hard-linked marker was trusted")
+ }
+}
+
+func TestAMarkerWithOtherContentIsNotRestricted(t *testing.T) {
+ log := systemLogFixture(t)
+ if err := os.WriteFile(LogAccessMarkerPath(log), []byte("shared\n"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if RuntimeLogAccessRestricted(log) {
+ t.Fatal("a marker that says shared read as restricted")
+ }
+}