server.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. // Copyright (C) 2019-2022 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 ftpd
  15. import (
  16. "crypto/tls"
  17. "crypto/x509"
  18. "errors"
  19. "fmt"
  20. "net"
  21. "os"
  22. "path/filepath"
  23. "sync"
  24. ftpserver "github.com/fclairamb/ftpserverlib"
  25. "github.com/drakkan/sftpgo/v2/internal/common"
  26. "github.com/drakkan/sftpgo/v2/internal/dataprovider"
  27. "github.com/drakkan/sftpgo/v2/internal/logger"
  28. "github.com/drakkan/sftpgo/v2/internal/metric"
  29. "github.com/drakkan/sftpgo/v2/internal/util"
  30. "github.com/drakkan/sftpgo/v2/internal/version"
  31. )
  32. // Server implements the ftpserverlib MainDriver interface
  33. type Server struct {
  34. ID int
  35. config *Configuration
  36. initialMsg string
  37. statusBanner string
  38. binding Binding
  39. tlsConfig *tls.Config
  40. mu sync.RWMutex
  41. verifiedTLSConns map[uint32]bool
  42. }
  43. // NewServer returns a new FTP server driver
  44. func NewServer(config *Configuration, configDir string, binding Binding, id int) *Server {
  45. binding.setCiphers()
  46. server := &Server{
  47. config: config,
  48. initialMsg: config.Banner,
  49. statusBanner: fmt.Sprintf("SFTPGo %v FTP Server", version.Get().Version),
  50. binding: binding,
  51. ID: id,
  52. verifiedTLSConns: make(map[uint32]bool),
  53. }
  54. if config.BannerFile != "" {
  55. bannerFilePath := config.BannerFile
  56. if !filepath.IsAbs(bannerFilePath) {
  57. bannerFilePath = filepath.Join(configDir, bannerFilePath)
  58. }
  59. bannerContent, err := os.ReadFile(bannerFilePath)
  60. if err == nil {
  61. server.initialMsg = string(bannerContent)
  62. } else {
  63. logger.WarnToConsole("unable to read FTPD banner file: %v", err)
  64. logger.Warn(logSender, "", "unable to read banner file: %v", err)
  65. }
  66. }
  67. server.buildTLSConfig()
  68. return server
  69. }
  70. func (s *Server) isTLSConnVerified(id uint32) bool {
  71. s.mu.RLock()
  72. defer s.mu.RUnlock()
  73. return s.verifiedTLSConns[id]
  74. }
  75. func (s *Server) setTLSConnVerified(id uint32, value bool) {
  76. s.mu.Lock()
  77. defer s.mu.Unlock()
  78. s.verifiedTLSConns[id] = value
  79. }
  80. func (s *Server) cleanTLSConnVerification(id uint32) {
  81. s.mu.Lock()
  82. defer s.mu.Unlock()
  83. delete(s.verifiedTLSConns, id)
  84. }
  85. // GetSettings returns FTP server settings
  86. func (s *Server) GetSettings() (*ftpserver.Settings, error) {
  87. if err := s.binding.checkPassiveIP(); err != nil {
  88. return nil, err
  89. }
  90. if err := s.binding.checkSecuritySettings(); err != nil {
  91. return nil, err
  92. }
  93. var portRange *ftpserver.PortRange
  94. if s.config.PassivePortRange.Start > 0 && s.config.PassivePortRange.End > s.config.PassivePortRange.Start {
  95. portRange = &ftpserver.PortRange{
  96. Start: s.config.PassivePortRange.Start,
  97. End: s.config.PassivePortRange.End,
  98. }
  99. }
  100. var ftpListener net.Listener
  101. if s.binding.HasProxy() {
  102. listener, err := net.Listen("tcp", s.binding.GetAddress())
  103. if err != nil {
  104. logger.Warn(logSender, "", "error starting listener on address %v: %v", s.binding.GetAddress(), err)
  105. return nil, err
  106. }
  107. ftpListener, err = common.Config.GetProxyListener(listener)
  108. if err != nil {
  109. logger.Warn(logSender, "", "error enabling proxy listener: %v", err)
  110. return nil, err
  111. }
  112. if s.binding.TLSMode == 2 && s.tlsConfig != nil {
  113. ftpListener = tls.NewListener(ftpListener, s.tlsConfig)
  114. }
  115. }
  116. if s.binding.TLSMode < 0 || s.binding.TLSMode > 2 {
  117. return nil, errors.New("unsupported TLS mode")
  118. }
  119. if s.binding.TLSMode > 0 && certMgr == nil {
  120. return nil, errors.New("to enable TLS you need to provide a certificate")
  121. }
  122. return &ftpserver.Settings{
  123. Listener: ftpListener,
  124. ListenAddr: s.binding.GetAddress(),
  125. PublicIPResolver: s.binding.passiveIPResolver,
  126. PassiveTransferPortRange: portRange,
  127. ActiveTransferPortNon20: s.config.ActiveTransfersPortNon20,
  128. IdleTimeout: -1,
  129. ConnectionTimeout: 20,
  130. Banner: s.statusBanner,
  131. TLSRequired: ftpserver.TLSRequirement(s.binding.TLSMode),
  132. DisableSite: !s.config.EnableSite,
  133. DisableActiveMode: s.config.DisableActiveMode,
  134. EnableHASH: s.config.HASHSupport > 0,
  135. EnableCOMB: s.config.CombineSupport > 0,
  136. DefaultTransferType: ftpserver.TransferTypeBinary,
  137. ActiveConnectionsCheck: ftpserver.DataConnectionRequirement(s.binding.ActiveConnectionsSecurity),
  138. PasvConnectionsCheck: ftpserver.DataConnectionRequirement(s.binding.PassiveConnectionsSecurity),
  139. }, nil
  140. }
  141. // ClientConnected is called to send the very first welcome message
  142. func (s *Server) ClientConnected(cc ftpserver.ClientContext) (string, error) {
  143. cc.SetDebug(s.binding.Debug)
  144. ipAddr := util.GetIPFromRemoteAddress(cc.RemoteAddr().String())
  145. common.Connections.AddClientConnection(ipAddr)
  146. if common.IsBanned(ipAddr) {
  147. logger.Log(logger.LevelDebug, common.ProtocolFTP, "", "connection refused, ip %#v is banned", ipAddr)
  148. return "Access denied: banned client IP", common.ErrConnectionDenied
  149. }
  150. if !common.Connections.IsNewConnectionAllowed(ipAddr) {
  151. logger.Log(logger.LevelDebug, common.ProtocolFTP, "", fmt.Sprintf("connection not allowed from ip %#v", ipAddr))
  152. return "Access denied", common.ErrConnectionDenied
  153. }
  154. _, err := common.LimitRate(common.ProtocolFTP, ipAddr)
  155. if err != nil {
  156. return fmt.Sprintf("Access denied: %v", err.Error()), err
  157. }
  158. if err := common.Config.ExecutePostConnectHook(ipAddr, common.ProtocolFTP); err != nil {
  159. return "Access denied by post connect hook", err
  160. }
  161. connID := fmt.Sprintf("%v_%v", s.ID, cc.ID())
  162. user := dataprovider.User{}
  163. connection := &Connection{
  164. BaseConnection: common.NewBaseConnection(connID, common.ProtocolFTP, cc.LocalAddr().String(),
  165. cc.RemoteAddr().String(), user),
  166. clientContext: cc,
  167. }
  168. err = common.Connections.Add(connection)
  169. return s.initialMsg, err
  170. }
  171. // ClientDisconnected is called when the user disconnects, even if he never authenticated
  172. func (s *Server) ClientDisconnected(cc ftpserver.ClientContext) {
  173. s.cleanTLSConnVerification(cc.ID())
  174. connID := fmt.Sprintf("%v_%v_%v", common.ProtocolFTP, s.ID, cc.ID())
  175. common.Connections.Remove(connID)
  176. common.Connections.RemoveClientConnection(util.GetIPFromRemoteAddress(cc.RemoteAddr().String()))
  177. }
  178. // AuthUser authenticates the user and selects an handling driver
  179. func (s *Server) AuthUser(cc ftpserver.ClientContext, username, password string) (ftpserver.ClientDriver, error) {
  180. loginMethod := dataprovider.LoginMethodPassword
  181. if s.isTLSConnVerified(cc.ID()) {
  182. loginMethod = dataprovider.LoginMethodTLSCertificateAndPwd
  183. }
  184. ipAddr := util.GetIPFromRemoteAddress(cc.RemoteAddr().String())
  185. user, err := dataprovider.CheckUserAndPass(username, password, ipAddr, common.ProtocolFTP)
  186. if err != nil {
  187. user.Username = username
  188. updateLoginMetrics(&user, ipAddr, loginMethod, err)
  189. return nil, dataprovider.ErrInvalidCredentials
  190. }
  191. connection, err := s.validateUser(user, cc, loginMethod)
  192. defer updateLoginMetrics(&user, ipAddr, loginMethod, err)
  193. if err != nil {
  194. return nil, err
  195. }
  196. setStartDirectory(user.Filters.StartDirectory, cc)
  197. connection.Log(logger.LevelInfo, "User %#v logged in with %#v from ip %#v", user.Username, loginMethod, ipAddr)
  198. dataprovider.UpdateLastLogin(&user)
  199. return connection, nil
  200. }
  201. // PreAuthUser implements the MainDriverExtensionUserVerifier interface
  202. func (s *Server) PreAuthUser(cc ftpserver.ClientContext, username string) error {
  203. if s.binding.TLSMode == 0 && s.tlsConfig != nil {
  204. user, err := dataprovider.GetFTPPreAuthUser(username, util.GetIPFromRemoteAddress(cc.RemoteAddr().String()))
  205. if err == nil {
  206. if user.Filters.FTPSecurity == 1 {
  207. return cc.SetTLSRequirement(ftpserver.MandatoryEncryption)
  208. }
  209. return nil
  210. }
  211. if _, ok := err.(*util.RecordNotFoundError); !ok {
  212. return common.ErrInternalFailure
  213. }
  214. }
  215. return nil
  216. }
  217. // WrapPassiveListener implements the MainDriverExtensionPassiveWrapper interface
  218. func (s *Server) WrapPassiveListener(listener net.Listener) (net.Listener, error) {
  219. if s.binding.HasProxy() {
  220. return common.Config.GetProxyListener(listener)
  221. }
  222. return listener, nil
  223. }
  224. // VerifyConnection checks whether a user should be authenticated using a client certificate without prompting for a password
  225. func (s *Server) VerifyConnection(cc ftpserver.ClientContext, user string, tlsConn *tls.Conn) (ftpserver.ClientDriver, error) {
  226. if !s.binding.isMutualTLSEnabled() {
  227. return nil, nil
  228. }
  229. s.setTLSConnVerified(cc.ID(), false)
  230. if tlsConn != nil {
  231. state := tlsConn.ConnectionState()
  232. if len(state.PeerCertificates) > 0 {
  233. ipAddr := util.GetIPFromRemoteAddress(cc.RemoteAddr().String())
  234. dbUser, err := dataprovider.CheckUserBeforeTLSAuth(user, ipAddr, common.ProtocolFTP, state.PeerCertificates[0])
  235. if err != nil {
  236. dbUser.Username = user
  237. updateLoginMetrics(&dbUser, ipAddr, dataprovider.LoginMethodTLSCertificate, err)
  238. return nil, dataprovider.ErrInvalidCredentials
  239. }
  240. if dbUser.IsTLSUsernameVerificationEnabled() {
  241. dbUser, err = dataprovider.CheckUserAndTLSCert(user, ipAddr, common.ProtocolFTP, state.PeerCertificates[0])
  242. if err != nil {
  243. return nil, err
  244. }
  245. s.setTLSConnVerified(cc.ID(), true)
  246. if dbUser.IsLoginMethodAllowed(dataprovider.LoginMethodTLSCertificate, common.ProtocolFTP, nil) {
  247. connection, err := s.validateUser(dbUser, cc, dataprovider.LoginMethodTLSCertificate)
  248. defer updateLoginMetrics(&dbUser, ipAddr, dataprovider.LoginMethodTLSCertificate, err)
  249. if err != nil {
  250. return nil, err
  251. }
  252. setStartDirectory(dbUser.Filters.StartDirectory, cc)
  253. connection.Log(logger.LevelInfo, "User id: %d, logged in with FTP using a TLS certificate, username: %#v, home_dir: %#v remote addr: %#v",
  254. dbUser.ID, dbUser.Username, dbUser.HomeDir, ipAddr)
  255. dataprovider.UpdateLastLogin(&dbUser)
  256. return connection, nil
  257. }
  258. }
  259. }
  260. }
  261. return nil, nil
  262. }
  263. func (s *Server) buildTLSConfig() {
  264. if certMgr != nil {
  265. certID := common.DefaultTLSKeyPaidID
  266. if getConfigPath(s.binding.CertificateFile, "") != "" && getConfigPath(s.binding.CertificateKeyFile, "") != "" {
  267. certID = s.binding.GetAddress()
  268. }
  269. s.tlsConfig = &tls.Config{
  270. GetCertificate: certMgr.GetCertificateFunc(certID),
  271. MinVersion: util.GetTLSVersion(s.binding.MinTLSVersion),
  272. CipherSuites: s.binding.ciphers,
  273. PreferServerCipherSuites: true,
  274. }
  275. logger.Debug(logSender, "", "configured TLS cipher suites for binding %#v: %v, certID: %v",
  276. s.binding.GetAddress(), s.binding.ciphers, certID)
  277. if s.binding.isMutualTLSEnabled() {
  278. s.tlsConfig.ClientCAs = certMgr.GetRootCAs()
  279. s.tlsConfig.VerifyConnection = s.verifyTLSConnection
  280. switch s.binding.ClientAuthType {
  281. case 1:
  282. s.tlsConfig.ClientAuth = tls.RequireAndVerifyClientCert
  283. case 2:
  284. s.tlsConfig.ClientAuth = tls.VerifyClientCertIfGiven
  285. }
  286. }
  287. }
  288. }
  289. // GetTLSConfig returns the TLS configuration for this server
  290. func (s *Server) GetTLSConfig() (*tls.Config, error) {
  291. if s.tlsConfig != nil {
  292. return s.tlsConfig, nil
  293. }
  294. return nil, errors.New("no TLS certificate configured")
  295. }
  296. func (s *Server) verifyTLSConnection(state tls.ConnectionState) error {
  297. if certMgr != nil {
  298. var clientCrt *x509.Certificate
  299. var clientCrtName string
  300. if len(state.PeerCertificates) > 0 {
  301. clientCrt = state.PeerCertificates[0]
  302. clientCrtName = clientCrt.Subject.String()
  303. }
  304. if len(state.VerifiedChains) == 0 {
  305. if s.binding.ClientAuthType == 2 {
  306. return nil
  307. }
  308. logger.Warn(logSender, "", "TLS connection cannot be verified: unable to get verification chain")
  309. return errors.New("TLS connection cannot be verified: unable to get verification chain")
  310. }
  311. for _, verifiedChain := range state.VerifiedChains {
  312. var caCrt *x509.Certificate
  313. if len(verifiedChain) > 0 {
  314. caCrt = verifiedChain[len(verifiedChain)-1]
  315. }
  316. if certMgr.IsRevoked(clientCrt, caCrt) {
  317. logger.Debug(logSender, "", "tls handshake error, client certificate %#v has beed revoked", clientCrtName)
  318. return common.ErrCrtRevoked
  319. }
  320. }
  321. }
  322. return nil
  323. }
  324. func (s *Server) validateUser(user dataprovider.User, cc ftpserver.ClientContext, loginMethod string) (*Connection, error) {
  325. connectionID := fmt.Sprintf("%v_%v_%v", common.ProtocolFTP, s.ID, cc.ID())
  326. if !filepath.IsAbs(user.HomeDir) {
  327. logger.Warn(logSender, connectionID, "user %#v has an invalid home dir: %#v. Home dir must be an absolute path, login not allowed",
  328. user.Username, user.HomeDir)
  329. return nil, fmt.Errorf("cannot login user with invalid home dir: %#v", user.HomeDir)
  330. }
  331. if util.Contains(user.Filters.DeniedProtocols, common.ProtocolFTP) {
  332. logger.Info(logSender, connectionID, "cannot login user %#v, protocol FTP is not allowed", user.Username)
  333. return nil, fmt.Errorf("protocol FTP is not allowed for user %#v", user.Username)
  334. }
  335. if !user.IsLoginMethodAllowed(loginMethod, common.ProtocolFTP, nil) {
  336. logger.Info(logSender, connectionID, "cannot login user %#v, %v login method is not allowed",
  337. user.Username, loginMethod)
  338. return nil, fmt.Errorf("login method %v is not allowed for user %#v", loginMethod, user.Username)
  339. }
  340. if user.MustSetSecondFactorForProtocol(common.ProtocolFTP) {
  341. logger.Info(logSender, connectionID, "cannot login user %#v, second factor authentication is not set",
  342. user.Username)
  343. return nil, fmt.Errorf("second factor authentication is not set for user %#v", user.Username)
  344. }
  345. if user.MaxSessions > 0 {
  346. activeSessions := common.Connections.GetActiveSessions(user.Username)
  347. if activeSessions >= user.MaxSessions {
  348. logger.Info(logSender, connectionID, "authentication refused for user: %#v, too many open sessions: %v/%v",
  349. user.Username, activeSessions, user.MaxSessions)
  350. return nil, fmt.Errorf("too many open sessions: %v", activeSessions)
  351. }
  352. }
  353. remoteAddr := cc.RemoteAddr().String()
  354. if !user.IsLoginFromAddrAllowed(remoteAddr) {
  355. logger.Info(logSender, connectionID, "cannot login user %#v, remote address is not allowed: %v",
  356. user.Username, remoteAddr)
  357. return nil, fmt.Errorf("login for user %#v is not allowed from this address: %v", user.Username, remoteAddr)
  358. }
  359. err := user.CheckFsRoot(connectionID)
  360. if err != nil {
  361. errClose := user.CloseFs()
  362. logger.Warn(logSender, connectionID, "unable to check fs root: %v close fs error: %v", err, errClose)
  363. return nil, common.ErrInternalFailure
  364. }
  365. connection := &Connection{
  366. BaseConnection: common.NewBaseConnection(fmt.Sprintf("%v_%v", s.ID, cc.ID()), common.ProtocolFTP,
  367. cc.LocalAddr().String(), remoteAddr, user),
  368. clientContext: cc,
  369. }
  370. err = common.Connections.Swap(connection)
  371. if err != nil {
  372. errClose := user.CloseFs()
  373. logger.Warn(logSender, connectionID, "unable to swap connection: %v, close fs error: %v", err, errClose)
  374. return nil, err
  375. }
  376. return connection, nil
  377. }
  378. func setStartDirectory(startDirectory string, cc ftpserver.ClientContext) {
  379. if startDirectory == "" {
  380. return
  381. }
  382. cc.SetPath(startDirectory)
  383. }
  384. func updateLoginMetrics(user *dataprovider.User, ip, loginMethod string, err error) {
  385. metric.AddLoginAttempt(loginMethod)
  386. if err != nil && err != common.ErrInternalFailure {
  387. logger.ConnectionFailedLog(user.Username, ip, loginMethod,
  388. common.ProtocolFTP, err.Error())
  389. event := common.HostEventLoginFailed
  390. if _, ok := err.(*util.RecordNotFoundError); ok {
  391. event = common.HostEventUserNotFound
  392. }
  393. common.AddDefenderEvent(ip, event)
  394. }
  395. metric.AddLoginResult(loginMethod, err)
  396. dataprovider.ExecutePostLoginHook(user, loginMethod, ip, common.ProtocolFTP, err)
  397. }