Which of the below allows you to restrict access to individual objects in an s3 bucket?

This section presents a few examples of typical use cases for bucket policies. The policies use DOC-EXAMPLE-BUCKET strings in the resource value. To test these policies, replace these strings with your bucket name. For information about bucket policies, see Using bucket policies. For more information about policy language, see Policies and Permissions in Amazon S3.

A bucket policy is a resource-based policy that you can use to grant access permissions to your bucket and the objects in it. Only the bucket owner can associate a policy with a bucket. The permissions attached to the bucket apply to all of the objects in the bucket that are owned by the bucket owner. These permissions do not apply to objects owned by other Amazon Web Services accounts.

By default, when another Amazon Web Services account uploads an object to your S3 bucket, that account (the object writer) owns the object, has access to it, and can grant other users access to it through access control lists (ACLs). You can use Object Ownership to change this default behavior so that ACLs are disabled and you, as the bucket owner, automatically own every object in your bucket. As a result, access control for your data is based on policies, such as IAM policies, S3 bucket policies, virtual private cloud (VPC) endpoint policies, and Amazon Organizations service control policies (SCPs). For more information, see Controlling ownership of objects and disabling ACLs for your bucket.

For more information about bucket policies, see Using bucket policies.

Bucket policies are limited to 20 KB in size.

You can use the Amazon Policy Generator to create a bucket policy for your Amazon S3 bucket. You can then use the generated document to set your bucket policy by using the Amazon S3 console, through several third-party tools, or through your application.

When testing permissions by using the Amazon S3 console, you must grant additional permissions that the console requires—s3:ListAllMyBuckets, s3:GetBucketLocation, and s3:ListBucket. For an example walkthrough that grants permissions to users and tests them by using the console, see Controlling access to a bucket with user policies.

Topics

  • Granting permissions to multiple accounts with added conditions
  • Granting read-only permission to an anonymous user
  • Limiting access to specific IP addresses
  • Restricting access to a specific HTTP referer
  • Granting permission to an Amazon CloudFront OAI
  • Adding a bucket policy to require MFA
  • Granting cross-account permissions to upload objects while ensuring the bucket owner has full control
  • Granting permissions for Amazon S3 Inventory and Amazon S3 analytics
  • Restricting access to an Amazon S3 Inventory report
  • Granting permissions for Amazon S3 Storage Lens

Granting permissions to multiple accounts with added conditions

The following example policy grants the s3:PutObject and s3:PutObjectAcl permissions to multiple Amazon Web Services accounts and requires that any request for these operations include the public-read canned access control list (ACL). For more information, see Amazon S3 actions and Amazon S3 condition key examples.

Use caution when granting anonymous access to your Amazon S3 bucket or disabling block public access settings. When you grant anonymous access, anyone in the world can access your bucket. We recommend that you never grant anonymous access to your Amazon S3 bucket unless you specifically need to, such as with static website hosting.

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "AddCannedAcl",
            "Effect": "Allow",
            "Principal": {
                "AWS": [
                    "arn:aws-cn:iam::111122223333:root",
                    "arn:aws-cn:iam::444455556666:root"
                ]
            },
            "Action": [
                "s3:PutObject",
                "s3:PutObjectAcl"
            ],
            "Resource": "arn:aws-cn:s3:::DOC-EXAMPLE-BUCKET/*",
            "Condition": {
                "StringEquals": {
                    "s3:x-amz-acl": [
                        "public-read"
                    ]
                }
            }
        }
    ]
}

Granting read-only permission to an anonymous user

The following example policy grants the s3:GetObject permission to any public anonymous users. (For a list of permissions and the operations that they allow, see Amazon S3 actions.) This permission allows anyone to read the object data, which is useful if you configure your bucket as a website and want everyone to be able to read objects in the bucket. Before you use a bucket policy to grant read-only permission to an anonymous user, you must disable block public access settings for your bucket. For more information, see Setting permissions for website access.

Use caution when granting anonymous access to your Amazon S3 bucket or disabling block public access settings. When you grant anonymous access, anyone in the world can access your bucket. We recommend that you never grant anonymous access to your Amazon S3 bucket unless you specifically need to, such as with static website hosting.

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "PublicRead",
            "Effect": "Allow",
            "Principal": "*",
            "Action": [
                "s3:GetObject",
                "s3:GetObjectVersion"
            ],
            "Resource": [
                "arn:aws-cn:s3:::DOC-EXAMPLE-BUCKET/*"
            ]
        }
    ]
}

Limiting access to specific IP addresses

The following example denies permissions to any user to perform any Amazon S3 operations on objects in the specified S3 bucket unless the request originates from the range of IP addresses that are specified in the condition.

This statement identifies 54.240.143.0/24 as the range of allowed Internet Protocol version 4 (IPv4) IP addresses.

The Condition block uses the NotIpAddress condition and the aws:SourceIp condition key, which is an Amazon wide condition key. For more information about these condition keys, see Amazon S3 condition key examples. The aws:SourceIp IPv4 values use standard CIDR notation. For more information, see IAM JSON Policy Elements Reference in the IAM User Guide.

Before using this policy, replace the 54.240.143.0/24 IP address range in this example with an appropriate value for your use case. Otherwise, you will lose the ability to access your bucket.

{
    "Version": "2012-10-17",
    "Id": "S3PolicyId1",
    "Statement": [
        {
            "Sid": "IPAllow",
            "Effect": "Deny",
            "Principal": "*",
            "Action": "s3:*",
            "Resource": [
                "arn:aws-cn:s3:::DOC-EXAMPLE-BUCKET",
                "arn:aws-cn:s3:::DOC-EXAMPLE-BUCKET/*"
            ],
            "Condition": {
                "NotIpAddress": {
                    "aws:SourceIp": "54.240.143.0/24"
                }
            }
        }
    ]
}

Allowing IPv4 and IPv6 addresses

When you start using IPv6 addresses, we recommend that you update all of your organization's policies with your IPv6 address ranges in addition to your existing IPv4 ranges to ensure that the policies continue to work as you make the transition to IPv6.

The following example bucket policy shows how to mix IPv4 and IPv6 address ranges to cover all of your organization's valid IP addresses. The example policy allows access to the example IP addresses 54.240.143.1 and 2001:DB8:1234:5678::1 and denies access to the addresses 54.240.143.129 and 2001:DB8:1234:5678:ABCD::1.

The IPv6 values for aws:SourceIp must be in standard CIDR format. For IPv6, we support using :: to represent a range of 0s (for example, 2032001:DB8:1234:5678::/64). For more information, see IP Address Condition Operators in the IAM User Guide.

Replace the IP address ranges in this example with appropriate values for your use case before using this policy. Otherwise, you might lose the ability to access your bucket.

{
    "Id": "PolicyId2",
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "AllowIPmix",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:*",
            "Resource": [
                "arn:aws-cn:s3:::DOC-EXAMPLE-BUCKET",
                "arn:aws-cn:s3:::DOC-EXAMPLE-BUCKET/*"
            ],
            "Condition": {
                "IpAddress": {
                    "aws:SourceIp": [
                        "54.240.143.0/24",
                        "2001:DB8:1234:5678::/64"
                    ]
                },
                "NotIpAddress": {
                    "aws:SourceIp": [
                        "54.240.143.128/30",
                        "2001:DB8:1234:5678:ABCD::/80"
                    ]
                }
            }
        }
    ]
}

Restricting access to a specific HTTP referer

Suppose that you have a website with a domain name (www.example.com or example.com) with links to photos and videos stored in your Amazon S3 bucket, DOC-EXAMPLE-BUCKET. By default, all Amazon S3 resources are private, so only the Amazon Web Services account that created the resources can access them. To allow read access to these objects from your website, you can add a bucket policy that allows the s3:GetObject permission with a condition, using the aws:Referer key, that the GET request must originate from specific webpages. The following policy specifies the StringLike condition with the aws:Referer condition key.

{
  "Version":"2012-10-17",
  "Id":"HTTP referer policy example",
  "Statement":[
    {
      "Sid":"Allow GET requests originating from www.example.com and example.com.",
      "Effect":"Allow",
      "Principal":"*",
      "Action":["s3:GetObject","s3:GetObjectVersion"],
      "Resource":"arn:aws-cn:s3:::DOC-EXAMPLE-BUCKET/*",
      "Condition":{
        "StringLike":{"aws:Referer":["http://www.example.com/*","http://example.com/*"]}
      }
    }
  ]
}

Make sure that the browsers that you use include the HTTP referer header in the request.

We recommend that you use caution when using the aws:Referer condition key. It is dangerous to include a publicly known HTTP referer header value. Unauthorized parties can use modified or custom browsers to provide any aws:Referer value that they choose. Therefore, do not use aws:Referer to prevent unauthorized parties from making direct Amazon requests.

The aws:Referer condition key is offered only to allow customers to protect their digital content, such as content stored in Amazon S3, from being referenced on unauthorized third-party sites. For more information, see aws:Referer in the IAM User Guide.

Granting permission to an Amazon CloudFront OAI

The following example bucket policy grants a CloudFront origin access identity (OAI) permission to get (read) all objects in your Amazon S3 bucket. You can use a CloudFront OAI to allow users to access objects in your bucket through CloudFront but not directly through Amazon S3. For more information, see Restricting Access to Amazon S3 Content by Using an Origin Access Identity in the Amazon CloudFront Developer Guide.

The following policy uses the OAI’s ID as the policy’s Principal. For more information about using S3 bucket policies to grant access to a CloudFront OAI, see Using Amazon S3 Bucket Policies in the Amazon CloudFront Developer Guide.

To use this example:

  • Replace EH1HDMB1FH2TC with the OAI’s ID. To find the OAI’s ID, see the Origin Access Identity page on the CloudFront console, or use ListCloudFrontOriginAccessIdentities in the CloudFront API.

  • Replace DOC-EXAMPLE-BUCKET with the name of your Amazon S3 bucket.

{
    "Version": "2012-10-17",
    "Id": "PolicyForCloudFrontPrivateContent",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws-cn:iam::cloudfront:user/CloudFront Origin Access Identity EH1HDMB1FH2TC"
            },
            "Action": "s3:GetObject",
            "Resource": "arn:aws-cn:s3:::DOC-EXAMPLE-BUCKET/*"
        }
    ]
}

Adding a bucket policy to require MFA

Amazon S3 supports MFA-protected API access, a feature that can enforce multi-factor authentication (MFA) for access to your Amazon S3 resources. Multi-factor authentication provides an extra level of security that you can apply to your Amazon environment. MFA is a security feature that requires users to prove physical possession of an MFA device by providing a valid MFA code. For more information, see Amazon Multi-Factor Authentication. You can require MFA for any requests to access your Amazon S3 resources.

To enforce the MFA requirement, use the aws:MultiFactorAuthAge key in a bucket policy. Amazon Identity and Access Management (IAM) users can access Amazon S3 resources by using temporary credentials issued by the Amazon Security Token Service (Amazon STS). You provide the MFA code at the time of the Amazon STS request.

When Amazon S3 receives a request with multi-factor authentication, the aws:MultiFactorAuthAge key provides a numeric value that indicates how long ago (in seconds) the temporary credential was created. If the temporary credential provided in the request was not created by using an MFA device, this key value is null (absent). In a bucket policy, you can add a condition to check this value, as shown in the following example. This example policy denies any Amazon S3 operation on the /taxdocuments folder in the DOC-EXAMPLE-BUCKET bucket if the request is not authenticated by using MFA. To learn more about MFA, see Using Multi-Factor Authentication (MFA) in Amazon in the IAM User Guide.

{
    "Version": "2012-10-17",
    "Id": "123",
    "Statement": [
      {
        "Sid": "",
        "Effect": "Deny",
        "Principal": "*",
        "Action": "s3:*",
        "Resource": "arn:aws-cn:s3:::DOC-EXAMPLE-BUCKET/taxdocuments/*",
        "Condition": { "Null": { "aws:MultiFactorAuthAge": true }}
      }
    ]
 }

The Null condition in the Condition block evaluates to true if the aws:MultiFactorAuthAge key value is null, indicating that the temporary security credentials in the request were created without an MFA device.

The following bucket policy is an extension of the preceding bucket policy. It includes two policy statements. One statement allows the s3:GetObject permission on a bucket (DOC-EXAMPLE-BUCKET) to everyone. Another statement further restricts access to the DOC-EXAMPLE-BUCKET/taxdocuments folder in the bucket by requiring MFA.

{
    "Version": "2012-10-17",
    "Id": "123",
    "Statement": [
      {
        "Sid": "",
        "Effect": "Deny",
        "Principal": "*",
        "Action": "s3:*",
        "Resource": "arn:aws-cn:s3:::DOC-EXAMPLE-BUCKET/taxdocuments/*",
        "Condition": { "Null": { "aws:MultiFactorAuthAge": true } }
      },
      {
        "Sid": "",
        "Effect": "Allow",
        "Principal": "*",
        "Action": ["s3:GetObject"],
        "Resource": "arn:aws-cn:s3:::DOC-EXAMPLE-BUCKET/*"
      }
    ]
 }

You can optionally use a numeric condition to limit the duration for which the aws:MultiFactorAuthAge key is valid, independent of the lifetime of the temporary security credential that's used in authenticating the request. For example, the following bucket policy, in addition to requiring MFA authentication, also checks how long ago the temporary session was created. The policy denies any operation if the aws:MultiFactorAuthAge key value indicates that the temporary session was created more than an hour ago (3,600 seconds).

{
    "Version": "2012-10-17",
    "Id": "123",
    "Statement": [
      {
        "Sid": "",
        "Effect": "Deny",
        "Principal": "*",
        "Action": "s3:*",
        "Resource": "arn:aws-cn:s3:::DOC-EXAMPLE-BUCKET/taxdocuments/*",
        "Condition": {"Null": {"aws:MultiFactorAuthAge": true }}
      },
      {
        "Sid": "",
        "Effect": "Deny",
        "Principal": "*",
        "Action": "s3:*",
        "Resource": "arn:aws-cn:s3:::DOC-EXAMPLE-BUCKET/taxdocuments/*",
        "Condition": {"NumericGreaterThan": {"aws:MultiFactorAuthAge": 3600 }}
       },
       {
         "Sid": "",
         "Effect": "Allow",
         "Principal": "*",
         "Action": ["s3:GetObject"],
         "Resource": "arn:aws-cn:s3:::DOC-EXAMPLE-BUCKET/*"
       }
    ]
 }

Granting cross-account permissions to upload objects while ensuring the bucket owner has full control

The following example shows how to allow another Amazon Web Services account to upload objects to your bucket while ensuring that you have full control of the uploaded objects. This policy grants a specific Amazon Web Services account (111122223333) the ability to upload objects only if that account includes the bucket-owner-full-control canned ACL on upload. The StringEquals condition in the policy specifies the s3:x-amz-acl condition key to express the requirement (see Amazon S3 condition key examples).

{
   "Version":"2012-10-17",
   "Statement":[
     {
       "Sid":"PolicyForAllowUploadWithACL",
       "Effect":"Allow",
       "Principal":{"AWS":"111122223333"},
       "Action":"s3:PutObject",
       "Resource":"arn:aws-cn:s3:::DOC-EXAMPLE-BUCKET/*",
       "Condition": {
         "StringEquals": {"s3:x-amz-acl":"bucket-owner-full-control"}
       }
     }
   ]
}

Granting permissions for Amazon S3 Inventory and Amazon S3 analytics

Amazon S3 Inventory creates lists of the objects in an Amazon S3 bucket, and Amazon S3 analytics export creates output files of the data used in the analysis. The bucket that the inventory lists the objects for is called the source bucket. The bucket where the inventory file or the analytics export file is written to is called a destination bucket. When setting up an inventory or an analytics export, you must create a bucket policy for the destination bucket. For more information, see Amazon S3 Inventory and Amazon S3 analytics – Storage Class Analysis.

The following example bucket policy grants Amazon S3 permission to write objects (PUT requests) from the account for the source bucket to the destination bucket. You use a bucket policy like this on the destination bucket when setting up Amazon S3 Inventory and Amazon S3 analytics export.

{  
      "Version": "2012-10-17",
      "Statement": [
        {
            "Sid": "InventoryAndAnalyticsExamplePolicy",
            "Effect": "Allow",
            "Principal": {
                "Service": "s3.amazonaws.com.cn"
            },
            "Action": "s3:PutObject",
            "Resource": [
                "arn:aws-cn:s3:::destinationbucket/*"
            ],
            "Condition": {
                "ArnLike": {
                    "aws:SourceArn": "arn:aws-cn:s3:::sourcebucket"
                },
                "StringEquals": {
                    "aws:SourceAccount": "111122223333",
                    "s3:x-amz-acl": "bucket-owner-full-control"
                }
            }
        }
    ]
}

Restricting access to an Amazon S3 Inventory report

Amazon S3 Inventory creates lists of the objects in an S3 bucket and the metadata for each object. The s3:PutInventoryConfiguration permission allows a user to create an inventory report that includes all object metadata fields that are available and to specify the destination bucket to store the inventory. A user with read access to objects in the destination bucket can access all object metadata fields that are available in the inventory report. For more information about the metadata fields that are available in S3 Inventory, see Amazon S3 Inventory list.

To restrict a user from configuring an S3 Inventory report of all object metadata available, remove the s3:PutInventoryConfiguration permission from the user.

To restrict a user from accessing your S3 Inventory report in a destination bucket, create a bucket policy like the following example on the destination bucket. This example bucket policy denies all the principals except the user Ana from accessing the inventory report DOC-EXAMPLE-DESTINATION-BUCKET-INVENTORY in the destination bucket DOC-EXAMPLE-DESTINATION-BUCKET.

{
	"Id": "GetObjectPolicy",
	"Version": "2012-10-17",
	"Statement": [{
			"Sid": "AllowListBucket",
			"Action": [
				"s3:ListBucket"
			],
			"Effect": "Allow",
			"Resource": [
				"arn:aws-cn:s3:::DOC-EXAMPLE-DESTINATION-BUCKET",
				"arn:aws-cn:s3:::DOC-EXAMPLE-DESTINATION-BUCKET/*"
			],
			"Principal": {
				"AWS": [
					"arn:aws-cn:iam::111122223333:user/Ana"
				]
			}
		},
		{
			"Sid": "AllowACertainUserToReadObject",
			"Action": [
				"s3:GetObject"
			],
			"Effect": "Allow",
			"Resource": "arn:aws-cn:s3:::DOC-EXAMPLE-DESTINATION-BUCKET/DOC-EXAMPLE-DESTINATION-BUCKET-INVENTORY/*",
			"Principal": {
				"AWS": [
					"arn:aws-cn:iam::111122223333:user/Ana"
				]
			}
		},
		{
			"Sid": "DenyAllTheOtherUsersToReadObject",
			"Action": [
				"s3:GetObject"
			],
			"Effect": "Deny",
			"Resource": "arn:aws-cn:s3:::DOC-EXAMPLE-DESTINATION-BUCKET/DOC-EXAMPLE-DESTINATION-BUCKET-INVENTORY/*",
			"Principal": {
				"AWS": "*"
			},
			"Condition": {
				"ArnNotEquals": {
					"aws:PrincipalArn": "arn:aws-cn:iam::111122223333:user/Ana"
				}
			}
		}
	]
}

Granting permissions for Amazon S3 Storage Lens

S3 Storage Lens aggregates your metrics and displays the information in the Account snapshot section on the Amazon S3 console Buckets page. S3 Storage Lens also provides an interactive dashboard that you can use to visualize insights and trends, flag outliers, and receive recommendations for optimizing storage costs and applying data-protection best practices. Your dashboard has drill-down options to generate insights at the organization, account, bucket, object, or prefix level. You can also send a once-daily metrics export in CSV or Parquet format to an S3 bucket.

S3 Storage Lens can aggregate your storage usage to metrics exports in an Amazon S3 bucket for further analysis. The bucket where S3 Storage Lens places its metrics exports is known as the destination bucket. When setting up your S3 Storage Lens metrics export, you must have a bucket policy for the destination bucket. For more information, see Assessing your storage activity and usage with Amazon S3 Storage Lens.

The following example bucket policy grants Amazon S3 permission to write objects (PUT requests) to a destination bucket. You use a bucket policy like this on the destination bucket when setting up an S3 Storage Lens metrics export.

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "S3StorageLensExamplePolicy",
            "Effect": "Allow",
            "Principal": {
                "Service": "storage-lens.s3.amazonaws.com.cn"
            },
            "Action": "s3:PutObject",
            "Resource": [
                "arn:aws-cn:s3:::destination-bucket/destination-prefix/StorageLens/111122223333/*"
            ],
            "Condition": {
                "StringEquals": {
                    "s3:x-amz-acl": "bucket-owner-full-control",
                    "aws:SourceAccount": "111122223333",
                    "aws:SourceArn": "arn:aws-cn:s3:Amazon Web Services Region:111122223333:storage-lens/storage-lens-dashboard-configuration-id"
                }
            }
        }
    ]
}

When setting up an S3 Storage Lens organization-level metrics export, use the following modification to the previous bucket policy's Resource statement.


"Resource": "arn:aws-cn:s3:::destination-bucket/destination-prefix/StorageLens/your-organization-id/*",
    

Which of the below feature can restrict access to S3?

The Amazon S3 Block Public Access feature provides settings for access points, buckets, and accounts to help you manage public access to Amazon S3 resources. By default, new buckets, access points, and objects don't allow public access.

Which Amazon S3 bucket policy can limit access to a specific object?

You can use the NotPrincipal element of an IAM or S3 bucket policy to limit resource access to a specific set of users.

What methods can be used to grant access to an object in S3?

Grant public read access in one of these ways: Update the object's access control list (ACL) using the Amazon S3 console. Update the object's ACL using the AWS Command Line Interface (AWS CLI) Use a bucket policy that grants public read access to a specific object tag.

Which methods of access control can you implement using S3 bucket policies?

ACLs were the first authorization mechanism in S3. Bucket policies are the newer method, and the method used for almost all AWS services. Policies can implement very complex rules and permissions, ACLs are simplistic (they have ALLOW but no DENY). To manage S3 you need a solid understanding of both.