server.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  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. // ctx parents per-Run contexts. Cancelling it (e.g. via Control.Stop) tears the server down even
  24. // across reloads, since each Run derives a fresh child rather than reusing this one directly.
  25. ctx context.Context
  26. }
  27. // NewSSHServer creates a new ssh server rigged with default commands and prepares to listen.
  28. // The ssh server's context is parented off the supplied ctx so cancelling it
  29. // (e.g. on Control.Stop) tears down active sessions and closes the listener.
  30. func NewSSHServer(ctx context.Context, l *slog.Logger) (*SSHServer, error) {
  31. s := &SSHServer{
  32. trustedKeys: make(map[string]map[string]bool),
  33. l: l,
  34. commands: radix.New(),
  35. ctx: ctx,
  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. Each invocation derives a fresh per-Run context
  126. // from the constructor-supplied ctx so a Stop+Run sequence (used by config reload) starts clean
  127. // rather than carrying a permanently-cancelled context across runs.
  128. func (s *SSHServer) Run(addr string) error {
  129. if s.ctx.Err() != nil {
  130. return s.ctx.Err()
  131. }
  132. listener, err := net.Listen("tcp", addr)
  133. if err != nil {
  134. return err
  135. }
  136. // s.listener is the public handle Stop uses to interrupt the active run; listener (the local) is what
  137. // this run owns. They start equal but a fast reload may overwrite s.listener with the next run's
  138. // listener before this run's watcher fires, so each run must close its own listener via the local
  139. // reference.
  140. s.listener = listener
  141. runCtx, cancel := context.WithCancel(s.ctx)
  142. defer cancel()
  143. // Close the listener when this run's context is cancelled. That can come from the parent
  144. // (Control.Stop), from Run returning normally (defer cancel above), or transitively when a sibling
  145. // run cancels through Stop closing the listener. net.Listener.Close is idempotent so a duplicate
  146. // close from Stop is benign.
  147. go func() {
  148. <-runCtx.Done()
  149. if err := listener.Close(); err != nil && !errors.Is(err, net.ErrClosed) {
  150. s.l.Warn("Failed to close the sshd listener", "error", err)
  151. }
  152. }()
  153. s.l.Info("SSH server is listening", "sshListener", addr)
  154. // Run loops until there is an error
  155. s.run(runCtx, listener)
  156. s.l.Info("SSH server stopped listening")
  157. // We don't return an error because run logs for us
  158. return nil
  159. }
  160. func (s *SSHServer) run(ctx context.Context, listener net.Listener) {
  161. for {
  162. c, err := listener.Accept()
  163. if err != nil {
  164. if !errors.Is(err, net.ErrClosed) {
  165. s.l.Warn("Error in listener, shutting down", "error", err)
  166. }
  167. return
  168. }
  169. go func(c net.Conn) {
  170. // NewServerConn may block while waiting for the client to complete the handshake.
  171. // Ensure that a bad client doesn't hurt us by checking for the parent context
  172. // cancellation before calling NewServerConn, and forcing the socket to close when
  173. // the context is cancelled.
  174. sessionContext, sessionCancel := context.WithCancel(ctx)
  175. go func() {
  176. <-sessionContext.Done()
  177. c.Close()
  178. }()
  179. conn, chans, reqs, err := ssh.NewServerConn(c, s.config)
  180. fp := ""
  181. if conn != nil {
  182. fp = conn.Permissions.Extensions["fp"]
  183. }
  184. if err != nil {
  185. l := s.l.With(
  186. "error", err,
  187. "remoteAddress", c.RemoteAddr(),
  188. )
  189. if conn != nil {
  190. l = l.With("sshUser", conn.User())
  191. conn.Close()
  192. }
  193. if fp != "" {
  194. l = l.With("sshFingerprint", fp)
  195. }
  196. l.Warn("failed to handshake")
  197. sessionCancel()
  198. return
  199. }
  200. l := s.l.With("sshUser", conn.User())
  201. l.Info("ssh user logged in",
  202. "remoteAddress", c.RemoteAddr(),
  203. "sshFingerprint", fp,
  204. )
  205. NewSession(s.commands, conn, chans, sessionCancel, l.With("subsystem", "sshd.session"))
  206. go ssh.DiscardRequests(reqs)
  207. }(c)
  208. }
  209. }
  210. func (s *SSHServer) Stop() {
  211. if s.listener != nil {
  212. if err := s.listener.Close(); err != nil {
  213. s.l.Warn("Failed to close the sshd listener", "error", err)
  214. }
  215. }
  216. }