# SPDX-FileCopyrightText: 2024 Bundesministerium des Innern und für Heimat, PG ZenDiS "Projektgruppe für Aufbau ZenDiS"
# SPDX-License-Identifier: Apache-2.0
---
apiVersion: "kyverno.io/v1"
kind: "ClusterPolicy"
metadata:
  name: "disallow-default-serviceaccount"
  annotations:
    policies.kyverno.io/title: "Prevent default ServiceAccount privilege escalation"
    policies.kyverno.io/subject: "Pod"
    policies.kyverno.io/description: >-
      Kubernetes automatically creates a ServiceAccount object named default for every namespace in your cluster.
      These default service accounts get no permissions by default.
      Accidental or intended assignment of permissions on the default service account results in elevated permissions
      for all pods with default service account assigned.
      This risk can be mitigated by creating a custom ServiceAccount for each application or reduce the risk by disable
      auto mounting the default service account into the pod.
spec:
  background: true
  rules:
    - match:
        resources:
          kinds:
            - "Pod"
      name: "disallow-default-serviceAccountName"
      validate:
        message: >-
          Field serviceAccountName must be set to anything other than 'default'.
          When serviceAccountName is 'default' then automountServiceAccountToken must set to 'false' .
        anyPattern:
          - spec:
              serviceAccountName: "!default"
          - spec:
              automountServiceAccountToken: "false"
  validationFailureAction: "audit"
...
