id: gcloud-vm-default-service-account-full-access

info:
  name: VM Instance Using Default Service Account with Full API Access
  author: princechaddha
  severity: medium
  description: |
    Ensure that your Google Compute Engine instances are not configured to use the default service account with the Cloud API access scope set to "Allow full access to all Cloud APIs". The principle of least privilege (POLP), also known as the principle of least authority, is the security concept of giving the user/system/service the minimal set of permissions required to successfully perform its tasks.
  impact: |
    Using default service accounts with full API access violates the principle of least privilege and could allow compromised instances to make unauthorized API calls to any GCP service.
  remediation: |
    Either replace the default service account with a custom one having minimal permissions, or change the access scope to "Allow default access" or "Set access for each API" with only required permissions.
  reference:
    - https://www.trendmicro.com/cloudoneconformity/knowledge-base/gcp/ComputeEngine/default-service-accounts-with-full-access-in-use.html
    - https://cloud.google.com/compute/docs/access/service-accounts
  tags: cloud,devops,gcp,gcloud,compute,security,iam,service-account,gcp-cloud-config

flow: |
  code(1)
  for(let projectId of iterate(template.projectIds)){
    set("projectId", projectId)
    code(2)
    for(let instance of iterate(template.instances)){
      instance = JSON.parse(instance)
      set("instanceName", instance.name)
      set("zone", instance.zone)
      code(3)
    }
  }

self-contained: true

code:
  - engine:
      - sh
      - bash
    source: |
      gcloud projects list --format="json(projectId)"

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

  - engine:
      - sh
      - bash
    source: |
      gcloud compute instances list --project $projectId --format="json(name,zone.basename())"

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

  - engine:
      - sh
      - bash
    source: |
      gcloud compute instances describe $instanceName --zone $zone --project $projectId --format="json(serviceAccounts[].email,serviceAccounts[].scopes[])"

    matchers:
      - type: word
        words:
          - "compute@developer.gserviceaccount.com"
          - "https://www.googleapis.com/auth/cloud-platform"
        condition: and

    extractors:
      - type: dsl
        dsl:
          - '"VM instance " + instanceName + " in zone " + zone + " of project " + projectId + " is using the default Compute Engine service account with full API access"'
# digest: 4a0a0047304502200d7ad4091f6a0ff34060826a1f14902901761a78be4de2737113f701a7e8e639022100e209dcd0cb14413813d204950308de2f7a6e1b116ddb2a54bd332d8ddbfa0c7e:922c64590222798bb761d5b6d8e72950