How to prevent directory browsing of S3 bucket?
Amazon S3Amazon S3 Problem Overview
I have a ton of files on my S3 bucket and add a bucket policy to make them all public. Now it lists the entire directory (or the first 1000 items) when I browse the root. How can I prevent directory browsing?
Amazon S3 Solutions
Solution 1 - Amazon S3
It should be noted that adding an index.html file to a bucket does absolutely nothing. This file will simply be listed with all other files when browsing the bucket root.
Also, setting access levels on the bucket so that 'everyone' cannot read, means that every new file you upload to your bucket will need to have its permission set to 'everyone' before it can be browsed. This isn't practical if you're adding files regularly.
The best solution is to first set access levels on the bucket to deny 'everyone' read access, but then create a bucket policy that allows everyone to read what's inside the bucket. This way, nobody will be able to list the contents of your bucket, but any new files you add will be readable by everyone who has the link to that file.
Here is what the bucket policy might look like. Replace 'my_bucket' with your bucket name, and you're good to go.
{
"Version": "2008-10-17",
"Statement": [
{
"Sid": "AddPerm",
"Effect": "Allow",
"Principal": "*",
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::my_bucket/*"
}
]
}
Solution 2 - Amazon S3
Solution 3 - Amazon S3
You can set the ACL on the directory and the individual files independently, do not give read permissions on the directory but allow it for the individual files. There are many tools to help with this including bucket explorer or s3 fox.
Solution 4 - Amazon S3
A bucket policy should no longer be needed for this, as far as I'm aware (it probably was back when the answers to this question were first posted).
Now, just set your bucket to public access but turn off the "List Objects" permission.
Solution 5 - Amazon S3
There are four type of s3 security and policies you could apply as of May 2020
- IAM policies
- Bucket Policies
- Object Access Control List (ACL)
- Bucket Access Control List (ACL)
Among them you can User Bucket Policies to apply policies
Line to Focus Just put /*
after bucket_name in Resource as below
"Resource": "arn:aws:s3:::my_bucket/*"
{
"Version": "2012-10-17",
"Id": "Policy212127",
"Statement": [
{
"Sid": "Stmt112121212",
"Effect": "Allow",
"Principal": "*",
"Action": "s3:*",
"Resource": "arn:aws:s3:::my_bucket/*"
}
]
}