server.go 48 KB

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