All Policies

Restrict Service Account

Users may be able to specify any ServiceAccount which exists in their Namespace without restrictions. Confining Pods to a list of authorized ServiceAccounts can be useful to ensure applications in those Pods do not have more privileges than they should. This policy verifies that in the `staging` Namespace the ServiceAccount being specified is matched based on the image and name of the container. For example: 'sa-name: ["registry/image-name"]'

Policy Definition

/other/restrict-service-account/restrict-service-account.yaml

 1apiVersion: kyverno.io/v1
 2kind: ClusterPolicy
 3metadata:
 4  name: restrict-service-account
 5  annotations:
 6    policies.kyverno.io/title: Restrict Service Account
 7    policies.kyverno.io/category: Sample
 8    policies.kyverno.io/severity: medium
 9    policies.kyverno.io/subject: Pod,ServiceAccount
10    policies.kyverno.io/minversion: 1.6.0
11    kyverno.io/kyverno-version: 1.6.2
12    kyverno.io/kubernetes-version: "1.23"
13    policies.kyverno.io/description: >-
14      Users may be able to specify any ServiceAccount which exists in their Namespace without
15      restrictions. Confining Pods to a list of authorized ServiceAccounts can be useful to
16      ensure applications in those Pods do not have more privileges than they should.
17      This policy verifies that in the `staging` Namespace the ServiceAccount being
18      specified is matched based on the image and name of the container. For example:
19      'sa-name: ["registry/image-name"]'
20spec:
21  validationFailureAction: Audit
22  background: true
23  rules:
24  - name: validate-service-account
25    context:
26    - name: saMap
27      configMap:
28        name: sa-map
29        namespace: staging
30    match:
31      any:
32      - resources:
33          kinds:
34          - Pod
35          namespaces:
36          - staging
37    validate:
38      message: "Invalid service account {{ request.object.spec.serviceAccountName }} for image {{ images.containers.*.registry | [0] }}/{{ images.containers.*.name | [0] }}"
39      deny:
40        conditions:
41          any:
42          - key: "{{ images.containers.*.registry | [0] }}/{{ images.containers.*.name | [0] }}"
43            operator: AnyNotIn
44            value: "{{ saMap.data.\"{{ request.object.spec.serviceAccountName }}\" }}"