server.go 14 KB

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