---
controls:
version: "gke-1.8.0"
id: 4
text: "Kubernetes Policies"
type: "policies"
groups:
  - id: 4.1
    text: "RBAC and Service Accounts"
    checks:
      - id: 4.1.1
        text: "Ensure that the cluster-admin role is only used where required (Automated)"
        audit: |
          kubectl get clusterrolebindings -o json | jq -r '
            [
              .items[]
              | select(.roleRef.name == "cluster-admin")
              | .subjects[]?
              | select(.kind != "Group" or .name != "system:masters")
            ]
            | if length == 0
              then "NO_CLUSTER_ADMIN_BINDINGS"
              else "FOUND_CLUSTER_ADMIN_BINDING"
              end
          '
        tests:
          test_items:
            - flag: "NO_CLUSTER_ADMIN_BINDINGS"
              set: true
              compare:
                op: eq
                value: "NO_CLUSTER_ADMIN_BINDINGS"
        remediation: |
          Identify all ClusterRoleBindings to the "cluster-admin" role and review their subjects:

            kubectl get clusterrolebindings -o=custom-columns=NAME:.metadata.name,ROLE:.roleRef.name,SUBJECTS:.subjects[*].name | grep cluster-admin

          If non-system principals (users, groups, or service accounts) do not strictly require cluster-admin,
          rebind them to a least-privileged (Cluster)Role and then remove the excessive binding:

            kubectl delete clusterrolebinding <binding-name>

          Notes:
          - Do not modify bindings with the "system:" prefix that are required for core components.
          - Prefer assigning narrowly scoped Roles/ClusterRoles that grant only the permissions needed.
        scored: true

      - id: 4.1.2
        text: "Minimize access to secrets (Automated)"
        audit: |
          count=$(kubectl get roles --all-namespaces -o json | jq '
            .items[]
            | select(.rules[]?
              | (.resources[]? == "secrets")
              and ((.verbs[]? == "get") or (.verbs[]? == "list") or (.verbs[]? == "watch"))
            )' | wc -l)

          if [ "$count" -gt 0 ]; then
            echo "SECRETS_ACCESS_FOUND"
          fi
        tests:
          test_items:
            - flag: "SECRETS_ACCESS_FOUND"
              set: false
        remediation: |
          Where possible, remove get, list and watch access to Secret objects in the cluster.
        scored: true

      - id: 4.1.3
        text: "Minimize wildcard use in Roles and ClusterRoles (Automated)"
        audit: |
          wildcards=$(kubectl get roles --all-namespaces -o json | jq '
            .items[] | select(
              .rules[]? | (.verbs[]? == "*" or .resources[]? == "*" or .apiGroups[]? == "*")
            )' | wc -l)

          wildcards_clusterroles=$(kubectl get clusterroles -o json | jq '
            .items[] | select(
              .rules[]? | (.verbs[]? == "*" or .resources[]? == "*" or .apiGroups[]? == "*")
            )' | wc -l)

          total=$((wildcards + wildcards_clusterroles))

          if [ "$total" -gt 0 ]; then
            echo "wildcards_present"
          fi
        tests:
          test_items:
            - flag: wildcards_present
              set: false
        remediation: |
          Where possible replace any use of wildcards in clusterroles and roles with specific
          objects or actions.
        scored: true

      - id: 4.1.4
        text: "Ensure that default service accounts are not actively used (Automated)"
        audit: |
          echo "🔹 Default Service Accounts with automountServiceAccountToken enabled:"
          default_sa_count=$(kubectl get serviceaccounts --all-namespaces -o json | jq '
            [.items[] | select(.metadata.name == "default" and (.automountServiceAccountToken != false))] | length')
          if [ "$default_sa_count" -gt 0 ]; then
            echo "default_sa_not_auto_mounted"
          fi

          echo "\n🔹 Pods using default ServiceAccount:"
          pods_using_default_sa=$(kubectl get pods --all-namespaces -o json | jq '
            [.items[] | select(.spec.serviceAccountName == "default")] | length')
          if [ "$pods_using_default_sa" -gt 0 ]; then
            echo "default_sa_used_in_pods"
          fi
        tests:
          test_items:
            - flag: default_sa_not_auto_mounted
              set: false
            - flag: default_sa_used_in_pods
              set: false
        remediation: |
          Create explicit service accounts wherever a Kubernetes workload requires specific
          access to the Kubernetes API server.

          Modify the configuration of each default service account to include this value

            automountServiceAccountToken: false
        scored: true

      - id: 4.1.5
        text: "Ensure that Service Account Tokens are only mounted where necessary (Automated)"
        audit: |
          echo "🔹 Pods with automountServiceAccountToken enabled:"
          pods_with_token_mount=$(kubectl get pods --all-namespaces -o json | jq '
            [.items[] | select(.spec.automountServiceAccountToken != false)] | length')

          if [ "$pods_with_token_mount" -gt 0 ]; then
            echo "automountServiceAccountToken"
          fi
        tests:
          test_items:
            - flag: automountServiceAccountToken
              set: false
        remediation: |
          Modify the definition of pods and service accounts which do not need to mount service
          account tokens to disable it.
        scored: true

      - id: 4.1.6
        text: "Avoid use of system:masters group (Automated)"
        audit: |
          found=0
          for csr in $(kubectl get csr -o name 2>/dev/null | sed 's|^.*/||'); do
            req=$(kubectl get csr "$csr" -o jsonpath='{.spec.request}' 2>/dev/null)
            [ -z "$req" ] && continue
            if echo "$req" | base64 -d 2>/dev/null | openssl req -noout -text 2>/dev/null | grep -q 'O = system:masters'; then
              conds=$(kubectl get csr "$csr" -o json | jq -r '[.status.conditions[]?.type] | join(",")')
              echo "FOUND_SYSTEM_MASTERS_CSR:${csr}:${conds:-NONE}"
              found=1
            fi
          done
          if [ "$found" -eq 0 ]; then
            echo "NO_SYSTEM_MASTERS_CREDENTIALS_FOUND"
          fi
        tests:
          test_items:
            - flag: "NO_SYSTEM_MASTERS_CREDENTIALS_FOUND"
              set: true
              compare:
                op: eq
                value: "NO_SYSTEM_MASTERS_CREDENTIALS_FOUND"
        remediation: |
          Remove the system:masters group from all users in the cluster.
        scored: true

      - id: 4.1.7
        text: "Limit use of the Bind, Impersonate and Escalate permissions in the Kubernetes cluster (Manual)"
        type: "manual"
        remediation: |
          Where possible, remove the impersonate, bind and escalate rights from subjects.
        scored: false

      - id: 4.1.8
        text: "Avoid bindings to system:anonymous (Automated)"
        audit: |
          # Flags any ClusterRoleBinding/RoleBinding that targets the user "system:anonymous".
          # Prints "NO_ANONYMOUS_BINDINGS" when none are found.
          (
            kubectl get clusterrolebindings -o json | jq -r '
              .items[]
              | select((.subjects | length) > 0)
              | select(any(.subjects[]?;
                  .kind=="User" and .name=="system:anonymous"
                ))
              | "FOUND_ANONYMOUS:ClusterRoleBinding:\(.metadata.name):ROLE=\(.roleRef.kind)/\(.roleRef.name)"
            ';
            kubectl get rolebindings -A -o json | jq -r '
              .items[]
              | select((.subjects | length) > 0)
              | select(any(.subjects[]?;
                  .kind=="User" and .name=="system:anonymous"
                ))
              | "FOUND_ANONYMOUS:RoleBinding:\(.metadata.namespace):\(.metadata.name):ROLE=\(.roleRef.kind)/\(.roleRef.name)"
            '
          ) | (grep -q '^FOUND_ANONYMOUS:' && cat || echo 'NO_ANONYMOUS_BINDINGS')
        tests:
          test_items:
            - flag: "NO_ANONYMOUS_BINDINGS"
              set: true
              compare:
                op: eq
                value: "NO_ANONYMOUS_BINDINGS"
        remediation: |
          Identify all clusterrolebindings and rolebindings to the user system:anonymous.
          Check if they are used and review the permissions associated with the binding using the
          commands in the Audit section above or refer to GKE documentation
          (https://cloud.google.com/kubernetes-engine/docs/best-practices/rbac#detect-prevent-default).

          Strongly consider replacing unsafe bindings with an authenticated, user-defined group.
          Where possible, bind to non-default, user-defined groups with least-privilege roles.

          If there are any unsafe bindings to the user system:anonymous, proceed to delete them
          after consideration for cluster operations with only necessary, safer bindings.

            kubectl delete clusterrolebinding [CLUSTER_ROLE_BINDING_NAME]
            kubectl delete rolebinding [ROLE_BINDING_NAME] --namespace [ROLE_BINDING_NAMESPACE]
        scored: true

      - id: 4.1.9
        text: "Avoid non-default bindings to system:unauthenticated (Automated)"
        audit: |
          # Flags any non-default binding to the group "system:unauthenticated".
          # Prints "NO_NON_DEFAULT_UNAUTH_BINDINGS" when none are found.
          (
            kubectl get clusterrolebindings -o json | jq -r '
              .items[]
              | select(.metadata.name != "system:public-info-viewer")
              | select((.subjects | length) > 0)
              | select(any(.subjects[]?;
                  .kind=="Group" and .name=="system:unauthenticated"
                ))
              | "FOUND_UNAUTH:ClusterRoleBinding:\(.metadata.name):ROLE=\(.roleRef.kind)/\(.roleRef.name)"
            ';
            kubectl get rolebindings -A -o json | jq -r '
              .items[]
              | select((.subjects | length) > 0)
              | select(any(.subjects[]?;
                  .kind=="Group" and .name=="system:unauthenticated"
                ))
              | "FOUND_UNAUTH:RoleBinding:\(.metadata.namespace):\(.metadata.name):ROLE=\(.roleRef.kind)/\(.roleRef.name)"
            '
          ) | (grep -q "^FOUND_UNAUTH:" && cat || echo "NO_NON_DEFAULT_UNAUTH_BINDINGS")
        tests:
          test_items:
            - flag: "NO_NON_DEFAULT_UNAUTH_BINDINGS"
              set: true
              compare:
                op: eq
                value: "NO_NON_DEFAULT_UNAUTH_BINDINGS"
        remediation: |
          Identify all non-default clusterrolebindings and rolebindings to the group
          system:unauthenticated. Check if they are used and review the permissions
          associated with the binding using the commands in the Audit section above or refer to
          GKE documentation (https://cloud.google.com/kubernetes-engine/docs/best-practices/rbac#detect-prevent-default).

          Strongly consider replacing non-default, unsafe bindings with an authenticated, user-
          defined group. Where possible, bind to non-default, user-defined groups with least-
          privilege roles.

          If there are any non-default, unsafe bindings to the group system:unauthenticated,
          proceed to delete them after consideration for cluster operations with only necessary,
          safer bindings.

            kubectl delete clusterrolebinding [CLUSTER_ROLE_BINDING_NAME]
            kubectl delete rolebinding [ROLE_BINDING_NAME] --namespace [ROLE_BINDING_NAMESPACE]
        scored: true

      - id: 4.1.10
        text: "Avoid non-default bindings to system:authenticated (Automated)"
        audit: |
          # Flags any non-default binding to the group "system:authenticated".
          # Allowed defaults (CRB): system:basic-user, system:discovery
          # Prints "NO_NON_DEFAULT_AUTH_BINDINGS" when none are found.
          (
            kubectl get clusterrolebindings -o json | jq -r '
              .items[]
              | select((.metadata.name != "system:basic-user") and (.metadata.name != "system:discovery"))
              | select((.subjects | length) > 0)
              | select(any(.subjects[]?;
                  .kind=="Group" and .name=="system:authenticated"
                ))
              | "FOUND_AUTH:ClusterRoleBinding:\(.metadata.name):ROLE=\(.roleRef.kind)/\(.roleRef.name)"
            ';
            kubectl get rolebindings -A -o json | jq -r '
              .items[]
              | select((.subjects | length) > 0)
              | select(any(.subjects[]?;
                  .kind=="Group" and .name=="system:authenticated"
                ))
              | "FOUND_AUTH:RoleBinding:\(.metadata.namespace):\(.metadata.name):ROLE=\(.roleRef.kind)/\(.roleRef.name)"
            '
          ) | (grep -q "^FOUND_AUTH:" && cat || echo "NO_NON_DEFAULT_AUTH_BINDINGS")
        tests:
          test_items:
            - flag: "NO_NON_DEFAULT_AUTH_BINDINGS"
              set: true
              compare:
                op: eq
                value: "NO_NON_DEFAULT_AUTH_BINDINGS"
        remediation: |
          Identify all non-default clusterrolebindings and rolebindings to the group
          system:authenticated. Check if they are used and review the permissions associated
          with the binding using the commands in the Audit section above or refer to GKE
          documentation.

          Strongly consider replacing non-default, unsafe bindings with an authenticated, user-
          defined group. Where possible, bind to non-default, user-defined groups with least-
          privilege roles.

          If there are any non-default, unsafe bindings to the group system:authenticated,
          proceed to delete them after consideration for cluster operations with only necessary,
          safer bindings.

            kubectl delete clusterrolebinding [CLUSTER_ROLE_BINDING_NAME]
            kubectl delete rolebinding [ROLE_BINDING_NAME] --namespace [ROLE_BINDING_NAMESPACE]
        scored: true

  - id: 4.2
    text: "Pod Security Standards"
    checks:
      - id: 4.2.1
        text: "Ensure that the cluster enforces Pod Security Standard Baseline profile or stricter for all namespaces. (Manual)"
        type: "manual"
        remediation: |
          Ensure that Pod Security Admission is in place for every namespace which contains
          user workloads.
          Run the following command to enforce the Baseline profile in a namespace:

            kubectl label namespace pod-security.kubernetes.io/enforce=baseline
        scored: false

  - id: 4.3
    text: "Network Policies and CNI"
    checks:
      - id: 4.3.1
        text: "Ensure that the CNI in use supports Network Policies (Manual)"
        type: "manual"
        remediation: |
          To use a CNI plugin with Network Policy, enable Network Policy in GKE, and the CNI plugin
          will be updated. See Recommendation 5.6.7.
        scored: false

      - id: 4.3.2
        text: "Ensure that all Namespaces have Network Policies defined (Automated)"
        audit: |
          (kubectl get ns -o json; kubectl get networkpolicy -A -o json) \
          | jq -rs '
            (.[0].items | map(.metadata.name)
             | map(select(.!="kube-system" and .!="kube-public" and .!="kube-node-lease"))) as $ns
            |
            ( (.[1].items // [])
              | sort_by(.metadata.namespace)
              | group_by(.metadata.namespace)
              | map({key: .[0].metadata.namespace, value: length})
              | from_entries
            ) as $np
            |
            [ $ns[] | select( ($np[.] // 0) == 0 ) ] as $missing
            |
            if ($missing|length)>0
            then ($missing[] | "FOUND_NAMESPACE_WITHOUT_NETWORKPOLICY:"+.)
            else "ALL_NAMESPACES_HAVE_NETWORK_POLICIES"
            end
          '
        tests:
          test_items:
            - flag: "ALL_NAMESPACES_HAVE_NETWORK_POLICIES"
              set: true
              compare:
                op: eq
                value: "ALL_NAMESPACES_HAVE_NETWORK_POLICIES"
        remediation: |
          Follow the documentation and create NetworkPolicy objects as needed.
          See: https://cloud.google.com/kubernetes-engine/docs/how-to/network-policy#creating_a_network_policy
          for more information.
        scored: true

  - id: 4.4
    text: "Secrets Management"
    checks:
      - id: 4.4.1
        text: "Prefer using secrets as files over secrets as environment variables (Automated)"
        audit: |
          output=$(kubectl get all --all-namespaces -o jsonpath='{range .items[?(@..secretKeyRef)]} {.kind} {.metadata.name} {"\n"}{end}')
          if [ -z "$output" ]; then echo "NO_ENV_SECRET_REFERENCES"; else echo "ENV_SECRET_REFERENCES_FOUND"; fi
        tests:
          test_items:
            - flag: "NO_ENV_SECRET_REFERENCES"
              set: true
              compare:
                op: eq
                value: "NO_ENV_SECRET_REFERENCES"
        remediation: |
          if possible, rewrite application code to read secrets from mounted secret files, rather than
          from environment variables.
        scored: true

      - id: 4.4.2
        text: "Consider external secret storage (Manual)"
        type: "manual"
        remediation: |
          Refer to the secrets management options offered by your cloud provider or a third-party
          secrets management solution.
        scored: false

  - id: 4.5
    text: "Extensible Admission Control"
    checks:
      - id: 4.5.1
        text: "Configure Image Provenance using ImagePolicyWebhook admission controller (Manual)"
        type: "manual"
        remediation: |
          Follow the Kubernetes documentation and setup image provenance.
          Also see recommendation 5.10.4.
        scored: false

  - id: 4.6
    text: "General Policies"
    checks:
      - id: 4.6.1
        text: "Create administrative boundaries between resources using namespaces (Manual)"
        type: "manual"
        remediation: |
          Follow the documentation and create namespaces for objects in your deployment as you need
          them.
        scored: false

      - id: 4.6.2
        text: "Ensure that the seccomp profile is set to RuntimeDefault in your pod definitions (Automated)"
        type: "manual"
        remediation: |
          Use security context to enable the RuntimeDefault seccomp profile in your pod
          definitions. An example is as below:

            {
              "namespace": "kube-system",
              "name": "metrics-server-v0.7.0-dbcc8ddf6-gz7d4",
              "seccompProfile": "RuntimeDefault"
            }
        scored: false

      - id: 4.6.3
        text: "Apply Security Context to Your Pods and Containers (Manual)"
        type: "manual"
        remediation: |
          Follow the Kubernetes documentation and apply security contexts to your pods. For a
          suggested list of security contexts, you may refer to the CIS Google Container-
          Optimized OS Benchmark.
        scored: false

      - id: 4.6.4
        text: "The default namespace should not be used (Automated)"
        audit: |
          output=$(kubectl get all -n default --no-headers 2>/dev/null | grep -v '^service\s\+kubernetes\s' || true)
          if [ -z "$output" ]; then echo "DEFAULT_NAMESPACE_UNUSED"; else echo "DEFAULT_NAMESPACE_IN_USE"; fi
        tests:
          test_items:
            - flag: "DEFAULT_NAMESPACE_UNUSED"
              set: true
              compare:
                op: eq
                value: "DEFAULT_NAMESPACE_UNUSED"
        remediation: |
          Ensure that namespaces are created to allow for appropriate segregation of Kubernetes
          resources and that all new resources are created in a specific namespace.
        scored: true
