server.go 42 KB

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