server.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. // Copyright (C) 2019-2023 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. )
  41. type webDavServer struct {
  42. config *Configuration
  43. binding Binding
  44. }
  45. func (s *webDavServer) listenAndServe(compressor *middleware.Compressor) error {
  46. handler := compressor.Handler(s)
  47. httpServer := &http.Server{
  48. ReadHeaderTimeout: 30 * time.Second,
  49. ReadTimeout: 60 * time.Second,
  50. WriteTimeout: 60 * time.Second,
  51. IdleTimeout: 60 * time.Second,
  52. MaxHeaderBytes: 1 << 16, // 64KB
  53. ErrorLog: log.New(&logger.StdLoggerWrapper{Sender: logSender}, "", 0),
  54. }
  55. if s.config.Cors.Enabled {
  56. c := cors.New(cors.Options{
  57. AllowedOrigins: util.RemoveDuplicates(s.config.Cors.AllowedOrigins, true),
  58. AllowedMethods: util.RemoveDuplicates(s.config.Cors.AllowedMethods, true),
  59. AllowedHeaders: util.RemoveDuplicates(s.config.Cors.AllowedHeaders, true),
  60. ExposedHeaders: util.RemoveDuplicates(s.config.Cors.ExposedHeaders, true),
  61. MaxAge: s.config.Cors.MaxAge,
  62. AllowCredentials: s.config.Cors.AllowCredentials,
  63. OptionsPassthrough: s.config.Cors.OptionsPassthrough,
  64. OptionsSuccessStatus: s.config.Cors.OptionsSuccessStatus,
  65. AllowPrivateNetwork: s.config.Cors.AllowPrivateNetwork,
  66. })
  67. handler = c.Handler(handler)
  68. }
  69. httpServer.Handler = handler
  70. if certMgr != nil && s.binding.EnableHTTPS {
  71. serviceStatus.Bindings = append(serviceStatus.Bindings, s.binding)
  72. certID := common.DefaultTLSKeyPaidID
  73. if getConfigPath(s.binding.CertificateFile, "") != "" && getConfigPath(s.binding.CertificateKeyFile, "") != "" {
  74. certID = s.binding.GetAddress()
  75. }
  76. httpServer.TLSConfig = &tls.Config{
  77. GetCertificate: certMgr.GetCertificateFunc(certID),
  78. MinVersion: util.GetTLSVersion(s.binding.MinTLSVersion),
  79. NextProtos: []string{"http/1.1", "h2"},
  80. CipherSuites: util.GetTLSCiphersFromNames(s.binding.TLSCipherSuites),
  81. PreferServerCipherSuites: true,
  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. ipAddr := s.checkRemoteAddress(r)
  159. common.Connections.AddClientConnection(ipAddr)
  160. defer common.Connections.RemoveClientConnection(ipAddr)
  161. if err := common.Connections.IsNewConnectionAllowed(ipAddr, common.ProtocolWebDAV); err != nil {
  162. logger.Log(logger.LevelDebug, common.ProtocolWebDAV, "", "connection not allowed from ip %q: %v", ipAddr, err)
  163. http.Error(w, err.Error(), http.StatusServiceUnavailable)
  164. return
  165. }
  166. if common.IsBanned(ipAddr, common.ProtocolWebDAV) {
  167. http.Error(w, common.ErrConnectionDenied.Error(), http.StatusForbidden)
  168. return
  169. }
  170. delay, err := common.LimitRate(common.ProtocolWebDAV, ipAddr)
  171. if err != nil {
  172. delay += 499999999 * time.Nanosecond
  173. w.Header().Set("Retry-After", fmt.Sprintf("%.0f", delay.Seconds()))
  174. w.Header().Set("X-Retry-In", delay.String())
  175. http.Error(w, err.Error(), http.StatusTooManyRequests)
  176. return
  177. }
  178. if err := common.Config.ExecutePostConnectHook(ipAddr, common.ProtocolWebDAV); err != nil {
  179. http.Error(w, common.ErrConnectionDenied.Error(), http.StatusForbidden)
  180. return
  181. }
  182. user, isCached, lockSystem, loginMethod, err := s.authenticate(r, ipAddr)
  183. if err != nil {
  184. if !s.binding.DisableWWWAuthHeader {
  185. w.Header().Set("WWW-Authenticate", "Basic realm=\"SFTPGo WebDAV\"")
  186. }
  187. http.Error(w, fmt.Sprintf("Authentication error: %v", err), http.StatusUnauthorized)
  188. return
  189. }
  190. connectionID, err := s.validateUser(&user, r, loginMethod)
  191. if err != nil {
  192. // remove the cached user, we have not yet validated its filesystem
  193. dataprovider.RemoveCachedWebDAVUser(user.Username)
  194. updateLoginMetrics(&user, ipAddr, loginMethod, err)
  195. http.Error(w, err.Error(), http.StatusForbidden)
  196. return
  197. }
  198. if !isCached {
  199. err = user.CheckFsRoot(connectionID)
  200. } else {
  201. _, err = user.GetFilesystemForPath("/", connectionID)
  202. }
  203. if err != nil {
  204. errClose := user.CloseFs()
  205. logger.Warn(logSender, connectionID, "unable to check fs root: %v close fs error: %v", err, errClose)
  206. updateLoginMetrics(&user, ipAddr, loginMethod, common.ErrInternalFailure)
  207. http.Error(w, err.Error(), http.StatusInternalServerError)
  208. return
  209. }
  210. connection := &Connection{
  211. BaseConnection: common.NewBaseConnection(connectionID, common.ProtocolWebDAV, util.GetHTTPLocalAddress(r),
  212. r.RemoteAddr, user),
  213. request: r,
  214. }
  215. if err = common.Connections.Add(connection); err != nil {
  216. errClose := user.CloseFs()
  217. logger.Warn(logSender, connectionID, "unable add connection: %v close fs error: %v", err, errClose)
  218. updateLoginMetrics(&user, ipAddr, loginMethod, err)
  219. http.Error(w, err.Error(), http.StatusTooManyRequests)
  220. return
  221. }
  222. defer common.Connections.Remove(connection.GetID())
  223. updateLoginMetrics(&user, ipAddr, loginMethod, err)
  224. ctx := context.WithValue(r.Context(), requestIDKey, connectionID)
  225. ctx = context.WithValue(ctx, requestStartKey, time.Now())
  226. dataprovider.UpdateLastLogin(&user)
  227. if s.checkRequestMethod(ctx, r, connection) {
  228. w.Header().Set("Content-Type", "text/xml; charset=utf-8")
  229. w.WriteHeader(http.StatusMultiStatus)
  230. w.Write([]byte("")) //nolint:errcheck
  231. writeLog(r, http.StatusMultiStatus, nil)
  232. return
  233. }
  234. handler := webdav.Handler{
  235. Prefix: s.binding.Prefix,
  236. FileSystem: connection,
  237. LockSystem: lockSystem,
  238. Logger: writeLog,
  239. }
  240. handler.ServeHTTP(w, r.WithContext(ctx))
  241. }
  242. func (s *webDavServer) getCredentialsAndLoginMethod(r *http.Request) (string, string, string, *x509.Certificate, bool) {
  243. var tlsCert *x509.Certificate
  244. loginMethod := dataprovider.LoginMethodPassword
  245. username, password, ok := r.BasicAuth()
  246. if s.binding.isMutualTLSEnabled() && r.TLS != nil {
  247. if len(r.TLS.PeerCertificates) > 0 {
  248. tlsCert = r.TLS.PeerCertificates[0]
  249. if ok {
  250. loginMethod = dataprovider.LoginMethodTLSCertificateAndPwd
  251. } else {
  252. loginMethod = dataprovider.LoginMethodTLSCertificate
  253. username = tlsCert.Subject.CommonName
  254. password = ""
  255. }
  256. ok = true
  257. }
  258. }
  259. return username, password, loginMethod, tlsCert, ok
  260. }
  261. func (s *webDavServer) authenticate(r *http.Request, ip string) (dataprovider.User, bool, webdav.LockSystem, string, error) {
  262. var user dataprovider.User
  263. var err error
  264. username, password, loginMethod, tlsCert, ok := s.getCredentialsAndLoginMethod(r)
  265. if !ok {
  266. user.Username = username
  267. return user, false, nil, loginMethod, common.ErrNoCredentials
  268. }
  269. cachedUser, ok := dataprovider.GetCachedWebDAVUser(username)
  270. if ok {
  271. if cachedUser.IsExpired() {
  272. dataprovider.RemoveCachedWebDAVUser(username)
  273. } else {
  274. if !cachedUser.User.IsTLSUsernameVerificationEnabled() {
  275. // for backward compatibility with 2.0.x we only check the password
  276. tlsCert = nil
  277. loginMethod = dataprovider.LoginMethodPassword
  278. }
  279. cu, u, err := dataprovider.CheckCachedUserCredentials(cachedUser, password, ip, loginMethod, common.ProtocolWebDAV, tlsCert)
  280. if err == nil {
  281. if cu != nil {
  282. return cu.User, true, cu.LockSystem, loginMethod, nil
  283. }
  284. lockSystem := webdav.NewMemLS()
  285. cachedUser = &dataprovider.CachedUser{
  286. User: *u,
  287. Password: password,
  288. LockSystem: lockSystem,
  289. Expiration: s.config.Cache.Users.getExpirationTime(),
  290. }
  291. dataprovider.CacheWebDAVUser(cachedUser)
  292. return cachedUser.User, false, cachedUser.LockSystem, loginMethod, nil
  293. }
  294. updateLoginMetrics(&cachedUser.User, ip, loginMethod, dataprovider.ErrInvalidCredentials)
  295. return user, false, nil, loginMethod, dataprovider.ErrInvalidCredentials
  296. }
  297. }
  298. user, loginMethod, err = dataprovider.CheckCompositeCredentials(username, password, ip, loginMethod,
  299. common.ProtocolWebDAV, tlsCert)
  300. if err != nil {
  301. user.Username = username
  302. updateLoginMetrics(&user, ip, loginMethod, err)
  303. return user, false, nil, loginMethod, dataprovider.ErrInvalidCredentials
  304. }
  305. lockSystem := webdav.NewMemLS()
  306. cachedUser = &dataprovider.CachedUser{
  307. User: user,
  308. Password: password,
  309. LockSystem: lockSystem,
  310. Expiration: s.config.Cache.Users.getExpirationTime(),
  311. }
  312. dataprovider.CacheWebDAVUser(cachedUser)
  313. return user, false, lockSystem, loginMethod, nil
  314. }
  315. func (s *webDavServer) validateUser(user *dataprovider.User, r *http.Request, loginMethod string) (string, error) {
  316. connID := xid.New().String()
  317. connectionID := fmt.Sprintf("%v_%v", common.ProtocolWebDAV, connID)
  318. if !filepath.IsAbs(user.HomeDir) {
  319. logger.Warn(logSender, connectionID, "user %q has an invalid home dir: %q. Home dir must be an absolute path, login not allowed",
  320. user.Username, user.HomeDir)
  321. return connID, fmt.Errorf("cannot login user with invalid home dir: %q", user.HomeDir)
  322. }
  323. if util.Contains(user.Filters.DeniedProtocols, common.ProtocolWebDAV) {
  324. logger.Info(logSender, connectionID, "cannot login user %q, protocol DAV is not allowed", user.Username)
  325. return connID, fmt.Errorf("protocol DAV is not allowed for user %q", user.Username)
  326. }
  327. if !user.IsLoginMethodAllowed(loginMethod, common.ProtocolWebDAV, nil) {
  328. logger.Info(logSender, connectionID, "cannot login user %q, %v login method is not allowed",
  329. user.Username, loginMethod)
  330. return connID, fmt.Errorf("login method %v is not allowed for user %q", loginMethod, user.Username)
  331. }
  332. if !user.IsLoginFromAddrAllowed(r.RemoteAddr) {
  333. logger.Info(logSender, connectionID, "cannot login user %q, remote address is not allowed: %v",
  334. user.Username, r.RemoteAddr)
  335. return connID, fmt.Errorf("login for user %q is not allowed from this address: %v", user.Username, r.RemoteAddr)
  336. }
  337. return connID, nil
  338. }
  339. func (s *webDavServer) checkRemoteAddress(r *http.Request) string {
  340. ipAddr := util.GetIPFromRemoteAddress(r.RemoteAddr)
  341. var ip net.IP
  342. isUnixSocket := filepath.IsAbs(s.binding.Address)
  343. if !isUnixSocket {
  344. ip = net.ParseIP(ipAddr)
  345. }
  346. if isUnixSocket || ip != nil {
  347. for _, allow := range s.binding.allowHeadersFrom {
  348. if allow(ip) {
  349. parsedIP := util.GetRealIP(r, s.binding.ClientIPProxyHeader, s.binding.ClientIPHeaderDepth)
  350. if parsedIP != "" {
  351. ipAddr = parsedIP
  352. r.RemoteAddr = ipAddr
  353. }
  354. break
  355. }
  356. }
  357. }
  358. return ipAddr
  359. }
  360. func writeLog(r *http.Request, status int, err error) {
  361. scheme := "http"
  362. if r.TLS != nil {
  363. scheme = "https"
  364. }
  365. fields := map[string]any{
  366. "remote_addr": r.RemoteAddr,
  367. "proto": r.Proto,
  368. "method": r.Method,
  369. "user_agent": r.UserAgent(),
  370. "uri": fmt.Sprintf("%s://%s%s", scheme, r.Host, r.RequestURI)}
  371. if reqID, ok := r.Context().Value(requestIDKey).(string); ok {
  372. fields["request_id"] = reqID
  373. }
  374. if reqStart, ok := r.Context().Value(requestStartKey).(time.Time); ok {
  375. fields["elapsed_ms"] = time.Since(reqStart).Nanoseconds() / 1000000
  376. }
  377. if depth := r.Header.Get("Depth"); depth != "" {
  378. fields["depth"] = depth
  379. }
  380. if contentLength := r.Header.Get("Content-Length"); contentLength != "" {
  381. fields["content_length"] = contentLength
  382. }
  383. if timeout := r.Header.Get("Timeout"); timeout != "" {
  384. fields["timeout"] = timeout
  385. }
  386. if status != 0 {
  387. fields["resp_status"] = status
  388. }
  389. logger.GetLogger().Info().
  390. Timestamp().
  391. Str("sender", logSender).
  392. Fields(fields).
  393. Err(err).
  394. Send()
  395. }
  396. func updateLoginMetrics(user *dataprovider.User, ip, loginMethod string, err error) {
  397. metric.AddLoginAttempt(loginMethod)
  398. if err != nil && err != common.ErrInternalFailure && err != common.ErrNoCredentials {
  399. logger.ConnectionFailedLog(user.Username, ip, loginMethod, common.ProtocolWebDAV, err.Error())
  400. event := common.HostEventLoginFailed
  401. logEv := notifier.LogEventTypeLoginFailed
  402. if errors.Is(err, util.ErrNotFound) {
  403. event = common.HostEventUserNotFound
  404. logEv = notifier.LogEventTypeLoginNoUser
  405. }
  406. common.AddDefenderEvent(ip, common.ProtocolWebDAV, event)
  407. plugin.Handler.NotifyLogEvent(logEv, common.ProtocolWebDAV, user.Username, ip, "", err)
  408. }
  409. metric.AddLoginResult(loginMethod, err)
  410. dataprovider.ExecutePostLoginHook(user, loginMethod, ip, common.ProtocolWebDAV, err)
  411. }