server.go 49 KB

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