server.go 12 KB

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