server.go 42 KB

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