mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 18:17:16 +01:00
* s3: refuse a public bucket policy when the bucket blocks public policies PutBucketPolicy stored and enforced a policy granting access to every principal even with BlockPublicPolicy set. Check the stored public access block on the bucket entry that the policy write reads, and answer AccessDenied for a public policy. A policy counts as public when an Allow names a wildcard principal (or uses NotPrincipal) and no fixed-value restricting condition such as aws:SourceIp or aws:SourceVpce narrows it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: keep a public bucket policy from granting anonymous access under RestrictPublicBuckets With RestrictPublicBuckets set, an anonymous request was still allowed by a public bucket policy. The bucket policy engine now treats such an Allow as granting nothing when the bucket restricts public buckets and its policy is public, so the request falls through to the remaining checks instead of reading as an explicit deny. A bucket whose configuration cannot be read is treated as restricted. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: write a bucket policy only over the extended attributes it checked setBucketPolicy rewrote the whole bucket entry it had read, so a public access block set between the BlockPublicPolicy check and the write was erased and the public policy stored anyway. Send the read extended attributes, including an absent public access block, as the update's expected values, and redo the read and check when they changed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: count more policy forms as public An empty principal list and a principal holding a policy variable can both match anyone, so they are public. An aws:SourceIp range wider than /8 (IPv4) or /32 (IPv6) no longer restricts a grant. An ARN condition value with a fixed account, such as an access point ARN with a wildcard name, does restrict it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: deny anonymous callers outright on a restricted bucket with a public policy RestrictPublicBuckets limits a bucket with a public policy to callers of the owning account, so dropping only the policy's own grant left public ACLs able to serve anonymous reads. While the policy is public, the policy engine now answers an anonymous request with a deny. It checks before and after evaluating, so a policy replaced in between cannot let an anonymous grant through. A bucket without a policy, or with a non-public one, is unaffected. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: count an empty principal string as public A principal of "" compiles to no principal check, so it matches anyone, the same as an empty list. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: write a bucket policy only over the bucket entry it checked The policy write replaced the whole bucket entry and asserted only the public access block key, so a bucket setting first written between the lookup and the write (versioning, for one) was dropped. Pin the write to the entry it read; any concurrent change fails it and the lookup retries. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: judge an IPv4-mapped aws:SourceIp range by its IPv4 prefix ::ffff:0.0.0.0/96 parses as a 128-bit network but matches every IPv4 caller, so it passed the /32 IPv6 bound and a public policy slipped past BlockPublicPolicy and RestrictPublicBuckets. Apply the IPv4 /8 bound to mapped ranges. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
231 lines
8.7 KiB
Go
231 lines
8.7 KiB
Go
package s3api
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
|
|
"github.com/seaweedfs/seaweedfs/weed/glog"
|
|
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
|
"github.com/seaweedfs/seaweedfs/weed/s3api/policy_engine"
|
|
)
|
|
|
|
// BucketPolicyEngine wraps the policy_engine to provide bucket policy evaluation
|
|
type BucketPolicyEngine struct {
|
|
engine *policy_engine.PolicyEngine
|
|
// MultipartSSELookup retrieves the canonical SSE algorithm ("AES256" or
|
|
// "aws:kms") that was stored when a multipart upload was initiated.
|
|
// Returns "" when the upload had no SSE or when the entry cannot be found.
|
|
// Set by S3ApiServer after construction to give the engine filer access.
|
|
MultipartSSELookup func(bucket, object, uploadID string) string
|
|
// RestrictsPublicBuckets reports whether a bucket's public access block
|
|
// sets RestrictPublicBuckets. Set by S3ApiServer after construction.
|
|
RestrictsPublicBuckets func(bucket string) bool
|
|
}
|
|
|
|
// NewBucketPolicyEngine creates a new bucket policy engine
|
|
func NewBucketPolicyEngine() *BucketPolicyEngine {
|
|
return &BucketPolicyEngine{
|
|
engine: policy_engine.NewPolicyEngine(),
|
|
}
|
|
}
|
|
|
|
// LoadBucketPolicy loads a bucket policy into the engine from the filer entry
|
|
func (bpe *BucketPolicyEngine) LoadBucketPolicy(bucket string, entry *filer_pb.Entry) error {
|
|
if entry == nil || entry.Extended == nil {
|
|
return nil
|
|
}
|
|
|
|
policyJSON, exists := entry.Extended[BUCKET_POLICY_METADATA_KEY]
|
|
if !exists || len(policyJSON) == 0 {
|
|
// No policy for this bucket - remove it if it exists
|
|
bpe.engine.DeleteBucketPolicy(bucket)
|
|
return nil
|
|
}
|
|
|
|
// Set the policy in the engine
|
|
if err := bpe.engine.SetBucketPolicy(bucket, string(policyJSON)); err != nil {
|
|
glog.Errorf("Failed to load bucket policy for %s: %v", bucket, err)
|
|
return err
|
|
}
|
|
|
|
glog.V(3).Infof("Loaded bucket policy for %s into policy engine", bucket)
|
|
return nil
|
|
}
|
|
|
|
// LoadBucketPolicyFromCache loads a bucket policy from a cached BucketConfig
|
|
//
|
|
// This function loads the policy directly into the engine
|
|
func (bpe *BucketPolicyEngine) LoadBucketPolicyFromCache(bucket string, policyDoc *policy_engine.PolicyDocument) error {
|
|
if policyDoc == nil {
|
|
// No policy for this bucket - remove it if it exists
|
|
bpe.engine.DeleteBucketPolicy(bucket)
|
|
return nil
|
|
}
|
|
|
|
// Policy is already in correct format, just load it
|
|
// We need to re-marshal to string because SetBucketPolicy expects JSON string
|
|
policyJSON, err := json.Marshal(policyDoc)
|
|
if err != nil {
|
|
glog.Errorf("Failed to marshal bucket policy for %s: %v", bucket, err)
|
|
return err
|
|
}
|
|
|
|
// Set the policy in the engine
|
|
if err := bpe.engine.SetBucketPolicy(bucket, string(policyJSON)); err != nil {
|
|
glog.Errorf("Failed to load bucket policy for %s: %v", bucket, err)
|
|
return err
|
|
}
|
|
|
|
glog.V(4).Infof("Loaded bucket policy for %s into policy engine from cache", bucket)
|
|
return nil
|
|
}
|
|
|
|
// DeleteBucketPolicy removes a bucket policy from the engine
|
|
func (bpe *BucketPolicyEngine) DeleteBucketPolicy(bucket string) error {
|
|
return bpe.engine.DeleteBucketPolicy(bucket)
|
|
}
|
|
|
|
// HasPolicyForBucket checks if a bucket has a policy configured
|
|
func (bpe *BucketPolicyEngine) HasPolicyForBucket(bucket string) bool {
|
|
return bpe.engine.HasPolicyForBucket(bucket)
|
|
}
|
|
|
|
// GetBucketPolicy gets the policy for a bucket
|
|
func (bpe *BucketPolicyEngine) GetBucketPolicy(bucket string) (*policy_engine.PolicyDocument, error) {
|
|
return bpe.engine.GetBucketPolicy(bucket)
|
|
}
|
|
|
|
// ListBucketPolicies returns all buckets that have policies
|
|
func (bpe *BucketPolicyEngine) ListBucketPolicies() []string {
|
|
return bpe.engine.GetAllBucketsWithPolicies()
|
|
}
|
|
|
|
// EvaluatePolicy evaluates whether an action is allowed by bucket policy
|
|
//
|
|
// Parameters:
|
|
// - bucket: the bucket name
|
|
// - object: the object key (can be empty for bucket-level operations)
|
|
// - action: the action being performed (e.g., "Read", "Write")
|
|
// - principal: the principal ARN or identifier
|
|
// - r: the HTTP request (optional, used for condition evaluation and action resolution)
|
|
// - objectEntry: the object's metadata from entry.Extended (can be nil at auth time,
|
|
// should be passed when available for tag-based conditions like s3:ExistingObjectTag)
|
|
//
|
|
// Returns:
|
|
// - allowed: whether the policy allows the action
|
|
// - evaluated: whether a policy was found and evaluated (false = no policy exists)
|
|
// - error: any error during evaluation
|
|
func (bpe *BucketPolicyEngine) EvaluatePolicy(bucket, object, action, principal string, r *http.Request, claims map[string]interface{}, objectEntry map[string][]byte) (allowed bool, evaluated bool, err error) {
|
|
// Validate required parameters
|
|
if bucket == "" {
|
|
return false, false, fmt.Errorf("bucket cannot be empty")
|
|
}
|
|
if action == "" {
|
|
return false, false, fmt.Errorf("action cannot be empty")
|
|
}
|
|
|
|
if principal == "*" && bpe.restrictsPublicPolicy(bucket) {
|
|
return false, true, nil
|
|
}
|
|
|
|
// Convert action to S3 action format
|
|
// ResolveS3Action handles nil request internally (falls back to mapBaseActionToS3Format)
|
|
s3Action := ResolveS3Action(r, action, bucket, object)
|
|
|
|
// Build resource ARN
|
|
resource := buildResourceARN(bucket, object)
|
|
|
|
glog.V(4).Infof("EvaluatePolicy: bucket=%s, resource=%s, action=%s, principal=%s",
|
|
bucket, resource, s3Action, principal)
|
|
|
|
// Evaluate using the policy engine
|
|
args := &policy_engine.PolicyEvaluationArgs{
|
|
Action: s3Action,
|
|
Resource: resource,
|
|
Principal: principal,
|
|
ObjectEntry: objectEntry,
|
|
}
|
|
|
|
// glog.V(4).Infof("EvaluatePolicy [Wrapper]: bucket=%s, resource=%s, action=%s, principal=%s",
|
|
// bucket, resource, s3Action, principal)
|
|
|
|
// Extract conditions and claims from request if available
|
|
if r != nil {
|
|
args.OriginalGrantConditions = policy_engine.OriginalGrantConditionsFromRequest(r)
|
|
args.Conditions = bpe.engine.ExtractConditionValuesFromRequest(r)
|
|
addEmptyListPrefix(args.Conditions, r, Action(action))
|
|
|
|
// Extract principal-related variables (aws:username, etc.) from principal ARN
|
|
principalVars := principalVariables(principal, claims)
|
|
for k, v := range principalVars {
|
|
args.Conditions[k] = v
|
|
}
|
|
|
|
// Extract JWT claims if authenticated via JWT or STS
|
|
if claims != nil {
|
|
args.Claims = claims
|
|
} else {
|
|
// If claims were not provided directly, try to get them from context Identity?
|
|
// But the caller is responsible for passing them.
|
|
// Falling back to empty claims if not provided.
|
|
}
|
|
|
|
// For multipart continuation actions look up the SSE algorithm that was
|
|
// set at CreateMultipartUpload time. UploadPart/UploadPartCopy do not
|
|
// re-send the SSE header, so we inject the stored value so that bucket
|
|
// policy conditions on s3:x-amz-server-side-encryption evaluate correctly.
|
|
if policy_engine.IsMultipartContinuationAction(s3Action) && bpe.MultipartSSELookup != nil {
|
|
if uploadID := r.URL.Query().Get("uploadId"); uploadID != "" {
|
|
args.InheritedSSEAlgorithm = bpe.MultipartSSELookup(bucket, object, uploadID)
|
|
}
|
|
}
|
|
}
|
|
|
|
result := bpe.engine.EvaluatePolicy(bucket, args)
|
|
|
|
switch result {
|
|
case policy_engine.PolicyResultAllow:
|
|
// glog.V(4).Infof("EvaluatePolicy [Wrapper]: ALLOW - bucket=%s, action=%s, principal=%s", bucket, s3Action, principal)
|
|
if principal == "*" && bpe.restrictsPublicPolicy(bucket) {
|
|
return false, true, nil
|
|
}
|
|
return true, true, nil
|
|
case policy_engine.PolicyResultDeny:
|
|
// glog.V(4).Infof("EvaluatePolicy [Wrapper]: DENY - bucket=%s, action=%s, principal=%s", bucket, s3Action, principal)
|
|
return false, true, nil
|
|
case policy_engine.PolicyResultIndeterminate:
|
|
// No policy exists for this bucket
|
|
// glog.V(4).Infof("EvaluatePolicy [Wrapper]: INDETERMINATE (no policy) - bucket=%s", bucket)
|
|
return false, false, nil
|
|
default:
|
|
return false, false, fmt.Errorf("unknown policy result: %v", result)
|
|
}
|
|
}
|
|
|
|
// restrictsPublicPolicy reports whether RestrictPublicBuckets denies the
|
|
// bucket to anonymous callers, which it does while the bucket has a public
|
|
// policy. It is checked before and after evaluation, so a policy replaced
|
|
// in between cannot slip an anonymous grant past it.
|
|
func (bpe *BucketPolicyEngine) restrictsPublicPolicy(bucket string) bool {
|
|
doc, err := bpe.engine.GetBucketPolicy(bucket)
|
|
if err != nil || !isPublicPolicy(doc) {
|
|
return false
|
|
}
|
|
return bpe.RestrictsPublicBuckets != nil && bpe.RestrictsPublicBuckets(bucket)
|
|
}
|
|
|
|
// principalVariables resolves the policy variables of a principal. A role
|
|
// session's ARN ends in the session name the caller chose, so its user comes
|
|
// from the session itself: the user the session was issued to.
|
|
func principalVariables(principal string, claims map[string]interface{}) map[string][]string {
|
|
vars := policy_engine.ExtractPrincipalVariables(principal)
|
|
if types := vars["aws:principaltype"]; len(types) == 1 && types[0] == "AssumedRole" {
|
|
if user, ok := claims["aws:username"].(string); ok && user != "" {
|
|
vars["aws:username"] = []string{user}
|
|
vars["aws:userid"] = []string{user}
|
|
}
|
|
}
|
|
return vars
|
|
}
|