id: gcloud-vm-default-service-account

info:
  name: VM Instance Using Default Service Account
  author: princechaddha
  severity: medium
  description: |
    Ensure that your Google Compute Engine instances are not configured to use the default Google Cloud service account in order to implement the principle of least privilege (POLP) and secure the access to your cloud resources. The default Compute Engine service account, named <project-number>-compute@developer.gserviceaccount.com, is associated with the Editor role at the project level, which allows read and write access to most Google Cloud Platform (GCP) services.
  impact: |
    Using default service accounts with Editor role permissions violates the principle of least privilege and could allow compromised instances to access most GCP services in the project.
  remediation: |
    Create a new service account with minimal required permissions and update VM instances to use it instead of the default Compute Engine service account. Note that this requires stopping and restarting the instances.
  reference:
    - https://www.trendmicro.com/cloudoneconformity/knowledge-base/gcp/ComputeEngine/default-service-accounts-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)"

    matchers:
      - type: word
        words:
          - "compute@developer.gserviceaccount.com"

    extractors:
      - type: dsl
        dsl:
          - '"VM instance " + instanceName + " in zone " + zone + " of project " + projectId + " is using the default Compute Engine service account"'
# digest: 490a00463044022056c433909de7542bcfb57e00e14f55d349a49c2c70b34094a96d1e9bd0c6103b022069f487e8b93417439beb811bb6580f86c41f64454481eea7b2cee02a543494a6:922c64590222798bb761d5b6d8e72950