server.go 44 KB

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