server.go 13 KB

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