server.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. package sshd
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "net"
  7. "github.com/armon/go-radix"
  8. "github.com/sirupsen/logrus"
  9. "github.com/wadey/synctrace"
  10. "golang.org/x/crypto/ssh"
  11. )
  12. type SSHServer struct {
  13. config *ssh.ServerConfig
  14. l *logrus.Entry
  15. certChecker *ssh.CertChecker
  16. // Map of user -> authorized keys
  17. trustedKeys map[string]map[string]bool
  18. trustedCAs []ssh.PublicKey
  19. // List of available commands
  20. helpCommand *Command
  21. commands *radix.Tree
  22. listener net.Listener
  23. // Locks the conns/counter to avoid concurrent map access
  24. connsLock synctrace.Mutex
  25. conns map[int]*session
  26. counter int
  27. }
  28. // NewSSHServer creates a new ssh server rigged with default commands and prepares to listen
  29. func NewSSHServer(l *logrus.Entry) (*SSHServer, error) {
  30. s := &SSHServer{
  31. trustedKeys: make(map[string]map[string]bool),
  32. l: l,
  33. commands: radix.New(),
  34. conns: make(map[int]*session),
  35. connsLock: synctrace.NewMutex("ssh-server-conns"),
  36. }
  37. cc := ssh.CertChecker{
  38. IsUserAuthority: func(auth ssh.PublicKey) bool {
  39. for _, ca := range s.trustedCAs {
  40. if bytes.Equal(ca.Marshal(), auth.Marshal()) {
  41. return true
  42. }
  43. }
  44. return false
  45. },
  46. UserKeyFallback: func(c ssh.ConnMetadata, pubKey ssh.PublicKey) (*ssh.Permissions, error) {
  47. pk := string(pubKey.Marshal())
  48. fp := ssh.FingerprintSHA256(pubKey)
  49. tk, ok := s.trustedKeys[c.User()]
  50. if !ok {
  51. return nil, fmt.Errorf("unknown user %s", c.User())
  52. }
  53. _, ok = tk[pk]
  54. if !ok {
  55. return nil, fmt.Errorf("unknown public key for %s (%s)", c.User(), fp)
  56. }
  57. return &ssh.Permissions{
  58. // Record the public key used for authentication.
  59. Extensions: map[string]string{
  60. "fp": fp,
  61. "user": c.User(),
  62. },
  63. }, nil
  64. },
  65. }
  66. s.config = &ssh.ServerConfig{
  67. PublicKeyCallback: cc.Authenticate,
  68. ServerVersion: fmt.Sprintf("SSH-2.0-Nebula???"),
  69. }
  70. s.RegisterCommand(&Command{
  71. Name: "help",
  72. ShortDescription: "prints available commands or help <command> for specific usage info",
  73. Callback: func(a any, args []string, w StringWriter) error {
  74. return helpCallback(s.commands, args, w)
  75. },
  76. })
  77. return s, nil
  78. }
  79. func (s *SSHServer) SetHostKey(hostPrivateKey []byte) error {
  80. private, err := ssh.ParsePrivateKey(hostPrivateKey)
  81. if err != nil {
  82. return fmt.Errorf("failed to parse private key: %s", err)
  83. }
  84. s.config.AddHostKey(private)
  85. return nil
  86. }
  87. func (s *SSHServer) ClearTrustedCAs() {
  88. s.trustedCAs = []ssh.PublicKey{}
  89. }
  90. func (s *SSHServer) ClearAuthorizedKeys() {
  91. s.trustedKeys = make(map[string]map[string]bool)
  92. }
  93. // AddTrustedCA adds a trusted CA for user certificates
  94. func (s *SSHServer) AddTrustedCA(pubKey string) error {
  95. pk, _, _, _, err := ssh.ParseAuthorizedKey([]byte(pubKey))
  96. if err != nil {
  97. return err
  98. }
  99. s.trustedCAs = append(s.trustedCAs, pk)
  100. s.l.WithField("sshKey", pubKey).Info("Trusted CA key")
  101. return nil
  102. }
  103. // AddAuthorizedKey adds an ssh public key for a user
  104. func (s *SSHServer) AddAuthorizedKey(user, pubKey string) error {
  105. pk, _, _, _, err := ssh.ParseAuthorizedKey([]byte(pubKey))
  106. if err != nil {
  107. return err
  108. }
  109. tk, ok := s.trustedKeys[user]
  110. if !ok {
  111. tk = make(map[string]bool)
  112. s.trustedKeys[user] = tk
  113. }
  114. tk[string(pk.Marshal())] = true
  115. s.l.WithField("sshKey", pubKey).WithField("sshUser", user).Info("Authorized ssh key")
  116. return nil
  117. }
  118. // RegisterCommand adds a command that can be run by a user, by default only `help` is available
  119. func (s *SSHServer) RegisterCommand(c *Command) {
  120. s.commands.Insert(c.Name, c)
  121. }
  122. // Run begins listening and accepting connections
  123. func (s *SSHServer) Run(addr string) error {
  124. var err error
  125. s.listener, err = net.Listen("tcp", addr)
  126. if err != nil {
  127. return err
  128. }
  129. s.l.WithField("sshListener", addr).Info("SSH server is listening")
  130. // Run loops until there is an error
  131. s.run()
  132. s.closeSessions()
  133. s.l.Info("SSH server stopped listening")
  134. // We don't return an error because run logs for us
  135. return nil
  136. }
  137. func (s *SSHServer) run() {
  138. for {
  139. c, err := s.listener.Accept()
  140. if err != nil {
  141. if !errors.Is(err, net.ErrClosed) {
  142. s.l.WithError(err).Warn("Error in listener, shutting down")
  143. }
  144. return
  145. }
  146. conn, chans, reqs, err := ssh.NewServerConn(c, s.config)
  147. fp := ""
  148. if conn != nil {
  149. fp = conn.Permissions.Extensions["fp"]
  150. }
  151. if err != nil {
  152. l := s.l.WithError(err).WithField("remoteAddress", c.RemoteAddr())
  153. if conn != nil {
  154. l = l.WithField("sshUser", conn.User())
  155. conn.Close()
  156. }
  157. if fp != "" {
  158. l = l.WithField("sshFingerprint", fp)
  159. }
  160. l.Warn("failed to handshake")
  161. continue
  162. }
  163. l := s.l.WithField("sshUser", conn.User())
  164. l.WithField("remoteAddress", c.RemoteAddr()).WithField("sshFingerprint", fp).Info("ssh user logged in")
  165. session := NewSession(s.commands, conn, chans, l.WithField("subsystem", "sshd.session"))
  166. s.connsLock.Lock()
  167. s.counter++
  168. counter := s.counter
  169. s.conns[counter] = session
  170. s.connsLock.Unlock()
  171. go ssh.DiscardRequests(reqs)
  172. go func() {
  173. <-session.exitChan
  174. s.l.WithField("id", counter).Debug("closing conn")
  175. s.connsLock.Lock()
  176. delete(s.conns, counter)
  177. s.connsLock.Unlock()
  178. }()
  179. }
  180. }
  181. func (s *SSHServer) Stop() {
  182. // Close the listener, this will cause all session to terminate as well, see SSHServer.Run
  183. if s.listener != nil {
  184. if err := s.listener.Close(); err != nil {
  185. s.l.WithError(err).Warn("Failed to close the sshd listener")
  186. }
  187. }
  188. }
  189. func (s *SSHServer) closeSessions() {
  190. s.connsLock.Lock()
  191. for _, c := range s.conns {
  192. c.Close()
  193. }
  194. s.connsLock.Unlock()
  195. }