server.go 49 KB

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