1//go:build linux || darwin || freebsd23package cowork45import (6 "errors"7 "fmt"8 "net"9 "os"10 "syscall"11)1213// checkPeer refuses a connection from another user's process: the14// socket's permissions already keep them out, and this holds even if15// they were loosened.16func checkPeer(c net.Conn) error {17 uc, ok := c.(*net.UnixConn)18 if !ok {19 return errors.New("not a Unix socket")20 }21 raw, err := uc.SyscallConn()22 if err != nil {23 return err24 }25 uid, perr := 0, error(nil)26 if err := raw.Control(func(fd uintptr) { uid, perr = peerUID(fd) }); err != nil {27 return err28 }29 if perr != nil {30 return perr31 }32 if uid != os.Getuid() {33 return fmt.Errorf("refused a connection from user %d: only %d's own processes may attach", uid, os.Getuid())34 }35 return nil36}3738// checkOwner refuses a file or folder another user owns, or that39// others can reach.40func checkOwner(path string) error {41 info, err := os.Stat(path)42 if err != nil {43 return err44 }45 st, ok := info.Sys().(*syscall.Stat_t)46 if !ok {47 return nil48 }49 if int(st.Uid) != os.Getuid() {50 return fmt.Errorf("%s belongs to user %d, not you: 012 attaches only to your own sessions", path, st.Uid)51 }52 if info.Mode().Perm()&0o077 != 0 {53 return fmt.Errorf("%s can be reached by other users (%v): 012 attaches only to sockets that are yours alone", path, info.Mode().Perm())54 }55 return nil56}