server.go 32 KB

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