server.go 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164
  1. // Copyright (C) 2019-2022 Nicola Murino
  2. //
  3. // This program is free software: you can redistribute it and/or modify
  4. // it under the terms of the GNU Affero General Public License as published
  5. // by the Free Software Foundation, version 3.
  6. //
  7. // This program is distributed in the hope that it will be useful,
  8. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. // GNU Affero General Public License for more details.
  11. //
  12. // You should have received a copy of the GNU Affero General Public License
  13. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. package sftpd
  15. import (
  16. "bytes"
  17. "encoding/hex"
  18. "encoding/json"
  19. "errors"
  20. "fmt"
  21. "io"
  22. "io/fs"
  23. "net"
  24. "os"
  25. "path"
  26. "path/filepath"
  27. "runtime/debug"
  28. "strings"
  29. "sync"
  30. "time"
  31. "github.com/pkg/sftp"
  32. "golang.org/x/crypto/ssh"
  33. "github.com/drakkan/sftpgo/v2/internal/common"
  34. "github.com/drakkan/sftpgo/v2/internal/dataprovider"
  35. "github.com/drakkan/sftpgo/v2/internal/logger"
  36. "github.com/drakkan/sftpgo/v2/internal/metric"
  37. "github.com/drakkan/sftpgo/v2/internal/util"
  38. "github.com/drakkan/sftpgo/v2/internal/vfs"
  39. )
  40. const (
  41. defaultPrivateRSAKeyName = "id_rsa"
  42. defaultPrivateECDSAKeyName = "id_ecdsa"
  43. defaultPrivateEd25519KeyName = "id_ed25519"
  44. sourceAddressCriticalOption = "source-address"
  45. )
  46. var (
  47. sftpExtensions = []string{"[email protected]"}
  48. supportedHostKeyAlgos = []string{
  49. ssh.CertAlgoRSASHA512v01, ssh.CertAlgoRSASHA256v01,
  50. ssh.CertAlgoRSAv01, ssh.CertAlgoDSAv01, ssh.CertAlgoECDSA256v01,
  51. ssh.CertAlgoECDSA384v01, ssh.CertAlgoECDSA521v01, ssh.CertAlgoED25519v01,
  52. ssh.KeyAlgoECDSA256, ssh.KeyAlgoECDSA384, ssh.KeyAlgoECDSA521,
  53. ssh.KeyAlgoRSASHA512, ssh.KeyAlgoRSASHA256,
  54. ssh.KeyAlgoRSA, ssh.KeyAlgoDSA,
  55. ssh.KeyAlgoED25519,
  56. }
  57. preferredHostKeyAlgos = []string{
  58. ssh.CertAlgoRSASHA512v01, ssh.CertAlgoRSASHA256v01,
  59. ssh.CertAlgoECDSA256v01,
  60. ssh.CertAlgoECDSA384v01, ssh.CertAlgoECDSA521v01, ssh.CertAlgoED25519v01,
  61. ssh.KeyAlgoECDSA256, ssh.KeyAlgoECDSA384, ssh.KeyAlgoECDSA521,
  62. ssh.KeyAlgoRSASHA512, ssh.KeyAlgoRSASHA256,
  63. ssh.KeyAlgoED25519,
  64. }
  65. supportedKexAlgos = []string{
  66. "curve25519-sha256", "[email protected]",
  67. "ecdh-sha2-nistp256", "ecdh-sha2-nistp384", "ecdh-sha2-nistp521",
  68. "diffie-hellman-group14-sha256", "diffie-hellman-group16-sha512",
  69. "diffie-hellman-group18-sha512", "diffie-hellman-group14-sha1",
  70. "diffie-hellman-group1-sha1",
  71. }
  72. supportedCiphers = []string{
  73. "[email protected]", "[email protected]",
  74. "[email protected]",
  75. "aes128-ctr", "aes192-ctr", "aes256-ctr",
  76. "aes128-cbc", "aes192-cbc", "aes256-cbc",
  77. "3des-cbc",
  78. "arcfour", "arcfour128", "arcfour256",
  79. }
  80. supportedMACs = []string{
  81. "[email protected]", "hmac-sha2-256",
  82. "[email protected]", "hmac-sha2-512",
  83. "hmac-sha1", "hmac-sha1-96",
  84. }
  85. revokedCertManager = revokedCertificates{
  86. certs: map[string]bool{},
  87. }
  88. )
  89. // Binding defines the configuration for a network listener
  90. type Binding struct {
  91. // The address to listen on. A blank value means listen on all available network interfaces.
  92. Address string `json:"address" mapstructure:"address"`
  93. // The port used for serving requests
  94. Port int `json:"port" mapstructure:"port"`
  95. // Apply the proxy configuration, if any, for this binding
  96. ApplyProxyConfig bool `json:"apply_proxy_config" mapstructure:"apply_proxy_config"`
  97. }
  98. // GetAddress returns the binding address
  99. func (b *Binding) GetAddress() string {
  100. return fmt.Sprintf("%s:%d", b.Address, b.Port)
  101. }
  102. // IsValid returns true if the binding port is > 0
  103. func (b *Binding) IsValid() bool {
  104. return b.Port > 0
  105. }
  106. // HasProxy returns true if the proxy protocol is active for this binding
  107. func (b *Binding) HasProxy() bool {
  108. return b.ApplyProxyConfig && common.Config.ProxyProtocol > 0
  109. }
  110. // Configuration for the SFTP server
  111. type Configuration struct {
  112. // Identification string used by the server
  113. Banner string `json:"banner" mapstructure:"banner"`
  114. // Addresses and ports to bind to
  115. Bindings []Binding `json:"bindings" mapstructure:"bindings"`
  116. // Maximum number of authentication attempts permitted per connection.
  117. // If set to a negative number, the number of attempts is unlimited.
  118. // If set to zero, the number of attempts are limited to 6.
  119. MaxAuthTries int `json:"max_auth_tries" mapstructure:"max_auth_tries"`
  120. // HostKeys define the daemon's private host keys.
  121. // Each host key can be defined as a path relative to the configuration directory or an absolute one.
  122. // If empty or missing, the daemon will search or try to generate "id_rsa" and "id_ecdsa" host keys
  123. // inside the configuration directory.
  124. HostKeys []string `json:"host_keys" mapstructure:"host_keys"`
  125. // HostCertificates defines public host certificates.
  126. // Each certificate can be defined as a path relative to the configuration directory or an absolute one.
  127. // Certificate's public key must match a private host key otherwise it will be silently ignored.
  128. HostCertificates []string `json:"host_certificates" mapstructure:"host_certificates"`
  129. // HostKeyAlgorithms lists the public key algorithms that the server will accept for host
  130. // key authentication.
  131. HostKeyAlgorithms []string `json:"host_key_algorithms" mapstructure:"host_key_algorithms"`
  132. // KexAlgorithms specifies the available KEX (Key Exchange) algorithms in
  133. // preference order.
  134. KexAlgorithms []string `json:"kex_algorithms" mapstructure:"kex_algorithms"`
  135. // Ciphers specifies the ciphers allowed
  136. Ciphers []string `json:"ciphers" mapstructure:"ciphers"`
  137. // MACs Specifies the available MAC (message authentication code) algorithms
  138. // in preference order
  139. MACs []string `json:"macs" mapstructure:"macs"`
  140. // TrustedUserCAKeys specifies a list of public keys paths of certificate authorities
  141. // that are trusted to sign user certificates for authentication.
  142. // The paths can be absolute or relative to the configuration directory
  143. TrustedUserCAKeys []string `json:"trusted_user_ca_keys" mapstructure:"trusted_user_ca_keys"`
  144. // Path to a file containing the revoked user certificates.
  145. // This file must contain a JSON list with the public key fingerprints of the revoked certificates.
  146. // Example content:
  147. // ["SHA256:bsBRHC/xgiqBJdSuvSTNpJNLTISP/G356jNMCRYC5Es","SHA256:119+8cL/HH+NLMawRsJx6CzPF1I3xC+jpM60bQHXGE8"]
  148. RevokedUserCertsFile string `json:"revoked_user_certs_file" mapstructure:"revoked_user_certs_file"`
  149. // LoginBannerFile the contents of the specified file, if any, are sent to
  150. // the remote user before authentication is allowed.
  151. LoginBannerFile string `json:"login_banner_file" mapstructure:"login_banner_file"`
  152. // List of enabled SSH commands.
  153. // We support the following SSH commands:
  154. // - "scp". SCP is an experimental feature, we have our own SCP implementation since
  155. // we can't rely on scp system command to proper handle permissions, quota and
  156. // user's home dir restrictions.
  157. // The SCP protocol is quite simple but there is no official docs about it,
  158. // so we need more testing and feedbacks before enabling it by default.
  159. // We may not handle some borderline cases or have sneaky bugs.
  160. // Please do accurate tests yourself before enabling SCP and let us known
  161. // if something does not work as expected for your use cases.
  162. // SCP between two remote hosts is supported using the `-3` scp option.
  163. // - "md5sum", "sha1sum", "sha256sum", "sha384sum", "sha512sum". Useful to check message
  164. // digests for uploaded files. These commands are implemented inside SFTPGo so they
  165. // work even if the matching system commands are not available, for example on Windows.
  166. // - "cd", "pwd". Some mobile SFTP clients does not support the SFTP SSH_FXP_REALPATH and so
  167. // they use "cd" and "pwd" SSH commands to get the initial directory.
  168. // Currently `cd` do nothing and `pwd` always returns the "/" path.
  169. //
  170. // The following SSH commands are enabled by default: "md5sum", "sha1sum", "cd", "pwd".
  171. // "*" enables all supported SSH commands.
  172. EnabledSSHCommands []string `json:"enabled_ssh_commands" mapstructure:"enabled_ssh_commands"`
  173. // KeyboardInteractiveAuthentication specifies whether keyboard interactive authentication is allowed.
  174. // If no keyboard interactive hook or auth plugin is defined the default is to prompt for the user password and then the
  175. // one time authentication code, if defined.
  176. KeyboardInteractiveAuthentication bool `json:"keyboard_interactive_authentication" mapstructure:"keyboard_interactive_authentication"`
  177. // Absolute path to an external program or an HTTP URL to invoke for keyboard interactive authentication.
  178. // Leave empty to disable this authentication mode.
  179. KeyboardInteractiveHook string `json:"keyboard_interactive_auth_hook" mapstructure:"keyboard_interactive_auth_hook"`
  180. // PasswordAuthentication specifies whether password authentication is allowed.
  181. PasswordAuthentication bool `json:"password_authentication" mapstructure:"password_authentication"`
  182. // Virtual root folder prefix to include in all file operations (ex: /files).
  183. // The virtual paths used for per-directory permissions, file patterns etc. must not include the folder prefix.
  184. // The prefix is only applied to SFTP requests, SCP and other SSH commands will be automatically disabled if
  185. // you configure a prefix.
  186. // This setting can help some migrations from OpenSSH. It is not recommended for general usage.
  187. FolderPrefix string `json:"folder_prefix" mapstructure:"folder_prefix"`
  188. certChecker *ssh.CertChecker
  189. parsedUserCAKeys []ssh.PublicKey
  190. }
  191. type authenticationError struct {
  192. err string
  193. }
  194. func (e *authenticationError) Error() string {
  195. return fmt.Sprintf("Authentication error: %s", e.err)
  196. }
  197. // ShouldBind returns true if there is at least a valid binding
  198. func (c *Configuration) ShouldBind() bool {
  199. for _, binding := range c.Bindings {
  200. if binding.IsValid() {
  201. return true
  202. }
  203. }
  204. return false
  205. }
  206. func (c *Configuration) getServerConfig() *ssh.ServerConfig {
  207. serverConfig := &ssh.ServerConfig{
  208. NoClientAuth: false,
  209. MaxAuthTries: c.MaxAuthTries,
  210. PublicKeyCallback: func(conn ssh.ConnMetadata, pubKey ssh.PublicKey) (*ssh.Permissions, error) {
  211. sp, err := c.validatePublicKeyCredentials(conn, pubKey)
  212. if err == ssh.ErrPartialSuccess {
  213. return sp, err
  214. }
  215. if err != nil {
  216. return nil, &authenticationError{err: fmt.Sprintf("could not validate public key credentials: %v", err)}
  217. }
  218. return sp, nil
  219. },
  220. NextAuthMethodsCallback: func(conn ssh.ConnMetadata) []string {
  221. var nextMethods []string
  222. user, err := dataprovider.GetUserWithGroupSettings(conn.User())
  223. if err == nil {
  224. nextMethods = user.GetNextAuthMethods(conn.PartialSuccessMethods(), c.PasswordAuthentication)
  225. }
  226. return nextMethods
  227. },
  228. ServerVersion: fmt.Sprintf("SSH-2.0-%v", c.Banner),
  229. }
  230. if c.PasswordAuthentication {
  231. serverConfig.PasswordCallback = func(conn ssh.ConnMetadata, pass []byte) (*ssh.Permissions, error) {
  232. sp, err := c.validatePasswordCredentials(conn, pass)
  233. if err != nil {
  234. return nil, &authenticationError{err: fmt.Sprintf("could not validate password credentials: %v", err)}
  235. }
  236. return sp, nil
  237. }
  238. serviceStatus.Authentications = append(serviceStatus.Authentications, dataprovider.LoginMethodPassword)
  239. }
  240. serviceStatus.Authentications = append(serviceStatus.Authentications, dataprovider.SSHLoginMethodPublicKey)
  241. return serverConfig
  242. }
  243. func (c *Configuration) updateSupportedAuthentications() {
  244. serviceStatus.Authentications = util.RemoveDuplicates(serviceStatus.Authentications, false)
  245. if util.Contains(serviceStatus.Authentications, dataprovider.LoginMethodPassword) &&
  246. util.Contains(serviceStatus.Authentications, dataprovider.SSHLoginMethodPublicKey) {
  247. serviceStatus.Authentications = append(serviceStatus.Authentications, dataprovider.SSHLoginMethodKeyAndPassword)
  248. }
  249. if util.Contains(serviceStatus.Authentications, dataprovider.SSHLoginMethodKeyboardInteractive) &&
  250. util.Contains(serviceStatus.Authentications, dataprovider.SSHLoginMethodPublicKey) {
  251. serviceStatus.Authentications = append(serviceStatus.Authentications, dataprovider.SSHLoginMethodKeyAndKeyboardInt)
  252. }
  253. }
  254. // Initialize the SFTP server and add a persistent listener to handle inbound SFTP connections.
  255. func (c *Configuration) Initialize(configDir string) error {
  256. serviceStatus.Authentications = nil
  257. serverConfig := c.getServerConfig()
  258. if !c.ShouldBind() {
  259. return common.ErrNoBinding
  260. }
  261. if err := c.checkAndLoadHostKeys(configDir, serverConfig); err != nil {
  262. serviceStatus.HostKeys = nil
  263. return err
  264. }
  265. if err := c.initializeCertChecker(configDir); err != nil {
  266. return err
  267. }
  268. sftp.SetSFTPExtensions(sftpExtensions...) //nolint:errcheck // we configure valid SFTP Extensions so we cannot get an error
  269. if err := c.configureSecurityOptions(serverConfig); err != nil {
  270. return err
  271. }
  272. c.configureKeyboardInteractiveAuth(serverConfig)
  273. c.configureLoginBanner(serverConfig, configDir)
  274. c.checkSSHCommands()
  275. c.checkFolderPrefix()
  276. exitChannel := make(chan error, 1)
  277. serviceStatus.Bindings = nil
  278. for _, binding := range c.Bindings {
  279. if !binding.IsValid() {
  280. continue
  281. }
  282. serviceStatus.Bindings = append(serviceStatus.Bindings, binding)
  283. go func(binding Binding) {
  284. addr := binding.GetAddress()
  285. util.CheckTCP4Port(binding.Port)
  286. listener, err := net.Listen("tcp", addr)
  287. if err != nil {
  288. logger.Warn(logSender, "", "error starting listener on address %v: %v", addr, err)
  289. exitChannel <- err
  290. return
  291. }
  292. if binding.ApplyProxyConfig && common.Config.ProxyProtocol > 0 {
  293. proxyListener, err := common.Config.GetProxyListener(listener)
  294. if err != nil {
  295. logger.Warn(logSender, "", "error enabling proxy listener: %v", err)
  296. exitChannel <- err
  297. return
  298. }
  299. listener = proxyListener
  300. }
  301. exitChannel <- c.serve(listener, serverConfig)
  302. }(binding)
  303. }
  304. serviceStatus.IsActive = true
  305. serviceStatus.SSHCommands = c.EnabledSSHCommands
  306. c.updateSupportedAuthentications()
  307. return <-exitChannel
  308. }
  309. func (c *Configuration) serve(listener net.Listener, serverConfig *ssh.ServerConfig) error {
  310. logger.Info(logSender, "", "server listener registered, address: %v", listener.Addr().String())
  311. var tempDelay time.Duration // how long to sleep on accept failure
  312. for {
  313. conn, err := listener.Accept()
  314. if err != nil {
  315. // see https://github.com/golang/go/blob/4aa1efed4853ea067d665a952eee77c52faac774/src/net/http/server.go#L3046
  316. if ne, ok := err.(net.Error); ok && ne.Temporary() { //nolint:staticcheck
  317. if tempDelay == 0 {
  318. tempDelay = 5 * time.Millisecond
  319. } else {
  320. tempDelay *= 2
  321. }
  322. if max := 1 * time.Second; tempDelay > max {
  323. tempDelay = max
  324. }
  325. logger.Warn(logSender, "", "accept error: %v; retrying in %v", err, tempDelay)
  326. time.Sleep(tempDelay)
  327. continue
  328. }
  329. logger.Warn(logSender, "", "unrecoverable accept error: %v", err)
  330. return err
  331. }
  332. tempDelay = 0
  333. go c.AcceptInboundConnection(conn, serverConfig)
  334. }
  335. }
  336. func (c *Configuration) configureSecurityOptions(serverConfig *ssh.ServerConfig) error {
  337. if len(c.HostKeyAlgorithms) == 0 {
  338. c.HostKeyAlgorithms = preferredHostKeyAlgos
  339. } else {
  340. c.HostKeyAlgorithms = util.RemoveDuplicates(c.HostKeyAlgorithms, true)
  341. }
  342. for _, hostKeyAlgo := range c.HostKeyAlgorithms {
  343. if !util.Contains(supportedHostKeyAlgos, hostKeyAlgo) {
  344. return fmt.Errorf("unsupported host key algorithm %#v", hostKeyAlgo)
  345. }
  346. }
  347. serverConfig.HostKeyAlgorithms = c.HostKeyAlgorithms
  348. if len(c.KexAlgorithms) > 0 {
  349. c.KexAlgorithms = util.RemoveDuplicates(c.KexAlgorithms, true)
  350. for _, kex := range c.KexAlgorithms {
  351. if !util.Contains(supportedKexAlgos, kex) {
  352. return fmt.Errorf("unsupported key-exchange algorithm %#v", kex)
  353. }
  354. }
  355. serverConfig.KeyExchanges = c.KexAlgorithms
  356. }
  357. if len(c.Ciphers) > 0 {
  358. c.Ciphers = util.RemoveDuplicates(c.Ciphers, true)
  359. for _, cipher := range c.Ciphers {
  360. if !util.Contains(supportedCiphers, cipher) {
  361. return fmt.Errorf("unsupported cipher %#v", cipher)
  362. }
  363. }
  364. serverConfig.Ciphers = c.Ciphers
  365. }
  366. if len(c.MACs) > 0 {
  367. c.MACs = util.RemoveDuplicates(c.MACs, true)
  368. for _, mac := range c.MACs {
  369. if !util.Contains(supportedMACs, mac) {
  370. return fmt.Errorf("unsupported MAC algorithm %#v", mac)
  371. }
  372. }
  373. serverConfig.MACs = c.MACs
  374. }
  375. return nil
  376. }
  377. func (c *Configuration) configureLoginBanner(serverConfig *ssh.ServerConfig, configDir string) {
  378. if len(c.LoginBannerFile) > 0 {
  379. bannerFilePath := c.LoginBannerFile
  380. if !filepath.IsAbs(bannerFilePath) {
  381. bannerFilePath = filepath.Join(configDir, bannerFilePath)
  382. }
  383. bannerContent, err := os.ReadFile(bannerFilePath)
  384. if err == nil {
  385. banner := string(bannerContent)
  386. serverConfig.BannerCallback = func(conn ssh.ConnMetadata) string {
  387. return banner
  388. }
  389. } else {
  390. logger.WarnToConsole("unable to read SFTPD login banner file: %v", err)
  391. logger.Warn(logSender, "", "unable to read login banner file: %v", err)
  392. }
  393. }
  394. }
  395. func (c *Configuration) configureKeyboardInteractiveAuth(serverConfig *ssh.ServerConfig) {
  396. if !c.KeyboardInteractiveAuthentication {
  397. return
  398. }
  399. if c.KeyboardInteractiveHook != "" {
  400. if !strings.HasPrefix(c.KeyboardInteractiveHook, "http") {
  401. if !filepath.IsAbs(c.KeyboardInteractiveHook) {
  402. logger.WarnToConsole("invalid keyboard interactive authentication program: %#v must be an absolute path",
  403. c.KeyboardInteractiveHook)
  404. logger.Warn(logSender, "", "invalid keyboard interactive authentication program: %#v must be an absolute path",
  405. c.KeyboardInteractiveHook)
  406. return
  407. }
  408. _, err := os.Stat(c.KeyboardInteractiveHook)
  409. if err != nil {
  410. logger.WarnToConsole("invalid keyboard interactive authentication program:: %v", err)
  411. logger.Warn(logSender, "", "invalid keyboard interactive authentication program:: %v", err)
  412. return
  413. }
  414. }
  415. }
  416. serverConfig.KeyboardInteractiveCallback = func(conn ssh.ConnMetadata, client ssh.KeyboardInteractiveChallenge) (*ssh.Permissions, error) {
  417. sp, err := c.validateKeyboardInteractiveCredentials(conn, client)
  418. if err != nil {
  419. return nil, &authenticationError{err: fmt.Sprintf("could not validate keyboard interactive credentials: %v", err)}
  420. }
  421. return sp, nil
  422. }
  423. serviceStatus.Authentications = append(serviceStatus.Authentications, dataprovider.SSHLoginMethodKeyboardInteractive)
  424. }
  425. func canAcceptConnection(ip string) bool {
  426. if common.IsBanned(ip) {
  427. logger.Log(logger.LevelDebug, common.ProtocolSSH, "", "connection refused, ip %#v is banned", ip)
  428. return false
  429. }
  430. if !common.Connections.IsNewConnectionAllowed(ip) {
  431. logger.Log(logger.LevelDebug, common.ProtocolSSH, "", fmt.Sprintf("connection not allowed from ip %#v", ip))
  432. return false
  433. }
  434. _, err := common.LimitRate(common.ProtocolSSH, ip)
  435. if err != nil {
  436. return false
  437. }
  438. if err := common.Config.ExecutePostConnectHook(ip, common.ProtocolSSH); err != nil {
  439. return false
  440. }
  441. return true
  442. }
  443. // AcceptInboundConnection handles an inbound connection to the server instance and determines if the request should be served or not.
  444. func (c *Configuration) AcceptInboundConnection(conn net.Conn, config *ssh.ServerConfig) {
  445. defer func() {
  446. if r := recover(); r != nil {
  447. logger.Error(logSender, "", "panic in AcceptInboundConnection: %#v stack trace: %v", r, string(debug.Stack()))
  448. }
  449. }()
  450. ipAddr := util.GetIPFromRemoteAddress(conn.RemoteAddr().String())
  451. common.Connections.AddClientConnection(ipAddr)
  452. defer common.Connections.RemoveClientConnection(ipAddr)
  453. if !canAcceptConnection(ipAddr) {
  454. conn.Close()
  455. return
  456. }
  457. // Before beginning a handshake must be performed on the incoming net.Conn
  458. // we'll set a Deadline for handshake to complete, the default is 2 minutes as OpenSSH
  459. conn.SetDeadline(time.Now().Add(handshakeTimeout)) //nolint:errcheck
  460. sconn, chans, reqs, err := ssh.NewServerConn(conn, config)
  461. if err != nil {
  462. logger.Debug(logSender, "", "failed to accept an incoming connection: %v", err)
  463. checkAuthError(ipAddr, err)
  464. return
  465. }
  466. // handshake completed so remove the deadline, we'll use IdleTimeout configuration from now on
  467. conn.SetDeadline(time.Time{}) //nolint:errcheck
  468. defer conn.Close()
  469. var user dataprovider.User
  470. // Unmarshal cannot fails here and even if it fails we'll have a user with no permissions
  471. json.Unmarshal([]byte(sconn.Permissions.Extensions["sftpgo_user"]), &user) //nolint:errcheck
  472. loginType := sconn.Permissions.Extensions["sftpgo_login_method"]
  473. connectionID := hex.EncodeToString(sconn.SessionID())
  474. if err = user.CheckFsRoot(connectionID); err != nil {
  475. errClose := user.CloseFs()
  476. logger.Warn(logSender, connectionID, "unable to check fs root: %v close fs error: %v", err, errClose)
  477. return
  478. }
  479. defer user.CloseFs() //nolint:errcheck
  480. logger.Log(logger.LevelInfo, common.ProtocolSSH, connectionID,
  481. "User %#v logged in with %#v, from ip %#v, client version %#v", user.Username, loginType,
  482. ipAddr, string(sconn.ClientVersion()))
  483. dataprovider.UpdateLastLogin(&user)
  484. sshConnection := common.NewSSHConnection(connectionID, conn)
  485. common.Connections.AddSSHConnection(sshConnection)
  486. defer common.Connections.RemoveSSHConnection(connectionID)
  487. go ssh.DiscardRequests(reqs)
  488. channelCounter := int64(0)
  489. for newChannel := range chans {
  490. // If its not a session channel we just move on because its not something we
  491. // know how to handle at this point.
  492. if newChannel.ChannelType() != "session" {
  493. logger.Log(logger.LevelDebug, common.ProtocolSSH, connectionID, "received an unknown channel type: %v",
  494. newChannel.ChannelType())
  495. newChannel.Reject(ssh.UnknownChannelType, "unknown channel type") //nolint:errcheck
  496. continue
  497. }
  498. channel, requests, err := newChannel.Accept()
  499. if err != nil {
  500. logger.Log(logger.LevelWarn, common.ProtocolSSH, connectionID, "could not accept a channel: %v", err)
  501. continue
  502. }
  503. channelCounter++
  504. sshConnection.UpdateLastActivity()
  505. // Channels have a type that is dependent on the protocol. For SFTP this is "subsystem"
  506. // with a payload that (should) be "sftp". Discard anything else we receive ("pty", "shell", etc)
  507. go func(in <-chan *ssh.Request, counter int64) {
  508. for req := range in {
  509. ok := false
  510. connID := fmt.Sprintf("%s_%d", connectionID, counter)
  511. switch req.Type {
  512. case "subsystem":
  513. if string(req.Payload[4:]) == "sftp" {
  514. ok = true
  515. connection := &Connection{
  516. BaseConnection: common.NewBaseConnection(connID, common.ProtocolSFTP, conn.LocalAddr().String(),
  517. conn.RemoteAddr().String(), user),
  518. ClientVersion: string(sconn.ClientVersion()),
  519. RemoteAddr: conn.RemoteAddr(),
  520. LocalAddr: conn.LocalAddr(),
  521. channel: channel,
  522. folderPrefix: c.FolderPrefix,
  523. }
  524. go c.handleSftpConnection(channel, connection)
  525. }
  526. case "exec":
  527. // protocol will be set later inside processSSHCommand it could be SSH or SCP
  528. connection := Connection{
  529. BaseConnection: common.NewBaseConnection(connID, "sshd_exec", conn.LocalAddr().String(),
  530. conn.RemoteAddr().String(), user),
  531. ClientVersion: string(sconn.ClientVersion()),
  532. RemoteAddr: conn.RemoteAddr(),
  533. LocalAddr: conn.LocalAddr(),
  534. channel: channel,
  535. folderPrefix: c.FolderPrefix,
  536. }
  537. ok = processSSHCommand(req.Payload, &connection, c.EnabledSSHCommands)
  538. }
  539. if req.WantReply {
  540. req.Reply(ok, nil) //nolint:errcheck
  541. }
  542. }
  543. }(requests, channelCounter)
  544. }
  545. }
  546. func (c *Configuration) handleSftpConnection(channel ssh.Channel, connection *Connection) {
  547. defer func() {
  548. if r := recover(); r != nil {
  549. logger.Error(logSender, "", "panic in handleSftpConnection: %#v stack trace: %v", r, string(debug.Stack()))
  550. }
  551. }()
  552. if err := common.Connections.Add(connection); err != nil {
  553. errClose := connection.Disconnect()
  554. logger.Info(logSender, "", "unable to add connection: %v, close err: %v", err, errClose)
  555. return
  556. }
  557. defer common.Connections.Remove(connection.GetID())
  558. // Create the server instance for the channel using the handler we created above.
  559. server := sftp.NewRequestServer(channel, c.createHandlers(connection), sftp.WithRSAllocator(),
  560. sftp.WithStartDirectory(connection.User.Filters.StartDirectory))
  561. defer server.Close()
  562. if err := server.Serve(); errors.Is(err, io.EOF) {
  563. exitStatus := sshSubsystemExitStatus{Status: uint32(0)}
  564. _, err = channel.SendRequest("exit-status", false, ssh.Marshal(&exitStatus))
  565. connection.Log(logger.LevelInfo, "connection closed, sent exit status %+v error: %v", exitStatus, err)
  566. } else if err != nil {
  567. connection.Log(logger.LevelError, "connection closed with error: %v", err)
  568. }
  569. }
  570. func (c *Configuration) createHandlers(connection *Connection) sftp.Handlers {
  571. if c.FolderPrefix != "" {
  572. prefixMiddleware := newPrefixMiddleware(c.FolderPrefix, connection)
  573. return sftp.Handlers{
  574. FileGet: prefixMiddleware,
  575. FilePut: prefixMiddleware,
  576. FileCmd: prefixMiddleware,
  577. FileList: prefixMiddleware,
  578. }
  579. }
  580. return sftp.Handlers{
  581. FileGet: connection,
  582. FilePut: connection,
  583. FileCmd: connection,
  584. FileList: connection,
  585. }
  586. }
  587. func checkAuthError(ip string, err error) {
  588. if authErrors, ok := err.(*ssh.ServerAuthError); ok {
  589. // check public key auth errors here
  590. for _, err := range authErrors.Errors {
  591. if err != nil {
  592. // these checks should be improved, we should check for error type and not error strings
  593. if strings.Contains(err.Error(), "public key credentials") {
  594. event := common.HostEventLoginFailed
  595. if strings.Contains(err.Error(), "not found") {
  596. event = common.HostEventUserNotFound
  597. }
  598. common.AddDefenderEvent(ip, event)
  599. break
  600. }
  601. }
  602. }
  603. } else {
  604. logger.ConnectionFailedLog("", ip, dataprovider.LoginMethodNoAuthTryed, common.ProtocolSSH, err.Error())
  605. metric.AddNoAuthTryed()
  606. common.AddDefenderEvent(ip, common.HostEventNoLoginTried)
  607. dataprovider.ExecutePostLoginHook(&dataprovider.User{}, dataprovider.LoginMethodNoAuthTryed, ip, common.ProtocolSSH, err)
  608. }
  609. }
  610. func loginUser(user *dataprovider.User, loginMethod, publicKey string, conn ssh.ConnMetadata) (*ssh.Permissions, error) {
  611. connectionID := ""
  612. if conn != nil {
  613. connectionID = hex.EncodeToString(conn.SessionID())
  614. }
  615. if !filepath.IsAbs(user.HomeDir) {
  616. logger.Warn(logSender, connectionID, "user %#v has an invalid home dir: %#v. Home dir must be an absolute path, login not allowed",
  617. user.Username, user.HomeDir)
  618. return nil, fmt.Errorf("cannot login user with invalid home dir: %#v", user.HomeDir)
  619. }
  620. if util.Contains(user.Filters.DeniedProtocols, common.ProtocolSSH) {
  621. logger.Info(logSender, connectionID, "cannot login user %#v, protocol SSH is not allowed", user.Username)
  622. return nil, fmt.Errorf("protocol SSH is not allowed for user %#v", user.Username)
  623. }
  624. if user.MaxSessions > 0 {
  625. activeSessions := common.Connections.GetActiveSessions(user.Username)
  626. if activeSessions >= user.MaxSessions {
  627. logger.Info(logSender, "", "authentication refused for user: %#v, too many open sessions: %v/%v", user.Username,
  628. activeSessions, user.MaxSessions)
  629. return nil, fmt.Errorf("too many open sessions: %v", activeSessions)
  630. }
  631. }
  632. if !user.IsLoginMethodAllowed(loginMethod, common.ProtocolSSH, conn.PartialSuccessMethods()) {
  633. logger.Info(logSender, connectionID, "cannot login user %#v, login method %#v is not allowed",
  634. user.Username, loginMethod)
  635. return nil, fmt.Errorf("login method %#v is not allowed for user %#v", loginMethod, user.Username)
  636. }
  637. if user.MustSetSecondFactorForProtocol(common.ProtocolSSH) {
  638. logger.Info(logSender, connectionID, "cannot login user %#v, second factor authentication is not set",
  639. user.Username)
  640. return nil, fmt.Errorf("second factor authentication is not set for user %#v", user.Username)
  641. }
  642. remoteAddr := conn.RemoteAddr().String()
  643. if !user.IsLoginFromAddrAllowed(remoteAddr) {
  644. logger.Info(logSender, connectionID, "cannot login user %#v, remote address is not allowed: %v",
  645. user.Username, remoteAddr)
  646. return nil, fmt.Errorf("login for user %#v is not allowed from this address: %v", user.Username, remoteAddr)
  647. }
  648. json, err := json.Marshal(user)
  649. if err != nil {
  650. logger.Warn(logSender, connectionID, "error serializing user info: %v, authentication rejected", err)
  651. return nil, err
  652. }
  653. if publicKey != "" {
  654. loginMethod = fmt.Sprintf("%v: %v", loginMethod, publicKey)
  655. }
  656. p := &ssh.Permissions{}
  657. p.Extensions = make(map[string]string)
  658. p.Extensions["sftpgo_user"] = string(json)
  659. p.Extensions["sftpgo_login_method"] = loginMethod
  660. return p, nil
  661. }
  662. func (c *Configuration) checkSSHCommands() {
  663. if util.Contains(c.EnabledSSHCommands, "*") {
  664. c.EnabledSSHCommands = GetSupportedSSHCommands()
  665. return
  666. }
  667. sshCommands := []string{}
  668. for _, command := range c.EnabledSSHCommands {
  669. command = strings.TrimSpace(command)
  670. if util.Contains(supportedSSHCommands, command) {
  671. sshCommands = append(sshCommands, command)
  672. } else {
  673. logger.Warn(logSender, "", "unsupported ssh command: %#v ignored", command)
  674. logger.WarnToConsole("unsupported ssh command: %#v ignored", command)
  675. }
  676. }
  677. c.EnabledSSHCommands = sshCommands
  678. logger.Debug(logSender, "", "enabled SSH commands %v", c.EnabledSSHCommands)
  679. }
  680. func (c *Configuration) checkFolderPrefix() {
  681. if c.FolderPrefix != "" {
  682. c.FolderPrefix = path.Join("/", c.FolderPrefix)
  683. if c.FolderPrefix == "/" {
  684. c.FolderPrefix = ""
  685. }
  686. }
  687. if c.FolderPrefix != "" {
  688. c.EnabledSSHCommands = nil
  689. logger.Debug(logSender, "", "folder prefix %#v configured, SSH commands are disabled", c.FolderPrefix)
  690. }
  691. }
  692. func (c *Configuration) generateDefaultHostKeys(configDir string) error {
  693. var err error
  694. defaultHostKeys := []string{defaultPrivateRSAKeyName, defaultPrivateECDSAKeyName, defaultPrivateEd25519KeyName}
  695. for _, k := range defaultHostKeys {
  696. autoFile := filepath.Join(configDir, k)
  697. if _, err = os.Stat(autoFile); errors.Is(err, fs.ErrNotExist) {
  698. logger.Info(logSender, "", "No host keys configured and %#v does not exist; try to create a new host key", autoFile)
  699. logger.InfoToConsole("No host keys configured and %#v does not exist; try to create a new host key", autoFile)
  700. if k == defaultPrivateRSAKeyName {
  701. err = util.GenerateRSAKeys(autoFile)
  702. } else if k == defaultPrivateECDSAKeyName {
  703. err = util.GenerateECDSAKeys(autoFile)
  704. } else {
  705. err = util.GenerateEd25519Keys(autoFile)
  706. }
  707. if err != nil {
  708. logger.Warn(logSender, "", "error creating host key %#v: %v", autoFile, err)
  709. logger.WarnToConsole("error creating host key %#v: %v", autoFile, err)
  710. return err
  711. }
  712. }
  713. c.HostKeys = append(c.HostKeys, k)
  714. }
  715. return err
  716. }
  717. func (c *Configuration) checkHostKeyAutoGeneration(configDir string) error {
  718. for _, k := range c.HostKeys {
  719. k = strings.TrimSpace(k)
  720. if filepath.IsAbs(k) {
  721. if _, err := os.Stat(k); errors.Is(err, fs.ErrNotExist) {
  722. keyName := filepath.Base(k)
  723. switch keyName {
  724. case defaultPrivateRSAKeyName:
  725. logger.Info(logSender, "", "try to create non-existent host key %#v", k)
  726. logger.InfoToConsole("try to create non-existent host key %#v", k)
  727. err = util.GenerateRSAKeys(k)
  728. if err != nil {
  729. logger.Warn(logSender, "", "error creating host key %#v: %v", k, err)
  730. logger.WarnToConsole("error creating host key %#v: %v", k, err)
  731. return err
  732. }
  733. case defaultPrivateECDSAKeyName:
  734. logger.Info(logSender, "", "try to create non-existent host key %#v", k)
  735. logger.InfoToConsole("try to create non-existent host key %#v", k)
  736. err = util.GenerateECDSAKeys(k)
  737. if err != nil {
  738. logger.Warn(logSender, "", "error creating host key %#v: %v", k, err)
  739. logger.WarnToConsole("error creating host key %#v: %v", k, err)
  740. return err
  741. }
  742. case defaultPrivateEd25519KeyName:
  743. logger.Info(logSender, "", "try to create non-existent host key %#v", k)
  744. logger.InfoToConsole("try to create non-existent host key %#v", k)
  745. err = util.GenerateEd25519Keys(k)
  746. if err != nil {
  747. logger.Warn(logSender, "", "error creating host key %#v: %v", k, err)
  748. logger.WarnToConsole("error creating host key %#v: %v", k, err)
  749. return err
  750. }
  751. default:
  752. logger.Warn(logSender, "", "non-existent host key %#v will not be created", k)
  753. logger.WarnToConsole("non-existent host key %#v will not be created", k)
  754. }
  755. }
  756. }
  757. }
  758. if len(c.HostKeys) == 0 {
  759. if err := c.generateDefaultHostKeys(configDir); err != nil {
  760. return err
  761. }
  762. }
  763. return nil
  764. }
  765. // If no host keys are defined we try to use or generate the default ones.
  766. func (c *Configuration) checkAndLoadHostKeys(configDir string, serverConfig *ssh.ServerConfig) error {
  767. if err := c.checkHostKeyAutoGeneration(configDir); err != nil {
  768. return err
  769. }
  770. hostCertificates, err := c.loadHostCertificates(configDir)
  771. if err != nil {
  772. return err
  773. }
  774. serviceStatus.HostKeys = nil
  775. for _, hostKey := range c.HostKeys {
  776. hostKey = strings.TrimSpace(hostKey)
  777. if !util.IsFileInputValid(hostKey) {
  778. logger.Warn(logSender, "", "unable to load invalid host key %#v", hostKey)
  779. logger.WarnToConsole("unable to load invalid host key %#v", hostKey)
  780. continue
  781. }
  782. if !filepath.IsAbs(hostKey) {
  783. hostKey = filepath.Join(configDir, hostKey)
  784. }
  785. logger.Info(logSender, "", "Loading private host key %#v", hostKey)
  786. privateBytes, err := os.ReadFile(hostKey)
  787. if err != nil {
  788. return err
  789. }
  790. private, err := ssh.ParsePrivateKey(privateBytes)
  791. if err != nil {
  792. return err
  793. }
  794. k := HostKey{
  795. Path: hostKey,
  796. Fingerprint: ssh.FingerprintSHA256(private.PublicKey()),
  797. }
  798. serviceStatus.HostKeys = append(serviceStatus.HostKeys, k)
  799. logger.Info(logSender, "", "Host key %#v loaded, type %#v, fingerprint %#v", hostKey,
  800. private.PublicKey().Type(), k.Fingerprint)
  801. // Add private key to the server configuration.
  802. serverConfig.AddHostKey(private)
  803. for _, cert := range hostCertificates {
  804. signer, err := ssh.NewCertSigner(cert, private)
  805. if err == nil {
  806. serverConfig.AddHostKey(signer)
  807. logger.Info(logSender, "", "Host certificate loaded for host key %#v, fingerprint %#v",
  808. hostKey, ssh.FingerprintSHA256(signer.PublicKey()))
  809. }
  810. }
  811. }
  812. var fp []string
  813. for idx := range serviceStatus.HostKeys {
  814. h := &serviceStatus.HostKeys[idx]
  815. fp = append(fp, h.Fingerprint)
  816. }
  817. vfs.SetSFTPFingerprints(fp)
  818. return nil
  819. }
  820. func (c *Configuration) loadHostCertificates(configDir string) ([]*ssh.Certificate, error) {
  821. var certs []*ssh.Certificate
  822. for _, certPath := range c.HostCertificates {
  823. certPath = strings.TrimSpace(certPath)
  824. if !util.IsFileInputValid(certPath) {
  825. logger.Warn(logSender, "", "unable to load invalid host certificate %#v", certPath)
  826. logger.WarnToConsole("unable to load invalid host certificate %#v", certPath)
  827. continue
  828. }
  829. if !filepath.IsAbs(certPath) {
  830. certPath = filepath.Join(configDir, certPath)
  831. }
  832. certBytes, err := os.ReadFile(certPath)
  833. if err != nil {
  834. return certs, fmt.Errorf("unable to load host certificate %#v: %w", certPath, err)
  835. }
  836. parsed, _, _, _, err := ssh.ParseAuthorizedKey(certBytes)
  837. if err != nil {
  838. return nil, fmt.Errorf("unable to parse host certificate %#v: %w", certPath, err)
  839. }
  840. cert, ok := parsed.(*ssh.Certificate)
  841. if !ok {
  842. return nil, fmt.Errorf("the file %#v is not an SSH certificate", certPath)
  843. }
  844. if cert.CertType != ssh.HostCert {
  845. return nil, fmt.Errorf("the file %#v is not an host certificate", certPath)
  846. }
  847. certs = append(certs, cert)
  848. }
  849. return certs, nil
  850. }
  851. func (c *Configuration) initializeCertChecker(configDir string) error {
  852. for _, keyPath := range c.TrustedUserCAKeys {
  853. keyPath = strings.TrimSpace(keyPath)
  854. if !util.IsFileInputValid(keyPath) {
  855. logger.Warn(logSender, "", "unable to load invalid trusted user CA key %#v", keyPath)
  856. logger.WarnToConsole("unable to load invalid trusted user CA key %#v", keyPath)
  857. continue
  858. }
  859. if !filepath.IsAbs(keyPath) {
  860. keyPath = filepath.Join(configDir, keyPath)
  861. }
  862. keyBytes, err := os.ReadFile(keyPath)
  863. if err != nil {
  864. logger.Warn(logSender, "", "error loading trusted user CA key %#v: %v", keyPath, err)
  865. logger.WarnToConsole("error loading trusted user CA key %#v: %v", keyPath, err)
  866. return err
  867. }
  868. parsedKey, _, _, _, err := ssh.ParseAuthorizedKey(keyBytes)
  869. if err != nil {
  870. logger.Warn(logSender, "", "error parsing trusted user CA key %#v: %v", keyPath, err)
  871. logger.WarnToConsole("error parsing trusted user CA key %#v: %v", keyPath, err)
  872. return err
  873. }
  874. c.parsedUserCAKeys = append(c.parsedUserCAKeys, parsedKey)
  875. }
  876. c.certChecker = &ssh.CertChecker{
  877. SupportedCriticalOptions: []string{
  878. sourceAddressCriticalOption,
  879. },
  880. IsUserAuthority: func(k ssh.PublicKey) bool {
  881. for _, key := range c.parsedUserCAKeys {
  882. if bytes.Equal(k.Marshal(), key.Marshal()) {
  883. return true
  884. }
  885. }
  886. return false
  887. },
  888. }
  889. if c.RevokedUserCertsFile != "" {
  890. if !util.IsFileInputValid(c.RevokedUserCertsFile) {
  891. return fmt.Errorf("invalid revoked user certificate: %#v", c.RevokedUserCertsFile)
  892. }
  893. if !filepath.IsAbs(c.RevokedUserCertsFile) {
  894. c.RevokedUserCertsFile = filepath.Join(configDir, c.RevokedUserCertsFile)
  895. }
  896. }
  897. revokedCertManager.filePath = c.RevokedUserCertsFile
  898. return revokedCertManager.load()
  899. }
  900. func (c *Configuration) validatePublicKeyCredentials(conn ssh.ConnMetadata, pubKey ssh.PublicKey) (*ssh.Permissions, error) {
  901. var err error
  902. var user dataprovider.User
  903. var keyID string
  904. var sshPerm *ssh.Permissions
  905. var certPerm *ssh.Permissions
  906. connectionID := hex.EncodeToString(conn.SessionID())
  907. method := dataprovider.SSHLoginMethodPublicKey
  908. ipAddr := util.GetIPFromRemoteAddress(conn.RemoteAddr().String())
  909. cert, ok := pubKey.(*ssh.Certificate)
  910. var certFingerprint string
  911. if ok {
  912. certFingerprint = ssh.FingerprintSHA256(cert.Key)
  913. if cert.CertType != ssh.UserCert {
  914. err = fmt.Errorf("ssh: cert has type %d", cert.CertType)
  915. user.Username = conn.User()
  916. updateLoginMetrics(&user, ipAddr, method, err)
  917. return nil, err
  918. }
  919. if !c.certChecker.IsUserAuthority(cert.SignatureKey) {
  920. err = errors.New("ssh: certificate signed by unrecognized authority")
  921. user.Username = conn.User()
  922. updateLoginMetrics(&user, ipAddr, method, err)
  923. return nil, err
  924. }
  925. if len(cert.ValidPrincipals) == 0 {
  926. err = fmt.Errorf("ssh: certificate %s has no valid principals, user: \"%s\"", certFingerprint, conn.User())
  927. user.Username = conn.User()
  928. updateLoginMetrics(&user, ipAddr, method, err)
  929. return nil, err
  930. }
  931. if revokedCertManager.isRevoked(certFingerprint) {
  932. err = fmt.Errorf("ssh: certificate %s is revoked", certFingerprint)
  933. user.Username = conn.User()
  934. updateLoginMetrics(&user, ipAddr, method, err)
  935. return nil, err
  936. }
  937. if err := c.certChecker.CheckCert(conn.User(), cert); err != nil {
  938. user.Username = conn.User()
  939. updateLoginMetrics(&user, ipAddr, method, err)
  940. return nil, err
  941. }
  942. certPerm = &cert.Permissions
  943. }
  944. if user, keyID, err = dataprovider.CheckUserAndPubKey(conn.User(), pubKey.Marshal(), ipAddr, common.ProtocolSSH, ok); err == nil {
  945. if ok {
  946. keyID = fmt.Sprintf("%s: ID: %s, serial: %v, CA %s %s", certFingerprint,
  947. cert.KeyId, cert.Serial, cert.Type(), ssh.FingerprintSHA256(cert.SignatureKey))
  948. }
  949. if user.IsPartialAuth(method) {
  950. logger.Debug(logSender, connectionID, "user %#v authenticated with partial success", conn.User())
  951. return certPerm, ssh.ErrPartialSuccess
  952. }
  953. sshPerm, err = loginUser(&user, method, keyID, conn)
  954. if err == nil && certPerm != nil {
  955. // if we have a SSH user cert we need to merge certificate permissions with our ones
  956. // we only set Extensions, so CriticalOptions are always the ones from the certificate
  957. sshPerm.CriticalOptions = certPerm.CriticalOptions
  958. if certPerm.Extensions != nil {
  959. for k, v := range certPerm.Extensions {
  960. sshPerm.Extensions[k] = v
  961. }
  962. }
  963. }
  964. }
  965. user.Username = conn.User()
  966. updateLoginMetrics(&user, ipAddr, method, err)
  967. return sshPerm, err
  968. }
  969. func (c *Configuration) validatePasswordCredentials(conn ssh.ConnMetadata, pass []byte) (*ssh.Permissions, error) {
  970. var err error
  971. var user dataprovider.User
  972. var sshPerm *ssh.Permissions
  973. method := dataprovider.LoginMethodPassword
  974. if len(conn.PartialSuccessMethods()) == 1 {
  975. method = dataprovider.SSHLoginMethodKeyAndPassword
  976. }
  977. ipAddr := util.GetIPFromRemoteAddress(conn.RemoteAddr().String())
  978. if user, err = dataprovider.CheckUserAndPass(conn.User(), string(pass), ipAddr, common.ProtocolSSH); err == nil {
  979. sshPerm, err = loginUser(&user, method, "", conn)
  980. }
  981. user.Username = conn.User()
  982. updateLoginMetrics(&user, ipAddr, method, err)
  983. return sshPerm, err
  984. }
  985. func (c *Configuration) validateKeyboardInteractiveCredentials(conn ssh.ConnMetadata, client ssh.KeyboardInteractiveChallenge) (*ssh.Permissions, error) {
  986. var err error
  987. var user dataprovider.User
  988. var sshPerm *ssh.Permissions
  989. method := dataprovider.SSHLoginMethodKeyboardInteractive
  990. if len(conn.PartialSuccessMethods()) == 1 {
  991. method = dataprovider.SSHLoginMethodKeyAndKeyboardInt
  992. }
  993. ipAddr := util.GetIPFromRemoteAddress(conn.RemoteAddr().String())
  994. if user, err = dataprovider.CheckKeyboardInteractiveAuth(conn.User(), c.KeyboardInteractiveHook, client,
  995. ipAddr, common.ProtocolSSH); err == nil {
  996. sshPerm, err = loginUser(&user, method, "", conn)
  997. }
  998. user.Username = conn.User()
  999. updateLoginMetrics(&user, ipAddr, method, err)
  1000. return sshPerm, err
  1001. }
  1002. func updateLoginMetrics(user *dataprovider.User, ip, method string, err error) {
  1003. metric.AddLoginAttempt(method)
  1004. if err != nil {
  1005. logger.ConnectionFailedLog(user.Username, ip, method, common.ProtocolSSH, err.Error())
  1006. if method != dataprovider.SSHLoginMethodPublicKey {
  1007. // some clients try all available public keys for a user, we
  1008. // record failed login key auth only once for session if the
  1009. // authentication fails in checkAuthError
  1010. event := common.HostEventLoginFailed
  1011. if _, ok := err.(*util.RecordNotFoundError); ok {
  1012. event = common.HostEventUserNotFound
  1013. }
  1014. common.AddDefenderEvent(ip, event)
  1015. }
  1016. }
  1017. metric.AddLoginResult(method, err)
  1018. dataprovider.ExecutePostLoginHook(user, method, ip, common.ProtocolSSH, err)
  1019. }
  1020. type revokedCertificates struct {
  1021. filePath string
  1022. mu sync.RWMutex
  1023. certs map[string]bool
  1024. }
  1025. func (r *revokedCertificates) load() error {
  1026. if r.filePath == "" {
  1027. return nil
  1028. }
  1029. logger.Debug(logSender, "", "loading revoked user certificate file %#v", r.filePath)
  1030. info, err := os.Stat(r.filePath)
  1031. if err != nil {
  1032. return fmt.Errorf("unable to load revoked user certificate file %#v: %w", r.filePath, err)
  1033. }
  1034. maxSize := int64(1048576 * 5) // 5MB
  1035. if info.Size() > maxSize {
  1036. return fmt.Errorf("unable to load revoked user certificate file %#v size too big: %v/%v bytes",
  1037. r.filePath, info.Size(), maxSize)
  1038. }
  1039. content, err := os.ReadFile(r.filePath)
  1040. if err != nil {
  1041. return fmt.Errorf("unable to read revoked user certificate file %#v: %w", r.filePath, err)
  1042. }
  1043. var certs []string
  1044. err = json.Unmarshal(content, &certs)
  1045. if err != nil {
  1046. return fmt.Errorf("unable to parse revoked user certificate file %#v: %w", r.filePath, err)
  1047. }
  1048. r.mu.Lock()
  1049. defer r.mu.Unlock()
  1050. r.certs = map[string]bool{}
  1051. for _, fp := range certs {
  1052. r.certs[fp] = true
  1053. }
  1054. logger.Debug(logSender, "", "revoked user certificate file %#v loaded, entries: %v", r.filePath, len(r.certs))
  1055. return nil
  1056. }
  1057. func (r *revokedCertificates) isRevoked(fp string) bool {
  1058. r.mu.RLock()
  1059. defer r.mu.RUnlock()
  1060. return r.certs[fp]
  1061. }
  1062. // Reload reloads the list of revoked user certificates
  1063. func Reload() error {
  1064. return revokedCertManager.load()
  1065. }