server.go 31 KB

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