server.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715
  1. package sftpd
  2. import (
  3. "bytes"
  4. "encoding/hex"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "io"
  9. "io/ioutil"
  10. "net"
  11. "os"
  12. "path/filepath"
  13. "strings"
  14. "time"
  15. "github.com/pkg/sftp"
  16. "golang.org/x/crypto/ssh"
  17. "github.com/drakkan/sftpgo/common"
  18. "github.com/drakkan/sftpgo/dataprovider"
  19. "github.com/drakkan/sftpgo/logger"
  20. "github.com/drakkan/sftpgo/metrics"
  21. "github.com/drakkan/sftpgo/utils"
  22. )
  23. const (
  24. defaultPrivateRSAKeyName = "id_rsa"
  25. defaultPrivateECDSAKeyName = "id_ecdsa"
  26. defaultPrivateEd25519KeyName = "id_ed25519"
  27. sourceAddressCriticalOption = "source-address"
  28. )
  29. var (
  30. sftpExtensions = []string{"posix-rename@openssh.com"}
  31. )
  32. // Configuration for the SFTP server
  33. type Configuration struct {
  34. // Identification string used by the server
  35. Banner string `json:"banner" mapstructure:"banner"`
  36. // The port used for serving SFTP requests
  37. BindPort int `json:"bind_port" mapstructure:"bind_port"`
  38. // The address to listen on. A blank value means listen on all available network interfaces.
  39. BindAddress string `json:"bind_address" mapstructure:"bind_address"`
  40. // Deprecated: please use the same key in common configuration
  41. IdleTimeout int `json:"idle_timeout" mapstructure:"idle_timeout"`
  42. // Maximum number of authentication attempts permitted per connection.
  43. // If set to a negative number, the number of attempts is unlimited.
  44. // If set to zero, the number of attempts are limited to 6.
  45. MaxAuthTries int `json:"max_auth_tries" mapstructure:"max_auth_tries"`
  46. // Deprecated: please use the same key in common configuration
  47. UploadMode int `json:"upload_mode" mapstructure:"upload_mode"`
  48. // Actions to execute on file operations and SSH commands
  49. Actions common.ProtocolActions `json:"actions" mapstructure:"actions"`
  50. // Deprecated: please use HostKeys
  51. Keys []Key `json:"keys" mapstructure:"keys"`
  52. // HostKeys define the daemon's private host keys.
  53. // Each host key can be defined as a path relative to the configuration directory or an absolute one.
  54. // If empty or missing, the daemon will search or try to generate "id_rsa" and "id_ecdsa" host keys
  55. // inside the configuration directory.
  56. HostKeys []string `json:"host_keys" mapstructure:"host_keys"`
  57. // KexAlgorithms specifies the available KEX (Key Exchange) algorithms in
  58. // preference order.
  59. KexAlgorithms []string `json:"kex_algorithms" mapstructure:"kex_algorithms"`
  60. // Ciphers specifies the ciphers allowed
  61. Ciphers []string `json:"ciphers" mapstructure:"ciphers"`
  62. // MACs Specifies the available MAC (message authentication code) algorithms
  63. // in preference order
  64. MACs []string `json:"macs" mapstructure:"macs"`
  65. // TrustedUserCAKeys specifies a list of public keys paths of certificate authorities
  66. // that are trusted to sign user certificates for authentication.
  67. // The paths can be absolute or relative to the configuration directory
  68. TrustedUserCAKeys []string `json:"trusted_user_ca_keys" mapstructure:"trusted_user_ca_keys"`
  69. // LoginBannerFile the contents of the specified file, if any, are sent to
  70. // the remote user before authentication is allowed.
  71. LoginBannerFile string `json:"login_banner_file" mapstructure:"login_banner_file"`
  72. // Deprecated: please use the same key in common configuration
  73. SetstatMode int `json:"setstat_mode" mapstructure:"setstat_mode"`
  74. // List of enabled SSH commands.
  75. // We support the following SSH commands:
  76. // - "scp". SCP is an experimental feature, we have our own SCP implementation since
  77. // we can't rely on scp system command to proper handle permissions, quota and
  78. // user's home dir restrictions.
  79. // The SCP protocol is quite simple but there is no official docs about it,
  80. // so we need more testing and feedbacks before enabling it by default.
  81. // We may not handle some borderline cases or have sneaky bugs.
  82. // Please do accurate tests yourself before enabling SCP and let us known
  83. // if something does not work as expected for your use cases.
  84. // SCP between two remote hosts is supported using the `-3` scp option.
  85. // - "md5sum", "sha1sum", "sha256sum", "sha384sum", "sha512sum". Useful to check message
  86. // digests for uploaded files. These commands are implemented inside SFTPGo so they
  87. // work even if the matching system commands are not available, for example on Windows.
  88. // - "cd", "pwd". Some mobile SFTP clients does not support the SFTP SSH_FXP_REALPATH and so
  89. // they use "cd" and "pwd" SSH commands to get the initial directory.
  90. // Currently `cd` do nothing and `pwd` always returns the "/" path.
  91. //
  92. // The following SSH commands are enabled by default: "md5sum", "sha1sum", "cd", "pwd".
  93. // "*" enables all supported SSH commands.
  94. EnabledSSHCommands []string `json:"enabled_ssh_commands" mapstructure:"enabled_ssh_commands"`
  95. // Absolute path to an external program or an HTTP URL to invoke for keyboard interactive authentication.
  96. // Leave empty to disable this authentication mode.
  97. KeyboardInteractiveHook string `json:"keyboard_interactive_auth_hook" mapstructure:"keyboard_interactive_auth_hook"`
  98. // PasswordAuthentication specifies whether password authentication is allowed.
  99. PasswordAuthentication bool `json:"password_authentication" mapstructure:"password_authentication"`
  100. // Deprecated: please use the same key in common configuration
  101. ProxyProtocol int `json:"proxy_protocol" mapstructure:"proxy_protocol"`
  102. // Deprecated: please use the same key in common configuration
  103. ProxyAllowed []string `json:"proxy_allowed" mapstructure:"proxy_allowed"`
  104. certChecker *ssh.CertChecker
  105. parsedUserCAKeys []ssh.PublicKey
  106. }
  107. // Key contains information about host keys
  108. // Deprecated: please use HostKeys
  109. type Key struct {
  110. // The private key path as absolute path or relative to the configuration directory
  111. PrivateKey string `json:"private_key" mapstructure:"private_key"`
  112. }
  113. type authenticationError struct {
  114. err string
  115. }
  116. func (e *authenticationError) Error() string {
  117. return fmt.Sprintf("Authentication error: %s", e.err)
  118. }
  119. // Initialize the SFTP server and add a persistent listener to handle inbound SFTP connections.
  120. func (c Configuration) Initialize(configDir string) error {
  121. serverConfig := &ssh.ServerConfig{
  122. NoClientAuth: false,
  123. MaxAuthTries: c.MaxAuthTries,
  124. PublicKeyCallback: func(conn ssh.ConnMetadata, pubKey ssh.PublicKey) (*ssh.Permissions, error) {
  125. sp, err := c.validatePublicKeyCredentials(conn, pubKey)
  126. if err == ssh.ErrPartialSuccess {
  127. return sp, err
  128. }
  129. if err != nil {
  130. return nil, &authenticationError{err: fmt.Sprintf("could not validate public key credentials: %v", err)}
  131. }
  132. return sp, nil
  133. },
  134. NextAuthMethodsCallback: func(conn ssh.ConnMetadata) []string {
  135. var nextMethods []string
  136. user, err := dataprovider.UserExists(conn.User())
  137. if err == nil {
  138. nextMethods = user.GetNextAuthMethods(conn.PartialSuccessMethods(), c.PasswordAuthentication)
  139. }
  140. return nextMethods
  141. },
  142. ServerVersion: fmt.Sprintf("SSH-2.0-%v", c.Banner),
  143. }
  144. if c.PasswordAuthentication {
  145. serverConfig.PasswordCallback = func(conn ssh.ConnMetadata, pass []byte) (*ssh.Permissions, error) {
  146. sp, err := c.validatePasswordCredentials(conn, pass)
  147. if err != nil {
  148. return nil, &authenticationError{err: fmt.Sprintf("could not validate password credentials: %v", err)}
  149. }
  150. return sp, nil
  151. }
  152. }
  153. if err := c.checkAndLoadHostKeys(configDir, serverConfig); err != nil {
  154. return err
  155. }
  156. if err := c.initializeCertChecker(configDir); err != nil {
  157. return err
  158. }
  159. sftp.SetSFTPExtensions(sftpExtensions...) //nolint:errcheck // we configure valid SFTP Extensions so we cannot get an error
  160. c.configureSecurityOptions(serverConfig)
  161. c.configureKeyboardInteractiveAuth(serverConfig)
  162. c.configureLoginBanner(serverConfig, configDir)
  163. c.checkSSHCommands()
  164. listener, err := net.Listen("tcp", fmt.Sprintf("%s:%d", c.BindAddress, c.BindPort))
  165. if err != nil {
  166. logger.Warn(logSender, "", "error starting listener on address %s:%d: %v", c.BindAddress, c.BindPort, err)
  167. return err
  168. }
  169. proxyListener, err := common.Config.GetProxyListener(listener)
  170. if err != nil {
  171. logger.Warn(logSender, "", "error enabling proxy listener: %v", err)
  172. return err
  173. }
  174. logger.Info(logSender, "", "server listener registered address: %v", listener.Addr().String())
  175. for {
  176. var conn net.Conn
  177. if proxyListener != nil {
  178. conn, err = proxyListener.Accept()
  179. } else {
  180. conn, err = listener.Accept()
  181. }
  182. if conn != nil && err == nil {
  183. go c.AcceptInboundConnection(conn, serverConfig)
  184. }
  185. }
  186. }
  187. func (c Configuration) configureSecurityOptions(serverConfig *ssh.ServerConfig) {
  188. if len(c.KexAlgorithms) > 0 {
  189. serverConfig.KeyExchanges = c.KexAlgorithms
  190. }
  191. if len(c.Ciphers) > 0 {
  192. serverConfig.Ciphers = c.Ciphers
  193. }
  194. if len(c.MACs) > 0 {
  195. serverConfig.MACs = c.MACs
  196. }
  197. }
  198. func (c Configuration) configureLoginBanner(serverConfig *ssh.ServerConfig, configDir string) {
  199. if len(c.LoginBannerFile) > 0 {
  200. bannerFilePath := c.LoginBannerFile
  201. if !filepath.IsAbs(bannerFilePath) {
  202. bannerFilePath = filepath.Join(configDir, bannerFilePath)
  203. }
  204. bannerContent, err := ioutil.ReadFile(bannerFilePath)
  205. if err == nil {
  206. banner := string(bannerContent)
  207. serverConfig.BannerCallback = func(conn ssh.ConnMetadata) string {
  208. return banner
  209. }
  210. } else {
  211. logger.WarnToConsole("unable to read SFTPD login banner file: %v", err)
  212. logger.Warn(logSender, "", "unable to read login banner file: %v", err)
  213. }
  214. }
  215. }
  216. func (c Configuration) configureKeyboardInteractiveAuth(serverConfig *ssh.ServerConfig) {
  217. if len(c.KeyboardInteractiveHook) == 0 {
  218. return
  219. }
  220. if !strings.HasPrefix(c.KeyboardInteractiveHook, "http") {
  221. if !filepath.IsAbs(c.KeyboardInteractiveHook) {
  222. logger.WarnToConsole("invalid keyboard interactive authentication program: %#v must be an absolute path",
  223. c.KeyboardInteractiveHook)
  224. logger.Warn(logSender, "", "invalid keyboard interactive authentication program: %#v must be an absolute path",
  225. c.KeyboardInteractiveHook)
  226. return
  227. }
  228. _, err := os.Stat(c.KeyboardInteractiveHook)
  229. if err != nil {
  230. logger.WarnToConsole("invalid keyboard interactive authentication program:: %v", err)
  231. logger.Warn(logSender, "", "invalid keyboard interactive authentication program:: %v", err)
  232. return
  233. }
  234. }
  235. serverConfig.KeyboardInteractiveCallback = func(conn ssh.ConnMetadata, client ssh.KeyboardInteractiveChallenge) (*ssh.Permissions, error) {
  236. sp, err := c.validateKeyboardInteractiveCredentials(conn, client)
  237. if err != nil {
  238. return nil, &authenticationError{err: fmt.Sprintf("could not validate keyboard interactive credentials: %v", err)}
  239. }
  240. return sp, nil
  241. }
  242. }
  243. // AcceptInboundConnection handles an inbound connection to the server instance and determines if the request should be served or not.
  244. func (c Configuration) AcceptInboundConnection(conn net.Conn, config *ssh.ServerConfig) {
  245. // Before beginning a handshake must be performed on the incoming net.Conn
  246. // we'll set a Deadline for handshake to complete, the default is 2 minutes as OpenSSH
  247. conn.SetDeadline(time.Now().Add(handshakeTimeout)) //nolint:errcheck
  248. remoteAddr := conn.RemoteAddr()
  249. if err := common.Config.ExecutePostConnectHook(remoteAddr.String(), common.ProtocolSSH); err != nil {
  250. conn.Close()
  251. return
  252. }
  253. sconn, chans, reqs, err := ssh.NewServerConn(conn, config)
  254. if err != nil {
  255. logger.Debug(logSender, "", "failed to accept an incoming connection: %v", err)
  256. if _, ok := err.(*ssh.ServerAuthError); !ok {
  257. ip := utils.GetIPFromRemoteAddress(remoteAddr.String())
  258. logger.ConnectionFailedLog("", ip, dataprovider.LoginMethodNoAuthTryed, common.ProtocolSSH, err.Error())
  259. metrics.AddNoAuthTryed()
  260. dataprovider.ExecutePostLoginHook("", dataprovider.LoginMethodNoAuthTryed, ip, common.ProtocolSSH, err)
  261. }
  262. return
  263. }
  264. // handshake completed so remove the deadline, we'll use IdleTimeout configuration from now on
  265. conn.SetDeadline(time.Time{}) //nolint:errcheck
  266. defer conn.Close()
  267. var user dataprovider.User
  268. // Unmarshal cannot fails here and even if it fails we'll have a user with no permissions
  269. json.Unmarshal([]byte(sconn.Permissions.Extensions["sftpgo_user"]), &user) //nolint:errcheck
  270. loginType := sconn.Permissions.Extensions["sftpgo_login_method"]
  271. connectionID := hex.EncodeToString(sconn.SessionID())
  272. fs, err := user.GetFilesystem(connectionID)
  273. if err != nil {
  274. logger.Warn(logSender, "", "could create filesystem for user %#v err: %v", user.Username, err)
  275. return
  276. }
  277. fs.CheckRootPath(user.Username, user.GetUID(), user.GetGID())
  278. logger.Log(logger.LevelInfo, common.ProtocolSSH, connectionID,
  279. "User id: %d, logged in with: %#v, username: %#v, home_dir: %#v remote addr: %#v",
  280. user.ID, loginType, user.Username, user.HomeDir, remoteAddr.String())
  281. dataprovider.UpdateLastLogin(user) //nolint:errcheck
  282. sshConnection := common.NewSSHConnection(connectionID, conn)
  283. common.Connections.AddSSHConnection(sshConnection)
  284. defer common.Connections.RemoveSSHConnection(connectionID)
  285. go ssh.DiscardRequests(reqs)
  286. channelCounter := int64(0)
  287. for newChannel := range chans {
  288. // If its not a session channel we just move on because its not something we
  289. // know how to handle at this point.
  290. if newChannel.ChannelType() != "session" {
  291. logger.Log(logger.LevelDebug, common.ProtocolSSH, connectionID, "received an unknown channel type: %v",
  292. newChannel.ChannelType())
  293. newChannel.Reject(ssh.UnknownChannelType, "unknown channel type") //nolint:errcheck
  294. continue
  295. }
  296. channel, requests, err := newChannel.Accept()
  297. if err != nil {
  298. logger.Log(logger.LevelWarn, common.ProtocolSSH, connectionID, "could not accept a channel: %v", err)
  299. continue
  300. }
  301. channelCounter++
  302. sshConnection.UpdateLastActivity()
  303. // Channels have a type that is dependent on the protocol. For SFTP this is "subsystem"
  304. // with a payload that (should) be "sftp". Discard anything else we receive ("pty", "shell", etc)
  305. go func(in <-chan *ssh.Request, counter int64) {
  306. for req := range in {
  307. ok := false
  308. connID := fmt.Sprintf("%v_%v", connectionID, counter)
  309. switch req.Type {
  310. case "subsystem":
  311. if string(req.Payload[4:]) == "sftp" {
  312. ok = true
  313. connection := Connection{
  314. BaseConnection: common.NewBaseConnection(connID, common.ProtocolSFTP, user, fs),
  315. ClientVersion: string(sconn.ClientVersion()),
  316. RemoteAddr: remoteAddr,
  317. channel: channel,
  318. }
  319. go c.handleSftpConnection(channel, &connection)
  320. }
  321. case "exec":
  322. // protocol will be set later inside processSSHCommand it could be SSH or SCP
  323. connection := Connection{
  324. BaseConnection: common.NewBaseConnection(connID, "sshd_exec", user, fs),
  325. ClientVersion: string(sconn.ClientVersion()),
  326. RemoteAddr: remoteAddr,
  327. channel: channel,
  328. }
  329. ok = processSSHCommand(req.Payload, &connection, c.EnabledSSHCommands)
  330. }
  331. req.Reply(ok, nil) //nolint:errcheck
  332. }
  333. }(requests, channelCounter)
  334. }
  335. }
  336. func (c Configuration) handleSftpConnection(channel ssh.Channel, connection *Connection) {
  337. common.Connections.Add(connection)
  338. defer common.Connections.Remove(connection.GetID())
  339. // Create a new handler for the currently logged in user's server.
  340. handler := c.createHandler(connection)
  341. // Create the server instance for the channel using the handler we created above.
  342. server := sftp.NewRequestServer(channel, handler, sftp.WithRSAllocator())
  343. if err := server.Serve(); err == io.EOF {
  344. connection.Log(logger.LevelDebug, "connection closed, sending exit status")
  345. exitStatus := sshSubsystemExitStatus{Status: uint32(0)}
  346. _, err = channel.SendRequest("exit-status", false, ssh.Marshal(&exitStatus))
  347. connection.Log(logger.LevelDebug, "sent exit status %+v error: %v", exitStatus, err)
  348. server.Close()
  349. } else if err != nil {
  350. connection.Log(logger.LevelWarn, "connection closed with error: %v", err)
  351. }
  352. }
  353. func (c Configuration) createHandler(connection *Connection) sftp.Handlers {
  354. return sftp.Handlers{
  355. FileGet: connection,
  356. FilePut: connection,
  357. FileCmd: connection,
  358. FileList: connection,
  359. }
  360. }
  361. func loginUser(user dataprovider.User, loginMethod, publicKey string, conn ssh.ConnMetadata) (*ssh.Permissions, error) {
  362. connectionID := ""
  363. if conn != nil {
  364. connectionID = hex.EncodeToString(conn.SessionID())
  365. }
  366. if !filepath.IsAbs(user.HomeDir) {
  367. logger.Warn(logSender, connectionID, "user %#v has an invalid home dir: %#v. Home dir must be an absolute path, login not allowed",
  368. user.Username, user.HomeDir)
  369. return nil, fmt.Errorf("cannot login user with invalid home dir: %#v", user.HomeDir)
  370. }
  371. if utils.IsStringInSlice(common.ProtocolSSH, user.Filters.DeniedProtocols) {
  372. logger.Debug(logSender, connectionID, "cannot login user %#v, protocol SSH is not allowed", user.Username)
  373. return nil, fmt.Errorf("Protocol SSH is not allowed for user %#v", user.Username)
  374. }
  375. if user.MaxSessions > 0 {
  376. activeSessions := common.Connections.GetActiveSessions(user.Username)
  377. if activeSessions >= user.MaxSessions {
  378. logger.Debug(logSender, "", "authentication refused for user: %#v, too many open sessions: %v/%v", user.Username,
  379. activeSessions, user.MaxSessions)
  380. return nil, fmt.Errorf("too many open sessions: %v", activeSessions)
  381. }
  382. }
  383. if !user.IsLoginMethodAllowed(loginMethod, conn.PartialSuccessMethods()) {
  384. logger.Debug(logSender, connectionID, "cannot login user %#v, login method %#v is not allowed", user.Username, loginMethod)
  385. return nil, fmt.Errorf("Login method %#v is not allowed for user %#v", loginMethod, user.Username)
  386. }
  387. if dataprovider.GetQuotaTracking() > 0 && user.HasOverlappedMappedPaths() {
  388. logger.Debug(logSender, connectionID, "cannot login user %#v, overlapping mapped folders are allowed only with quota tracking disabled",
  389. user.Username)
  390. return nil, errors.New("overlapping mapped folders are allowed only with quota tracking disabled")
  391. }
  392. remoteAddr := conn.RemoteAddr().String()
  393. if !user.IsLoginFromAddrAllowed(remoteAddr) {
  394. logger.Debug(logSender, connectionID, "cannot login user %#v, remote address is not allowed: %v", user.Username, remoteAddr)
  395. return nil, fmt.Errorf("Login for user %#v is not allowed from this address: %v", user.Username, remoteAddr)
  396. }
  397. json, err := json.Marshal(user)
  398. if err != nil {
  399. logger.Warn(logSender, connectionID, "error serializing user info: %v, authentication rejected", err)
  400. return nil, err
  401. }
  402. if len(publicKey) > 0 {
  403. loginMethod = fmt.Sprintf("%v: %v", loginMethod, publicKey)
  404. }
  405. p := &ssh.Permissions{}
  406. p.Extensions = make(map[string]string)
  407. p.Extensions["sftpgo_user"] = string(json)
  408. p.Extensions["sftpgo_login_method"] = loginMethod
  409. return p, nil
  410. }
  411. func (c *Configuration) checkSSHCommands() {
  412. if utils.IsStringInSlice("*", c.EnabledSSHCommands) {
  413. c.EnabledSSHCommands = GetSupportedSSHCommands()
  414. return
  415. }
  416. sshCommands := []string{}
  417. for _, command := range c.EnabledSSHCommands {
  418. if utils.IsStringInSlice(command, supportedSSHCommands) {
  419. sshCommands = append(sshCommands, command)
  420. } else {
  421. logger.Warn(logSender, "", "unsupported ssh command: %#v ignored", command)
  422. logger.WarnToConsole("unsupported ssh command: %#v ignored", command)
  423. }
  424. }
  425. c.EnabledSSHCommands = sshCommands
  426. }
  427. func (c *Configuration) generateDefaultHostKeys(configDir string) error {
  428. var err error
  429. defaultHostKeys := []string{defaultPrivateRSAKeyName, defaultPrivateECDSAKeyName, defaultPrivateEd25519KeyName}
  430. for _, k := range defaultHostKeys {
  431. autoFile := filepath.Join(configDir, k)
  432. if _, err = os.Stat(autoFile); os.IsNotExist(err) {
  433. logger.Info(logSender, "", "No host keys configured and %#v does not exist; try to create a new host key", autoFile)
  434. logger.InfoToConsole("No host keys configured and %#v does not exist; try to create a new host key", autoFile)
  435. if k == defaultPrivateRSAKeyName {
  436. err = utils.GenerateRSAKeys(autoFile)
  437. } else if k == defaultPrivateECDSAKeyName {
  438. err = utils.GenerateECDSAKeys(autoFile)
  439. } else {
  440. err = utils.GenerateEd25519Keys(autoFile)
  441. }
  442. if err != nil {
  443. logger.Warn(logSender, "", "error creating host key %#v: %v", autoFile, err)
  444. logger.WarnToConsole("error creating host key %#v: %v", autoFile, err)
  445. return err
  446. }
  447. }
  448. c.HostKeys = append(c.HostKeys, k)
  449. }
  450. return err
  451. }
  452. func (c *Configuration) checkHostKeyAutoGeneration(configDir string) error {
  453. for _, k := range c.HostKeys {
  454. if filepath.IsAbs(k) {
  455. if _, err := os.Stat(k); os.IsNotExist(err) {
  456. keyName := filepath.Base(k)
  457. switch keyName {
  458. case defaultPrivateRSAKeyName:
  459. logger.Info(logSender, "", "try to create non-existent host key %#v", k)
  460. logger.InfoToConsole("try to create non-existent host key %#v", k)
  461. err = utils.GenerateRSAKeys(k)
  462. if err != nil {
  463. logger.Warn(logSender, "", "error creating host key %#v: %v", k, err)
  464. logger.WarnToConsole("error creating host key %#v: %v", k, err)
  465. return err
  466. }
  467. case defaultPrivateECDSAKeyName:
  468. logger.Info(logSender, "", "try to create non-existent host key %#v", k)
  469. logger.InfoToConsole("try to create non-existent host key %#v", k)
  470. err = utils.GenerateECDSAKeys(k)
  471. if err != nil {
  472. logger.Warn(logSender, "", "error creating host key %#v: %v", k, err)
  473. logger.WarnToConsole("error creating host key %#v: %v", k, err)
  474. return err
  475. }
  476. case defaultPrivateEd25519KeyName:
  477. logger.Info(logSender, "", "try to create non-existent host key %#v", k)
  478. logger.InfoToConsole("try to create non-existent host key %#v", k)
  479. err = utils.GenerateEd25519Keys(k)
  480. if err != nil {
  481. logger.Warn(logSender, "", "error creating host key %#v: %v", k, err)
  482. logger.WarnToConsole("error creating host key %#v: %v", k, err)
  483. return err
  484. }
  485. default:
  486. logger.Warn(logSender, "", "non-existent host key %#v will not be created", k)
  487. logger.WarnToConsole("non-existent host key %#v will not be created", k)
  488. }
  489. }
  490. }
  491. }
  492. if len(c.HostKeys) == 0 {
  493. if err := c.generateDefaultHostKeys(configDir); err != nil {
  494. return err
  495. }
  496. }
  497. return nil
  498. }
  499. // If no host keys are defined we try to use or generate the default ones.
  500. func (c *Configuration) checkAndLoadHostKeys(configDir string, serverConfig *ssh.ServerConfig) error {
  501. if err := c.checkHostKeyAutoGeneration(configDir); err != nil {
  502. return err
  503. }
  504. for _, k := range c.HostKeys {
  505. hostKey := k
  506. if !utils.IsFileInputValid(hostKey) {
  507. logger.Warn(logSender, "", "unable to load invalid host key: %#v", hostKey)
  508. logger.WarnToConsole("unable to load invalid host key: %#v", hostKey)
  509. continue
  510. }
  511. if !filepath.IsAbs(hostKey) {
  512. hostKey = filepath.Join(configDir, hostKey)
  513. }
  514. logger.Info(logSender, "", "Loading private host key: %s", hostKey)
  515. privateBytes, err := ioutil.ReadFile(hostKey)
  516. if err != nil {
  517. return err
  518. }
  519. private, err := ssh.ParsePrivateKey(privateBytes)
  520. if err != nil {
  521. return err
  522. }
  523. // Add private key to the server configuration.
  524. serverConfig.AddHostKey(private)
  525. }
  526. return nil
  527. }
  528. func (c *Configuration) initializeCertChecker(configDir string) error {
  529. for _, keyPath := range c.TrustedUserCAKeys {
  530. if !utils.IsFileInputValid(keyPath) {
  531. logger.Warn(logSender, "", "unable to load invalid trusted user CA key: %#v", keyPath)
  532. logger.WarnToConsole("unable to load invalid trusted user CA key: %#v", keyPath)
  533. continue
  534. }
  535. if !filepath.IsAbs(keyPath) {
  536. keyPath = filepath.Join(configDir, keyPath)
  537. }
  538. keyBytes, err := ioutil.ReadFile(keyPath)
  539. if err != nil {
  540. logger.Warn(logSender, "", "error loading trusted user CA key %#v: %v", keyPath, err)
  541. logger.WarnToConsole("error loading trusted user CA key %#v: %v", keyPath, err)
  542. return err
  543. }
  544. parsedKey, _, _, _, err := ssh.ParseAuthorizedKey(keyBytes)
  545. if err != nil {
  546. logger.Warn(logSender, "", "error parsing trusted user CA key %#v: %v", keyPath, err)
  547. logger.WarnToConsole("error parsing trusted user CA key %#v: %v", keyPath, err)
  548. return err
  549. }
  550. c.parsedUserCAKeys = append(c.parsedUserCAKeys, parsedKey)
  551. }
  552. c.certChecker = &ssh.CertChecker{
  553. SupportedCriticalOptions: []string{
  554. sourceAddressCriticalOption,
  555. },
  556. IsUserAuthority: func(k ssh.PublicKey) bool {
  557. for _, key := range c.parsedUserCAKeys {
  558. if bytes.Equal(k.Marshal(), key.Marshal()) {
  559. return true
  560. }
  561. }
  562. return false
  563. },
  564. }
  565. return nil
  566. }
  567. func (c Configuration) validatePublicKeyCredentials(conn ssh.ConnMetadata, pubKey ssh.PublicKey) (*ssh.Permissions, error) {
  568. var err error
  569. var user dataprovider.User
  570. var keyID string
  571. var sshPerm *ssh.Permissions
  572. var certPerm *ssh.Permissions
  573. connectionID := hex.EncodeToString(conn.SessionID())
  574. method := dataprovider.SSHLoginMethodPublicKey
  575. cert, ok := pubKey.(*ssh.Certificate)
  576. if ok {
  577. if cert.CertType != ssh.UserCert {
  578. err = fmt.Errorf("ssh: cert has type %d", cert.CertType)
  579. updateLoginMetrics(conn, method, err)
  580. return nil, err
  581. }
  582. if !c.certChecker.IsUserAuthority(cert.SignatureKey) {
  583. err = fmt.Errorf("ssh: certificate signed by unrecognized authority")
  584. updateLoginMetrics(conn, method, err)
  585. return nil, err
  586. }
  587. if err := c.certChecker.CheckCert(conn.User(), cert); err != nil {
  588. updateLoginMetrics(conn, method, err)
  589. return nil, err
  590. }
  591. certPerm = &cert.Permissions
  592. }
  593. ipAddr := utils.GetIPFromRemoteAddress(conn.RemoteAddr().String())
  594. if user, keyID, err = dataprovider.CheckUserAndPubKey(conn.User(), pubKey.Marshal(), ipAddr, common.ProtocolSSH); err == nil {
  595. if user.IsPartialAuth(method) {
  596. logger.Debug(logSender, connectionID, "user %#v authenticated with partial success", conn.User())
  597. return certPerm, ssh.ErrPartialSuccess
  598. }
  599. sshPerm, err = loginUser(user, method, keyID, conn)
  600. if err == nil && certPerm != nil {
  601. // if we have a SSH user cert we need to merge certificate permissions with our ones
  602. // we only set Extensions, so CriticalOptions are always the ones from the certificate
  603. sshPerm.CriticalOptions = certPerm.CriticalOptions
  604. if certPerm.Extensions != nil {
  605. for k, v := range certPerm.Extensions {
  606. sshPerm.Extensions[k] = v
  607. }
  608. }
  609. }
  610. }
  611. updateLoginMetrics(conn, method, err)
  612. return sshPerm, err
  613. }
  614. func (c Configuration) validatePasswordCredentials(conn ssh.ConnMetadata, pass []byte) (*ssh.Permissions, error) {
  615. var err error
  616. var user dataprovider.User
  617. var sshPerm *ssh.Permissions
  618. method := dataprovider.LoginMethodPassword
  619. if len(conn.PartialSuccessMethods()) == 1 {
  620. method = dataprovider.SSHLoginMethodKeyAndPassword
  621. }
  622. ipAddr := utils.GetIPFromRemoteAddress(conn.RemoteAddr().String())
  623. if user, err = dataprovider.CheckUserAndPass(conn.User(), string(pass), ipAddr, common.ProtocolSSH); err == nil {
  624. sshPerm, err = loginUser(user, method, "", conn)
  625. }
  626. updateLoginMetrics(conn, method, err)
  627. return sshPerm, err
  628. }
  629. func (c Configuration) validateKeyboardInteractiveCredentials(conn ssh.ConnMetadata, client ssh.KeyboardInteractiveChallenge) (*ssh.Permissions, error) {
  630. var err error
  631. var user dataprovider.User
  632. var sshPerm *ssh.Permissions
  633. method := dataprovider.SSHLoginMethodKeyboardInteractive
  634. if len(conn.PartialSuccessMethods()) == 1 {
  635. method = dataprovider.SSHLoginMethodKeyAndKeyboardInt
  636. }
  637. ipAddr := utils.GetIPFromRemoteAddress(conn.RemoteAddr().String())
  638. if user, err = dataprovider.CheckKeyboardInteractiveAuth(conn.User(), c.KeyboardInteractiveHook, client,
  639. ipAddr, common.ProtocolSSH); err == nil {
  640. sshPerm, err = loginUser(user, method, "", conn)
  641. }
  642. updateLoginMetrics(conn, method, err)
  643. return sshPerm, err
  644. }
  645. func updateLoginMetrics(conn ssh.ConnMetadata, method string, err error) {
  646. metrics.AddLoginAttempt(method)
  647. ip := utils.GetIPFromRemoteAddress(conn.RemoteAddr().String())
  648. if err != nil {
  649. logger.ConnectionFailedLog(conn.User(), ip, method, common.ProtocolSSH, err.Error())
  650. }
  651. metrics.AddLoginResult(method, err)
  652. dataprovider.ExecutePostLoginHook(conn.User(), method, ip, common.ProtocolSSH, err)
  653. }