server.go 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879
  1. package sftpd
  2. import (
  3. "bytes"
  4. "encoding/hex"
  5. "encoding/json"
  6. "fmt"
  7. "io"
  8. "net"
  9. "os"
  10. "path/filepath"
  11. "runtime/debug"
  12. "strings"
  13. "time"
  14. "github.com/pkg/sftp"
  15. "golang.org/x/crypto/ssh"
  16. "github.com/drakkan/sftpgo/common"
  17. "github.com/drakkan/sftpgo/dataprovider"
  18. "github.com/drakkan/sftpgo/logger"
  19. "github.com/drakkan/sftpgo/metrics"
  20. "github.com/drakkan/sftpgo/utils"
  21. "github.com/drakkan/sftpgo/vfs"
  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{"[email protected]"}
  31. )
  32. // Binding defines the configuration for a network listener
  33. type Binding struct {
  34. // The address to listen on. A blank value means listen on all available network interfaces.
  35. Address string `json:"address" mapstructure:"address"`
  36. // The port used for serving requests
  37. Port int `json:"port" mapstructure:"port"`
  38. // Apply the proxy configuration, if any, for this binding
  39. ApplyProxyConfig bool `json:"apply_proxy_config" mapstructure:"apply_proxy_config"`
  40. }
  41. // GetAddress returns the binding address
  42. func (b *Binding) GetAddress() string {
  43. return fmt.Sprintf("%s:%d", b.Address, b.Port)
  44. }
  45. // IsValid returns true if the binding port is > 0
  46. func (b *Binding) IsValid() bool {
  47. return b.Port > 0
  48. }
  49. // HasProxy returns true if the proxy protocol is active for this binding
  50. func (b *Binding) HasProxy() bool {
  51. return b.ApplyProxyConfig && common.Config.ProxyProtocol > 0
  52. }
  53. // Configuration for the SFTP server
  54. type Configuration struct {
  55. // Identification string used by the server
  56. Banner string `json:"banner" mapstructure:"banner"`
  57. // Addresses and ports to bind to
  58. Bindings []Binding `json:"bindings" mapstructure:"bindings"`
  59. // Deprecated: please use Bindings
  60. BindPort int `json:"bind_port" mapstructure:"bind_port"`
  61. // Deprecated: please use Bindings
  62. BindAddress string `json:"bind_address" mapstructure:"bind_address"`
  63. // Deprecated: please use the same key in common configuration
  64. IdleTimeout int `json:"idle_timeout" mapstructure:"idle_timeout"`
  65. // Maximum number of authentication attempts permitted per connection.
  66. // If set to a negative number, the number of attempts is unlimited.
  67. // If set to zero, the number of attempts are limited to 6.
  68. MaxAuthTries int `json:"max_auth_tries" mapstructure:"max_auth_tries"`
  69. // Deprecated: please use the same key in common configuration
  70. UploadMode int `json:"upload_mode" mapstructure:"upload_mode"`
  71. // Actions to execute on file operations and SSH commands
  72. Actions common.ProtocolActions `json:"actions" mapstructure:"actions"`
  73. // Deprecated: please use HostKeys
  74. Keys []Key `json:"keys" mapstructure:"keys"`
  75. // HostKeys define the daemon's private host keys.
  76. // Each host key can be defined as a path relative to the configuration directory or an absolute one.
  77. // If empty or missing, the daemon will search or try to generate "id_rsa" and "id_ecdsa" host keys
  78. // inside the configuration directory.
  79. HostKeys []string `json:"host_keys" mapstructure:"host_keys"`
  80. // KexAlgorithms specifies the available KEX (Key Exchange) algorithms in
  81. // preference order.
  82. KexAlgorithms []string `json:"kex_algorithms" mapstructure:"kex_algorithms"`
  83. // Ciphers specifies the ciphers allowed
  84. Ciphers []string `json:"ciphers" mapstructure:"ciphers"`
  85. // MACs Specifies the available MAC (message authentication code) algorithms
  86. // in preference order
  87. MACs []string `json:"macs" mapstructure:"macs"`
  88. // TrustedUserCAKeys specifies a list of public keys paths of certificate authorities
  89. // that are trusted to sign user certificates for authentication.
  90. // The paths can be absolute or relative to the configuration directory
  91. TrustedUserCAKeys []string `json:"trusted_user_ca_keys" mapstructure:"trusted_user_ca_keys"`
  92. // LoginBannerFile the contents of the specified file, if any, are sent to
  93. // the remote user before authentication is allowed.
  94. LoginBannerFile string `json:"login_banner_file" mapstructure:"login_banner_file"`
  95. // Deprecated: please use the same key in common configuration
  96. SetstatMode int `json:"setstat_mode" mapstructure:"setstat_mode"`
  97. // List of enabled SSH commands.
  98. // We support the following SSH commands:
  99. // - "scp". SCP is an experimental feature, we have our own SCP implementation since
  100. // we can't rely on scp system command to proper handle permissions, quota and
  101. // user's home dir restrictions.
  102. // The SCP protocol is quite simple but there is no official docs about it,
  103. // so we need more testing and feedbacks before enabling it by default.
  104. // We may not handle some borderline cases or have sneaky bugs.
  105. // Please do accurate tests yourself before enabling SCP and let us known
  106. // if something does not work as expected for your use cases.
  107. // SCP between two remote hosts is supported using the `-3` scp option.
  108. // - "md5sum", "sha1sum", "sha256sum", "sha384sum", "sha512sum". Useful to check message
  109. // digests for uploaded files. These commands are implemented inside SFTPGo so they
  110. // work even if the matching system commands are not available, for example on Windows.
  111. // - "cd", "pwd". Some mobile SFTP clients does not support the SFTP SSH_FXP_REALPATH and so
  112. // they use "cd" and "pwd" SSH commands to get the initial directory.
  113. // Currently `cd` do nothing and `pwd` always returns the "/" path.
  114. //
  115. // The following SSH commands are enabled by default: "md5sum", "sha1sum", "cd", "pwd".
  116. // "*" enables all supported SSH commands.
  117. EnabledSSHCommands []string `json:"enabled_ssh_commands" mapstructure:"enabled_ssh_commands"`
  118. // Absolute path to an external program or an HTTP URL to invoke for keyboard interactive authentication.
  119. // Leave empty to disable this authentication mode.
  120. KeyboardInteractiveHook string `json:"keyboard_interactive_auth_hook" mapstructure:"keyboard_interactive_auth_hook"`
  121. // PasswordAuthentication specifies whether password authentication is allowed.
  122. PasswordAuthentication bool `json:"password_authentication" mapstructure:"password_authentication"`
  123. // Deprecated: please use the same key in common configuration
  124. ProxyProtocol int `json:"proxy_protocol" mapstructure:"proxy_protocol"`
  125. // Deprecated: please use the same key in common configuration
  126. ProxyAllowed []string `json:"proxy_allowed" mapstructure:"proxy_allowed"`
  127. certChecker *ssh.CertChecker
  128. parsedUserCAKeys []ssh.PublicKey
  129. }
  130. // Key contains information about host keys
  131. // Deprecated: please use HostKeys
  132. type Key struct {
  133. // The private key path as absolute path or relative to the configuration directory
  134. PrivateKey string `json:"private_key" mapstructure:"private_key"`
  135. }
  136. type authenticationError struct {
  137. err string
  138. }
  139. func (e *authenticationError) Error() string {
  140. return fmt.Sprintf("Authentication error: %s", e.err)
  141. }
  142. // ShouldBind returns true if there is at least a valid binding
  143. func (c *Configuration) ShouldBind() bool {
  144. for _, binding := range c.Bindings {
  145. if binding.IsValid() {
  146. return true
  147. }
  148. }
  149. return false
  150. }
  151. // Initialize the SFTP server and add a persistent listener to handle inbound SFTP connections.
  152. func (c *Configuration) Initialize(configDir string) error {
  153. serverConfig := &ssh.ServerConfig{
  154. NoClientAuth: false,
  155. MaxAuthTries: c.MaxAuthTries,
  156. PublicKeyCallback: func(conn ssh.ConnMetadata, pubKey ssh.PublicKey) (*ssh.Permissions, error) {
  157. sp, err := c.validatePublicKeyCredentials(conn, pubKey)
  158. if err == ssh.ErrPartialSuccess {
  159. return sp, err
  160. }
  161. if err != nil {
  162. return nil, &authenticationError{err: fmt.Sprintf("could not validate public key credentials: %v", err)}
  163. }
  164. return sp, nil
  165. },
  166. NextAuthMethodsCallback: func(conn ssh.ConnMetadata) []string {
  167. var nextMethods []string
  168. user, err := dataprovider.UserExists(conn.User())
  169. if err == nil {
  170. nextMethods = user.GetNextAuthMethods(conn.PartialSuccessMethods(), c.PasswordAuthentication)
  171. }
  172. return nextMethods
  173. },
  174. ServerVersion: fmt.Sprintf("SSH-2.0-%v", c.Banner),
  175. }
  176. if c.PasswordAuthentication {
  177. serverConfig.PasswordCallback = func(conn ssh.ConnMetadata, pass []byte) (*ssh.Permissions, error) {
  178. sp, err := c.validatePasswordCredentials(conn, pass)
  179. if err != nil {
  180. return nil, &authenticationError{err: fmt.Sprintf("could not validate password credentials: %v", err)}
  181. }
  182. return sp, nil
  183. }
  184. }
  185. if !c.ShouldBind() {
  186. return common.ErrNoBinding
  187. }
  188. if err := c.checkAndLoadHostKeys(configDir, serverConfig); err != nil {
  189. serviceStatus.HostKeys = nil
  190. return err
  191. }
  192. if err := c.initializeCertChecker(configDir); err != nil {
  193. return err
  194. }
  195. sftp.SetSFTPExtensions(sftpExtensions...) //nolint:errcheck // we configure valid SFTP Extensions so we cannot get an error
  196. c.configureSecurityOptions(serverConfig)
  197. c.configureKeyboardInteractiveAuth(serverConfig)
  198. c.configureLoginBanner(serverConfig, configDir)
  199. c.checkSSHCommands()
  200. exitChannel := make(chan error, 1)
  201. serviceStatus.Bindings = nil
  202. for _, binding := range c.Bindings {
  203. if !binding.IsValid() {
  204. continue
  205. }
  206. serviceStatus.Bindings = append(serviceStatus.Bindings, binding)
  207. go func(binding Binding) {
  208. addr := binding.GetAddress()
  209. utils.CheckTCP4Port(binding.Port)
  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 = 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 := os.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 c.KeyboardInteractiveHook == "" {
  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. func canAcceptConnection(ip string) bool {
  316. if common.IsBanned(ip) {
  317. logger.Log(logger.LevelDebug, common.ProtocolSSH, "", "connection refused, ip %#v is banned", ip)
  318. return false
  319. }
  320. if !common.Connections.IsNewConnectionAllowed(ip) {
  321. logger.Log(logger.LevelDebug, common.ProtocolSSH, "", "connection refused, configured limit reached")
  322. return false
  323. }
  324. _, err := common.LimitRate(common.ProtocolSSH, ip)
  325. if err != nil {
  326. return false
  327. }
  328. if err := common.Config.ExecutePostConnectHook(ip, common.ProtocolSSH); err != nil {
  329. return false
  330. }
  331. return true
  332. }
  333. // AcceptInboundConnection handles an inbound connection to the server instance and determines if the request should be served or not.
  334. func (c *Configuration) AcceptInboundConnection(conn net.Conn, config *ssh.ServerConfig) {
  335. defer func() {
  336. if r := recover(); r != nil {
  337. logger.Error(logSender, "", "panic in AcceptInboundConnection: %#v stack strace: %v", r, string(debug.Stack()))
  338. }
  339. }()
  340. ipAddr := utils.GetIPFromRemoteAddress(conn.RemoteAddr().String())
  341. common.Connections.AddClientConnection(ipAddr)
  342. defer common.Connections.RemoveClientConnection(ipAddr)
  343. if !canAcceptConnection(ipAddr) {
  344. conn.Close()
  345. return
  346. }
  347. // Before beginning a handshake must be performed on the incoming net.Conn
  348. // we'll set a Deadline for handshake to complete, the default is 2 minutes as OpenSSH
  349. conn.SetDeadline(time.Now().Add(handshakeTimeout)) //nolint:errcheck
  350. sconn, chans, reqs, err := ssh.NewServerConn(conn, config)
  351. if err != nil {
  352. logger.Debug(logSender, "", "failed to accept an incoming connection: %v", err)
  353. checkAuthError(ipAddr, err)
  354. return
  355. }
  356. // handshake completed so remove the deadline, we'll use IdleTimeout configuration from now on
  357. conn.SetDeadline(time.Time{}) //nolint:errcheck
  358. defer conn.Close()
  359. var user dataprovider.User
  360. // Unmarshal cannot fails here and even if it fails we'll have a user with no permissions
  361. json.Unmarshal([]byte(sconn.Permissions.Extensions["sftpgo_user"]), &user) //nolint:errcheck
  362. loginType := sconn.Permissions.Extensions["sftpgo_login_method"]
  363. connectionID := hex.EncodeToString(sconn.SessionID())
  364. if err = user.CheckFsRoot(connectionID); err != nil {
  365. errClose := user.CloseFs()
  366. logger.Warn(logSender, connectionID, "unable to check fs root: %v close fs error: %v", err, errClose)
  367. return
  368. }
  369. defer user.CloseFs() //nolint:errcheck
  370. logger.Log(logger.LevelInfo, common.ProtocolSSH, connectionID,
  371. "User id: %d, logged in with: %#v, username: %#v, home_dir: %#v remote addr: %#v",
  372. user.ID, loginType, user.Username, user.HomeDir, ipAddr)
  373. dataprovider.UpdateLastLogin(&user) //nolint:errcheck
  374. sshConnection := common.NewSSHConnection(connectionID, conn)
  375. common.Connections.AddSSHConnection(sshConnection)
  376. defer common.Connections.RemoveSSHConnection(connectionID)
  377. go ssh.DiscardRequests(reqs)
  378. channelCounter := int64(0)
  379. for newChannel := range chans {
  380. // If its not a session channel we just move on because its not something we
  381. // know how to handle at this point.
  382. if newChannel.ChannelType() != "session" {
  383. logger.Log(logger.LevelDebug, common.ProtocolSSH, connectionID, "received an unknown channel type: %v",
  384. newChannel.ChannelType())
  385. newChannel.Reject(ssh.UnknownChannelType, "unknown channel type") //nolint:errcheck
  386. continue
  387. }
  388. channel, requests, err := newChannel.Accept()
  389. if err != nil {
  390. logger.Log(logger.LevelWarn, common.ProtocolSSH, connectionID, "could not accept a channel: %v", err)
  391. continue
  392. }
  393. channelCounter++
  394. sshConnection.UpdateLastActivity()
  395. // Channels have a type that is dependent on the protocol. For SFTP this is "subsystem"
  396. // with a payload that (should) be "sftp". Discard anything else we receive ("pty", "shell", etc)
  397. go func(in <-chan *ssh.Request, counter int64) {
  398. for req := range in {
  399. ok := false
  400. connID := fmt.Sprintf("%v_%v", connectionID, counter)
  401. switch req.Type {
  402. case "subsystem":
  403. if string(req.Payload[4:]) == "sftp" {
  404. ok = true
  405. connection := Connection{
  406. BaseConnection: common.NewBaseConnection(connID, common.ProtocolSFTP, conn.RemoteAddr().String(), user),
  407. ClientVersion: string(sconn.ClientVersion()),
  408. RemoteAddr: conn.RemoteAddr(),
  409. channel: channel,
  410. }
  411. go c.handleSftpConnection(channel, &connection)
  412. }
  413. case "exec":
  414. // protocol will be set later inside processSSHCommand it could be SSH or SCP
  415. connection := Connection{
  416. BaseConnection: common.NewBaseConnection(connID, "sshd_exec", conn.RemoteAddr().String(), user),
  417. ClientVersion: string(sconn.ClientVersion()),
  418. RemoteAddr: conn.RemoteAddr(),
  419. channel: channel,
  420. }
  421. ok = processSSHCommand(req.Payload, &connection, c.EnabledSSHCommands)
  422. }
  423. if req.WantReply {
  424. req.Reply(ok, nil) //nolint:errcheck
  425. }
  426. }
  427. }(requests, channelCounter)
  428. }
  429. }
  430. func (c *Configuration) handleSftpConnection(channel ssh.Channel, connection *Connection) {
  431. defer func() {
  432. if r := recover(); r != nil {
  433. logger.Error(logSender, "", "panic in handleSftpConnection: %#v stack strace: %v", r, string(debug.Stack()))
  434. }
  435. }()
  436. common.Connections.Add(connection)
  437. defer common.Connections.Remove(connection.GetID())
  438. // Create a new handler for the currently logged in user's server.
  439. handler := c.createHandler(connection)
  440. // Create the server instance for the channel using the handler we created above.
  441. server := sftp.NewRequestServer(channel, handler, sftp.WithRSAllocator())
  442. defer server.Close()
  443. if err := server.Serve(); err == io.EOF {
  444. connection.Log(logger.LevelDebug, "connection closed, sending exit status")
  445. exitStatus := sshSubsystemExitStatus{Status: uint32(0)}
  446. _, err = channel.SendRequest("exit-status", false, ssh.Marshal(&exitStatus))
  447. connection.Log(logger.LevelDebug, "sent exit status %+v error: %v", exitStatus, err)
  448. } else if err != nil {
  449. connection.Log(logger.LevelWarn, "connection closed with error: %v", err)
  450. }
  451. }
  452. func (c *Configuration) createHandler(connection *Connection) sftp.Handlers {
  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. metrics.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 utils.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 utils.IsStringInSlice("*", c.EnabledSSHCommands) {
  530. c.EnabledSSHCommands = GetSupportedSSHCommands()
  531. return
  532. }
  533. sshCommands := []string{}
  534. for _, command := range c.EnabledSSHCommands {
  535. if utils.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. }
  544. func (c *Configuration) generateDefaultHostKeys(configDir string) error {
  545. var err error
  546. defaultHostKeys := []string{defaultPrivateRSAKeyName, defaultPrivateECDSAKeyName, defaultPrivateEd25519KeyName}
  547. for _, k := range defaultHostKeys {
  548. autoFile := filepath.Join(configDir, k)
  549. if _, err = os.Stat(autoFile); os.IsNotExist(err) {
  550. logger.Info(logSender, "", "No host keys configured and %#v does not exist; try to create a new host key", autoFile)
  551. logger.InfoToConsole("No host keys configured and %#v does not exist; try to create a new host key", autoFile)
  552. if k == defaultPrivateRSAKeyName {
  553. err = utils.GenerateRSAKeys(autoFile)
  554. } else if k == defaultPrivateECDSAKeyName {
  555. err = utils.GenerateECDSAKeys(autoFile)
  556. } else {
  557. err = utils.GenerateEd25519Keys(autoFile)
  558. }
  559. if err != nil {
  560. logger.Warn(logSender, "", "error creating host key %#v: %v", autoFile, err)
  561. logger.WarnToConsole("error creating host key %#v: %v", autoFile, err)
  562. return err
  563. }
  564. }
  565. c.HostKeys = append(c.HostKeys, k)
  566. }
  567. return err
  568. }
  569. func (c *Configuration) checkHostKeyAutoGeneration(configDir string) error {
  570. for _, k := range c.HostKeys {
  571. if filepath.IsAbs(k) {
  572. if _, err := os.Stat(k); os.IsNotExist(err) {
  573. keyName := filepath.Base(k)
  574. switch keyName {
  575. case defaultPrivateRSAKeyName:
  576. logger.Info(logSender, "", "try to create non-existent host key %#v", k)
  577. logger.InfoToConsole("try to create non-existent host key %#v", k)
  578. err = utils.GenerateRSAKeys(k)
  579. if err != nil {
  580. logger.Warn(logSender, "", "error creating host key %#v: %v", k, err)
  581. logger.WarnToConsole("error creating host key %#v: %v", k, err)
  582. return err
  583. }
  584. case defaultPrivateECDSAKeyName:
  585. logger.Info(logSender, "", "try to create non-existent host key %#v", k)
  586. logger.InfoToConsole("try to create non-existent host key %#v", k)
  587. err = utils.GenerateECDSAKeys(k)
  588. if err != nil {
  589. logger.Warn(logSender, "", "error creating host key %#v: %v", k, err)
  590. logger.WarnToConsole("error creating host key %#v: %v", k, err)
  591. return err
  592. }
  593. case defaultPrivateEd25519KeyName:
  594. logger.Info(logSender, "", "try to create non-existent host key %#v", k)
  595. logger.InfoToConsole("try to create non-existent host key %#v", k)
  596. err = utils.GenerateEd25519Keys(k)
  597. if err != nil {
  598. logger.Warn(logSender, "", "error creating host key %#v: %v", k, err)
  599. logger.WarnToConsole("error creating host key %#v: %v", k, err)
  600. return err
  601. }
  602. default:
  603. logger.Warn(logSender, "", "non-existent host key %#v will not be created", k)
  604. logger.WarnToConsole("non-existent host key %#v will not be created", k)
  605. }
  606. }
  607. }
  608. }
  609. if len(c.HostKeys) == 0 {
  610. if err := c.generateDefaultHostKeys(configDir); err != nil {
  611. return err
  612. }
  613. }
  614. return nil
  615. }
  616. // If no host keys are defined we try to use or generate the default ones.
  617. func (c *Configuration) checkAndLoadHostKeys(configDir string, serverConfig *ssh.ServerConfig) error {
  618. if err := c.checkHostKeyAutoGeneration(configDir); err != nil {
  619. return err
  620. }
  621. serviceStatus.HostKeys = nil
  622. for _, hostKey := range c.HostKeys {
  623. if !utils.IsFileInputValid(hostKey) {
  624. logger.Warn(logSender, "", "unable to load invalid host key %#v", hostKey)
  625. logger.WarnToConsole("unable to load invalid host key %#v", hostKey)
  626. continue
  627. }
  628. if !filepath.IsAbs(hostKey) {
  629. hostKey = filepath.Join(configDir, hostKey)
  630. }
  631. logger.Info(logSender, "", "Loading private host key %#v", hostKey)
  632. privateBytes, err := os.ReadFile(hostKey)
  633. if err != nil {
  634. return err
  635. }
  636. private, err := ssh.ParsePrivateKey(privateBytes)
  637. if err != nil {
  638. return err
  639. }
  640. k := HostKey{
  641. Path: hostKey,
  642. Fingerprint: ssh.FingerprintSHA256(private.PublicKey()),
  643. }
  644. serviceStatus.HostKeys = append(serviceStatus.HostKeys, k)
  645. logger.Info(logSender, "", "Host key %#v loaded, type %#v, fingerprint %#v", hostKey,
  646. private.PublicKey().Type(), k.Fingerprint)
  647. // Add private key to the server configuration.
  648. serverConfig.AddHostKey(private)
  649. }
  650. var fp []string
  651. for idx := range serviceStatus.HostKeys {
  652. h := &serviceStatus.HostKeys[idx]
  653. fp = append(fp, h.Fingerprint)
  654. }
  655. vfs.SetSFTPFingerprints(fp)
  656. return nil
  657. }
  658. func (c *Configuration) initializeCertChecker(configDir string) error {
  659. for _, keyPath := range c.TrustedUserCAKeys {
  660. if !utils.IsFileInputValid(keyPath) {
  661. logger.Warn(logSender, "", "unable to load invalid trusted user CA key: %#v", keyPath)
  662. logger.WarnToConsole("unable to load invalid trusted user CA key: %#v", keyPath)
  663. continue
  664. }
  665. if !filepath.IsAbs(keyPath) {
  666. keyPath = filepath.Join(configDir, keyPath)
  667. }
  668. keyBytes, err := os.ReadFile(keyPath)
  669. if err != nil {
  670. logger.Warn(logSender, "", "error loading trusted user CA key %#v: %v", keyPath, err)
  671. logger.WarnToConsole("error loading trusted user CA key %#v: %v", keyPath, err)
  672. return err
  673. }
  674. parsedKey, _, _, _, err := ssh.ParseAuthorizedKey(keyBytes)
  675. if err != nil {
  676. logger.Warn(logSender, "", "error parsing trusted user CA key %#v: %v", keyPath, err)
  677. logger.WarnToConsole("error parsing trusted user CA key %#v: %v", keyPath, err)
  678. return err
  679. }
  680. c.parsedUserCAKeys = append(c.parsedUserCAKeys, parsedKey)
  681. }
  682. c.certChecker = &ssh.CertChecker{
  683. SupportedCriticalOptions: []string{
  684. sourceAddressCriticalOption,
  685. },
  686. IsUserAuthority: func(k ssh.PublicKey) bool {
  687. for _, key := range c.parsedUserCAKeys {
  688. if bytes.Equal(k.Marshal(), key.Marshal()) {
  689. return true
  690. }
  691. }
  692. return false
  693. },
  694. }
  695. return nil
  696. }
  697. func (c *Configuration) validatePublicKeyCredentials(conn ssh.ConnMetadata, pubKey ssh.PublicKey) (*ssh.Permissions, error) {
  698. var err error
  699. var user dataprovider.User
  700. var keyID string
  701. var sshPerm *ssh.Permissions
  702. var certPerm *ssh.Permissions
  703. connectionID := hex.EncodeToString(conn.SessionID())
  704. method := dataprovider.SSHLoginMethodPublicKey
  705. ipAddr := utils.GetIPFromRemoteAddress(conn.RemoteAddr().String())
  706. cert, ok := pubKey.(*ssh.Certificate)
  707. if ok {
  708. if cert.CertType != ssh.UserCert {
  709. err = fmt.Errorf("ssh: cert has type %d", cert.CertType)
  710. user.Username = conn.User()
  711. updateLoginMetrics(&user, ipAddr, method, err)
  712. return nil, err
  713. }
  714. if !c.certChecker.IsUserAuthority(cert.SignatureKey) {
  715. err = fmt.Errorf("ssh: certificate signed by unrecognized authority")
  716. user.Username = conn.User()
  717. updateLoginMetrics(&user, ipAddr, method, err)
  718. return nil, err
  719. }
  720. if err := c.certChecker.CheckCert(conn.User(), cert); err != nil {
  721. user.Username = conn.User()
  722. updateLoginMetrics(&user, ipAddr, method, err)
  723. return nil, err
  724. }
  725. certPerm = &cert.Permissions
  726. }
  727. if user, keyID, err = dataprovider.CheckUserAndPubKey(conn.User(), pubKey.Marshal(), ipAddr, common.ProtocolSSH); err == nil {
  728. if user.IsPartialAuth(method) {
  729. logger.Debug(logSender, connectionID, "user %#v authenticated with partial success", conn.User())
  730. return certPerm, ssh.ErrPartialSuccess
  731. }
  732. sshPerm, err = loginUser(&user, method, keyID, conn)
  733. if err == nil && certPerm != nil {
  734. // if we have a SSH user cert we need to merge certificate permissions with our ones
  735. // we only set Extensions, so CriticalOptions are always the ones from the certificate
  736. sshPerm.CriticalOptions = certPerm.CriticalOptions
  737. if certPerm.Extensions != nil {
  738. for k, v := range certPerm.Extensions {
  739. sshPerm.Extensions[k] = v
  740. }
  741. }
  742. }
  743. }
  744. user.Username = conn.User()
  745. updateLoginMetrics(&user, ipAddr, method, err)
  746. return sshPerm, err
  747. }
  748. func (c *Configuration) validatePasswordCredentials(conn ssh.ConnMetadata, pass []byte) (*ssh.Permissions, error) {
  749. var err error
  750. var user dataprovider.User
  751. var sshPerm *ssh.Permissions
  752. method := dataprovider.LoginMethodPassword
  753. if len(conn.PartialSuccessMethods()) == 1 {
  754. method = dataprovider.SSHLoginMethodKeyAndPassword
  755. }
  756. ipAddr := utils.GetIPFromRemoteAddress(conn.RemoteAddr().String())
  757. if user, err = dataprovider.CheckUserAndPass(conn.User(), string(pass), ipAddr, common.ProtocolSSH); err == nil {
  758. sshPerm, err = loginUser(&user, method, "", conn)
  759. }
  760. user.Username = conn.User()
  761. updateLoginMetrics(&user, ipAddr, method, err)
  762. return sshPerm, err
  763. }
  764. func (c *Configuration) validateKeyboardInteractiveCredentials(conn ssh.ConnMetadata, client ssh.KeyboardInteractiveChallenge) (*ssh.Permissions, error) {
  765. var err error
  766. var user dataprovider.User
  767. var sshPerm *ssh.Permissions
  768. method := dataprovider.SSHLoginMethodKeyboardInteractive
  769. if len(conn.PartialSuccessMethods()) == 1 {
  770. method = dataprovider.SSHLoginMethodKeyAndKeyboardInt
  771. }
  772. ipAddr := utils.GetIPFromRemoteAddress(conn.RemoteAddr().String())
  773. if user, err = dataprovider.CheckKeyboardInteractiveAuth(conn.User(), c.KeyboardInteractiveHook, client,
  774. ipAddr, common.ProtocolSSH); err == nil {
  775. sshPerm, err = loginUser(&user, method, "", conn)
  776. }
  777. user.Username = conn.User()
  778. updateLoginMetrics(&user, ipAddr, method, err)
  779. return sshPerm, err
  780. }
  781. func updateLoginMetrics(user *dataprovider.User, ip, method string, err error) {
  782. metrics.AddLoginAttempt(method)
  783. if err != nil {
  784. logger.ConnectionFailedLog(user.Username, ip, method, common.ProtocolSSH, err.Error())
  785. if method != dataprovider.SSHLoginMethodPublicKey {
  786. // some clients try all available public keys for a user, we
  787. // record failed login key auth only once for session if the
  788. // authentication fails in checkAuthError
  789. event := common.HostEventLoginFailed
  790. if _, ok := err.(*dataprovider.RecordNotFoundError); ok {
  791. event = common.HostEventUserNotFound
  792. }
  793. common.AddDefenderEvent(ip, event)
  794. }
  795. }
  796. metrics.AddLoginResult(method, err)
  797. dataprovider.ExecutePostLoginHook(user, method, ip, common.ProtocolSSH, err)
  798. }