> ## Documentation Index
> Fetch the complete documentation index at: https://cloudanix.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Cloudfront origin access s3 origins remediation

### Triage and Remediation

<Tabs>
  <Tab title="Remediation">
    ### Remediation

    <AccordionGroup>
      <Accordion title="Using Console" defaultOpen="true">
        Sure, here are the steps to remediate the misconfiguration "Origin Access Identity should be enabled for CloudFront distributions" in AWS using AWS console:

        1. Log in to the AWS Management Console.
        2. Navigate to the CloudFront service.
        3. Select the distribution for which you want to enable Origin Access Identity.
        4. Click on the "Behaviors" tab.
        5. Select the behavior for which you want to enable Origin Access Identity.
        6. Click on the "Edit" button.
        7. In the "Origin Settings" section, select "Yes" for "Restrict Bucket Access".
        8. Select "Create a New Identity" under "Origin Access Identity".
        9. Provide a name for the new identity and click on the "Create" button.
        10. Click on the "Yes, Edit" button to save the changes.

        By following these steps, you have successfully enabled Origin Access Identity for the CloudFront distribution and remediated the misconfiguration.

        #
      </Accordion>

      <Accordion title="Using CLI">
        To remediate this misconfiguration in AWS using AWS CLI, you can follow the below steps:

        1. Open the AWS CLI on your local machine.

        2. Run the following command to list all the CloudFront distributions in your AWS account:

        ```
        aws cloudfront list-distributions
        ```

        3. Identify the distribution for which the Origin Access Identity should be enabled.

        4. Run the following command to update the distribution configuration and enable Origin Access Identity:

        ```
        aws cloudfront update-distribution --id <distribution-id> --distribution-config '{"Comment":"", "Origins": {"Quantity":1,"Items":[{"Id":"<origin-id>","DomainName":"<origin-domain-name>","OriginPath":"","CustomHeaders":{"Quantity":0},"S3OriginConfig":{"OriginAccessIdentity":"<origin-access-identity>"},"CustomOriginConfig":{"HTTPPort":80,"HTTPSPort":443,"OriginProtocolPolicy":"http-only","OriginSslProtocols":{"Quantity":3,"Items":["TLSv1","TLSv1.1","TLSv1.2"]},"OriginReadTimeout":30,"OriginKeepaliveTimeout":5}}]},"Enabled":true,"PriceClass":"PriceClass_All","ViewerCertificate":{"CloudFrontDefaultCertificate":true,"MinimumProtocolVersion":"TLSv1","CertificateSource":"cloudfront"},"DefaultRootObject":"","Logging":{"Enabled":false,"IncludeCookies":false,"Bucket":"","Prefix":""},"WebACLId":"","HttpVersion":"http2","IsIPV6Enabled":true}'
        ```

        Replace the following placeholders with actual values:

        * `<distribution-id>`: The ID of the CloudFront distribution.
        * `<origin-id>`: The ID of the origin for which Origin Access Identity should be enabled.
        * `<origin-domain-name>`: The domain name of the origin for which Origin Access Identity should be enabled.
        * `<origin-access-identity>`: The ARN of the Origin Access Identity that should be associated with the origin.

        5. After running the command, the CloudFront distribution configuration will be updated, and Origin Access Identity will be enabled for the specified origin.

        Note: Make sure you have the necessary permissions to update the CloudFront distribution configuration.
      </Accordion>

      <Accordion title="Using Python">
        To remediate the misconfiguration "Origin Access Identity should be enabled for CloudFront distributions" in AWS using Python, follow the below steps:

        1. Import the required libraries:

        ```python theme={null}
        import boto3
        ```

        2. Create a CloudFront client:

        ```python theme={null}
        client = boto3.client('cloudfront')
        ```

        3. Get the list of all distributions:

        ```python theme={null}
        response = client.list_distributions()
        ```

        4. Loop through the distributions and check if Origin Access Identity is enabled:

        ```python theme={null}
        for distribution in response['DistributionList']['Items']:
            if distribution['Enabled'] and not distribution['Origins']['Items'][0]['S3OriginConfig']['OriginAccessIdentity']:
                print(f"Disabling distribution {distribution['Id']}...")
                client.update_distribution(
                    DistributionConfig={
                        'Id': distribution['Id'],
                        'CallerReference': distribution['CallerReference'],
                        'Comment': distribution['Comment'],
                        'DefaultCacheBehavior': distribution['DefaultCacheBehavior'],
                        'Origins': {
                            'Quantity': len(distribution['Origins']['Items']),
                            'Items': [
                                {
                                    'Id': distribution['Origins']['Items'][0]['Id'],
                                    'DomainName': distribution['Origins']['Items'][0]['DomainName'],
                                    'S3OriginConfig': {
                                        'OriginAccessIdentity': 'origin-access-identity/cloudfront/XXXXXXXXXXXX'
                                    }
                                }
                            ]
                        },
                        'Enabled': True
                    },
                    IfMatch=distribution['ETag']
                )
        ```

        5. Replace `'origin-access-identity/cloudfront/XXXXXXXXXXXX'` with the actual Origin Access Identity that you want to use.

        6. Run the Python script to remediate the misconfiguration.

        With these steps, you can remediate the misconfiguration "Origin Access Identity should be enabled for CloudFront distributions" in AWS using Python.
      </Accordion>

      <Accordion title="Using Terraform">
        ```hcl theme={null}
        # CloudFront Origin Access Control (OAC) for S3 origin
        resource "aws_cloudfront_origin_access_control" "S3_OAC" {
          name                              = "oac-for-${aws_cloudfront_distribution.CLOUDFRONT_DISTRIBUTION.id}" # adjust if needed
          description                       = "OAC for distribution ${aws_cloudfront_distribution.CLOUDFRONT_DISTRIBUTION.id}"
          signing_protocol                  = "sigv4"
          signing_behavior                  = "always"
          origin_access_control_origin_type = "s3"
        }

        # CloudFront distribution with S3 origin using the OAC
        resource "aws_cloudfront_distribution" "CLOUDFRONT_DISTRIBUTION" {
          # ... other required arguments (enabled, default_cache_behavior, etc.)

          origin {
            domain_name = aws_s3_bucket.S3_ORIGIN_BUCKET.bucket_regional_domain_name
            origin_id   = "S3-${aws_s3_bucket.S3_ORIGIN_BUCKET.id}"

            s3_origin_config {
              origin_access_identity = null # ensure OAI is not used (legacy)
            }

            origin_access_control_id = aws_cloudfront_origin_access_control.S3_OAC.id
          }

          # ... rest of the distribution config
        }

        # S3 bucket used as the CloudFront origin
        resource "aws_s3_bucket" "S3_ORIGIN_BUCKET" {
          bucket = "S3_ORIGIN_BUCKET_NAME" # replace with your S3 origin bucket name
        }

        # Bucket policy granting CloudFront access via service principal + SourceArn condition
        resource "aws_s3_bucket_policy" "S3_ORIGIN_BUCKET_POLICY" {
          bucket = aws_s3_bucket.S3_ORIGIN_BUCKET.id

          # WARNING: This policy document REPLACES any existing bucket policy on this bucket.
          # If you already have a policy, merge its statements into this document before applying.
          policy = jsonencode({
            Version = "2012-10-17"
            Statement = [
              {
                Sid    = "AllowCloudFrontServicePrincipal"
                Effect = "Allow"
                Principal = {
                  Service = "cloudfront.amazonaws.com"
                }
                Action   = "s3:GetObject"
                Resource = "arn:aws:s3:::${aws_s3_bucket.S3_ORIGIN_BUCKET.bucket}/*"
                Condition = {
                  StringEquals = {
                    "AWS:SourceArn" = aws_cloudfront_distribution.CLOUDFRONT_DISTRIBUTION.arn
                  }
                }
              }
            ]
          })
        }
        ```

        Substitute:

        * `S3_ORIGIN_BUCKET_NAME` with your S3 origin bucket name.
        * Add all other required arguments to `aws_cloudfront_distribution.CLOUDFRONT_DISTRIBUTION` (commented as “...”).

        This change updates the CloudFront distribution in place (it does not force resource replacement) but will trigger a distribution update that must propagate to edge locations.

        For verification, `terraform plan` should show:

        * A new `aws_cloudfront_origin_access_control` resource.
        * An in-place update to `aws_cloudfront_distribution` adding `origin_access_control_id` and removing any OAI usage.
        * A create or update of `aws_s3_bucket_policy` with a statement allowing `cloudfront.amazonaws.com` with the `AWS:SourceArn` condition referencing the distribution ARN.
      </Accordion>
    </AccordionGroup>
  </Tab>
</Tabs>
