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
Narrow the Windows system log ACL and lock down %ProgramData%\Beacon
Claude7ebcdb5f4681
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 0c553520..78e53ba9 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -523,6 +523,7 @@ jobs:./internal/endpoint/service/... `./internal/endpoint/siempack/... `./internal/endpoint/sumo/... `+ ./internal/endpoint/sysacl/... `./internal/endpoint/traceview/... `./internal/endpoint/wazuh/... `./internal/endpoint/writer/... `diff --git a/cli/beacon-hooks/internal/logging/endpoint_event_unix_test.go b/cli/beacon-hooks/internal/logging/endpoint_event_unix_test.goindex ee4449fd..e9d89e62 100644--- a/cli/beacon-hooks/internal/logging/endpoint_event_unix_test.go+++ b/cli/beacon-hooks/internal/logging/endpoint_event_unix_test.go@@ -41,3 +41,42 @@ func TestEndpointEventCreatesSharedRuntimeFilesDespiteUmask(t *testing.T) {}}}++// A hook runs as the person at the keyboard and may not rename or delete anything in a system log+// directory -- root-owned 0755 here, and on Windows an ACL that withholds exactly those rights so a+// user cannot redirect a SYSTEM write. When the log is over its size limit the hook must append+// anyway and leave rotation to the collector, rather than drop the event.+func TestAppendEndpointJSONLAppendsWhenRotationIsRefused(t *testing.T) {+ if os.Geteuid() == 0 {+ t.Skip("root ignores directory permissions, so the refusal cannot be reproduced")+ }+ dir := filepath.Join(t.TempDir(), "logs")+ if err := os.MkdirAll(dir, 0o755); err != nil {+ t.Fatal(err)+ }+ path := filepath.Join(dir, "runtime.jsonl")+ if err := os.WriteFile(path, []byte("{\"existing\":true}\n"), 0o666); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(path+".lock", nil, 0o666); err != nil {+ t.Fatal(err)+ }+ if err := os.Chmod(dir, 0o555); err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { _ = os.Chmod(dir, 0o755) })++ if err := appendEndpointJSONL(path, []byte("{\"next\":true}\n"), 8, defaultEndpointRotateArchives); err != nil {+ t.Fatalf("append with rotation refused: %v", err)+ }+ data, err := os.ReadFile(path)+ if err != nil {+ t.Fatal(err)+ }+ if string(data) != "{\"existing\":true}\n{\"next\":true}\n" {+ t.Fatalf("log after a refused rotation = %q, want the new line appended", data)+ }+ if _, err := os.Stat(path + ".1"); !os.IsNotExist(err) {+ t.Fatalf("an archive appeared although rotation was refused: %v", err)+ }+}diff --git a/cli/beacon-hooks/internal/logging/logging.go b/cli/beacon-hooks/internal/logging/logging.goindex 739a9524..e829a9f2 100644--- a/cli/beacon-hooks/internal/logging/logging.go+++ b/cli/beacon-hooks/internal/logging/logging.go@@ -2,8 +2,10 @@ package loggingimport ("encoding/json"+ "errors""fmt""io"+ "io/fs""os"osuser "os/user""path/filepath"@@ -660,7 +662,13 @@ func appendEndpointJSONL(path string, line []byte, rotateBytes int64, rotateArchif asymptoteobserve.IsDuplicateEndpointEvent(path, line, asymptoteobserve.EndpointDuplicateWindow) {return nil}- if err := rotateEndpointLogIfNeeded(path, rotateBytes, rotateArchives, int64(len(line))); err != nil {+ // A hook usually runs as the person at the keyboard, and on a system-mode log it may not rename+ // or delete anything in the directory: the directory is root-owned 0755 on POSIX, and on Windows+ // its ACL gives ordinary users no right to add, rename or delete entries -- the rights that would+ // let one redirect a SYSTEM write. Rotation is the privileged writers' job there. The refusal+ // comes at the first step, so nothing has moved, and the event is appended past the size limit+ // rather than lost; the collector rotates at its next write.+ if err := rotateEndpointLogIfNeeded(path, rotateBytes, rotateArchives, int64(len(line))); err != nil && !errors.Is(err, fs.ErrPermission) {return err}f, err := openEndpointRuntimeFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY)diff --git a/cli/beacon/cmd/endpoint_diagnostics.go b/cli/beacon/cmd/endpoint_diagnostics.goindex 0e44bebd..185576be 100644--- a/cli/beacon/cmd/endpoint_diagnostics.go+++ b/cli/beacon/cmd/endpoint_diagnostics.go@@ -1143,7 +1143,7 @@ func actionForCheck(check diagnostics.Check, runtimeLog lifecycle.RuntimeLogSourswitch check.Evidence {case "runtime_log_missing", "missing_optional_file":return "beacon endpoint doctor --fix"- case "acl_missing_interactive_write":+ case "acl_missing_interactive_write", "acl_too_broad":// Printed rather than only offered through --fix: this one needs an elevated shell, and// an operator who cannot elevate right now still deserves to know the exact command.if hint := writer.GrantCommandHint(check.Target); hint != "" {@@ -1514,8 +1514,10 @@ func planDoctorFixes(result doctorResult, status lifecycle.Status) doctorFixPlan// The one permission failure that is repairable in place, and the one that matters// most: without this grant a system-mode Windows endpoint runs a healthy collector// that records nothing an agent did, because hooks cannot write to its log.- case "acl_missing_interactive_write":- addFix(plannedAction{Action: "grant_log_access", Target: check.Target, Message: "grant interactive users write access to the log directory"})+ case "acl_missing_interactive_write", "acl_too_broad":+ // Target is the log itself: the repair creates the log and its lock, which needs+ // their name, not just the directory the check reports.+ addFix(plannedAction{Action: "grant_log_access", Target: status.LogPath, Message: "reset the log directory ACL so interactive users can append to the runtime log and nothing more"})default:// Anything else here is a permission problem doctor cannot repair. Reported as a// skip rather than dropped: falling out of this switch is how a broken systemd unitdiff --git a/cli/beacon/cmd/endpoint_diagnostics_action_test.go b/cli/beacon/cmd/endpoint_diagnostics_action_test.goindex e1b257d5..5018b476 100644--- a/cli/beacon/cmd/endpoint_diagnostics_action_test.go+++ b/cli/beacon/cmd/endpoint_diagnostics_action_test.go@@ -29,6 +29,7 @@ func TestLogPermissionRemediationMatchesThePlatformThatFailed(t *testing.T) {// Every ACL evidence is Windows-only by construction, so none of them may produce POSIX advice.for _, evidence := range []string{"acl_missing_interactive_write",+ "acl_too_broad","acl_not_writable_by_user","acl_unreadable",} {@@ -42,18 +43,22 @@ func TestLogPermissionRemediationMatchesThePlatformThatFailed(t *testing.T) {}}- // The system-mode grant is the one that decides whether an endpoint captures anything, so its- // advice has to be the actual command, not a gesture at the problem.- grant := action("acl_missing_interactive_write")- if runtime.GOOS == "windows" {- if !strings.Contains(grant, "icacls") || !strings.Contains(grant, "S-1-5-4") {- t.Fatalf("the missing-grant remediation is %q; it should be the icacls command that "+- "restores the grant, naming the well-known SID rather than a localized account name", grant)+ // The system-mode ACL is the one that decides whether an endpoint captures anything -- and,+ // when it is too broad, whether a user can redirect a SYSTEM write -- so its advice has to be+ // the actual repair, not a gesture at the problem. Both evidences get the same one.+ for _, evidence := range []string{"acl_missing_interactive_write", "acl_too_broad"} {+ grant := action(evidence)+ if runtime.GOOS == "windows" {+ if !strings.Contains(grant, "doctor") || !strings.Contains(grant, "--fix") || !strings.Contains(grant, "--system") {+ t.Fatalf("the %s remediation is %q; it should be the elevated doctor --system --fix "++ "repair, which applies the same ACL install does", evidence, grant)+ }+ } else if grant != "beacon endpoint doctor --fix" {+ // No such ACL exists here, so the hint is empty and the advice falls back to the+ // command that does apply. Printing a Windows command on a Mac would be worse than+ // saying nothing.+ t.Fatalf("off Windows the %s remediation is %q, want the doctor --fix fallback", evidence, grant)}- } else if grant != "beacon endpoint doctor --fix" {- // No such grant exists here, so the hint is empty and the advice falls back to the command- // that does apply. Printing an icacls line on a Mac would be worse than saying nothing.- t.Fatalf("off Windows the missing-grant remediation is %q, want the doctor --fix fallback", grant)}if runtime.GOOS != "windows" {diff --git a/cli/beacon/internal/endpoint/diagnostics/diagnostics.go b/cli/beacon/internal/endpoint/diagnostics/diagnostics.goindex 0c86fb4e..48d215b4 100644--- a/cli/beacon/internal/endpoint/diagnostics/diagnostics.go+++ b/cli/beacon/internal/endpoint/diagnostics/diagnostics.go@@ -6,6 +6,7 @@ import ("os/user""path/filepath""runtime"+ "strings""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/collector"endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config"@@ -231,18 +232,23 @@ func checkLogWritableByThisUser(path string) Check {}// checkLogACL is the system-mode Windows form of the same question: can the people whose sessions-// this endpoint captures write to its log?+// this endpoint captures append to its log -- and can they do anything more?//// The mode-bit check above cannot answer it there. Windows reports 0666 for any ordinary file// regardless of its ACL, so `mode&0222 == 0` is never true and the check would report OK for// exactly the configuration it exists to catch -- a %ProgramData% log that only administrators can// write, with every hook write failing silently.//+// The second half matters as much. An endpoint installed before the log ACL was narrowed gives+// interactive users Modify on the directory, which lets any of them delete or rename the log and+// plant links a SYSTEM write follows. That endpoint captures everything, so nothing else would+// ever flag it; this does, and doctor --fix applies the same ACL a fresh install does.+//// Read from the ACL rather than by attempting a write, because doctor usually runs elevated: a// test write would succeed for the very user whose access is not in question.func checkLogACL(path string) Check {dir := filepath.Dir(path)- ok, err := writer.SystemLogWritableByUsers(dir)+ state, err := writer.CheckSystemLogACL(path)switch {case err != nil:// Unknown is reported as unknown. Claiming either answer here would be worse than saying@@ -250,15 +256,22 @@ func checkLogACL(path string) Check {return Check{Name: "runtime_log_permissions", Target: dir, Status: StatusWarn,Severity: SeverityLow, Message: "could not read the log directory ACL: " + err.Error(),Evidence: "acl_unreadable"}- case !ok:+ case len(state.Problems) > 0:+ return Check{Name: "runtime_log_permissions", Target: dir, Status: StatusFail,+ Severity: SeverityHigh,+ Message: "the log directory ACL lets ordinary users do more than append, so one could " ++ "redirect a SYSTEM write: " + strings.Join(state.Problems, "; "),+ Evidence: "acl_too_broad"}+ case !state.HooksCanAppend:return Check{Name: "runtime_log_permissions", Target: dir, Status: StatusFail,Severity: SeverityHigh,- Message: "interactive users cannot write to the log directory, so agent hooks will " ++ Message: "interactive users cannot append to the runtime log, so agent hooks will " +"fail silently while the collector reports healthy",Evidence: "acl_missing_interactive_write"}default:return Check{Name: "runtime_log_permissions", Target: dir, Status: StatusOK,- Severity: SeverityInfo, Message: "interactive users may write to the log directory",+ Severity: SeverityInfo, Message: "interactive users may append to the runtime log, and " ++ "only SYSTEM and Administrators may change the log directory",Evidence: "acl_interactive_write"}}}diff --git a/cli/beacon/internal/endpoint/lifecycle/lifecycle.go b/cli/beacon/internal/endpoint/lifecycle/lifecycle.goindex 9d166168..3e055504 100644--- a/cli/beacon/internal/endpoint/lifecycle/lifecycle.go+++ b/cli/beacon/internal/endpoint/lifecycle/lifecycle.go@@ -18,6 +18,7 @@ import ("github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/selfupdate""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/service"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/sysacl""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/writer""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/version")@@ -429,8 +430,19 @@ func Install(opts InstallOptions) (InstallResult, error) {// Only for system mode: a user-mode log lives in that user's own profile, which they can// already write, and widening its ACL would hand their prompt text to every interactive// account on the machine.+ //+ // Before that, the machine-wide directory itself. On Windows %ProgramData%\Beacon is created --+ // or, when it already exists, reset -- with Administrators as owner and a protected ACL that+ // gives ordinary users read and execute only. It holds the config the SYSTEM collector reads and+ // the hooks binary every user's agent runs, and %ProgramData% lets any user create a+ // subdirectory, so a directory found here may have been made by someone else before Beacon was+ // installed. A no-op elsewhere, where root ownership carries the same guarantee.if !cfg.UserMode {- if err := writer.EnsureSystemLogWritable(filepath.Dir(cfg.LogPath)); err != nil {+ root := sysacl.SystemRoot(endpointconfig.SystemBaseDir())+ if err := sysacl.SecureSystemTree(root, filepath.Dir(cfg.LogPath)); err != nil {+ return InstallResult{}, fmt.Errorf("secure %s: %w", root, err)+ }+ if err := writer.EnsureSystemLogWritable(cfg.LogPath); err != nil {return InstallResult{}, fmt.Errorf("prepare the log directory: %w", err)}}diff --git a/cli/beacon/internal/endpoint/sysacl/spec.go b/cli/beacon/internal/endpoint/sysacl/spec.gonew file mode 100644index 00000000..2263869e--- /dev/null+++ b/cli/beacon/internal/endpoint/sysacl/spec.go@@ -0,0 +1,372 @@+// Package sysacl owns the Windows access control on the machine-wide Beacon directories:+// %ProgramData%\Beacon (config, collector config, the hooks binary every user's agent runs) and+// the system log directory beneath it.+//+// The model and the policy live in this file, which builds on every platform, so the decisions --+// which entries each directory carries, what a child inherits, what counts as a grant an ordinary+// user must not hold -- are tested on every CI leg rather than only on the Windows runner. The+// Windows file applies and reads them; elsewhere every entry point is a no-op, because POSIX+// carries the same guarantees in file modes and root ownership.+//+// # Why these ACLs+//+// The collector runs as LocalSystem and writes the runtime log; hooks run as whoever is at the+// keyboard and append to the same file. The original grant gave INTERACTIVE Modify on the log+// directory, recursively. Modify on a directory includes adding and deleting entries, so a user+// could empty it, turn it into a mount-point junction, and plant object-manager symbolic links+// named runtime.jsonl, runtime.jsonl.N or runtime.jsonl.lock -- and the next SYSTEM open, create or+// rename would land on a path of the user's choosing. Separately, nothing set the ACL on+// %ProgramData%\Beacon itself, which a non-administrator can create (and so own) before the+// package is ever installed.+//+// The policy below closes both. Every Beacon directory is owned by Administrators and carries a+// protected DACL (inheritance from %ProgramData% disabled): SYSTEM and Administrators full+// control, Users read and execute. The log directory adds exactly one more entry: an inherit-only+// grant to INTERACTIVE, applied to files directly inside it, of read and write data -- no DELETE,+// no WRITE_DAC, no WRITE_OWNER, and nothing on the directory itself. Ordinary users therefore+// cannot add, remove or rename anything in the directory, cannot turn it into a junction, and+// cannot change the security of the files they append to.+package sysacl++import (+ "fmt"+ "path/filepath"+ "strconv"+ "strings"+)++// Access rights, ACE types and ACE flags from winnt.h. Declared here rather than taken from+// x/sys/windows so the policy and its tests build on every platform; the values are part of the+// Windows ABI and do not change.+const (+ fileReadData = 0x00000001 // FILE_LIST_DIRECTORY on a directory+ fileWriteData = 0x00000002 // FILE_ADD_FILE on a directory+ fileAppendData = 0x00000004 // FILE_ADD_SUBDIRECTORY on a directory+ fileReadEA = 0x00000008+ fileWriteEA = 0x00000010+ fileExecute = 0x00000020 // FILE_TRAVERSE on a directory+ fileDeleteChild = 0x00000040+ fileReadAttributes = 0x00000080+ fileWriteAttributes = 0x00000100++ accessDelete = 0x00010000+ readControl = 0x00020000+ writeDAC = 0x00040000+ writeOwner = 0x00080000+ synchronize = 0x00100000+ accessSystemSecurity = 0x01000000+ maximumAllowed = 0x02000000+ genericAll = 0x10000000+ genericExecute = 0x20000000+ genericWrite = 0x40000000+ genericRead = 0x80000000++ fileAllAccess = 0x001F01FF+ fileGenericRead = readControl | fileReadData | fileReadAttributes | fileReadEA | synchronize+ fileGenericWrite = readControl | fileWriteData | fileWriteAttributes | fileWriteEA | fileAppendData | synchronize+ fileGenericExecute = readControl | fileReadAttributes | fileExecute | synchronize+)++const (+ aceTypeAllowed uint8 = 0+ aceTypeDenied uint8 = 1+)++const (+ aceObjectInherit uint8 = 0x01+ aceContainerInherit uint8 = 0x02+ aceNoPropagate uint8 = 0x04+ aceInheritOnly uint8 = 0x08+ aceInherited uint8 = 0x10+)++// Well-known SIDs, by string form so the comparison never depends on the display language.+const (+ sidSystem = "S-1-5-18"+ sidAdministrators = "S-1-5-32-544"+ sidUsers = "S-1-5-32-545"+ sidInteractive = "S-1-5-4"+ sidAuthenticated = "S-1-5-11"+ sidEveryone = "S-1-1-0"+ sidCreatorOwner = "S-1-3-0"+ sidCreatorGroup = "S-1-3-1"+ sidTrustedInstaller = "S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464"+)++// readExecute is what Users hold everywhere: list, traverse, read. Hooks read config.json and run+// hooks\beacon-hooks.exe from here, and duplicate detection reads the tail of the runtime log.+const readExecute = fileGenericRead | fileGenericExecute++// logAppend is the one write grant. Read plus FILE_GENERIC_WRITE, which is everything Go asks for+// when a hook opens the log for append (FILE_APPEND_DATA, FILE_WRITE_ATTRIBUTES, FILE_WRITE_EA,+// READ_CONTROL, SYNCHRONIZE) and when it opens runtime.jsonl.lock read-write to take the lock+// (adds FILE_WRITE_DATA). It deliberately excludes DELETE, WRITE_DAC and WRITE_OWNER.+//+// FILE_WRITE_DATA means a user can overwrite bytes already in the log, as the 0666 POSIX log+// allows. It is granted through inheritance rather than as an explicit entry on two files because+// the collector re-creates runtime.jsonl on every rotation (and the lock, if anyone removes it), and+// an entry inherited at creation is the only one that survives that without Beacon re-applying it.+const logAppend = fileGenericRead | fileGenericWrite++// ACE is one access control entry, in the shape both the policy and the reader use.+type ACE struct {+ Type uint8+ Flags uint8+ Mask uint32+ SID string+}++// Object is the security of one file or directory, as read back.+type Object struct {+ Owner string+ NullDACL bool+ Protected bool+ DACL []ACE+}++// TreeDACL is the protected DACL on %ProgramData%\Beacon, and what everything below it inherits.+func TreeDACL() []ACE {+ return []ACE{+ {Type: aceTypeAllowed, Flags: aceObjectInherit | aceContainerInherit, Mask: fileAllAccess, SID: sidSystem},+ {Type: aceTypeAllowed, Flags: aceObjectInherit | aceContainerInherit, Mask: fileAllAccess, SID: sidAdministrators},+ {Type: aceTypeAllowed, Flags: aceObjectInherit | aceContainerInherit, Mask: readExecute, SID: sidUsers},+ }+}++// LogDirDACL is the protected DACL on the system log directory: the tree's entries plus the+// inherit-only append grant, which applies to files directly in the directory (object inherit,+// inherit only, no propagate) and so never to the directory itself or to a subdirectory.+func LogDirDACL() []ACE {+ return append(TreeDACL(), ACE{+ Type: aceTypeAllowed,+ Flags: aceObjectInherit | aceInheritOnly | aceNoPropagate,+ Mask: logAppend,+ SID: sidInteractive,+ })+}++// InheritedDACL is what a new child of a directory carrying parent receives, following the+// Windows inheritance rules for ACE flags. It is applied to existing children Beacon resets, so a+// reset child carries exactly what one created now would.+func InheritedDACL(parent []ACE, childIsDir bool) []ACE {+ var out []ACE+ for _, ace := range parent {+ flags := ace.Flags &^ aceInherited+ oi := flags&aceObjectInherit != 0+ ci := flags&aceContainerInherit != 0+ np := flags&aceNoPropagate != 0+ if !childIsDir {+ if oi {+ out = append(out, ACE{Type: ace.Type, Flags: aceInherited, Mask: ace.Mask, SID: ace.SID})+ }+ continue+ }+ switch {+ case ci && np:+ out = append(out, ACE{Type: ace.Type, Flags: aceInherited, Mask: ace.Mask, SID: ace.SID})+ case ci:+ out = append(out, ACE{Type: ace.Type, Flags: aceInherited | (flags & (aceObjectInherit | aceContainerInherit)), Mask: ace.Mask, SID: ace.SID})+ case oi && !np:+ // Carried through the directory, inherit-only, for the files inside it.+ out = append(out, ACE{Type: ace.Type, Flags: aceInherited | aceObjectInherit | aceInheritOnly, Mask: ace.Mask, SID: ace.SID})+ }+ }+ return out+}++// SDDL renders an owner and DACL as a security descriptor string. Protected descriptors are the+// roots Beacon owns outright; unprotected ones are children carrying inherited entries.+func SDDL(owner string, protected bool, dacl []ACE) string {+ var b strings.Builder+ b.WriteString("O:" + owner + "D:")+ if protected {+ b.WriteString("P")+ }+ b.WriteString("AI")+ for _, ace := range dacl {+ kind := "A"+ if ace.Type == aceTypeDenied {+ kind = "D"+ }+ fmt.Fprintf(&b, "(%s;%s;0x%x;;;%s)", kind, sddlFlags(ace.Flags), ace.Mask, ace.SID)+ }+ return b.String()+}++func sddlFlags(flags uint8) string {+ var s string+ for _, f := range []struct {+ bit uint8+ name string+ }{{aceObjectInherit, "OI"}, {aceContainerInherit, "CI"}, {aceNoPropagate, "NP"}, {aceInheritOnly, "IO"}, {aceInherited, "ID"}} {+ if flags&f.bit != 0 {+ s += f.name+ }+ }+ return s+}++// trustedPrincipal reports whether a SID may hold write, delete or ownership rights anywhere in+// Beacon's machine-wide directories.+func trustedPrincipal(sid string) bool {+ switch sid {+ case sidSystem, sidAdministrators, sidTrustedInstaller:+ return true+ }+ return false+}++// coversInteractiveUsers reports whether a grant to this SID reaches a hook running as the person+// at the keyboard.+func coversInteractiveUsers(sid string) bool {+ switch sid {+ case sidInteractive, sidUsers, sidAuthenticated, sidEveryone:+ return true+ }+ return false+}++// Rights an untrusted principal must never hold on a Beacon directory: adding or removing+// entries, deleting it, writing the attributes or reparse data that turn it into a junction, or+// changing its security.+const dirForbidden = fileWriteData | fileAppendData | fileWriteEA | fileWriteAttributes | fileDeleteChild |+ accessDelete | writeDAC | writeOwner | accessSystemSecurity | maximumAllowed | genericAll | genericWrite++// Rights an untrusted principal must never hold on a Beacon file other than the runtime log+// family: config, the collector config and the hooks binary are read by SYSTEM or run by every+// user, so any write is a privilege escalation.+const fileForbidden = fileWriteData | fileAppendData | fileWriteEA | fileWriteAttributes |+ accessDelete | writeDAC | writeOwner | accessSystemSecurity | maximumAllowed | genericAll | genericWrite++// Rights an untrusted principal must never hold on the runtime log, its archives or its lock.+// Appending is the point; deleting, renaming or re-securing them is the attack.+const logFileForbidden = accessDelete | writeDAC | writeOwner | accessSystemSecurity | maximumAllowed | genericAll++// Kind says which rules an object is held to.+type Kind int++const (+ KindDir Kind = iota // a directory in the Beacon tree+ KindFile // a file in the Beacon tree+ KindLogDir // the system log directory+ KindLogFile // runtime.jsonl, its archives, or its lock+)++// Problems lists every reason obj is not safe to leave as it is. Empty means safe.+//+// An entry counts by what it grants, wherever it applies: to the object itself (unless it is+// inherit-only), and, on a directory, to the files (object inherit) and subdirectories (container+// inherit) created in it later. Deny entries never make an object less safe and are ignored.+// Entries of a type this does not model are treated as grants, so an unfamiliar ACL is reset+// rather than trusted.+func Problems(obj Object, kind Kind) []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")+ }+ isDir := kind == KindDir || kind == KindLogDir+ selfForbidden := uint32(fileForbidden)+ switch kind {+ case KindDir, KindLogDir:+ selfForbidden = dirForbidden+ case KindLogFile:+ selfForbidden = logFileForbidden+ }+ for _, ace := range obj.DACL {+ if ace.Type == aceTypeDenied || trustedPrincipal(ace.SID) {+ continue+ }+ if ace.SID == sidCreatorOwner || ace.SID == sidCreatorGroup {+ // Stand-ins resolved to whoever creates the child. Only trusted principals can+ // create anything here once the directory itself is safe.+ continue+ }+ if ace.Flags&aceInheritOnly == 0 {+ if bad := ace.Mask & selfForbidden; bad != 0 {+ out = append(out, fmt.Sprintf("grants %s rights 0x%x it must not hold", ace.SID, bad))+ }+ }+ if !isDir {+ continue+ }+ if ace.Flags&aceObjectInherit != 0 {+ // What files created in this directory will grant.+ childForbidden := uint32(fileForbidden)+ if kind == KindLogDir {+ childForbidden = logFileForbidden+ }+ if bad := ace.Mask & childForbidden; bad != 0 {+ out = append(out, fmt.Sprintf("passes %s rights 0x%x to new files", ace.SID, bad))+ }+ }+ if ace.Flags&aceContainerInherit != 0 {+ if bad := ace.Mask & dirForbidden; bad != 0 {+ out = append(out, fmt.Sprintf("passes %s rights 0x%x to new subdirectories", ace.SID, bad))+ }+ }+ }+ return out+}++// CanAppend reports whether a hook running as an interactive user can open the log for append+// and its lock for read-write. On a directory it asks about the files the directory passes its+// entries to; on a file, about the file itself. A matching deny of either bit settles it.+func CanAppend(dacl []ACE, nullDACL bool, ofChildren bool) bool {+ if nullDACL {+ return true+ }+ const need = fileWriteData | fileAppendData+ allowed := false+ for _, ace := range dacl {+ if !coversInteractiveUsers(ace.SID) {+ continue+ }+ applies := ace.Flags&aceInheritOnly == 0+ if ofChildren {+ applies = ace.Flags&aceObjectInherit != 0+ }+ if !applies {+ continue+ }+ switch ace.Type {+ case aceTypeDenied:+ if ace.Mask&(need|genericWrite|genericAll) != 0 {+ return false+ }+ case aceTypeAllowed:+ if ace.Mask&need == need || ace.Mask&(genericWrite|genericAll) != 0 {+ allowed = true+ }+ }+ }+ return allowed+}++// LogDirState is what doctor reports about the log directory.+type LogDirState struct {+ // HooksCanAppend is true when files in the directory, and each existing file of the log+ // family, grant interactive users read and write data.+ HooksCanAppend bool+ // Problems lists grants or owners that would let an ordinary user redirect a SYSTEM write.+ Problems []string+}++// IsLogFamily reports whether name is the runtime log called base, one of its numbered archives,+// or its lock -- the files hooks append to and the privileged writers rotate.+func IsLogFamily(name, base string) bool {+ if strings.EqualFold(name, base) || strings.EqualFold(name, base+".lock") {+ return true+ }+ if len(name) <= len(base)+1 || !strings.EqualFold(name[:len(base)+1], base+".") {+ return false+ }+ _, err := strconv.Atoi(name[len(base)+1:])+ return err == nil+}++// SystemRoot is the directory Beacon owns outright on Windows: the parent of the endpoint base+// directory, %ProgramData%\Beacon.+func SystemRoot(baseDir string) string { return filepath.Dir(baseDir) }diff --git a/cli/beacon/internal/endpoint/sysacl/spec_test.go b/cli/beacon/internal/endpoint/sysacl/spec_test.gonew file mode 100644index 00000000..ed056584--- /dev/null+++ b/cli/beacon/internal/endpoint/sysacl/spec_test.go@@ -0,0 +1,223 @@+package sysacl++import (+ "strings"+ "testing"+)++const (+ someUser = "S-1-5-21-1111111111-2222222222-3333333333-1001"+ // icacls (M): everything in (RX) and (W) plus DELETE.+ modify = 0x001301BF+)++func TestThePolicyIsSafeByItsOwnRules(t *testing.T) {+ cases := []struct {+ name string+ obj Object+ kind Kind+ }{+ {"tree root", Object{Owner: sidAdministrators, Protected: true, DACL: TreeDACL()}, KindDir},+ {"log directory", Object{Owner: sidAdministrators, Protected: true, DACL: LogDirDACL()}, KindLogDir},+ {"a directory in the tree", Object{Owner: sidAdministrators, DACL: InheritedDACL(TreeDACL(), true)}, KindDir},+ {"a file in the tree", Object{Owner: sidAdministrators, DACL: InheritedDACL(TreeDACL(), false)}, KindFile},+ {"the runtime log", Object{Owner: sidSystem, DACL: InheritedDACL(LogDirDACL(), false)}, KindLogFile},+ {"a subdirectory of the log directory", Object{Owner: sidAdministrators, DACL: InheritedDACL(LogDirDACL(), true)}, KindDir},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ if problems := Problems(tc.obj, tc.kind); len(problems) > 0 {+ t.Fatalf("the ACL Beacon applies fails its own check: %v", problems)+ }+ })+ }+}++// The finding this package exists for: each of these let an ordinary user redirect a SYSTEM write.+func TestProblemsCatchesWhatLetAUserRedirectASystemWrite(t *testing.T) {+ cases := []struct {+ name string+ obj Object+ kind Kind+ }{+ {+ // The grant every endpoint carried before: Modify for INTERACTIVE, (OI)(CI), on the+ // log directory. Adding, deleting and junctioning entries all follow from it.+ name: "the legacy Modify grant on the log directory",+ obj: Object{Owner: sidAdministrators, DACL: append(TreeDACL(),+ ACE{Type: aceTypeAllowed, Flags: aceObjectInherit | aceContainerInherit, Mask: modify, SID: sidInteractive})},+ kind: KindLogDir,+ },+ {+ // What the same grant left on the log itself after icacls /T.+ name: "Modify on the runtime log",+ obj: Object{Owner: sidAdministrators, DACL: append(InheritedDACL(TreeDACL(), false),+ ACE{Type: aceTypeAllowed, Mask: modify, SID: sidInteractive})},+ kind: KindLogFile,+ },+ {+ // %ProgramData% lets any user create a subdirectory, which they then own.+ name: "a directory a non-administrator created",+ obj: Object{Owner: someUser, DACL: TreeDACL()},+ kind: KindDir,+ },+ {+ // What a directory MkdirAll creates under %ProgramData% inherits: Users may add files+ // and subdirectories.+ name: "the ACL inherited from %ProgramData%",+ obj: Object{Owner: sidAdministrators, DACL: []ACE{+ {Type: aceTypeAllowed, Flags: aceInherited | aceObjectInherit | aceContainerInherit, Mask: fileAllAccess, SID: sidSystem},+ {Type: aceTypeAllowed, Flags: aceInherited | aceObjectInherit | aceContainerInherit, Mask: fileAllAccess, SID: sidAdministrators},+ {Type: aceTypeAllowed, Flags: aceInherited | aceObjectInherit | aceContainerInherit, Mask: readExecute, SID: sidUsers},+ {Type: aceTypeAllowed, Flags: aceInherited | aceContainerInherit, Mask: fileWriteData | fileAppendData | fileWriteEA | fileWriteAttributes, SID: sidUsers},+ {Type: aceTypeAllowed, Flags: aceInherited | aceObjectInherit | aceContainerInherit | aceInheritOnly, Mask: fileAllAccess, SID: sidCreatorOwner},+ }},+ kind: KindDir,+ },+ {+ name: "write access to the hooks binary every user runs",+ obj: Object{Owner: sidAdministrators, DACL: append(InheritedDACL(TreeDACL(), false),+ ACE{Type: aceTypeAllowed, Mask: fileAppendData, SID: sidUsers})},+ kind: KindFile,+ },+ {+ name: "an inherit-only grant that hands new files DELETE",+ obj: Object{Owner: sidAdministrators, DACL: append(TreeDACL(),+ ACE{Type: aceTypeAllowed, Flags: aceObjectInherit | aceInheritOnly, Mask: logAppend | accessDelete, SID: sidInteractive})},+ kind: KindLogDir,+ },+ {+ name: "a grant to change the security of the log",+ obj: Object{Owner: sidAdministrators, DACL: append(InheritedDACL(LogDirDACL(), false),+ ACE{Type: aceTypeAllowed, Mask: writeDAC, SID: sidInteractive})},+ kind: KindLogFile,+ },+ {+ name: "a null DACL",+ obj: Object{Owner: sidAdministrators, NullDACL: true},+ kind: KindDir,+ },+ {+ name: "an entry of a type this does not model",+ obj: Object{Owner: sidAdministrators, DACL: append(TreeDACL(), ACE{Type: 9, Mask: fileWriteData})},+ kind: KindDir,+ },+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ if problems := Problems(tc.obj, tc.kind); len(problems) == 0 {+ t.Fatal("reported safe")+ }+ })+ }+}++// The log directory's only extra entry reaches files directly in it, never the directory itself+// (users must not add, remove or rename entries) and never a subdirectory.+func TestTheAppendGrantReachesOnlyTheLogFiles(t *testing.T) {+ if CanAppend(LogDirDACL(), false, false) {+ t.Fatal("the log directory itself is writable by interactive users")+ }+ if !CanAppend(LogDirDACL(), false, true) {+ t.Fatal("files created in the log directory are not appendable by interactive users")+ }+ file := InheritedDACL(LogDirDACL(), false)+ if !CanAppend(file, false, false) {+ t.Fatal("the runtime log does not inherit the append grant")+ }+ for _, ace := range InheritedDACL(LogDirDACL(), true) {+ if ace.SID == sidInteractive {+ t.Fatalf("a subdirectory of the log directory inherits %+v", ace)+ }+ }+ for _, ace := range file {+ if trustedPrincipal(ace.SID) {+ continue+ }+ if ace.Mask&(accessDelete|writeDAC|writeOwner|genericAll) != 0 {+ t.Fatalf("the runtime log grants %s 0x%x, which includes delete or re-securing it", ace.SID, ace.Mask)+ }+ if ace.Flags != aceInherited {+ t.Fatalf("an entry on the runtime log carries flags 0x%x, want only INHERITED_ACE", ace.Flags)+ }+ }+}++// What Go's os.OpenFile asks for on Windows, from syscall.Open: O_APPEND|O_CREATE|O_WRONLY for the+// log, and O_CREATE|O_RDWR (GENERIC_READ|GENERIC_WRITE) for the lock. If the grant ever stops+// covering either, every hook write fails with access denied.+func TestTheAppendGrantCoversWhatHookOpensRequest(t *testing.T) {+ appendOpen := uint32(fileAppendData | fileWriteAttributes | fileWriteEA | readControl | synchronize)+ lockOpen := uint32(fileGenericRead | fileGenericWrite)+ if logAppend&appendOpen != appendOpen {+ t.Fatalf("the grant 0x%x misses 0x%x of what an append open requests", logAppend, appendOpen&^logAppend)+ }+ if logAppend&lockOpen != lockOpen {+ t.Fatalf("the grant 0x%x misses 0x%x of what the lock open requests", logAppend, lockOpen&^logAppend)+ }+}++func TestCanAppendHonorsADeny(t *testing.T) {+ dacl := append([]ACE{{Type: aceTypeDenied, Mask: fileAppendData, SID: sidInteractive}}, InheritedDACL(LogDirDACL(), false)...)+ if CanAppend(dacl, false, false) {+ t.Fatal("a deny of append on the log reads as appendable")+ }+ other := append([]ACE{{Type: aceTypeDenied, Mask: fileReadData, SID: sidInteractive}}, InheritedDACL(LogDirDACL(), false)...)+ if !CanAppend(other, false, false) {+ t.Fatal("a deny of unrelated rights reads as a deny of append")+ }+}++func TestInheritedDACLFollowsTheWindowsRules(t *testing.T) {+ parent := []ACE{+ {Type: aceTypeAllowed, Flags: aceObjectInherit | aceContainerInherit, Mask: 1, SID: "A"},+ {Type: aceTypeAllowed, Flags: aceContainerInherit, Mask: 2, SID: "B"},+ {Type: aceTypeAllowed, Flags: aceObjectInherit, Mask: 3, SID: "C"},+ {Type: aceTypeAllowed, Flags: aceObjectInherit | aceNoPropagate | aceInheritOnly, Mask: 4, SID: "D"},+ {Type: aceTypeAllowed, Flags: aceContainerInherit | aceNoPropagate, Mask: 5, SID: "E"},+ {Type: aceTypeAllowed, Flags: 0, Mask: 6, SID: "F"},+ {Type: aceTypeAllowed, Flags: aceInherited | aceObjectInherit | aceContainerInherit | aceInheritOnly, Mask: 7, SID: "G"},+ }+ render := func(dacl []ACE) string {+ var parts []string+ for _, a := range dacl {+ parts = append(parts, a.SID+":"+sddlFlags(a.Flags))+ }+ return strings.Join(parts, " ")+ }+ if got, want := render(InheritedDACL(parent, false)), "A:ID C:ID D:ID G:ID"; got != want {+ t.Fatalf("file inherits %q, want %q", got, want)+ }+ if got, want := render(InheritedDACL(parent, true)), "A:OICIID B:CIID C:OIIOID E:ID G:OICIID"; got != want {+ t.Fatalf("directory inherits %q, want %q", got, want)+ }+}++// The descriptors are what an administrator reads in an audit, so their exact form is pinned.+func TestSDDLIsTheDocumentedACL(t *testing.T) {+ if got, want := SDDL(sidAdministrators, true, TreeDACL()),+ "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;;;S-1-5-32-545)"; got != want {+ t.Fatalf("tree SDDL = %s\nwant %s", got, want)+ }+ if got, want := SDDL(sidAdministrators, true, LogDirDACL()),+ "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;;;S-1-5-32-545)(A;OINPIO;0x12019f;;;S-1-5-4)"; got != want {+ t.Fatalf("log directory SDDL = %s\nwant %s", got, want)+ }+ if got, want := SDDL(sidAdministrators, false, InheritedDACL(LogDirDACL(), false)),+ "O:S-1-5-32-544D:AI(A;ID;0x1f01ff;;;S-1-5-18)(A;ID;0x1f01ff;;;S-1-5-32-544)(A;ID;0x1200a9;;;S-1-5-32-545)(A;ID;0x12019f;;;S-1-5-4)"; got != want {+ t.Fatalf("runtime log SDDL = %s\nwant %s", got, want)+ }+}++func TestIsLogFamily(t *testing.T) {+ for _, name := range []string{"runtime.jsonl", "RUNTIME.JSONL", "runtime.jsonl.lock", "runtime.jsonl.1", "runtime.jsonl.12"} {+ if !IsLogFamily(name, "runtime.jsonl") {+ t.Errorf("%s is not recognized as the runtime log family", name)+ }+ }+ for _, name := range []string{"cloud-backfill.jsonl", "runtime.jsonl.", "runtime.jsonl.tmp", "runtime.jsonl.1.bak", "xruntime.jsonl"} {+ if IsLogFamily(name, "runtime.jsonl") {+ t.Errorf("%s is wrongly recognized as the runtime log family", name)+ }+ }+}diff --git a/cli/beacon/internal/endpoint/sysacl/sysacl_other.go b/cli/beacon/internal/endpoint/sysacl/sysacl_other.gonew file mode 100644index 00000000..cbe95fd1--- /dev/null+++ b/cli/beacon/internal/endpoint/sysacl/sysacl_other.go@@ -0,0 +1,14 @@+//go:build !windows++package sysacl++// POSIX carries these guarantees in root ownership and file modes, which the install and the+// packaging scripts already set, so there is nothing to apply and nothing to inspect.++func SecureSystemTree(root string, skip ...string) error { return nil }++func SecureLogDir(dir, base string) error { return nil }++func InspectLogDir(dir, base string) (LogDirState, error) {+ return LogDirState{HooksCanAppend: true}, nil+}diff --git a/cli/beacon/internal/endpoint/sysacl/sysacl_windows.go b/cli/beacon/internal/endpoint/sysacl/sysacl_windows.gonew file mode 100644index 00000000..f3dd94d0--- /dev/null+++ b/cli/beacon/internal/endpoint/sysacl/sysacl_windows.go@@ -0,0 +1,428 @@+//go:build windows++package sysacl++import (+ "errors"+ "fmt"+ "io/fs"+ "os"+ "path/filepath"+ "runtime"+ "strings"+ "unsafe"++ "golang.org/x/sys/windows"+)++// SecureSystemTree resets %ProgramData%\Beacon (root) and everything beneath it.+//+// root is created if missing and replaced if it is a link. It is then owned by Administrators and+// given the protected TreeDACL, unconditionally: an existing directory -- including one a+// non-administrator created before the package was installed, and so owns -- is reset, not+// trusted. Below it, every link (junction, symbolic link, mount point) and every hard-linked file+// is removed, since Beacon creates neither and both redirect a privileged write elsewhere; and+// every object whose owner or DACL fails Problems is given Administrators ownership and exactly+// what it would inherit. Objects that are already safe are left alone, so a stricter ACL an+// administrator set deliberately survives.+//+// Paths in skip (the log directory, which SecureLogDir owns) are not descended into.+//+// Everything is set through a handle opened without following reparse points, and with+// SetKernelObjectSecurity, which writes exactly the descriptor given and does not walk or+// re-propagate to children by path the way SetNamedSecurityInfo does. A pass that resets security+// must never be steerable onto a path outside the tree.+func SecureSystemTree(root string, skip ...string) error {+ return withPrivileges(func() error {+ h, err := ensureRealDir(root)+ if err != nil {+ return err+ }+ err = setSecurity(h, true, TreeDACL())+ windows.CloseHandle(h)+ if err != nil {+ return fmt.Errorf("secure %s: %w", root, err)+ }+ return walkTree(root, TreeDACL(), skipSet(skip))+ })+}++// SecureLogDir gives the system log directory its ACL, and resets the runtime log family in it.+//+// dir is created if missing and replaced if it is a link. It is owned by Administrators with the+// protected LogDirDACL. Of its direct children, every link is removed (a link in a directory a+// SYSTEM process writes to is the attack this exists to close); every file of the base log's+// family that is hard-linked elsewhere is removed; and every other file of the family is given+// Administrators ownership and exactly the inherited DACL a newly rotated log gets. Anything else+// in the directory is left as it is: a log directory an operator pointed elsewhere may hold their+// own files, and no Beacon process writes them.+func SecureLogDir(dir, base string) error {+ return withPrivileges(func() error {+ h, err := ensureRealDir(dir)+ if err != nil {+ return err+ }+ err = setSecurity(h, true, LogDirDACL())+ 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(LogDirDACL(), 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:+ 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...)+ })+}++// InspectLogDir reads the log directory and its log family and assesses them. Read-only; it needs+// no privilege beyond READ_CONTROL, which Users hold.+func InspectLogDir(dir, base string) (LogDirState, error) {+ var state LogDirState+ obj, isLink, err := readObject(dir)+ if err != nil {+ return state, err+ }+ if isLink {+ state.Problems = append(state.Problems, dir+" is a link, so writes to it land wherever it points")+ return state, nil+ }+ for _, p := range Problems(obj, KindLogDir) {+ state.Problems = append(state.Problems, dir+": "+p)+ }+ state.HooksCanAppend = CanAppend(obj.DACL, obj.NullDACL, true)++ entries, err := os.ReadDir(dir)+ if err != nil {+ return state, 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 state, err+ }+ if link {+ state.Problems = append(state.Problems, child+" is a link, so writes to it land wherever it points")+ continue+ }+ for _, p := range Problems(fobj, KindLogFile) {+ state.Problems = append(state.Problems, child+": "+p)+ }+ // Only the files a hook opens decide whether it can write; an archive it cannot append to+ // is how it should be once rotation stops granting more.+ if strings.EqualFold(entry.Name(), base) || strings.EqualFold(entry.Name(), base+".lock") {+ if !CanAppend(fobj.DACL, fobj.NullDACL, false) {+ state.HooksCanAppend = false+ }+ }+ }+ return state, nil+}++// InspectTree reports the problems on root itself, for tests and diagnostics.+func InspectTree(path string, kind Kind) ([]string, error) {+ obj, link, err := readObject(path)+ if err != nil {+ return nil, err+ }+ if link {+ return []string{path + " is a link"}, nil+ }+ return Problems(obj, kind), nil+}++// ReadObject returns the owner and DACL of path without following a link, for tests.+func ReadObject(path string) (Object, error) {+ obj, _, err := readObject(path)+ return obj, err+}++func walkTree(dir string, dirDACL []ACE, skip map[string]bool) error {+ entries, err := os.ReadDir(dir)+ if err != nil {+ return err+ }+ var errs []error+ for _, entry := range entries {+ child := filepath.Join(dir, entry.Name())+ if skip[normPath(child)] {+ continue+ }+ 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+ }+ isDir := info.FileAttributes&windows.FILE_ATTRIBUTE_DIRECTORY != 0+ if info.FileAttributes&windows.FILE_ATTRIBUTE_REPARSE_POINT != 0 || (!isDir && info.NumberOfLinks > 1) {+ 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))+ }+ continue+ }+ kind := KindFile+ if isDir {+ kind = KindDir+ }+ obj, err := objectFromHandle(h)+ if err == nil && len(Problems(obj, kind)) > 0 {+ err = setSecurity(h, false, InheritedDACL(dirDACL, isDir))+ if err == nil {+ obj, err = objectFromHandle(h)+ }+ }+ windows.CloseHandle(h)+ if err != nil {+ errs = append(errs, fmt.Errorf("secure %s: %w", child, err))+ continue+ }+ if isDir {+ if err := walkTree(child, obj.DACL, skip); err != nil {+ errs = append(errs, err)+ }+ }+ }+ return errors.Join(errs...)+}++// ensureRealDir opens path as a directory that is not a link, creating it if missing and removing a+// link found in its place. A few attempts, because removing a link and creating the directory are+// two steps; the parent is expected to be one ordinary users cannot write (the tree root's parent+// is %ProgramData%, whose existing entries they cannot replace), so a lost race means something is+// actively interfering and the install should stop rather than loop.+func ensureRealDir(path string) (windows.Handle, error) {+ for attempt := 0; attempt < 3; attempt++ {+ h, info, err := openNoFollow(path)+ if errors.Is(err, fs.ErrNotExist) {+ if err := os.MkdirAll(path, 0o755); err != nil && !errors.Is(err, fs.ErrExist) {+ return windows.InvalidHandle, fmt.Errorf("create %s: %w", path, err)+ }+ continue+ }+ if err != nil {+ return windows.InvalidHandle, fmt.Errorf("open %s: %w", path, err)+ }+ if info.FileAttributes&windows.FILE_ATTRIBUTE_REPARSE_POINT != 0 {+ windows.CloseHandle(h)+ // Removes the link itself, never what it points to.+ if err := os.Remove(path); err != nil && !errors.Is(err, fs.ErrNotExist) {+ return windows.InvalidHandle, fmt.Errorf("%s is a link and could not be removed: %w", path, err)+ }+ continue+ }+ if info.FileAttributes&windows.FILE_ATTRIBUTE_DIRECTORY == 0 {+ windows.CloseHandle(h)+ return windows.InvalidHandle, fmt.Errorf("%s exists and is not a directory", path)+ }+ return h, nil+ }+ return windows.InvalidHandle, fmt.Errorf("%s kept changing while it was being secured", path)+}++// openNoFollow opens the object at path itself -- a link rather than its target -- with the rights+// needed to read and replace its owner and DACL.+func openNoFollow(path string) (windows.Handle, windows.ByHandleFileInformation, error) {+ var info windows.ByHandleFileInformation+ p, err := windows.UTF16PtrFromString(path)+ if err != nil {+ return windows.InvalidHandle, info, err+ }+ h, err := windows.CreateFile(p,+ windows.READ_CONTROL|windows.WRITE_DAC|windows.WRITE_OWNER,+ windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE|windows.FILE_SHARE_DELETE,+ nil, windows.OPEN_EXISTING,+ windows.FILE_FLAG_BACKUP_SEMANTICS|windows.FILE_FLAG_OPEN_REPARSE_POINT, 0)+ if err != nil {+ return windows.InvalidHandle, info, &os.PathError{Op: "open", Path: path, Err: err}+ }+ if err := windows.GetFileInformationByHandle(h, &info); err != nil {+ windows.CloseHandle(h)+ return windows.InvalidHandle, info, &os.PathError{Op: "stat", Path: path, Err: err}+ }+ return h, info, nil+}++// readObject reads path's security without following a link and without asking for write access.+func readObject(path string) (Object, bool, error) {+ p, err := windows.UTF16PtrFromString(path)+ if err != nil {+ return Object{}, false, err+ }+ h, err := windows.CreateFile(p, windows.READ_CONTROL|windows.FILE_READ_ATTRIBUTES,+ windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE|windows.FILE_SHARE_DELETE,+ nil, windows.OPEN_EXISTING,+ windows.FILE_FLAG_BACKUP_SEMANTICS|windows.FILE_FLAG_OPEN_REPARSE_POINT, 0)+ if err != nil {+ return Object{}, false, &os.PathError{Op: "open", Path: path, Err: err}+ }+ defer windows.CloseHandle(h)+ var info windows.ByHandleFileInformation+ if err := windows.GetFileInformationByHandle(h, &info); err != nil {+ return Object{}, false, &os.PathError{Op: "stat", Path: path, Err: err}+ }+ obj, err := objectFromHandle(h)+ return obj, info.FileAttributes&windows.FILE_ATTRIBUTE_REPARSE_POINT != 0, err+}++func objectFromHandle(h windows.Handle) (Object, error) {+ sd, err := windows.GetSecurityInfo(h, windows.SE_FILE_OBJECT,+ windows.OWNER_SECURITY_INFORMATION|windows.DACL_SECURITY_INFORMATION)+ if err != nil {+ return Object{}, fmt.Errorf("read the security descriptor: %w", err)+ }+ var obj Object+ if owner, _, err := sd.Owner(); err == nil && owner != nil {+ obj.Owner = owner.String()+ }+ if control, _, err := sd.Control(); err == nil {+ obj.Protected = control&windows.SE_DACL_PROTECTED != 0+ }+ dacl, _, err := sd.DACL()+ if err != nil {+ return Object{}, fmt.Errorf("read the DACL: %w", err)+ }+ if dacl == nil {+ obj.NullDACL = true+ return obj, nil+ }+ 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 Object{}, fmt.Errorf("read access control entry %d: %w", i, err)+ }+ // ACCESS_ALLOWED and ACCESS_DENIED entries carry the SID at the same offset. Other types+ // (object and callback entries) lay out differently; they never appear on files Beacon+ // creates, so one is recorded without a SID, which Problems treats as untrusted and resets.+ entry := ACE{Type: ace.Header.AceType, Flags: ace.Header.AceFlags, Mask: uint32(ace.Mask)}+ if entry.Type == aceTypeAllowed || entry.Type == aceTypeDenied {+ entry.SID = (*windows.SID)(unsafe.Pointer(&ace.SidStart)).String()+ }+ obj.DACL = append(obj.DACL, entry)+ }+ runtime.KeepAlive(sd)+ return obj, nil+}++// setSecurity replaces the owner and DACL on h. A protected descriptor stops inheritance from the+// parent; an unprotected one carries the inherited entries computed by InheritedDACL.+func setSecurity(h windows.Handle, protected bool, dacl []ACE) error {+ sd, err := windows.SecurityDescriptorFromString(SDDL(sidAdministrators, protected, dacl))+ if err != nil {+ return fmt.Errorf("build the security descriptor: %w", err)+ }+ info := windows.SECURITY_INFORMATION(windows.OWNER_SECURITY_INFORMATION | windows.DACL_SECURITY_INFORMATION)+ if protected {+ info |= windows.PROTECTED_DACL_SECURITY_INFORMATION+ } else {+ info |= windows.UNPROTECTED_DACL_SECURITY_INFORMATION+ }+ err = windows.SetKernelObjectSecurity(h, info, sd)+ runtime.KeepAlive(sd)+ return err+}++// withPrivileges runs fn on a locked OS thread impersonating this process with SeRestorePrivilege,+// SeTakeOwnershipPrivilege and SeBackupPrivilege enabled.+//+// They are what let an administrator take back a directory someone else created and locked:+// without them, a pre-created %ProgramData%\Beacon whose owner denied Administrators everything+// could not be opened for WRITE_OWNER at all. Enabled on an impersonation token for this thread+// only, so the rest of the process never runs with them. A privilege the token does not hold is+// simply not enabled, and fn runs anyway: an ordinary elevated install needs none of them.+func withPrivileges(fn func() error) error {+ done := make(chan error, 1)+ go func() {+ runtime.LockOSThread()+ if err := windows.ImpersonateSelf(windows.SecurityImpersonation); err != nil {+ runtime.UnlockOSThread()+ done <- fn()+ return+ }+ enablePrivileges("SeRestorePrivilege", "SeTakeOwnershipPrivilege", "SeBackupPrivilege")+ err := fn()+ if rerr := windows.RevertToSelf(); rerr != nil {+ // Leave the thread locked: a goroutine that exits while locked takes its thread with+ // it, so the impersonation token cannot leak to other goroutines.+ done <- errors.Join(err, fmt.Errorf("revert impersonation: %w", rerr))+ return+ }+ runtime.UnlockOSThread()+ done <- err+ }()+ return <-done+}++func enablePrivileges(names ...string) {+ var token windows.Token+ if err := windows.OpenThreadToken(windows.CurrentThread(), windows.TOKEN_ADJUST_PRIVILEGES|windows.TOKEN_QUERY, true, &token); err != nil {+ return+ }+ defer token.Close()+ for _, name := range names {+ var luid windows.LUID+ p, err := windows.UTF16PtrFromString(name)+ if err != nil {+ continue+ }+ if err := windows.LookupPrivilegeValue(nil, p, &luid); err != nil {+ continue+ }+ privileges := windows.Tokenprivileges{PrivilegeCount: 1}+ privileges.Privileges[0] = windows.LUIDAndAttributes{Luid: luid, Attributes: windows.SE_PRIVILEGE_ENABLED}+ _ = windows.AdjustTokenPrivileges(token, false, &privileges, 0, nil, nil)+ }+}++func skipSet(paths []string) map[string]bool {+ out := make(map[string]bool, len(paths))+ for _, p := range paths {+ if p != "" {+ out[normPath(p)] = true+ }+ }+ return out+}++func normPath(p string) string { return strings.ToLower(filepath.Clean(p)) }diff --git a/cli/beacon/internal/endpoint/sysacl/sysacl_windows_test.go b/cli/beacon/internal/endpoint/sysacl/sysacl_windows_test.gonew file mode 100644index 00000000..6d4c0291--- /dev/null+++ b/cli/beacon/internal/endpoint/sysacl/sysacl_windows_test.go@@ -0,0 +1,250 @@+//go:build windows++package sysacl++import (+ "os"+ "os/exec"+ "path/filepath"+ "reflect"+ "strings"+ "testing"++ "golang.org/x/sys/windows"+)++// requireElevated skips when this process cannot set Administrators as an owner. The endpoint+// install already requires elevation and the Windows CI runner has it; an unelevated contributor+// should see a skip, not a red suite.+func requireElevated(t *testing.T) {+ t.Helper()+ token, err := windows.OpenCurrentProcessToken()+ if err != nil {+ t.Skipf("open the process token: %v", err)+ }+ defer token.Close()+ if !token.IsElevated() {+ t.Skip("setting the Beacon ACLs needs an elevated shell")+ }+}++func icacls(t *testing.T, args ...string) {+ t.Helper()+ if out, err := exec.Command("icacls", args...).CombinedOutput(); err != nil {+ t.Fatalf("icacls %s: %v: %s", strings.Join(args, " "), err, strings.TrimSpace(string(out)))+ }+}++func mustRead(t *testing.T, path string) Object {+ t.Helper()+ obj, err := ReadObject(path)+ if err != nil {+ t.Fatalf("read the security of %s: %v", path, err)+ }+ return obj+}++// assertNoUserMayChange checks the directory itself, as read back from Windows: owned by+// Administrators, inheritance off, and no principal other than SYSTEM and Administrators holds a+// right that adds, removes or renames entries, writes its attributes, or changes its security.+func assertNoUserMayChange(t *testing.T, dir string) {+ t.Helper()+ obj := mustRead(t, dir)+ if obj.Owner != sidAdministrators {+ t.Errorf("%s is owned by %s, want Administrators", dir, obj.Owner)+ }+ if !obj.Protected {+ t.Errorf("%s still inherits from its parent", dir)+ }+ for _, ace := range obj.DACL {+ if ace.Type != aceTypeAllowed || trustedPrincipal(ace.SID) || ace.Flags&aceInheritOnly != 0 {+ continue+ }+ if bad := ace.Mask & (fileWriteData | fileAppendData | fileDeleteChild | accessDelete | writeDAC | writeOwner | fileWriteAttributes | genericWrite | genericAll); bad != 0 {+ t.Errorf("%s grants %s 0x%x on the directory itself", dir, ace.SID, bad)+ }+ }+}++func TestSecureLogDirReplacesTheLegacyGrant(t *testing.T) {+ requireElevated(t)+ dir := filepath.Join(t.TempDir(), "logs")+ if err := os.MkdirAll(dir, 0o755); 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)+ }+ }+ icacls(t, dir, "/grant", `*S-1-5-4:(OI)(CI)(M)`, "/T")+ notesBefore := mustRead(t, filepath.Join(dir, "operator-notes.txt"))++ if err := SecureLogDir(dir, "runtime.jsonl"); err != nil {+ t.Fatalf("SecureLogDir: %v", err)+ }++ assertNoUserMayChange(t, dir)+ state, err := InspectLogDir(dir, "runtime.jsonl")+ if err != nil {+ t.Fatal(err)+ }+ if len(state.Problems) > 0 {+ t.Fatalf("the secured log directory reads back with problems: %v", state.Problems)+ }+ if !state.HooksCanAppend {+ t.Fatal("hooks can no longer append to the secured log")+ }+ for _, name := range []string{"runtime.jsonl", "runtime.jsonl.lock", "runtime.jsonl.1"} {+ obj := mustRead(t, filepath.Join(dir, name))+ want := InheritedDACL(LogDirDACL(), false)+ if !reflect.DeepEqual(obj.DACL, want) {+ t.Errorf("%s carries %+v, want exactly the inherited %+v", name, obj.DACL, want)+ }+ }+ // A file outside the log family is the operator's, and Beacon never writes it.+ 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)+ }++ // New files -- the log the collector re-creates on rotation -- inherit the append grant and+ // nothing more.+ rotated := filepath.Join(dir, "runtime.jsonl.2")+ if err := os.WriteFile(rotated, nil, 0o666); err != nil {+ t.Fatal(err)+ }+ obj := mustRead(t, rotated)+ if !CanAppend(obj.DACL, obj.NullDACL, false) {+ t.Errorf("a newly created log does not inherit the append grant: %+v", obj.DACL)+ }+ if problems := Problems(Object{Owner: sidAdministrators, DACL: obj.DACL}, KindLogFile); len(problems) > 0 {+ t.Errorf("a newly created log inherits too much: %v", problems)+ }+}++// A junction in place of the log directory sends every SYSTEM write to its target. Securing the+// path must replace the link with a real directory and leave the target untouched.+func TestSecureLogDirReplacesAJunctionWithoutTouchingItsTarget(t *testing.T) {+ requireElevated(t)+ root := t.TempDir()+ target := filepath.Join(root, "elsewhere")+ if err := os.MkdirAll(target, 0o755); err != nil {+ t.Fatal(err)+ }+ dir := filepath.Join(root, "logs")+ if out, err := exec.Command("cmd", "/c", "mklink", "/J", dir, target).CombinedOutput(); err != nil {+ t.Skipf("create a junction: %v: %s", err, strings.TrimSpace(string(out)))+ }+ before := mustRead(t, target)++ if err := SecureLogDir(dir, "runtime.jsonl"); err != nil {+ t.Fatalf("SecureLogDir: %v", err)+ }+ info, err := os.Lstat(dir)+ if err != nil {+ t.Fatal(err)+ }+ if info.Mode()&(os.ModeSymlink|os.ModeIrregular) != 0 || !info.IsDir() {+ t.Fatalf("%s is still a link (mode %v)", dir, info.Mode())+ }+ assertNoUserMayChange(t, dir)+ if after := mustRead(t, target); !reflect.DeepEqual(before, after) {+ t.Fatalf("the junction's target was re-secured: %+v -> %+v", before, after)+ }+}++// Links planted under the old grant -- a symbolic link named like the lock, a hard link named like+// an archive -- are removed, never followed, and what they point to keeps its security.+func TestSecureLogDirRemovesPlantedLinks(t *testing.T) {+ requireElevated(t)+ root := t.TempDir()+ victim := filepath.Join(root, "victim.txt")+ if err := os.WriteFile(victim, []byte("not Beacon's"), 0o644); err != nil {+ t.Fatal(err)+ }+ dir := filepath.Join(root, "logs")+ if err := os.MkdirAll(dir, 0o755); err != nil {+ t.Fatal(err)+ }+ before := mustRead(t, victim)++ planted := []string{}+ if err := os.Symlink(victim, filepath.Join(dir, "runtime.jsonl.lock")); err == nil {+ planted = append(planted, "runtime.jsonl.lock")+ }+ if err := os.Link(victim, filepath.Join(dir, "runtime.jsonl.3")); err == nil {+ planted = append(planted, "runtime.jsonl.3")+ }+ if len(planted) == 0 {+ t.Skip("could not create either kind of link here")+ }++ if err := SecureLogDir(dir, "runtime.jsonl"); err != nil {+ t.Fatalf("SecureLogDir: %v", err)+ }+ for _, name := range planted {+ if _, err := os.Lstat(filepath.Join(dir, name)); !os.IsNotExist(err) {+ t.Errorf("the planted link %s survived: %v", name, err)+ }+ }+ if data, err := os.ReadFile(victim); err != nil || string(data) != "not Beacon's" {+ t.Fatalf("the link target was changed or removed: %q, %v", data, err)+ }+ if after := mustRead(t, victim); !reflect.DeepEqual(before, after) {+ t.Fatalf("the link target was re-secured: %+v -> %+v", before, after)+ }+}++// %ProgramData% lets any user create a subdirectory, so %ProgramData%\Beacon may exist, owned by+// someone else, before the package is installed. It is reset, not trusted; what is unsafe below it+// is reset; what an administrator deliberately locked down further is left alone.+func TestSecureSystemTreeResetsAPreCreatedRoot(t *testing.T) {+ requireElevated(t)+ root := filepath.Join(t.TempDir(), "Beacon")+ open := filepath.Join(root, "Endpoint", "hooks")+ locked := filepath.Join(root, "Endpoint", "asymptote")+ logs := filepath.Join(root, "Endpoint", "logs")+ for _, d := range []string{open, logs} {+ if err := os.MkdirAll(d, 0o755); err != nil {+ t.Fatal(err)+ }+ }+ binary := filepath.Join(open, "beacon-hooks.exe")+ if err := os.WriteFile(binary, []byte("MZ"), 0o755); err != nil {+ t.Fatal(err)+ }+ // Users full control over the whole tree, as a directory someone else made might grant.+ icacls(t, root, "/grant", `*S-1-5-32-545:(OI)(CI)(F)`, "/T")+ // Created afterwards and cut off from it: owned by Administrators, SYSTEM and Administrators+ // only. Stricter than the tree, and so to be left alone.+ if err := os.MkdirAll(locked, 0o755); err != nil {+ t.Fatal(err)+ }+ icacls(t, locked, "/inheritance:r", "/grant:r", `*S-1-5-18:(OI)(CI)(F)`, `*S-1-5-32-544:(OI)(CI)(F)`)+ icacls(t, locked, "/setowner", `*S-1-5-32-544`)+ lockedBefore := mustRead(t, locked)+ logsBefore := mustRead(t, logs)++ if err := SecureSystemTree(root, logs); err != nil {+ t.Fatalf("SecureSystemTree: %v", err)+ }++ assertNoUserMayChange(t, root)+ if obj := mustRead(t, root); !reflect.DeepEqual(obj.DACL, TreeDACL()) {+ t.Errorf("the root carries %+v, want %+v", obj.DACL, TreeDACL())+ }+ for _, p := range []string{filepath.Join(root, "Endpoint"), open} {+ if problems, err := InspectTree(p, KindDir); err != nil || len(problems) > 0 {+ t.Errorf("%s after the reset: %v, %v", p, problems, err)+ }+ }+ if problems, err := InspectTree(binary, KindFile); err != nil || len(problems) > 0 {+ t.Errorf("the hooks binary after the reset: %v, %v", problems, err)+ }+ if after := mustRead(t, locked); !reflect.DeepEqual(lockedBefore, after) {+ t.Errorf("a directory already locked down further was changed: %+v -> %+v", lockedBefore, after)+ }+ if after := mustRead(t, logs); !reflect.DeepEqual(logsBefore, after) {+ t.Errorf("the skipped log directory was changed: %+v -> %+v", logsBefore, after)+ }+}diff --git a/cli/beacon/internal/endpoint/writer/acl_other.go b/cli/beacon/internal/endpoint/writer/acl_other.goindex 85edd286..0e3bb7b3 100644--- a/cli/beacon/internal/endpoint/writer/acl_other.go+++ b/cli/beacon/internal/endpoint/writer/acl_other.go@@ -3,17 +3,20 @@package writer// POSIX carries this in the file mode instead: openRuntimeFile creates the runtime log 0666 so-// hooks running as the console user can append to a log the elevated collector created. There is-// no separate ACL step to perform, and no separate state to check.+// hooks running as the console user can append to a log the elevated collector created, inside a+// root-owned 0755 directory they cannot add to or remove from. There is no separate ACL step to+// perform, and no separate state to check.-func grantInteractiveUsersWrite(dir string) error { return nil }+func secureSystemLog(path string) error { return nil }-// interactiveUsersCanWrite reports true because the equivalent guarantee is the file mode, which-// EnsureRuntimeFile already establishes. Reporting false here would make doctor demand a fix that-// does not exist on this platform.-func interactiveUsersCanWrite(dir string) (bool, error) { return true, nil }+// inspectSystemLog reports hooks can append because the equivalent guarantee is the file mode,+// which EnsureRuntimeFile already establishes. Reporting otherwise here would make doctor demand a+// fix that does not exist on this platform.+func inspectSystemLog(path string) (LogACLState, error) {+ return LogACLState{HooksCanAppend: true}, nil+}// GrantCommandHint is empty because there is no grant to run here. Callers use the empty string to-// mean "this remediation does not apply on this platform" rather than printing an icacls command to+// mean "this remediation does not apply on this platform" rather than printing a Windows command to// someone on a Mac.func GrantCommandHint(dir string) string { return "" }diff --git a/cli/beacon/internal/endpoint/writer/acl_other_test.go b/cli/beacon/internal/endpoint/writer/acl_other_test.gonew file mode 100644index 00000000..d7180007--- /dev/null+++ b/cli/beacon/internal/endpoint/writer/acl_other_test.go@@ -0,0 +1,8 @@+//go:build !windows++package writer++import "testing"++// requireSystemACLRights is a no-op where the system log has no ACL step to apply.+func requireSystemACLRights(t *testing.T) { t.Helper() }diff --git a/cli/beacon/internal/endpoint/writer/acl_windows.go b/cli/beacon/internal/endpoint/writer/acl_windows.goindex db956406..81e4f86b 100644--- a/cli/beacon/internal/endpoint/writer/acl_windows.go+++ b/cli/beacon/internal/endpoint/writer/acl_windows.go@@ -3,195 +3,68 @@package writerimport (- "fmt"- "os/exec"- "strings"- "unsafe"+ "os"+ "path/filepath"- "golang.org/x/sys/windows"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/sysacl")-// grantInteractiveUsersWrite makes a machine-wide log directory writable by ordinary users.+// secureSystemLog gives a machine-wide log directory the one ACL under which hooks can append and+// nobody but SYSTEM and Administrators can change what is in it.//-// This is the Windows counterpart to the 0666 runtime log on POSIX, and it exists for the same-// reason: a system-mode collector runs elevated and creates the log, while hooks run as the person-// at the keyboard and append to it. On POSIX the file mode carries that. Windows has no mode ---// %ProgramData% subdirectories inherit an ACL where only administrators and SYSTEM may write, so-// without an explicit grant every hook write fails with access denied.+// This is the Windows counterpart to the 0666 runtime log in a root-owned 0755 directory on POSIX,+// and it exists for the same reason: a system-mode collector runs as LocalSystem and creates the+// log, while hooks run as the person at the keyboard and append to it. %ProgramData%+// subdirectories inherit an ACL where ordinary users cannot write existing files, so without a+// grant every hook write fails with access denied -- quietly, because status and doctor describe+// the collector rather than the hooks exporting to it.//-// The failure that makes it worth doing at install time is the quiet one. Nothing errors visibly:-// the collector is healthy, `endpoint status` reports running, and `doctor` agrees -- because all-// of them describe the collector, not the hooks that export to it. The log simply stays empty of-// anything the agent did. That is the same shape as the Linux SUDO_USER bug, where a package-// install produced a perfectly healthy collector that captured nothing.+// The grant used to be Modify for INTERACTIVE on the directory, recursively. That let any logged-on+// user delete the log and its archives, empty the directory, turn it into a junction and plant+// links named runtime.jsonl, runtime.jsonl.N or the lock -- so the collector, running as SYSTEM,+// would create or append to a file of the user's choosing. sysacl.LogDirDACL replaces it: the+// directory is owned by Administrators with inheritance disabled, SYSTEM and Administrators have+// full control, Users read and traverse, and INTERACTIVE holds read and write data on the files+// in the directory only, through an inherit-only entry. Users cannot create, delete or rename+// anything there, and cannot change the security of the files they append to.//-// Granted to INTERACTIVE rather than Users or Everyone. INTERACTIVE covers anyone logged on at the-// machine, which is exactly the set whose agent sessions this endpoint is meant to capture, and-// excludes service and network logons that have no business writing here.-//-// (OI)(CI) makes the grant inherit to files and subdirectories created later, so the log and its-// rotated archives are covered without re-running this after every rotation.-func grantInteractiveUsersWrite(dir string) error {- out, err := exec.Command("icacls", grantArgs(dir)...).CombinedOutput()- if err != nil {- return fmt.Errorf("grant interactive users write access to %s: %w: %s",- dir, err, strings.TrimSpace(string(out)))- }- return nil-}--// grantArgs is the single definition of the grant.-//-// icacls rather than the security APIs directly: it is present on every supported Windows, its-// argument form is stable, and the equivalent through SetNamedSecurityInfo means building an ACL by-// hand for a grant an administrator can read and audit in one line.-//-// The `*` prefix passes the well-known SID literally, so this does not depend on the machine's-// display language the way an `INTERACTIVE` or `INTERAKTIV` spelling would.-//-// One definition because doctor prints this command as the remediation for a missing grant. Advice-// that has drifted from the implementation is worse than no advice: an operator runs it, doctor-// still reports the failure, and the next thing they doubt is the diagnosis rather than the hint.-func grantArgs(dir string) []string {- return []string{dir, "/grant", `*S-1-5-4:(OI)(CI)(M)`, "/T"}-}--// GrantCommandHint renders the grant as a command an operator can paste.-//-// Empty on platforms with no such grant, which is how callers tell that this remediation does not-// apply rather than printing a Windows command on a Mac.-//-// Quoting matters here in a way it does not for the grant itself: applying it goes through argv-// with no shell involved, while this is read by a person and pasted into whichever shell they have-// open. The rights string carries parentheses, which PowerShell reads as grouping, so an unquoted-// hint is a command that fails on paste -- and a remediation that fails on paste is worse than-// none, because the operator concludes the diagnosis was wrong.-func GrantCommandHint(dir string) string {- parts := make([]string, 0, len(grantArgs(dir))+1)- parts = append(parts, "icacls")- for _, arg := range grantArgs(dir) {- parts = append(parts, quoteForShellPaste(arg))+// Because users cannot create files, the log and its lock are created here, by the elevated+// install, so a hook always finds them. Rotation is the privileged writers' job on Windows (the+// collector and the CLI running as SYSTEM or an administrator); a hook that finds the log over+// its size limit appends anyway and leaves the rename to them.+func secureSystemLog(path string) error {+ dir := filepath.Dir(path)+ if err := sysacl.SecureLogDir(dir, filepath.Base(path)); err != nil {+ return err}- return strings.Join(parts, " ")-}--// quoteForShellPaste wraps anything either Windows shell would not pass through literally.-//-// An allowlist rather than a list of metacharacters: cmd.exe and PowerShell disagree about which-// characters are special, and the set that is safe in both is small and easy to state. Double-// quotes work in both for everything here, and no argument in this command contains one, so simple-// wrapping is enough -- if that ever changes this needs the escaping rules too, not just the quotes.-func quoteForShellPaste(arg string) string {- safe := func(r rune) bool {- switch {- case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9':- return true- }- return strings.ContainsRune(`\/.:_-`, r)+ // Created after the directory ACL is in place, so both inherit the append grant.+ lock, err := openRuntimeFile(path+".lock", os.O_CREATE|os.O_RDWR)+ if err != nil {+ return err}- for _, r := range arg {- if !safe(r) {- return `"` + arg + `"`- }+ _ = lock.Close()+ f, err := openRuntimeFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY)+ if err != nil {+ return err}- return arg+ return f.Close()}-// Rights that answer the question doctor is actually asking: can a hook running as the logged-on-// user create the runtime log if it is missing, and append to it if it is not.-//-// Both bits are required. FILE_APPEND_DATA alone cannot create the file, and FILE_WRITE_DATA alone-// on a directory does not permit adding entries to it, so a grant carrying only one of them leaves-// a hook that still fails -- just at a different call.-const writeAccessMask = uint32(windows.FILE_WRITE_DATA | windows.FILE_APPEND_DATA)--// inheritOnlyACE marks an entry that applies to children but not to the object carrying it.-// Not exported by x/sys/windows, and needed here because such an entry must not read as a grant:-// the directory itself has to be writable for a hook to create the log in the first place.-const inheritOnlyACE = 0x08--type aceVerdict int--const (- aceIrrelevant aceVerdict = iota- aceAllowsWrite- aceDeniesWrite-)--// classifyACE decides what one access control entry says about interactive write access.+// inspectSystemLog reports whether hooks can append and what, if anything, grants more.//-// Split out from the DACL walk so it can be tested against entry shapes that are tedious to-// construct on a real directory -- inherit-only grants, deny entries, partial masks.-func classifyACE(aceType, aceFlags uint8, mask uint32, matchesSID bool) aceVerdict {- if !matchesSID || aceFlags&inheritOnlyACE != 0 {- return aceIrrelevant- }- switch aceType {- case windows.ACCESS_DENIED_ACE_TYPE:- // Any overlap denies. A deny of one of the two bits is enough to break a hook, and Windows- // evaluates a matching deny ahead of any grant, so partial credit would be wrong here.- if mask&writeAccessMask != 0 {- return aceDeniesWrite- }- case windows.ACCESS_ALLOWED_ACE_TYPE:- // GENERIC_WRITE is normally mapped to its specific rights when an entry is stored, but it- // survives in entries written by some tooling, and it subsumes both bits.- if mask&writeAccessMask == writeAccessMask || mask&windows.GENERIC_WRITE != 0 {- return aceAllowsWrite- }- }- return aceIrrelevant+// Read through the security APIs rather than by attempting a write: doctor runs elevated, so a test+// write would succeed regardless and report healthy for exactly the configuration that is broken.+// Read by SID rather than by parsing icacls output, which names accounts in the display language.+func inspectSystemLog(path string) (LogACLState, error) {+ state, err := sysacl.InspectLogDir(filepath.Dir(path), filepath.Base(path))+ return LogACLState{HooksCanAppend: state.HooksCanAppend, Problems: state.Problems}, err}-// interactiveUsersCanWrite reports whether the grant is in place, for doctor.+// GrantCommandHint is the command that restores the log directory ACL.//-// Checked by reading the ACL rather than by attempting a write: doctor runs elevated, so a test-// write would succeed regardless and report healthy for exactly the configuration that is broken.-// That is the trap this check exists to avoid, so it must not fall into it.-//-// Read through the security APIs rather than by parsing `icacls` output. The text form is a-// rendering for humans and varies with the things a rendering varies with: it resolves the SID to a-// localized account name, so a correctly granted directory reads as ungranted on a German or-// Japanese install, and it prints an expanded rights list instead of the short `(M)` alias whenever-// the mask is not exactly one of the aliases. Both produce the same wrong answer -- doctor telling-// an administrator their working endpoint is broken -- and neither is visible from an English test-// machine, which is every machine this would be tested on.-func interactiveUsersCanWrite(dir string) (bool, error) {- sd, err := windows.GetNamedSecurityInfo(dir, windows.SE_FILE_OBJECT, windows.DACL_SECURITY_INFORMATION)- if err != nil {- return false, fmt.Errorf("read the access control list on %s: %w", dir, err)- }- dacl, _, err := sd.DACL()- if err != nil {- return false, fmt.Errorf("read the discretionary access control list on %s: %w", dir, err)- }- if dacl == nil {- // A NULL DACL grants everyone full control. Alarming, and worth surfacing elsewhere, but- // the question here is only whether hooks can write -- and they can.- return true, nil- }-- interactive, err := windows.CreateWellKnownSid(windows.WinInteractiveSid)- if err != nil {- return false, fmt.Errorf("resolve the INTERACTIVE security identifier: %w", err)- }-- allowed := false- 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, fmt.Errorf("read access control entry %d on %s: %w", i, dir, err)- }- // Every ACE type this cares about carries its SID at the same offset; the field is named- // SidStart because the identifier is variable length and runs past the struct.- sid := (*windows.SID)(unsafe.Pointer(&ace.SidStart))- switch classifyACE(ace.Header.AceType, ace.Header.AceFlags, uint32(ace.Mask), sid.Equals(interactive)) {- case aceDeniesWrite:- // A deny anywhere in the list settles it, whatever else grants.- return false, nil- case aceAllowsWrite:- allowed = true- }- }- return allowed, nil+// It used to print an icacls grant. The ACL is now several entries, an owner, inheritance turned+// off and a reset of the log family's files, and printing a hand-run equivalent would be advice+// that drifts from the implementation. doctor --fix runs the same code the install does.+func GrantCommandHint(dir string) string {+ return "beacon endpoint doctor --system --fix (from an elevated shell)"}diff --git a/cli/beacon/internal/endpoint/writer/acl_windows_test.go b/cli/beacon/internal/endpoint/writer/acl_windows_test.goindex 2ef0bba6..31ea5b69 100644--- a/cli/beacon/internal/endpoint/writer/acl_windows_test.go+++ b/cli/beacon/internal/endpoint/writer/acl_windows_test.go@@ -3,216 +3,106 @@package writerimport (+ "os""os/exec"+ "path/filepath""strings""testing""golang.org/x/sys/windows")-func TestClassifyACEReadsTheEntryShapesThatDecideAccess(t *testing.T) {- const (- writeData = uint32(windows.FILE_WRITE_DATA)- appendData = uint32(windows.FILE_APPEND_DATA)- readData = uint32(windows.FILE_READ_DATA)- )-- cases := []struct {- name string- aceType uint8- aceFlags uint8- mask uint32- matchesSID bool- want aceVerdict- }{- {- name: "the grant install writes",- aceType: windows.ACCESS_ALLOWED_ACE_TYPE,- mask: writeData | appendData,- matchesSID: true,- want: aceAllowsWrite,- },- {- // The whole reason this is not a substring search for a rendered name.- name: "another principal's full control says nothing about INTERACTIVE",- aceType: windows.ACCESS_ALLOWED_ACE_TYPE,- mask: writeData | appendData,- matchesSID: false,- want: aceIrrelevant,- },- {- // A hook that cannot create the log fails as surely as one that cannot append to it,- // so half the mask is not half a pass.- name: "append without write cannot create the log",- aceType: windows.ACCESS_ALLOWED_ACE_TYPE,- mask: appendData,- matchesSID: true,- want: aceIrrelevant,- },- {- name: "write without append cannot extend the log",- aceType: windows.ACCESS_ALLOWED_ACE_TYPE,- mask: writeData,- matchesSID: true,- want: aceIrrelevant,- },- {- name: "read access is not write access",- aceType: windows.ACCESS_ALLOWED_ACE_TYPE,- mask: readData,- matchesSID: true,- want: aceIrrelevant,- },- {- name: "generic write subsumes both bits",- aceType: windows.ACCESS_ALLOWED_ACE_TYPE,- mask: windows.GENERIC_WRITE,- matchesSID: true,- want: aceAllowsWrite,- },- {- // The directory itself must be writable: a hook creates the log when it is missing.- name: "an inherit-only grant does not make this directory writable",- aceType: windows.ACCESS_ALLOWED_ACE_TYPE,- aceFlags: inheritOnlyACE,- mask: writeData | appendData,- matchesSID: true,- want: aceIrrelevant,- },- {- name: "a deny of either bit is a deny",- aceType: windows.ACCESS_DENIED_ACE_TYPE,- mask: appendData,- matchesSID: true,- want: aceDeniesWrite,- },- {- name: "a deny of unrelated rights is not a deny of write",- aceType: windows.ACCESS_DENIED_ACE_TYPE,- mask: readData,- matchesSID: true,- want: aceIrrelevant,- },- {- name: "an inherit-only deny does not apply to this directory",- aceType: windows.ACCESS_DENIED_ACE_TYPE,- aceFlags: inheritOnlyACE,- mask: writeData | appendData,- matchesSID: true,- want: aceIrrelevant,- },+// requireSystemACLRights skips a test that applies the system log ACL when this process cannot.+//+// Setting Administrators as the owner needs an elevated token, which the endpoint install already+// requires and the Windows CI runner has. Skipped rather than failed elsewhere: a contributor+// running the suite unelevated should not see a red suite for a step their shell cannot perform.+func requireSystemACLRights(t *testing.T) {+ t.Helper()+ token, err := windows.OpenCurrentProcessToken()+ if err != nil {+ t.Skipf("open the process token: %v", err)}-- for _, tc := range cases {- t.Run(tc.name, func(t *testing.T) {- got := classifyACE(tc.aceType, tc.aceFlags, tc.mask, tc.matchesSID)- if got != tc.want {- t.Fatalf("classifyACE = %v, want %v", got, tc.want)- }- })+ defer token.Close()+ if !token.IsElevated() {+ t.Skip("applying the system log ACL needs an elevated shell")}}-// TestGrantAndReadBackAgree exercises the halves against each other on a real directory.-//-// They are written against different interfaces -- the grant shells out to icacls, the read walks-// the DACL through the security APIs -- so nothing but a test like this catches them drifting-// apart. A reader that silently answered "no" to a directory the granter had just fixed would make-// doctor report a working endpoint as broken, and it would do so only on machines nobody develops-// on.-//-// Every step here needs administrator rights, which the endpoint install already requires and the-// Windows CI runner already has. Skipped rather than failed elsewhere: a contributor running the-// suite unelevated should not see a red suite for a check their shell cannot perform.-func TestGrantAndReadBackAgree(t *testing.T) {- dir := t.TempDir()-- // Strip inheritance so the starting state is known: administrators only, no INTERACTIVE. This- // is what makes the negative half real -- without it the answer could be "true" before the- // grant, and a reader hardcoded to return true would pass.- if out, err := exec.Command("icacls", dir, "/inheritance:r", "/grant", `*S-1-5-32-544:(OI)(CI)(F)`).CombinedOutput(); err != nil {- t.Skipf("could not take ownership of the ACL on %s (needs an elevated shell): %v: %s",- dir, err, strings.TrimSpace(string(out)))+// TestEnsureSystemLogWritableAndDoctorAgree exercises the halves against each other on a real+// directory: what install applies must read back as healthy, and the grant this replaced must read+// back as the problem it is.+func TestEnsureSystemLogWritableAndDoctorAgree(t *testing.T) {+ requireSystemACLRights(t)+ dir := filepath.Join(t.TempDir(), "logs")+ if err := os.MkdirAll(dir, 0o755); err != nil {+ t.Fatal(err)}+ path := filepath.Join(dir, "runtime.jsonl")- if writable, err := interactiveUsersCanWrite(dir); err != nil {- t.Fatalf("read the ACL before granting: %v", err)- } else if writable {- t.Fatal("a directory granting only administrators reported interactive users can write; " +- "the reader cannot distinguish a granted directory from an ungranted one")+ // The grant every endpoint installed before this change carries: Modify for INTERACTIVE on+ // the directory, recursively, over a log and an archive a hook created.+ for _, name := range []string{"runtime.jsonl", "runtime.jsonl.1"} {+ if err := os.WriteFile(filepath.Join(dir, name), []byte("{}\n"), 0o666); err != nil {+ t.Fatal(err)+ }}-- if err := grantInteractiveUsersWrite(dir); err != nil {- t.Fatalf("grant interactive write access: %v", err)+ if out, err := exec.Command("icacls", dir, "/grant", `*S-1-5-4:(OI)(CI)(M)`, "/T").CombinedOutput(); err != nil {+ t.Fatalf("apply the legacy grant: %v: %s", err, strings.TrimSpace(string(out)))+ }+ before, err := CheckSystemLogACL(path)+ if err != nil {+ t.Fatalf("read the legacy ACL: %v", err)+ }+ if len(before.Problems) == 0 {+ t.Fatal("doctor reads Modify for INTERACTIVE on the log directory as healthy; that grant " ++ "lets any logged-on user delete the log and plant links a SYSTEM write follows")}- if writable, err := interactiveUsersCanWrite(dir); err != nil {- t.Fatalf("read the ACL after granting: %v", err)- } else if !writable {- t.Fatal("the directory the granter just fixed reads as not writable by interactive users; " ++ if err := EnsureSystemLogWritable(path); err != nil {+ t.Fatalf("EnsureSystemLogWritable: %v", err)+ }+ after, err := CheckSystemLogACL(path)+ if err != nil {+ t.Fatalf("read the ACL after securing: %v", err)+ }+ if len(after.Problems) > 0 {+ t.Fatalf("the ACL install applies reads back with problems: %v", after.Problems)+ }+ if !after.HooksCanAppend {+ t.Fatal("the ACL install applies reads back as not appendable by interactive users; " +"doctor would report a healthy endpoint as broken")}+ for _, target := range []string{path, path + ".lock"} {+ if _, err := os.Stat(target); err != nil {+ t.Fatalf("%s was not created; users cannot create files in the log directory, so "++ "install has to: %v", target, err)+ }+ }- // A deny entry outranks the grant, and doctor must say so: hooks would fail here despite the+ // A deny entry outranks the grant, and doctor must say so: hooks would fail despite the// allow entry still being present.- if out, err := exec.Command("icacls", dir, "/deny", `*S-1-5-4:(WD)`).CombinedOutput(); err != nil {+ if out, err := exec.Command("icacls", path, "/deny", `*S-1-5-4:(AD)`).CombinedOutput(); err != nil {t.Fatalf("add a deny entry: %v: %s", err, strings.TrimSpace(string(out)))}- if writable, err := interactiveUsersCanWrite(dir); err != nil {+ denied, err := CheckSystemLogACL(path)+ if err != nil {t.Fatalf("read the ACL after denying: %v", err)- } else if writable {- t.Fatal("an explicit deny of write access reported as writable; " +- "the grant was read without the deny that overrides it")}-}--// TestGrantCommandHintQuotesThePathItPrints covers the half of the grant an operator runs by hand.-//-// doctor prints this when the grant is missing, and the default log directory lives under-// %ProgramData%. A hint that breaks at the first space would be pasted, would fail, and would send-// the operator looking for a problem in the diagnosis instead of the advice.-func TestGrantCommandHintQuotesThePathItPrints(t *testing.T) {- hint := GrantCommandHint(`C:\Program Files\Beacon\logs`)- if !strings.Contains(hint, `"C:\Program Files\Beacon\logs"`) {- t.Fatalf("GrantCommandHint left a path containing a space unquoted: %s", hint)- }- // The rights string carries parentheses, which PowerShell reads as grouping rather than as- // part of an argument. Unquoted, the hint is a command that fails the moment it is pasted.- if !strings.Contains(hint, `"*S-1-5-4:(OI)(CI)(M)"`) {- t.Fatalf("GrantCommandHint left the rights string unquoted: %s; "+- "PowerShell would try to evaluate the parentheses", hint)- }- // Same definition as the applied grant, so the advice cannot drift from the implementation.- for _, arg := range grantArgs(`C:\Program Files\Beacon\logs`)[1:] {- if !strings.Contains(hint, arg) {- t.Fatalf("GrantCommandHint omits %q from the grant it claims to describe: %s", arg, hint)- }- }- // Plain flags stay readable: quoting everything would work but makes the line harder to scan,- // and this is read before it is run.- if !strings.Contains(hint, " /grant ") || !strings.HasSuffix(hint, " /T") {- t.Fatalf("GrantCommandHint quoted arguments that needed no quoting: %s", hint)+ if denied.HooksCanAppend {+ t.Fatal("an explicit deny of append on the log reads as appendable")}}-func TestQuoteForShellPasteCoversWhatBothWindowsShellsTreatSpecially(t *testing.T) {- // Safe in cmd.exe and PowerShell alike, so left alone.- for _, arg := range []string{`/T`, `/grant`, `C:\ProgramData\Beacon\logs`, `icacls`, `S-1-5-4`} {- if got := quoteForShellPaste(arg); got != arg {- t.Fatalf("quoteForShellPaste(%q) = %q, want it unchanged", arg, got)- }+// TestGrantCommandHintIsTheRepairCommand covers the half of the repair an operator runs by hand.+// The ACL is several entries, an owner and a reset of the log's files, so the advice is the command+// that runs the same code install does rather than a hand-written equivalent that could drift.+func TestGrantCommandHintIsTheRepairCommand(t *testing.T) {+ hint := GrantCommandHint(`C:\ProgramData\Beacon\Endpoint\logs`)+ if !strings.Contains(hint, "doctor") || !strings.Contains(hint, "--fix") || !strings.Contains(hint, "--system") {+ t.Fatalf("GrantCommandHint = %q, want the elevated doctor --system --fix repair", hint)}- // Each of these is special to at least one of the two shells.- for _, arg := range []string{- `*S-1-5-4:(OI)(CI)(M)`,- `C:\Program Files\Beacon`,- `C:\logs&more`,- `C:\logs;more`,- `C:\logs$more`,- `C:\logs'more`,- } {- if got := quoteForShellPaste(arg); got != `"`+arg+`"` {- t.Fatalf("quoteForShellPaste(%q) = %q, want it quoted", arg, got)- }+ if strings.Contains(hint, "icacls") {+ t.Fatalf("GrantCommandHint = %q still prints an icacls grant", hint)}}diff --git a/cli/beacon/internal/endpoint/writer/ensure_test.go b/cli/beacon/internal/endpoint/writer/ensure_test.goindex b572e940..20e8432c 100644--- a/cli/beacon/internal/endpoint/writer/ensure_test.go+++ b/cli/beacon/internal/endpoint/writer/ensure_test.go@@ -19,10 +19,11 @@ import (// directory has to exist either way, and keeping that guarantee in the shared function is what// stops the next platform from reintroducing it.func TestEnsureSystemLogWritableCreatesTheDirectoryItIsAskedAbout(t *testing.T) {+ requireSystemACLRights(t)// Nested, so this fails if the implementation only creates a leaf under an existing parent.dir := filepath.Join(t.TempDir(), "Beacon", "Endpoint", "logs")- if err := EnsureSystemLogWritable(dir); err != nil {+ if err := EnsureSystemLogWritable(filepath.Join(dir, "runtime.jsonl")); err != nil {t.Fatalf("EnsureSystemLogWritable on a directory that does not exist yet: %v", err)}@@ -38,9 +39,10 @@ func TestEnsureSystemLogWritableCreatesTheDirectoryItIsAskedAbout(t *testing.T)func TestEnsureSystemLogWritableIsRepeatable(t *testing.T) {// Repair and reinstall both call this over a live endpoint, so a second call must not fail on// the directory it created the first time.- dir := filepath.Join(t.TempDir(), "logs")+ requireSystemACLRights(t)+ path := filepath.Join(t.TempDir(), "logs", "runtime.jsonl")for i := 0; i < 2; i++ {- if err := EnsureSystemLogWritable(dir); err != nil {+ if err := EnsureSystemLogWritable(path); err != nil {t.Fatalf("EnsureSystemLogWritable call %d: %v", i+1, err)}}diff --git a/cli/beacon/internal/endpoint/writer/logdir_perm_test.go b/cli/beacon/internal/endpoint/writer/logdir_perm_test.goindex 1e6ec18f..9a5b1e17 100644--- a/cli/beacon/internal/endpoint/writer/logdir_perm_test.go+++ b/cli/beacon/internal/endpoint/writer/logdir_perm_test.go@@ -25,7 +25,7 @@ func TestSystemLogDirIsTraversableUnderARestrictiveUmask(t *testing.T) {t.Cleanup(func() { syscall.Umask(old) })dir := filepath.Join(t.TempDir(), "beacon-agent")- if err := EnsureSystemLogWritable(dir); err != nil {+ if err := EnsureSystemLogWritable(filepath.Join(dir, "runtime.jsonl")); err != nil {t.Fatal(err)}@@ -55,7 +55,7 @@ func TestSystemLogDirIsCorrectedWhenItAlreadyExists(t *testing.T) {t.Fatal(err)}- if err := EnsureSystemLogWritable(dir); err != nil {+ if err := EnsureSystemLogWritable(filepath.Join(dir, "runtime.jsonl")); err != nil {t.Fatal(err)}diff --git a/cli/beacon/internal/endpoint/writer/writer.go b/cli/beacon/internal/endpoint/writer/writer.goindex 48980656..59a33b86 100644--- a/cli/beacon/internal/endpoint/writer/writer.go+++ b/cli/beacon/internal/endpoint/writer/writer.go@@ -3,7 +3,9 @@ package writerimport ("bufio""encoding/json"+ "errors""fmt"+ "io/fs""os""path/filepath""strconv"@@ -117,20 +119,24 @@ func AppendEvent(event schema.Event, opts Options) (string, error) {return opts.Path, nil}-// EnsureSystemLogWritable makes a machine-wide log directory writable by the people whose agent-// sessions this endpoint captures.+// EnsureSystemLogWritable prepares a machine-wide runtime log so the people whose agent sessions+// this endpoint captures can append to it, and nobody else can redirect what the privileged+// writers do there.//-// A no-op on POSIX, where the file mode carries the same guarantee. On Windows it is the step-// without which a system-mode install produces a healthy collector that records nothing the agent-// did: %ProgramData% denies ordinary users write access, hooks run as the console user, and-// nothing reports an error because status and doctor both describe the collector rather than the-// hooks exporting to it.+// path is the runtime log itself, not its directory: on Windows the log and its lock are created+// here, and the files of its family (archives, lock) are reset, so the base name matters.+//+// On POSIX this makes the directory 0755 and leaves the 0666 file mode to openRuntimeFile. On+// Windows it is the step without which a system-mode install produces a healthy collector that+// records nothing the agent did -- and the step that keeps the grant from being more than hooks+// need; see secureSystemLog.//// Creates the directory first. Install calls this before anything has written a log there, so on a-// fresh system-mode install the directory does not exist yet -- and granting access to a path that-// is not there fails, taking the whole install down before the service is ever registered. Ensure-// means ensure.-func EnsureSystemLogWritable(dir string) error {+// fresh system-mode install the directory does not exist yet -- and securing a path that is not+// there fails, taking the whole install down before the service is ever registered. Ensure means+// ensure.+func EnsureSystemLogWritable(path string) error {+ dir := filepath.Dir(path)if err := os.MkdirAll(dir, 0755); err != nil {return fmt.Errorf("create the log directory %s: %w", dir, err)}@@ -149,12 +155,25 @@ func EnsureSystemLogWritable(dir string) error {if err := os.Chmod(dir, 0755); err != nil {return fmt.Errorf("make the log directory %s traversable: %w", dir, err)}- return grantInteractiveUsersWrite(dir)+ if err := secureSystemLog(path); err != nil {+ return fmt.Errorf("secure the log directory %s: %w", dir, err)+ }+ return nil}-// SystemLogWritableByUsers reports whether that grant is in place, for doctor.-func SystemLogWritableByUsers(dir string) (bool, error) {- return interactiveUsersCanWrite(dir)+// LogACLState is what doctor reports about a system log's access control.+type LogACLState struct {+ // HooksCanAppend is true when a hook running as the interactive user can open the log for+ // append and its lock for read-write.+ HooksCanAppend bool+ // Problems lists grants or owners that would let an ordinary user delete, rename or redirect+ // the files a SYSTEM process writes. Empty when the ACL is the one install applies.+ Problems []string+}++// CheckSystemLogACL reports the state EnsureSystemLogWritable establishes, for doctor.+func CheckSystemLogACL(path string) (LogACLState, error) {+ return inspectSystemLog(path)}// EnsureRuntimeFile creates the shared runtime log with the shared writable@@ -232,7 +251,7 @@ func appendJSONL(path string, line []byte, rotateBytes int64, rotateArchives int}}}- if err := rotateIfNeeded(path, rotateBytes, rotateArchives, int64(len(line))); err != nil {+ if err := rotateIfNeeded(path, rotateBytes, rotateArchives, int64(len(line))); err != nil && !rotationRefused(err) {return err}f, err := openRuntimeFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY)@@ -303,6 +322,18 @@ func rotateIfNeeded(path string, maxSize int64, archives int, nextWriteBytes intreturn os.Rename(path, rotated)}+// rotationRefused reports whether a rotation failed because this process may not rename or delete+// in the log directory, which is the expected outcome for an unprivileged writer of a system log.+//+// Rotation belongs to the privileged writers there: on POSIX the directory is root-owned 0755, and+// on Windows its ACL gives ordinary users no right to add, rename or delete entries -- which is the+// point, since those are the rights that let a user redirect a SYSTEM write. The first step of a+// rotation is therefore the one refused, nothing has moved, and the event is better appended past+// the size limit than lost; the collector rotates the log at its next write.+func rotationRefused(err error) bool {+ return errors.Is(err, fs.ErrPermission)+}+// needsRotation reports whether appending nextWriteBytes to path would take it past maxSize, which// is when rotateIfNeeded rotates. An empty or missing file never rotates, so one oversized line// still lands somewhere.diff --git a/cli/beacon/internal/endpoint/writer/writer_unix_test.go b/cli/beacon/internal/endpoint/writer/writer_unix_test.goindex 1db95649..60254390 100644--- a/cli/beacon/internal/endpoint/writer/writer_unix_test.go+++ b/cli/beacon/internal/endpoint/writer/writer_unix_test.go@@ -66,3 +66,43 @@ func TestEnsureRuntimeFileCreatesSharedRuntimeLogDespiteUmask(t *testing.T) {t.Fatalf("%s mode = %o, want %o", path, got, runtimeFileMode)}}++// An unprivileged writer of a system log cannot rotate it: the directory is root-owned 0755 here,+// and on Windows its ACL withholds the rename and delete rights on purpose. The event must still+// land -- appended past the size limit for the collector to rotate later -- rather than be lost to+// a rotation the writer was never meant to perform.+func TestAppendJSONLAppendsWhenRotationIsRefused(t *testing.T) {+ if os.Geteuid() == 0 {+ t.Skip("root ignores directory permissions, so the refusal cannot be reproduced")+ }+ dir := filepath.Join(t.TempDir(), "logs")+ if err := os.MkdirAll(dir, 0o755); err != nil {+ t.Fatal(err)+ }+ path := filepath.Join(dir, "runtime.jsonl")+ if err := os.WriteFile(path, []byte("{\"existing\":true}\n"), 0o666); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(path+".lock", nil, 0o666); err != nil {+ t.Fatal(err)+ }+ if err := os.Chmod(dir, 0o555); err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { _ = os.Chmod(dir, 0o755) })++ line := []byte("{\"next\":true}\n")+ if err := appendJSONL(path, line, 8, DefaultRotateArchives, nil); err != nil {+ t.Fatalf("append with rotation refused: %v", err)+ }+ data, err := os.ReadFile(path)+ if err != nil {+ t.Fatal(err)+ }+ if string(data) != "{\"existing\":true}\n{\"next\":true}\n" {+ t.Fatalf("log after a refused rotation = %q, want the new line appended", data)+ }+ if _, err := os.Stat(path + ".1"); !os.IsNotExist(err) {+ t.Fatalf("an archive appeared although rotation was refused: %v", err)+ }+}diff --git a/docs/cli/endpoint-doctor.mdx b/docs/cli/endpoint-doctor.mdxindex d380d4f3..d830b7de 100644--- a/docs/cli/endpoint-doctor.mdx+++ b/docs/cli/endpoint-doctor.mdx@@ -64,7 +64,7 @@ This is a warning, not a failure. The sandbox mode is the operator's choice in `## Fix mode-`beacon endpoint doctor --fix` plans and applies safe remediations for supported findings. It can create a missing runtime log, and recreate managed collector configuration and the service definition (a launchd plist or a systemd unit) when the endpoint configuration is valid.+`beacon endpoint doctor --fix` plans and applies safe remediations for supported findings. It can create a missing runtime log, and recreate managed collector configuration and the service definition (a launchd plist or a systemd unit) when the endpoint configuration is valid. On a Windows system install it also resets the log directory ACL, from an elevated shell, when interactive users cannot append to the runtime log or when they hold more than append (an older install's Modify grant): the same ACL a fresh install applies, described in [Windows](/platforms/windows#what-the-install-does).Fix mode deliberately skips cases that need operator intent, such as invalid endpoint configuration, missing harness setup, missing observed runtime events, unsafe runtime log permissions, or service repair on a host with no service manager to repair. If a collector service repair fails, Beacon rolls back the files and service state it changed where possible, then refreshes doctor results so the printed checks reflect any partial fixes that succeeded.diff --git a/docs/platforms/windows.mdx b/docs/platforms/windows.mdxindex 7b8506c2..5aa265a3 100644--- a/docs/platforms/windows.mdx+++ b/docs/platforms/windows.mdx@@ -120,15 +120,32 @@ See the [event schema](/telemetry-schema/event-schema) for the full field refere| Step | Result ||---|---|| Unpack | `beacon.exe`, `beacon-hooks.exe`, and `beacon-otelcol.exe` under `%ProgramFiles%\Beacon\bin` |-| System install | Config and collector config under `%ProgramData%\Beacon\Endpoint` |+| System install | Config and collector config under `%ProgramData%\Beacon\Endpoint`, with `%ProgramData%\Beacon` owned by Administrators and locked down || Service | `BeaconCollector`, registered with the SCM, automatic start, restart on failure || Runtime log | `%ProgramData%\Beacon\Endpoint\logs\runtime.jsonl` |-| Log permissions | Write access granted to `INTERACTIVE`, so hooks running as you can append |+| Log permissions | `INTERACTIVE` may append to the runtime log files, and nothing more || Agent runtime | Claude Code and Codex CLI settings for the interactive user, pointed at `127.0.0.1:4317` |Two of those rows deserve explanation.-**The log permission grant.** A system-mode collector runs as `LocalSystem` and creates the log, while hooks run as you and append to it. `%ProgramData%` subdirectories inherit an ACL where only administrators and SYSTEM may write, so without an explicit grant every hook write fails with access denied. Nothing reports it either, because `status` and `doctor` describe the collector rather than the hooks exporting to it. The install grants `INTERACTIVE` write access on the log directory, and `doctor` checks the grant is still there.+**The directory and log permissions.** A system-mode collector runs as `LocalSystem` and writes the log, while hooks run as you and append to it. `%ProgramData%` subdirectories inherit an ACL where ordinary users cannot write existing files, so without a grant every hook write fails with access denied, and nothing reports it, because `status` and `doctor` describe the collector rather than the hooks exporting to it. The grant has to stop there: a user who can add, delete or rename entries in a directory a SYSTEM process writes to can swap the log for a link and send the collector's writes anywhere.++So the install sets these ACLs, by well-known SID, with inheritance from `%ProgramData%` turned off:++| Path | Owner | Access |+|---|---|---|+| `%ProgramData%\Beacon` and everything below it | Administrators | SYSTEM and Administrators: full control. Users: read and execute |+| `%ProgramData%\Beacon\Endpoint\logs` | Administrators | The same, plus `INTERACTIVE`: read and write data on files directly in the directory (inherit-only). No right to create, delete or rename entries, and no right to change a file's permissions or owner |++Because users cannot create files in the log directory, the install creates `runtime.jsonl` and `runtime.jsonl.lock` itself; files the collector creates later, such as the log it starts after a rotation, inherit the same append grant. Rotation is done by the collector and by `beacon` commands run as an administrator. A hook that finds the log over its size limit appends anyway and leaves the rename to them.++`%ProgramData%\Beacon` is reset even when it already exists. `%ProgramData%` lets any user create a subdirectory, so one found there before the package was installed may belong to someone else: the install takes ownership, replaces its ACL, removes any junction, symbolic link or hard link inside it (Beacon creates none), and resets anything below it that grants an ordinary user write, delete or ownership rights. Anything already locked down further than this is left as it is.++`doctor --system` checks both halves: that interactive users can append, and that nothing grants them more. An endpoint installed by an older version carries a broader grant (Modify for `INTERACTIVE` on the log directory) and is reported as `acl_too_broad`. Upgrading the package fixes it, as does running this from an elevated shell:++```powershell title="Reset the log directory ACL"+beacon endpoint doctor --system --fix+```**The agent runtime row.** A system-mode endpoint is installed by an administrator or by a management agent running as `LocalSystem`, neither of which is necessarily the person at the keyboard, and the collector is useless if nothing exports to it. Beacon works out who is signed in at the console and configures their runtime. If it cannot identify anyone, it says so instead of failing, and you can configure yourself later:diff --git a/packaging/windows/install-endpoint.ps1 b/packaging/windows/install-endpoint.ps1index e80491d0..6b0baa04 100644--- a/packaging/windows/install-endpoint.ps1+++ b/packaging/windows/install-endpoint.ps1@@ -56,6 +56,14 @@ if (-not [string]::IsNullOrWhiteSpace($collector)) { $installArgs += @('--collecif (-not [string]::IsNullOrWhiteSpace($service)) { $installArgs += @('--service', $service) }if ($noStart -eq '1') { $installArgs += '--no-start' }+# The access control on %ProgramData%\Beacon is applied by the install itself, not here, so a fleet+# that runs `beacon endpoint install --system` directly gets the same result as the MSI. It resets the+# directory even when it already exists -- %ProgramData% lets any user create a subdirectory, so one+# found there may belong to someone else -- to Administrators ownership with inheritance disabled:+# SYSTEM and Administrators full control, Users read and execute. The log directory adds only an+# inherit-only grant letting INTERACTIVE append to the runtime log files; ordinary users cannot add,+# delete or rename anything in it. Do not add an icacls grant here: a second, broader grant is how+# the log directory once became writable enough to redirect the collector's writes.Write-Output "beacon: installing the system endpoint"& $beaconBin @installArgsif ($LASTEXITCODE -ne 0) {diff --git a/packaging/windows/test-endpoint-scripts.ps1 b/packaging/windows/test-endpoint-scripts.ps1index 5e07c58b..bf3245ae 100644--- a/packaging/windows/test-endpoint-scripts.ps1+++ b/packaging/windows/test-endpoint-scripts.ps1@@ -59,6 +59,17 @@ foreach ($needle in @('--keep-logs', '--keep-config', 'BEACON_PURGE')) {}}+# The ACL on %ProgramData%\Beacon belongs to `beacon endpoint install --system`, which gives ordinary+# users read and execute plus append to the runtime log, and nothing that lets them delete, rename or+# plant links. A packaging script that grants Modify or Full Control on top would quietly undo that.+foreach ($name in @('install-endpoint.ps1', 'uninstall-endpoint.ps1')) {+ $text = Get-Content -Raw -LiteralPath (Join-Path $scriptDir $name)+ $code = ($text -split "`n" | Where-Object { $_ -notmatch '^\s*#' }) -join "`n"+ if ($code -match '(?i)icacls[^\n]*/grant' -or $code -match '(?i)FileSystemAccessRule') {+ Fail "$name grants file system access itself; the ACL is applied by 'beacon endpoint install --system' and must not be widened here"+ }+}+# The WiX source has to keep running the scripts rather than growing its own copy of the flags.$wxs = Get-Content -Raw -LiteralPath (Join-Path $scriptDir 'beacon.wxs')foreach ($needle in @('install-endpoint.ps1', 'uninstall-endpoint.ps1')) {