server.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  1. package sftpd
  2. import (
  3. "encoding/hex"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "io/ioutil"
  9. "net"
  10. "os"
  11. "path/filepath"
  12. "strconv"
  13. "time"
  14. "github.com/drakkan/sftpgo/dataprovider"
  15. "github.com/drakkan/sftpgo/logger"
  16. "github.com/drakkan/sftpgo/metrics"
  17. "github.com/drakkan/sftpgo/utils"
  18. "github.com/pires/go-proxyproto"
  19. "github.com/pkg/sftp"
  20. "golang.org/x/crypto/ssh"
  21. )
  22. const (
  23. defaultPrivateRSAKeyName = "id_rsa"
  24. defaultPrivateECDSAKeyName = "id_ecdsa"
  25. )
  26. var (
  27. sftpExtensions = []string{"[email protected]"}
  28. errWrongProxyProtoVersion = errors.New("unacceptable proxy protocol version")
  29. )
  30. // Configuration for the SFTP server
  31. type Configuration struct {
  32. // Identification string used by the server
  33. Banner string `json:"banner" mapstructure:"banner"`
  34. // The port used for serving SFTP requests
  35. BindPort int `json:"bind_port" mapstructure:"bind_port"`
  36. // The address to listen on. A blank value means listen on all available network interfaces.
  37. BindAddress string `json:"bind_address" mapstructure:"bind_address"`
  38. // Maximum idle timeout as minutes. If a client is idle for a time that exceeds this setting it will be disconnected.
  39. // 0 means disabled
  40. IdleTimeout int `json:"idle_timeout" mapstructure:"idle_timeout"`
  41. // Maximum number of authentication attempts permitted per connection.
  42. // If set to a negative number, the number of attempts is unlimited.
  43. // If set to zero, the number of attempts are limited to 6.
  44. MaxAuthTries int `json:"max_auth_tries" mapstructure:"max_auth_tries"`
  45. // Umask for new files
  46. Umask string `json:"umask" mapstructure:"umask"`
  47. // UploadMode 0 means standard, the files are uploaded directly to the requested path.
  48. // 1 means atomic: the files are uploaded to a temporary path and renamed to the requested path
  49. // when the client ends the upload. Atomic mode avoid problems such as a web server that
  50. // serves partial files when the files are being uploaded.
  51. // In atomic mode if there is an upload error the temporary file is deleted and so the requested
  52. // upload path will not contain a partial file.
  53. // 2 means atomic with resume support: as atomic but if there is an upload error the temporary
  54. // file is renamed to the requested path and not deleted, this way a client can reconnect and resume
  55. // the upload.
  56. UploadMode int `json:"upload_mode" mapstructure:"upload_mode"`
  57. // Actions to execute on SFTP create, download, delete and rename
  58. Actions Actions `json:"actions" mapstructure:"actions"`
  59. // Keys are a list of host keys
  60. Keys []Key `json:"keys" mapstructure:"keys"`
  61. // IsSCPEnabled determines if experimental SCP support is enabled.
  62. // This setting is deprecated and will be removed in future versions,
  63. // please add "scp" to the EnabledSSHCommands list to enable it.
  64. IsSCPEnabled bool `json:"enable_scp" mapstructure:"enable_scp"`
  65. // KexAlgorithms specifies the available KEX (Key Exchange) algorithms in
  66. // preference order.
  67. KexAlgorithms []string `json:"kex_algorithms" mapstructure:"kex_algorithms"`
  68. // Ciphers specifies the ciphers allowed
  69. Ciphers []string `json:"ciphers" mapstructure:"ciphers"`
  70. // MACs Specifies the available MAC (message authentication code) algorithms
  71. // in preference order
  72. MACs []string `json:"macs" mapstructure:"macs"`
  73. // LoginBannerFile the contents of the specified file, if any, are sent to
  74. // the remote user before authentication is allowed.
  75. LoginBannerFile string `json:"login_banner_file" mapstructure:"login_banner_file"`
  76. // SetstatMode 0 means "normal mode": requests for changing permissions and owner/group are executed.
  77. // 1 means "ignore mode": requests for changing permissions and owner/group are silently ignored.
  78. SetstatMode int `json:"setstat_mode" mapstructure:"setstat_mode"`
  79. // List of enabled SSH commands.
  80. // We support the following SSH commands:
  81. // - "scp". SCP is an experimental feature, we have our own SCP implementation since
  82. // we can't rely on scp system command to proper handle permissions, quota and
  83. // user's home dir restrictions.
  84. // The SCP protocol is quite simple but there is no official docs about it,
  85. // so we need more testing and feedbacks before enabling it by default.
  86. // We may not handle some borderline cases or have sneaky bugs.
  87. // Please do accurate tests yourself before enabling SCP and let us known
  88. // if something does not work as expected for your use cases.
  89. // SCP between two remote hosts is supported using the `-3` scp option.
  90. // - "md5sum", "sha1sum", "sha256sum", "sha384sum", "sha512sum". Useful to check message
  91. // digests for uploaded files. These commands are implemented inside SFTPGo so they
  92. // work even if the matching system commands are not available, for example on Windows.
  93. // - "cd", "pwd". Some mobile SFTP clients does not support the SFTP SSH_FXP_REALPATH and so
  94. // they use "cd" and "pwd" SSH commands to get the initial directory.
  95. // Currently `cd` do nothing and `pwd` always returns the "/" path.
  96. //
  97. // The following SSH commands are enabled by default: "md5sum", "sha1sum", "cd", "pwd".
  98. // "*" enables all supported SSH commands.
  99. EnabledSSHCommands []string `json:"enabled_ssh_commands" mapstructure:"enabled_ssh_commands"`
  100. // Absolute path to an external program to use for keyboard interactive authentication.
  101. // Leave empty to disable this authentication mode.
  102. KeyboardInteractiveProgram string `json:"keyboard_interactive_auth_program" mapstructure:"keyboard_interactive_auth_program"`
  103. // Support for HAProxy PROXY protocol.
  104. // If you are running SFTPGo behind a proxy server such as HAProxy, AWS ELB or NGNIX, you can enable
  105. // the proxy protocol. It provides a convenient way to safely transport connection information
  106. // such as a client's address across multiple layers of NAT or TCP proxies to get the real
  107. // client IP address instead of the proxy IP. Both protocol version 1 and 2 are supported.
  108. // - 0 means disabled
  109. // - 1 means proxy protocol enabled. Proxy header will be used and requests without proxy header will be accepted.
  110. // - 2 means proxy protocol required. Proxy header will be used and requests without proxy header will be rejected.
  111. // If the proxy protocol is enabled in SFTPGo then you have to enable the protocol in your proxy configuration too,
  112. // for example for HAProxy add "send-proxy" or "send-proxy-v2" to each server configuration line.
  113. ProxyProtocol int `json:"proxy_protocol" mapstructure:"proxy_protocol"`
  114. // List of IP addresses and IP ranges allowed to send the proxy header.
  115. // If proxy protocol is set to 1 and we receive a proxy header from an IP that is not in the list then the
  116. // connection will be accepted and the header will be ignored.
  117. // If proxy protocol is set to 2 and we receive a proxy header from an IP that is not in the list then the
  118. // connection will be rejected.
  119. ProxyAllowed []string `json:"proxy_allowed" mapstructure:"proxy_allowed"`
  120. }
  121. // Key contains information about host keys
  122. type Key struct {
  123. // The private key path relative to the configuration directory or absolute
  124. PrivateKey string `json:"private_key" mapstructure:"private_key"`
  125. }
  126. type authenticationError struct {
  127. err string
  128. }
  129. func (e *authenticationError) Error() string {
  130. return fmt.Sprintf("Authentication error: %s", e.err)
  131. }
  132. // Initialize the SFTP server and add a persistent listener to handle inbound SFTP connections.
  133. func (c Configuration) Initialize(configDir string) error {
  134. umask, err := strconv.ParseUint(c.Umask, 8, 8)
  135. if err == nil {
  136. utils.SetUmask(int(umask), c.Umask)
  137. } else {
  138. logger.Warn(logSender, "", "error reading umask, please fix your config file: %v", err)
  139. logger.WarnToConsole("error reading umask, please fix your config file: %v", err)
  140. }
  141. serverConfig := &ssh.ServerConfig{
  142. NoClientAuth: false,
  143. MaxAuthTries: c.MaxAuthTries,
  144. PasswordCallback: func(conn ssh.ConnMetadata, pass []byte) (*ssh.Permissions, error) {
  145. sp, err := c.validatePasswordCredentials(conn, pass)
  146. if err != nil {
  147. return nil, &authenticationError{err: fmt.Sprintf("could not validate password credentials: %v", err)}
  148. }
  149. return sp, nil
  150. },
  151. PublicKeyCallback: func(conn ssh.ConnMetadata, pubKey ssh.PublicKey) (*ssh.Permissions, error) {
  152. sp, err := c.validatePublicKeyCredentials(conn, string(pubKey.Marshal()))
  153. if err != nil {
  154. return nil, &authenticationError{err: fmt.Sprintf("could not validate public key credentials: %v", err)}
  155. }
  156. return sp, nil
  157. },
  158. ServerVersion: "SSH-2.0-" + c.Banner,
  159. }
  160. err = c.checkHostKeys(configDir)
  161. if err != nil {
  162. return err
  163. }
  164. for _, k := range c.Keys {
  165. privateFile := k.PrivateKey
  166. if !filepath.IsAbs(privateFile) {
  167. privateFile = filepath.Join(configDir, privateFile)
  168. }
  169. logger.Info(logSender, "", "Loading private key: %s", privateFile)
  170. privateBytes, err := ioutil.ReadFile(privateFile)
  171. if err != nil {
  172. return err
  173. }
  174. private, err := ssh.ParsePrivateKey(privateBytes)
  175. if err != nil {
  176. return err
  177. }
  178. // Add private key to the server configuration.
  179. serverConfig.AddHostKey(private)
  180. }
  181. c.configureSecurityOptions(serverConfig)
  182. c.configureKeyboardInteractiveAuth(serverConfig)
  183. c.configureLoginBanner(serverConfig, configDir)
  184. c.configureSFTPExtensions()
  185. c.checkSSHCommands()
  186. listener, err := net.Listen("tcp", fmt.Sprintf("%s:%d", c.BindAddress, c.BindPort))
  187. if err != nil {
  188. logger.Warn(logSender, "", "error starting listener on address %s:%d: %v", c.BindAddress, c.BindPort, err)
  189. return err
  190. }
  191. proxyListener, err := c.getProxyListener(listener)
  192. if err != nil {
  193. logger.Warn(logSender, "", "error enabling proxy listener: %v", err)
  194. return err
  195. }
  196. actions = c.Actions
  197. uploadMode = c.UploadMode
  198. setstatMode = c.SetstatMode
  199. logger.Info(logSender, "", "server listener registered address: %v", listener.Addr().String())
  200. c.checkIdleTimer()
  201. for {
  202. var conn net.Conn
  203. if proxyListener != nil {
  204. conn, err = proxyListener.Accept()
  205. } else {
  206. conn, err = listener.Accept()
  207. }
  208. if conn != nil && err == nil {
  209. go c.AcceptInboundConnection(conn, serverConfig)
  210. }
  211. }
  212. }
  213. func (c *Configuration) getProxyListener(listener net.Listener) (*proxyproto.Listener, error) {
  214. var proxyListener *proxyproto.Listener
  215. var err error
  216. if c.ProxyProtocol > 0 {
  217. var policyFunc func(upstream net.Addr) (proxyproto.Policy, error)
  218. if c.ProxyProtocol == 1 && len(c.ProxyAllowed) > 0 {
  219. policyFunc, err = proxyproto.LaxWhiteListPolicy(c.ProxyAllowed)
  220. if err != nil {
  221. return nil, err
  222. }
  223. }
  224. if c.ProxyProtocol == 2 {
  225. if len(c.ProxyAllowed) == 0 {
  226. policyFunc = func(upstream net.Addr) (proxyproto.Policy, error) {
  227. return proxyproto.REQUIRE, nil
  228. }
  229. } else {
  230. policyFunc, err = proxyproto.StrictWhiteListPolicy(c.ProxyAllowed)
  231. if err != nil {
  232. return nil, err
  233. }
  234. }
  235. }
  236. proxyListener = &proxyproto.Listener{
  237. Listener: listener,
  238. Policy: policyFunc,
  239. }
  240. }
  241. return proxyListener, nil
  242. }
  243. func (c Configuration) checkIdleTimer() {
  244. if c.IdleTimeout > 0 {
  245. startIdleTimer(time.Duration(c.IdleTimeout) * time.Minute)
  246. }
  247. }
  248. func (c Configuration) configureSecurityOptions(serverConfig *ssh.ServerConfig) {
  249. if len(c.KexAlgorithms) > 0 {
  250. serverConfig.KeyExchanges = c.KexAlgorithms
  251. }
  252. if len(c.Ciphers) > 0 {
  253. serverConfig.Ciphers = c.Ciphers
  254. }
  255. if len(c.MACs) > 0 {
  256. serverConfig.MACs = c.MACs
  257. }
  258. }
  259. func (c Configuration) configureLoginBanner(serverConfig *ssh.ServerConfig, configDir string) error {
  260. var err error
  261. if len(c.LoginBannerFile) > 0 {
  262. bannerFilePath := c.LoginBannerFile
  263. if !filepath.IsAbs(bannerFilePath) {
  264. bannerFilePath = filepath.Join(configDir, bannerFilePath)
  265. }
  266. var banner []byte
  267. banner, err = ioutil.ReadFile(bannerFilePath)
  268. if err == nil {
  269. serverConfig.BannerCallback = func(conn ssh.ConnMetadata) string {
  270. return string(banner)
  271. }
  272. } else {
  273. logger.WarnToConsole("unable to read login banner file: %v", err)
  274. logger.Warn(logSender, "", "unable to read login banner file: %v", err)
  275. }
  276. }
  277. return err
  278. }
  279. func (c Configuration) configureKeyboardInteractiveAuth(serverConfig *ssh.ServerConfig) {
  280. if len(c.KeyboardInteractiveProgram) == 0 {
  281. return
  282. }
  283. if !filepath.IsAbs(c.KeyboardInteractiveProgram) {
  284. logger.WarnToConsole("invalid keyboard interactive authentication program: %#v must be an absolute path",
  285. c.KeyboardInteractiveProgram)
  286. logger.Warn(logSender, "", "invalid keyboard interactive authentication program: %#v must be an absolute path",
  287. c.KeyboardInteractiveProgram)
  288. return
  289. }
  290. _, err := os.Stat(c.KeyboardInteractiveProgram)
  291. if err != nil {
  292. logger.WarnToConsole("invalid keyboard interactive authentication program:: %v", err)
  293. logger.Warn(logSender, "", "invalid keyboard interactive authentication program:: %v", err)
  294. return
  295. }
  296. serverConfig.KeyboardInteractiveCallback = func(conn ssh.ConnMetadata, client ssh.KeyboardInteractiveChallenge) (*ssh.Permissions, error) {
  297. sp, err := c.validateKeyboardInteractiveCredentials(conn, client)
  298. if err != nil {
  299. return nil, &authenticationError{err: fmt.Sprintf("could not validate keyboard interactive credentials: %v", err)}
  300. }
  301. return sp, nil
  302. }
  303. }
  304. func (c Configuration) configureSFTPExtensions() error {
  305. err := sftp.SetSFTPExtensions(sftpExtensions...)
  306. if err != nil {
  307. logger.WarnToConsole("unable to configure SFTP extensions: %v", err)
  308. logger.Warn(logSender, "", "unable to configure SFTP extensions: %v", err)
  309. }
  310. return err
  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))
  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{})
  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["user"]), &user)
  331. loginType := sconn.Permissions.Extensions["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)
  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")
  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)
  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)
  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, remoteAddr, publicKey string) (*ssh.Permissions, error) {
  415. if !filepath.IsAbs(user.HomeDir) {
  416. logger.Warn(logSender, "", "user %#v has an invalid home dir: %#v. Home dir must be an absolute path, login not allowed",
  417. user.Username, user.HomeDir)
  418. return nil, fmt.Errorf("cannot login user with invalid home dir: %#v", user.HomeDir)
  419. }
  420. if user.MaxSessions > 0 {
  421. activeSessions := getActiveSessions(user.Username)
  422. if activeSessions >= user.MaxSessions {
  423. logger.Debug(logSender, "", "authentication refused for user: %#v, too many open sessions: %v/%v", user.Username,
  424. activeSessions, user.MaxSessions)
  425. return nil, fmt.Errorf("too many open sessions: %v", activeSessions)
  426. }
  427. }
  428. if !user.IsLoginMethodAllowed(loginMethod) {
  429. logger.Debug(logSender, "", "cannot login user %#v, login method %#v is not allowed", user.Username, loginMethod)
  430. return nil, fmt.Errorf("Login method %#v is not allowed for user %#v", loginMethod, user.Username)
  431. }
  432. if !user.IsLoginFromAddrAllowed(remoteAddr) {
  433. logger.Debug(logSender, "", "cannot login user %#v, remote address is not allowed: %v", user.Username, remoteAddr)
  434. return nil, fmt.Errorf("Login for user %#v is not allowed from this address: %v", user.Username, remoteAddr)
  435. }
  436. json, err := json.Marshal(user)
  437. if err != nil {
  438. logger.Warn(logSender, "", "error serializing user info: %v, authentication rejected", err)
  439. return nil, err
  440. }
  441. if len(publicKey) > 0 {
  442. loginMethod = fmt.Sprintf("%v: %v", loginMethod, publicKey)
  443. }
  444. p := &ssh.Permissions{}
  445. p.Extensions = make(map[string]string)
  446. p.Extensions["user"] = string(json)
  447. p.Extensions["login_method"] = loginMethod
  448. return p, nil
  449. }
  450. func (c *Configuration) checkSSHCommands() {
  451. if utils.IsStringInSlice("*", c.EnabledSSHCommands) {
  452. c.EnabledSSHCommands = GetSupportedSSHCommands()
  453. return
  454. }
  455. sshCommands := []string{}
  456. if c.IsSCPEnabled {
  457. sshCommands = append(sshCommands, "scp")
  458. }
  459. for _, command := range c.EnabledSSHCommands {
  460. if utils.IsStringInSlice(command, supportedSSHCommands) {
  461. sshCommands = append(sshCommands, command)
  462. } else {
  463. logger.Warn(logSender, "", "unsupported ssh command: %#v ignored", command)
  464. logger.WarnToConsole("unsupported ssh command: %#v ignored", command)
  465. }
  466. }
  467. c.EnabledSSHCommands = sshCommands
  468. }
  469. // If no host keys are defined we try to use or generate the default one.
  470. func (c *Configuration) checkHostKeys(configDir string) error {
  471. if len(c.Keys) == 0 {
  472. defaultKeys := []string{defaultPrivateRSAKeyName, defaultPrivateECDSAKeyName}
  473. for _, k := range defaultKeys {
  474. autoFile := filepath.Join(configDir, k)
  475. if _, err := os.Stat(autoFile); os.IsNotExist(err) {
  476. logger.Info(logSender, "", "No host keys configured and %#v does not exist; creating new key for server", autoFile)
  477. logger.InfoToConsole("No host keys configured and %#v does not exist; creating new key for server", autoFile)
  478. if k == defaultPrivateRSAKeyName {
  479. err = utils.GenerateRSAKeys(autoFile)
  480. } else {
  481. err = utils.GenerateECDSAKeys(autoFile)
  482. }
  483. if err != nil {
  484. return err
  485. }
  486. }
  487. c.Keys = append(c.Keys, Key{PrivateKey: k})
  488. }
  489. }
  490. return nil
  491. }
  492. func (c Configuration) validatePublicKeyCredentials(conn ssh.ConnMetadata, pubKey string) (*ssh.Permissions, error) {
  493. var err error
  494. var user dataprovider.User
  495. var keyID string
  496. var sshPerm *ssh.Permissions
  497. method := dataprovider.SSHLoginMethodPublicKey
  498. metrics.AddLoginAttempt(method)
  499. if user, keyID, err = dataprovider.CheckUserAndPubKey(dataProvider, conn.User(), pubKey); err == nil {
  500. sshPerm, err = loginUser(user, method, conn.RemoteAddr().String(), keyID)
  501. }
  502. if err != nil {
  503. logger.ConnectionFailedLog(conn.User(), utils.GetIPFromRemoteAddress(conn.RemoteAddr().String()), method, err.Error())
  504. }
  505. metrics.AddLoginResult(method, err)
  506. return sshPerm, err
  507. }
  508. func (c Configuration) validatePasswordCredentials(conn ssh.ConnMetadata, pass []byte) (*ssh.Permissions, error) {
  509. var err error
  510. var user dataprovider.User
  511. var sshPerm *ssh.Permissions
  512. method := dataprovider.SSHLoginMethodPassword
  513. metrics.AddLoginAttempt(method)
  514. if user, err = dataprovider.CheckUserAndPass(dataProvider, conn.User(), string(pass)); err == nil {
  515. sshPerm, err = loginUser(user, method, conn.RemoteAddr().String(), "")
  516. }
  517. if err != nil {
  518. logger.ConnectionFailedLog(conn.User(), utils.GetIPFromRemoteAddress(conn.RemoteAddr().String()), method, err.Error())
  519. }
  520. metrics.AddLoginResult(method, err)
  521. return sshPerm, err
  522. }
  523. func (c Configuration) validateKeyboardInteractiveCredentials(conn ssh.ConnMetadata, client ssh.KeyboardInteractiveChallenge) (*ssh.Permissions, error) {
  524. var err error
  525. var user dataprovider.User
  526. var sshPerm *ssh.Permissions
  527. method := dataprovider.SSHLoginMethodKeyboardInteractive
  528. metrics.AddLoginAttempt(method)
  529. if user, err = dataprovider.CheckKeyboardInteractiveAuth(dataProvider, conn.User(), c.KeyboardInteractiveProgram, client); err == nil {
  530. sshPerm, err = loginUser(user, method, conn.RemoteAddr().String(), "")
  531. }
  532. if err != nil {
  533. logger.ConnectionFailedLog(conn.User(), utils.GetIPFromRemoteAddress(conn.RemoteAddr().String()), method, err.Error())
  534. }
  535. metrics.AddLoginResult(method, err)
  536. return sshPerm, err
  537. }