platform_unix.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. //go:build !windows
  2. package localapi
  3. import (
  4. "errors"
  5. "fmt"
  6. "log/slog"
  7. "net"
  8. "os"
  9. "os/user"
  10. "path/filepath"
  11. "strconv"
  12. "sync"
  13. "syscall"
  14. "time"
  15. )
  16. const network = "unix"
  17. // withPeerFD runs f on the descriptor behind conn, which must be a unix socket, and
  18. // returns whichever error came first: not a unix socket, no raw access to it, or f's
  19. // own. It is the scaffolding every platform's peerUID shares; only the getsockopt inside
  20. // differs.
  21. func withPeerFD(conn net.Conn, f func(fd int) error) error {
  22. uc, ok := conn.(*net.UnixConn)
  23. if !ok {
  24. return fmt.Errorf("not a unix connection")
  25. }
  26. raw, err := uc.SyscallConn()
  27. if err != nil {
  28. return err
  29. }
  30. var inner error
  31. if err := raw.Control(func(fd uintptr) { inner = f(int(fd)) }); err != nil {
  32. return err
  33. }
  34. return inner
  35. }
  36. // currentUID is the user the owner checks are made for. A variable so a test can stand
  37. // in for root, or for a stranger, without owning a second account on the host.
  38. var currentUID = func() uint32 { return uint32(os.Geteuid()) }
  39. // listen binds the socket at path with the given access.
  40. //
  41. // Access control is the socket's own mode and group, which the node is created no
  42. // looser than and which are set after bind, together with the peer check the server
  43. // applies on accept unless a group shares the socket, in which case the kernel's check
  44. // is the whole of it: connect(2) needs write permission on the socket file on every
  45. // unix we build for. The
  46. // directory is not part of that, and is never chmoded: a directory a service manager
  47. // made for us is served from at whatever mode it came with (systemd's
  48. // RuntimeDirectoryMode= is 0755 by default), and one an operator pointed us into keeps
  49. // whatever else it holds readable. The one we make ourselves is 0755, searchable by
  50. // everyone, so that an unprivileged nebula ctl can see a root daemon's socket and say
  51. // so; see ServedByRootFor.
  52. func listen(path string, acc Access) (net.Listener, error) {
  53. // The kernel silently truncates an over long sun_path and bind then fails with
  54. // "invalid argument", which tells an operator nothing. Say what is actually wrong.
  55. if pathTooLong(path) {
  56. return nil, fmt.Errorf("socket path is %d bytes, over the %d byte limit for a unix socket: %s", len(path), maxSocketPath, path)
  57. }
  58. dir := filepath.Dir(path)
  59. // One level only. Every directory defaultPathFor offers sits directly under one that
  60. // exists, and an operator who names a deeper path creates it; a missing parent is a
  61. // mistake to report, not a tree to build. A directory made here is remembered, so
  62. // that removeSocket can take it away again once nothing is left in it.
  63. //
  64. // 0755 gives nothing away: the socket's own mode is the access control. What it
  65. // gives is a directory others can look into, which is what a client that is not the
  66. // daemon's user needs to reach the socket. Mkdir applies the umask, so the mode is
  67. // pinned afterwards, as the socket's is; only on a directory this call created.
  68. switch err := os.Mkdir(dir, 0755); {
  69. case err == nil:
  70. if err := os.Chmod(dir, 0755); err != nil {
  71. return nil, fmt.Errorf("could not set the mode of %s: %w", dir, err)
  72. }
  73. madeDirs.add(dir)
  74. case !errors.Is(err, os.ErrExist):
  75. return nil, fmt.Errorf("could not create %s: %w", dir, err)
  76. }
  77. // Whether it was made here or came with the environment, the directory has to be
  78. // one nobody else could change; see checkSocketDir.
  79. if err := checkSocketDir(dir); err != nil {
  80. return nil, err
  81. }
  82. if err := clearStale(path); err != nil {
  83. return nil, err
  84. }
  85. // bind creates the socket node at the process umask, and a connect(2) between that
  86. // and a later chmod would be queued for accept. Tighten the umask around the bind so
  87. // the node is never looser than 0600, however briefly. umask is process wide, so
  88. // another goroutine creating a file during this one syscall gets 0600 too: stricter
  89. // than it asked for, never looser, and nothing here creates files on a hot path.
  90. old := syscall.Umask(0077)
  91. ln, err := net.Listen(network, path)
  92. syscall.Umask(old)
  93. if err != nil {
  94. return nil, err
  95. }
  96. // The node at path is given up by release, which unlinks it before the listener
  97. // closes; see there for why the order matters. Go's listener would unlink on Close
  98. // as well, and an unlink after the close could only be of whatever bound the path
  99. // next, so that is turned off and release is the one place the node is removed.
  100. if ul, ok := ln.(*net.UnixListener); ok {
  101. ul.SetUnlinkOnClose(false)
  102. }
  103. // The umask only promises no looser than 0600; this pins the mode and the group
  104. // exactly, and is the one place a failure to secure the socket is reported.
  105. if err := applyAccess(path, acc); err != nil {
  106. release(ln, path)
  107. return nil, fmt.Errorf("could not secure %s: %w", path, err)
  108. }
  109. return ln, nil
  110. }
  111. // applyAccess sets the owning group, when there is one, and the mode of the socket node
  112. // at path. The chown is Lchown, so a link at the path is not followed to its target.
  113. func applyAccess(path string, acc Access) error {
  114. if acc.Group != nil {
  115. gid, err := gidOf(acc.Group)
  116. if err != nil {
  117. return err
  118. }
  119. if err := os.Lchown(path, -1, gid); err != nil {
  120. return err
  121. }
  122. }
  123. return os.Chmod(path, acc.Mode.Perm())
  124. }
  125. // checkSocketDir refuses to serve from a directory that somebody other than the user
  126. // nebula runs as, or root, could change. The socket's mode and group say who may connect
  127. // to it; what makes the path they connect to the daemon's is the directory, since
  128. // whoever can write it can put a socket of their own at the path and answer the clients
  129. // in the daemon's place. So the directory must be owned by the daemon's user or by root
  130. // and writable by its owner alone; a sticky bit is not an exception. A runtime directory
  131. // a service manager made for another user, or /var/run/nebula created ahead of a root
  132. // daemon by a member of group daemon, where darwin lets that group write /var/run, are
  133. // both refused with the owner named.
  134. //
  135. // A link where the directory should be is judged twice: whoever owns the link decides
  136. // where the path leads, so the link must be ours or root's too, and the directory it
  137. // resolves to is then held to the rule above. /var/run is such a link on linux, root's,
  138. // to /run, and a socket named directly under it is served; a link somebody else planted
  139. // is refused as theirs.
  140. //
  141. // Only this directory is checked, not the ones above it. /var/run itself is group
  142. // writable on darwin by design, and the parents are the operator's to trust, as they are
  143. // for every file nebula reads. The check is made at bind, so a directory loosened while
  144. // the daemon runs is noticed at the next reload.
  145. func checkSocketDir(dir string) error {
  146. fi, err := os.Lstat(dir)
  147. if err != nil {
  148. return err
  149. }
  150. if fi.Mode()&os.ModeSymlink != 0 {
  151. if uid, ok := owner(fi); ok && uid != currentUID() && uid != 0 {
  152. return fmt.Errorf("%s is a symlink owned by %s, not by the user nebula runs as or by root, and its owner decides where the path leads; name a socket path that does not go through it", dir, describeUID(uid))
  153. }
  154. if fi, err = os.Stat(dir); err != nil {
  155. return err
  156. }
  157. }
  158. if !fi.IsDir() {
  159. return fmt.Errorf("%s is not a directory", dir)
  160. }
  161. if uid, ok := owner(fi); ok && uid != currentUID() && uid != 0 {
  162. return fmt.Errorf("%s is owned by %s, not by the user nebula runs as or by root, and its owner could replace the socket; make it ours or root's, or name a socket path in a directory that is", dir, describeUID(uid))
  163. }
  164. if perm := fi.Mode().Perm(); perm&0022 != 0 {
  165. who := "its group"
  166. if perm&0002 != 0 {
  167. who = "everyone"
  168. }
  169. return fmt.Errorf("%s is writable by %s (mode %04o), who could replace the socket; make it writable by its owner alone, or name a socket path in a directory that is", dir, who, perm)
  170. }
  171. return nil
  172. }
  173. // owner returns the uid that owns the file fi describes.
  174. func owner(fi os.FileInfo) (uint32, bool) {
  175. st, ok := fi.Sys().(*syscall.Stat_t)
  176. if !ok {
  177. return 0, false
  178. }
  179. return uint32(st.Uid), true
  180. }
  181. // describeUID renders a uid with its account name when the host can say what it is, so
  182. // a message about somebody else's socket tells the operator who that is.
  183. func describeUID(uid uint32) string {
  184. id := strconv.FormatUint(uint64(uid), 10)
  185. if u, err := user.LookupId(id); err == nil && u.Username != "" {
  186. return "uid " + id + " (" + u.Username + ")"
  187. }
  188. return "uid " + id
  189. }
  190. // clearStale removes a leftover socket file, but only after proving nothing is
  191. // listening on it. An unclean restart leaves one behind every time, so this is a
  192. // routine path; blindly unlinking would let a second daemon steal a live endpoint.
  193. //
  194. // Liveness is a plain connect. Only a refused connect proves there is nothing behind
  195. // the file. Anything else, a timeout or a permission error, is a socket we cannot vouch
  196. // for, and it is left alone with the reason in the error.
  197. func clearStale(path string) error {
  198. fi, err := os.Stat(path)
  199. if err != nil {
  200. if os.IsNotExist(err) {
  201. return nil
  202. }
  203. return err
  204. }
  205. if !isSocket(fi) {
  206. return fmt.Errorf("%s exists and is not a socket", path)
  207. }
  208. conn, err := dial(path, 250*time.Millisecond)
  209. if err == nil {
  210. _ = conn.Close()
  211. return fmt.Errorf("%s is already in use by another nebula instance", path)
  212. }
  213. if errors.Is(err, os.ErrNotExist) {
  214. // Gone between the stat and the connect; nothing to clear.
  215. return nil
  216. }
  217. if !errors.Is(err, syscall.ECONNREFUSED) {
  218. return fmt.Errorf("%s exists and could not be shown to be stale, refusing to remove it: %w", path, err)
  219. }
  220. return os.Remove(path)
  221. }
  222. // removeSocket unlinks the socket node and, when listen made the directory it is in,
  223. // removes that too, so a socket that moves off an override or a daemon that stops
  224. // leaves nothing behind. A directory that came with the environment, a service
  225. // manager's runtime directory or one the operator pointed us into, is not ours to
  226. // remove and is left as it was.
  227. func removeSocket(path string) {
  228. _ = os.Remove(path)
  229. madeDirs.remove(filepath.Dir(path))
  230. }
  231. // madeDirs is the set of directories listen created and has not yet removed. It is
  232. // package state because the socket's path is all release and listen share.
  233. var madeDirs = dirSet{made: map[string]bool{}}
  234. type dirSet struct {
  235. mu sync.Mutex
  236. made map[string]bool
  237. }
  238. func (d *dirSet) add(dir string) {
  239. d.mu.Lock()
  240. defer d.mu.Unlock()
  241. d.made[dir] = true
  242. }
  243. // remove takes dir away if listen made it and it is empty. One that still holds
  244. // something, another socket of ours or whatever else arrived, is kept and stays
  245. // remembered, so the release of the last socket in it is the one that removes it. The
  246. // same goes for any other failure: a directory that is still there is still ours to
  247. // remove, and the next release tries again. Only one that is gone is forgotten.
  248. func (d *dirSet) remove(dir string) {
  249. d.mu.Lock()
  250. defer d.mu.Unlock()
  251. if !d.made[dir] {
  252. return
  253. }
  254. if err := os.Remove(dir); err != nil && !errors.Is(err, os.ErrNotExist) {
  255. return
  256. }
  257. delete(d.made, dir)
  258. }
  259. func dial(path string, timeout time.Duration) (net.Conn, error) {
  260. return net.DialTimeout(network, path, timeout)
  261. }
  262. // sunPathMax is the smallest sun_path any platform we build for offers (104 on darwin,
  263. // 108 on linux). Overrunning it truncates the path rather than failing cleanly, so we
  264. // check against the tighter bound everywhere.
  265. const sunPathMax = 104
  266. // maxSocketPath is the longest path that actually binds. sun_path holds the trailing
  267. // NUL as well, and Go's syscall package refuses a path that fills the whole buffer
  268. // with a bare EINVAL, so the usable limit is one byte short of the buffer.
  269. const maxSocketPath = sunPathMax - 1
  270. func pathTooLong(path string) bool { return len(path) > maxSocketPath }
  271. // defaultSocketPath is the control socket when the config names none. It is root's to
  272. // create, as the tun device is root's to open; a daemon run as anyone else names a path
  273. // of its own with CtlSocketKey.
  274. const defaultSocketPath = "/var/run/" + DirName + "/ctl.sock"
  275. // checkSocketPath refuses a configured socket path that is relative, or too long to
  276. // bind. A relative path would mean a different socket to the daemon and to nebula ctl,
  277. // each resolving it against the directory it happened to be started from.
  278. func checkSocketPath(key, value string) error {
  279. if !filepath.IsAbs(value) {
  280. return fmt.Errorf("%s must be an absolute path, got %q", key, value)
  281. }
  282. if pathTooLong(value) {
  283. return fmt.Errorf("%s is %d bytes, too long for this platform: %s", key, len(value), value)
  284. }
  285. return nil
  286. }
  287. // logListening is the line written when the socket is up. It says what the access
  288. // control is: the socket's mode plus the peer check on each connection, or, when a group
  289. // shares the socket, the mode and group alone.
  290. func logListening(l *slog.Logger, path string, acc Access) {
  291. if acc.Group != nil {
  292. l.Info("Local control socket listening, access decided by the socket's group", "path", path, "access", acc.String())
  293. return
  294. }
  295. l.Info("Local control socket listening", "path", path, "access", acc.String())
  296. }
  297. func isSocket(fi os.FileInfo) bool { return fi.Mode()&os.ModeSocket != 0 }