server.go 32 KB

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