server.go 24 KB

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