server.go 15 KB

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