middleware.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. package http
  2. import (
  3. "context"
  4. "encoding/base64"
  5. "fmt"
  6. "net/http"
  7. "strings"
  8. "sync"
  9. goauth "github.com/abbot/go-http-auth"
  10. "github.com/rclone/rclone/fs"
  11. )
  12. // parseAuthorization parses the Authorization header into user, pass
  13. // it returns a boolean as to whether the parse was successful
  14. func parseAuthorization(r *http.Request) (user, pass string, ok bool) {
  15. authHeader := r.Header.Get("Authorization")
  16. if authHeader != "" {
  17. s := strings.SplitN(authHeader, " ", 2)
  18. if len(s) == 2 && s[0] == "Basic" {
  19. b, err := base64.StdEncoding.DecodeString(s[1])
  20. if err == nil {
  21. parts := strings.SplitN(string(b), ":", 2)
  22. user = parts[0]
  23. if len(parts) > 1 {
  24. pass = parts[1]
  25. ok = true
  26. }
  27. }
  28. }
  29. }
  30. return
  31. }
  32. // LoggedBasicAuth simply wraps the goauth.BasicAuth struct
  33. type LoggedBasicAuth struct {
  34. goauth.BasicAuth
  35. }
  36. // CheckAuth extends BasicAuth.CheckAuth to emit a log entry for unauthorised requests
  37. func (a *LoggedBasicAuth) CheckAuth(r *http.Request) string {
  38. username := a.BasicAuth.CheckAuth(r)
  39. if username == "" {
  40. user, _, _ := parseAuthorization(r)
  41. fs.Infof(r.URL.Path, "%s: Unauthorized request from %s", r.RemoteAddr, user)
  42. }
  43. return username
  44. }
  45. // NewLoggedBasicAuthenticator instantiates a new instance of LoggedBasicAuthenticator
  46. func NewLoggedBasicAuthenticator(realm string, secrets goauth.SecretProvider) *LoggedBasicAuth {
  47. return &LoggedBasicAuth{BasicAuth: goauth.BasicAuth{Realm: realm, Secrets: secrets}}
  48. }
  49. // Helper to generate required interface for middleware
  50. func basicAuth(authenticator *LoggedBasicAuth) func(next http.Handler) http.Handler {
  51. return func(next http.Handler) http.Handler {
  52. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  53. // skip auth for unix socket
  54. if IsUnixSocket(r) {
  55. next.ServeHTTP(w, r)
  56. return
  57. }
  58. // skip auth for CORS preflight
  59. if r.Method == "OPTIONS" {
  60. next.ServeHTTP(w, r)
  61. return
  62. }
  63. username := authenticator.CheckAuth(r)
  64. if username == "" {
  65. authenticator.RequireAuth(w, r)
  66. return
  67. }
  68. ctx := context.WithValue(r.Context(), ctxKeyUser, username)
  69. next.ServeHTTP(w, r.WithContext(ctx))
  70. })
  71. }
  72. }
  73. // MiddlewareAuthCertificateUser instantiates middleware that extracts the authenticated user via client certificate common name
  74. func MiddlewareAuthCertificateUser() Middleware {
  75. return func(next http.Handler) http.Handler {
  76. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  77. for _, cert := range r.TLS.PeerCertificates {
  78. if cert.Subject.CommonName != "" {
  79. r = r.WithContext(context.WithValue(r.Context(), ctxKeyUser, cert.Subject.CommonName))
  80. next.ServeHTTP(w, r)
  81. return
  82. }
  83. }
  84. code := http.StatusUnauthorized
  85. w.Header().Set("Content-Type", "text/plain")
  86. http.Error(w, http.StatusText(code), code)
  87. })
  88. }
  89. }
  90. // MiddlewareAuthHtpasswd instantiates middleware that authenticates against the passed htpasswd file
  91. func MiddlewareAuthHtpasswd(path, realm string) Middleware {
  92. fs.Infof(nil, "Using %q as htpasswd storage", path)
  93. secretProvider := goauth.HtpasswdFileProvider(path)
  94. authenticator := NewLoggedBasicAuthenticator(realm, secretProvider)
  95. return basicAuth(authenticator)
  96. }
  97. // MiddlewareAuthBasic instantiates middleware that authenticates for a single user
  98. func MiddlewareAuthBasic(user, pass, realm, salt string) Middleware {
  99. fs.Infof(nil, "Using --user %s --pass XXXX as authenticated user", user)
  100. pass = string(goauth.MD5Crypt([]byte(pass), []byte(salt), []byte("$1$")))
  101. secretProvider := func(u, r string) string {
  102. if user == u {
  103. return pass
  104. }
  105. return ""
  106. }
  107. authenticator := NewLoggedBasicAuthenticator(realm, secretProvider)
  108. return basicAuth(authenticator)
  109. }
  110. // MiddlewareAuthCustom instantiates middleware that authenticates using a custom function
  111. func MiddlewareAuthCustom(fn CustomAuthFn, realm string, userFromContext bool) Middleware {
  112. return func(next http.Handler) http.Handler {
  113. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  114. // skip auth for unix socket
  115. if IsUnixSocket(r) {
  116. next.ServeHTTP(w, r)
  117. return
  118. }
  119. // skip auth for CORS preflight
  120. if r.Method == "OPTIONS" {
  121. next.ServeHTTP(w, r)
  122. return
  123. }
  124. user, pass, ok := parseAuthorization(r)
  125. if !ok && userFromContext {
  126. user, ok = CtxGetUser(r.Context())
  127. }
  128. if !ok {
  129. code := http.StatusUnauthorized
  130. w.Header().Set("Content-Type", "text/plain")
  131. w.Header().Set("WWW-Authenticate", fmt.Sprintf(`Basic realm=%q, charset="UTF-8"`, realm))
  132. http.Error(w, http.StatusText(code), code)
  133. return
  134. }
  135. value, err := fn(user, pass)
  136. if err != nil {
  137. fs.Infof(r.URL.Path, "%s: Auth failed from %s: %v", r.RemoteAddr, user, err)
  138. goauth.NewBasicAuthenticator(realm, func(user, realm string) string { return "" }).RequireAuth(w, r) //Reuse BasicAuth error reporting
  139. return
  140. }
  141. if value != nil {
  142. r = r.WithContext(context.WithValue(r.Context(), ctxKeyAuth, value))
  143. }
  144. next.ServeHTTP(w, r)
  145. })
  146. }
  147. }
  148. var onlyOnceWarningAllowOrigin sync.Once
  149. // MiddlewareCORS instantiates middleware that handles basic CORS protections for rcd
  150. func MiddlewareCORS(allowOrigin string) Middleware {
  151. onlyOnceWarningAllowOrigin.Do(func() {
  152. if allowOrigin == "*" {
  153. fs.Logf(nil, "Warning: Allow origin set to *. This can cause serious security problems.")
  154. }
  155. })
  156. return func(next http.Handler) http.Handler {
  157. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  158. // skip cors for unix sockets
  159. if IsUnixSocket(r) {
  160. next.ServeHTTP(w, r)
  161. return
  162. }
  163. if allowOrigin != "" {
  164. w.Header().Add("Access-Control-Allow-Origin", allowOrigin)
  165. w.Header().Add("Access-Control-Allow-Headers", "authorization, Content-Type")
  166. w.Header().Add("Access-Control-Allow-Methods", "COPY, DELETE, GET, HEAD, LOCK, MKCOL, MOVE, OPTIONS, POST, PROPFIND, PROPPATCH, PUT, TRACE, UNLOCK")
  167. }
  168. next.ServeHTTP(w, r)
  169. })
  170. }
  171. }
  172. // MiddlewareStripPrefix instantiates middleware that removes the BaseURL from the path
  173. func MiddlewareStripPrefix(prefix string) Middleware {
  174. return func(next http.Handler) http.Handler {
  175. stripPrefixHandler := http.StripPrefix(prefix, next)
  176. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  177. // Allow OPTIONS on the root only
  178. if r.URL.Path == "/" && r.Method == "OPTIONS" {
  179. next.ServeHTTP(w, r)
  180. return
  181. }
  182. stripPrefixHandler.ServeHTTP(w, r)
  183. })
  184. }
  185. }