id: gcloud-service-account-user-keys

info:
  name: User-Managed Service Account Keys Found
  author: princechaddha
  severity: medium
  description: |
    Ensure that your Google Cloud Platform (GCP) user-managed service accounts are using GCP-managed keys instead of user-managed keys for authentication. For user-managed key pairs, key management operations such as key storage, key distribution, key revocation, key recovery, and key rotation, as well as key protection against unauthorized access, are your responsibilities.
  impact: |
    Using user-managed keys can lead to potential security risks such as unauthorized access if keys are not properly managed and secured.
  remediation: |
    Transition to using GCP-managed keys for service accounts to ensure key management is handled by Google Cloud, thereby enhancing security and reducing the administrative burden of manual key management.
  reference:
    - https://cloud.google.com/iam/docs/managing-service-account-keys
  tags: cloud,devops,gcp,gcloud,google-cloud-iam,gcp-cloud-config

flow: |
  code(1)
  for(let projectId of iterate(template.projectIds)){
    set("projectId", projectId)
    code(2)
    for(let email of iterate(template.emails)){
      set("email", email)
      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 iam service-accounts list --project $projectId --format="json(email)"

    extractors:
      - type: json
        name: emails
        internal: true
        json:
          - ".[].email"

  - engine:
      - sh
      - bash
    source: |
      gcloud iam service-accounts keys list --iam-account=$email --managed-by=user --format="json"

    matchers:
      - type: word
        words:
          - "USER_MANAGED"
          - "KEY_ID"
        condition: or

    extractors:
      - type: dsl
        dsl:
          - '"User-Managed Keys Found in Service Account " + email + " in project " + projectId'
# digest: 490a0046304402200b5e24605932c74af12b6c325e37ca631802cc31f53ffbd0bc812862c1f2a6bf02205f1402f6334cba1c99ea9385c89646f8a707b752850f350c30263061779818c3:922c64590222798bb761d5b6d8e72950