server.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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 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, common.ProtocolFTP) {
  147. logger.Log(logger.LevelDebug, common.ProtocolFTP, "", "connection refused, ip %q is banned", ipAddr)
  148. return "Access denied: banned client IP", common.ErrConnectionDenied
  149. }
  150. if err := common.Connections.IsNewConnectionAllowed(ipAddr, common.ProtocolFTP); err != nil {
  151. logger.Log(logger.LevelDebug, common.ProtocolFTP, "", "connection not allowed from ip %q: %v", ipAddr, err)
  152. return "Access denied", err
  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 %q logged in with %q from ip %q", 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 !errors.Is(err, util.ErrNotFound) {
  212. logger.Error(logSender, fmt.Sprintf("%v_%v_%v", common.ProtocolFTP, s.ID, cc.ID()),
  213. "unable to get user on pre auth: %v", err)
  214. return common.ErrInternalFailure
  215. }
  216. }
  217. return nil
  218. }
  219. // WrapPassiveListener implements the MainDriverExtensionPassiveWrapper interface
  220. func (s *Server) WrapPassiveListener(listener net.Listener) (net.Listener, error) {
  221. if s.binding.HasProxy() {
  222. return common.Config.GetProxyListener(listener)
  223. }
  224. return listener, nil
  225. }
  226. // VerifyConnection checks whether a user should be authenticated using a client certificate without prompting for a password
  227. func (s *Server) VerifyConnection(cc ftpserver.ClientContext, user string, tlsConn *tls.Conn) (ftpserver.ClientDriver, error) {
  228. if !s.binding.isMutualTLSEnabled() {
  229. return nil, nil
  230. }
  231. s.setTLSConnVerified(cc.ID(), false)
  232. if tlsConn != nil {
  233. state := tlsConn.ConnectionState()
  234. if len(state.PeerCertificates) > 0 {
  235. ipAddr := util.GetIPFromRemoteAddress(cc.RemoteAddr().String())
  236. dbUser, err := dataprovider.CheckUserBeforeTLSAuth(user, ipAddr, common.ProtocolFTP, state.PeerCertificates[0])
  237. if err != nil {
  238. dbUser.Username = user
  239. updateLoginMetrics(&dbUser, ipAddr, dataprovider.LoginMethodTLSCertificate, err)
  240. return nil, dataprovider.ErrInvalidCredentials
  241. }
  242. if dbUser.IsTLSUsernameVerificationEnabled() {
  243. dbUser, err = dataprovider.CheckUserAndTLSCert(user, ipAddr, common.ProtocolFTP, state.PeerCertificates[0])
  244. if err != nil {
  245. return nil, err
  246. }
  247. s.setTLSConnVerified(cc.ID(), true)
  248. if dbUser.IsLoginMethodAllowed(dataprovider.LoginMethodTLSCertificate, common.ProtocolFTP, nil) {
  249. connection, err := s.validateUser(dbUser, cc, dataprovider.LoginMethodTLSCertificate)
  250. defer updateLoginMetrics(&dbUser, ipAddr, dataprovider.LoginMethodTLSCertificate, err)
  251. if err != nil {
  252. return nil, err
  253. }
  254. setStartDirectory(dbUser.Filters.StartDirectory, cc)
  255. connection.Log(logger.LevelInfo, "User id: %d, logged in with FTP using a TLS certificate, username: %q, home_dir: %q remote addr: %q",
  256. dbUser.ID, dbUser.Username, dbUser.HomeDir, ipAddr)
  257. dataprovider.UpdateLastLogin(&dbUser)
  258. return connection, nil
  259. }
  260. }
  261. }
  262. }
  263. return nil, nil
  264. }
  265. func (s *Server) buildTLSConfig() {
  266. if certMgr != nil {
  267. certID := common.DefaultTLSKeyPaidID
  268. if getConfigPath(s.binding.CertificateFile, "") != "" && getConfigPath(s.binding.CertificateKeyFile, "") != "" {
  269. certID = s.binding.GetAddress()
  270. }
  271. s.tlsConfig = &tls.Config{
  272. GetCertificate: certMgr.GetCertificateFunc(certID),
  273. MinVersion: util.GetTLSVersion(s.binding.MinTLSVersion),
  274. CipherSuites: s.binding.ciphers,
  275. PreferServerCipherSuites: true,
  276. }
  277. logger.Debug(logSender, "", "configured TLS cipher suites for binding %q: %v, certID: %v",
  278. s.binding.GetAddress(), s.binding.ciphers, certID)
  279. if s.binding.isMutualTLSEnabled() {
  280. s.tlsConfig.ClientCAs = certMgr.GetRootCAs()
  281. s.tlsConfig.VerifyConnection = s.verifyTLSConnection
  282. switch s.binding.ClientAuthType {
  283. case 1:
  284. s.tlsConfig.ClientAuth = tls.RequireAndVerifyClientCert
  285. case 2:
  286. s.tlsConfig.ClientAuth = tls.VerifyClientCertIfGiven
  287. }
  288. }
  289. }
  290. }
  291. // GetTLSConfig returns the TLS configuration for this server
  292. func (s *Server) GetTLSConfig() (*tls.Config, error) {
  293. if s.tlsConfig != nil {
  294. return s.tlsConfig, nil
  295. }
  296. return nil, errors.New("no TLS certificate configured")
  297. }
  298. func (s *Server) verifyTLSConnection(state tls.ConnectionState) error {
  299. if certMgr != nil {
  300. var clientCrt *x509.Certificate
  301. var clientCrtName string
  302. if len(state.PeerCertificates) > 0 {
  303. clientCrt = state.PeerCertificates[0]
  304. clientCrtName = clientCrt.Subject.String()
  305. }
  306. if len(state.VerifiedChains) == 0 {
  307. if s.binding.ClientAuthType == 2 {
  308. return nil
  309. }
  310. logger.Warn(logSender, "", "TLS connection cannot be verified: unable to get verification chain")
  311. return errors.New("TLS connection cannot be verified: unable to get verification chain")
  312. }
  313. for _, verifiedChain := range state.VerifiedChains {
  314. var caCrt *x509.Certificate
  315. if len(verifiedChain) > 0 {
  316. caCrt = verifiedChain[len(verifiedChain)-1]
  317. }
  318. if certMgr.IsRevoked(clientCrt, caCrt) {
  319. logger.Debug(logSender, "", "tls handshake error, client certificate %q has beed revoked", clientCrtName)
  320. return common.ErrCrtRevoked
  321. }
  322. }
  323. }
  324. return nil
  325. }
  326. func (s *Server) validateUser(user dataprovider.User, cc ftpserver.ClientContext, loginMethod string) (*Connection, error) {
  327. connectionID := fmt.Sprintf("%v_%v_%v", common.ProtocolFTP, s.ID, cc.ID())
  328. if !filepath.IsAbs(user.HomeDir) {
  329. logger.Warn(logSender, connectionID, "user %q has an invalid home dir: %q. Home dir must be an absolute path, login not allowed",
  330. user.Username, user.HomeDir)
  331. return nil, fmt.Errorf("cannot login user with invalid home dir: %q", user.HomeDir)
  332. }
  333. if util.Contains(user.Filters.DeniedProtocols, common.ProtocolFTP) {
  334. logger.Info(logSender, connectionID, "cannot login user %q, protocol FTP is not allowed", user.Username)
  335. return nil, fmt.Errorf("protocol FTP is not allowed for user %q", user.Username)
  336. }
  337. if !user.IsLoginMethodAllowed(loginMethod, common.ProtocolFTP, nil) {
  338. logger.Info(logSender, connectionID, "cannot login user %q, %v login method is not allowed",
  339. user.Username, loginMethod)
  340. return nil, fmt.Errorf("login method %v is not allowed for user %q", loginMethod, user.Username)
  341. }
  342. if user.MustSetSecondFactorForProtocol(common.ProtocolFTP) {
  343. logger.Info(logSender, connectionID, "cannot login user %q, second factor authentication is not set",
  344. user.Username)
  345. return nil, fmt.Errorf("second factor authentication is not set for user %q", user.Username)
  346. }
  347. if user.MaxSessions > 0 {
  348. activeSessions := common.Connections.GetActiveSessions(user.Username)
  349. if activeSessions >= user.MaxSessions {
  350. logger.Info(logSender, connectionID, "authentication refused for user: %q, too many open sessions: %v/%v",
  351. user.Username, activeSessions, user.MaxSessions)
  352. return nil, fmt.Errorf("too many open sessions: %v", activeSessions)
  353. }
  354. }
  355. remoteAddr := cc.RemoteAddr().String()
  356. if !user.IsLoginFromAddrAllowed(remoteAddr) {
  357. logger.Info(logSender, connectionID, "cannot login user %q, remote address is not allowed: %v",
  358. user.Username, remoteAddr)
  359. return nil, fmt.Errorf("login for user %q is not allowed from this address: %v", user.Username, remoteAddr)
  360. }
  361. err := user.CheckFsRoot(connectionID)
  362. if err != nil {
  363. errClose := user.CloseFs()
  364. logger.Warn(logSender, connectionID, "unable to check fs root: %v close fs error: %v", err, errClose)
  365. return nil, common.ErrInternalFailure
  366. }
  367. connection := &Connection{
  368. BaseConnection: common.NewBaseConnection(fmt.Sprintf("%v_%v", s.ID, cc.ID()), common.ProtocolFTP,
  369. cc.LocalAddr().String(), remoteAddr, user),
  370. clientContext: cc,
  371. }
  372. err = common.Connections.Swap(connection)
  373. if err != nil {
  374. errClose := user.CloseFs()
  375. logger.Warn(logSender, connectionID, "unable to swap connection: %v, close fs error: %v", err, errClose)
  376. return nil, err
  377. }
  378. return connection, nil
  379. }
  380. func setStartDirectory(startDirectory string, cc ftpserver.ClientContext) {
  381. if startDirectory == "" {
  382. return
  383. }
  384. cc.SetPath(startDirectory)
  385. }
  386. func updateLoginMetrics(user *dataprovider.User, ip, loginMethod string, err error) {
  387. metric.AddLoginAttempt(loginMethod)
  388. if err != nil && err != common.ErrInternalFailure {
  389. logger.ConnectionFailedLog(user.Username, ip, loginMethod,
  390. common.ProtocolFTP, err.Error())
  391. event := common.HostEventLoginFailed
  392. if errors.Is(err, util.ErrNotFound) {
  393. event = common.HostEventUserNotFound
  394. }
  395. common.AddDefenderEvent(ip, common.ProtocolFTP, event)
  396. }
  397. metric.AddLoginResult(loginMethod, err)
  398. dataprovider.ExecutePostLoginHook(user, loginMethod, ip, common.ProtocolFTP, err)
  399. }