server.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691
  1. package sftpd
  2. import (
  3. "bytes"
  4. "encoding/hex"
  5. "encoding/json"
  6. "fmt"
  7. "io"
  8. "io/ioutil"
  9. "net"
  10. "os"
  11. "path/filepath"
  12. "strconv"
  13. "strings"
  14. "time"
  15. "github.com/pires/go-proxyproto"
  16. "github.com/pkg/sftp"
  17. "golang.org/x/crypto/ssh"
  18. "github.com/drakkan/sftpgo/dataprovider"
  19. "github.com/drakkan/sftpgo/logger"
  20. "github.com/drakkan/sftpgo/metrics"
  21. "github.com/drakkan/sftpgo/utils"
  22. )
  23. const (
  24. defaultPrivateRSAKeyName = "id_rsa"
  25. defaultPrivateECDSAKeyName = "id_ecdsa"
  26. sourceAddressCriticalOption = "source-address"
  27. )
  28. var (
  29. sftpExtensions = []string{"[email protected]"}
  30. )
  31. // Configuration for the SFTP server
  32. type Configuration struct {
  33. // Identification string used by the server
  34. Banner string `json:"banner" mapstructure:"banner"`
  35. // The port used for serving SFTP requests
  36. BindPort int `json:"bind_port" mapstructure:"bind_port"`
  37. // The address to listen on. A blank value means listen on all available network interfaces.
  38. BindAddress string `json:"bind_address" mapstructure:"bind_address"`
  39. // Maximum idle timeout as minutes. If a client is idle for a time that exceeds this setting it will be disconnected.
  40. // 0 means disabled
  41. IdleTimeout int `json:"idle_timeout" mapstructure:"idle_timeout"`
  42. // Maximum number of authentication attempts permitted per connection.
  43. // If set to a negative number, the number of attempts is unlimited.
  44. // If set to zero, the number of attempts are limited to 6.
  45. MaxAuthTries int `json:"max_auth_tries" mapstructure:"max_auth_tries"`
  46. // Umask for new files
  47. Umask string `json:"umask" mapstructure:"umask"`
  48. // UploadMode 0 means standard, the files are uploaded directly to the requested path.
  49. // 1 means atomic: the files are uploaded to a temporary path and renamed to the requested path
  50. // when the client ends the upload. Atomic mode avoid problems such as a web server that
  51. // serves partial files when the files are being uploaded.
  52. // In atomic mode if there is an upload error the temporary file is deleted and so the requested
  53. // upload path will not contain a partial file.
  54. // 2 means atomic with resume support: as atomic but if there is an upload error the temporary
  55. // file is renamed to the requested path and not deleted, this way a client can reconnect and resume
  56. // the upload.
  57. UploadMode int `json:"upload_mode" mapstructure:"upload_mode"`
  58. // Actions to execute on SFTP create, download, delete and rename
  59. Actions Actions `json:"actions" mapstructure:"actions"`
  60. // Deprecated: please use HostKeys
  61. Keys []Key `json:"keys" mapstructure:"keys"`
  62. // HostKeys define the daemon's private host keys.
  63. // Each host key can be defined as a path relative to the configuration directory or an absolute one.
  64. // If empty or missing, the daemon will search or try to generate "id_rsa" and "id_ecdsa" host keys
  65. // inside the configuration directory.
  66. HostKeys []string `json:"host_keys" mapstructure:"host_keys"`
  67. // KexAlgorithms specifies the available KEX (Key Exchange) algorithms in
  68. // preference order.
  69. KexAlgorithms []string `json:"kex_algorithms" mapstructure:"kex_algorithms"`
  70. // Ciphers specifies the ciphers allowed
  71. Ciphers []string `json:"ciphers" mapstructure:"ciphers"`
  72. // MACs Specifies the available MAC (message authentication code) algorithms
  73. // in preference order
  74. MACs []string `json:"macs" mapstructure:"macs"`
  75. // TrustedUserCAKeys specifies a list of public keys paths of certificate authorities
  76. // that are trusted to sign user certificates for authentication.
  77. // The paths can be absolute or relative to the configuration directory
  78. TrustedUserCAKeys []string `json:"trusted_user_ca_keys" mapstructure:"trusted_user_ca_keys"`
  79. // LoginBannerFile the contents of the specified file, if any, are sent to
  80. // the remote user before authentication is allowed.
  81. LoginBannerFile string `json:"login_banner_file" mapstructure:"login_banner_file"`
  82. // SetstatMode 0 means "normal mode": requests for changing permissions and owner/group are executed.
  83. // 1 means "ignore mode": requests for changing permissions and owner/group are silently ignored.
  84. SetstatMode int `json:"setstat_mode" mapstructure:"setstat_mode"`
  85. // List of enabled SSH commands.
  86. // We support the following SSH commands:
  87. // - "scp". SCP is an experimental feature, we have our own SCP implementation since
  88. // we can't rely on scp system command to proper handle permissions, quota and
  89. // user's home dir restrictions.
  90. // The SCP protocol is quite simple but there is no official docs about it,
  91. // so we need more testing and feedbacks before enabling it by default.
  92. // We may not handle some borderline cases or have sneaky bugs.
  93. // Please do accurate tests yourself before enabling SCP and let us known
  94. // if something does not work as expected for your use cases.
  95. // SCP between two remote hosts is supported using the `-3` scp option.
  96. // - "md5sum", "sha1sum", "sha256sum", "sha384sum", "sha512sum". Useful to check message
  97. // digests for uploaded files. These commands are implemented inside SFTPGo so they
  98. // work even if the matching system commands are not available, for example on Windows.
  99. // - "cd", "pwd". Some mobile SFTP clients does not support the SFTP SSH_FXP_REALPATH and so
  100. // they use "cd" and "pwd" SSH commands to get the initial directory.
  101. // Currently `cd` do nothing and `pwd` always returns the "/" path.
  102. //
  103. // The following SSH commands are enabled by default: "md5sum", "sha1sum", "cd", "pwd".
  104. // "*" enables all supported SSH commands.
  105. EnabledSSHCommands []string `json:"enabled_ssh_commands" mapstructure:"enabled_ssh_commands"`
  106. // Deprecated: please use KeyboardInteractiveHook
  107. KeyboardInteractiveProgram string `json:"keyboard_interactive_auth_program" mapstructure:"keyboard_interactive_auth_program"`
  108. // Absolute path to an external program or an HTTP URL to invoke for keyboard interactive authentication.
  109. // Leave empty to disable this authentication mode.
  110. KeyboardInteractiveHook string `json:"keyboard_interactive_auth_hook" mapstructure:"keyboard_interactive_auth_hook"`
  111. // Support for HAProxy PROXY protocol.
  112. // If you are running SFTPGo behind a proxy server such as HAProxy, AWS ELB or NGNIX, you can enable
  113. // the proxy protocol. It provides a convenient way to safely transport connection information
  114. // such as a client's address across multiple layers of NAT or TCP proxies to get the real
  115. // client IP address instead of the proxy IP. Both protocol versions 1 and 2 are supported.
  116. // - 0 means disabled
  117. // - 1 means proxy protocol enabled. Proxy header will be used and requests without proxy header will be accepted.
  118. // - 2 means proxy protocol required. Proxy header will be used and requests without proxy header will be rejected.
  119. // If the proxy protocol is enabled in SFTPGo then you have to enable the protocol in your proxy configuration too,
  120. // for example for HAProxy add "send-proxy" or "send-proxy-v2" to each server configuration line.
  121. ProxyProtocol int `json:"proxy_protocol" mapstructure:"proxy_protocol"`
  122. // List of IP addresses and IP ranges allowed to send the proxy header.
  123. // If proxy protocol is set to 1 and we receive a proxy header from an IP that is not in the list then the
  124. // connection will be accepted and the header will be ignored.
  125. // If proxy protocol is set to 2 and we receive a proxy header from an IP that is not in the list then the
  126. // connection will be rejected.
  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. // Initialize the SFTP server and add a persistent listener to handle inbound SFTP connections.
  144. func (c Configuration) Initialize(configDir string) error {
  145. umask, err := strconv.ParseUint(c.Umask, 8, 8)
  146. if err == nil {
  147. utils.SetUmask(int(umask), c.Umask)
  148. } else {
  149. logger.Warn(logSender, "", "error reading umask, please fix your config file: %v", err)
  150. logger.WarnToConsole("error reading umask, please fix your config file: %v", err)
  151. }
  152. serverConfig := &ssh.ServerConfig{
  153. NoClientAuth: false,
  154. MaxAuthTries: c.MaxAuthTries,
  155. PasswordCallback: func(conn ssh.ConnMetadata, pass []byte) (*ssh.Permissions, error) {
  156. sp, err := c.validatePasswordCredentials(conn, pass)
  157. if err != nil {
  158. return nil, &authenticationError{err: fmt.Sprintf("could not validate password credentials: %v", err)}
  159. }
  160. return sp, nil
  161. },
  162. PublicKeyCallback: func(conn ssh.ConnMetadata, pubKey ssh.PublicKey) (*ssh.Permissions, error) {
  163. sp, err := c.validatePublicKeyCredentials(conn, pubKey)
  164. if err == ssh.ErrPartialSuccess {
  165. return sp, err
  166. }
  167. if err != nil {
  168. return nil, &authenticationError{err: fmt.Sprintf("could not validate public key credentials: %v", err)}
  169. }
  170. return sp, nil
  171. },
  172. NextAuthMethodsCallback: func(conn ssh.ConnMetadata) []string {
  173. var nextMethods []string
  174. user, err := dataprovider.UserExists(dataProvider, conn.User())
  175. if err == nil {
  176. nextMethods = user.GetNextAuthMethods(conn.PartialSuccessMethods())
  177. }
  178. return nextMethods
  179. },
  180. ServerVersion: fmt.Sprintf("SSH-2.0-%v", c.Banner),
  181. }
  182. if err = c.checkAndLoadHostKeys(configDir, serverConfig); err != nil {
  183. return err
  184. }
  185. if err = c.initializeCertChecker(configDir); err != nil {
  186. return err
  187. }
  188. sftp.SetSFTPExtensions(sftpExtensions...) //nolint:errcheck // we configure valid SFTP Extensions so we cannot get an error
  189. c.configureSecurityOptions(serverConfig)
  190. c.configureKeyboardInteractiveAuth(serverConfig)
  191. c.configureLoginBanner(serverConfig, configDir)
  192. c.checkSSHCommands()
  193. listener, err := net.Listen("tcp", fmt.Sprintf("%s:%d", c.BindAddress, c.BindPort))
  194. if err != nil {
  195. logger.Warn(logSender, "", "error starting listener on address %s:%d: %v", c.BindAddress, c.BindPort, err)
  196. return err
  197. }
  198. proxyListener, err := c.getProxyListener(listener)
  199. if err != nil {
  200. logger.Warn(logSender, "", "error enabling proxy listener: %v", err)
  201. return err
  202. }
  203. actions = c.Actions
  204. uploadMode = c.UploadMode
  205. setstatMode = c.SetstatMode
  206. logger.Info(logSender, "", "server listener registered address: %v", listener.Addr().String())
  207. c.checkIdleTimer()
  208. for {
  209. var conn net.Conn
  210. if proxyListener != nil {
  211. conn, err = proxyListener.Accept()
  212. } else {
  213. conn, err = listener.Accept()
  214. }
  215. if conn != nil && err == nil {
  216. go c.AcceptInboundConnection(conn, serverConfig)
  217. }
  218. }
  219. }
  220. func (c *Configuration) getProxyListener(listener net.Listener) (*proxyproto.Listener, error) {
  221. var proxyListener *proxyproto.Listener
  222. var err error
  223. if c.ProxyProtocol > 0 {
  224. var policyFunc func(upstream net.Addr) (proxyproto.Policy, error)
  225. if c.ProxyProtocol == 1 && len(c.ProxyAllowed) > 0 {
  226. policyFunc, err = proxyproto.LaxWhiteListPolicy(c.ProxyAllowed)
  227. if err != nil {
  228. return nil, err
  229. }
  230. }
  231. if c.ProxyProtocol == 2 {
  232. if len(c.ProxyAllowed) == 0 {
  233. policyFunc = func(upstream net.Addr) (proxyproto.Policy, error) {
  234. return proxyproto.REQUIRE, nil
  235. }
  236. } else {
  237. policyFunc, err = proxyproto.StrictWhiteListPolicy(c.ProxyAllowed)
  238. if err != nil {
  239. return nil, err
  240. }
  241. }
  242. }
  243. proxyListener = &proxyproto.Listener{
  244. Listener: listener,
  245. Policy: policyFunc,
  246. }
  247. }
  248. return proxyListener, nil
  249. }
  250. func (c Configuration) checkIdleTimer() {
  251. if c.IdleTimeout > 0 {
  252. startIdleTimer(time.Duration(c.IdleTimeout) * time.Minute)
  253. }
  254. }
  255. func (c Configuration) configureSecurityOptions(serverConfig *ssh.ServerConfig) {
  256. if len(c.KexAlgorithms) > 0 {
  257. serverConfig.KeyExchanges = c.KexAlgorithms
  258. }
  259. if len(c.Ciphers) > 0 {
  260. serverConfig.Ciphers = c.Ciphers
  261. }
  262. if len(c.MACs) > 0 {
  263. serverConfig.MACs = c.MACs
  264. }
  265. }
  266. func (c Configuration) configureLoginBanner(serverConfig *ssh.ServerConfig, configDir string) {
  267. if len(c.LoginBannerFile) > 0 {
  268. bannerFilePath := c.LoginBannerFile
  269. if !filepath.IsAbs(bannerFilePath) {
  270. bannerFilePath = filepath.Join(configDir, bannerFilePath)
  271. }
  272. bannerContent, err := ioutil.ReadFile(bannerFilePath)
  273. if err == nil {
  274. banner := string(bannerContent)
  275. serverConfig.BannerCallback = func(conn ssh.ConnMetadata) string {
  276. return banner
  277. }
  278. } else {
  279. logger.WarnToConsole("unable to read login banner file: %v", err)
  280. logger.Warn(logSender, "", "unable to read login banner file: %v", err)
  281. }
  282. }
  283. }
  284. func (c Configuration) configureKeyboardInteractiveAuth(serverConfig *ssh.ServerConfig) {
  285. if len(c.KeyboardInteractiveHook) == 0 {
  286. return
  287. }
  288. if !strings.HasPrefix(c.KeyboardInteractiveHook, "http") {
  289. if !filepath.IsAbs(c.KeyboardInteractiveHook) {
  290. logger.WarnToConsole("invalid keyboard interactive authentication program: %#v must be an absolute path",
  291. c.KeyboardInteractiveHook)
  292. logger.Warn(logSender, "", "invalid keyboard interactive authentication program: %#v must be an absolute path",
  293. c.KeyboardInteractiveHook)
  294. return
  295. }
  296. _, err := os.Stat(c.KeyboardInteractiveHook)
  297. if err != nil {
  298. logger.WarnToConsole("invalid keyboard interactive authentication program:: %v", err)
  299. logger.Warn(logSender, "", "invalid keyboard interactive authentication program:: %v", err)
  300. return
  301. }
  302. }
  303. serverConfig.KeyboardInteractiveCallback = func(conn ssh.ConnMetadata, client ssh.KeyboardInteractiveChallenge) (*ssh.Permissions, error) {
  304. sp, err := c.validateKeyboardInteractiveCredentials(conn, client)
  305. if err != nil {
  306. return nil, &authenticationError{err: fmt.Sprintf("could not validate keyboard interactive credentials: %v", err)}
  307. }
  308. return sp, nil
  309. }
  310. }
  311. // AcceptInboundConnection handles an inbound connection to the server instance and determines if the request should be served or not.
  312. func (c Configuration) AcceptInboundConnection(conn net.Conn, config *ssh.ServerConfig) {
  313. // Before beginning a handshake must be performed on the incoming net.Conn
  314. // we'll set a Deadline for handshake to complete, the default is 2 minutes as OpenSSH
  315. conn.SetDeadline(time.Now().Add(handshakeTimeout)) //nolint:errcheck
  316. remoteAddr := conn.RemoteAddr()
  317. sconn, chans, reqs, err := ssh.NewServerConn(conn, config)
  318. if err != nil {
  319. logger.Warn(logSender, "", "failed to accept an incoming connection: %v", err)
  320. if _, ok := err.(*ssh.ServerAuthError); !ok {
  321. logger.ConnectionFailedLog("", utils.GetIPFromRemoteAddress(remoteAddr.String()), "no_auth_tryed", err.Error())
  322. }
  323. return
  324. }
  325. // handshake completed so remove the deadline, we'll use IdleTimeout configuration from now on
  326. conn.SetDeadline(time.Time{}) //nolint:errcheck
  327. var user dataprovider.User
  328. // Unmarshal cannot fails here and even if it fails we'll have a user with no permissions
  329. json.Unmarshal([]byte(sconn.Permissions.Extensions["sftpgo_user"]), &user) //nolint:errcheck
  330. loginType := sconn.Permissions.Extensions["sftpgo_login_method"]
  331. connectionID := hex.EncodeToString(sconn.SessionID())
  332. fs, err := user.GetFilesystem(connectionID)
  333. if err != nil {
  334. logger.Warn(logSender, "", "could create filesystem for user %#v err: %v", user.Username, err)
  335. conn.Close()
  336. return
  337. }
  338. connection := Connection{
  339. ID: connectionID,
  340. User: user,
  341. ClientVersion: string(sconn.ClientVersion()),
  342. RemoteAddr: remoteAddr,
  343. StartTime: time.Now(),
  344. lastActivity: time.Now(),
  345. netConn: conn,
  346. channel: nil,
  347. fs: fs,
  348. }
  349. connection.fs.CheckRootPath(user.Username, user.GetUID(), user.GetGID())
  350. connection.Log(logger.LevelInfo, logSender, "User id: %d, logged in with: %#v, username: %#v, home_dir: %#v remote addr: %#v",
  351. user.ID, loginType, user.Username, user.HomeDir, remoteAddr.String())
  352. dataprovider.UpdateLastLogin(dataProvider, user) //nolint:errcheck
  353. go ssh.DiscardRequests(reqs)
  354. for newChannel := range chans {
  355. // If its not a session channel we just move on because its not something we
  356. // know how to handle at this point.
  357. if newChannel.ChannelType() != "session" {
  358. connection.Log(logger.LevelDebug, logSender, "received an unknown channel type: %v", newChannel.ChannelType())
  359. newChannel.Reject(ssh.UnknownChannelType, "unknown channel type") //nolint:errcheck
  360. continue
  361. }
  362. channel, requests, err := newChannel.Accept()
  363. if err != nil {
  364. connection.Log(logger.LevelWarn, logSender, "could not accept a channel: %v", err)
  365. continue
  366. }
  367. // Channels have a type that is dependent on the protocol. For SFTP this is "subsystem"
  368. // with a payload that (should) be "sftp". Discard anything else we receive ("pty", "shell", etc)
  369. go func(in <-chan *ssh.Request) {
  370. for req := range in {
  371. ok := false
  372. switch req.Type {
  373. case "subsystem":
  374. if string(req.Payload[4:]) == "sftp" {
  375. ok = true
  376. connection.protocol = protocolSFTP
  377. connection.channel = channel
  378. go c.handleSftpConnection(channel, connection)
  379. }
  380. case "exec":
  381. ok = processSSHCommand(req.Payload, &connection, channel, c.EnabledSSHCommands)
  382. }
  383. req.Reply(ok, nil) //nolint:errcheck
  384. }
  385. }(requests)
  386. }
  387. }
  388. func (c Configuration) handleSftpConnection(channel ssh.Channel, connection Connection) {
  389. addConnection(connection)
  390. defer removeConnection(connection)
  391. // Create a new handler for the currently logged in user's server.
  392. handler := c.createHandler(connection)
  393. // Create the server instance for the channel using the handler we created above.
  394. server := sftp.NewRequestServer(channel, handler, sftp.WithRSAllocator())
  395. if err := server.Serve(); err == io.EOF {
  396. connection.Log(logger.LevelDebug, logSender, "connection closed, sending exit status")
  397. exitStatus := sshSubsystemExitStatus{Status: uint32(0)}
  398. _, err = channel.SendRequest("exit-status", false, ssh.Marshal(&exitStatus))
  399. connection.Log(logger.LevelDebug, logSender, "sent exit status %+v error: %v", exitStatus, err)
  400. server.Close()
  401. } else if err != nil {
  402. connection.Log(logger.LevelWarn, logSender, "connection closed with error: %v", err)
  403. }
  404. }
  405. func (c Configuration) createHandler(connection Connection) sftp.Handlers {
  406. return sftp.Handlers{
  407. FileGet: connection,
  408. FilePut: connection,
  409. FileCmd: connection,
  410. FileList: connection,
  411. }
  412. }
  413. func loginUser(user dataprovider.User, loginMethod, publicKey string, conn ssh.ConnMetadata) (*ssh.Permissions, error) {
  414. connectionID := ""
  415. if conn != nil {
  416. connectionID = hex.EncodeToString(conn.SessionID())
  417. }
  418. if !filepath.IsAbs(user.HomeDir) {
  419. logger.Warn(logSender, connectionID, "user %#v has an invalid home dir: %#v. Home dir must be an absolute path, login not allowed",
  420. user.Username, user.HomeDir)
  421. return nil, fmt.Errorf("cannot login user with invalid home dir: %#v", user.HomeDir)
  422. }
  423. if user.MaxSessions > 0 {
  424. activeSessions := getActiveSessions(user.Username)
  425. if activeSessions >= user.MaxSessions {
  426. logger.Debug(logSender, "", "authentication refused for user: %#v, too many open sessions: %v/%v", user.Username,
  427. activeSessions, user.MaxSessions)
  428. return nil, fmt.Errorf("too many open sessions: %v", activeSessions)
  429. }
  430. }
  431. if !user.IsLoginMethodAllowed(loginMethod, conn.PartialSuccessMethods()) {
  432. logger.Debug(logSender, connectionID, "cannot login user %#v, login method %#v is not allowed", user.Username, loginMethod)
  433. return nil, fmt.Errorf("Login method %#v is not allowed for user %#v", loginMethod, user.Username)
  434. }
  435. remoteAddr := conn.RemoteAddr().String()
  436. if !user.IsLoginFromAddrAllowed(remoteAddr) {
  437. logger.Debug(logSender, connectionID, "cannot login user %#v, remote address is not allowed: %v", user.Username, remoteAddr)
  438. return nil, fmt.Errorf("Login for user %#v is not allowed from this address: %v", user.Username, remoteAddr)
  439. }
  440. json, err := json.Marshal(user)
  441. if err != nil {
  442. logger.Warn(logSender, connectionID, "error serializing user info: %v, authentication rejected", err)
  443. return nil, err
  444. }
  445. if len(publicKey) > 0 {
  446. loginMethod = fmt.Sprintf("%v: %v", loginMethod, publicKey)
  447. }
  448. p := &ssh.Permissions{}
  449. p.Extensions = make(map[string]string)
  450. p.Extensions["sftpgo_user"] = string(json)
  451. p.Extensions["sftpgo_login_method"] = loginMethod
  452. return p, nil
  453. }
  454. func (c *Configuration) checkSSHCommands() {
  455. if utils.IsStringInSlice("*", c.EnabledSSHCommands) {
  456. c.EnabledSSHCommands = GetSupportedSSHCommands()
  457. return
  458. }
  459. sshCommands := []string{}
  460. for _, command := range c.EnabledSSHCommands {
  461. if utils.IsStringInSlice(command, supportedSSHCommands) {
  462. sshCommands = append(sshCommands, command)
  463. } else {
  464. logger.Warn(logSender, "", "unsupported ssh command: %#v ignored", command)
  465. logger.WarnToConsole("unsupported ssh command: %#v ignored", command)
  466. }
  467. }
  468. c.EnabledSSHCommands = sshCommands
  469. }
  470. // If no host keys are defined we try to use or generate the default ones.
  471. func (c *Configuration) checkAndLoadHostKeys(configDir string, serverConfig *ssh.ServerConfig) error {
  472. if len(c.HostKeys) == 0 {
  473. defaultKeys := []string{defaultPrivateRSAKeyName, defaultPrivateECDSAKeyName}
  474. for _, k := range defaultKeys {
  475. autoFile := filepath.Join(configDir, k)
  476. if _, err := os.Stat(autoFile); os.IsNotExist(err) {
  477. logger.Info(logSender, "", "No host keys configured and %#v does not exist; creating new key for server", autoFile)
  478. logger.InfoToConsole("No host keys configured and %#v does not exist; creating new key for server", autoFile)
  479. if k == defaultPrivateRSAKeyName {
  480. err = utils.GenerateRSAKeys(autoFile)
  481. } else {
  482. err = utils.GenerateECDSAKeys(autoFile)
  483. }
  484. if err != nil {
  485. return err
  486. }
  487. }
  488. c.HostKeys = append(c.HostKeys, k)
  489. }
  490. }
  491. for _, k := range c.HostKeys {
  492. hostKey := k
  493. if !utils.IsFileInputValid(hostKey) {
  494. logger.Warn(logSender, "", "unable to load invalid host key: %#v", hostKey)
  495. logger.WarnToConsole("unable to load invalid host key: %#v", hostKey)
  496. continue
  497. }
  498. if !filepath.IsAbs(hostKey) {
  499. hostKey = filepath.Join(configDir, hostKey)
  500. }
  501. logger.Info(logSender, "", "Loading private host key: %s", hostKey)
  502. privateBytes, err := ioutil.ReadFile(hostKey)
  503. if err != nil {
  504. return err
  505. }
  506. private, err := ssh.ParsePrivateKey(privateBytes)
  507. if err != nil {
  508. return err
  509. }
  510. // Add private key to the server configuration.
  511. serverConfig.AddHostKey(private)
  512. }
  513. return nil
  514. }
  515. func (c *Configuration) initializeCertChecker(configDir string) error {
  516. for _, keyPath := range c.TrustedUserCAKeys {
  517. if !utils.IsFileInputValid(keyPath) {
  518. logger.Warn(logSender, "", "unable to load invalid trusted user CA key: %#v", keyPath)
  519. logger.WarnToConsole("unable to load invalid trusted user CA key: %#v", keyPath)
  520. continue
  521. }
  522. if !filepath.IsAbs(keyPath) {
  523. keyPath = filepath.Join(configDir, keyPath)
  524. }
  525. keyBytes, err := ioutil.ReadFile(keyPath)
  526. if err != nil {
  527. logger.Warn(logSender, "", "error loading trusted user CA key %#v: %v", keyPath, err)
  528. logger.WarnToConsole("error loading trusted user CA key %#v: %v", keyPath, err)
  529. return err
  530. }
  531. parsedKey, _, _, _, err := ssh.ParseAuthorizedKey(keyBytes)
  532. if err != nil {
  533. logger.Warn(logSender, "", "error parsing trusted user CA key %#v: %v", keyPath, err)
  534. logger.WarnToConsole("error parsing trusted user CA key %#v: %v", keyPath, err)
  535. return err
  536. }
  537. c.parsedUserCAKeys = append(c.parsedUserCAKeys, parsedKey)
  538. }
  539. c.certChecker = &ssh.CertChecker{
  540. SupportedCriticalOptions: []string{
  541. sourceAddressCriticalOption,
  542. },
  543. IsUserAuthority: func(k ssh.PublicKey) bool {
  544. for _, key := range c.parsedUserCAKeys {
  545. if bytes.Equal(k.Marshal(), key.Marshal()) {
  546. return true
  547. }
  548. }
  549. return false
  550. },
  551. }
  552. return nil
  553. }
  554. func (c Configuration) validatePublicKeyCredentials(conn ssh.ConnMetadata, pubKey ssh.PublicKey) (*ssh.Permissions, error) {
  555. var err error
  556. var user dataprovider.User
  557. var keyID string
  558. var sshPerm *ssh.Permissions
  559. var certPerm *ssh.Permissions
  560. connectionID := hex.EncodeToString(conn.SessionID())
  561. method := dataprovider.SSHLoginMethodPublicKey
  562. cert, ok := pubKey.(*ssh.Certificate)
  563. if ok {
  564. if cert.CertType != ssh.UserCert {
  565. err = fmt.Errorf("ssh: cert has type %d", cert.CertType)
  566. updateLoginMetrics(conn, method, err)
  567. return nil, err
  568. }
  569. if !c.certChecker.IsUserAuthority(cert.SignatureKey) {
  570. err = fmt.Errorf("ssh: certificate signed by unrecognized authority")
  571. updateLoginMetrics(conn, method, err)
  572. return nil, err
  573. }
  574. if err := c.certChecker.CheckCert(conn.User(), cert); err != nil {
  575. updateLoginMetrics(conn, method, err)
  576. return nil, err
  577. }
  578. certPerm = &cert.Permissions
  579. }
  580. if user, keyID, err = dataprovider.CheckUserAndPubKey(dataProvider, conn.User(), pubKey.Marshal()); err == nil {
  581. if user.IsPartialAuth(method) {
  582. logger.Debug(logSender, connectionID, "user %#v authenticated with partial success", conn.User())
  583. return certPerm, ssh.ErrPartialSuccess
  584. }
  585. sshPerm, err = loginUser(user, method, keyID, conn)
  586. if err == nil && certPerm != nil {
  587. // if we have a SSH user cert we need to merge certificate permissions with our ones
  588. // we only set Extensions, so CriticalOptions are always the ones from the certificate
  589. sshPerm.CriticalOptions = certPerm.CriticalOptions
  590. if certPerm.Extensions != nil {
  591. for k, v := range certPerm.Extensions {
  592. sshPerm.Extensions[k] = v
  593. }
  594. }
  595. }
  596. }
  597. updateLoginMetrics(conn, method, err)
  598. return sshPerm, err
  599. }
  600. func (c Configuration) validatePasswordCredentials(conn ssh.ConnMetadata, pass []byte) (*ssh.Permissions, error) {
  601. var err error
  602. var user dataprovider.User
  603. var sshPerm *ssh.Permissions
  604. method := dataprovider.SSHLoginMethodPassword
  605. if len(conn.PartialSuccessMethods()) == 1 {
  606. method = dataprovider.SSHLoginMethodKeyAndPassword
  607. }
  608. if user, err = dataprovider.CheckUserAndPass(dataProvider, conn.User(), string(pass)); err == nil {
  609. sshPerm, err = loginUser(user, method, "", conn)
  610. }
  611. updateLoginMetrics(conn, method, err)
  612. return sshPerm, err
  613. }
  614. func (c Configuration) validateKeyboardInteractiveCredentials(conn ssh.ConnMetadata, client ssh.KeyboardInteractiveChallenge) (*ssh.Permissions, error) {
  615. var err error
  616. var user dataprovider.User
  617. var sshPerm *ssh.Permissions
  618. method := dataprovider.SSHLoginMethodKeyboardInteractive
  619. if len(conn.PartialSuccessMethods()) == 1 {
  620. method = dataprovider.SSHLoginMethodKeyAndKeyboardInt
  621. }
  622. if user, err = dataprovider.CheckKeyboardInteractiveAuth(dataProvider, conn.User(), c.KeyboardInteractiveHook, client); err == nil {
  623. sshPerm, err = loginUser(user, method, "", conn)
  624. }
  625. updateLoginMetrics(conn, method, err)
  626. return sshPerm, err
  627. }
  628. func updateLoginMetrics(conn ssh.ConnMetadata, method string, err error) {
  629. metrics.AddLoginAttempt(method)
  630. if err != nil {
  631. logger.ConnectionFailedLog(conn.User(), utils.GetIPFromRemoteAddress(conn.RemoteAddr().String()), method, err.Error())
  632. }
  633. metrics.AddLoginResult(method, err)
  634. }