server.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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. common.Connections.AddNetworkConnection()
  123. ipAddr := utils.GetIPFromRemoteAddress(cc.RemoteAddr().String())
  124. if common.IsBanned(ipAddr) {
  125. logger.Log(logger.LevelDebug, common.ProtocolFTP, "", "connection refused, ip %#v is banned", ipAddr)
  126. return "Access denied: banned client IP", common.ErrConnectionDenied
  127. }
  128. if !common.Connections.IsNewConnectionAllowed() {
  129. logger.Log(logger.LevelDebug, common.ProtocolFTP, "", "connection refused, configured limit reached")
  130. return "Access denied: max allowed connection exceeded", common.ErrConnectionDenied
  131. }
  132. _, err := common.LimitRate(common.ProtocolFTP, ipAddr)
  133. if err != nil {
  134. return fmt.Sprintf("Access denied: %v", err.Error()), err
  135. }
  136. if err := common.Config.ExecutePostConnectHook(ipAddr, common.ProtocolFTP); err != nil {
  137. return "Access denied by post connect hook", err
  138. }
  139. connID := fmt.Sprintf("%v_%v", s.ID, cc.ID())
  140. user := dataprovider.User{}
  141. connection := &Connection{
  142. BaseConnection: common.NewBaseConnection(connID, common.ProtocolFTP, user),
  143. clientContext: cc,
  144. }
  145. common.Connections.Add(connection)
  146. return s.initialMsg, nil
  147. }
  148. // ClientDisconnected is called when the user disconnects, even if he never authenticated
  149. func (s *Server) ClientDisconnected(cc ftpserver.ClientContext) {
  150. s.cleanTLSConnVerification(cc.ID())
  151. connID := fmt.Sprintf("%v_%v_%v", common.ProtocolFTP, s.ID, cc.ID())
  152. common.Connections.Remove(connID)
  153. common.Connections.RemoveNetworkConnection()
  154. }
  155. // AuthUser authenticates the user and selects an handling driver
  156. func (s *Server) AuthUser(cc ftpserver.ClientContext, username, password string) (ftpserver.ClientDriver, error) {
  157. loginMethod := dataprovider.LoginMethodPassword
  158. if s.isTLSConnVerified(cc.ID()) {
  159. loginMethod = dataprovider.LoginMethodTLSCertificateAndPwd
  160. }
  161. ipAddr := utils.GetIPFromRemoteAddress(cc.RemoteAddr().String())
  162. user, err := dataprovider.CheckUserAndPass(username, password, ipAddr, common.ProtocolFTP)
  163. if err != nil {
  164. user.Username = username
  165. updateLoginMetrics(&user, ipAddr, loginMethod, err)
  166. return nil, err
  167. }
  168. connection, err := s.validateUser(user, cc, loginMethod)
  169. defer updateLoginMetrics(&user, ipAddr, loginMethod, err)
  170. if err != nil {
  171. return nil, err
  172. }
  173. connection.Log(logger.LevelInfo, "User id: %d, logged in with FTP, username: %#v, home_dir: %#v remote addr: %#v",
  174. user.ID, user.Username, user.HomeDir, ipAddr)
  175. dataprovider.UpdateLastLogin(&user) //nolint:errcheck
  176. return connection, nil
  177. }
  178. // VerifyConnection checks whether a user should be authenticated using a client certificate without prompting for a password
  179. func (s *Server) VerifyConnection(cc ftpserver.ClientContext, user string, tlsConn *tls.Conn) (ftpserver.ClientDriver, error) {
  180. if !s.binding.isMutualTLSEnabled() {
  181. return nil, nil
  182. }
  183. s.setTLSConnVerified(cc.ID(), false)
  184. if tlsConn != nil {
  185. state := tlsConn.ConnectionState()
  186. if len(state.PeerCertificates) > 0 {
  187. ipAddr := utils.GetIPFromRemoteAddress(cc.RemoteAddr().String())
  188. dbUser, err := dataprovider.CheckUserBeforeTLSAuth(user, ipAddr, common.ProtocolFTP, state.PeerCertificates[0])
  189. if err != nil {
  190. dbUser.Username = user
  191. updateLoginMetrics(&dbUser, ipAddr, dataprovider.LoginMethodTLSCertificate, err)
  192. return nil, err
  193. }
  194. if dbUser.IsTLSUsernameVerificationEnabled() {
  195. dbUser, err = dataprovider.CheckUserAndTLSCert(user, ipAddr, common.ProtocolFTP, state.PeerCertificates[0])
  196. if err != nil {
  197. return nil, err
  198. }
  199. s.setTLSConnVerified(cc.ID(), true)
  200. if dbUser.IsLoginMethodAllowed(dataprovider.LoginMethodTLSCertificate, nil) {
  201. connection, err := s.validateUser(dbUser, cc, dataprovider.LoginMethodTLSCertificate)
  202. defer updateLoginMetrics(&dbUser, ipAddr, dataprovider.LoginMethodTLSCertificate, err)
  203. if err != nil {
  204. return nil, err
  205. }
  206. connection.Log(logger.LevelInfo, "User id: %d, logged in with FTP using a TLS certificate, username: %#v, home_dir: %#v remote addr: %#v",
  207. dbUser.ID, dbUser.Username, dbUser.HomeDir, ipAddr)
  208. dataprovider.UpdateLastLogin(&dbUser) //nolint:errcheck
  209. return connection, nil
  210. }
  211. }
  212. }
  213. }
  214. return nil, nil
  215. }
  216. func (s *Server) buildTLSConfig() {
  217. if certMgr != nil {
  218. s.tlsConfig = &tls.Config{
  219. GetCertificate: certMgr.GetCertificateFunc(),
  220. MinVersion: tls.VersionTLS12,
  221. CipherSuites: s.binding.ciphers,
  222. PreferServerCipherSuites: true,
  223. }
  224. if s.binding.isMutualTLSEnabled() {
  225. s.tlsConfig.ClientCAs = certMgr.GetRootCAs()
  226. s.tlsConfig.VerifyConnection = s.verifyTLSConnection
  227. switch s.binding.ClientAuthType {
  228. case 1:
  229. s.tlsConfig.ClientAuth = tls.RequireAndVerifyClientCert
  230. case 2:
  231. s.tlsConfig.ClientAuth = tls.VerifyClientCertIfGiven
  232. }
  233. }
  234. }
  235. }
  236. // GetTLSConfig returns the TLS configuration for this server
  237. func (s *Server) GetTLSConfig() (*tls.Config, error) {
  238. if s.tlsConfig != nil {
  239. return s.tlsConfig, nil
  240. }
  241. return nil, errors.New("no TLS certificate configured")
  242. }
  243. func (s *Server) verifyTLSConnection(state tls.ConnectionState) error {
  244. if certMgr != nil {
  245. var clientCrt *x509.Certificate
  246. var clientCrtName string
  247. if len(state.PeerCertificates) > 0 {
  248. clientCrt = state.PeerCertificates[0]
  249. clientCrtName = clientCrt.Subject.String()
  250. }
  251. if len(state.VerifiedChains) == 0 {
  252. if s.binding.ClientAuthType == 2 {
  253. return nil
  254. }
  255. logger.Warn(logSender, "", "TLS connection cannot be verified: unable to get verification chain")
  256. return errors.New("TLS connection cannot be verified: unable to get verification chain")
  257. }
  258. for _, verifiedChain := range state.VerifiedChains {
  259. var caCrt *x509.Certificate
  260. if len(verifiedChain) > 0 {
  261. caCrt = verifiedChain[len(verifiedChain)-1]
  262. }
  263. if certMgr.IsRevoked(clientCrt, caCrt) {
  264. logger.Debug(logSender, "", "tls handshake error, client certificate %#v has beed revoked", clientCrtName)
  265. return common.ErrCrtRevoked
  266. }
  267. }
  268. }
  269. return nil
  270. }
  271. func (s *Server) validateUser(user dataprovider.User, cc ftpserver.ClientContext, loginMethod string) (*Connection, error) {
  272. connectionID := fmt.Sprintf("%v_%v_%v", common.ProtocolFTP, s.ID, cc.ID())
  273. if !filepath.IsAbs(user.HomeDir) {
  274. logger.Warn(logSender, connectionID, "user %#v has an invalid home dir: %#v. Home dir must be an absolute path, login not allowed",
  275. user.Username, user.HomeDir)
  276. return nil, fmt.Errorf("cannot login user with invalid home dir: %#v", user.HomeDir)
  277. }
  278. if utils.IsStringInSlice(common.ProtocolFTP, user.Filters.DeniedProtocols) {
  279. logger.Debug(logSender, connectionID, "cannot login user %#v, protocol FTP is not allowed", user.Username)
  280. return nil, fmt.Errorf("protocol FTP is not allowed for user %#v", user.Username)
  281. }
  282. if !user.IsLoginMethodAllowed(loginMethod, nil) {
  283. logger.Debug(logSender, connectionID, "cannot login user %#v, %v login method is not allowed", user.Username, loginMethod)
  284. return nil, fmt.Errorf("login method %v is not allowed for user %#v", loginMethod, user.Username)
  285. }
  286. if user.MaxSessions > 0 {
  287. activeSessions := common.Connections.GetActiveSessions(user.Username)
  288. if activeSessions >= user.MaxSessions {
  289. logger.Debug(logSender, connectionID, "authentication refused for user: %#v, too many open sessions: %v/%v", user.Username,
  290. activeSessions, user.MaxSessions)
  291. return nil, fmt.Errorf("too many open sessions: %v", activeSessions)
  292. }
  293. }
  294. remoteAddr := cc.RemoteAddr().String()
  295. if !user.IsLoginFromAddrAllowed(remoteAddr) {
  296. logger.Debug(logSender, connectionID, "cannot login user %#v, remote address is not allowed: %v", user.Username, remoteAddr)
  297. return nil, fmt.Errorf("login for user %#v is not allowed from this address: %v", user.Username, remoteAddr)
  298. }
  299. err := user.CheckFsRoot(connectionID)
  300. if err != nil {
  301. errClose := user.CloseFs()
  302. logger.Warn(logSender, connectionID, "unable to check fs root: %v close fs error: %v", err, errClose)
  303. return nil, err
  304. }
  305. connection := &Connection{
  306. BaseConnection: common.NewBaseConnection(fmt.Sprintf("%v_%v", s.ID, cc.ID()), common.ProtocolFTP, user),
  307. clientContext: cc,
  308. }
  309. err = common.Connections.Swap(connection)
  310. if err != nil {
  311. err = user.CloseFs()
  312. logger.Warn(logSender, connectionID, "unable to swap connection, close fs error: %v", err)
  313. return nil, errors.New("internal authentication error")
  314. }
  315. return connection, nil
  316. }
  317. func updateLoginMetrics(user *dataprovider.User, ip, loginMethod string, err error) {
  318. metrics.AddLoginAttempt(loginMethod)
  319. if err != nil {
  320. logger.ConnectionFailedLog(user.Username, ip, loginMethod,
  321. common.ProtocolFTP, err.Error())
  322. event := common.HostEventLoginFailed
  323. if _, ok := err.(*dataprovider.RecordNotFoundError); ok {
  324. event = common.HostEventUserNotFound
  325. }
  326. common.AddDefenderEvent(ip, event)
  327. }
  328. metrics.AddLoginResult(loginMethod, err)
  329. dataprovider.ExecutePostLoginHook(user, loginMethod, ip, common.ProtocolFTP, err)
  330. }