server.go 16 KB

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