server.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  1. package localapi
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "log/slog"
  9. "math"
  10. "net"
  11. "runtime/debug"
  12. "strconv"
  13. "sync"
  14. "time"
  15. "github.com/slackhq/nebula/commands"
  16. )
  17. const (
  18. // defaultMaxConns caps concurrent connections. Exceeding it is rejected rather than
  19. // queued: a queue turns a load problem into a latency problem and hides it.
  20. defaultMaxConns = 8
  21. // readTimeout bounds how long a client may take to send its request line.
  22. readTimeout = 10 * time.Second
  23. // writeTimeout bounds a single write. A client that stops reading is dropped rather
  24. // than waited on, so a paused terminal cannot pin daemon resources.
  25. writeTimeout = 30 * time.Second
  26. // defaultSlowAfter is how long a command may run before the daemon says so. A
  27. // command holds a connection slot until it returns, and one that never returns
  28. // holds it for good; after enough of those the socket answers only "busy". The
  29. // warning is what tells an operator that from load, and names the command.
  30. defaultSlowAfter = 30 * time.Second
  31. )
  32. // Server serves the read only portion of a command registry over a local socket.
  33. type Server struct {
  34. l *slog.Logger
  35. src *commands.Registry
  36. maxConns int
  37. slowAfter time.Duration
  38. mu sync.Mutex
  39. ln net.Listener
  40. path string
  41. running bool
  42. unwatch func() bool
  43. sem chan struct{}
  44. euid uint32
  45. }
  46. // servedHere decides what this surface will run.
  47. //
  48. // Everything except the profiling commands, which stay on the ssh debug server. Profile
  49. // output is written on the host running nebula, under sshd.sandbox_dir, so a path typed
  50. // here would not mean what the person typing it expects; and the profiling commands are
  51. // one workflow, so splitting them would leave someone able to start a CPU profile in one
  52. // place and stop it only in another.
  53. func servedHere(c *commands.Command) bool {
  54. return !c.ForProfiling
  55. }
  56. // notServedHere explains a refusal in terms an operator can act on, naming the surface
  57. // that will run the command instead.
  58. const notServedHere = "profiling is driven from the ssh debug server, where the sshd.sandbox_dir " +
  59. "setting governs where profile output is written on the host running nebula"
  60. // NewServer returns a Server that will serve the commands in reg that this surface
  61. // accepts.
  62. //
  63. // reg is kept rather than filtered here, so a command registered on it after the server
  64. // is built is served too. Filtering happens per request, which is how the ssh server
  65. // treats the same registry, cloning it per session.
  66. func NewServer(l *slog.Logger, reg *commands.Registry) *Server {
  67. return &Server{
  68. l: l,
  69. src: reg,
  70. maxConns: defaultMaxConns,
  71. slowAfter: defaultSlowAfter,
  72. // The same identity the client's owner check is made for, so the peer check
  73. // cannot disagree with it, and so a test can stand in for it the same way.
  74. euid: currentUID(),
  75. }
  76. }
  77. // Rebind brings the server up at path, moves a running server there, and serves it until
  78. // Stop or ctx cancellation. It is the one way the server comes up, so Wire's first
  79. // attempt and its reload callback are the same call, and a server already serving path
  80. // is left as it is: Wire registers the callback before the first attempt, so a HUP that
  81. // lands between the two has the callback do the first bind, and the first attempt then
  82. // finds the socket it was about to create already up.
  83. //
  84. // The new socket is bound before the old one is given up: a bad path in a reloaded
  85. // config leaves the operator with the endpoint they already had rather than none.
  86. //
  87. // s.mu is held for the whole operation, bind included. Releasing it around listen would
  88. // let a Stop land in between, and this would then install a fresh listener on a server
  89. // that had just shut down, leaving a live socket on disk until the process exits. listen
  90. // does not take s.mu, so holding it costs the other methods one bind's wait, at most the
  91. // stale socket probe, once per reload.
  92. //
  93. // An error here is never fatal to the caller: nebula keeps forwarding packets without a
  94. // control endpoint, and the caller is expected to log and carry on.
  95. func (s *Server) Rebind(ctx context.Context, path string) error {
  96. s.mu.Lock()
  97. defer s.mu.Unlock()
  98. if s.running && s.path == path {
  99. return nil
  100. }
  101. ln, err := listen(path)
  102. if err != nil {
  103. return err
  104. }
  105. // A reload that arrives during shutdown must not bring the endpoint back. Stop is
  106. // not terminal (Rebind after Stop is allowed, and is how a server whose first bind
  107. // failed comes up), so running is no guide; the context is what shutdown cancels,
  108. // and it is checked here, while nothing else can change the server's state.
  109. if err := ctx.Err(); err != nil {
  110. release(ln, path)
  111. return fmt.Errorf("not starting the local control socket, nebula is shutting down: %w", err)
  112. }
  113. oldLn, oldPath := s.ln, s.path
  114. s.ln = ln
  115. s.path = path
  116. s.running = true
  117. sem := s.semaphore()
  118. s.watchLocked(ctx)
  119. // Stop accepting on the old listener. In flight commands keep their connections,
  120. // which stay usable until they finish. Its accept loop exits on the closed-listener
  121. // error, so it is gone as soon as this returns. oldPath differs from path whenever
  122. // oldLn is set: a running server on the same path returned above.
  123. if oldLn != nil {
  124. release(oldLn, oldPath)
  125. }
  126. logListening(s.l, path)
  127. go func() {
  128. s.accept(ln, sem)
  129. }()
  130. return nil
  131. }
  132. // watchLocked stops the server when ctx is cancelled. One watcher covers a run of the
  133. // server, from the first bind that succeeds until Stop: a daemon whose initial listen
  134. // failed and which later Rebinds onto a good path from a reloaded config still needs its
  135. // socket removed on shutdown, and a Rebind on a running server must not stack a second
  136. // watcher on the same ctx. Stop detaches the watcher, so a server started again
  137. // afterwards is watched on the ctx that started it, and the ctx of an earlier run no
  138. // longer reaches it whenever that one ends. Callers hold s.mu.
  139. func (s *Server) watchLocked(ctx context.Context) {
  140. if s.unwatch != nil {
  141. return
  142. }
  143. s.unwatch = context.AfterFunc(ctx, s.Stop)
  144. }
  145. // registry returns the commands this surface serves, filtered from the source at the
  146. // time of the call. It is a few allocations per request, which a control socket that
  147. // sees a request every few seconds at most never notices.
  148. func (s *Server) registry() *commands.Registry {
  149. return s.src.Filter(servedHere, notServedHere)
  150. }
  151. // Path returns the socket path currently being served, or "" when stopped.
  152. func (s *Server) Path() string {
  153. s.mu.Lock()
  154. defer s.mu.Unlock()
  155. return s.path
  156. }
  157. // Stop closes the listener and removes the socket. In flight commands are allowed to
  158. // finish; Stop does not wait for them.
  159. //
  160. // The whole of it runs under s.mu, listener and socket included, so a Rebind cannot land
  161. // between the state change and the close and find a path that is still bound by the
  162. // listener it is replacing.
  163. func (s *Server) Stop() {
  164. s.mu.Lock()
  165. defer s.mu.Unlock()
  166. if !s.running {
  167. return
  168. }
  169. release(s.ln, s.path)
  170. s.running = false
  171. s.ln = nil
  172. s.path = ""
  173. // Set whenever running is. When this Stop is the watcher's own, stopping a watcher
  174. // that has already fired is a no-op.
  175. s.unwatch()
  176. s.unwatch = nil
  177. }
  178. // release gives up a listener and the socket node at its path. The node goes first,
  179. // while the listener is still open: for as long as it is, the node is this server's,
  180. // since a starting daemon's stale check refuses to remove a socket that answers. The
  181. // other order opens a window between the close and the unlink in which a new daemon can
  182. // find the node stale, clear it and bind its own at the same path, which the unlink
  183. // then takes from under it, leaving that daemon serving a socket nothing can reach.
  184. // listen turns off the listener's own unlink on close so this is the only unlink.
  185. func release(ln net.Listener, path string) {
  186. removeSocket(path)
  187. _ = ln.Close()
  188. }
  189. // semaphore returns the connection limiter, creating it on first use. It is made once
  190. // and never replaced: a handler releases into the channel it acquired from, so swapping
  191. // in a fresh one across a Stop and Start would leave any handler still in flight
  192. // blocked forever on a channel nothing had filled. Callers hold s.mu.
  193. func (s *Server) semaphore() chan struct{} {
  194. if s.sem == nil {
  195. s.sem = make(chan struct{}, s.maxConns)
  196. }
  197. return s.sem
  198. }
  199. // Accept failures that are not the listener closing are retried after a pause that
  200. // doubles from acceptRetryMin up to acceptRetryMax, the same shape as net/http.Serve.
  201. const (
  202. acceptRetryMin = 5 * time.Millisecond
  203. acceptRetryMax = time.Second
  204. )
  205. // accept serves connections from ln until it is closed. sem is the limiter to acquire
  206. // from and release into; it is passed rather than read from s so the handlers spawned
  207. // here never touch s.sem without the lock.
  208. //
  209. // Only a closed listener ends the loop; Stop and Rebind are the two things that close
  210. // it. Every other error is retried: the process being out of descriptors (EMFILE,
  211. // ENFILE) or a client that hung up between the kernel's queue and us (ECONNABORTED)
  212. // are passing conditions, and giving up on them would leave a socket on disk that
  213. // nothing answers, with the reason buried in a log line from minutes or days earlier.
  214. func (s *Server) accept(ln net.Listener, sem chan struct{}) {
  215. var delay time.Duration
  216. for {
  217. conn, err := ln.Accept()
  218. if err != nil {
  219. if errors.Is(err, net.ErrClosed) {
  220. return
  221. }
  222. if ne, ok := err.(net.Error); ok && ne.Timeout() {
  223. continue
  224. }
  225. if delay == 0 {
  226. delay = acceptRetryMin
  227. } else {
  228. delay = min(delay*2, acceptRetryMax)
  229. }
  230. s.l.Warn("Local control socket could not accept a connection, retrying", "error", err, "retry_in", delay)
  231. time.Sleep(delay)
  232. continue
  233. }
  234. delay = 0
  235. select {
  236. case sem <- struct{}{}:
  237. default:
  238. // At capacity. Say so and hang up rather than holding the connection open.
  239. // Logged too: a slot is held for as long as a command runs, and the slow
  240. // command warning in serve says which ones are still running.
  241. s.l.Warn("Local control socket is at capacity, refusing a connection", "max", s.maxConns)
  242. s.reply(conn, &Response{Version: ProtocolVersion, Error: "local control socket is busy, try again"})
  243. _ = conn.Close()
  244. continue
  245. }
  246. go func() {
  247. defer func() { <-sem }()
  248. s.handle(conn)
  249. }()
  250. }
  251. }
  252. // handle serves one request. It recovers from panics in command callbacks: this
  253. // surface is present on every install and reachable by any local process running as
  254. // the daemon's user, so a malformed argument must cost a connection rather than the
  255. // overlay.
  256. func (s *Server) handle(conn net.Conn) {
  257. defer conn.Close()
  258. var (
  259. args []string
  260. replied bool
  261. )
  262. defer func() {
  263. if r := recover(); r != nil {
  264. s.l.Error("Recovered from panic serving a local control command",
  265. "panic", r,
  266. "args", args,
  267. "stack", string(debug.Stack()),
  268. )
  269. // A panic in a command's AfterReply arrives here after the answer has gone
  270. // out; the client has its reply, so it is not sent a second one.
  271. if !replied {
  272. s.reply(conn, &Response{Version: ProtocolVersion, Error: "command failed"})
  273. }
  274. }
  275. }()
  276. // Where the platform can identify the caller, check it. Where it cannot, the
  277. // endpoint is still protected by the socket's mode or the pipe's security
  278. // descriptor, which listen() set before serving.
  279. if peerCheckSupported {
  280. uid, err := peerUID(conn)
  281. if err != nil {
  282. s.l.Warn("Refusing local control connection with unreadable credentials", "error", err)
  283. return
  284. }
  285. // Access is restricted to the user who ran nebula. Root is allowed through
  286. // because it can reach the daemon's memory regardless of what this check says.
  287. if uid != s.euid && uid != 0 {
  288. s.l.Warn("Refusing local control connection from another user", "peerUid", uid)
  289. s.reply(conn, &Response{Version: ProtocolVersion, Error: "not permitted"})
  290. return
  291. }
  292. }
  293. _ = conn.SetReadDeadline(time.Now().Add(readTimeout))
  294. req, err := readRequest(conn)
  295. if err != nil {
  296. s.reply(conn, &Response{Version: ProtocolVersion, Error: err.Error()})
  297. return
  298. }
  299. args = req.Args
  300. // No deadline while a command runs; the write deadline below is what bounds a client
  301. // that stops reading.
  302. _ = conn.SetReadDeadline(time.Time{})
  303. _ = conn.SetWriteDeadline(time.Now().Add(writeTimeout))
  304. res, after := s.serve(req)
  305. s.reply(conn, res)
  306. replied = true
  307. // A command that would cut off its own reply acts only now, once the answer is out.
  308. if after != nil {
  309. after()
  310. }
  311. }
  312. // serve runs one request and describes the outcome. after, when not nil, is the
  313. // command's AfterReply, which the caller runs once the response has been written.
  314. //
  315. // Nothing bounds a command's run; a context would have to reach every Run. What is
  316. // bounded is the silence: a command still running at slowAfter is named in the log, with
  317. // the slot it is holding, so a socket that has gone "busy" can be traced to the commands
  318. // that wedged it. The timer is stopped however the command ends, a panic included, so
  319. // the line is only ever written about a command that is still running.
  320. func (s *Server) serve(req *Request) (res *Response, after func()) {
  321. slow := time.AfterFunc(s.slowAfter, func() {
  322. s.l.Warn("Local control command is still running and holding a connection slot",
  323. "command", req.Command,
  324. "args", req.Args,
  325. "after", s.slowAfter,
  326. "max", s.maxConns,
  327. )
  328. })
  329. defer slow.Stop()
  330. res = &Response{Version: ProtocolVersion}
  331. reg := s.registry()
  332. if req.Describe {
  333. schema, err := json.Marshal(reg.Schema())
  334. if err != nil {
  335. res.Error = err.Error()
  336. return res, nil
  337. }
  338. res.Result = schema
  339. return res, nil
  340. }
  341. if req.Command == "" {
  342. res.Error = "no command given"
  343. return res, nil
  344. }
  345. params, err := stringParams(req.Params)
  346. if err != nil {
  347. res.Error = err.Error()
  348. return res, nil
  349. }
  350. format, err := parseFormat(req.Format)
  351. if err != nil {
  352. res.Error = err.Error()
  353. return res, nil
  354. }
  355. cmd, err := reg.Resolve(commands.Name(req.Command))
  356. if err != nil {
  357. s.l.Debug("Local control command refused", "command", req.Command, "error", err)
  358. res.Error = err.Error()
  359. return res, nil
  360. }
  361. r, err := commands.Invoke(commands.Request{Command: cmd, Params: params, Args: req.Args})
  362. if err != nil {
  363. s.l.Debug("Local control command failed", "command", req.Command, "error", err)
  364. res.Error = err.Error()
  365. return res, nil
  366. }
  367. after = cmd.AfterReply
  368. // A command with nothing to say gets an empty, successful reply.
  369. if r.Empty() {
  370. return res, after
  371. }
  372. return render(res, cmd, r, format), after
  373. }
  374. // render turns a command's Result into the response, in the format the caller asked for.
  375. // Both formats come from commands.Render, which is where ssh and the control socket
  376. // meet: the JSON a program reads here is byte for byte what -json prints at an ssh
  377. // prompt, and the text is the command's own rendering, which only the daemon can run.
  378. func render(res *Response, cmd *commands.Command, r commands.Result, format commands.Format) *Response {
  379. buf := &bytes.Buffer{}
  380. if err := commands.Render(cmd, r, format, buf); err != nil {
  381. res.Error = err.Error()
  382. return res
  383. }
  384. if format != commands.FormatText {
  385. // The caller is a program. Carry the payload as JSON rather than as a string that
  386. // happens to contain some; the newline Render ends a line with is not the value's.
  387. res.Result = bytes.TrimSuffix(buf.Bytes(), []byte("\n"))
  388. // A command that ran and refused is a failure to whoever asked, in either format.
  389. // The structured outcome still travels in Result for a program to read; Error
  390. // carries the reason so the one rule, Error set means failed, holds here too and
  391. // a client never has to guess from the payload.
  392. if !r.OK {
  393. res.Error = r.Reason
  394. }
  395. return res
  396. }
  397. // A command that ran and refused reads as an error to whoever asked for text: they
  398. // are a person or a script, and both expect a refusal on the error stream.
  399. if !r.OK {
  400. res.Error = buf.String()
  401. return res
  402. }
  403. quoted, err := json.Marshal(buf.String())
  404. if err != nil {
  405. res.Error = err.Error()
  406. return res
  407. }
  408. res.Result = quoted
  409. return res
  410. }
  411. // parseFormat turns the request's format into the one the registry understands. An
  412. // unknown value is an error rather than a silent default, so a client that asks for
  413. // something this daemon cannot do hears about it.
  414. func parseFormat(s string) (commands.Format, error) {
  415. switch s {
  416. case "", "json":
  417. return commands.FormatJSON, nil
  418. case "text":
  419. return commands.FormatText, nil
  420. default:
  421. return commands.FormatJSON, fmt.Errorf("unknown format %q, expected \"json\" or \"text\"", s)
  422. }
  423. }
  424. // reply writes one response frame.
  425. func (s *Server) reply(conn net.Conn, res *Response) {
  426. _ = conn.SetWriteDeadline(time.Now().Add(writeTimeout))
  427. if err := writeFrame(conn, res); err != nil {
  428. s.l.Debug("Could not send a local control response", "error", err)
  429. }
  430. }
  431. // stringParams converts JSON's types into the strings flag.Value.Set expects, so a
  432. // caller writes true and 3 rather than "true" and "3".
  433. func stringParams(in map[string]any) (map[string]string, error) {
  434. if len(in) == 0 {
  435. return nil, nil
  436. }
  437. out := make(map[string]string, len(in))
  438. for k, v := range in {
  439. switch t := v.(type) {
  440. case bool:
  441. out[k] = strconv.FormatBool(t)
  442. case string:
  443. out[k] = t
  444. case float64:
  445. // encoding/json gives every number as a float64; render whole ones without
  446. // a decimal point so an int flag accepts them.
  447. if t != math.Trunc(t) {
  448. out[k] = strconv.FormatFloat(t, 'f', -1, 64)
  449. continue
  450. }
  451. // A whole float64 can be far outside int64, and Go's conversion of one that is
  452. // gives an unspecified value rather than an error, so the bounds are checked
  453. // first. MinInt64 is exactly representable and is in range. MaxInt64 is not:
  454. // as a float64 it rounds up to 2^63, which is the first value out of range,
  455. // hence the >= on that side.
  456. if t < math.MinInt64 || t >= math.MaxInt64 {
  457. return nil, fmt.Errorf("parameter %q is %s, outside the range of a 64-bit integer",
  458. k, strconv.FormatFloat(t, 'g', -1, 64))
  459. }
  460. out[k] = strconv.FormatInt(int64(t), 10)
  461. case nil:
  462. return nil, fmt.Errorf("parameter %q has no value", k)
  463. default:
  464. return nil, fmt.Errorf("parameter %q is not a string, number or boolean", k)
  465. }
  466. }
  467. return out, nil
  468. }
  469. func readRequest(conn net.Conn) (*Request, error) {
  470. req := &Request{}
  471. if err := readFrame(conn, MaxRequestBytes, "request", req); err != nil {
  472. return nil, err
  473. }
  474. if req.Version != ProtocolVersion {
  475. return nil, fmt.Errorf(
  476. "this nebula speaks local control protocol v%d, the client sent v%d; the two binaries are different versions",
  477. ProtocolVersion, req.Version,
  478. )
  479. }
  480. return req, nil
  481. }