server.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. package localapi
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "io"
  9. "log/slog"
  10. "math"
  11. "net"
  12. "os"
  13. "runtime/debug"
  14. "strconv"
  15. "sync/atomic"
  16. "time"
  17. "github.com/slackhq/nebula/commands"
  18. )
  19. const (
  20. // defaultMaxConns caps concurrent connections. Exceeding it is rejected rather than
  21. // queued: a queue turns a load problem into a latency problem and hides it.
  22. defaultMaxConns = 8
  23. // readTimeout bounds how long a client may take to send its request line.
  24. readTimeout = 10 * time.Second
  25. // writeTimeout bounds a single write. A client that stops reading is dropped rather
  26. // than waited on, so a paused terminal cannot pin daemon resources.
  27. writeTimeout = 30 * time.Second
  28. // defaultSlowAfter is how long a command may run before the daemon says so. A
  29. // command holds a connection slot until it returns, and one that never returns
  30. // holds it for good; after enough of those the socket answers only "busy". The
  31. // warning is what tells an operator that from load, and names the command.
  32. defaultSlowAfter = 30 * time.Second
  33. )
  34. // ctlSocketMode is the control socket's mode when no group shares it: the user who ran
  35. // nebula, and nobody else. The mode itself is not configurable; what an operator can
  36. // choose is a group, CtlGroupKey, which makes it groupSocketMode.
  37. const ctlSocketMode os.FileMode = 0600
  38. // Server serves a command registry over a local socket to the user who ran nebula.
  39. type Server struct {
  40. endpoint
  41. src *commands.Registry
  42. maxConns int
  43. slowAfter time.Duration
  44. sem chan struct{}
  45. euid uint32
  46. // trustSocket is set while a group shares the socket. The kernel admitted the peer
  47. // through the socket's mode and group, which is the whole access control then, and
  48. // the peer check below stands aside: on unix it sees the peer's uid and primary gid
  49. // only, so it could not tell a member of the group from anyone else.
  50. trustSocket atomic.Bool
  51. }
  52. // NewServer returns a Server that will serve every command in reg, including one
  53. // registered on it after the server is built.
  54. func NewServer(l *slog.Logger, reg *commands.Registry) *Server {
  55. return &Server{
  56. endpoint: endpoint{l: l, name: "local control socket"},
  57. src: reg,
  58. maxConns: defaultMaxConns,
  59. slowAfter: defaultSlowAfter,
  60. // The same identity the client's owner check is made for, so the peer check
  61. // cannot disagree with it, and so a test can stand in for it the same way.
  62. euid: currentUID(),
  63. }
  64. }
  65. // Rebind brings the server up at path, moves a running server there, and serves it until
  66. // Stop or ctx cancellation; endpoint.rebindLocked says what that promises. An error here
  67. // is never fatal to the caller: nebula keeps forwarding packets without a control
  68. // endpoint, and the caller is expected to log and carry on.
  69. func (s *Server) Rebind(ctx context.Context, path string, acc Access) error {
  70. s.mu.Lock()
  71. defer s.mu.Unlock()
  72. // Set before the access is applied, not after, so no connection the new access
  73. // admits is checked against the old setting. Early is safe either way: a member
  74. // arriving before a group's mode is set is refused by the kernel, and with a group
  75. // being taken away the peer check applies a moment before the mode tightens.
  76. prev := s.trustSocket.Swap(acc.Group != nil)
  77. err := s.rebindLocked(ctx, path, acc, func(ln net.Listener) io.Closer {
  78. logListening(s.l, path, acc)
  79. // Closing the listener, when it is given up, ends the accept loop on the
  80. // closed-listener error; in flight commands keep their connections, which stay
  81. // usable until they finish.
  82. go s.accept(ln, s.semaphore())
  83. return ln
  84. })
  85. if err != nil {
  86. // Whatever was serving still is, with the access it had.
  87. s.trustSocket.Store(prev)
  88. }
  89. return err
  90. }
  91. // semaphore returns the connection limiter, creating it on first use. It is made once
  92. // and never replaced: a handler releases into the channel it acquired from, so swapping
  93. // in a fresh one across a Stop and Rebind would leave any handler still in flight
  94. // blocked forever on a channel nothing had filled. Callers hold s.mu.
  95. func (s *Server) semaphore() chan struct{} {
  96. if s.sem == nil {
  97. s.sem = make(chan struct{}, s.maxConns)
  98. }
  99. return s.sem
  100. }
  101. // Accept failures that are not the listener closing are retried after a pause that
  102. // doubles from acceptRetryMin up to acceptRetryMax, the same shape as net/http.Serve.
  103. const (
  104. acceptRetryMin = 5 * time.Millisecond
  105. acceptRetryMax = time.Second
  106. )
  107. // accept serves connections from ln until it is closed. sem is the limiter to acquire
  108. // from and release into; it is passed rather than read from s so the handlers spawned
  109. // here never touch s.sem without the lock.
  110. //
  111. // Only a closed listener ends the loop; Stop and Rebind are the two things that close
  112. // it. Every other error is retried: the process being out of descriptors (EMFILE,
  113. // ENFILE) or a client that hung up between the kernel's queue and us (ECONNABORTED)
  114. // are passing conditions, and giving up on them would leave a socket on disk that
  115. // nothing answers, with the reason buried in a log line from minutes or days earlier.
  116. func (s *Server) accept(ln net.Listener, sem chan struct{}) {
  117. var delay time.Duration
  118. for {
  119. conn, err := ln.Accept()
  120. if err != nil {
  121. if errors.Is(err, net.ErrClosed) {
  122. return
  123. }
  124. if ne, ok := err.(net.Error); ok && ne.Timeout() {
  125. continue
  126. }
  127. if delay == 0 {
  128. delay = acceptRetryMin
  129. } else {
  130. delay = min(delay*2, acceptRetryMax)
  131. }
  132. s.l.Warn("Local control socket could not accept a connection, retrying", "error", err, "retry_in", delay)
  133. time.Sleep(delay)
  134. continue
  135. }
  136. delay = 0
  137. select {
  138. case sem <- struct{}{}:
  139. default:
  140. // At capacity. Say so and hang up rather than holding the connection open.
  141. // Logged too: a slot is held for as long as a command runs, and the slow
  142. // command warning in serve says which ones are still running.
  143. s.l.Warn("Local control socket is at capacity, refusing a connection", "max", s.maxConns)
  144. s.reply(conn, &Response{Version: ProtocolVersion, Error: "local control socket is busy, try again"})
  145. _ = conn.Close()
  146. continue
  147. }
  148. go func() {
  149. defer func() { <-sem }()
  150. s.handle(conn)
  151. }()
  152. }
  153. }
  154. // handle serves one request. It recovers from panics in command callbacks: this
  155. // surface is present on every install and reachable by any local process running as
  156. // the daemon's user, so a malformed argument must cost a connection rather than the
  157. // overlay.
  158. func (s *Server) handle(conn net.Conn) {
  159. defer conn.Close()
  160. var args []string
  161. defer func() {
  162. if r := recover(); r != nil {
  163. s.l.Error("Recovered from panic serving a local control command",
  164. "panic", r,
  165. "args", args,
  166. "stack", string(debug.Stack()),
  167. )
  168. s.reply(conn, &Response{Version: ProtocolVersion, Error: "command failed"})
  169. }
  170. }()
  171. // Where the platform can identify the caller, check it. Where it cannot, or where a
  172. // group shares the socket, the endpoint is protected by the socket's mode and group
  173. // or the pipe's security descriptor, which listen() set before serving.
  174. if peerCheckSupported && !s.trustSocket.Load() {
  175. uid, err := peerUID(conn)
  176. if err != nil {
  177. s.l.Warn("Refusing local control connection with unreadable credentials", "error", err)
  178. return
  179. }
  180. // Access is restricted to the user who ran nebula. Root is allowed through
  181. // because it can reach the daemon's memory regardless of what this check says.
  182. if uid != s.euid && uid != 0 {
  183. s.l.Warn("Refusing local control connection from another user", "peerUid", uid)
  184. s.reply(conn, &Response{Version: ProtocolVersion, Error: "not permitted"})
  185. return
  186. }
  187. }
  188. _ = conn.SetReadDeadline(time.Now().Add(readTimeout))
  189. req, err := readRequest(conn)
  190. if err != nil {
  191. s.reply(conn, &Response{Version: ProtocolVersion, Error: err.Error()})
  192. return
  193. }
  194. args = req.Args
  195. // No deadline while a command runs; the write deadline below is what bounds a client
  196. // that stops reading.
  197. _ = conn.SetReadDeadline(time.Time{})
  198. _ = conn.SetWriteDeadline(time.Now().Add(writeTimeout))
  199. s.reply(conn, s.serve(req))
  200. }
  201. // serve runs one request and describes the outcome.
  202. //
  203. // Nothing bounds a command's run; a context would have to reach every Run. What is
  204. // bounded is the silence: a command still running at slowAfter is named in the log, with
  205. // the slot it is holding, so a socket that has gone "busy" can be traced to the commands
  206. // that wedged it. The timer is stopped however the command ends, a panic included, so
  207. // the line is only ever written about a command that is still running.
  208. func (s *Server) serve(req *Request) *Response {
  209. slow := time.AfterFunc(s.slowAfter, func() {
  210. s.l.Warn("Local control command is still running and holding a connection slot",
  211. "command", req.Command,
  212. "args", req.Args,
  213. "after", s.slowAfter,
  214. "max", s.maxConns,
  215. )
  216. })
  217. defer slow.Stop()
  218. res := &Response{Version: ProtocolVersion}
  219. reg := s.src
  220. if req.Describe {
  221. schema, err := json.Marshal(reg.Schema())
  222. if err != nil {
  223. res.Error = err.Error()
  224. return res
  225. }
  226. res.Result = schema
  227. return res
  228. }
  229. if req.Command == "" {
  230. res.Error = "no command given"
  231. return res
  232. }
  233. params, err := stringParams(req.Params)
  234. if err != nil {
  235. res.Error = err.Error()
  236. return res
  237. }
  238. format, err := parseFormat(req.Format)
  239. if err != nil {
  240. res.Error = err.Error()
  241. return res
  242. }
  243. cmd, err := reg.Resolve(commands.Name(req.Command))
  244. if err != nil {
  245. s.l.Debug("Local control command refused", "command", req.Command, "error", err)
  246. res.Error = err.Error()
  247. return res
  248. }
  249. r, err := commands.Invoke(commands.Request{Command: cmd, Params: params, Args: req.Args})
  250. if err != nil {
  251. s.l.Debug("Local control command failed", "command", req.Command, "error", err)
  252. res.Error = err.Error()
  253. return res
  254. }
  255. // A command that acts does so now, before the one reply this surface gives, and the
  256. // reply carries both halves: the line Run promised and the outcome Then produced.
  257. // In JSON only the outcome travels, since the promise is for a person to read.
  258. var preface []byte
  259. if cmd.Then != nil {
  260. if format == commands.FormatText && !r.Empty() {
  261. buf := &bytes.Buffer{}
  262. if err := commands.Render(cmd, r, format, buf); err == nil {
  263. preface = buf.Bytes()
  264. }
  265. }
  266. r = cmd.Then()
  267. }
  268. // A command with nothing to say gets an empty, successful reply.
  269. if r.Empty() {
  270. res.Text = preface
  271. return res
  272. }
  273. return render(res, cmd, r, format, preface)
  274. }
  275. // render turns a command's Result into the response, in the format the caller asked for.
  276. // Both formats come from commands.Render, which is where ssh and the control socket
  277. // meet: the JSON a program reads here is byte for byte what -json prints at an ssh
  278. // prompt, and the text is the command's own rendering, which only the daemon can run.
  279. func render(res *Response, cmd *commands.Command, r commands.Result, format commands.Format, preface []byte) *Response {
  280. buf := &bytes.Buffer{}
  281. if err := commands.Render(cmd, r, format, buf); err != nil {
  282. res.Error = err.Error()
  283. return res
  284. }
  285. if format != commands.FormatText {
  286. // The caller is a program. Carry the payload as JSON rather than as a string that
  287. // happens to contain some; the newline Render ends a line with is not the value's.
  288. res.Result = bytes.TrimSuffix(buf.Bytes(), []byte("\n"))
  289. // A command that ran and refused is a failure to whoever asked, in either format.
  290. // The structured outcome still travels in Result for a program to read; Error
  291. // carries the reason so the one rule, Error set means failed, holds here too and
  292. // a client never has to guess from the payload.
  293. if !r.OK {
  294. res.Error = r.Reason
  295. }
  296. return res
  297. }
  298. // A command that ran and refused reads as an error to whoever asked for text: they
  299. // are a person or a script, and both expect a refusal on the error stream.
  300. if !r.OK {
  301. res.Error = buf.String()
  302. return res
  303. }
  304. // The bytes the command wrote, as they are; see Response.Text.
  305. res.Text = append(preface, buf.Bytes()...)
  306. return res
  307. }
  308. // parseFormat turns the request's format into the one the registry understands. An
  309. // unknown value is an error rather than a silent default, so a client that asks for
  310. // something this daemon cannot do hears about it.
  311. func parseFormat(s string) (commands.Format, error) {
  312. switch s {
  313. case "", "json":
  314. return commands.FormatJSON, nil
  315. case "text":
  316. return commands.FormatText, nil
  317. default:
  318. return commands.FormatJSON, fmt.Errorf("unknown format %q, expected \"json\" or \"text\"", s)
  319. }
  320. }
  321. // reply writes one response frame.
  322. func (s *Server) reply(conn net.Conn, res *Response) {
  323. _ = conn.SetWriteDeadline(time.Now().Add(writeTimeout))
  324. if err := writeFrame(conn, res); err != nil {
  325. s.l.Debug("Could not send a local control response", "error", err)
  326. }
  327. }
  328. // stringParams converts JSON's types into the strings flag.Value.Set expects, so a
  329. // caller writes true and 3 rather than "true" and "3".
  330. func stringParams(in map[string]any) (map[string]string, error) {
  331. if len(in) == 0 {
  332. return nil, nil
  333. }
  334. out := make(map[string]string, len(in))
  335. for k, v := range in {
  336. switch t := v.(type) {
  337. case bool:
  338. out[k] = strconv.FormatBool(t)
  339. case string:
  340. out[k] = t
  341. case float64:
  342. // encoding/json gives every number as a float64; render whole ones without
  343. // a decimal point so an int flag accepts them.
  344. if t != math.Trunc(t) {
  345. out[k] = strconv.FormatFloat(t, 'f', -1, 64)
  346. continue
  347. }
  348. // A whole float64 can be far outside int64, and Go's conversion of one that is
  349. // gives an unspecified value rather than an error, so the bounds are checked
  350. // first. MinInt64 is exactly representable and is in range. MaxInt64 is not:
  351. // as a float64 it rounds up to 2^63, which is the first value out of range,
  352. // hence the >= on that side.
  353. if t < math.MinInt64 || t >= math.MaxInt64 {
  354. return nil, fmt.Errorf("parameter %q is %s, outside the range of a 64-bit integer",
  355. k, strconv.FormatFloat(t, 'g', -1, 64))
  356. }
  357. out[k] = strconv.FormatInt(int64(t), 10)
  358. case nil:
  359. return nil, fmt.Errorf("parameter %q has no value", k)
  360. default:
  361. return nil, fmt.Errorf("parameter %q is not a string, number or boolean", k)
  362. }
  363. }
  364. return out, nil
  365. }
  366. func readRequest(conn net.Conn) (*Request, error) {
  367. req := &Request{}
  368. if err := readFrame(conn, MaxRequestBytes, "request", req, true); err != nil {
  369. return nil, err
  370. }
  371. if req.Version != ProtocolVersion {
  372. return nil, fmt.Errorf(
  373. "this nebula speaks local control protocol v%d, the client sent v%d; the two binaries are different versions",
  374. ProtocolVersion, req.Version,
  375. )
  376. }
  377. return req, nil
  378. }