Back to Policies

Restrict Pod Controller ServiceAccount Updates

ServiceAccounts which have the ability to edit/patch workloads which they created may potentially use that privilege to update to a different ServiceAccount with higher privileges. This policy, intended to be run in `enforce` mode, blocks updates to Pod controllers if those updates modify the serviceAccountName field. Updates to Pods directly for this field are not possible as it is immutable once set.

View on GitHub

Policy Definition

apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: restrict-pod-controller-serviceaccount-updates
annotations:
policies.kyverno.io/title: Restrict Pod Controller ServiceAccount Updates
policies.kyverno.io/category: Other
policies.kyverno.io/severity: Medium
policies.kyverno.io/subject: Pod
kyverno.io/kyverno-version: 1.9.0
kyverno.io/kubernetes-version: "1.24"
policies.kyverno.io/description: ServiceAccounts which have the ability to edit/patch workloads which they created may potentially use that privilege to update to a different ServiceAccount with higher privileges. This policy, intended to be run in `enforce` mode, blocks updates to Pod controllers if those updates modify the serviceAccountName field. Updates to Pods directly for this field are not possible as it is immutable once set.
spec:
validationFailureAction: Audit
background: true
rules:
- name: block-serviceaccount-updates
match:
any:
- resources:
kinds:
- DaemonSet
- Deployment
- Job
- StatefulSet
- ReplicaSet
- ReplicationController
preconditions:
all:
- key: "{{ request.operation }}"
operator: Equals
value: UPDATE
validate:
message: The serviceAccountName field may not be changed once created.
deny:
conditions:
all:
- key: "{{ request.object.spec.template.spec.serviceAccountName || 'empty'}}"
operator: NotEquals
value: "{{ request.oldObject.spec.template.spec.serviceAccountName || 'empty'}}"
- name: block-serviceaccount-updates-cronjob
match:
any:
- resources:
kinds:
- CronJob
preconditions:
all:
- key: "{{ request.operation }}"
operator: Equals
value: UPDATE
validate:
message: The serviceAccountName field may not be changed once created.
deny:
conditions:
all:
- key: "{{ request.object.spec.jobTemplate.spec.template.spec.serviceAccountName || 'empty'}}"
operator: NotEquals
value: "{{ request.oldObject.spec.jobTemplate.spec.template.spec.serviceAccountName || 'empty'}}"

Related Policies