server.go 28 KB

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