server.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. // Copyright (C) 2019 Nicola Murino
  2. //
  3. // This program is free software: you can redistribute it and/or modify
  4. // it under the terms of the GNU Affero General Public License as published
  5. // by the Free Software Foundation, version 3.
  6. //
  7. // This program is distributed in the hope that it will be useful,
  8. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. // GNU Affero General Public License for more details.
  11. //
  12. // You should have received a copy of the GNU Affero General Public License
  13. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. package webdavd
  15. import (
  16. "context"
  17. "crypto/tls"
  18. "crypto/x509"
  19. "errors"
  20. "fmt"
  21. "log"
  22. "net"
  23. "net/http"
  24. "path"
  25. "path/filepath"
  26. "runtime/debug"
  27. "slices"
  28. "strings"
  29. "time"
  30. "github.com/drakkan/webdav"
  31. "github.com/go-chi/chi/v5/middleware"
  32. "github.com/rs/cors"
  33. "github.com/rs/xid"
  34. "github.com/rs/zerolog"
  35. "github.com/sftpgo/sdk/plugin/notifier"
  36. "github.com/drakkan/sftpgo/v2/internal/common"
  37. "github.com/drakkan/sftpgo/v2/internal/dataprovider"
  38. "github.com/drakkan/sftpgo/v2/internal/logger"
  39. "github.com/drakkan/sftpgo/v2/internal/metric"
  40. "github.com/drakkan/sftpgo/v2/internal/plugin"
  41. "github.com/drakkan/sftpgo/v2/internal/util"
  42. "github.com/drakkan/sftpgo/v2/internal/version"
  43. )
  44. type webDavServer struct {
  45. config *Configuration
  46. binding Binding
  47. }
  48. func (s *webDavServer) listenAndServe(compressor *middleware.Compressor) error {
  49. handler := compressor.Handler(s)
  50. httpServer := &http.Server{
  51. ReadHeaderTimeout: 30 * time.Second,
  52. IdleTimeout: 60 * time.Second,
  53. MaxHeaderBytes: 1 << 16, // 64KB
  54. ErrorLog: log.New(&logger.StdLoggerWrapper{Sender: logSender}, "", 0),
  55. }
  56. if s.config.Cors.Enabled {
  57. c := cors.New(cors.Options{
  58. AllowedOrigins: util.RemoveDuplicates(s.config.Cors.AllowedOrigins, true),
  59. AllowedMethods: util.RemoveDuplicates(s.config.Cors.AllowedMethods, true),
  60. AllowedHeaders: util.RemoveDuplicates(s.config.Cors.AllowedHeaders, true),
  61. ExposedHeaders: util.RemoveDuplicates(s.config.Cors.ExposedHeaders, true),
  62. MaxAge: s.config.Cors.MaxAge,
  63. AllowCredentials: s.config.Cors.AllowCredentials,
  64. OptionsPassthrough: s.config.Cors.OptionsPassthrough,
  65. OptionsSuccessStatus: s.config.Cors.OptionsSuccessStatus,
  66. AllowPrivateNetwork: s.config.Cors.AllowPrivateNetwork,
  67. })
  68. handler = c.Handler(handler)
  69. }
  70. httpServer.Handler = handler
  71. if certMgr != nil && s.binding.EnableHTTPS {
  72. serviceStatus.Bindings = append(serviceStatus.Bindings, s.binding)
  73. certID := common.DefaultTLSKeyPaidID
  74. if getConfigPath(s.binding.CertificateFile, "") != "" && getConfigPath(s.binding.CertificateKeyFile, "") != "" {
  75. certID = s.binding.GetAddress()
  76. }
  77. httpServer.TLSConfig = &tls.Config{
  78. GetCertificate: certMgr.GetCertificateFunc(certID),
  79. MinVersion: util.GetTLSVersion(s.binding.MinTLSVersion),
  80. NextProtos: util.GetALPNProtocols(s.binding.Protocols),
  81. CipherSuites: util.GetTLSCiphersFromNames(s.binding.TLSCipherSuites),
  82. }
  83. logger.Debug(logSender, "", "configured TLS cipher suites for binding %q: %v, certID: %v",
  84. s.binding.GetAddress(), httpServer.TLSConfig.CipherSuites, certID)
  85. if s.binding.isMutualTLSEnabled() {
  86. httpServer.TLSConfig.ClientCAs = certMgr.GetRootCAs()
  87. httpServer.TLSConfig.VerifyConnection = s.verifyTLSConnection
  88. switch s.binding.ClientAuthType {
  89. case 1:
  90. httpServer.TLSConfig.ClientAuth = tls.RequireAndVerifyClientCert
  91. case 2:
  92. httpServer.TLSConfig.ClientAuth = tls.VerifyClientCertIfGiven
  93. }
  94. }
  95. return util.HTTPListenAndServe(httpServer, s.binding.Address, s.binding.Port, true,
  96. s.binding.listenerWrapper(), logSender)
  97. }
  98. s.binding.EnableHTTPS = false
  99. serviceStatus.Bindings = append(serviceStatus.Bindings, s.binding)
  100. return util.HTTPListenAndServe(httpServer, s.binding.Address, s.binding.Port, false,
  101. s.binding.listenerWrapper(), logSender)
  102. }
  103. func (s *webDavServer) verifyTLSConnection(state tls.ConnectionState) error {
  104. if certMgr != nil {
  105. var clientCrt *x509.Certificate
  106. var clientCrtName string
  107. if len(state.PeerCertificates) > 0 {
  108. clientCrt = state.PeerCertificates[0]
  109. clientCrtName = clientCrt.Subject.String()
  110. }
  111. if len(state.VerifiedChains) == 0 {
  112. if s.binding.ClientAuthType == 2 {
  113. return nil
  114. }
  115. logger.Warn(logSender, "", "TLS connection cannot be verified: unable to get verification chain")
  116. return errors.New("TLS connection cannot be verified: unable to get verification chain")
  117. }
  118. for _, verifiedChain := range state.VerifiedChains {
  119. var caCrt *x509.Certificate
  120. if len(verifiedChain) > 0 {
  121. caCrt = verifiedChain[len(verifiedChain)-1]
  122. }
  123. if certMgr.IsRevoked(clientCrt, caCrt) {
  124. logger.Debug(logSender, "", "tls handshake error, client certificate %q has been revoked", clientCrtName)
  125. return common.ErrCrtRevoked
  126. }
  127. }
  128. }
  129. return nil
  130. }
  131. // returns true if we have to handle a HEAD response, for a directory, ourself
  132. func (s *webDavServer) checkRequestMethod(ctx context.Context, r *http.Request, connection *Connection) bool {
  133. // see RFC4918, section 9.4
  134. if r.Method == http.MethodGet || r.Method == http.MethodHead {
  135. p := path.Clean(r.URL.Path)
  136. if s.binding.Prefix != "" {
  137. p = strings.TrimPrefix(p, s.binding.Prefix)
  138. }
  139. info, err := connection.Stat(ctx, p)
  140. if err == nil && info.IsDir() {
  141. if r.Method == http.MethodHead {
  142. return true
  143. }
  144. r.Method = "PROPFIND"
  145. if r.Header.Get("Depth") == "" {
  146. r.Header.Add("Depth", "1")
  147. }
  148. }
  149. }
  150. return false
  151. }
  152. // ServeHTTP implements the http.Handler interface
  153. func (s *webDavServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  154. defer func() {
  155. if r := recover(); r != nil {
  156. logger.Error(logSender, "", "panic in ServeHTTP: %q stack trace: %v", r, string(debug.Stack()))
  157. http.Error(w, common.ErrGenericFailure.Error(), http.StatusInternalServerError)
  158. }
  159. }()
  160. responseControllerDeadlines(
  161. http.NewResponseController(w),
  162. time.Now().Add(60*time.Second),
  163. time.Now().Add(60*time.Second),
  164. )
  165. w.Header().Set("Server", version.GetServerVersion("/", false))
  166. ipAddr := s.checkRemoteAddress(r)
  167. common.Connections.AddClientConnection(ipAddr)
  168. defer common.Connections.RemoveClientConnection(ipAddr)
  169. if err := common.Connections.IsNewConnectionAllowed(ipAddr, common.ProtocolWebDAV); err != nil {
  170. logger.Log(logger.LevelDebug, common.ProtocolWebDAV, "", "connection not allowed from ip %q: %v", ipAddr, err)
  171. http.Error(w, err.Error(), http.StatusServiceUnavailable)
  172. return
  173. }
  174. if common.IsBanned(ipAddr, common.ProtocolWebDAV) {
  175. http.Error(w, common.ErrConnectionDenied.Error(), http.StatusForbidden)
  176. return
  177. }
  178. delay, err := common.LimitRate(common.ProtocolWebDAV, ipAddr)
  179. if err != nil {
  180. delay += 499999999 * time.Nanosecond
  181. w.Header().Set("Retry-After", fmt.Sprintf("%.0f", delay.Seconds()))
  182. w.Header().Set("X-Retry-In", delay.String())
  183. http.Error(w, err.Error(), http.StatusTooManyRequests)
  184. return
  185. }
  186. if err := common.Config.ExecutePostConnectHook(ipAddr, common.ProtocolWebDAV); err != nil {
  187. http.Error(w, common.ErrConnectionDenied.Error(), http.StatusForbidden)
  188. return
  189. }
  190. user, isCached, lockSystem, loginMethod, err := s.authenticate(r, ipAddr)
  191. if err != nil {
  192. if !s.binding.DisableWWWAuthHeader {
  193. w.Header().Set("WWW-Authenticate", fmt.Sprintf("Basic realm=\"%s WebDAV\"", version.GetServerVersion("_", false)))
  194. }
  195. http.Error(w, fmt.Sprintf("Authentication error: %v", err), http.StatusUnauthorized)
  196. return
  197. }
  198. connectionID, err := s.validateUser(&user, r, loginMethod)
  199. if err != nil {
  200. // remove the cached user, we have not yet validated its filesystem
  201. dataprovider.RemoveCachedWebDAVUser(user.Username)
  202. updateLoginMetrics(&user, ipAddr, loginMethod, err, r)
  203. http.Error(w, err.Error(), http.StatusForbidden)
  204. return
  205. }
  206. if !isCached {
  207. err = user.CheckFsRoot(connectionID)
  208. } else {
  209. _, err = user.GetFilesystemForPath("/", connectionID)
  210. }
  211. if err != nil {
  212. errClose := user.CloseFs()
  213. logger.Warn(logSender, connectionID, "unable to check fs root: %v close fs error: %v", err, errClose)
  214. updateLoginMetrics(&user, ipAddr, loginMethod, common.ErrInternalFailure, r)
  215. http.Error(w, err.Error(), http.StatusInternalServerError)
  216. return
  217. }
  218. baseConn := common.NewBaseConnection(connectionID, common.ProtocolWebDAV, util.GetHTTPLocalAddress(r),
  219. r.RemoteAddr, user)
  220. connection := newConnection(baseConn, w, r)
  221. if err = common.Connections.Add(connection); err != nil {
  222. errClose := user.CloseFs()
  223. logger.Warn(logSender, connectionID, "unable add connection: %v close fs error: %v", err, errClose)
  224. updateLoginMetrics(&user, ipAddr, loginMethod, err, r)
  225. http.Error(w, err.Error(), http.StatusTooManyRequests)
  226. return
  227. }
  228. defer common.Connections.Remove(connection.GetID())
  229. updateLoginMetrics(&user, ipAddr, loginMethod, err, r)
  230. ctx := context.WithValue(r.Context(), requestIDKey, connectionID)
  231. ctx = context.WithValue(ctx, requestStartKey, time.Now())
  232. dataprovider.UpdateLastLogin(&user)
  233. if s.checkRequestMethod(ctx, r, connection) {
  234. w.Header().Set("Content-Type", "text/xml; charset=utf-8")
  235. w.WriteHeader(http.StatusMultiStatus)
  236. w.Write([]byte("")) //nolint:errcheck
  237. writeLog(r, http.StatusMultiStatus, nil)
  238. return
  239. }
  240. handler := webdav.Handler{
  241. Prefix: s.binding.Prefix,
  242. FileSystem: connection,
  243. LockSystem: lockSystem,
  244. Logger: writeLog,
  245. }
  246. handler.ServeHTTP(w, r.WithContext(ctx))
  247. }
  248. func (s *webDavServer) getCredentialsAndLoginMethod(r *http.Request) (string, string, string, *x509.Certificate, bool) {
  249. var tlsCert *x509.Certificate
  250. loginMethod := dataprovider.LoginMethodPassword
  251. username, password, ok := r.BasicAuth()
  252. if s.binding.isMutualTLSEnabled() && r.TLS != nil {
  253. if len(r.TLS.PeerCertificates) > 0 {
  254. tlsCert = r.TLS.PeerCertificates[0]
  255. if ok {
  256. loginMethod = dataprovider.LoginMethodTLSCertificateAndPwd
  257. } else {
  258. loginMethod = dataprovider.LoginMethodTLSCertificate
  259. username = tlsCert.Subject.CommonName
  260. password = ""
  261. }
  262. ok = true
  263. }
  264. }
  265. return username, password, loginMethod, tlsCert, ok
  266. }
  267. func (s *webDavServer) authenticate(r *http.Request, ip string) (dataprovider.User, bool, webdav.LockSystem, string, error) {
  268. var user dataprovider.User
  269. var err error
  270. username, password, loginMethod, tlsCert, ok := s.getCredentialsAndLoginMethod(r)
  271. if !ok {
  272. user.Username = username
  273. return user, false, nil, loginMethod, common.ErrNoCredentials
  274. }
  275. cachedUser, ok := dataprovider.GetCachedWebDAVUser(username)
  276. if ok {
  277. if cachedUser.IsExpired() {
  278. dataprovider.RemoveCachedWebDAVUser(username)
  279. } else {
  280. if !cachedUser.User.IsTLSVerificationEnabled() {
  281. // for backward compatibility with 2.0.x we only check the password
  282. tlsCert = nil
  283. loginMethod = dataprovider.LoginMethodPassword
  284. }
  285. cu, u, err := dataprovider.CheckCachedUserCredentials(cachedUser, password, ip, loginMethod, common.ProtocolWebDAV, tlsCert)
  286. if err == nil {
  287. if cu != nil {
  288. return cu.User, true, cu.LockSystem, loginMethod, nil
  289. }
  290. lockSystem := webdav.NewMemLS()
  291. cachedUser = &dataprovider.CachedUser{
  292. User: *u,
  293. Password: password,
  294. LockSystem: lockSystem,
  295. Expiration: s.config.Cache.Users.getExpirationTime(),
  296. }
  297. dataprovider.CacheWebDAVUser(cachedUser)
  298. return cachedUser.User, false, cachedUser.LockSystem, loginMethod, nil
  299. }
  300. updateLoginMetrics(&cachedUser.User, ip, loginMethod, dataprovider.ErrInvalidCredentials, r)
  301. return user, false, nil, loginMethod, dataprovider.ErrInvalidCredentials
  302. }
  303. }
  304. user, loginMethod, err = dataprovider.CheckCompositeCredentials(username, password, ip, loginMethod,
  305. common.ProtocolWebDAV, tlsCert)
  306. if err != nil {
  307. user.Username = username
  308. updateLoginMetrics(&user, ip, loginMethod, err, r)
  309. return user, false, nil, loginMethod, dataprovider.ErrInvalidCredentials
  310. }
  311. lockSystem := webdav.NewMemLS()
  312. cachedUser = &dataprovider.CachedUser{
  313. User: user,
  314. Password: password,
  315. LockSystem: lockSystem,
  316. Expiration: s.config.Cache.Users.getExpirationTime(),
  317. }
  318. dataprovider.CacheWebDAVUser(cachedUser)
  319. return user, false, lockSystem, loginMethod, nil
  320. }
  321. func (s *webDavServer) validateUser(user *dataprovider.User, r *http.Request, loginMethod string) (string, error) {
  322. connID := xid.New().String()
  323. connectionID := fmt.Sprintf("%v_%v", common.ProtocolWebDAV, connID)
  324. if !filepath.IsAbs(user.HomeDir) {
  325. logger.Warn(logSender, connectionID, "user %q has an invalid home dir: %q. Home dir must be an absolute path, login not allowed",
  326. user.Username, user.HomeDir)
  327. return connID, fmt.Errorf("cannot login user with invalid home dir: %q", user.HomeDir)
  328. }
  329. if slices.Contains(user.Filters.DeniedProtocols, common.ProtocolWebDAV) {
  330. logger.Info(logSender, connectionID, "cannot login user %q, protocol DAV is not allowed", user.Username)
  331. return connID, fmt.Errorf("protocol DAV is not allowed for user %q", user.Username)
  332. }
  333. if !user.IsLoginMethodAllowed(loginMethod, common.ProtocolWebDAV) {
  334. logger.Info(logSender, connectionID, "cannot login user %q, %v login method is not allowed",
  335. user.Username, loginMethod)
  336. return connID, fmt.Errorf("login method %v is not allowed for user %q", loginMethod, user.Username)
  337. }
  338. if !user.IsLoginFromAddrAllowed(r.RemoteAddr) {
  339. logger.Info(logSender, connectionID, "cannot login user %q, remote address is not allowed: %v",
  340. user.Username, r.RemoteAddr)
  341. return connID, fmt.Errorf("login for user %q is not allowed from this address: %v", user.Username, r.RemoteAddr)
  342. }
  343. return connID, nil
  344. }
  345. func (s *webDavServer) checkRemoteAddress(r *http.Request) string {
  346. ipAddr := util.GetIPFromRemoteAddress(r.RemoteAddr)
  347. var ip net.IP
  348. isUnixSocket := filepath.IsAbs(s.binding.Address)
  349. if !isUnixSocket {
  350. ip = net.ParseIP(ipAddr)
  351. }
  352. if isUnixSocket || ip != nil {
  353. for _, allow := range s.binding.allowHeadersFrom {
  354. if allow(ip) {
  355. parsedIP := util.GetRealIP(r, s.binding.ClientIPProxyHeader, s.binding.ClientIPHeaderDepth)
  356. if parsedIP != "" {
  357. ipAddr = parsedIP
  358. r.RemoteAddr = ipAddr
  359. }
  360. break
  361. }
  362. }
  363. }
  364. return ipAddr
  365. }
  366. func responseControllerDeadlines(rc *http.ResponseController, read, write time.Time) {
  367. if err := rc.SetReadDeadline(read); err != nil {
  368. logger.Error(logSender, "", "unable to set read timeout to %s: %v", read, err)
  369. }
  370. if err := rc.SetWriteDeadline(write); err != nil {
  371. logger.Error(logSender, "", "unable to set write timeout to %s: %v", write, err)
  372. }
  373. }
  374. func writeLog(r *http.Request, status int, err error) {
  375. scheme := "http"
  376. cipherSuite := ""
  377. if r.TLS != nil {
  378. scheme = "https"
  379. cipherSuite = tls.CipherSuiteName(r.TLS.CipherSuite)
  380. }
  381. fields := map[string]any{
  382. "remote_addr": r.RemoteAddr,
  383. "proto": r.Proto,
  384. "method": r.Method,
  385. "user_agent": r.UserAgent(),
  386. "uri": fmt.Sprintf("%s://%s%s", scheme, r.Host, r.RequestURI),
  387. "cipher_suite": cipherSuite,
  388. }
  389. if reqID, ok := r.Context().Value(requestIDKey).(string); ok {
  390. fields["request_id"] = reqID
  391. }
  392. if reqStart, ok := r.Context().Value(requestStartKey).(time.Time); ok {
  393. fields["elapsed_ms"] = time.Since(reqStart).Nanoseconds() / 1000000
  394. }
  395. if depth := r.Header.Get("Depth"); depth != "" {
  396. fields["depth"] = depth
  397. }
  398. if contentLength := r.Header.Get("Content-Length"); contentLength != "" {
  399. fields["content_length"] = contentLength
  400. }
  401. if timeout := r.Header.Get("Timeout"); timeout != "" {
  402. fields["timeout"] = timeout
  403. }
  404. if status != 0 {
  405. fields["resp_status"] = status
  406. }
  407. var ev *zerolog.Event
  408. if status >= http.StatusInternalServerError {
  409. ev = logger.GetLogger().Error()
  410. } else if status >= http.StatusBadRequest {
  411. ev = logger.GetLogger().Warn()
  412. } else {
  413. ev = logger.GetLogger().Debug()
  414. }
  415. ev.
  416. Timestamp().
  417. Str("sender", logSender).
  418. Fields(fields).
  419. Err(err).
  420. Send()
  421. }
  422. func updateLoginMetrics(user *dataprovider.User, ip, loginMethod string, err error, r *http.Request) {
  423. metric.AddLoginAttempt(loginMethod)
  424. if err == nil {
  425. logger.LoginLog(user.Username, ip, loginMethod, common.ProtocolWebDAV, "", r.UserAgent(), r.TLS != nil, "")
  426. plugin.Handler.NotifyLogEvent(notifier.LogEventTypeLoginOK, common.ProtocolWebDAV, user.Username, ip, "", nil)
  427. common.DelayLogin(nil)
  428. } else if err != common.ErrInternalFailure && err != common.ErrNoCredentials {
  429. logger.ConnectionFailedLog(user.Username, ip, loginMethod, common.ProtocolWebDAV, err.Error())
  430. event := common.HostEventLoginFailed
  431. logEv := notifier.LogEventTypeLoginFailed
  432. if errors.Is(err, util.ErrNotFound) {
  433. event = common.HostEventUserNotFound
  434. logEv = notifier.LogEventTypeLoginNoUser
  435. }
  436. common.AddDefenderEvent(ip, common.ProtocolWebDAV, event)
  437. plugin.Handler.NotifyLogEvent(logEv, common.ProtocolWebDAV, user.Username, ip, "", err)
  438. if loginMethod != dataprovider.LoginMethodTLSCertificate {
  439. common.DelayLogin(err)
  440. }
  441. }
  442. metric.AddLoginResult(loginMethod, err)
  443. dataprovider.ExecutePostLoginHook(user, loginMethod, ip, common.ProtocolWebDAV, err)
  444. }