server.go 32 KB

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