server.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. package sshd
  2. import (
  3. "bytes"
  4. "context"
  5. "errors"
  6. "fmt"
  7. "log/slog"
  8. "net"
  9. "github.com/armon/go-radix"
  10. "golang.org/x/crypto/ssh"
  11. )
  12. type SSHServer struct {
  13. config *ssh.ServerConfig
  14. l *slog.Logger
  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. // Call the cancel() function to stop all active sessions
  24. ctx context.Context
  25. cancel func()
  26. }
  27. // NewSSHServer creates a new ssh server rigged with default commands and prepares to listen
  28. func NewSSHServer(l *slog.Logger) (*SSHServer, error) {
  29. ctx, cancel := context.WithCancel(context.Background())
  30. s := &SSHServer{
  31. trustedKeys: make(map[string]map[string]bool),
  32. l: l,
  33. commands: radix.New(),
  34. ctx: ctx,
  35. cancel: cancel,
  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.Info("Trusted CA key", "sshKey", pubKey)
  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.Info("Authorized ssh key",
  116. "sshKey", pubKey,
  117. "sshUser", user,
  118. )
  119. return nil
  120. }
  121. // RegisterCommand adds a command that can be run by a user, by default only `help` is available
  122. func (s *SSHServer) RegisterCommand(c *Command) {
  123. s.commands.Insert(c.Name, c)
  124. }
  125. // Run begins listening and accepting connections
  126. func (s *SSHServer) Run(addr string) error {
  127. var err error
  128. s.listener, err = net.Listen("tcp", addr)
  129. if err != nil {
  130. return err
  131. }
  132. s.l.Info("SSH server is listening", "sshListener", addr)
  133. // Run loops until there is an error
  134. s.run()
  135. s.closeSessions()
  136. s.l.Info("SSH server stopped listening")
  137. // We don't return an error because run logs for us
  138. return nil
  139. }
  140. func (s *SSHServer) run() {
  141. for {
  142. c, err := s.listener.Accept()
  143. if err != nil {
  144. if !errors.Is(err, net.ErrClosed) {
  145. s.l.Warn("Error in listener, shutting down", "error", err)
  146. }
  147. return
  148. }
  149. go func(c net.Conn) {
  150. // NewServerConn may block while waiting for the client to complete the handshake.
  151. // Ensure that a bad client doesn't hurt us by checking for the parent context
  152. // cancellation before calling NewServerConn, and forcing the socket to close when
  153. // the context is cancelled.
  154. sessionContext, sessionCancel := context.WithCancel(s.ctx)
  155. go func() {
  156. <-sessionContext.Done()
  157. c.Close()
  158. }()
  159. conn, chans, reqs, err := ssh.NewServerConn(c, s.config)
  160. fp := ""
  161. if conn != nil {
  162. fp = conn.Permissions.Extensions["fp"]
  163. }
  164. if err != nil {
  165. l := s.l.With(
  166. "error", err,
  167. "remoteAddress", c.RemoteAddr(),
  168. )
  169. if conn != nil {
  170. l = l.With("sshUser", conn.User())
  171. conn.Close()
  172. }
  173. if fp != "" {
  174. l = l.With("sshFingerprint", fp)
  175. }
  176. l.Warn("failed to handshake")
  177. sessionCancel()
  178. return
  179. }
  180. l := s.l.With("sshUser", conn.User())
  181. l.Info("ssh user logged in",
  182. "remoteAddress", c.RemoteAddr(),
  183. "sshFingerprint", fp,
  184. )
  185. NewSession(s.commands, conn, chans, sessionCancel, l.With("subsystem", "sshd.session"))
  186. go ssh.DiscardRequests(reqs)
  187. }(c)
  188. }
  189. }
  190. func (s *SSHServer) Stop() {
  191. // Close the listener, this will cause all session to terminate as well, see SSHServer.Run
  192. if s.listener != nil {
  193. if err := s.listener.Close(); err != nil {
  194. s.l.Warn("Failed to close the sshd listener", "error", err)
  195. }
  196. }
  197. }
  198. func (s *SSHServer) closeSessions() {
  199. s.cancel()
  200. }