Created
January 24, 2025 00:23
-
-
Save TomGranot/41d58d2b9b1a82d5b4b557159ffbfb3c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
AWSTemplateFormatVersion: '2010-09-09' | |
Description: Remediate a public S3 bucket by introducing CloudFront with Origin Access Control (OAC). | |
Parameters: | |
BucketName: | |
Type: String | |
Description: The name of the S3 bucket to remediate. | |
DistributionComment: | |
Type: String | |
Default: "CloudFront distribution for secure bucket access" | |
Description: Comment for the CloudFront distribution. | |
Resources: | |
# CloudFront Origin Access Control (OAC) | |
CloudFrontOAC: | |
Type: AWS::CloudFront::OriginAccessControl | |
Properties: | |
OriginAccessControlConfig: | |
Name: !Sub "${BucketName}-oac" | |
Description: "OAC for accessing the S3 bucket securely" | |
OriginAccessControlOriginType: s3 | |
SigningBehavior: always | |
SigningProtocol: sigv4 | |
# CloudFront Distribution | |
CloudFrontDistribution: | |
Type: AWS::CloudFront::Distribution | |
Properties: | |
DistributionConfig: | |
Enabled: true | |
Comment: !Ref DistributionComment | |
DefaultCacheBehavior: | |
TargetOriginId: S3Origin | |
ViewerProtocolPolicy: redirect-to-https | |
AllowedMethods: | |
- GET | |
- HEAD | |
CachedMethods: | |
- GET | |
- HEAD | |
ForwardedValues: | |
QueryString: false | |
Cookies: | |
Forward: none | |
Compress: true | |
Origins: | |
- Id: S3Origin | |
DomainName: !Sub "${BucketName}.s3.amazonaws.com" | |
S3OriginConfig: # Use S3OriginConfig for S3 buckets | |
OriginAccessIdentity: "" # Required but set to an empty string since we're using OAC | |
OriginAccessControlId: !Ref CloudFrontOAC | |
# Update Bucket Policy to Allow CloudFront Access | |
RemediationBucketPolicy: | |
Type: AWS::S3::BucketPolicy | |
Properties: | |
Bucket: !Ref BucketName | |
PolicyDocument: | |
Version: "2012-10-17" | |
Statement: | |
- Sid: AllowCloudFrontServicePrincipalReadOnly | |
Effect: Allow | |
Principal: | |
Service: "cloudfront.amazonaws.com" | |
Action: "s3:GetObject" | |
Resource: !Sub "arn:aws:s3:::${BucketName}/*" | |
Condition: | |
StringEquals: | |
AWS:SourceArn: !Sub "arn:aws:cloudfront::${AWS::AccountId}:distribution/${CloudFrontDistribution}" | |
Outputs: | |
DistributionDomainName: | |
Description: The domain name of the CloudFront distribution. | |
Value: !GetAtt CloudFrontDistribution.DomainName | |
BucketPolicyStatus: | |
Description: Indicates that the bucket policy has been updated to allow access via CloudFront. | |
Value: "Bucket policy successfully remediated." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment