2
0

server.go 5.4 KB

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