server.go 42 KB

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