server.go 47 KB

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