server.go 16 KB

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