server.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. package webdavd
  2. import (
  3. "context"
  4. "crypto/tls"
  5. "crypto/x509"
  6. "errors"
  7. "fmt"
  8. "log"
  9. "net/http"
  10. "path"
  11. "path/filepath"
  12. "runtime/debug"
  13. "strings"
  14. "time"
  15. "github.com/go-chi/chi/v5/middleware"
  16. "github.com/rs/cors"
  17. "github.com/rs/xid"
  18. "golang.org/x/net/webdav"
  19. "github.com/drakkan/sftpgo/common"
  20. "github.com/drakkan/sftpgo/dataprovider"
  21. "github.com/drakkan/sftpgo/logger"
  22. "github.com/drakkan/sftpgo/metrics"
  23. "github.com/drakkan/sftpgo/utils"
  24. )
  25. var (
  26. err401 = errors.New("Unauthorized")
  27. xForwardedFor = http.CanonicalHeaderKey("X-Forwarded-For")
  28. xRealIP = http.CanonicalHeaderKey("X-Real-IP")
  29. )
  30. type webDavServer struct {
  31. config *Configuration
  32. binding Binding
  33. }
  34. func (s *webDavServer) listenAndServe(compressor *middleware.Compressor) error {
  35. handler := compressor.Handler(s)
  36. httpServer := &http.Server{
  37. Addr: s.binding.GetAddress(),
  38. ReadHeaderTimeout: 30 * time.Second,
  39. IdleTimeout: 120 * time.Second,
  40. MaxHeaderBytes: 1 << 16, // 64KB
  41. ErrorLog: log.New(&logger.StdLoggerWrapper{Sender: logSender}, "", 0),
  42. }
  43. if s.config.Cors.Enabled {
  44. c := cors.New(cors.Options{
  45. AllowedOrigins: s.config.Cors.AllowedOrigins,
  46. AllowedMethods: s.config.Cors.AllowedMethods,
  47. AllowedHeaders: s.config.Cors.AllowedHeaders,
  48. ExposedHeaders: s.config.Cors.ExposedHeaders,
  49. MaxAge: s.config.Cors.MaxAge,
  50. AllowCredentials: s.config.Cors.AllowCredentials,
  51. OptionsPassthrough: true,
  52. })
  53. handler = c.Handler(handler)
  54. }
  55. httpServer.Handler = handler
  56. if certMgr != nil && s.binding.EnableHTTPS {
  57. serviceStatus.Bindings = append(serviceStatus.Bindings, s.binding)
  58. httpServer.TLSConfig = &tls.Config{
  59. GetCertificate: certMgr.GetCertificateFunc(),
  60. MinVersion: tls.VersionTLS12,
  61. CipherSuites: utils.GetTLSCiphersFromNames(s.binding.TLSCipherSuites),
  62. PreferServerCipherSuites: true,
  63. }
  64. logger.Debug(logSender, "", "configured TLS cipher suites for binding %#v: %v", s.binding.GetAddress(),
  65. httpServer.TLSConfig.CipherSuites)
  66. if s.binding.isMutualTLSEnabled() {
  67. httpServer.TLSConfig.ClientCAs = certMgr.GetRootCAs()
  68. httpServer.TLSConfig.VerifyConnection = s.verifyTLSConnection
  69. switch s.binding.ClientAuthType {
  70. case 1:
  71. httpServer.TLSConfig.ClientAuth = tls.RequireAndVerifyClientCert
  72. case 2:
  73. httpServer.TLSConfig.ClientAuth = tls.VerifyClientCertIfGiven
  74. }
  75. }
  76. logger.Info(logSender, "", "starting HTTPS serving, binding: %v", s.binding.GetAddress())
  77. return httpServer.ListenAndServeTLS("", "")
  78. }
  79. s.binding.EnableHTTPS = false
  80. serviceStatus.Bindings = append(serviceStatus.Bindings, s.binding)
  81. logger.Info(logSender, "", "starting HTTP serving, binding: %v", s.binding.GetAddress())
  82. return httpServer.ListenAndServe()
  83. }
  84. func (s *webDavServer) verifyTLSConnection(state tls.ConnectionState) error {
  85. if certMgr != nil {
  86. var clientCrt *x509.Certificate
  87. var clientCrtName string
  88. if len(state.PeerCertificates) > 0 {
  89. clientCrt = state.PeerCertificates[0]
  90. clientCrtName = clientCrt.Subject.String()
  91. }
  92. if len(state.VerifiedChains) == 0 {
  93. if s.binding.ClientAuthType == 2 {
  94. return nil
  95. }
  96. logger.Warn(logSender, "", "TLS connection cannot be verified: unable to get verification chain")
  97. return errors.New("TLS connection cannot be verified: unable to get verification chain")
  98. }
  99. for _, verifiedChain := range state.VerifiedChains {
  100. var caCrt *x509.Certificate
  101. if len(verifiedChain) > 0 {
  102. caCrt = verifiedChain[len(verifiedChain)-1]
  103. }
  104. if certMgr.IsRevoked(clientCrt, caCrt) {
  105. logger.Debug(logSender, "", "tls handshake error, client certificate %#v has been revoked", clientCrtName)
  106. return common.ErrCrtRevoked
  107. }
  108. }
  109. }
  110. return nil
  111. }
  112. // returns true if we have to handle a HEAD response, for a directory, ourself
  113. func (s *webDavServer) checkRequestMethod(ctx context.Context, r *http.Request, connection *Connection) bool {
  114. // see RFC4918, section 9.4
  115. if r.Method == http.MethodGet || r.Method == http.MethodHead {
  116. p := path.Clean(r.URL.Path)
  117. info, err := connection.Stat(ctx, p)
  118. if err == nil && info.IsDir() {
  119. if r.Method == http.MethodHead {
  120. return true
  121. }
  122. r.Method = "PROPFIND"
  123. if r.Header.Get("Depth") == "" {
  124. r.Header.Add("Depth", "1")
  125. }
  126. }
  127. }
  128. return false
  129. }
  130. // ServeHTTP implements the http.Handler interface
  131. func (s *webDavServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  132. defer func() {
  133. if r := recover(); r != nil {
  134. logger.Error(logSender, "", "panic in ServeHTTP: %#v stack strace: %v", r, string(debug.Stack()))
  135. http.Error(w, common.ErrGenericFailure.Error(), http.StatusInternalServerError)
  136. }
  137. }()
  138. if !common.Connections.IsNewConnectionAllowed() {
  139. logger.Log(logger.LevelDebug, common.ProtocolFTP, "", "connection refused, configured limit reached")
  140. http.Error(w, common.ErrConnectionDenied.Error(), http.StatusServiceUnavailable)
  141. return
  142. }
  143. checkRemoteAddress(r)
  144. ipAddr := utils.GetIPFromRemoteAddress(r.RemoteAddr)
  145. if common.IsBanned(ipAddr) {
  146. http.Error(w, common.ErrConnectionDenied.Error(), http.StatusForbidden)
  147. return
  148. }
  149. if err := common.Config.ExecutePostConnectHook(ipAddr, common.ProtocolWebDAV); err != nil {
  150. http.Error(w, common.ErrConnectionDenied.Error(), http.StatusForbidden)
  151. return
  152. }
  153. user, isCached, lockSystem, loginMethod, err := s.authenticate(r, ipAddr)
  154. if err != nil {
  155. w.Header().Set("WWW-Authenticate", "Basic realm=\"SFTPGo WebDAV\"")
  156. http.Error(w, fmt.Sprintf("Authentication error: %v", err), http.StatusUnauthorized)
  157. return
  158. }
  159. connectionID, err := s.validateUser(&user, r, loginMethod)
  160. if err != nil {
  161. updateLoginMetrics(&user, ipAddr, loginMethod, err)
  162. http.Error(w, err.Error(), http.StatusForbidden)
  163. return
  164. }
  165. if !isCached {
  166. err = user.CheckFsRoot(connectionID)
  167. } else {
  168. _, err = user.GetFilesystem(connectionID)
  169. }
  170. if err != nil {
  171. errClose := user.CloseFs()
  172. logger.Warn(logSender, connectionID, "unable to check fs root: %v close fs error: %v", err, errClose)
  173. updateLoginMetrics(&user, ipAddr, loginMethod, err)
  174. http.Error(w, err.Error(), http.StatusInternalServerError)
  175. return
  176. }
  177. updateLoginMetrics(&user, ipAddr, loginMethod, err)
  178. ctx := context.WithValue(r.Context(), requestIDKey, connectionID)
  179. ctx = context.WithValue(ctx, requestStartKey, time.Now())
  180. connection := &Connection{
  181. BaseConnection: common.NewBaseConnection(connectionID, common.ProtocolWebDAV, user),
  182. request: r,
  183. }
  184. common.Connections.Add(connection)
  185. defer common.Connections.Remove(connection.GetID())
  186. dataprovider.UpdateLastLogin(&user) //nolint:errcheck
  187. if s.checkRequestMethod(ctx, r, connection) {
  188. w.Header().Set("Content-Type", "text/xml; charset=utf-8")
  189. w.WriteHeader(http.StatusMultiStatus)
  190. w.Write([]byte("")) //nolint:errcheck
  191. return
  192. }
  193. handler := webdav.Handler{
  194. Prefix: s.binding.Prefix,
  195. FileSystem: connection,
  196. LockSystem: lockSystem,
  197. Logger: writeLog,
  198. }
  199. handler.ServeHTTP(w, r.WithContext(ctx))
  200. }
  201. func (s *webDavServer) getCredentialsAndLoginMethod(r *http.Request) (string, string, string, *x509.Certificate, bool) {
  202. var tlsCert *x509.Certificate
  203. loginMethod := dataprovider.LoginMethodPassword
  204. username, password, ok := r.BasicAuth()
  205. if s.binding.isMutualTLSEnabled() && r.TLS != nil {
  206. if len(r.TLS.PeerCertificates) > 0 {
  207. tlsCert = r.TLS.PeerCertificates[0]
  208. if ok {
  209. loginMethod = dataprovider.LoginMethodTLSCertificateAndPwd
  210. } else {
  211. loginMethod = dataprovider.LoginMethodTLSCertificate
  212. username = tlsCert.Subject.CommonName
  213. password = ""
  214. }
  215. ok = true
  216. }
  217. }
  218. return username, password, loginMethod, tlsCert, ok
  219. }
  220. func (s *webDavServer) authenticate(r *http.Request, ip string) (dataprovider.User, bool, webdav.LockSystem, string, error) {
  221. var user dataprovider.User
  222. var err error
  223. username, password, loginMethod, tlsCert, ok := s.getCredentialsAndLoginMethod(r)
  224. if !ok {
  225. return user, false, nil, loginMethod, err401
  226. }
  227. result, ok := dataprovider.GetCachedWebDAVUser(username)
  228. if ok {
  229. cachedUser := result.(*dataprovider.CachedUser)
  230. if cachedUser.IsExpired() {
  231. dataprovider.RemoveCachedWebDAVUser(username)
  232. } else {
  233. if !cachedUser.User.IsTLSUsernameVerificationEnabled() {
  234. // for backward compatibility with 2.0.x we only check the password
  235. tlsCert = nil
  236. loginMethod = dataprovider.LoginMethodPassword
  237. }
  238. if err := dataprovider.CheckCachedUserCredentials(cachedUser, password, loginMethod, common.ProtocolWebDAV, tlsCert); err == nil {
  239. return cachedUser.User, true, cachedUser.LockSystem, loginMethod, nil
  240. }
  241. updateLoginMetrics(&cachedUser.User, ip, loginMethod, dataprovider.ErrInvalidCredentials)
  242. return user, false, nil, loginMethod, dataprovider.ErrInvalidCredentials
  243. }
  244. }
  245. user, loginMethod, err = dataprovider.CheckCompositeCredentials(username, password, ip, loginMethod,
  246. common.ProtocolWebDAV, tlsCert)
  247. if err != nil {
  248. user.Username = username
  249. updateLoginMetrics(&user, ip, loginMethod, err)
  250. return user, false, nil, loginMethod, err
  251. }
  252. lockSystem := webdav.NewMemLS()
  253. cachedUser := &dataprovider.CachedUser{
  254. User: user,
  255. Password: password,
  256. LockSystem: lockSystem,
  257. }
  258. if s.config.Cache.Users.ExpirationTime > 0 {
  259. cachedUser.Expiration = time.Now().Add(time.Duration(s.config.Cache.Users.ExpirationTime) * time.Minute)
  260. }
  261. dataprovider.CacheWebDAVUser(cachedUser, s.config.Cache.Users.MaxSize)
  262. return user, false, lockSystem, loginMethod, nil
  263. }
  264. func (s *webDavServer) validateUser(user *dataprovider.User, r *http.Request, loginMethod string) (string, error) {
  265. connID := xid.New().String()
  266. connectionID := fmt.Sprintf("%v_%v", common.ProtocolWebDAV, connID)
  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 connID, fmt.Errorf("cannot login user with invalid home dir: %#v", user.HomeDir)
  271. }
  272. if utils.IsStringInSlice(common.ProtocolWebDAV, user.Filters.DeniedProtocols) {
  273. logger.Debug(logSender, connectionID, "cannot login user %#v, protocol DAV is not allowed", user.Username)
  274. return connID, fmt.Errorf("protocol DAV 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 connID, 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, connID, "authentication refused for user: %#v, too many open sessions: %v/%v", user.Username,
  284. activeSessions, user.MaxSessions)
  285. return connID, fmt.Errorf("too many open sessions: %v", activeSessions)
  286. }
  287. }
  288. if !user.IsLoginFromAddrAllowed(r.RemoteAddr) {
  289. logger.Debug(logSender, connectionID, "cannot login user %#v, remote address is not allowed: %v", user.Username, r.RemoteAddr)
  290. return connID, fmt.Errorf("login for user %#v is not allowed from this address: %v", user.Username, r.RemoteAddr)
  291. }
  292. return connID, nil
  293. }
  294. func writeLog(r *http.Request, err error) {
  295. scheme := "http"
  296. if r.TLS != nil {
  297. scheme = "https"
  298. }
  299. fields := map[string]interface{}{
  300. "remote_addr": r.RemoteAddr,
  301. "proto": r.Proto,
  302. "method": r.Method,
  303. "user_agent": r.UserAgent(),
  304. "uri": fmt.Sprintf("%s://%s%s", scheme, r.Host, r.RequestURI)}
  305. if reqID, ok := r.Context().Value(requestIDKey).(string); ok {
  306. fields["request_id"] = reqID
  307. }
  308. if reqStart, ok := r.Context().Value(requestStartKey).(time.Time); ok {
  309. fields["elapsed_ms"] = time.Since(reqStart).Nanoseconds() / 1000000
  310. }
  311. logger.GetLogger().Info().
  312. Timestamp().
  313. Str("sender", logSender).
  314. Fields(fields).
  315. Err(err).
  316. Send()
  317. }
  318. func checkRemoteAddress(r *http.Request) {
  319. if common.Config.ProxyProtocol != 0 {
  320. return
  321. }
  322. var ip string
  323. if xrip := r.Header.Get(xRealIP); xrip != "" {
  324. ip = xrip
  325. } else if xff := r.Header.Get(xForwardedFor); xff != "" {
  326. i := strings.Index(xff, ", ")
  327. if i == -1 {
  328. i = len(xff)
  329. }
  330. ip = strings.TrimSpace(xff[:i])
  331. }
  332. if len(ip) > 0 {
  333. r.RemoteAddr = ip
  334. }
  335. }
  336. func updateLoginMetrics(user *dataprovider.User, ip, loginMethod string, err error) {
  337. metrics.AddLoginAttempt(loginMethod)
  338. if err != nil {
  339. logger.ConnectionFailedLog(user.Username, ip, loginMethod, common.ProtocolWebDAV, err.Error())
  340. event := common.HostEventLoginFailed
  341. if _, ok := err.(*dataprovider.RecordNotFoundError); ok {
  342. event = common.HostEventUserNotFound
  343. }
  344. common.AddDefenderEvent(ip, event)
  345. }
  346. metrics.AddLoginResult(loginMethod, err)
  347. dataprovider.ExecutePostLoginHook(user, loginMethod, ip, common.ProtocolWebDAV, err)
  348. }