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
localingest: serve and send over a named pipe on Windows
Claudee26a7b0a07b0
diff --git a/cli/beacon-hooks/go.mod b/cli/beacon-hooks/go.modindex c476f920..43ff8677 100644--- a/cli/beacon-hooks/go.mod+++ b/cli/beacon-hooks/go.mod@@ -12,6 +12,7 @@ require (replace github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve => ../../pkg/asymptoteobserverequire (+ github.com/Microsoft/go-winio v0.6.2 // indirectgithub.com/inconshreveable/mousetrap v1.1.0 // indirectgithub.com/spf13/pflag v1.0.5 // indirectgolang.org/x/sys v0.47.0 // indirectdiff --git a/cli/beacon-hooks/go.sum b/cli/beacon-hooks/go.sumindex 874fb7ae..643253a4 100644--- a/cli/beacon-hooks/go.sum+++ b/cli/beacon-hooks/go.sum@@ -1,3 +1,5 @@+github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=+github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=diff --git a/cli/beacon/go.mod b/cli/beacon/go.modindex dbc4d851..b75556a9 100644--- a/cli/beacon/go.mod+++ b/cli/beacon/go.mod@@ -20,6 +20,7 @@ replace github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve => ../../pkgrequire (cel.dev/expr v0.25.1 // indirect+ github.com/Microsoft/go-winio v0.6.2 // indirectgithub.com/antlr4-go/antlr/v4 v4.13.1 // indirectgithub.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirectgithub.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc // indirectdiff --git a/cli/beacon/go.sum b/cli/beacon/go.sumindex be15e5d8..76ccdc15 100644--- a/cli/beacon/go.sum+++ b/cli/beacon/go.sum@@ -1,5 +1,7 @@cel.dev/expr v0.25.1 h1:1KrZg61W6TWSxuNZ37Xy49ps13NUovb66QLprthtwi4=cel.dev/expr v0.25.1/go.mod h1:hrXvqGP6G6gyx8UAHSHJ5RGk//1Oj5nXQ2NI02Nrsg4=+github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=+github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=github.com/antlr4-go/antlr/v4 v4.13.1 h1:SqQKkuVZ+zWkMMNkjy5FZe5mr5WURWnlpmOuzYWrPrQ=github.com/antlr4-go/antlr/v4 v4.13.1/go.mod h1:GKmUxMtwp6ZgGwZSva4eWPC5mS6vUAmOABFgjdkM7Nw=github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k=diff --git a/collector-builder/exporter/beaconjsonexporter/beaconingestextension/extension.go b/collector-builder/exporter/beaconjsonexporter/beaconingestextension/extension.goindex 27ca3586..8124ab2a 100644--- a/collector-builder/exporter/beaconjsonexporter/beaconingestextension/extension.go+++ b/collector-builder/exporter/beaconjsonexporter/beaconingestextension/extension.go@@ -29,8 +29,8 @@ type ingest struct {names *nameCache// listen, serveListener and appendLine are the seams tests replace.- listen func(path string) (*net.UnixListener, error)- serveListener func(*net.UnixListener) net.Listener+ listen func(path string) (localingest.Listener, error)+ serveListener func(localingest.Listener) net.ListenerappendLine func(path string, line []byte, rotateBytes int64, rotateArchives int) errormu sync.Mutexdiff --git a/collector-builder/exporter/beaconjsonexporter/beaconingestextension/extension_unix_test.go b/collector-builder/exporter/beaconjsonexporter/beaconingestextension/extension_unix_test.goindex 81f21e37..52cc037e 100644--- a/collector-builder/exporter/beaconjsonexporter/beaconingestextension/extension_unix_test.go+++ b/collector-builder/exporter/beaconjsonexporter/beaconingestextension/extension_unix_test.go@@ -11,6 +11,7 @@ import ("net""os""path/filepath"+ "strconv""strings""sync""sync/atomic"@@ -119,7 +120,7 @@ func TestEventsSentToTheSocketLandInTheLogUnderTheSendersAccount(t *testing.T) {t.Fatalf("log has %d lines, want 2", len(lines))}uid := fmt.Sprint(os.Geteuid())- want := resolveName(uint32(os.Geteuid()))+ want := resolveName(strconv.Itoa(os.Geteuid()))for i, line := range lines {user := line["user"].(map[string]interface{})if user["uid"] != uid {@@ -366,10 +367,10 @@ func TestAServeFailureIsReportedAndTheSocketRemoved(t *testing.T) {cfg.SocketPath = filepath.Join(dir, "run", "ingest.sock")cfg.LogPath = filepath.Join(dir, "log", "runtime.jsonl")ext := newIngest(cfg, zap.NewNop())- ext.listen = func(path string) (*net.UnixListener, error) {+ ext.listen = func(path string) (localingest.Listener, error) {return localingest.Listen(path)}- ext.serveListener = func(l *net.UnixListener) net.Listener { return brokenListener{l} }+ ext.serveListener = func(l localingest.Listener) net.Listener { return brokenListener{l} }host := &statusHost{}if err := ext.Start(context.Background(), host); err != nil {t.Fatal(err)diff --git a/collector-builder/exporter/beaconjsonexporter/beaconingestextension/names.go b/collector-builder/exporter/beaconjsonexporter/beaconingestextension/names.goindex 0340fa43..bcedd1a8 100644--- a/collector-builder/exporter/beaconjsonexporter/beaconingestextension/names.go+++ b/collector-builder/exporter/beaconjsonexporter/beaconingestextension/names.go@@ -5,7 +5,6 @@ import ("os""os/exec""os/user"- "strconv""strings""sync""time"@@ -30,9 +29,9 @@ const (// fallback.type nameCache struct {mu sync.Mutex- entries map[uint32]nameEntry+ entries map[string]nameEntrynow func() time.Time- lookup1 func(uid uint32) string+ lookup1 func(uid string) string}type nameEntry struct {@@ -41,10 +40,10 @@ type nameEntry struct {}func newNameCache() *nameCache {- return &nameCache{entries: map[uint32]nameEntry{}, now: time.Now, lookup1: resolveName}+ return &nameCache{entries: map[string]nameEntry{}, now: time.Now, lookup1: resolveName}}-func (c *nameCache) lookup(uid uint32) string {+func (c *nameCache) lookup(uid string) string {now := c.now()c.mu.Lock()entry, ok := c.entries[uid]@@ -73,8 +72,7 @@ func firstExecutable(paths []string) string {return ""}-func resolveName(uid uint32) string {- id := strconv.FormatUint(uint64(uid), 10)+func resolveName(id string) string {if u, err := user.LookupId(id); err == nil && validName(u.Username) {return u.Username}diff --git a/collector-builder/exporter/beaconjsonexporter/beaconingestextension/names_test.go b/collector-builder/exporter/beaconjsonexporter/beaconingestextension/names_test.goindex 2fbc507d..df5bef75 100644--- a/collector-builder/exporter/beaconjsonexporter/beaconingestextension/names_test.go+++ b/collector-builder/exporter/beaconjsonexporter/beaconingestextension/names_test.go@@ -4,6 +4,7 @@ import ("os""os/user""runtime"+ "strconv""testing""time")@@ -13,10 +14,10 @@ func TestNameCacheReusesAndExpires(t *testing.T) {calls := 0c := newNameCache()c.now = func() time.Time { return now }- c.lookup1 = func(uid uint32) string { calls++; return "alice" }+ c.lookup1 = func(uid string) string { calls++; return "alice" }for i := 0; i < 5; i++ {- if got := c.lookup(501); got != "alice" {+ if got := c.lookup("501"); got != "alice" {t.Fatalf("lookup = %q", got)}}@@ -24,7 +25,7 @@ func TestNameCacheReusesAndExpires(t *testing.T) {t.Fatalf("resolved %d times within the TTL, want 1", calls)}now = now.Add(nameCacheTTL + time.Second)- _ = c.lookup(501)+ _ = c.lookup("501")if calls != 2 {t.Fatalf("resolved %d times after the TTL, want 2", calls)}@@ -35,16 +36,16 @@ func TestNameCacheRetriesAMissAfterTheTTL(t *testing.T) {answer := ""c := newNameCache()c.now = func() time.Time { return now }- c.lookup1 = func(uint32) string { return answer }- if got := c.lookup(7); got != "" {+ c.lookup1 = func(string) string { return answer }+ if got := c.lookup("7"); got != "" {t.Fatalf("lookup = %q", got)}answer = "bob"- if got := c.lookup(7); got != "" {+ if got := c.lookup("7"); got != "" {t.Fatalf("a miss was retried within the TTL: %q", got)}now = now.Add(nameCacheTTL + time.Second)- if got := c.lookup(7); got != "bob" {+ if got := c.lookup("7"); got != "bob" {t.Fatalf("a miss was not retried after the TTL: %q", got)}}@@ -57,13 +58,13 @@ func TestResolveNameFindsTheCurrentAccount(t *testing.T) {if err != nil {t.Skip(err)}- if got := resolveName(uint32(os.Geteuid())); got != me.Username {+ if got := resolveName(strconv.Itoa(os.Geteuid())); got != me.Username {t.Fatalf("resolveName = %q, want %q", got, me.Username)}}func TestResolveNameOfAnUnknownUID(t *testing.T) {- if got := resolveName(4294967000); got != "" {+ if got := resolveName("4294967000"); got != "" {t.Fatalf("resolveName of an unused uid = %q, want empty", got)}}diff --git a/collector-builder/exporter/beaconjsonexporter/go.mod b/collector-builder/exporter/beaconjsonexporter/go.modindex a80378e8..d47d3397 100644--- a/collector-builder/exporter/beaconjsonexporter/go.mod+++ b/collector-builder/exporter/beaconjsonexporter/go.mod@@ -22,6 +22,7 @@ require (replace github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve => ../../../pkg/asymptoteobserverequire (+ github.com/Microsoft/go-winio v0.6.2 // indirectgithub.com/cenkalti/backoff/v4 v4.3.0 // indirectgithub.com/cespare/xxhash/v2 v2.3.0 // indirectgithub.com/davecgh/go-spew v1.1.1 // indirectdiff --git a/collector-builder/exporter/beaconjsonexporter/go.sum b/collector-builder/exporter/beaconjsonexporter/go.sumindex 802c2cab..f19aadf6 100644--- a/collector-builder/exporter/beaconjsonexporter/go.sum+++ b/collector-builder/exporter/beaconjsonexporter/go.sum@@ -1,3 +1,5 @@+github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=+github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8=github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE=github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=diff --git a/pkg/asymptoteobserve/go.mod b/pkg/asymptoteobserve/go.modindex a1c20583..11d8923e 100644--- a/pkg/asymptoteobserve/go.mod+++ b/pkg/asymptoteobserve/go.mod@@ -5,6 +5,7 @@ go 1.27.0toolchain go1.27.3require (+ github.com/Microsoft/go-winio v0.6.2github.com/google/cel-go v0.30.0golang.org/x/sys v0.47.0gopkg.in/yaml.v3 v3.0.1diff --git a/pkg/asymptoteobserve/go.sum b/pkg/asymptoteobserve/go.sumindex 324b158b..fb08b095 100644--- a/pkg/asymptoteobserve/go.sum+++ b/pkg/asymptoteobserve/go.sum@@ -1,5 +1,7 @@cel.dev/expr v0.25.1 h1:1KrZg61W6TWSxuNZ37Xy49ps13NUovb66QLprthtwi4=cel.dev/expr v0.25.1/go.mod h1:hrXvqGP6G6gyx8UAHSHJ5RGk//1Oj5nXQ2NI02Nrsg4=+github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=+github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=github.com/antlr4-go/antlr/v4 v4.13.1 h1:SqQKkuVZ+zWkMMNkjy5FZe5mr5WURWnlpmOuzYWrPrQ=github.com/antlr4-go/antlr/v4 v4.13.1/go.mod h1:GKmUxMtwp6ZgGwZSva4eWPC5mS6vUAmOABFgjdkM7Nw=github.com/go-quicktest/qt v1.102.0 h1:HSQxCeh5YZH3EL3W39ixjtyaEhcWSXQHtHnMBzSs474=diff --git a/pkg/asymptoteobserve/localingest/accept_other.go b/pkg/asymptoteobserve/localingest/accept_other.godeleted file mode 100644index c99171d1..00000000--- a/pkg/asymptoteobserve/localingest/accept_other.go+++ /dev/null@@ -1,6 +0,0 @@-//go:build !unix--package localingest--// temporaryAcceptError is never true off Unix, where nothing serves the socket.-func temporaryAcceptError(error) bool { return false }diff --git a/pkg/asymptoteobserve/localingest/client.go b/pkg/asymptoteobserve/localingest/client.goindex 55593d7a..f3652970 100644--- a/pkg/asymptoteobserve/localingest/client.go+++ b/pkg/asymptoteobserve/localingest/client.go@@ -7,7 +7,6 @@ import ("errors""fmt""io"- "net""time")@@ -17,15 +16,19 @@ import (// busy server reports how far it got rather than leaving the client to resend lines it wrote.const DefaultClientTimeout = 3 * time.Second-// Client sends batches to a collector's ingest socket.+// Client sends batches to a collector's ingest socket, or on Windows its named pipe.type Client struct {- // SocketPath is the socket to send to. Empty means DefaultSocketPath.+ // SocketPath is the socket or pipe to send to. Empty means DefaultSocketPath.SocketPath string// Timeout bounds each connection, from dial to reply. Zero means DefaultClientTimeout.Timeout time.Duration- // TrustedOwner is the uid the socket and its directory must belong to. Zero, the default, is- // root; tests set their own uid.+ // TrustedOwner is the uid the socket and its directory must belong to on Unix. Zero, the+ // default, is root; tests set their own uid.TrustedOwner int+ // TrustedSID is, on Windows, one more account the pipe may belong to besides SYSTEM and+ // Administrators, the only creators trusted otherwise. Empty in production; tests that serve a+ // pipe as their own account set their SID.+ TrustedSID string// LogPath is the runtime log the lines are meant for, sent in the header. The collector refuses// them, with ErrLogMismatch, if it writes another log.LogPath string@@ -38,23 +41,11 @@ func (c Client) path() string {return c.SocketPath}-// Available reports whether a trusted ingest socket exists, without connecting to it. It is how a-// writer decides whether the endpoint is in the restricted mode at all; ErrNoSocket means it is-// not.-func (c Client) Available() error {- _, err := checkSocket(c.path(), c.TrustedOwner)- return err-}-// Probe asks the collector to answer an empty batch for LogPath. It is what tells a live-// collector from a socket a killed one left behind, which Available cannot: that only looks at the-// file. ErrNoSocket and ErrLogMismatch keep their meaning.+// collector from a socket a killed one left behind, which looking at the socket file cannot.+// ErrNoSocket, ErrUntrustedSocket and ErrLogMismatch keep their meaning.func (c Client) Probe() error {- socket, err := checkSocket(c.path(), c.TrustedOwner)- if err != nil {- return err- }- _, err = c.sendBatch(socket, nil)+ _, err := c.sendBatch(nil)return err}@@ -73,17 +64,13 @@ func (c Client) Send(lines [][]byte) (Response, error) {}cleaned[i] = line}- socket, err := checkSocket(c.path(), c.TrustedOwner)- if err != nil {- return Response{}, err- }var total Responsefor start := 0; start < len(cleaned); start += MaxLinesPerConn {end := start + MaxLinesPerConnif end > len(cleaned) {end = len(cleaned)}- resp, err := c.sendBatch(socket, cleaned[start:end])+ resp, err := c.sendBatch(cleaned[start:end])total.Accepted += resp.Acceptedtotal.Rejected += resp.Rejectedtotal.Processed += resp.Processed@@ -95,14 +82,20 @@ func (c Client) Send(lines [][]byte) (Response, error) {return total, nil}-func (c Client) sendBatch(socket string, lines [][]byte) (Response, error) {+// halfCloser is a connection whose write side can be closed on its own: a Unix socket, or a+// message-mode named pipe, which signals it with a zero-byte message.+type halfCloser interface{ CloseWrite() error }++func (c Client) sendBatch(lines [][]byte) (Response, error) {timeout := c.Timeoutif timeout <= 0 {timeout = DefaultClientTimeout}- conn, err := net.DialTimeout("unix", socket, timeout)+ // connect checks that the socket or pipe is the collector's before anything is sent to it, and+ // returns ErrNoSocket or ErrUntrustedSocket when it is missing or someone else's.+ conn, err := c.connect(timeout)if err != nil {- return Response{}, fmt.Errorf("connect to %s: %w", c.path(), err)+ return Response{}, err}defer conn.Close()_ = conn.SetDeadline(time.Now().Add(timeout))@@ -125,8 +118,8 @@ func (c Client) sendBatch(socket string, lines [][]byte) (Response, error) {writeErr = w.Flush()}if writeErr == nil {- if uc, ok := conn.(*net.UnixConn); ok {- writeErr = uc.CloseWrite()+ if hc, ok := conn.(halfCloser); ok {+ writeErr = hc.CloseWrite()}}@@ -163,6 +156,7 @@ func (c Client) sendBatch(socket string, lines [][]byte) (Response, error) {}// ErrUntrustedSocket is returned when something exists at the socket path but could have been put-// there by someone other than root. A writer that sees it does not send there, because a socket a-// user planted would receive every other user's events.+// there by someone other than root, or on Windows a pipe of that name was created by someone other+// than SYSTEM or Administrators. A writer that sees it does not send there, because a socket or+// pipe a user planted would receive every other user's events.var ErrUntrustedSocket = errors.New("untrusted ingest socket")diff --git a/pkg/asymptoteobserve/localingest/exchange_test.go b/pkg/asymptoteobserve/localingest/exchange_test.gonew file mode 100644index 00000000..90ef57f4--- /dev/null+++ b/pkg/asymptoteobserve/localingest/exchange_test.go@@ -0,0 +1,57 @@+package localingest++import (+ "fmt"+ "sync"+ "testing"+)++// The helpers below serve the exchange tests on every platform: the Unix socket tests and the+// Windows named pipe tests drive the same Server and Client.++type recorder struct {+ mu sync.Mutex+ lines [][]byte+ fail func(n int, line []byte) error+}++func (r *recorder) append(line []byte) error {+ r.mu.Lock()+ defer r.mu.Unlock()+ if r.fail != nil {+ if err := r.fail(len(r.lines), line); err != nil {+ return err+ }+ }+ r.lines = append(r.lines, append([]byte(nil), line...))+ return nil+}++func (r *recorder) setFail(fail func(n int, line []byte) error) {+ r.mu.Lock()+ r.fail = fail+ r.mu.Unlock()+}++func (r *recorder) count() int {+ r.mu.Lock()+ defer r.mu.Unlock()+ return len(r.lines)+}++func lines(t *testing.T, n int) [][]byte {+ t.Helper()+ out := make([][]byte, n)+ for i := range out {+ i := i+ out[i] = validLine(t, func(e map[string]interface{}) {+ e["event"].(map[string]interface{})["id"] = fmt.Sprintf("id-%d", i)+ e["message"] = fmt.Sprintf("m-%d", i)+ e["user"] = map[string]interface{}{"name": "root", "uid": "0"}+ })+ }+ return out+}++// opening is the preamble and a header naming no log, which a server without a LogPath accepts.+const opening = Preamble + "\n" + `{"log":""}` + "\n"diff --git a/pkg/asymptoteobserve/localingest/identify_unix.go b/pkg/asymptoteobserve/localingest/identify_unix.gonew file mode 100644index 00000000..b1d2a65c--- /dev/null+++ b/pkg/asymptoteobserve/localingest/identify_unix.go@@ -0,0 +1,24 @@+//go:build unix++package localingest++import (+ "errors"+ "net"+)++// connectingAccount is the account that opened conn, before anything is read from it. On Unix the+// kernel reports it at any time, so it is identify's own answer.+func connectingAccount(conn net.Conn) (string, error) {+ peer, err := identify(conn)+ return peer.UID, err+}++// identify asks the kernel who opened the other end of conn.+func identify(conn net.Conn) (Peer, error) {+ unixConn, ok := conn.(*net.UnixConn)+ if !ok {+ return Peer{}, errors.New("not a Unix socket")+ }+ return peerCredentials(unixConn)+}diff --git a/pkg/asymptoteobserve/localingest/localingest.go b/pkg/asymptoteobserve/localingest/localingest.goindex d64e52bb..1926c572 100644--- a/pkg/asymptoteobserve/localingest/localingest.go+++ b/pkg/asymptoteobserve/localingest/localingest.go@@ -11,10 +11,14 @@// the collector becomes the only writer, the log becomes 0640 root:beacon-log, and hooks send their// events here instead.//+// On Windows the same mode makes the SYSTEM collector the only writer of the log under+// %ProgramData%, whose ACL then grants ordinary users nothing, and hooks send to it here the same+// way.+//// # The channel//-// The collector listens on a Unix domain socket (DefaultSocketPath) in a root-owned directory. A-// connection carries one batch:+// The collector listens on a Unix domain socket in a root-owned directory, or on Windows on a named+// pipe (DefaultSocketPath for both). A connection carries one batch://// client: "BEACON-INGEST/1\n", a Header line, one event per line, then half-closes its write side// server: one JSON Response line, after it has handled every line it read@@ -24,14 +28,17 @@// directly rather than landing in the system log.//// The server learns who is on the other end from the kernel (SO_PEERCRED on Linux, LOCAL_PEERCRED-// on macOS), never from the event, and StampLine overwrites the event's user with that identity.+// on macOS, the client's token through ImpersonateNamedPipeClient on Windows), never from the+// event, and StampLine overwrites the event's user with that identity.// So a user can still describe their own sessions however they like -- their agent runs under their// control -- but cannot erase, rewrite or read anything already in the log, and cannot write an// event that claims to be someone else's.//-// Nothing here touches the network: a Unix socket is a local file, and the client refuses to+// Nothing here touches the network. A Unix socket is a local file, and the client refuses to// connect to one that is not in a directory only root could have created it in, because a socket a-// user planted there would receive every other user's events.+// user planted there would receive every other user's events. A named pipe could be reached over+// SMB, so the pipe rejects remote clients and its ACL denies network logons; the client refuses a+// pipe that SYSTEM or Administrators did not create, for the same reason as the socket.package localingestimport (@@ -42,18 +49,12 @@ import ("errors""fmt""io"- "strconv""strings""github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve")const (- // DefaultSocketPath is where a system-mode collector in the restricted log access mode listens.- // /var/run is root-owned on Linux (a link to /run) and macOS (a link to /private/var/run), so- // only root can create the directory the socket lives in.- DefaultSocketPath = "/var/run/beacon-agent/ingest.sock"-// Preamble opens every connection. It names the protocol version, so a later version can be// told apart, and keeps a stray client that happened to connect from having its bytes taken// for events.@@ -95,7 +96,10 @@ var ErrNoSocket = errors.New("no ingest socket")// Peer is who the kernel says is on the other end of a connection.type Peer struct {- UID uint32+ // UID names the account: its decimal uid on Unix, its SID on Windows. It is what the stamped+ // event's user.uid carries, the same value the account's own hooks write there.+ UID string+ // GID is the primary group where the kernel reports one, and 0 on Windows.GID uint32// PID is the sending process, or 0 where the platform does not report one.PID int32@@ -125,9 +129,9 @@ type Response struct {// event.id follows the rules in stampEventID. A line that would only exceed MaxLineBytes because// of the id is written without one, as every writer does with an event at the size limit.//-// lookupName resolves a uid to an account name and may be nil; a name it cannot resolve is left-// out rather than taken from the event, which the sender wrote.-func StampLine(line []byte, peer Peer, lookupName func(uid uint32) string) ([]byte, error) {+// lookupName resolves the peer's account (see Peer.UID) to a name and may be nil; a name it cannot+// resolve is left out rather than taken from the event, which the sender wrote.+func StampLine(line []byte, peer Peer, lookupName func(uid string) string) ([]byte, error) {line = bytes.TrimSuffix(line, []byte{'\r'})if len(line) == 0 {return nil, fmt.Errorf("%w: empty line", ErrRejected)@@ -152,7 +156,10 @@ func StampLine(line []byte, peer Peer, lookupName func(uid uint32) string) ([]byreturn nil, fmt.Errorf("%w: %v", ErrRejected, err)}- user := map[string]interface{}{"uid": strconv.FormatUint(uint64(peer.UID), 10)}+ if strings.TrimSpace(peer.UID) == "" {+ return nil, errors.New("the peer has no account")+ }+ user := map[string]interface{}{"uid": peer.UID}if lookupName != nil {if name := strings.TrimSpace(lookupName(peer.UID)); name != "" {user["name"] = name@@ -190,7 +197,7 @@ func StampLine(line []byte, peer Peer, lookupName func(uid uint32) string) ([]by// account it is not, so the id is derived again from what is written.// - Any other id is one the sender chose, as session-store importers do from their source// records. It is kept stable for that account, so a re-swept record keeps its id, but scoped to-// the verified uid, so one account cannot write under an id another account's events carry.+// the verified account, so one account cannot write under an id another account's events carry.//// A call-keyed id stays as strong as the session and call ids it is built from: an account that// knows another session's ids can name the same call, as it could over the loopback OTLP port.@@ -210,11 +217,12 @@ func stampEventID(sentID string, claimed, withoutID []byte, peer Peer) string {// namespace, it is a contract: changing it renames every scoped id written through the socket.var scopedIDNamespace = [16]byte{0x6b, 0x2d, 0x1f, 0x9a, 0x4c, 0x37, 0x4e, 0x0b, 0x9f, 0x51, 0x8e, 0x2a, 0x77, 0xc3, 0x05, 0xd4}-// scopedEventID is a version 5 UUID of the uid and the id the sender chose.-func scopedEventID(uid uint32, sentID string) string {+// scopedEventID is a version 5 UUID of the account (Peer.UID: a decimal uid or a SID) and the id+// the sender chose.+func scopedEventID(uid string, sentID string) string {digest := sha1.New()digest.Write(scopedIDNamespace[:])- io.WriteString(digest, strconv.FormatUint(uint64(uid), 10))+ io.WriteString(digest, uid)digest.Write([]byte{0})io.WriteString(digest, sentID)var id [16]bytediff --git a/pkg/asymptoteobserve/localingest/localingest_test.go b/pkg/asymptoteobserve/localingest/localingest_test.goindex afdc2b1f..ca22b524 100644--- a/pkg/asymptoteobserve/localingest/localingest_test.go+++ b/pkg/asymptoteobserve/localingest/localingest_test.go@@ -47,9 +47,9 @@ func decode(t *testing.T, line []byte) map[string]interface{} {func TestStampLineReplacesTheClaimedUserWithThePeer(t *testing.T) {line := validLine(t, nil)- out, err := StampLine(line, Peer{UID: 1002, GID: 20, PID: 77}, func(uid uint32) string {- if uid != 1002 {- t.Fatalf("lookup asked for uid %d", uid)+ out, err := StampLine(line, Peer{UID: "1002", GID: 20, PID: 77}, func(uid string) string {+ if uid != "1002" {+ t.Fatalf("lookup asked for uid %s", uid)}return "mallory"})@@ -64,12 +64,12 @@ func TestStampLineReplacesTheClaimedUserWithThePeer(t *testing.T) {}func TestStampLineLeavesOutANameItCannotResolve(t *testing.T) {- for name, lookup := range map[string]func(uint32) string{+ for name, lookup := range map[string]func(string) string{"nil lookup": nil,- "empty result": func(uint32) string { return " " },+ "empty result": func(string) string { return " " },} {t.Run(name, func(t *testing.T) {- out, err := StampLine(validLine(t, nil), Peer{UID: 42}, lookup)+ out, err := StampLine(validLine(t, nil), Peer{UID: "42"}, lookup)if err != nil {t.Fatal(err)}@@ -86,7 +86,7 @@ func TestStampLineLeavesOutANameItCannotResolve(t *testing.T) {func TestStampLineAddsAUserToAnEventWithout(t *testing.T) {line := validLine(t, func(e map[string]interface{}) { delete(e, "user") })- out, err := StampLine(line, Peer{UID: 0}, nil)+ out, err := StampLine(line, Peer{UID: "0"}, nil)if err != nil {t.Fatal(err)}@@ -97,7 +97,7 @@ func TestStampLineAddsAUserToAnEventWithout(t *testing.T) {func TestStampLineKeepsEverythingElseExactly(t *testing.T) {line := validLine(t, nil)- out, err := StampLine(line, Peer{UID: 501}, func(uint32) string { return "alice" })+ out, err := StampLine(line, Peer{UID: "501"}, func(string) string { return "alice" })if err != nil {t.Fatal(err)}@@ -126,11 +126,11 @@ func TestStampLineNamesAnEventThatArrivesWithoutAnID(t *testing.T) {line := validLine(t, func(e map[string]interface{}) {delete(e["event"].(map[string]interface{}), "id")})- first, err := StampLine(line, Peer{UID: 501}, nil)+ first, err := StampLine(line, Peer{UID: "501"}, nil)if err != nil {t.Fatal(err)}- second, err := StampLine(line, Peer{UID: 501}, nil)+ second, err := StampLine(line, Peer{UID: "501"}, nil)if err != nil {t.Fatal(err)}@@ -149,7 +149,7 @@ func TestStampLineNamesAnEventThatArrivesWithoutAnID(t *testing.T) {t.Fatalf("event.id = %q, want %q", id, want)}// A different account sending the same bytes is a different event.- other, err := StampLine(line, Peer{UID: 502}, nil)+ other, err := StampLine(line, Peer{UID: "502"}, nil)if err != nil {t.Fatal(err)}@@ -178,7 +178,7 @@ func TestStampLineRejects(t *testing.T) {}for name, line := range cases {t.Run(name, func(t *testing.T) {- out, err := StampLine(line, Peer{UID: 1}, nil)+ out, err := StampLine(line, Peer{UID: "1"}, nil)if !errors.Is(err, ErrRejected) {t.Fatalf("err = %v, out = %s; want ErrRejected", err, out)}@@ -196,7 +196,7 @@ func TestStampLineRejectsALineThatOutgrowsTheLimitWhenStamped(t *testing.T) {if len(line) > MaxLineBytes {t.Fatalf("fixture is %d bytes, want it under the limit before stamping", len(line))}- _, err := StampLine(line, Peer{UID: 1}, func(uint32) string { return strings.Repeat("n", 64) })+ _, err := StampLine(line, Peer{UID: "1"}, func(string) string { return strings.Repeat("n", 64) })if !errors.Is(err, ErrRejected) {t.Fatalf("err = %v, want ErrRejected for a line over the limit once stamped", err)}@@ -204,7 +204,7 @@ func TestStampLineRejectsALineThatOutgrowsTheLimitWhenStamped(t *testing.T) {func TestStampLineAcceptsATrailingCarriageReturn(t *testing.T) {line := append(validLine(t, nil), '\r')- out, err := StampLine(line, Peer{UID: 501}, func(uint32) string { return "alice" })+ out, err := StampLine(line, Peer{UID: "501"}, func(string) string { return "alice" })if err != nil {t.Fatal(err)}@@ -231,7 +231,7 @@ func TestStampLineKeepsAnIDDerivedFromWhatIsWritten(t *testing.T) {e["user"] = map[string]interface{}{"uid": "501", "name": "alice"}e["event"].(map[string]interface{})["id"] = want})- out, err := StampLine(withID, Peer{UID: 501}, func(uint32) string { return "alice" })+ out, err := StampLine(withID, Peer{UID: "501"}, func(string) string { return "alice" })if err != nil {t.Fatal(err)}@@ -257,7 +257,7 @@ func TestStampLineKeepsACallKeyedID(t *testing.T) {call(e)e["event"].(map[string]interface{})["id"] = sent})- out, err := StampLine(line, Peer{UID: 501}, func(uint32) string { return "alice" })+ out, err := StampLine(line, Peer{UID: "501"}, func(string) string { return "alice" })if err != nil {t.Fatal(err)}@@ -281,7 +281,7 @@ func TestStampLineRederivesTheIDOfALineThatClaimedAnotherAccount(t *testing.T) {e["user"] = map[string]interface{}{"uid": "0", "name": "root"}e["event"].(map[string]interface{})["id"] = sent})- out, err := StampLine(line, Peer{UID: 501}, func(uint32) string { return "alice" })+ out, err := StampLine(line, Peer{UID: "501"}, func(string) string { return "alice" })if err != nil {t.Fatal(err)}@@ -296,12 +296,12 @@ func TestStampLineScopesASenderChosenIDToItsAccount(t *testing.T) {line := validLine(t, func(e map[string]interface{}) {e["event"].(map[string]interface{})["id"] = "claude:session-1:record-42"})- first, err := StampLine(line, Peer{UID: 501}, nil)+ first, err := StampLine(line, Peer{UID: "501"}, nil)if err != nil {t.Fatal(err)}- again, _ := StampLine(line, Peer{UID: 501}, nil)- other, _ := StampLine(line, Peer{UID: 502}, nil)+ again, _ := StampLine(line, Peer{UID: "501"}, nil)+ other, _ := StampLine(line, Peer{UID: "502"}, nil)a, b, c := stampedID(t, first), stampedID(t, again), stampedID(t, other)if a == "claude:session-1:record-42" || a == "" {t.Fatalf("event.id = %q; a sender-chosen id must be scoped", a)@@ -312,9 +312,14 @@ func TestStampLineScopesASenderChosenIDToItsAccount(t *testing.T) {if a == c {t.Fatal("two accounts sending the same chosen id got the same event.id")}- if a != scopedEventID(501, "claude:session-1:record-42") {+ if a != scopedEventID("501", "claude:session-1:record-42") {t.Fatal("scoped id does not match its definition")}+ // Pinned: the derivation is a contract, and changing it would rename every scoped id already+ // written through the socket. A Unix account is named by its decimal uid, as it always was.+ if a != "1e67ad0d-6971-5cce-9a8a-565d5e4b8fa6" {+ t.Fatalf("scoped id = %s; the derivation changed", a)+ }}// An event at the limit, which only the id would push over, is written without one, the way the@@ -334,7 +339,7 @@ func TestStampLineDropsTheIDRatherThanTheEvent(t *testing.T) {if len(line) > MaxLineBytes {t.Fatal("fixture over the limit")}- out, err := StampLine(line, Peer{UID: 501}, func(uint32) string { return "alice" })+ out, err := StampLine(line, Peer{UID: "501"}, func(string) string { return "alice" })if err != nil {t.Fatalf("an event the id alone would push over the limit was rejected: %v", err)}diff --git a/pkg/asymptoteobserve/localingest/peercred_darwin.go b/pkg/asymptoteobserve/localingest/peercred_darwin.goindex 4b5eee4f..dc015321 100644--- a/pkg/asymptoteobserve/localingest/peercred_darwin.go+++ b/pkg/asymptoteobserve/localingest/peercred_darwin.go@@ -5,6 +5,7 @@ package localingestimport ("fmt""net"+ "strconv""golang.org/x/sys/unix")@@ -30,7 +31,7 @@ func peerCredentials(conn *net.UnixConn) (Peer, error) {if credErr != nil {return Peer{}, fmt.Errorf("read peer credentials: %w", credErr)}- peer := Peer{UID: cred.Uid, PID: int32(pid)}+ peer := Peer{UID: strconv.FormatUint(uint64(cred.Uid), 10), PID: int32(pid)}if cred.Ngroups > 0 {peer.GID = cred.Groups[0]}diff --git a/pkg/asymptoteobserve/localingest/peercred_linux.go b/pkg/asymptoteobserve/localingest/peercred_linux.goindex b663b288..66cd749d 100644--- a/pkg/asymptoteobserve/localingest/peercred_linux.go+++ b/pkg/asymptoteobserve/localingest/peercred_linux.go@@ -5,6 +5,7 @@ package localingestimport ("fmt""net"+ "strconv""golang.org/x/sys/unix")@@ -27,7 +28,7 @@ func peerCredentials(conn *net.UnixConn) (Peer, error) {if credErr != nil {return Peer{}, fmt.Errorf("read peer credentials: %w", credErr)}- return Peer{UID: cred.Uid, GID: cred.Gid, PID: cred.Pid}, nil+ return Peer{UID: strconv.FormatUint(uint64(cred.Uid), 10), GID: cred.Gid, PID: cred.Pid}, nil}const peerCredentialsSupported = truediff --git a/pkg/asymptoteobserve/localingest/peercred_other.go b/pkg/asymptoteobserve/localingest/peercred_other.goindex 32402704..ec2fd37f 100644--- a/pkg/asymptoteobserve/localingest/peercred_other.go+++ b/pkg/asymptoteobserve/localingest/peercred_other.go@@ -1,4 +1,4 @@-//go:build !linux && !darwin+//go:build unix && !linux && !darwinpackage localingestdiff --git a/pkg/asymptoteobserve/localingest/server.go b/pkg/asymptoteobserve/localingest/server.goindex 9dc5048a..4f942117 100644--- a/pkg/asymptoteobserve/localingest/server.go+++ b/pkg/asymptoteobserve/localingest/server.go@@ -41,8 +41,8 @@ type Server struct {// ErrRejected drops that line for good; any other error stops the batch, and the client keeps// the rest to send again.Append func(line []byte) error- // LookupName resolves a peer's uid to its account name for the stamped user. Optional.- LookupName func(uid uint32) string+ // LookupName resolves a peer's account (Peer.UID) to its name for the stamped user. Optional.+ LookupName func(uid string) string// LogPath is the runtime log Append writes. A batch whose header names another log is refused// without being read into the log. Empty accepts any header; only tests leave it empty.LogPath string@@ -70,16 +70,16 @@ type Server struct {slots chan struct{}closed boolwg sync.WaitGroup- buckets map[uint32]*bucket- perUID map[uint32]int- logStates map[uint32]*logState+ buckets map[string]*bucket+ perUID map[string]int+ logStates map[string]*logState}// ErrServerClosed is returned by Serve after Close.var ErrServerClosed = errors.New("localingest: server closed")// Serve accepts connections on l until Close is called or l fails. It refuses to run where the-// kernel cannot say who a peer is, because then nothing it wrote could be attributed.+// operating system cannot say who a peer is, because then nothing it wrote could be attributed.func (s *Server) Serve(l net.Listener) error {if s.Append == nil {return errors.New("localingest: Server.Append is required")@@ -165,8 +165,8 @@ func (s *Server) init() {if s.listeners == nil {s.listeners = map[net.Listener]struct{}{}s.conns = map[net.Conn]struct{}{}- s.buckets = map[uint32]*bucket{}- s.perUID = map[uint32]int{}+ s.buckets = map[string]*bucket{}+ s.perUID = map[string]int{}n := s.MaxConnsif n <= 0 {n = defaultMaxConns@@ -215,8 +215,8 @@ func (s *Server) isClosed() bool {return s.closed}-// noUID keys log lines that belong to no one connection.-const noUID = ^uint32(0)+// noUID keys log lines that belong to no one account.+const noUID = ""// logInterval is the least time between two log lines about one account. Any account can connect,// and each refused connection or rejected line is something to log, so without a bound one@@ -228,14 +228,14 @@ type logState struct {suppressed int}-func (s *Server) logf(uid uint32, format string, args ...interface{}) {+func (s *Server) logf(uid string, format string, args ...interface{}) {if s.Logf == nil {return}now := time.Now()s.mu.Lock()if s.logStates == nil {- s.logStates = map[uint32]*logState{}+ s.logStates = map[string]*logState{}}st := s.logStates[uid]if st == nil {@@ -268,35 +268,42 @@ func (s *Server) handle(conn net.Conn) {budget := time.Now().Add(timeout)_ = conn.SetDeadline(budget.Add(replyGrace))- unixConn, ok := conn.(*net.UnixConn)- if !ok {- s.logf(noUID, "refusing connection: not a Unix socket")+ // The account is counted against its connection cap before anything is read, so a connection+ // that sends nothing still holds one of its account's slots rather than only one of everyone's.+ // The identity events are stamped with is read after the preamble: a named pipe server cannot+ // take on its client's identity until it has read from the pipe. The two must agree.+ account, err := connectingAccount(conn)+ if err != nil {+ s.logf(noUID, "refusing connection: %v", err)+ return+ }+ if !s.acquireUID(account) {+ s.logf(account, "refusing connection from account %s: it already has the most connections one account may hold", account)+ return+ }+ defer s.releaseUID(account)+ r := bufio.NewReaderSize(conn, MaxLineBytes+2)+ preamble, tooLong, preambleErr := readLine(r, len(Preamble)+1)+ if preambleErr != nil && !errors.Is(preambleErr, io.EOF) || tooLong || string(preamble) != Preamble {+ s.logf(account, "refusing connection from account %s: no %s preamble", account, Preamble)+ writeResponse(conn, Response{Error: "expected " + Preamble})return}- peer, err := peerCredentials(unixConn)+ peer, err := identify(conn)if err != nil {- s.logf(noUID, "refusing connection: %v", err)+ s.logf(account, "refusing connection from account %s: %v", account, err)return}- if !s.acquireUID(peer.UID) {- s.logf(peer.UID, "refusing connection from uid %d: it already has the most connections one account may hold", peer.UID)+ if peer.UID != account {+ s.logf(account, "refusing connection from account %s: it identified as %s once connected", account, peer.UID)return}- defer s.releaseUID(peer.UID)// The name is resolved once per connection, before any line, so a slow directory service is// paid for once and never between writes.- var lookup func(uint32) string+ var lookup func(string) stringif s.LookupName != nil {name := s.LookupName(peer.UID)- lookup = func(uint32) string { return name }- }-- r := bufio.NewReaderSize(conn, MaxLineBytes+2)- preamble, tooLong, err := readLine(r, len(Preamble)+1)- if err != nil && !errors.Is(err, io.EOF) || tooLong || string(preamble) != Preamble {- s.logf(peer.UID, "refusing connection from uid %d: no %s preamble", peer.UID, Preamble)- writeResponse(conn, Response{Error: "expected " + Preamble})- return+ lookup = func(string) string { return name }}var resp Response@@ -305,7 +312,7 @@ func (s *Server) handle(conn net.Conn) {var header Headerswitch {case err != nil && !errors.Is(err, io.EOF), tooLong, json.Unmarshal(headerLine, &header) != nil:- s.logf(peer.UID, "refusing connection from uid %d: no valid header", peer.UID)+ s.logf(peer.UID, "refusing connection from account %s: no valid header", peer.UID)writeResponse(conn, Response{Error: "expected a header"})returncase s.LogPath != "" && !sameLog(header.Log, s.LogPath):@@ -328,7 +335,7 @@ func (s *Server) handle(conn net.Conn) {break}// The connection broke (a reset): there is nobody to reply to.- s.logf(peer.UID, "connection from uid %d ended early: %v", peer.UID, err)+ s.logf(peer.UID, "connection from account %s ended early: %v", peer.UID, err)return}if len(line) == 0 && !tooLong {@@ -354,7 +361,7 @@ func (s *Server) handle(conn net.Conn) {stopped = truecase tooLong:resp.Rejected++- s.logf(peer.UID, "rejected an event from uid %d: over %d bytes", peer.UID, MaxLineBytes)+ s.logf(peer.UID, "rejected an event from account %s: over %d bytes", peer.UID, MaxLineBytes)case !s.allow(peer.UID, len(line)):resp.Error = "rate limited"stopped = true@@ -362,7 +369,7 @@ func (s *Server) handle(conn net.Conn) {stamped, stampErr := StampLine(line, peer, lookup)if stampErr != nil {resp.Rejected++- s.logf(peer.UID, "rejected an event from uid %d: %v", peer.UID, stampErr)+ s.logf(peer.UID, "rejected an event from account %s: %v", peer.UID, stampErr)break}if appendErr := s.Append(stamped); appendErr != nil {@@ -371,7 +378,7 @@ func (s *Server) handle(conn net.Conn) {break}resp.Error = "write failed"- s.logf(peer.UID, "could not write an event from uid %d: %v", peer.UID, appendErr)+ s.logf(peer.UID, "could not write an event from account %s: %v", peer.UID, appendErr)stopped = truebreak}@@ -386,7 +393,7 @@ func (s *Server) handle(conn net.Conn) {writeResponse(conn, resp)}-func (s *Server) acquireUID(uid uint32) bool {+func (s *Server) acquireUID(uid string) bool {limit := s.MaxConnsPerUIDif limit <= 0 {limit = defaultMaxConnsPerUID@@ -400,7 +407,7 @@ func (s *Server) acquireUID(uid uint32) bool {return true}-func (s *Server) releaseUID(uid uint32) {+func (s *Server) releaseUID(uid string) {s.mu.Lock()defer s.mu.Unlock()if s.perUID[uid] <= 1 {@@ -460,8 +467,8 @@ type bucket struct {last time.Time}-// allow charges size bytes to uid's bucket.-func (s *Server) allow(uid uint32, size int) bool {+// allow charges size bytes to the account's bucket.+func (s *Server) allow(uid string, size int) bool {rate := s.RateBytesPerSecondif rate < 0 {return truediff --git a/pkg/asymptoteobserve/localingest/server_unix_test.go b/pkg/asymptoteobserve/localingest/server_unix_test.goindex 97d1dcc7..4e5ab7c0 100644--- a/pkg/asymptoteobserve/localingest/server_unix_test.go+++ b/pkg/asymptoteobserve/localingest/server_unix_test.go@@ -11,6 +11,7 @@ import ("os""path/filepath""runtime"+ "strconv""strings""sync""syscall"@@ -33,36 +34,6 @@ func shortTempDir(t *testing.T) string {return dir}-type recorder struct {- mu sync.Mutex- lines [][]byte- fail func(n int, line []byte) error-}--func (r *recorder) append(line []byte) error {- r.mu.Lock()- defer r.mu.Unlock()- if r.fail != nil {- if err := r.fail(len(r.lines), line); err != nil {- return err- }- }- r.lines = append(r.lines, append([]byte(nil), line...))- return nil-}--func (r *recorder) setFail(fail func(n int, line []byte) error) {- r.mu.Lock()- r.fail = fail- r.mu.Unlock()-}--func (r *recorder) count() int {- r.mu.Lock()- defer r.mu.Unlock()- return len(r.lines)-}-type harness struct {server *Serverrec *recorder@@ -82,7 +53,7 @@ func startServer(t *testing.T, configure func(*Server)) *harness {rec := &recorder{}s := &Server{Append: rec.append,- LookupName: func(uid uint32) string { return fmt.Sprintf("user%d", uid) },+ LookupName: func(uid string) string { return "user" + uid },}if configure != nil {configure(s)@@ -95,23 +66,6 @@ func startServer(t *testing.T, configure func(*Server)) *harness {return h}-func lines(t *testing.T, n int) [][]byte {- t.Helper()- out := make([][]byte, n)- for i := range out {- i := i- out[i] = validLine(t, func(e map[string]interface{}) {- e["event"].(map[string]interface{})["id"] = fmt.Sprintf("id-%d", i)- e["message"] = fmt.Sprintf("m-%d", i)- e["user"] = map[string]interface{}{"name": "root", "uid": "0"}- })- }- return out-}--// opening is the preamble and a header naming no log, which a server without a LogPath accepts.-const opening = Preamble + "\n" + `{"log":""}` + "\n"-// rawExchange speaks the protocol by hand, for what a well-behaved Client never sends.func rawExchange(t *testing.T, path string, payload string) (Response, error) {t.Helper()@@ -188,7 +142,7 @@ func TestPeerCredentialsMatchTheConnectingProcess(t *testing.T) {}defer conn.Close()peer := <-got- if int(peer.UID) != os.Geteuid() || int(peer.GID) != os.Getegid() {+ if peer.UID != strconv.Itoa(os.Geteuid()) || int(peer.GID) != os.Getegid() {t.Fatalf("peer = %+v, want uid %d gid %d", peer, os.Geteuid(), os.Getegid())}if peer.PID != int32(os.Getpid()) {@@ -536,7 +490,7 @@ func TestClientRefusesALineWithAnEmbeddedNewline(t *testing.T) {func TestClientWithoutASocket(t *testing.T) {c := Client{SocketPath: filepath.Join(shortTempDir(t), "missing.sock"), TrustedOwner: os.Geteuid()}- if err := c.Available(); !errors.Is(err, ErrNoSocket) {+ if err := available(c); !errors.Is(err, ErrNoSocket) {t.Fatalf("Available = %v, want ErrNoSocket", err)}if _, err := c.Send(lines(t, 1)); !errors.Is(err, ErrNoSocket) {@@ -572,7 +526,7 @@ func TestClientRefusesUntrustedSockets(t *testing.T) {if err := os.Chmod(filepath.Dir(h.path), 0o777); err != nil {t.Fatal(err)}- if err := h.client.Available(); !errors.Is(err, ErrUntrustedSocket) {+ if err := available(h.client); !errors.Is(err, ErrUntrustedSocket) {t.Fatalf("Available = %v", err)}if _, err := h.client.Send(lines(t, 1)); !errors.Is(err, ErrUntrustedSocket) {@@ -585,13 +539,13 @@ func TestClientRefusesUntrustedSockets(t *testing.T) {if err := os.Chmod(ancestor, 0o777); err != nil {t.Fatal(err)}- if err := h.client.Available(); !errors.Is(err, ErrUntrustedSocket) {+ if err := available(h.client); !errors.Is(err, ErrUntrustedSocket) {t.Fatalf("Available = %v", err)}if err := os.Chmod(ancestor, 0o777|os.ModeSticky); err != nil {t.Fatal(err)}- if err := h.client.Available(); err != nil {+ if err := available(h.client); err != nil {t.Fatalf("a sticky ancestor (like /tmp) should be trusted: %v", err)}})@@ -608,7 +562,7 @@ func TestClientRefusesUntrustedSockets(t *testing.T) {systemGroups = map[int]bool{}t.Cleanup(func() { systemGroups = prev })}- if err := h.client.Available(); !errors.Is(err, ErrUntrustedSocket) {+ if err := available(h.client); !errors.Is(err, ErrUntrustedSocket) {t.Fatalf("Available = %v, want a group-writable ancestor refused", err)}})@@ -621,7 +575,7 @@ func TestClientRefusesUntrustedSockets(t *testing.T) {prev := systemGroupssystemGroups = map[int]bool{os.Getegid(): true}t.Cleanup(func() { systemGroups = prev })- if err := h.client.Available(); err != nil {+ if err := available(h.client); err != nil {t.Fatalf("Available = %v, want a system group's write trusted", err)}})@@ -633,7 +587,7 @@ func TestClientRefusesUntrustedSockets(t *testing.T) {}c := h.clientc.SocketPath = link- if err := c.Available(); !errors.Is(err, ErrUntrustedSocket) {+ if err := available(c); !errors.Is(err, ErrUntrustedSocket) {t.Fatalf("Available = %v, want a link refused", err)}})@@ -827,7 +781,7 @@ func TestOneAccountCannotHoldEveryConnection(t *testing.T) {// Wait for both to be counted against the account.for time.Now().Before(deadline) {h.server.mu.Lock()- n := h.server.perUID[uint32(os.Geteuid())]+ n := h.server.perUID[strconv.Itoa(os.Geteuid())]h.server.mu.Unlock()if n == 2 {break@@ -928,7 +882,7 @@ func TestProbe(t *testing.T) {l.SetUnlinkOnClose(false)_ = l.Close()dead := Client{SocketPath: stale, TrustedOwner: os.Geteuid(), Timeout: time.Second}- if err := dead.Available(); err != nil {+ if err := available(dead); err != nil {t.Fatalf("fixture: Available on a dead socket = %v", err)}if err := dead.Probe(); err == nil || errors.Is(err, ErrNoSocket) {@@ -1037,3 +991,10 @@ func TestServerLogsAnAccountAtMostOncePerInterval(t *testing.T) {t.Fatalf("logged %d lines for one account's flood, want 1: %q", len(logged), logged)}}++// available is the socket trust check on its own, without connecting: what a client decides+// before it dials.+func available(c Client) error {+ _, err := checkSocket(c.path(), c.TrustedOwner)+ return err+}diff --git a/pkg/asymptoteobserve/localingest/server_windows_test.go b/pkg/asymptoteobserve/localingest/server_windows_test.gonew file mode 100644index 00000000..93275ebb--- /dev/null+++ b/pkg/asymptoteobserve/localingest/server_windows_test.go@@ -0,0 +1,364 @@+//go:build windows++package localingest++import (+ "bufio"+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "os"+ "strings"+ "sync/atomic"+ "testing"+ "time"+ "unsafe"++ "github.com/Microsoft/go-winio"+ "golang.org/x/sys/windows"+)++var pipeSeq atomic.Int64++// testPipe is a pipe name no other test, and no other run on the machine, uses.+func testPipe(t *testing.T) string {+ t.Helper()+ return fmt.Sprintf(`\\.\pipe\beacon-ingest-test-%d-%d-%d`, os.Getpid(), time.Now().UnixNano(), pipeSeq.Add(1))+}++// currentSID is the account this test runs as.+func currentSID(t *testing.T) string {+ t.Helper()+ user, err := windows.GetCurrentProcessToken().GetTokenUser()+ if err != nil {+ t.Fatal(err)+ }+ return user.User.Sid.String()+}++type pipeHarness struct {+ server *Server+ rec *recorder+ client Client+ path string+}++// startPipeServer serves a fresh pipe as this test's account. The client trusts the test's account+// as the pipe's owner, the way a production client trusts SYSTEM's.+func startPipeServer(t *testing.T, configure func(*Server)) *pipeHarness {+ t.Helper()+ path := testPipe(t)+ l, err := Listen(path)+ if err != nil {+ t.Fatal(err)+ }+ rec := &recorder{}+ s := &Server{Append: rec.append, LookupName: func(uid string) string { return "name-of-" + uid }}+ if configure != nil {+ configure(s)+ }+ go func() { _ = s.Serve(l) }()+ t.Cleanup(func() { _ = s.Close() })+ return &pipeHarness{server: s, rec: rec, path: path,+ client: Client{SocketPath: path, TrustedSID: currentSID(t), Timeout: 5 * time.Second}}+}++func TestPipeRoundTripStampsTheSendersAccount(t *testing.T) {+ h := startPipeServer(t, nil)+ resp, err := h.client.Send(lines(t, 3))+ if err != nil {+ t.Fatal(err)+ }+ if resp.Accepted != 3 || resp.Processed != 3 {+ t.Fatalf("response = %+v", resp)+ }+ if h.rec.count() != 3 {+ t.Fatalf("recorded %d lines", h.rec.count())+ }+ sid := currentSID(t)+ for _, line := range h.rec.lines {+ user := decode(t, line)["user"].(map[string]interface{})+ if user["uid"] != sid || user["name"] != "name-of-"+sid {+ t.Fatalf("user = %#v; the line claimed root, and must carry this account (%s) instead", user, sid)+ }+ }+}++func TestPipeManyBatchesAndProbe(t *testing.T) {+ h := startPipeServer(t, nil)+ if err := h.client.Probe(); err != nil {+ t.Fatalf("Probe = %v", err)+ }+ resp, err := h.client.Send(lines(t, MaxLinesPerConn+5))+ if err != nil {+ t.Fatal(err)+ }+ if resp.Accepted != MaxLinesPerConn+5 || h.rec.count() != MaxLinesPerConn+5 {+ t.Fatalf("response %+v, recorded %d", resp, h.rec.count())+ }+}++func TestPipeWithoutAServer(t *testing.T) {+ c := Client{SocketPath: testPipe(t), Timeout: time.Second}+ if _, err := c.Send(lines(t, 1)); !errors.Is(err, ErrNoSocket) {+ t.Fatalf("Send = %v, want ErrNoSocket", err)+ }+ if err := c.Probe(); !errors.Is(err, ErrNoSocket) {+ t.Fatalf("Probe = %v, want ErrNoSocket", err)+ }+}++func TestPipeLogMismatch(t *testing.T) {+ h := startPipeServer(t, func(s *Server) { s.LogPath = `C:\ProgramData\Beacon\Endpoint\logs\runtime.jsonl` })+ c := h.client+ c.LogPath = `C:\elsewhere\runtime.jsonl`+ if _, err := c.Send(lines(t, 1)); !errors.Is(err, ErrLogMismatch) {+ t.Fatalf("Send = %v, want ErrLogMismatch", err)+ }+ if h.rec.count() != 0 {+ t.Fatal("wrote a line meant for another log")+ }+ c.LogPath = h.server.LogPath+ if err := c.Probe(); err != nil {+ t.Fatalf("Probe for the served log = %v", err)+ }+}++// A second Listen on a name already served fails: a collector cannot be started alongside another,+// and an account that created the pipe first cannot have the collector serve its instance.+func TestPipeListenRefusesANameAlreadyTaken(t *testing.T) {+ path := testPipe(t)+ l, err := Listen(path)+ if err != nil {+ t.Fatal(err)+ }+ defer l.Close()+ if second, err := Listen(path); err == nil {+ _ = second.Close()+ t.Fatal("a second Listen on the same pipe succeeded")+ }+}++func TestListenRefusesAPathThatIsNotAPipe(t *testing.T) {+ if l, err := Listen(`C:\Windows\Temp\ingest.sock`); err == nil {+ _ = l.Close()+ t.Fatal("Listen accepted a path outside the pipe namespace")+ }+}++// The client sends only to a pipe SYSTEM or Administrators created. A pipe this test created is+// owned by its account -- or by Administrators when the test runs elevated, which is trusted -- so+// what the client must do depends on which; both are asserted.+func TestPipeClientChecksThePipesOwner(t *testing.T) {+ h := startPipeServer(t, nil)+ conn, err := winio.DialPipeAccessImpLevel(context.Background(), h.path, clientPipeAccess, winio.PipeImpLevelIdentification)+ if err != nil {+ t.Fatal(err)+ }+ owner, err := pipeOwner(conn)+ _ = conn.Close()+ if err != nil {+ t.Fatal(err)+ }+ untrusting := h.client+ untrusting.TrustedSID = ""+ _, err = untrusting.Send(lines(t, 1))+ switch owner {+ case sidLocalSystem, sidAdministrators:+ if err != nil {+ t.Fatalf("pipe owned by %s refused: %v", owner, err)+ }+ default:+ if !errors.Is(err, ErrUntrustedSocket) {+ t.Fatalf("pipe owned by %s: Send = %v, want ErrUntrustedSocket", owner, err)+ }+ if h.rec.count() != 0 {+ t.Fatal("sent an event to a pipe an ordinary account created")+ }+ }+}++func TestTrustedPipeOwner(t *testing.T) {+ c := Client{}+ for sid, want := range map[string]bool{+ sidLocalSystem: true,+ sidAdministrators: true,+ "S-1-5-32-545": false, // Users+ "S-1-5-11": false, // Authenticated Users+ "S-1-5-21-1-2-3-1001": false,+ "": false,+ } {+ if got := c.trustedPipeOwner(sid); got != want {+ t.Errorf("trustedPipeOwner(%q) = %v, want %v", sid, got, want)+ }+ }+ c.TrustedSID = "S-1-5-21-1-2-3-1001"+ if !c.trustedPipeOwner("s-1-5-21-1-2-3-1001") {+ t.Error("TrustedSID is compared without regard to case")+ }+}++// The pipe denies network logons ahead of every grant, and gives ordinary accounts no right to add+// an instance of their own.+func TestPipeSecurity(t *testing.T) {+ h := startPipeServer(t, nil)+ conn, err := winio.DialPipeAccessImpLevel(context.Background(), h.path, clientPipeAccess, winio.PipeImpLevelIdentification)+ if err != nil {+ t.Fatal(err)+ }+ defer conn.Close()+ handle, err := handleOf(conn)+ if err != nil {+ t.Fatal(err)+ }+ sd, err := windows.GetSecurityInfo(handle, windows.SE_KERNEL_OBJECT, windows.DACL_SECURITY_INFORMATION)+ if err != nil {+ t.Fatal(err)+ }+ dacl, _, err := sd.DACL()+ if err != nil || dacl == nil {+ t.Fatalf("DACL: %v", err)+ }+ var sawNetworkDeny bool+ for i := uint32(0); i < uint32(dacl.AceCount); i++ {+ var ace *windows.ACCESS_ALLOWED_ACE+ if err := windows.GetAce(dacl, i, &ace); err != nil {+ t.Fatal(err)+ }+ sid := (*windows.SID)(unsafe.Pointer(&ace.SidStart)).String()+ switch ace.Header.AceType {+ case windows.ACCESS_DENIED_ACE_TYPE:+ if sid == "S-1-5-2" {+ if i != 0 {+ t.Errorf("the network deny is entry %d; it must come before every grant", i)+ }+ sawNetworkDeny = true+ }+ case windows.ACCESS_ALLOWED_ACE_TYPE:+ if sid != sidLocalSystem && sid != sidAdministrators && ace.Mask&windows.FILE_APPEND_DATA != 0 {+ t.Errorf("%s may create pipe instances (mask %#x)", sid, ace.Mask)+ }+ }+ }+ if !sawNetworkDeny {+ t.Error("no entry denies network logons")+ }+}++// identify reads the client's own token once the server has read from the pipe, and agrees with+// the account the connection was counted against.+func TestIdentifyReadsTheClientsAccount(t *testing.T) {+ path := testPipe(t)+ l, err := Listen(path)+ if err != nil {+ t.Fatal(err)+ }+ defer l.Close()+ type got struct {+ account string+ peer Peer+ err error+ }+ result := make(chan got, 1)+ go func() {+ conn, err := l.Accept()+ if err != nil {+ result <- got{err: err}+ return+ }+ defer conn.Close()+ account, err := connectingAccount(conn)+ if err != nil {+ result <- got{err: err}+ return+ }+ if _, err := bufio.NewReader(conn).ReadString('\n'); err != nil {+ result <- got{err: err}+ return+ }+ peer, err := identify(conn)+ result <- got{account: account, peer: peer, err: err}+ }()+ conn, err := winio.DialPipeAccessImpLevel(context.Background(), path, clientPipeAccess, winio.PipeImpLevelIdentification)+ if err != nil {+ t.Fatal(err)+ }+ defer conn.Close()+ if _, err := conn.Write([]byte(Preamble + "\n")); err != nil {+ t.Fatal(err)+ }+ r := <-result+ if r.err != nil {+ t.Fatal(r.err)+ }+ sid := currentSID(t)+ if r.account != sid || r.peer.UID != sid {+ t.Fatalf("account %q, peer %q; want both %q", r.account, r.peer.UID, sid)+ }+ if r.peer.PID != int32(os.Getpid()) {+ t.Fatalf("peer pid %d, want %d", r.peer.PID, os.Getpid())+ }+}++// A client that connects anonymously gives the server nothing to stamp, and is refused.+func TestPipeRefusesAnAnonymousClient(t *testing.T) {+ h := startPipeServer(t, nil)+ conn, err := winio.DialPipeAccessImpLevel(context.Background(), h.path, clientPipeAccess, winio.PipeImpLevelAnonymous)+ if err != nil {+ t.Fatal(err)+ }+ defer conn.Close()+ _ = conn.SetDeadline(time.Now().Add(5 * time.Second))+ payload := opening + string(lines(t, 1)[0]) + "\n"+ if _, err := conn.Write([]byte(payload)); err != nil {+ t.Fatal(err)+ }+ if hc, ok := conn.(halfCloser); ok {+ _ = hc.CloseWrite()+ }+ reply, _ := bufio.NewReader(conn).ReadString('\n')+ var resp Response+ if strings.TrimSpace(reply) != "" {+ if err := json.Unmarshal([]byte(reply), &resp); err != nil {+ t.Fatalf("reply %q: %v", reply, err)+ }+ }+ if resp.Accepted != 0 || h.rec.count() != 0 {+ t.Fatalf("an anonymous client's event was written: reply %q", reply)+ }+}++func TestPipeRefusesAConnectionWithoutThePreamble(t *testing.T) {+ h := startPipeServer(t, nil)+ conn, err := winio.DialPipeAccessImpLevel(context.Background(), h.path, clientPipeAccess, winio.PipeImpLevelIdentification)+ if err != nil {+ t.Fatal(err)+ }+ defer conn.Close()+ _ = conn.SetDeadline(time.Now().Add(5 * time.Second))+ if _, err := conn.Write([]byte("GET / HTTP/1.1\n" + string(lines(t, 1)[0]) + "\n")); err != nil {+ t.Fatal(err)+ }+ _ = conn.(halfCloser).CloseWrite()+ reply, err := bufio.NewReader(conn).ReadString('\n')+ if err != nil {+ t.Fatal(err)+ }+ if !strings.Contains(reply, Preamble) || h.rec.count() != 0 {+ t.Fatalf("reply %q, recorded %d", reply, h.rec.count())+ }+}++func TestPipeServerCloseStopsServing(t *testing.T) {+ h := startPipeServer(t, nil)+ if _, err := h.client.Send(lines(t, 1)); err != nil {+ t.Fatal(err)+ }+ if err := h.server.Close(); err != nil {+ t.Fatal(err)+ }+ if _, err := h.client.Send(lines(t, 1)); !errors.Is(err, ErrNoSocket) {+ t.Fatalf("Send after Close = %v, want ErrNoSocket: a closed server leaves no pipe behind", err)+ }+}diff --git a/pkg/asymptoteobserve/localingest/transport_other.go b/pkg/asymptoteobserve/localingest/transport_other.gonew file mode 100644index 00000000..6136b841--- /dev/null+++ b/pkg/asymptoteobserve/localingest/transport_other.go@@ -0,0 +1,35 @@+//go:build !unix && !windows++package localingest++import (+ "errors"+ "net"+ "time"+)++// DefaultSocketPath names no socket here: the restricted log access mode is not available on this+// platform, so writers keep appending to the log as before.+const DefaultSocketPath = ""++// Listener is what Listen would return.+type Listener = net.Listener++// connect always reports no socket here.+func (c Client) connect(time.Duration) (net.Conn, error) { return nil, ErrNoSocket }++// RemoveStale has nothing to remove here.+func RemoveStale(string) error { return nil }++// Listen is unsupported here.+func Listen(string) (Listener, error) { return nil, errors.ErrUnsupported }++// connectingAccount is unsupported here.+func connectingAccount(net.Conn) (string, error) { return "", errors.ErrUnsupported }++// identify is unsupported here.+func identify(net.Conn) (Peer, error) { return Peer{}, errors.ErrUnsupported }++const peerCredentialsSupported = false++func temporaryAcceptError(error) bool { return false }diff --git a/pkg/asymptoteobserve/localingest/trust_unix.go b/pkg/asymptoteobserve/localingest/transport_unix.gosimilarity index 89%rename from pkg/asymptoteobserve/localingest/trust_unix.gorename to pkg/asymptoteobserve/localingest/transport_unix.goindex 976aef9a..f0ec0857 100644--- a/pkg/asymptoteobserve/localingest/trust_unix.go+++ b/pkg/asymptoteobserve/localingest/transport_unix.go@@ -12,6 +12,14 @@ import ("time")+// DefaultSocketPath is where a system-mode collector in the restricted log access mode listens.+// /var/run is root-owned on Linux (a link to /run) and macOS (a link to /private/var/run), so only+// root can create the directory the socket lives in.+const DefaultSocketPath = "/var/run/beacon-agent/ingest.sock"++// Listener is what Listen returns: a Unix socket listener, which removes its socket when closed.+type Listener = *net.UnixListener+// SocketDirMode is the mode of the directory the socket lives in: root may create entries, nobody// else may.const SocketDirMode os.FileMode = 0o755@@ -20,6 +28,20 @@ const SocketDirMode os.FileMode = 0o755// what a connection may do is decided by the server, from the peer's kernel credentials.const SocketMode os.FileMode = 0o666+// connect dials the socket at the client's path once checkSocket has accepted it, by its resolved+// path.+func (c Client) connect(timeout time.Duration) (net.Conn, error) {+ socket, err := checkSocket(c.path(), c.TrustedOwner)+ if err != nil {+ return nil, err+ }+ conn, err := net.DialTimeout("unix", socket, timeout)+ if err != nil {+ return nil, fmt.Errorf("connect to %s: %w", c.path(), err)+ }+ return conn, nil+}+// checkSocket decides whether a writer may send to path. The socket must be owned by owner, and so// must its directory, which nobody else may write; every directory above it must belong to root or// owner and be writable by nobody else unless it is sticky (as /tmp is), so the directory holdingdiff --git a/pkg/asymptoteobserve/localingest/transport_windows.go b/pkg/asymptoteobserve/localingest/transport_windows.gonew file mode 100644index 00000000..a2cc066e--- /dev/null+++ b/pkg/asymptoteobserve/localingest/transport_windows.go@@ -0,0 +1,274 @@+//go:build windows++package localingest++import (+ "context"+ "errors"+ "fmt"+ "io/fs"+ "net"+ "runtime"+ "strings"+ "time"++ "github.com/Microsoft/go-winio"+ "golang.org/x/sys/windows"+)++// DefaultSocketPath is the named pipe a system-mode collector in the restricted log access mode+// serves. Named pipes live in their own namespace rather than in a directory, so what keeps a user+// from standing up a pipe of this name first is checked on both ends instead: the collector creates+// it as the first instance or fails to start, and a client sends only to a pipe whose owner is+// SYSTEM or Administrators, which no ordinary account can make itself.+const DefaultSocketPath = `\\.\pipe\beacon-agent-ingest`++// Listener is what Listen returns.+type Listener = net.Listener++// pipeSecurity is the pipe's security descriptor, in SDDL.+//+// - Network logons are denied outright, ahead of every grant. The pipe also rejects remote+// clients (go-winio creates it with FILE_PIPE_REJECT_REMOTE_CLIENTS), so the deny is a second+// lock on the same door: a pipe is otherwise reachable over SMB, and this channel must never be+// a network one.+// - SYSTEM and Administrators have full control.+// - Authenticated users may connect, read and write: 0x12019b is FILE_GENERIC_READ and+// FILE_GENERIC_WRITE without FILE_APPEND_DATA, which on a pipe is FILE_CREATE_PIPE_INSTANCE.+// Without it no other account can add an instance of its own to this pipe and answer the+// clients that connect to it.+const pipeSecurity = "D:P(D;;GA;;;NU)(A;;GA;;;SY)(A;;GA;;;BA)(A;;0x12019b;;;AU)"++// clientPipeAccess is what a client asks for: read and write data, read attributes (go-winio reads+// the pipe's mode), READ_CONTROL to read the pipe's owner, and SYNCHRONIZE. GENERIC_WRITE would+// include FILE_CREATE_PIPE_INSTANCE, which pipeSecurity withholds, and fail.+const clientPipeAccess = windows.FILE_READ_DATA | windows.FILE_WRITE_DATA | windows.FILE_READ_ATTRIBUTES |+ windows.READ_CONTROL | windows.SYNCHRONIZE++const (+ sidLocalSystem = "S-1-5-18"+ sidAdministrators = "S-1-5-32-544"+)++// pipeBufferBytes sizes the server's inbound buffer to hold a maximum-size line with room to spare.+const pipeBufferBytes = 2 * (MaxLineBytes + 2)++// Listen creates the pipe at path for a Server to serve. The pipe must not already exist: its first+// instance is created with pipeSecurity, and a pipe someone else created first -- another collector,+// or an account squatting the name -- fails the call rather than being served alongside.+//+// The pipe is in message mode so a client can signal the end of its batch with a zero-byte message,+// which is how a pipe half-closes; it is read as a byte stream all the same.+func Listen(path string) (Listener, error) {+ if path == "" {+ path = DefaultSocketPath+ }+ if !isPipePath(path) {+ return nil, fmt.Errorf("%s is not a named pipe path (\\\\.\\pipe\\name)", path)+ }+ l, err := winio.ListenPipe(path, &winio.PipeConfig{+ SecurityDescriptor: pipeSecurity,+ MessageMode: true,+ InputBufferSize: pipeBufferBytes,+ OutputBufferSize: maxResponseBytes,+ })+ if err != nil {+ if errors.Is(err, windows.ERROR_ACCESS_DENIED) || errors.Is(err, windows.ERROR_PIPE_BUSY) || errors.Is(err, fs.ErrExist) {+ return nil, fmt.Errorf("another process already serves %s: %w", path, err)+ }+ return nil, err+ }+ return l, nil+}++// RemoveStale has nothing to remove on Windows: a pipe disappears with the last handle to it, so a+// collector that was killed leaves nothing behind.+func RemoveStale(string) error { return nil }++func isPipePath(path string) bool {+ return len(path) > len(`\\.\pipe\`) && strings.EqualFold(path[:len(`\\.\pipe\`)], `\\.\pipe\`)+}++// connect opens the pipe at the client's path and checks who created it before anything is sent.+//+// The client allows the server to identify it and no more (SECURITY_IDENTIFICATION): the collector+// needs to know whose events these are, and has no business acting as that account.+func (c Client) connect(timeout time.Duration) (net.Conn, error) {+ path := c.path()+ if !isPipePath(path) {+ return nil, fmt.Errorf("%w: %s is not a named pipe", ErrUntrustedSocket, path)+ }+ ctx, cancel := context.WithTimeout(context.Background(), timeout)+ defer cancel()+ conn, err := winio.DialPipeAccessImpLevel(ctx, path, clientPipeAccess, winio.PipeImpLevelIdentification)+ if err != nil {+ if errors.Is(err, fs.ErrNotExist) {+ return nil, ErrNoSocket+ }+ return nil, fmt.Errorf("connect to %s: %w", path, err)+ }+ owner, err := pipeOwner(conn)+ if err != nil {+ _ = conn.Close()+ return nil, fmt.Errorf("%w: %s: %v", ErrUntrustedSocket, path, err)+ }+ if !c.trustedPipeOwner(owner) {+ _ = conn.Close()+ return nil, fmt.Errorf("%w: %s was created by %s, not SYSTEM or Administrators", ErrUntrustedSocket, path, owner)+ }+ return conn, nil+}++// trustedPipeOwner reports whether a pipe owned by sid can only have been created by a privileged+// process. A pipe's owner is its creator's default owner -- SYSTEM, or Administrators for an+// elevated administrator -- and no ordinary account can name another owner when it creates one.+func (c Client) trustedPipeOwner(sid string) bool {+ switch {+ case strings.EqualFold(sid, sidLocalSystem), strings.EqualFold(sid, sidAdministrators):+ return true+ case c.TrustedSID != "" && strings.EqualFold(sid, c.TrustedSID):+ return true+ }+ return false+}++// handleOf is the Windows handle under a go-winio pipe connection.+func handleOf(conn net.Conn) (windows.Handle, error) {+ f, ok := conn.(interface{ Fd() uintptr })+ if !ok {+ return 0, errors.New("not a named pipe")+ }+ return windows.Handle(f.Fd()), nil+}++func pipeOwner(conn net.Conn) (string, error) {+ h, err := handleOf(conn)+ if err != nil {+ return "", err+ }+ sd, err := windows.GetSecurityInfo(h, windows.SE_KERNEL_OBJECT, windows.OWNER_SECURITY_INFORMATION)+ if err != nil {+ return "", fmt.Errorf("read the pipe's owner: %w", err)+ }+ owner, _, err := sd.Owner()+ if err != nil || owner == nil {+ return "", fmt.Errorf("read the pipe's owner: %v", err)+ }+ sid := owner.String()+ runtime.KeepAlive(sd)+ return sid, nil+}++// connectingAccount is the account of the process at the other end of conn, read from that+// process's token before anything is read from the pipe, for the server's per-account connection+// cap. It names whoever runs that process id now, which could in principle be another process that+// took the id after the client exited; identify, which reads the client's own token once the pipe+// has been read, settles the identity events are stamped with, and the server refuses the+// connection when the two disagree.+func connectingAccount(conn net.Conn) (string, error) {+ h, err := handleOf(conn)+ if err != nil {+ return "", err+ }+ var pid uint32+ if err := windows.GetNamedPipeClientProcessId(h, &pid); err != nil {+ return "", fmt.Errorf("read the client's process id: %w", err)+ }+ process, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, false, pid)+ if err != nil {+ return "", fmt.Errorf("open the client process %d: %w", pid, err)+ }+ defer windows.CloseHandle(process)+ var token windows.Token+ if err := windows.OpenProcessToken(process, windows.TOKEN_QUERY, &token); err != nil {+ return "", fmt.Errorf("open the client process's token: %w", err)+ }+ defer token.Close()+ user, err := token.GetTokenUser()+ if err != nil {+ return "", fmt.Errorf("read the client process's account: %w", err)+ }+ return user.User.Sid.String(), nil+}++var procImpersonateNamedPipeClient = windows.NewLazySystemDLL("advapi32.dll").NewProc("ImpersonateNamedPipeClient")++// identify asks Windows who is on the other end of conn: the server takes on the client's identity+// for a moment, reads the account from that token, and reverts. The client connected at+// identification level, which is enough to read the token and not enough to act as the account.+// It needs the server to have read from the pipe first, which Server.handle does.+func identify(conn net.Conn) (Peer, error) {+ h, err := handleOf(conn)+ if err != nil {+ return Peer{}, err+ }+ sid, err := pipeClientSID(h)+ if err != nil {+ return Peer{}, err+ }+ peer := Peer{UID: sid}+ var pid uint32+ if windows.GetNamedPipeClientProcessId(h, &pid) == nil {+ peer.PID = int32(pid)+ }+ return peer, nil+}++// pipeClientSID reads the account of the client of the pipe h. It runs on a thread of its own,+// locked, because impersonation belongs to the thread: if reverting failed, the thread is left+// locked so it ends with its goroutine and the client's identity never leaks to other work.+func pipeClientSID(h windows.Handle) (string, error) {+ type result struct {+ sid string+ err error+ }+ done := make(chan result, 1)+ go func() {+ runtime.LockOSThread()+ if r, _, callErr := procImpersonateNamedPipeClient.Call(uintptr(h)); r == 0 {+ runtime.UnlockOSThread()+ done <- result{err: fmt.Errorf("identify the client: %w", callErr)}+ return+ }+ var token windows.Token+ openErr := windows.OpenThreadToken(windows.CurrentThread(), windows.TOKEN_QUERY, true, &token)+ if err := windows.RevertToSelf(); err != nil {+ if openErr == nil {+ _ = token.Close()+ }+ done <- result{err: fmt.Errorf("stop identifying as the client: %w", err)}+ return+ }+ runtime.UnlockOSThread()+ if openErr != nil {+ done <- result{err: fmt.Errorf("read the client's token: %w", openErr)}+ return+ }+ defer token.Close()+ user, err := token.GetTokenUser()+ if err != nil {+ done <- result{err: fmt.Errorf("read the client's account: %w", err)}+ return+ }+ if user.User.Sid.IsWellKnown(windows.WinAnonymousSid) {+ done <- result{err: errors.New("the client connected anonymously")}+ return+ }+ done <- result{sid: user.User.Sid.String()}+ }()+ r := <-done+ return r.sid, r.err+}++const peerCredentialsSupported = true++// temporaryAcceptError reports an accept failure that passes on its own: the system is short of+// memory or handles for a moment.+func temporaryAcceptError(err error) bool {+ for _, errno := range []windows.Errno{windows.ERROR_NOT_ENOUGH_MEMORY, windows.ERROR_NO_SYSTEM_RESOURCES, windows.ERROR_TOO_MANY_OPEN_FILES, windows.ERROR_OUTOFMEMORY} {+ if errors.Is(err, errno) {+ return true+ }+ }+ return false+}diff --git a/pkg/asymptoteobserve/localingest/trust_other.go b/pkg/asymptoteobserve/localingest/trust_other.godeleted file mode 100644index 5ec9c3c1..00000000--- a/pkg/asymptoteobserve/localingest/trust_other.go+++ /dev/null@@ -1,18 +0,0 @@-//go:build !unix--package localingest--import (- "errors"- "net"-)--// checkSocket always reports no socket off Unix: the restricted log access mode is not available-// there, so writers keep appending to the log as before.-func checkSocket(string, int) (string, error) { return "", ErrNoSocket }--// RemoveStale has nothing to remove off Unix.-func RemoveStale(string) error { return nil }--// Listen is unsupported off Unix.-func Listen(string) (*net.UnixListener, error) { return nil, errors.ErrUnsupported }