session.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. package sshd
  2. import (
  3. "errors"
  4. "log/slog"
  5. "sort"
  6. "strings"
  7. "github.com/slackhq/nebula/commands"
  8. "golang.org/x/crypto/ssh"
  9. "golang.org/x/term"
  10. )
  11. type session struct {
  12. l *slog.Logger
  13. c *ssh.ServerConn
  14. term *term.Terminal
  15. commands *commands.Registry
  16. cancel func()
  17. }
  18. func NewSession(reg *commands.Registry, conn *ssh.ServerConn, chans <-chan ssh.NewChannel, cancel func(), l *slog.Logger) *session {
  19. s := &session{
  20. commands: reg.Clone(),
  21. l: l,
  22. c: conn,
  23. cancel: cancel,
  24. }
  25. s.commands.DefaultFormat = DefaultFormat
  26. s.commands.Register(LogoutCommand(s.Close))
  27. go s.handleChannels(chans)
  28. return s
  29. }
  30. // LogoutCommand is the logout command a session registers on its clone of the registry,
  31. // with end as what it does. Exported so a test can serve what a session serves.
  32. func LogoutCommand(end func()) *commands.Command {
  33. return &commands.Command{
  34. Name: commands.Logout,
  35. ShortDescription: "Ends the current session",
  36. Run: func(a any, args []string) (commands.Result, error) {
  37. end()
  38. return commands.Nothing(), nil
  39. },
  40. }
  41. }
  42. // DefaultFormat is what an ssh session renders when the operator gave neither -json nor
  43. // -pretty: text where a command has a human form, and compact JSON for the ones that
  44. // have none (print-tunnel, print-relays, query-lighthouse). It is ssh's policy, exported so a test
  45. // can dispatch through the same choice, and ssh's to change.
  46. func DefaultFormat(c *commands.Command, r commands.Result) commands.Format {
  47. if !c.JSONOnly {
  48. return commands.FormatText
  49. }
  50. // A JSON-only command's refusal ("No vpn address was provided") is a sentence for a
  51. // person, so an outcome renders as text here; ssh users and scripts expect it.
  52. if r.Value == nil {
  53. return commands.FormatText
  54. }
  55. return commands.FormatJSON
  56. }
  57. func (s *session) handleChannels(chans <-chan ssh.NewChannel) {
  58. defer s.Close()
  59. for newChannel := range chans {
  60. if newChannel.ChannelType() != "session" {
  61. s.l.Error("unknown channel type", "sshChannelType", newChannel.ChannelType())
  62. newChannel.Reject(ssh.UnknownChannelType, "unknown channel type")
  63. continue
  64. }
  65. channel, requests, err := newChannel.Accept()
  66. if err != nil {
  67. s.l.Warn("could not accept channel", "error", err)
  68. continue
  69. }
  70. go s.handleRequests(requests, channel)
  71. }
  72. }
  73. func (s *session) handleRequests(in <-chan *ssh.Request, channel ssh.Channel) {
  74. for req := range in {
  75. var err error
  76. switch req.Type {
  77. case "shell":
  78. if s.term == nil {
  79. s.term = s.createTerm(channel)
  80. err = req.Reply(true, nil)
  81. } else {
  82. err = req.Reply(false, nil)
  83. }
  84. case "pty-req":
  85. err = req.Reply(true, nil)
  86. case "window-change":
  87. err = req.Reply(true, nil)
  88. case "exec":
  89. var payload = struct{ Value string }{}
  90. cErr := ssh.Unmarshal(req.Payload, &payload)
  91. if cErr != nil {
  92. req.Reply(false, nil)
  93. return
  94. }
  95. req.Reply(true, nil)
  96. err := s.dispatchCommand(payload.Value, commands.MergedOutput(channel))
  97. // A command that failed exits 1, so `ssh host cmd` callers can tell.
  98. status := struct{ Status uint32 }{uint32(0)}
  99. if err != nil {
  100. status.Status = 1
  101. }
  102. channel.SendRequest("exit-status", false, ssh.Marshal(status))
  103. channel.Close()
  104. return
  105. default:
  106. s.l.Debug("Rejected unknown request", "sshRequest", req.Type)
  107. err = req.Reply(false, nil)
  108. }
  109. if err != nil {
  110. s.l.Info("Error handling ssh session requests", "error", err)
  111. return
  112. }
  113. }
  114. }
  115. func (s *session) createTerm(channel ssh.Channel) *term.Terminal {
  116. term := term.NewTerminal(channel, s.c.User()+"@nebula > ")
  117. term.AutoCompleteCallback = func(line string, pos int, key rune) (newLine string, newPos int, ok bool) {
  118. // key 9 is tab
  119. if key == 9 {
  120. cmds := s.commands.Match(line)
  121. if len(cmds) == 1 {
  122. return cmds[0] + " ", len(cmds[0]) + 1, true
  123. }
  124. sort.Strings(cmds)
  125. term.Write([]byte(strings.Join(cmds, "\n") + "\n\n"))
  126. }
  127. return "", 0, false
  128. }
  129. go s.handleInput()
  130. return term
  131. }
  132. func (s *session) handleInput() {
  133. w := commands.MergedOutput(s.term)
  134. for {
  135. line, err := s.term.ReadLine()
  136. if err != nil {
  137. break
  138. }
  139. s.dispatchCommand(line, w)
  140. }
  141. }
  142. // dispatchCommand runs line and returns the command's error, which it has logged unless
  143. // the command already told the user everything: the log line is for the operator reading
  144. // the daemon's log, who learns nothing from a failure the user caused.
  145. func (s *session) dispatchCommand(line string, w commands.Output) error {
  146. err := s.commands.Dispatch(line, w)
  147. if err == nil {
  148. return nil
  149. }
  150. var f *commands.Failure
  151. if !errors.As(err, &f) {
  152. s.l.Debug("Command returned an error", "line", line, "error", err)
  153. }
  154. return err
  155. }
  156. func (s *session) Close() {
  157. s.c.Close()
  158. s.cancel()
  159. }