You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

262 lines
12 KiB

5 years ago
5 years ago
FEATURE: add JWT to HTTP endpoints of Filer and use them in S3 Client - one JWT for reading and one for writing, analogous to how the JWT between Master and Volume Server works - I did not implement IP `whiteList` parameter on the filer Additionally, because http_util.DownloadFile now sets the JWT, the `download` command should now work when `jwt.signing.read` is configured. By looking at the code, I think this case did not work before. ## Docs to be adjusted after a release Page `Amazon-S3-API`: ``` # Authentication with Filer You can use mTLS for the gRPC connection between S3-API-Proxy and the filer, as explained in [Security-Configuration](Security-Configuration) - controlled by the `grpc.*` configuration in `security.toml`. Starting with version XX, it is also possible to authenticate the HTTP operations between the S3-API-Proxy and the Filer (especially uploading new files). This is configured by setting `filer_jwt.signing.key` and `filer_jwt.signing.read.key` in `security.toml`. With both configurations (gRPC and JWT), it is possible to have Filer and S3 communicate in fully authenticated fashion; so Filer will reject any unauthenticated communication. ``` Page `Security Overview`: ``` The following items are not covered, yet: - master server http REST services Starting with version XX, the Filer HTTP REST services can be secured with a JWT, by setting `filer_jwt.signing.key` and `filer_jwt.signing.read.key` in `security.toml`. ... Before version XX: "weed filer -disableHttp", disable http operations, only gRPC operations are allowed. This works with "weed mount" by FUSE. It does **not work** with the [S3 Gateway](Amazon S3 API), as this does HTTP calls to the Filer. Starting with version XX: secured by JWT, by setting `filer_jwt.signing.key` and `filer_jwt.signing.read.key` in `security.toml`. **This now works with the [S3 Gateway](Amazon S3 API).** ... # Securing Filer HTTP with JWT To enable JWT-based access control for the Filer, 1. generate `security.toml` file by `weed scaffold -config=security` 2. set `filer_jwt.signing.key` to a secret string - and optionally filer_jwt.signing.read.key` as well to a secret string 3. copy the same `security.toml` file to the filers and all S3 proxies. If `filer_jwt.signing.key` is configured: When sending upload/update/delete HTTP operations to a filer server, the request header `Authorization` should be the JWT string (`Authorization: Bearer [JwtToken]`). The operation is authorized after the filer validates the JWT with `filer_jwt.signing.key`. If `filer_jwt.signing.read.key` is configured: When sending GET or HEAD requests to a filer server, the request header `Authorization` should be the JWT string (`Authorization: Bearer [JwtToken]`). The operation is authorized after the filer validates the JWT with `filer_jwt.signing.read.key`. The S3 API Gateway reads the above JWT keys and sends authenticated HTTP requests to the filer. ``` Page `Security Configuration`: ``` (update scaffold file) ... [filer_jwt.signing] key = "blahblahblahblah" [filer_jwt.signing.read] key = "blahblahblahblah" ``` Resolves: #158
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
  1. package s3api
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/seaweedfs/seaweedfs/weed/filer"
  6. "github.com/seaweedfs/seaweedfs/weed/pb/s3_pb"
  7. "github.com/seaweedfs/seaweedfs/weed/s3api/s3account"
  8. "net"
  9. "net/http"
  10. "strings"
  11. "time"
  12. "github.com/gorilla/mux"
  13. "github.com/seaweedfs/seaweedfs/weed/pb"
  14. . "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
  15. "github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
  16. "github.com/seaweedfs/seaweedfs/weed/security"
  17. "github.com/seaweedfs/seaweedfs/weed/util"
  18. "google.golang.org/grpc"
  19. )
  20. type S3ApiServerOption struct {
  21. Filer pb.ServerAddress
  22. Port int
  23. Config string
  24. DomainName string
  25. BucketsPath string
  26. GrpcDialOption grpc.DialOption
  27. AllowEmptyFolder bool
  28. AllowDeleteBucketNotEmpty bool
  29. LocalFilerSocket string
  30. DataCenter string
  31. }
  32. type S3ApiServer struct {
  33. s3_pb.UnimplementedSeaweedS3Server
  34. option *S3ApiServerOption
  35. iam *IdentityAccessManagement
  36. cb *CircuitBreaker
  37. randomClientId int32
  38. filerGuard *security.Guard
  39. client *http.Client
  40. accountManager *s3account.AccountManager
  41. bucketRegistry *BucketRegistry
  42. }
  43. func NewS3ApiServer(router *mux.Router, option *S3ApiServerOption) (s3ApiServer *S3ApiServer, err error) {
  44. v := util.GetViper()
  45. signingKey := v.GetString("jwt.filer_signing.key")
  46. v.SetDefault("jwt.filer_signing.expires_after_seconds", 10)
  47. expiresAfterSec := v.GetInt("jwt.filer_signing.expires_after_seconds")
  48. readSigningKey := v.GetString("jwt.filer_signing.read.key")
  49. v.SetDefault("jwt.filer_signing.read.expires_after_seconds", 60)
  50. readExpiresAfterSec := v.GetInt("jwt.filer_signing.read.expires_after_seconds")
  51. s3ApiServer = &S3ApiServer{
  52. option: option,
  53. iam: NewIdentityAccessManagement(option),
  54. randomClientId: util.RandomInt32(),
  55. filerGuard: security.NewGuard([]string{}, signingKey, expiresAfterSec, readSigningKey, readExpiresAfterSec),
  56. cb: NewCircuitBreaker(option),
  57. }
  58. s3ApiServer.accountManager = s3account.NewAccountManager(s3ApiServer)
  59. s3ApiServer.bucketRegistry = NewBucketRegistry(s3ApiServer)
  60. if option.LocalFilerSocket == "" {
  61. s3ApiServer.client = &http.Client{Transport: &http.Transport{
  62. MaxIdleConns: 1024,
  63. MaxIdleConnsPerHost: 1024,
  64. DisableCompression: true,
  65. }}
  66. } else {
  67. s3ApiServer.client = &http.Client{
  68. Transport: &http.Transport{
  69. DialContext: func(_ context.Context, _, _ string) (net.Conn, error) {
  70. return net.Dial("unix", option.LocalFilerSocket)
  71. },
  72. DisableCompression: true,
  73. },
  74. }
  75. }
  76. s3ApiServer.registerRouter(router)
  77. go s3ApiServer.subscribeMetaEvents("s3", time.Now().UnixNano(), filer.DirectoryEtcRoot, []string{option.BucketsPath})
  78. return s3ApiServer, nil
  79. }
  80. func (s3a *S3ApiServer) registerRouter(router *mux.Router) {
  81. // API Router
  82. apiRouter := router.PathPrefix("/").Subrouter()
  83. // Readiness Probe
  84. apiRouter.Methods("GET").Path("/status").HandlerFunc(s3a.StatusHandler)
  85. apiRouter.Methods("OPTIONS").HandlerFunc(
  86. func(w http.ResponseWriter, r *http.Request) {
  87. w.Header().Set("Access-Control-Allow-Origin", "*")
  88. w.Header().Set("Access-Control-Expose-Headers", "*")
  89. w.Header().Set("Access-Control-Allow-Methods", "*")
  90. w.Header().Set("Access-Control-Allow-Headers", "*")
  91. writeSuccessResponseEmpty(w, r)
  92. })
  93. var routers []*mux.Router
  94. if s3a.option.DomainName != "" {
  95. domainNames := strings.Split(s3a.option.DomainName, ",")
  96. for _, domainName := range domainNames {
  97. routers = append(routers, apiRouter.Host(
  98. fmt.Sprintf("%s.%s:%d", "{bucket:.+}", domainName, s3a.option.Port)).Subrouter())
  99. routers = append(routers, apiRouter.Host(
  100. fmt.Sprintf("%s.%s", "{bucket:.+}", domainName)).Subrouter())
  101. }
  102. }
  103. routers = append(routers, apiRouter.PathPrefix("/{bucket}").Subrouter())
  104. for _, bucket := range routers {
  105. // each case should follow the next rule:
  106. // - requesting object with query must precede any other methods
  107. // - requesting object must precede any methods with buckets
  108. // - requesting bucket with query must precede raw methods with buckets
  109. // - requesting bucket must be processed in the end
  110. // objects with query
  111. // CopyObjectPart
  112. bucket.Methods("PUT").Path("/{object:.+}").HeadersRegexp("X-Amz-Copy-Source", `.*?(\/|%2F).*?`).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.CopyObjectPartHandler, ACTION_WRITE)), "PUT")).Queries("partNumber", "{partNumber:[0-9]+}", "uploadId", "{uploadId:.*}")
  113. // PutObjectPart
  114. bucket.Methods("PUT").Path("/{object:.+}").HandlerFunc(track(s3a.Auth(withAcl(s3a.cb.Limit, s3a.PutObjectPartHandler, ACTION_WRITE)), "PUT")).Queries("partNumber", "{partNumber:[0-9]+}", "uploadId", "{uploadId:.*}")
  115. // CompleteMultipartUpload
  116. bucket.Methods("POST").Path("/{object:.+}").HandlerFunc(track(s3a.Auth(withAcl(s3a.cb.Limit, s3a.CompleteMultipartUploadHandler, ACTION_WRITE)), "POST")).Queries("uploadId", "{uploadId:.*}")
  117. // NewMultipartUpload
  118. bucket.Methods("POST").Path("/{object:.+}").HandlerFunc(track(s3a.Auth(withAcl(s3a.cb.Limit, s3a.NewMultipartUploadHandler, ACTION_WRITE)), "POST")).Queries("uploads", "")
  119. // AbortMultipartUpload
  120. bucket.Methods("DELETE").Path("/{object:.+}").HandlerFunc(track(s3a.Auth(withAcl(s3a.cb.Limit, s3a.AbortMultipartUploadHandler, ACTION_WRITE)), "DELETE")).Queries("uploadId", "{uploadId:.*}")
  121. // ListObjectParts
  122. bucket.Methods("GET").Path("/{object:.+}").HandlerFunc(track(s3a.Auth(withAcl(s3a.cb.Limit, s3a.ListObjectPartsHandler, ACTION_READ)), "GET")).Queries("uploadId", "{uploadId:.*}")
  123. // ListMultipartUploads
  124. bucket.Methods("GET").HandlerFunc(track(s3a.Auth(withAcl(s3a.cb.Limit, s3a.ListMultipartUploadsHandler, ACTION_READ)), "GET")).Queries("uploads", "")
  125. // GetObjectTagging
  126. bucket.Methods("GET").Path("/{object:.+}").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.GetObjectTaggingHandler, ACTION_READ)), "GET")).Queries("tagging", "")
  127. // PutObjectTagging
  128. bucket.Methods("PUT").Path("/{object:.+}").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.PutObjectTaggingHandler, ACTION_TAGGING)), "PUT")).Queries("tagging", "")
  129. // DeleteObjectTagging
  130. bucket.Methods("DELETE").Path("/{object:.+}").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.DeleteObjectTaggingHandler, ACTION_TAGGING)), "DELETE")).Queries("tagging", "")
  131. // PutObjectACL
  132. bucket.Methods("PUT").Path("/{object:.+}").HandlerFunc(track(s3a.Auth(withAcl(s3a.cb.Limit, s3a.PutObjectAclHandler, ACTION_WRITE)), "PUT")).Queries("acl", "")
  133. // PutObjectRetention
  134. bucket.Methods("PUT").Path("/{object:.+}").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.PutObjectRetentionHandler, ACTION_WRITE)), "PUT")).Queries("retention", "")
  135. // PutObjectLegalHold
  136. bucket.Methods("PUT").Path("/{object:.+}").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.PutObjectLegalHoldHandler, ACTION_WRITE)), "PUT")).Queries("legal-hold", "")
  137. // PutObjectLockConfiguration
  138. bucket.Methods("PUT").Path("/{object:.+}").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.PutObjectLockConfigurationHandler, ACTION_WRITE)), "PUT")).Queries("object-lock", "")
  139. // GetObjectACL
  140. bucket.Methods("GET").Path("/{object:.+}").HandlerFunc(track(s3a.Auth(withAcl(s3a.cb.Limit, s3a.GetObjectAclHandler, ACTION_READ)), "GET")).Queries("acl", "")
  141. // objects with query
  142. // raw objects
  143. // HeadObject
  144. bucket.Methods("HEAD").Path("/{object:.+}").HandlerFunc(track(s3a.Auth(withAcl(s3a.cb.Limit, s3a.HeadObjectHandler, ACTION_READ)), "GET"))
  145. // GetObject, but directory listing is not supported
  146. bucket.Methods("GET").Path("/{object:.+}").HandlerFunc(track(s3a.Auth(withAcl(s3a.cb.Limit, s3a.GetObjectHandler, ACTION_READ)), "GET"))
  147. // CopyObject
  148. bucket.Methods("PUT").Path("/{object:.+}").HeadersRegexp("X-Amz-Copy-Source", ".*?(\\/|%2F).*?").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.CopyObjectHandler, ACTION_WRITE)), "COPY"))
  149. // PutObject
  150. bucket.Methods("PUT").Path("/{object:.+}").HandlerFunc(track(s3a.Auth(withAcl(s3a.cb.Limit, s3a.PutObjectHandler, ACTION_WRITE)), "PUT"))
  151. // DeleteObject
  152. bucket.Methods("DELETE").Path("/{object:.+}").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.DeleteObjectHandler, ACTION_WRITE)), "DELETE"))
  153. // raw objects
  154. // buckets with query
  155. // DeleteMultipleObjects
  156. bucket.Methods("POST").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.DeleteMultipleObjectsHandler, ACTION_WRITE)), "DELETE")).Queries("delete", "")
  157. // GetBucketACL
  158. bucket.Methods("GET").HandlerFunc(track(s3a.Auth(withAcl(s3a.cb.Limit, s3a.GetBucketAclHandler, ACTION_READ)), "GET")).Queries("acl", "")
  159. // PutBucketACL
  160. bucket.Methods("PUT").HandlerFunc(track(s3a.Auth(withAcl(s3a.cb.Limit, s3a.PutBucketAclHandler, ACTION_WRITE)), "PUT")).Queries("acl", "")
  161. // GetBucketPolicy
  162. bucket.Methods("GET").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.GetBucketPolicyHandler, ACTION_READ)), "GET")).Queries("policy", "")
  163. // PutBucketPolicy
  164. bucket.Methods("PUT").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.PutBucketPolicyHandler, ACTION_WRITE)), "PUT")).Queries("policy", "")
  165. // DeleteBucketPolicy
  166. bucket.Methods("DELETE").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.DeleteBucketPolicyHandler, ACTION_WRITE)), "DELETE")).Queries("policy", "")
  167. // GetBucketCors
  168. bucket.Methods("GET").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.GetBucketCorsHandler, ACTION_READ)), "GET")).Queries("cors", "")
  169. // PutBucketCors
  170. bucket.Methods("PUT").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.PutBucketCorsHandler, ACTION_WRITE)), "PUT")).Queries("cors", "")
  171. // DeleteBucketCors
  172. bucket.Methods("DELETE").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.DeleteBucketCorsHandler, ACTION_WRITE)), "DELETE")).Queries("cors", "")
  173. // GetBucketLifecycleConfiguration
  174. bucket.Methods("GET").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.GetBucketLifecycleConfigurationHandler, ACTION_READ)), "GET")).Queries("lifecycle", "")
  175. // PutBucketLifecycleConfiguration
  176. bucket.Methods("PUT").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.PutBucketLifecycleConfigurationHandler, ACTION_WRITE)), "PUT")).Queries("lifecycle", "")
  177. // DeleteBucketLifecycleConfiguration
  178. bucket.Methods("DELETE").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.DeleteBucketLifecycleHandler, ACTION_WRITE)), "DELETE")).Queries("lifecycle", "")
  179. // GetBucketLocation
  180. bucket.Methods("GET").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.GetBucketLocationHandler, ACTION_READ)), "GET")).Queries("location", "")
  181. // GetBucketRequestPayment
  182. bucket.Methods("GET").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.GetBucketRequestPaymentHandler, ACTION_READ)), "GET")).Queries("requestPayment", "")
  183. // ListObjectsV2
  184. bucket.Methods("GET").HandlerFunc(track(s3a.Auth(withAcl(s3a.cb.Limit, s3a.ListObjectsV2Handler, ACTION_LIST)), "LIST")).Queries("list-type", "2")
  185. // buckets with query
  186. // PutBucketOwnershipControls
  187. bucket.Methods("PUT").HandlerFunc(track(s3a.Auth(s3a.PutBucketOwnershipControls, ACTION_ADMIN, true), "PUT")).Queries("ownershipControls", "")
  188. //GetBucketOwnershipControls
  189. bucket.Methods("GET").HandlerFunc(track(s3a.Auth(s3a.GetBucketOwnershipControls, ACTION_READ, true), "GET")).Queries("ownershipControls", "")
  190. //DeleteBucketOwnershipControls
  191. bucket.Methods("DELETE").HandlerFunc(track(s3a.Auth(s3a.DeleteBucketOwnershipControls, ACTION_ADMIN, true), "DELETE")).Queries("ownershipControls", "")
  192. // raw buckets
  193. // PostPolicy
  194. bucket.Methods("POST").HeadersRegexp("Content-Type", "multipart/form-data*").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.PostPolicyBucketHandler, ACTION_WRITE)), "POST"))
  195. // HeadBucket
  196. bucket.Methods("HEAD").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.HeadBucketHandler, ACTION_READ)), "GET"))
  197. // PutBucket
  198. bucket.Methods("PUT").HandlerFunc(track(s3a.PutBucketHandler, "PUT"))
  199. // DeleteBucket
  200. bucket.Methods("DELETE").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.DeleteBucketHandler, ACTION_ADMIN)), "DELETE"))
  201. // ListObjectsV1 (Legacy)
  202. bucket.Methods("GET").HandlerFunc(track(s3a.Auth(withAcl(s3a.cb.Limit, s3a.ListObjectsV1Handler, ACTION_LIST)), "LIST"))
  203. // raw buckets
  204. }
  205. // ListBuckets
  206. apiRouter.Methods("GET").Path("/").HandlerFunc(track(s3a.ListBucketsHandler, "LIST"))
  207. // NotFound
  208. apiRouter.NotFoundHandler = http.HandlerFunc(s3err.NotFoundHandler)
  209. }
  210. func withAcl(limitFunc func(http.HandlerFunc, string) (http.HandlerFunc, Action), hf http.HandlerFunc, action string) (http.HandlerFunc, Action, bool) {
  211. f, a := limitFunc(hf, action)
  212. return f, a, true
  213. }