server.go 5.4 KB

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