1
0

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 err == ssh.ErrPartialSuccess {
  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. NextAuthMethodsCallback: func(conn ssh.ConnMetadata) []string {
  262. var nextMethods []string
  263. user, err := dataprovider.GetUserWithGroupSettings(conn.User(), "")
  264. if err == nil {
  265. nextMethods = user.GetNextAuthMethods(conn.PartialSuccessMethods(), c.PasswordAuthentication)
  266. }
  267. return nextMethods
  268. },
  269. ServerVersion: fmt.Sprintf("SSH-2.0-%s", c.Banner),
  270. }
  271. if c.PasswordAuthentication {
  272. serverConfig.PasswordCallback = func(conn ssh.ConnMetadata, pass []byte) (*ssh.Permissions, error) {
  273. sp, err := c.validatePasswordCredentials(conn, pass)
  274. if err != nil {
  275. return nil, newAuthenticationError(fmt.Errorf("could not validate password credentials: %w", err),
  276. dataprovider.SSHLoginMethodPassword)
  277. }
  278. return sp, nil
  279. }
  280. serviceStatus.Authentications = append(serviceStatus.Authentications, dataprovider.LoginMethodPassword)
  281. }
  282. serviceStatus.Authentications = append(serviceStatus.Authentications, dataprovider.SSHLoginMethodPublicKey)
  283. return serverConfig
  284. }
  285. func (c *Configuration) updateSupportedAuthentications() {
  286. serviceStatus.Authentications = util.RemoveDuplicates(serviceStatus.Authentications, false)
  287. if util.Contains(serviceStatus.Authentications, dataprovider.LoginMethodPassword) &&
  288. util.Contains(serviceStatus.Authentications, dataprovider.SSHLoginMethodPublicKey) {
  289. serviceStatus.Authentications = append(serviceStatus.Authentications, dataprovider.SSHLoginMethodKeyAndPassword)
  290. }
  291. if util.Contains(serviceStatus.Authentications, dataprovider.SSHLoginMethodKeyboardInteractive) &&
  292. util.Contains(serviceStatus.Authentications, dataprovider.SSHLoginMethodPublicKey) {
  293. serviceStatus.Authentications = append(serviceStatus.Authentications, dataprovider.SSHLoginMethodKeyAndKeyboardInt)
  294. }
  295. }
  296. func (c *Configuration) loadFromProvider() error {
  297. configs, err := dataprovider.GetConfigs()
  298. if err != nil {
  299. return fmt.Errorf("unable to load config from provider: %w", err)
  300. }
  301. configs.SetNilsToEmpty()
  302. if len(configs.SFTPD.HostKeyAlgos) > 0 {
  303. if len(c.HostKeyAlgorithms) == 0 {
  304. c.HostKeyAlgorithms = preferredHostKeyAlgos
  305. }
  306. c.HostKeyAlgorithms = append(c.HostKeyAlgorithms, configs.SFTPD.HostKeyAlgos...)
  307. }
  308. c.Moduli = append(c.Moduli, configs.SFTPD.Moduli...)
  309. if len(configs.SFTPD.KexAlgorithms) > 0 {
  310. if len(c.KexAlgorithms) == 0 {
  311. c.KexAlgorithms = preferredKexAlgos
  312. }
  313. c.KexAlgorithms = append(c.KexAlgorithms, configs.SFTPD.KexAlgorithms...)
  314. }
  315. if len(configs.SFTPD.Ciphers) > 0 {
  316. if len(c.Ciphers) == 0 {
  317. c.Ciphers = preferredCiphers
  318. }
  319. c.Ciphers = append(c.Ciphers, configs.SFTPD.Ciphers...)
  320. }
  321. if len(configs.SFTPD.MACs) > 0 {
  322. if len(c.MACs) == 0 {
  323. c.MACs = preferredMACs
  324. }
  325. c.MACs = append(c.MACs, configs.SFTPD.MACs...)
  326. }
  327. return nil
  328. }
  329. // Initialize the SFTP server and add a persistent listener to handle inbound SFTP connections.
  330. func (c *Configuration) Initialize(configDir string) error {
  331. if err := c.loadFromProvider(); err != nil {
  332. return fmt.Errorf("unable to load configs from provider: %w", err)
  333. }
  334. serviceStatus = ServiceStatus{}
  335. serverConfig := c.getServerConfig()
  336. if !c.ShouldBind() {
  337. return common.ErrNoBinding
  338. }
  339. if err := c.checkAndLoadHostKeys(configDir, serverConfig); err != nil {
  340. serviceStatus.HostKeys = nil
  341. return err
  342. }
  343. if err := c.initializeCertChecker(configDir); err != nil {
  344. return err
  345. }
  346. c.loadModuli(configDir)
  347. sftp.SetSFTPExtensions(sftpExtensions...) //nolint:errcheck // we configure valid SFTP Extensions so we cannot get an error
  348. if err := c.configureSecurityOptions(serverConfig); err != nil {
  349. return err
  350. }
  351. c.configureKeyboardInteractiveAuth(serverConfig)
  352. c.configureLoginBanner(serverConfig, configDir)
  353. c.checkSSHCommands()
  354. c.checkFolderPrefix()
  355. exitChannel := make(chan error, 1)
  356. serviceStatus.Bindings = nil
  357. for _, binding := range c.Bindings {
  358. if !binding.IsValid() {
  359. continue
  360. }
  361. serviceStatus.Bindings = append(serviceStatus.Bindings, binding)
  362. go func(binding Binding) {
  363. addr := binding.GetAddress()
  364. util.CheckTCP4Port(binding.Port)
  365. listener, err := net.Listen("tcp", addr)
  366. if err != nil {
  367. logger.Warn(logSender, "", "error starting listener on address %v: %v", addr, err)
  368. exitChannel <- err
  369. return
  370. }
  371. if binding.ApplyProxyConfig && common.Config.ProxyProtocol > 0 {
  372. proxyListener, err := common.Config.GetProxyListener(listener)
  373. if err != nil {
  374. logger.Warn(logSender, "", "error enabling proxy listener: %v", err)
  375. exitChannel <- err
  376. return
  377. }
  378. listener = proxyListener
  379. }
  380. exitChannel <- c.serve(listener, serverConfig)
  381. }(binding)
  382. }
  383. serviceStatus.IsActive = true
  384. serviceStatus.SSHCommands = c.EnabledSSHCommands
  385. c.updateSupportedAuthentications()
  386. return <-exitChannel
  387. }
  388. func (c *Configuration) serve(listener net.Listener, serverConfig *ssh.ServerConfig) error {
  389. logger.Info(logSender, "", "server listener registered, address: %s", listener.Addr().String())
  390. var tempDelay time.Duration // how long to sleep on accept failure
  391. for {
  392. conn, err := listener.Accept()
  393. if err != nil {
  394. // see https://github.com/golang/go/blob/4aa1efed4853ea067d665a952eee77c52faac774/src/net/http/server.go#L3046
  395. if ne, ok := err.(net.Error); ok && ne.Temporary() { //nolint:staticcheck
  396. if tempDelay == 0 {
  397. tempDelay = 5 * time.Millisecond
  398. } else {
  399. tempDelay *= 2
  400. }
  401. if max := 1 * time.Second; tempDelay > max {
  402. tempDelay = max
  403. }
  404. logger.Warn(logSender, "", "accept error: %v; retrying in %v", err, tempDelay)
  405. time.Sleep(tempDelay)
  406. continue
  407. }
  408. logger.Warn(logSender, "", "unrecoverable accept error: %v", err)
  409. return err
  410. }
  411. tempDelay = 0
  412. go c.AcceptInboundConnection(conn, serverConfig)
  413. }
  414. }
  415. func (c *Configuration) configureSecurityOptions(serverConfig *ssh.ServerConfig) error {
  416. if len(c.HostKeyAlgorithms) == 0 {
  417. c.HostKeyAlgorithms = preferredHostKeyAlgos
  418. } else {
  419. c.HostKeyAlgorithms = util.RemoveDuplicates(c.HostKeyAlgorithms, true)
  420. }
  421. for _, hostKeyAlgo := range c.HostKeyAlgorithms {
  422. if !util.Contains(supportedHostKeyAlgos, hostKeyAlgo) {
  423. return fmt.Errorf("unsupported host key algorithm %q", hostKeyAlgo)
  424. }
  425. }
  426. serverConfig.HostKeyAlgorithms = c.HostKeyAlgorithms
  427. serviceStatus.HostKeyAlgos = c.HostKeyAlgorithms
  428. if len(c.KexAlgorithms) > 0 {
  429. hasDHGroupKEX := util.Contains(supportedKexAlgos, kexDHGroupExchangeSHA256)
  430. if !hasDHGroupKEX {
  431. c.KexAlgorithms = util.Remove(c.KexAlgorithms, kexDHGroupExchangeSHA1)
  432. c.KexAlgorithms = util.Remove(c.KexAlgorithms, kexDHGroupExchangeSHA256)
  433. }
  434. c.KexAlgorithms = util.RemoveDuplicates(c.KexAlgorithms, true)
  435. for _, kex := range c.KexAlgorithms {
  436. if !util.Contains(supportedKexAlgos, kex) {
  437. return fmt.Errorf("unsupported key-exchange algorithm %q", kex)
  438. }
  439. }
  440. serverConfig.KeyExchanges = c.KexAlgorithms
  441. serviceStatus.KexAlgorithms = c.KexAlgorithms
  442. } else {
  443. serviceStatus.KexAlgorithms = preferredKexAlgos
  444. }
  445. if len(c.Ciphers) > 0 {
  446. c.Ciphers = util.RemoveDuplicates(c.Ciphers, true)
  447. for _, cipher := range c.Ciphers {
  448. if !util.Contains(supportedCiphers, cipher) {
  449. return fmt.Errorf("unsupported cipher %q", cipher)
  450. }
  451. }
  452. serverConfig.Ciphers = c.Ciphers
  453. serviceStatus.Ciphers = c.Ciphers
  454. } else {
  455. serviceStatus.Ciphers = preferredCiphers
  456. }
  457. if len(c.MACs) > 0 {
  458. c.MACs = util.RemoveDuplicates(c.MACs, true)
  459. for _, mac := range c.MACs {
  460. if !util.Contains(supportedMACs, mac) {
  461. return fmt.Errorf("unsupported MAC algorithm %q", mac)
  462. }
  463. }
  464. serverConfig.MACs = c.MACs
  465. serviceStatus.MACs = c.MACs
  466. } else {
  467. serviceStatus.MACs = preferredMACs
  468. }
  469. return nil
  470. }
  471. func (c *Configuration) configureLoginBanner(serverConfig *ssh.ServerConfig, configDir string) {
  472. if len(c.LoginBannerFile) > 0 {
  473. bannerFilePath := c.LoginBannerFile
  474. if !filepath.IsAbs(bannerFilePath) {
  475. bannerFilePath = filepath.Join(configDir, bannerFilePath)
  476. }
  477. bannerContent, err := os.ReadFile(bannerFilePath)
  478. if err == nil {
  479. banner := string(bannerContent)
  480. serverConfig.BannerCallback = func(conn ssh.ConnMetadata) string {
  481. return banner
  482. }
  483. } else {
  484. logger.WarnToConsole("unable to read SFTPD login banner file: %v", err)
  485. logger.Warn(logSender, "", "unable to read login banner file: %v", err)
  486. }
  487. }
  488. }
  489. func (c *Configuration) configureKeyboardInteractiveAuth(serverConfig *ssh.ServerConfig) {
  490. if !c.KeyboardInteractiveAuthentication {
  491. return
  492. }
  493. if c.KeyboardInteractiveHook != "" {
  494. if !strings.HasPrefix(c.KeyboardInteractiveHook, "http") {
  495. if !filepath.IsAbs(c.KeyboardInteractiveHook) {
  496. logger.WarnToConsole("invalid keyboard interactive authentication program: %q must be an absolute path",
  497. c.KeyboardInteractiveHook)
  498. logger.Warn(logSender, "", "invalid keyboard interactive authentication program: %q must be an absolute path",
  499. c.KeyboardInteractiveHook)
  500. return
  501. }
  502. _, err := os.Stat(c.KeyboardInteractiveHook)
  503. if err != nil {
  504. logger.WarnToConsole("invalid keyboard interactive authentication program:: %v", err)
  505. logger.Warn(logSender, "", "invalid keyboard interactive authentication program:: %v", err)
  506. return
  507. }
  508. }
  509. }
  510. serverConfig.KeyboardInteractiveCallback = func(conn ssh.ConnMetadata, client ssh.KeyboardInteractiveChallenge) (*ssh.Permissions, error) {
  511. sp, err := c.validateKeyboardInteractiveCredentials(conn, client)
  512. if err != nil {
  513. return nil, newAuthenticationError(fmt.Errorf("could not validate keyboard interactive credentials: %w", err),
  514. dataprovider.SSHLoginMethodKeyboardInteractive)
  515. }
  516. return sp, nil
  517. }
  518. serviceStatus.Authentications = append(serviceStatus.Authentications, dataprovider.SSHLoginMethodKeyboardInteractive)
  519. }
  520. // AcceptInboundConnection handles an inbound connection to the server instance and determines if the request should be served or not.
  521. func (c *Configuration) AcceptInboundConnection(conn net.Conn, config *ssh.ServerConfig) {
  522. defer func() {
  523. if r := recover(); r != nil {
  524. logger.Error(logSender, "", "panic in AcceptInboundConnection: %q stack trace: %v", r, string(debug.Stack()))
  525. }
  526. }()
  527. ipAddr := util.GetIPFromRemoteAddress(conn.RemoteAddr().String())
  528. common.Connections.AddClientConnection(ipAddr)
  529. defer common.Connections.RemoveClientConnection(ipAddr)
  530. if !canAcceptConnection(ipAddr) {
  531. conn.Close()
  532. return
  533. }
  534. // Before beginning a handshake must be performed on the incoming net.Conn
  535. // we'll set a Deadline for handshake to complete, the default is 2 minutes as OpenSSH
  536. conn.SetDeadline(time.Now().Add(handshakeTimeout)) //nolint:errcheck
  537. sconn, chans, reqs, err := ssh.NewServerConn(conn, config)
  538. if err != nil {
  539. logger.Debug(logSender, "", "failed to accept an incoming connection from ip %q: %v", ipAddr, err)
  540. checkAuthError(ipAddr, err)
  541. return
  542. }
  543. // handshake completed so remove the deadline, we'll use IdleTimeout configuration from now on
  544. conn.SetDeadline(time.Time{}) //nolint:errcheck
  545. go ssh.DiscardRequests(reqs)
  546. defer conn.Close()
  547. var user dataprovider.User
  548. // Unmarshal cannot fails here and even if it fails we'll have a user with no permissions
  549. json.Unmarshal([]byte(sconn.Permissions.Extensions["sftpgo_user"]), &user) //nolint:errcheck
  550. loginType := sconn.Permissions.Extensions["sftpgo_login_method"]
  551. connectionID := hex.EncodeToString(sconn.SessionID())
  552. defer user.CloseFs() //nolint:errcheck
  553. if err = user.CheckFsRoot(connectionID); err != nil {
  554. logger.Warn(logSender, connectionID, "unable to check fs root for user %q: %v", user.Username, err)
  555. go discardAllChannels(chans, "invalid root fs", connectionID)
  556. return
  557. }
  558. logger.Log(logger.LevelInfo, common.ProtocolSSH, connectionID,
  559. "User %q logged in with %q, from ip %q, client version %q", user.Username, loginType,
  560. ipAddr, string(sconn.ClientVersion()))
  561. dataprovider.UpdateLastLogin(&user)
  562. sshConnection := common.NewSSHConnection(connectionID, conn)
  563. common.Connections.AddSSHConnection(sshConnection)
  564. defer common.Connections.RemoveSSHConnection(connectionID)
  565. channelCounter := int64(0)
  566. for newChannel := range chans {
  567. // If its not a session channel we just move on because its not something we
  568. // know how to handle at this point.
  569. if newChannel.ChannelType() != "session" {
  570. logger.Log(logger.LevelDebug, common.ProtocolSSH, connectionID, "received an unknown channel type: %v",
  571. newChannel.ChannelType())
  572. newChannel.Reject(ssh.UnknownChannelType, "unknown channel type") //nolint:errcheck
  573. continue
  574. }
  575. channel, requests, err := newChannel.Accept()
  576. if err != nil {
  577. logger.Log(logger.LevelWarn, common.ProtocolSSH, connectionID, "could not accept a channel: %v", err)
  578. continue
  579. }
  580. channelCounter++
  581. sshConnection.UpdateLastActivity()
  582. // Channels have a type that is dependent on the protocol. For SFTP this is "subsystem"
  583. // with a payload that (should) be "sftp". Discard anything else we receive ("pty", "shell", etc)
  584. go func(in <-chan *ssh.Request, counter int64) {
  585. for req := range in {
  586. ok := false
  587. connID := fmt.Sprintf("%s_%d", connectionID, counter)
  588. switch req.Type {
  589. case "subsystem":
  590. if string(req.Payload[4:]) == "sftp" {
  591. ok = true
  592. connection := &Connection{
  593. BaseConnection: common.NewBaseConnection(connID, common.ProtocolSFTP, 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. go c.handleSftpConnection(channel, connection)
  602. }
  603. case "exec":
  604. // protocol will be set later inside processSSHCommand it could be SSH or SCP
  605. connection := Connection{
  606. BaseConnection: common.NewBaseConnection(connID, "sshd_exec", conn.LocalAddr().String(),
  607. conn.RemoteAddr().String(), user),
  608. ClientVersion: string(sconn.ClientVersion()),
  609. RemoteAddr: conn.RemoteAddr(),
  610. LocalAddr: conn.LocalAddr(),
  611. channel: channel,
  612. folderPrefix: c.FolderPrefix,
  613. }
  614. ok = processSSHCommand(req.Payload, &connection, c.EnabledSSHCommands)
  615. }
  616. if req.WantReply {
  617. req.Reply(ok, nil) //nolint:errcheck
  618. }
  619. }
  620. }(requests, channelCounter)
  621. }
  622. }
  623. func (c *Configuration) handleSftpConnection(channel ssh.Channel, connection *Connection) {
  624. defer func() {
  625. if r := recover(); r != nil {
  626. logger.Error(logSender, "", "panic in handleSftpConnection: %q stack trace: %v", r, string(debug.Stack()))
  627. }
  628. }()
  629. if err := common.Connections.Add(connection); err != nil {
  630. errClose := connection.Disconnect()
  631. logger.Info(logSender, "", "unable to add connection: %v, close err: %v", err, errClose)
  632. return
  633. }
  634. defer common.Connections.Remove(connection.GetID())
  635. // Create the server instance for the channel using the handler we created above.
  636. server := sftp.NewRequestServer(channel, c.createHandlers(connection), sftp.WithRSAllocator(),
  637. sftp.WithStartDirectory(connection.User.Filters.StartDirectory))
  638. defer server.Close()
  639. if err := server.Serve(); errors.Is(err, io.EOF) {
  640. exitStatus := sshSubsystemExitStatus{Status: uint32(0)}
  641. _, err = channel.SendRequest("exit-status", false, ssh.Marshal(&exitStatus))
  642. connection.Log(logger.LevelInfo, "connection closed, sent exit status %+v error: %v", exitStatus, err)
  643. } else if err != nil {
  644. connection.Log(logger.LevelError, "connection closed with error: %v", err)
  645. }
  646. }
  647. func (c *Configuration) createHandlers(connection *Connection) sftp.Handlers {
  648. if c.FolderPrefix != "" {
  649. prefixMiddleware := newPrefixMiddleware(c.FolderPrefix, connection)
  650. return sftp.Handlers{
  651. FileGet: prefixMiddleware,
  652. FilePut: prefixMiddleware,
  653. FileCmd: prefixMiddleware,
  654. FileList: prefixMiddleware,
  655. }
  656. }
  657. return sftp.Handlers{
  658. FileGet: connection,
  659. FilePut: connection,
  660. FileCmd: connection,
  661. FileList: connection,
  662. }
  663. }
  664. func canAcceptConnection(ip string) bool {
  665. if common.IsBanned(ip, common.ProtocolSSH) {
  666. logger.Log(logger.LevelDebug, common.ProtocolSSH, "", "connection refused, ip %q is banned", ip)
  667. return false
  668. }
  669. if err := common.Connections.IsNewConnectionAllowed(ip, common.ProtocolSSH); err != nil {
  670. logger.Log(logger.LevelDebug, common.ProtocolSSH, "", "connection not allowed from ip %q: %v", ip, err)
  671. return false
  672. }
  673. _, err := common.LimitRate(common.ProtocolSSH, ip)
  674. if err != nil {
  675. return false
  676. }
  677. if err := common.Config.ExecutePostConnectHook(ip, common.ProtocolSSH); err != nil {
  678. return false
  679. }
  680. return true
  681. }
  682. func discardAllChannels(in <-chan ssh.NewChannel, message, connectionID string) {
  683. for req := range in {
  684. err := req.Reject(ssh.ConnectionFailed, message)
  685. logger.Debug(logSender, connectionID, "discarded channel request, message %q err: %v", message, err)
  686. }
  687. }
  688. func checkAuthError(ip string, err error) {
  689. if authErrors, ok := err.(*ssh.ServerAuthError); ok {
  690. // check public key auth errors here
  691. for _, err := range authErrors.Errors {
  692. var sftpAuthErr *authenticationError
  693. if errors.As(err, &sftpAuthErr) {
  694. if sftpAuthErr.getLoginMethod() == dataprovider.SSHLoginMethodPublicKey {
  695. event := common.HostEventLoginFailed
  696. logEv := notifier.LogEventTypeLoginFailed
  697. if errors.Is(err, util.ErrNotFound) {
  698. event = common.HostEventUserNotFound
  699. logEv = notifier.LogEventTypeLoginNoUser
  700. }
  701. common.AddDefenderEvent(ip, common.ProtocolSSH, event)
  702. plugin.Handler.NotifyLogEvent(logEv, common.ProtocolSSH, "", ip, "", err)
  703. return
  704. }
  705. }
  706. }
  707. } else {
  708. logger.ConnectionFailedLog("", ip, dataprovider.LoginMethodNoAuthTried, common.ProtocolSSH, err.Error())
  709. metric.AddNoAuthTried()
  710. common.AddDefenderEvent(ip, common.ProtocolSSH, common.HostEventNoLoginTried)
  711. dataprovider.ExecutePostLoginHook(&dataprovider.User{}, dataprovider.LoginMethodNoAuthTried, ip, common.ProtocolSSH, err)
  712. logEv := notifier.LogEventTypeNoLoginTried
  713. if errors.Is(err, ssh.ErrNoCommonAlgo) {
  714. logEv = notifier.LogEventTypeNotNegotiated
  715. }
  716. plugin.Handler.NotifyLogEvent(logEv, common.ProtocolSSH, "", ip, "", err)
  717. }
  718. }
  719. func loginUser(user *dataprovider.User, loginMethod, publicKey string, conn ssh.ConnMetadata) (*ssh.Permissions, error) {
  720. connectionID := ""
  721. if conn != nil {
  722. connectionID = hex.EncodeToString(conn.SessionID())
  723. }
  724. if !filepath.IsAbs(user.HomeDir) {
  725. logger.Warn(logSender, connectionID, "user %q has an invalid home dir: %q. Home dir must be an absolute path, login not allowed",
  726. user.Username, user.HomeDir)
  727. return nil, fmt.Errorf("cannot login user with invalid home dir: %q", user.HomeDir)
  728. }
  729. if util.Contains(user.Filters.DeniedProtocols, common.ProtocolSSH) {
  730. logger.Info(logSender, connectionID, "cannot login user %q, protocol SSH is not allowed", user.Username)
  731. return nil, fmt.Errorf("protocol SSH is not allowed for user %q", user.Username)
  732. }
  733. if user.MaxSessions > 0 {
  734. activeSessions := common.Connections.GetActiveSessions(user.Username)
  735. if activeSessions >= user.MaxSessions {
  736. logger.Info(logSender, "", "authentication refused for user: %q, too many open sessions: %v/%v", user.Username,
  737. activeSessions, user.MaxSessions)
  738. return nil, fmt.Errorf("too many open sessions: %v", activeSessions)
  739. }
  740. }
  741. if !user.IsLoginMethodAllowed(loginMethod, common.ProtocolSSH, conn.PartialSuccessMethods()) {
  742. logger.Info(logSender, connectionID, "cannot login user %q, login method %q is not allowed",
  743. user.Username, loginMethod)
  744. return nil, fmt.Errorf("login method %q is not allowed for user %q", loginMethod, user.Username)
  745. }
  746. if user.MustSetSecondFactorForProtocol(common.ProtocolSSH) {
  747. logger.Info(logSender, connectionID, "cannot login user %q, second factor authentication is not set",
  748. user.Username)
  749. return nil, fmt.Errorf("second factor authentication is not set for user %q", user.Username)
  750. }
  751. remoteAddr := conn.RemoteAddr().String()
  752. if !user.IsLoginFromAddrAllowed(remoteAddr) {
  753. logger.Info(logSender, connectionID, "cannot login user %q, remote address is not allowed: %v",
  754. user.Username, remoteAddr)
  755. return nil, fmt.Errorf("login for user %q is not allowed from this address: %v", user.Username, remoteAddr)
  756. }
  757. json, err := json.Marshal(user)
  758. if err != nil {
  759. logger.Warn(logSender, connectionID, "error serializing user info: %v, authentication rejected", err)
  760. return nil, err
  761. }
  762. if publicKey != "" {
  763. loginMethod = fmt.Sprintf("%v: %v", loginMethod, publicKey)
  764. }
  765. p := &ssh.Permissions{}
  766. p.Extensions = make(map[string]string)
  767. p.Extensions["sftpgo_user"] = string(json)
  768. p.Extensions["sftpgo_login_method"] = loginMethod
  769. return p, nil
  770. }
  771. func (c *Configuration) checkSSHCommands() {
  772. if util.Contains(c.EnabledSSHCommands, "*") {
  773. c.EnabledSSHCommands = GetSupportedSSHCommands()
  774. return
  775. }
  776. sshCommands := []string{}
  777. for _, command := range c.EnabledSSHCommands {
  778. command = strings.TrimSpace(command)
  779. if util.Contains(supportedSSHCommands, command) {
  780. sshCommands = append(sshCommands, command)
  781. } else {
  782. logger.Warn(logSender, "", "unsupported ssh command: %q ignored", command)
  783. logger.WarnToConsole("unsupported ssh command: %q ignored", command)
  784. }
  785. }
  786. c.EnabledSSHCommands = sshCommands
  787. logger.Debug(logSender, "", "enabled SSH commands %v", c.EnabledSSHCommands)
  788. }
  789. func (c *Configuration) checkFolderPrefix() {
  790. if c.FolderPrefix != "" {
  791. c.FolderPrefix = path.Join("/", c.FolderPrefix)
  792. if c.FolderPrefix == "/" {
  793. c.FolderPrefix = ""
  794. }
  795. }
  796. if c.FolderPrefix != "" {
  797. c.EnabledSSHCommands = nil
  798. logger.Debug(logSender, "", "folder prefix %q configured, SSH commands are disabled", c.FolderPrefix)
  799. }
  800. }
  801. func (c *Configuration) generateDefaultHostKeys(configDir string) error {
  802. var err error
  803. defaultHostKeys := []string{defaultPrivateRSAKeyName, defaultPrivateECDSAKeyName, defaultPrivateEd25519KeyName}
  804. for _, k := range defaultHostKeys {
  805. autoFile := filepath.Join(configDir, k)
  806. if _, err = os.Stat(autoFile); errors.Is(err, fs.ErrNotExist) {
  807. logger.Info(logSender, "", "No host keys configured and %q does not exist; try to create a new host key", autoFile)
  808. logger.InfoToConsole("No host keys configured and %q does not exist; try to create a new host key", autoFile)
  809. if k == defaultPrivateRSAKeyName {
  810. err = util.GenerateRSAKeys(autoFile)
  811. } else if k == defaultPrivateECDSAKeyName {
  812. err = util.GenerateECDSAKeys(autoFile)
  813. } else {
  814. err = util.GenerateEd25519Keys(autoFile)
  815. }
  816. if err != nil {
  817. logger.Warn(logSender, "", "error creating host key %q: %v", autoFile, err)
  818. logger.WarnToConsole("error creating host key %q: %v", autoFile, err)
  819. return err
  820. }
  821. }
  822. c.HostKeys = append(c.HostKeys, k)
  823. }
  824. return err
  825. }
  826. func (c *Configuration) checkHostKeyAutoGeneration(configDir string) error {
  827. for _, k := range c.HostKeys {
  828. k = strings.TrimSpace(k)
  829. if filepath.IsAbs(k) {
  830. if _, err := os.Stat(k); errors.Is(err, fs.ErrNotExist) {
  831. keyName := filepath.Base(k)
  832. switch keyName {
  833. case defaultPrivateRSAKeyName:
  834. logger.Info(logSender, "", "try to create non-existent host key %q", k)
  835. logger.InfoToConsole("try to create non-existent host key %q", k)
  836. err = util.GenerateRSAKeys(k)
  837. if err != nil {
  838. logger.Warn(logSender, "", "error creating host key %q: %v", k, err)
  839. logger.WarnToConsole("error creating host key %q: %v", k, err)
  840. return err
  841. }
  842. case defaultPrivateECDSAKeyName:
  843. logger.Info(logSender, "", "try to create non-existent host key %q", k)
  844. logger.InfoToConsole("try to create non-existent host key %q", k)
  845. err = util.GenerateECDSAKeys(k)
  846. if err != nil {
  847. logger.Warn(logSender, "", "error creating host key %q: %v", k, err)
  848. logger.WarnToConsole("error creating host key %q: %v", k, err)
  849. return err
  850. }
  851. case defaultPrivateEd25519KeyName:
  852. logger.Info(logSender, "", "try to create non-existent host key %q", k)
  853. logger.InfoToConsole("try to create non-existent host key %q", k)
  854. err = util.GenerateEd25519Keys(k)
  855. if err != nil {
  856. logger.Warn(logSender, "", "error creating host key %q: %v", k, err)
  857. logger.WarnToConsole("error creating host key %q: %v", k, err)
  858. return err
  859. }
  860. default:
  861. logger.Warn(logSender, "", "non-existent host key %q will not be created", k)
  862. logger.WarnToConsole("non-existent host key %q will not be created", k)
  863. }
  864. }
  865. }
  866. }
  867. if len(c.HostKeys) == 0 {
  868. if err := c.generateDefaultHostKeys(configDir); err != nil {
  869. return err
  870. }
  871. }
  872. return nil
  873. }
  874. func (c *Configuration) loadModuli(configDir string) {
  875. supportedKexAlgos = util.Remove(supportedKexAlgos, kexDHGroupExchangeSHA1)
  876. supportedKexAlgos = util.Remove(supportedKexAlgos, kexDHGroupExchangeSHA256)
  877. preferredKexAlgos = util.Remove(preferredKexAlgos, kexDHGroupExchangeSHA256)
  878. c.Moduli = util.RemoveDuplicates(c.Moduli, false)
  879. for _, m := range c.Moduli {
  880. m = strings.TrimSpace(m)
  881. if !util.IsFileInputValid(m) {
  882. logger.Warn(logSender, "", "unable to load invalid moduli file %q", m)
  883. logger.WarnToConsole("unable to load invalid host moduli file %q", m)
  884. continue
  885. }
  886. if !filepath.IsAbs(m) {
  887. m = filepath.Join(configDir, m)
  888. }
  889. logger.Info(logSender, "", "loading moduli file %q", m)
  890. if err := ssh.ParseModuli(m); err != nil {
  891. logger.Warn(logSender, "", "ignoring moduli file %q, error: %v", m, err)
  892. continue
  893. }
  894. if !util.Contains(supportedKexAlgos, kexDHGroupExchangeSHA1) {
  895. supportedKexAlgos = append(supportedKexAlgos, kexDHGroupExchangeSHA1)
  896. }
  897. if !util.Contains(supportedKexAlgos, kexDHGroupExchangeSHA256) {
  898. supportedKexAlgos = append(supportedKexAlgos, kexDHGroupExchangeSHA256)
  899. }
  900. if !util.Contains(preferredKexAlgos, kexDHGroupExchangeSHA256) {
  901. preferredKexAlgos = append(preferredKexAlgos, kexDHGroupExchangeSHA256)
  902. }
  903. }
  904. }
  905. // If no host keys are defined we try to use or generate the default ones.
  906. func (c *Configuration) checkAndLoadHostKeys(configDir string, serverConfig *ssh.ServerConfig) error {
  907. if err := c.checkHostKeyAutoGeneration(configDir); err != nil {
  908. return err
  909. }
  910. hostCertificates, err := c.loadHostCertificates(configDir)
  911. if err != nil {
  912. return err
  913. }
  914. serviceStatus.HostKeys = nil
  915. for _, hostKey := range c.HostKeys {
  916. hostKey = strings.TrimSpace(hostKey)
  917. if !util.IsFileInputValid(hostKey) {
  918. logger.Warn(logSender, "", "unable to load invalid host key %q", hostKey)
  919. logger.WarnToConsole("unable to load invalid host key %q", hostKey)
  920. continue
  921. }
  922. if !filepath.IsAbs(hostKey) {
  923. hostKey = filepath.Join(configDir, hostKey)
  924. }
  925. logger.Info(logSender, "", "Loading private host key %q", hostKey)
  926. privateBytes, err := os.ReadFile(hostKey)
  927. if err != nil {
  928. return err
  929. }
  930. private, err := ssh.ParsePrivateKey(privateBytes)
  931. if err != nil {
  932. return err
  933. }
  934. k := HostKey{
  935. Path: hostKey,
  936. Fingerprint: ssh.FingerprintSHA256(private.PublicKey()),
  937. }
  938. serviceStatus.HostKeys = append(serviceStatus.HostKeys, k)
  939. logger.Info(logSender, "", "Host key %q loaded, type %q, fingerprint %q", hostKey,
  940. private.PublicKey().Type(), k.Fingerprint)
  941. // Add private key to the server configuration.
  942. serverConfig.AddHostKey(private)
  943. for _, cert := range hostCertificates {
  944. signer, err := ssh.NewCertSigner(cert, private)
  945. if err == nil {
  946. serverConfig.AddHostKey(signer)
  947. logger.Info(logSender, "", "Host certificate loaded for host key %q, fingerprint %q",
  948. hostKey, ssh.FingerprintSHA256(signer.PublicKey()))
  949. }
  950. }
  951. }
  952. var fp []string
  953. for idx := range serviceStatus.HostKeys {
  954. h := &serviceStatus.HostKeys[idx]
  955. fp = append(fp, h.Fingerprint)
  956. }
  957. vfs.SetSFTPFingerprints(fp)
  958. return nil
  959. }
  960. func (c *Configuration) loadHostCertificates(configDir string) ([]*ssh.Certificate, error) {
  961. var certs []*ssh.Certificate
  962. for _, certPath := range c.HostCertificates {
  963. certPath = strings.TrimSpace(certPath)
  964. if !util.IsFileInputValid(certPath) {
  965. logger.Warn(logSender, "", "unable to load invalid host certificate %q", certPath)
  966. logger.WarnToConsole("unable to load invalid host certificate %q", certPath)
  967. continue
  968. }
  969. if !filepath.IsAbs(certPath) {
  970. certPath = filepath.Join(configDir, certPath)
  971. }
  972. certBytes, err := os.ReadFile(certPath)
  973. if err != nil {
  974. return certs, fmt.Errorf("unable to load host certificate %q: %w", certPath, err)
  975. }
  976. parsed, _, _, _, err := ssh.ParseAuthorizedKey(certBytes)
  977. if err != nil {
  978. return nil, fmt.Errorf("unable to parse host certificate %q: %w", certPath, err)
  979. }
  980. cert, ok := parsed.(*ssh.Certificate)
  981. if !ok {
  982. return nil, fmt.Errorf("the file %q is not an SSH certificate", certPath)
  983. }
  984. if cert.CertType != ssh.HostCert {
  985. return nil, fmt.Errorf("the file %q is not an host certificate", certPath)
  986. }
  987. certs = append(certs, cert)
  988. }
  989. return certs, nil
  990. }
  991. func (c *Configuration) initializeCertChecker(configDir string) error {
  992. for _, keyPath := range c.TrustedUserCAKeys {
  993. keyPath = strings.TrimSpace(keyPath)
  994. if !util.IsFileInputValid(keyPath) {
  995. logger.Warn(logSender, "", "unable to load invalid trusted user CA key %q", keyPath)
  996. logger.WarnToConsole("unable to load invalid trusted user CA key %q", keyPath)
  997. continue
  998. }
  999. if !filepath.IsAbs(keyPath) {
  1000. keyPath = filepath.Join(configDir, keyPath)
  1001. }
  1002. keyBytes, err := os.ReadFile(keyPath)
  1003. if err != nil {
  1004. logger.Warn(logSender, "", "error loading trusted user CA key %q: %v", keyPath, err)
  1005. logger.WarnToConsole("error loading trusted user CA key %q: %v", keyPath, err)
  1006. return err
  1007. }
  1008. parsedKey, _, _, _, err := ssh.ParseAuthorizedKey(keyBytes)
  1009. if err != nil {
  1010. logger.Warn(logSender, "", "error parsing trusted user CA key %q: %v", keyPath, err)
  1011. logger.WarnToConsole("error parsing trusted user CA key %q: %v", keyPath, err)
  1012. return err
  1013. }
  1014. c.parsedUserCAKeys = append(c.parsedUserCAKeys, parsedKey)
  1015. }
  1016. c.certChecker = &ssh.CertChecker{
  1017. SupportedCriticalOptions: []string{
  1018. sourceAddressCriticalOption,
  1019. },
  1020. IsUserAuthority: func(k ssh.PublicKey) bool {
  1021. for _, key := range c.parsedUserCAKeys {
  1022. if bytes.Equal(k.Marshal(), key.Marshal()) {
  1023. return true
  1024. }
  1025. }
  1026. return false
  1027. },
  1028. }
  1029. if c.RevokedUserCertsFile != "" {
  1030. if !util.IsFileInputValid(c.RevokedUserCertsFile) {
  1031. return fmt.Errorf("invalid revoked user certificate: %q", c.RevokedUserCertsFile)
  1032. }
  1033. if !filepath.IsAbs(c.RevokedUserCertsFile) {
  1034. c.RevokedUserCertsFile = filepath.Join(configDir, c.RevokedUserCertsFile)
  1035. }
  1036. }
  1037. revokedCertManager.filePath = c.RevokedUserCertsFile
  1038. return revokedCertManager.load()
  1039. }
  1040. func (c *Configuration) validatePublicKeyCredentials(conn ssh.ConnMetadata, pubKey ssh.PublicKey) (*ssh.Permissions, error) {
  1041. var err error
  1042. var user dataprovider.User
  1043. var keyID string
  1044. var sshPerm *ssh.Permissions
  1045. var certPerm *ssh.Permissions
  1046. connectionID := hex.EncodeToString(conn.SessionID())
  1047. method := dataprovider.SSHLoginMethodPublicKey
  1048. ipAddr := util.GetIPFromRemoteAddress(conn.RemoteAddr().String())
  1049. cert, ok := pubKey.(*ssh.Certificate)
  1050. var certFingerprint string
  1051. if ok {
  1052. certFingerprint = ssh.FingerprintSHA256(cert.Key)
  1053. if cert.CertType != ssh.UserCert {
  1054. err = fmt.Errorf("ssh: cert has type %d", cert.CertType)
  1055. user.Username = conn.User()
  1056. updateLoginMetrics(&user, ipAddr, method, err)
  1057. return nil, err
  1058. }
  1059. if !c.certChecker.IsUserAuthority(cert.SignatureKey) {
  1060. err = errors.New("ssh: certificate signed by unrecognized authority")
  1061. user.Username = conn.User()
  1062. updateLoginMetrics(&user, ipAddr, method, err)
  1063. return nil, err
  1064. }
  1065. if len(cert.ValidPrincipals) == 0 {
  1066. err = fmt.Errorf("ssh: certificate %s has no valid principals, user: \"%s\"", certFingerprint, conn.User())
  1067. user.Username = conn.User()
  1068. updateLoginMetrics(&user, ipAddr, method, err)
  1069. return nil, err
  1070. }
  1071. if revokedCertManager.isRevoked(certFingerprint) {
  1072. err = fmt.Errorf("ssh: certificate %s is revoked", certFingerprint)
  1073. user.Username = conn.User()
  1074. updateLoginMetrics(&user, ipAddr, method, err)
  1075. return nil, err
  1076. }
  1077. if err := c.certChecker.CheckCert(conn.User(), cert); err != nil {
  1078. user.Username = conn.User()
  1079. updateLoginMetrics(&user, ipAddr, method, err)
  1080. return nil, err
  1081. }
  1082. certPerm = &cert.Permissions
  1083. }
  1084. if user, keyID, err = dataprovider.CheckUserAndPubKey(conn.User(), pubKey.Marshal(), ipAddr, common.ProtocolSSH, ok); err == nil {
  1085. if ok {
  1086. keyID = fmt.Sprintf("%s: ID: %s, serial: %v, CA %s %s", certFingerprint,
  1087. cert.KeyId, cert.Serial, cert.Type(), ssh.FingerprintSHA256(cert.SignatureKey))
  1088. }
  1089. if user.IsPartialAuth(method) {
  1090. logger.Debug(logSender, connectionID, "user %q authenticated with partial success", conn.User())
  1091. return certPerm, ssh.ErrPartialSuccess
  1092. }
  1093. sshPerm, err = loginUser(&user, method, keyID, conn)
  1094. if err == nil && certPerm != nil {
  1095. // if we have a SSH user cert we need to merge certificate permissions with our ones
  1096. // we only set Extensions, so CriticalOptions are always the ones from the certificate
  1097. sshPerm.CriticalOptions = certPerm.CriticalOptions
  1098. if certPerm.Extensions != nil {
  1099. for k, v := range certPerm.Extensions {
  1100. sshPerm.Extensions[k] = v
  1101. }
  1102. }
  1103. }
  1104. }
  1105. user.Username = conn.User()
  1106. updateLoginMetrics(&user, ipAddr, method, err)
  1107. return sshPerm, err
  1108. }
  1109. func (c *Configuration) validatePasswordCredentials(conn ssh.ConnMetadata, pass []byte) (*ssh.Permissions, error) {
  1110. var err error
  1111. var user dataprovider.User
  1112. var sshPerm *ssh.Permissions
  1113. method := dataprovider.LoginMethodPassword
  1114. if len(conn.PartialSuccessMethods()) == 1 {
  1115. method = dataprovider.SSHLoginMethodKeyAndPassword
  1116. }
  1117. ipAddr := util.GetIPFromRemoteAddress(conn.RemoteAddr().String())
  1118. if user, err = dataprovider.CheckUserAndPass(conn.User(), string(pass), ipAddr, common.ProtocolSSH); err == nil {
  1119. sshPerm, err = loginUser(&user, method, "", conn)
  1120. }
  1121. user.Username = conn.User()
  1122. updateLoginMetrics(&user, ipAddr, method, err)
  1123. return sshPerm, err
  1124. }
  1125. func (c *Configuration) validateKeyboardInteractiveCredentials(conn ssh.ConnMetadata, client ssh.KeyboardInteractiveChallenge) (*ssh.Permissions, error) {
  1126. var err error
  1127. var user dataprovider.User
  1128. var sshPerm *ssh.Permissions
  1129. method := dataprovider.SSHLoginMethodKeyboardInteractive
  1130. if len(conn.PartialSuccessMethods()) == 1 {
  1131. method = dataprovider.SSHLoginMethodKeyAndKeyboardInt
  1132. }
  1133. ipAddr := util.GetIPFromRemoteAddress(conn.RemoteAddr().String())
  1134. if user, err = dataprovider.CheckKeyboardInteractiveAuth(conn.User(), c.KeyboardInteractiveHook, client,
  1135. ipAddr, common.ProtocolSSH); err == nil {
  1136. sshPerm, err = loginUser(&user, method, "", conn)
  1137. }
  1138. user.Username = conn.User()
  1139. updateLoginMetrics(&user, ipAddr, method, err)
  1140. return sshPerm, err
  1141. }
  1142. func updateLoginMetrics(user *dataprovider.User, ip, method string, err error) {
  1143. metric.AddLoginAttempt(method)
  1144. if err != nil {
  1145. logger.ConnectionFailedLog(user.Username, ip, method, common.ProtocolSSH, err.Error())
  1146. if method != dataprovider.SSHLoginMethodPublicKey {
  1147. // some clients try all available public keys for a user, we
  1148. // record failed login key auth only once for session if the
  1149. // authentication fails in checkAuthError
  1150. event := common.HostEventLoginFailed
  1151. logEv := notifier.LogEventTypeLoginFailed
  1152. if errors.Is(err, util.ErrNotFound) {
  1153. event = common.HostEventUserNotFound
  1154. logEv = notifier.LogEventTypeLoginNoUser
  1155. }
  1156. common.AddDefenderEvent(ip, common.ProtocolSSH, event)
  1157. plugin.Handler.NotifyLogEvent(logEv, common.ProtocolSSH, user.Username, ip, "", err)
  1158. }
  1159. }
  1160. metric.AddLoginResult(method, err)
  1161. dataprovider.ExecutePostLoginHook(user, method, ip, common.ProtocolSSH, err)
  1162. }
  1163. type revokedCertificates struct {
  1164. filePath string
  1165. mu sync.RWMutex
  1166. certs map[string]bool
  1167. }
  1168. func (r *revokedCertificates) load() error {
  1169. if r.filePath == "" {
  1170. return nil
  1171. }
  1172. logger.Debug(logSender, "", "loading revoked user certificate file %q", r.filePath)
  1173. info, err := os.Stat(r.filePath)
  1174. if err != nil {
  1175. return fmt.Errorf("unable to load revoked user certificate file %q: %w", r.filePath, err)
  1176. }
  1177. maxSize := int64(1048576 * 5) // 5MB
  1178. if info.Size() > maxSize {
  1179. return fmt.Errorf("unable to load revoked user certificate file %q size too big: %v/%v bytes",
  1180. r.filePath, info.Size(), maxSize)
  1181. }
  1182. content, err := os.ReadFile(r.filePath)
  1183. if err != nil {
  1184. return fmt.Errorf("unable to read revoked user certificate file %q: %w", r.filePath, err)
  1185. }
  1186. var certs []string
  1187. err = json.Unmarshal(content, &certs)
  1188. if err != nil {
  1189. return fmt.Errorf("unable to parse revoked user certificate file %q: %w", r.filePath, err)
  1190. }
  1191. r.mu.Lock()
  1192. defer r.mu.Unlock()
  1193. r.certs = map[string]bool{}
  1194. for _, fp := range certs {
  1195. r.certs[fp] = true
  1196. }
  1197. logger.Debug(logSender, "", "revoked user certificate file %q loaded, entries: %v", r.filePath, len(r.certs))
  1198. return nil
  1199. }
  1200. func (r *revokedCertificates) isRevoked(fp string) bool {
  1201. r.mu.RLock()
  1202. defer r.mu.RUnlock()
  1203. return r.certs[fp]
  1204. }
  1205. // Reload reloads the list of revoked user certificates
  1206. func Reload() error {
  1207. return revokedCertManager.load()
  1208. }