server.go 15 KB

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