id: s3-bucket-policy-public-access
info:
  name: Public Access of S3 Buckets via Policy
  author: princechaddha
  severity: critical
  description: |
    This template checks if Amazon S3 buckets are configured to prevent public access via bucket policies
  reference:
    - https://docs.aws.amazon.com/cli/latest/reference/s3api/get-bucket-policy.html
  metadata:
    max-request: 2
  tags: cloud,devops,aws,amazon,s3,aws-cloud-config

flow: |
  code(1)
  for(let bucketName of iterate(template.buckets)){
    set("bucket", bucketName)
    code(2)
  }

self-contained: true
code:
  - engine:
      - sh
      - bash
    source: |
      aws s3api list-buckets --query 'Buckets[*].Name'

    extractors:
      - type: json
        internal: true
        name: buckets
        json:
          - '.[]'

  - engine:
      - sh
      - bash
    source: |
      aws s3api get-bucket-policy --bucket $bucket --query Policy --output text

    matchers:
      - type: regex
        part: body
        regex:
          - '\{[^}]*?(?:(?:"Effect"\s*:\s*"Allow"[^}]*?"Principal"\s*:\s*(?:"\*"|\{\s*"AWS"\s*:\s*"\*"\s*\}))|(?:"Principal"\s*:\s*(?:"\*"|\{\s*"AWS"\s*:\s*"\*"\s*\})[^}]*?"Effect"\s*:\s*"Allow"))[^}]*?\}'

    extractors:
      - type: dsl
        dsl:
          - '"The S3 bucket " + bucket +" is publicly accessible via Policy"'
# digest: 4a0a0047304502204aa1c0bf7c39ed575786813f4442686d138c58747766d33101948713281ac9610221008b7dc698b16415a2e1262b4bf9da7afda5e909f72df76d03d403dab9b8f1d479:922c64590222798bb761d5b6d8e72950