server.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  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. utils.CheckTCP4Port(s.binding.Port)
  78. return httpServer.ListenAndServeTLS("", "")
  79. }
  80. s.binding.EnableHTTPS = false
  81. serviceStatus.Bindings = append(serviceStatus.Bindings, s.binding)
  82. logger.Info(logSender, "", "starting HTTP serving, binding: %v", s.binding.GetAddress())
  83. utils.CheckTCP4Port(s.binding.Port)
  84. return httpServer.ListenAndServe()
  85. }
  86. func (s *webDavServer) verifyTLSConnection(state tls.ConnectionState) error {
  87. if certMgr != nil {
  88. var clientCrt *x509.Certificate
  89. var clientCrtName string
  90. if len(state.PeerCertificates) > 0 {
  91. clientCrt = state.PeerCertificates[0]
  92. clientCrtName = clientCrt.Subject.String()
  93. }
  94. if len(state.VerifiedChains) == 0 {
  95. if s.binding.ClientAuthType == 2 {
  96. return nil
  97. }
  98. logger.Warn(logSender, "", "TLS connection cannot be verified: unable to get verification chain")
  99. return errors.New("TLS connection cannot be verified: unable to get verification chain")
  100. }
  101. for _, verifiedChain := range state.VerifiedChains {
  102. var caCrt *x509.Certificate
  103. if len(verifiedChain) > 0 {
  104. caCrt = verifiedChain[len(verifiedChain)-1]
  105. }
  106. if certMgr.IsRevoked(clientCrt, caCrt) {
  107. logger.Debug(logSender, "", "tls handshake error, client certificate %#v has been revoked", clientCrtName)
  108. return common.ErrCrtRevoked
  109. }
  110. }
  111. }
  112. return nil
  113. }
  114. // returns true if we have to handle a HEAD response, for a directory, ourself
  115. func (s *webDavServer) checkRequestMethod(ctx context.Context, r *http.Request, connection *Connection) bool {
  116. // see RFC4918, section 9.4
  117. if r.Method == http.MethodGet || r.Method == http.MethodHead {
  118. p := path.Clean(r.URL.Path)
  119. info, err := connection.Stat(ctx, p)
  120. if err == nil && info.IsDir() {
  121. if r.Method == http.MethodHead {
  122. return true
  123. }
  124. r.Method = "PROPFIND"
  125. if r.Header.Get("Depth") == "" {
  126. r.Header.Add("Depth", "1")
  127. }
  128. }
  129. }
  130. return false
  131. }
  132. // ServeHTTP implements the http.Handler interface
  133. func (s *webDavServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  134. defer func() {
  135. if r := recover(); r != nil {
  136. logger.Error(logSender, "", "panic in ServeHTTP: %#v stack strace: %v", r, string(debug.Stack()))
  137. http.Error(w, common.ErrGenericFailure.Error(), http.StatusInternalServerError)
  138. }
  139. }()
  140. common.Connections.AddNetworkConnection()
  141. defer common.Connections.RemoveNetworkConnection()
  142. if !common.Connections.IsNewConnectionAllowed() {
  143. logger.Log(logger.LevelDebug, common.ProtocolWebDAV, "", "connection refused, configured limit reached")
  144. http.Error(w, common.ErrConnectionDenied.Error(), http.StatusServiceUnavailable)
  145. return
  146. }
  147. checkRemoteAddress(r)
  148. ipAddr := utils.GetIPFromRemoteAddress(r.RemoteAddr)
  149. if common.IsBanned(ipAddr) {
  150. http.Error(w, common.ErrConnectionDenied.Error(), http.StatusForbidden)
  151. return
  152. }
  153. delay, err := common.LimitRate(common.ProtocolWebDAV, ipAddr)
  154. if err != nil {
  155. delay += 499999999 * time.Nanosecond
  156. w.Header().Set("Retry-After", fmt.Sprintf("%.0f", delay.Seconds()))
  157. w.Header().Set("X-Retry-In", delay.String())
  158. http.Error(w, err.Error(), http.StatusTooManyRequests)
  159. return
  160. }
  161. if err := common.Config.ExecutePostConnectHook(ipAddr, common.ProtocolWebDAV); err != nil {
  162. http.Error(w, common.ErrConnectionDenied.Error(), http.StatusForbidden)
  163. return
  164. }
  165. user, isCached, lockSystem, loginMethod, err := s.authenticate(r, ipAddr)
  166. if err != nil {
  167. w.Header().Set("WWW-Authenticate", "Basic realm=\"SFTPGo WebDAV\"")
  168. http.Error(w, fmt.Sprintf("Authentication error: %v", err), http.StatusUnauthorized)
  169. return
  170. }
  171. connectionID, err := s.validateUser(&user, r, loginMethod)
  172. if err != nil {
  173. // remove the cached user, we have not yet validated its filesystem
  174. dataprovider.RemoveCachedWebDAVUser(user.Username)
  175. updateLoginMetrics(&user, ipAddr, loginMethod, err)
  176. http.Error(w, err.Error(), http.StatusForbidden)
  177. return
  178. }
  179. if !isCached {
  180. err = user.CheckFsRoot(connectionID)
  181. } else {
  182. _, err = user.GetFilesystem(connectionID)
  183. }
  184. if err != nil {
  185. errClose := user.CloseFs()
  186. logger.Warn(logSender, connectionID, "unable to check fs root: %v close fs error: %v", err, errClose)
  187. updateLoginMetrics(&user, ipAddr, loginMethod, err)
  188. http.Error(w, err.Error(), http.StatusInternalServerError)
  189. return
  190. }
  191. updateLoginMetrics(&user, ipAddr, loginMethod, err)
  192. ctx := context.WithValue(r.Context(), requestIDKey, connectionID)
  193. ctx = context.WithValue(ctx, requestStartKey, time.Now())
  194. connection := &Connection{
  195. BaseConnection: common.NewBaseConnection(connectionID, common.ProtocolWebDAV, user),
  196. request: r,
  197. }
  198. common.Connections.Add(connection)
  199. defer common.Connections.Remove(connection.GetID())
  200. dataprovider.UpdateLastLogin(&user) //nolint:errcheck
  201. if s.checkRequestMethod(ctx, r, connection) {
  202. w.Header().Set("Content-Type", "text/xml; charset=utf-8")
  203. w.WriteHeader(http.StatusMultiStatus)
  204. w.Write([]byte("")) //nolint:errcheck
  205. return
  206. }
  207. handler := webdav.Handler{
  208. Prefix: s.binding.Prefix,
  209. FileSystem: connection,
  210. LockSystem: lockSystem,
  211. Logger: writeLog,
  212. }
  213. handler.ServeHTTP(w, r.WithContext(ctx))
  214. }
  215. func (s *webDavServer) getCredentialsAndLoginMethod(r *http.Request) (string, string, string, *x509.Certificate, bool) {
  216. var tlsCert *x509.Certificate
  217. loginMethod := dataprovider.LoginMethodPassword
  218. username, password, ok := r.BasicAuth()
  219. if s.binding.isMutualTLSEnabled() && r.TLS != nil {
  220. if len(r.TLS.PeerCertificates) > 0 {
  221. tlsCert = r.TLS.PeerCertificates[0]
  222. if ok {
  223. loginMethod = dataprovider.LoginMethodTLSCertificateAndPwd
  224. } else {
  225. loginMethod = dataprovider.LoginMethodTLSCertificate
  226. username = tlsCert.Subject.CommonName
  227. password = ""
  228. }
  229. ok = true
  230. }
  231. }
  232. return username, password, loginMethod, tlsCert, ok
  233. }
  234. func (s *webDavServer) authenticate(r *http.Request, ip string) (dataprovider.User, bool, webdav.LockSystem, string, error) {
  235. var user dataprovider.User
  236. var err error
  237. username, password, loginMethod, tlsCert, ok := s.getCredentialsAndLoginMethod(r)
  238. if !ok {
  239. return user, false, nil, loginMethod, err401
  240. }
  241. cachedUser, ok := dataprovider.GetCachedWebDAVUser(username)
  242. if ok {
  243. if cachedUser.IsExpired() {
  244. dataprovider.RemoveCachedWebDAVUser(username)
  245. } else {
  246. if !cachedUser.User.IsTLSUsernameVerificationEnabled() {
  247. // for backward compatibility with 2.0.x we only check the password
  248. tlsCert = nil
  249. loginMethod = dataprovider.LoginMethodPassword
  250. }
  251. if err := dataprovider.CheckCachedUserCredentials(cachedUser, password, loginMethod, common.ProtocolWebDAV, tlsCert); err == nil {
  252. return cachedUser.User, true, cachedUser.LockSystem, loginMethod, nil
  253. }
  254. updateLoginMetrics(&cachedUser.User, ip, loginMethod, dataprovider.ErrInvalidCredentials)
  255. return user, false, nil, loginMethod, dataprovider.ErrInvalidCredentials
  256. }
  257. }
  258. user, loginMethod, err = dataprovider.CheckCompositeCredentials(username, password, ip, loginMethod,
  259. common.ProtocolWebDAV, tlsCert)
  260. if err != nil {
  261. user.Username = username
  262. updateLoginMetrics(&user, ip, loginMethod, err)
  263. return user, false, nil, loginMethod, dataprovider.ErrInvalidCredentials
  264. }
  265. lockSystem := webdav.NewMemLS()
  266. cachedUser = &dataprovider.CachedUser{
  267. User: user,
  268. Password: password,
  269. LockSystem: lockSystem,
  270. }
  271. if s.config.Cache.Users.ExpirationTime > 0 {
  272. cachedUser.Expiration = time.Now().Add(time.Duration(s.config.Cache.Users.ExpirationTime) * time.Minute)
  273. }
  274. dataprovider.CacheWebDAVUser(cachedUser)
  275. return user, false, lockSystem, loginMethod, nil
  276. }
  277. func (s *webDavServer) validateUser(user *dataprovider.User, r *http.Request, loginMethod string) (string, error) {
  278. connID := xid.New().String()
  279. connectionID := fmt.Sprintf("%v_%v", common.ProtocolWebDAV, connID)
  280. if !filepath.IsAbs(user.HomeDir) {
  281. logger.Warn(logSender, connectionID, "user %#v has an invalid home dir: %#v. Home dir must be an absolute path, login not allowed",
  282. user.Username, user.HomeDir)
  283. return connID, fmt.Errorf("cannot login user with invalid home dir: %#v", user.HomeDir)
  284. }
  285. if utils.IsStringInSlice(common.ProtocolWebDAV, user.Filters.DeniedProtocols) {
  286. logger.Debug(logSender, connectionID, "cannot login user %#v, protocol DAV is not allowed", user.Username)
  287. return connID, fmt.Errorf("protocol DAV is not allowed for user %#v", user.Username)
  288. }
  289. if !user.IsLoginMethodAllowed(loginMethod, nil) {
  290. logger.Debug(logSender, connectionID, "cannot login user %#v, %v login method is not allowed", user.Username, loginMethod)
  291. return connID, fmt.Errorf("login method %v is not allowed for user %#v", loginMethod, user.Username)
  292. }
  293. if user.MaxSessions > 0 {
  294. activeSessions := common.Connections.GetActiveSessions(user.Username)
  295. if activeSessions >= user.MaxSessions {
  296. logger.Debug(logSender, connID, "authentication refused for user: %#v, too many open sessions: %v/%v", user.Username,
  297. activeSessions, user.MaxSessions)
  298. return connID, fmt.Errorf("too many open sessions: %v", activeSessions)
  299. }
  300. }
  301. if !user.IsLoginFromAddrAllowed(r.RemoteAddr) {
  302. logger.Debug(logSender, connectionID, "cannot login user %#v, remote address is not allowed: %v", user.Username, r.RemoteAddr)
  303. return connID, fmt.Errorf("login for user %#v is not allowed from this address: %v", user.Username, r.RemoteAddr)
  304. }
  305. return connID, nil
  306. }
  307. func writeLog(r *http.Request, err error) {
  308. scheme := "http"
  309. if r.TLS != nil {
  310. scheme = "https"
  311. }
  312. fields := map[string]interface{}{
  313. "remote_addr": r.RemoteAddr,
  314. "proto": r.Proto,
  315. "method": r.Method,
  316. "user_agent": r.UserAgent(),
  317. "uri": fmt.Sprintf("%s://%s%s", scheme, r.Host, r.RequestURI)}
  318. if reqID, ok := r.Context().Value(requestIDKey).(string); ok {
  319. fields["request_id"] = reqID
  320. }
  321. if reqStart, ok := r.Context().Value(requestStartKey).(time.Time); ok {
  322. fields["elapsed_ms"] = time.Since(reqStart).Nanoseconds() / 1000000
  323. }
  324. logger.GetLogger().Info().
  325. Timestamp().
  326. Str("sender", logSender).
  327. Fields(fields).
  328. Err(err).
  329. Send()
  330. }
  331. func checkRemoteAddress(r *http.Request) {
  332. if common.Config.ProxyProtocol != 0 {
  333. return
  334. }
  335. var ip string
  336. if xrip := r.Header.Get(xRealIP); xrip != "" {
  337. ip = xrip
  338. } else if xff := r.Header.Get(xForwardedFor); xff != "" {
  339. i := strings.Index(xff, ", ")
  340. if i == -1 {
  341. i = len(xff)
  342. }
  343. ip = strings.TrimSpace(xff[:i])
  344. }
  345. if len(ip) > 0 {
  346. r.RemoteAddr = ip
  347. }
  348. }
  349. func updateLoginMetrics(user *dataprovider.User, ip, loginMethod string, err error) {
  350. metrics.AddLoginAttempt(loginMethod)
  351. if err != nil {
  352. logger.ConnectionFailedLog(user.Username, ip, loginMethod, common.ProtocolWebDAV, err.Error())
  353. event := common.HostEventLoginFailed
  354. if _, ok := err.(*dataprovider.RecordNotFoundError); ok {
  355. event = common.HostEventUserNotFound
  356. }
  357. common.AddDefenderEvent(ip, event)
  358. }
  359. metrics.AddLoginResult(loginMethod, err)
  360. dataprovider.ExecutePostLoginHook(user, loginMethod, ip, common.ProtocolWebDAV, err)
  361. }