id: k8s-role-pod-create

info:
  name: Roles that have pod create permissions
  author: domwhewell-sage
  severity: medium
  description: Checks for roles that have permissions to create pods.
  impact: |
    Pods that have the service account with a role that allows them to create pods, could allow a pod breakout.
  remediation: Configure pods so they are not assigned the permission to create other pods
  reference:
    - https://kubernetes.io/docs/concepts/security/rbac-good-practices/#least-privilege
    - https://cloud.hacktricks.wiki/en/pentesting-cloud/kubernetes-security/abusing-roles-clusterroles-in-kubernetes/index.html
  tags: cloud,devops,kubernetes,devsecops,roles,k8s,k8s-cluster-security

flow: |
  code(1);
  for (let role of template.items) {
    set("role", role)
    javascript(1);
  }

self-contained: true
code:
  - engine:
      - sh
      - bash
    source: kubectl get role --all-namespaces --output=json
    extractors:
      - type: json
        name: items
        internal: true
        json:
          - '.items[]'

javascript:
  - code: |
        let role = JSON.parse(template.role);
        let riskyRules = 0;
        role.rules.forEach(rule => {
          if ((rule.resources.includes("pods") && rule.verbs.includes("create")) ||
              (rule.resources.includes("pods") && rule.verbs.includes("*")) ||
              (rule.resources.includes("*") && rule.verbs.includes("create")) ||
              (rule.resources.includes("*") && rule.verbs.includes("*"))) {
            riskyRules++;
          }
        });
        if (riskyRules > 0) {
          let result = (`Role '${role.metadata.name}' in namespace '${role.metadata.namespace}' has ${riskyRules} rule(s) with 'pods' resource and 'create' verb.`);
          Export(result);
        }

    extractors:
      - type: dsl
        dsl:
          - response
# digest: 4b0a00483046022100d2e5577540b193bfbc85b570e8b36dd351705f4e45ca26c8ffc614abc5aa5336022100e00accf96a83579e3addfc9cc8b2830a7ec1b7eb754c8bd6240ee344b2ce9f35:922c64590222798bb761d5b6d8e72950