server.go 16 KB

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