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:
          - 'KEY_ID'

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