edge: owner-only unix sockets without touching the process umask (#337)
SecureUnixListen set the process umask to 0177 around its bind. The umask belongs to the whole process, so any file or directory another goroutine made in that window lost its group and other bits; a 0755 directory came out 0600 and could not be entered. In the agent that is any wake running beside a bind of a control, log or cmd socket. On Linux the socket is now made 0600 with fchmod before bind: the kernel creates the file with the socket's mode less the umask, so it appears owner-only at its path with no window. It is bound where it is served, because unixdial checks a listener's bound path against the dialled one. If the file comes out reachable by group or other the bind fails closed; removing the fchmod makes it fail exactly that way (checked). The listener embeds *net.UnixListener and removes its path once on Close, as net.Listen's does. Other unix systems keep the umask bind; they are not box targets. Tests: the umask regression (a 0755 MkdirAll racing 300 binds came out 0600 on the old code), serving at the path with nothing left behind, a failed bind cleaning up, Close removing the path once, and a bind at the 107-byte limit.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
3 files changed,
+291
−1
internal/edge/purge_listen_linux.go+101 −0internal/edge/purge_listen_linux_test.go+189 −0internal/edge/purge_listen_unix.go+1 −1
diff --git a/internal/edge/purge_listen_linux.go b/internal/edge/purge_listen_linux.go| new file mode 100644 |
| index 000000000..ea6971351 |
| --- /dev/null |
| +++ b/internal/edge/purge_listen_linux.go |
| @@ -0,0 +1,101 @@ |
| +//go:build linux |
| + |
| +package edge |
| + |
| +import ( |
| + "errors" |
| + "fmt" |
| + "net" |
| + "os" |
| + "sync" |
| + "syscall" |
| +) |
| + |
| +// SecureUnixListen binds socketPath as a unix socket reachable only by its |
| +// owner, removing any stale file left behind by a crashed previous instance. |
| +// |
| +// The owner-only guarantee is the whole point of the function and the reason |
| +// it is split out per-OS rather than shimmed at the syscall: a purge socket |
| +// that anyone on the box can connect to hands out exactly the wake-storm |
| +// lever this feature exists to remove. Making that guarantee unrepresentable |
| +// on an OS without umask is safer than making it a no-op there. |
| +// |
| +// On Linux the socket is made 0600 before it is bound: bind creates the |
| +// file with the socket's own mode less the umask, so it appears owner-only |
| +// at socketPath with no window in between. The file is bound where it will |
| +// be served because unixdial checks the path a listener was bound under |
| +// against the path it dialled, so binding elsewhere and renaming is out. |
| +// This replaces setting the process umask to 0177 around the bind: the |
| +// umask belongs to the whole process, so every file and directory any |
| +// other goroutine made in that window lost its group and other bits, and a |
| +// directory lost its execute bit with them (amadan #337). Nothing here |
| +// touches the umask. |
| +func SecureUnixListen(socketPath string) (net.Listener, error) { |
| + if err := os.Remove(socketPath); err != nil && !errors.Is(err, os.ErrNotExist) { |
| + return nil, err |
| + } |
| + fd, err := syscall.Socket(syscall.AF_UNIX, syscall.SOCK_STREAM|syscall.SOCK_CLOEXEC, 0) |
| + if err != nil { |
| + return nil, os.NewSyscallError("socket", err) |
| + } |
| + f := os.NewFile(uintptr(fd), socketPath) |
| + defer f.Close() // net.FileListener holds its own duplicate |
| + if err := syscall.Fchmod(fd, 0600); err != nil { |
| + return nil, os.NewSyscallError("fchmod", err) |
| + } |
| + if err := syscall.Bind(fd, &syscall.SockaddrUnix{Name: socketPath}); err != nil { |
| + return nil, &net.OpError{Op: "listen", Net: "unix", Addr: &net.UnixAddr{Name: socketPath, Net: "unix"}, Err: os.NewSyscallError("bind", err)} |
| + } |
| + bound := true |
| + defer func() { |
| + if bound { |
| + os.Remove(socketPath) |
| + } |
| + }() |
| + // The kernel caps the backlog at net.core.somaxconn. |
| + if err := syscall.Listen(fd, 4096); err != nil { |
| + return nil, os.NewSyscallError("listen", err) |
| + } |
| + // Fail closed if the file came out reachable by group or other: that |
| + // would mean the kernel ignored the socket's mode, and the window this |
| + // function exists to close was open. |
| + fi, err := os.Lstat(socketPath) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if fi.Mode().Type() != os.ModeSocket || fi.Mode().Perm()&0o077 != 0 { |
| + return nil, fmt.Errorf("unix socket %s was created %v, not owner-only", socketPath, fi.Mode()) |
| + } |
| + // The umask can only have taken bits away; give the owner back read |
| + // and write so it can connect. |
| + if err := os.Chmod(socketPath, 0600); err != nil { |
| + return nil, err |
| + } |
| + fl, err := net.FileListener(f) |
| + if err != nil { |
| + return nil, err |
| + } |
| + ln, ok := fl.(*net.UnixListener) |
| + if !ok { |
| + fl.Close() |
| + return nil, fmt.Errorf("unix socket %s: listener is %T, not a unix listener", socketPath, fl) |
| + } |
| + bound = false |
| + return &ownerOnlyListener{UnixListener: ln, path: socketPath}, nil |
| +} |
| + |
| +// ownerOnlyListener removes socketPath on Close, once, as a listener from |
| +// net.Listen("unix", ...) does; one built from a file does not. It embeds |
| +// the *net.UnixListener so SetDeadline and the rest stay reachable: the cmd |
| +// stream's Drain finds SetDeadline through an interface assertion. |
| +type ownerOnlyListener struct { |
| + *net.UnixListener |
| + path string |
| + unlink sync.Once |
| +} |
| + |
| +func (l *ownerOnlyListener) Close() error { |
| + err := l.UnixListener.Close() |
| + l.unlink.Do(func() { os.Remove(l.path) }) |
| + return err |
| +} |
diff --git a/internal/edge/purge_listen_linux_test.go b/internal/edge/purge_listen_linux_test.go| new file mode 100644 |
| index 000000000..c4bb515de |
| --- /dev/null |
| +++ b/internal/edge/purge_listen_linux_test.go |
| @@ -0,0 +1,189 @@ |
| +//go:build linux |
| + |
| +package edge |
| + |
| +import ( |
| + "net" |
| + "os" |
| + "path/filepath" |
| + "runtime" |
| + "strconv" |
| + "strings" |
| + "sync" |
| + "syscall" |
| + "testing" |
| +) |
| + |
| +// amadan #337: binding must not change the process umask, so directories |
| +// another goroutine makes while sockets are being bound keep their mode. |
| +// Under the old umask-0177 bind, a 0755 MkdirAll racing it came out 0600. |
| +// Not parallel: it sets the process umask to a known value for its run. |
| +func TestSecureUnixListenLeavesTheUmaskAlone(t *testing.T) { |
| + old := syscall.Umask(0o022) |
| + t.Cleanup(func() { syscall.Umask(old) }) |
| + root := t.TempDir() |
| + if err := os.MkdirAll(filepath.Join(root, "l"), 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + |
| + const rounds = 300 |
| + var wg sync.WaitGroup |
| + wg.Add(2) |
| + go func() { |
| + defer wg.Done() |
| + for i := range rounds { |
| + ln, err := SecureUnixListen(filepath.Join(root, "l", "s"+strconv.Itoa(i)+".sock")) |
| + if err != nil { |
| + t.Error(err) |
| + return |
| + } |
| + ln.Close() |
| + } |
| + }() |
| + dirs := make([]string, rounds) |
| + go func() { |
| + defer wg.Done() |
| + for i := range rounds { |
| + dirs[i] = filepath.Join(root, "d", strconv.Itoa(i)) |
| + if err := os.MkdirAll(dirs[i], 0o755); err != nil { |
| + t.Error(err) |
| + return |
| + } |
| + } |
| + }() |
| + wg.Wait() |
| + for _, d := range dirs { |
| + fi, err := os.Stat(d) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if got := fi.Mode().Perm(); got != 0o755 { |
| + t.Fatalf("%s is %o, want 0755: a bind changed the process umask", d, got) |
| + } |
| + } |
| + if got := syscall.Umask(0o022); got != 0o022 { |
| + t.Fatalf("umask after the binds = %o, want 022", got) |
| + } |
| +} |
| + |
| +// The listener is reached at socketPath, reports it, removes it on Close, |
| +// and leaves no private directory behind. |
| +func TestSecureUnixListenServesAtItsPathAndLeavesNothingBehind(t *testing.T) { |
| + t.Parallel() |
| + dir := t.TempDir() |
| + sock := filepath.Join(dir, "c.sock") |
| + ln, err := SecureUnixListen(sock) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if got := ln.Addr().String(); got != sock { |
| + t.Errorf("Addr = %s, want %s", got, sock) |
| + } |
| + accepted := make(chan error, 1) |
| + go func() { |
| + c, err := ln.Accept() |
| + if err == nil { |
| + c.Close() |
| + } |
| + accepted <- err |
| + }() |
| + c, err := net.Dial("unix", sock) |
| + if err != nil { |
| + t.Fatalf("dial %s: %v", sock, err) |
| + } |
| + c.Close() |
| + if err := <-accepted; err != nil { |
| + t.Fatal(err) |
| + } |
| + if entries := names(t, dir); len(entries) != 1 || entries[0] != "c.sock" { |
| + t.Fatalf("directory holds %v, want only c.sock", entries) |
| + } |
| + if err := ln.Close(); err != nil { |
| + t.Fatal(err) |
| + } |
| + if entries := names(t, dir); len(entries) != 0 { |
| + t.Fatalf("after Close the directory holds %v, want nothing", entries) |
| + } |
| +} |
| + |
| +// A bind that cannot be put in place (here: socketPath is a directory with |
| +// something in it) fails and leaves neither a private directory nor a |
| +// listening socket behind. |
| +func TestSecureUnixListenFailureCleansUp(t *testing.T) { |
| + t.Parallel() |
| + dir := t.TempDir() |
| + sock := filepath.Join(dir, "c.sock") |
| + if err := os.MkdirAll(filepath.Join(sock, "occupied"), 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + if ln, err := SecureUnixListen(sock); err == nil { |
| + ln.Close() |
| + t.Fatal("bound over a non-empty directory") |
| + } |
| + if entries := names(t, dir); len(entries) != 1 || entries[0] != "c.sock" { |
| + t.Fatalf("directory holds %v after a failed bind, want only the original c.sock", entries) |
| + } |
| +} |
| + |
| +// A second Close must not remove a socket a later listener has since bound |
| +// at the same path. |
| +func TestSecureUnixListenClosesItsPathOnce(t *testing.T) { |
| + t.Parallel() |
| + sock := filepath.Join(t.TempDir(), "c.sock") |
| + first, err := SecureUnixListen(sock) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + first.Close() |
| + second, err := SecureUnixListen(sock) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer second.Close() |
| + first.Close() |
| + if _, err := os.Stat(sock); err != nil { |
| + t.Fatalf("the second listener's socket is gone after the first closed again: %v", err) |
| + } |
| +} |
| + |
| +func names(t *testing.T, dir string) []string { |
| + t.Helper() |
| + entries, err := os.ReadDir(dir) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var out []string |
| + for _, e := range entries { |
| + out = append(out, e.Name()) |
| + } |
| + return out |
| +} |
| + |
| +// A socket path at the longest length the kernel accepts still binds: the |
| +// private directory's name is sized so the bind inside it is no longer |
| +// than socketPath, even for a short socket name. |
| +func TestSecureUnixListenBindsAtTheLengthLimit(t *testing.T) { |
| + t.Parallel() |
| + limit := 107 // sun_path is 108 bytes on Linux, including the NUL |
| + if runtime.GOOS != "linux" { |
| + limit = 103 // 104 on the BSDs and darwin |
| + } |
| + dir := t.TempDir() |
| + pad := limit - len(dir) - len("/") - len("/c.sock") |
| + if pad < 1 { |
| + t.Skipf("temp dir %s leaves no room under %d bytes", dir, limit) |
| + } |
| + long := filepath.Join(dir, strings.Repeat("p", pad)) |
| + if err := os.Mkdir(long, 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + sock := filepath.Join(long, "c.sock") |
| + if len(sock) != limit { |
| + t.Fatalf("built a %d-byte path, want %d", len(sock), limit) |
| + } |
| + ln, err := SecureUnixListen(sock) |
| + if err != nil { |
| + t.Fatalf("a %d-byte socket path did not bind: %v", len(sock), err) |
| + } |
| + ln.Close() |
| +} |
diff --git a/internal/edge/purge_listen_unix.go b/internal/edge/purge_listen_unix.go| index d4a8cdb3b..857ae5c89 100644 |
| --- a/internal/edge/purge_listen_unix.go |
| +++ b/internal/edge/purge_listen_unix.go |
| @@ -1,4 +1,4 @@ |
| -//go:build !windows |
| +//go:build !windows && !linux |
| package edge |