server.go 35 KB

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