id: k8s-root-container-admission

info:
  name: Minimize the admission of root containers
  author: princechaddha
  severity: critical
  description: Checks if any Kubernetes Deployments admit containers that run as root, which can pose a significant security risk.
  impact: |
    Allowing containers to run as root can lead to privilege escalation and unauthorized access to host resources, significantly compromising the security of the cluster.
  remediation: |
    Configure security contexts for all pods to run containers with a non-root user. Use Pod Security Policies or OPA/Gatekeeper to enforce these configurations.
  reference:
    - https://kubernetes.io/docs/concepts/policy/pod-security-policy/#users-and-groups
  tags: cloud,devops,kubernetes,devsecops,deployments,k8s,k8s-cluster-security

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

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

javascript:
  - code: |
        deployment = JSON.parse(template.deployment);
        if (deployment.spec.template.spec.containers.some(container => container.securityContext && container.securityContext.runAsUser === null)) {
          let result = (`Deployment '${deployment.metadata.name}' in namespace '${deployment.metadata.namespace}' permits containers to run as root.`);
          Export(result);
        }

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