Admission Control for Trusted Workloads
Write a ValidatingAdmissionPolicy in CEL that admits only images from an allow-listed registry pinned by digest, prove it with rejected and admitted requests on a real API server, close the Deployment and ephemeral-container paths, roll it out with Warn and Audit first, and see how Kyverno or Sigstore policy-controller add signature checks.
Contentsand lesson path
On this page
- The problem
- Step 1: Write the policy
- Step 2: Apply it and label the namespace
- Step 3: Test with requests that must fail and one that must pass
- Step 4: Check the paths around the rule
- Step 5: Roll it out with Warn and Audit first
- Step 6: Add signature verification
- Common mistakes
- Check your understanding
- Apply it
- Review prompt
Lessons of Container & Kubernetes Security
- What Containers Isolate and What They Do Not Concept · 15 min
- Hardening and Scanning Images Lab · 25 min
- Cluster Hardening: RBAC, Pod Security and Network Policy Lab · 30 min
- Admission Control for Trusted Workloads Worked example · 20 min
- Runtime Detection and Cluster Audit Logs Lab · 25 min
- Container & Kubernetes Security Check Knowledge check · 6 questions
What you will learn
- Build minimal, non-root container images, scan them for vulnerabilities and misconfigurations, and enforce signed or allow-listed images at admission.
Prerequisites: Kubernetes Fundamentals
01. The problem
The shop team builds its images in CI and pushes them to registry.shop.example, its private registry. The cluster should run nothing else in the shop namespace: no image from Docker Hub, no image from a host whose name only looks similar, and no image named by a tag, because a tag can be moved to different content after review. That last point is how Implant Internal Image (T1525) works in a registry: the name stays the same and the content changes. Pinning by digest, the SHA-256 of the image manifest, means the cluster runs exactly the bytes that were reviewed and scanned.
Admission control is the right place for this rule. Create and update requests pass through admission after authentication and authorisation and before the object is stored, so a rule there applies to people, pipelines and controllers alike. Since Kubernetes v1.30 the API server has a built-in way to write such rules: a ValidatingAdmissionPolicy, whose checks are expressions in CEL (Common Expression Language). It runs inside the API server, so there is no webhook service to deploy or keep available.
This worked example uses the control plane from the lab Cluster Hardening: RBAC, Pod Security and Network Policy, steps 1 and 2, with its shop namespace. Every step needs only kubectl, so any v1.30 or later cluster, including kind, works too. registry.shop.example uses the reserved .example domain; on a control plane without nodes the pods are only checked and stored, never pulled.
02. Step 1: Write the policy
A policy has three parts. matchConstraints says which requests it sees. variables compute values once, so that the checks stay readable. validations are CEL expressions that must be true; messageExpression builds the error that the client sees.
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicy
metadata:
name: trusted-images
spec:
failurePolicy: Fail
matchConstraints:
resourceRules:
- apiGroups: [""]
apiVersions: ["v1"]
operations: ["CREATE", "UPDATE"]
resources: ["pods", "pods/ephemeralcontainers"]
- apiGroups: ["apps"]
apiVersions: ["v1"]
operations: ["CREATE", "UPDATE"]
resources: ["deployments", "statefulsets", "daemonsets", "replicasets"]
variables:
- name: podSpec
expression: "object.kind == 'Pod' ? object.spec : object.spec.template.spec"
- name: images
expression: >-
variables.podSpec.containers.map(c, c.image)
+ variables.podSpec.?initContainers.orValue([]).map(c, c.image)
+ variables.podSpec.?ephemeralContainers.orValue([]).map(c, c.image)
- name: untrusted
expression: >-
variables.images.filter(i, !i.startsWith('registry.shop.example/'))
- name: unpinned
expression: >-
variables.images.filter(i, !i.matches('@sha256:[a-f0-9]{64}$'))
validations:
- expression: "size(variables.untrusted) == 0"
messageExpression: >-
'image not from registry.shop.example: ' + variables.untrusted.join(', ')
reason: Forbidden
- expression: "size(variables.unpinned) == 0"
messageExpression: >-
'image not pinned by digest: ' + variables.unpinned.join(', ')
reason: Forbidden
---
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicyBinding
metadata:
name: trusted-images-enforce
spec:
policyName: trusted-images
validationActions: [Deny]
matchResources:
namespaceSelector:
matchLabels:
images.shop.example/policy: enforceRead it in order. The policy matches pods and also the workload kinds that contain a pod template. Pods would be enough to stop a bad image from running, because controllers create pods through the API too, but checking the Deployment gives the author an error at kubectl apply time instead of a ReplicaSet that fails quietly. The subresource pods/ephemeralcontainers is listed because kubectl debug adds containers to an existing pod through it, and a rule on pods alone does not see that request.
The podSpec variable picks object.spec for a pod and object.spec.template.spec for a workload. The images variable collects containers, init containers and ephemeral containers; the ?. operator with orValue([]) returns an empty list when a field is missing, instead of an error. The allow-list check ends with a slash, so registry.shop.example.lookalike.test does not pass. The digest check requires @sha256: and 64 hexadecimal characters at the end of the reference. failurePolicy: Fail means that if an expression cannot be evaluated, the request is rejected rather than allowed.
The binding connects the policy to namespaces. validationActions: [Deny] rejects violating requests, and the namespaceSelector limits it to namespaces that carry the label, so system namespaces are not affected by accident.
03. Step 2: Apply it and label the namespace
kubectl apply -f image-policy.yaml -o name
kubectl label namespace shop images.shop.example/policy=enforce
sleep 2
kubectl get validatingadmissionpolicy trusted-images -o jsonpath='{.status}'; echovalidatingadmissionpolicy.admissionregistration.k8s.io/trusted-images
validatingadmissionpolicybinding.admissionregistration.k8s.io/trusted-images-enforce
namespace/shop labeled
{"observedGeneration":1,"typeChecking":{}}The API server type-checks every expression against the schemas of the matched resources and reports problems in status.typeChecking. An empty object means it found none. Check this after each change; a typo in a field name shows up here before it rejects real traffic.
04. Step 3: Test with requests that must fail and one that must pass
Test a security rule with the inputs it must reject, not only with the one it must allow. --dry-run=server sends the request through authentication, authorisation and admission, but does not store the object, so you can repeat the tests freely.
D=sha256:80b514138d31203ce7fb099562f8b9bb2cfe49790d84ee967a078d88319eb9d0
try() {
echo "== ${1/@$D/@\$D}"
kubectl -n shop run web --image="$1" --dry-run=server -o name 2>&1 | fold -s -w 80
}
try nginx:latest
try registry.shop.example/web:1.4.2
try registry.shop.example.lookalike.test/web@$D
try registry.shop.example/web@$D== nginx:latest
Error from server (Forbidden): pods "web" is forbidden:
ValidatingAdmissionPolicy 'trusted-images' with binding
'trusted-images-enforce' denied request: image not from registry.shop.example:
nginx:latest
== registry.shop.example/web:1.4.2
Error from server (Forbidden): pods "web" is forbidden:
ValidatingAdmissionPolicy 'trusted-images' with binding
'trusted-images-enforce' denied request: image not pinned by digest:
registry.shop.example/web:1.4.2
== registry.shop.example.lookalike.test/web@$D
Error from server (Forbidden): pods "web" is forbidden:
ValidatingAdmissionPolicy 'trusted-images' with binding
'trusted-images-enforce' denied request: image not from registry.shop.example:
registry.shop.example.lookalike.test/web@sha256:80b514138d31203ce7fb099562f8b9bb
2cfe49790d84ee967a078d88319eb9d0
== registry.shop.example/web@$D
pod/webEach rejection names the image and the reason, which helps the author fix it without asking you. Note that nginx:latest is a short name for docker.io/library/nginx:latest: the policy sees the reference exactly as written, so allow-lists must be written for the full form your teams use.
05. Step 4: Check the paths around the rule
A rule is only as good as the paths it covers. Try a Deployment, and then an ephemeral container added to an existing pod with kubectl debug.
D=sha256:80b514138d31203ce7fb099562f8b9bb2cfe49790d84ee967a078d88319eb9d0
echo "== a Deployment with an untrusted image"
kubectl -n shop create deployment api --image=docker.io/library/nginx:1.29 \
--dry-run=server -o name 2>&1 | fold -s -w 80
echo "== an ephemeral debug container added to an existing pod"
kubectl -n shop run web --image=registry.shop.example/web@$D
kubectl -n shop debug web --image=busybox:1.37 --container=debugger 2>&1 \
| fold -s -w 80== a Deployment with an untrusted image
error: failed to create deployment: deployments.apps "api" is forbidden:
ValidatingAdmissionPolicy 'trusted-images' with binding
'trusted-images-enforce' denied request: image not from registry.shop.example:
docker.io/library/nginx:1.29
== an ephemeral debug container added to an existing pod
pod/web created
Error from server (Forbidden): pods "web" is forbidden:
ValidatingAdmissionPolicy 'trusted-images' with binding
'trusted-images-enforce' denied request: image not from registry.shop.example:
busybox:1.37Both are rejected. If you delete pods/ephemeralcontainers from the policy and repeat the last command, the API server accepts the debug container with its Docker Hub image. Unexpected debug containers in production are worth an alert of their own: adding one is a way to run a new image inside a pod without creating a pod (compare Deploy Container, T1610).
An alert needs the image, and the lab's audit policy records pods/ephemeralcontainers at Request level for that reason: the event keeps the request body, rejected attempts included. Read it back.
python3 - <<'PY'
import json
for line in open("logs/audit.log"):
e = json.loads(line)
if e.get("objectRef", {}).get("subresource") == "ephemeralcontainers":
added = e["requestObject"]["spec"]["ephemeralContainers"]
print(e["level"], e["verb"], e["user"]["username"], e["objectRef"]["name"],
"->", e["responseStatus"]["code"], [c["image"] for c in added])
PYRequest patch lab-admin web -> 403 ['busybox:1.37']06. Step 5: Roll it out with Warn and Audit first
Switching on Deny across many namespaces at once breaks deployments you did not know about. A second binding for the same policy can use validationActions: [Warn, Audit]: the client gets a warning, the request succeeds, and the audit log records the failure.
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicyBinding
metadata:
name: trusted-images-dry-run
spec:
policyName: trusted-images
validationActions: [Warn, Audit]
matchResources:
namespaceSelector:
matchLabels:
images.shop.example/policy: warnkubectl apply -f image-policy-warn.yaml -o name
kubectl create namespace staging
kubectl label namespace staging images.shop.example/policy=warn
kubectl -n staging wait --for=create serviceaccount/default --timeout=30s
sleep 3 # bindings and namespace labels reach admission through a cache
kubectl -n staging run legacy --image=nginx:1.29 2>&1 | fold -s -w 80validatingadmissionpolicybinding.admissionregistration.k8s.io/trusted-images-dry-run
namespace/staging created
namespace/staging labeled
serviceaccount/default condition met
Warning: Validation failed for ValidatingAdmissionPolicy 'trusted-images' with
binding 'trusted-images-dry-run': image not from registry.shop.example:
nginx:1.29
Warning: Validation failed for ValidatingAdmissionPolicy 'trusted-images' with
binding 'trusted-images-dry-run': image not pinned by digest: nginx:1.29
pod/legacy createdThe Audit action adds an annotation to the audit event. Collect the failures from the log, which gives you the list of workloads to fix before you change the namespace label to enforce.
python3 - <<'PY'
import json
KEY = "validation.policy.admission.k8s.io/validation_failure"
for line in open("logs/audit.log"):
event = json.loads(line)
failures = event.get("annotations", {}).get(KEY)
for failure in json.loads(failures) if failures else []:
ref, code = event["objectRef"], event["responseStatus"]["code"]
print(f'{ref["namespace"]}/{ref["name"]} -> {code}: {failure["message"]}')
PYstaging/legacy -> 201: image not from registry.shop.example: nginx:1.29
staging/legacy -> 201: image not pinned by digest: nginx:1.2907. Step 6: Add signature verification
The allow-list proves where an image is stored, not who built it. Anyone with push rights to the registry, including a stolen CI credential, can push an image that passes. The stronger rule is: run only images signed by your CI pipeline, and run them by digest. With Sigstore keyless signing, CI signs with a short-lived certificate that names its identity, for example the GitHub Actions workflow that ran, and the signature is recorded in the public transparency log. The admission check then verifies the signature against that exact identity and issuer.
Checking a signature means fetching it from the registry, which CEL in the API server cannot do. You need an admission webhook. Kyverno's ImageValidatingPolicy (or the older verifyImages rule in a ClusterPolicy) and Sigstore's policy-controller (ClusterImagePolicy) both do this. The policy below follows the Kyverno 1.20 documentation. It needs Kyverno installed in a cluster and a registry it can reach, so it is not run in this lesson.
# Illustrative only: needs Kyverno 1.20 running in the cluster and a real registry.
apiVersion: policies.kyverno.io/v1
kind: ImageValidatingPolicy
metadata:
name: shop-images-signed-by-ci
spec:
validationActions: [Deny]
matchConstraints:
resourceRules:
- apiGroups: [""]
apiVersions: ["v1"]
operations: ["CREATE", "UPDATE"]
resources: ["pods"]
matchImageReferences:
- glob: "registry.shop.example/*"
attestors:
- name: ci
cosign:
keyless:
identities:
- issuer: https://token.actions.githubusercontent.com
subject: >-
https://github.com/shop/web/.github/workflows/ci.yml@refs/heads/main
ctlog:
url: https://rekor.sigstore.dev
validationConfigurations:
required: true
mutateDigest: true
verifyDigest: true
validations:
- expression: >-
images.containers.map(image,
verifyImageSignatures(image, [attestors.ci])).all(e, e > 0)
message: image must be signed by the shop release workflowrequired rejects matching images that were not verified, mutateDigest rewrites a tag to the digest that was verified, and verifyDigest insists on a digest in the end. Keep the ValidatingAdmissionPolicy as well: it is cheap, has no external dependency and covers images that the webhook does not match. Webhooks can fail or time out, so decide their failurePolicy as carefully as the rule itself.
08. Common mistakes
09. Check your understanding
10. Apply it
On your kind cluster for the skill project, apply this policy with your own registry and a [Warn, Audit] binding for the application namespace, collect the failures for a day, fix them, and switch to [Deny]. Then install Kyverno or the Sigstore policy-controller, sign the image from lesson 02 with cosign sign in your pipeline, and enforce a policy that rejects unsigned images. Keep the evidence: one rejected unsigned image, one admitted signed image, and the audit events of both.
11. Review prompt
Without looking back:
- Where in the life of an API request does admission run, and why does that make it a good place for image rules?
- Why does the policy match
pods/ephemeralcontainersand also Deployments, when matching pods would already stop a bad image from running? - What does
failurePolicydecide, and what doesvalidationActionsdecide? - Why is an allow-listed registry with digests not enough, and what does a signature check against a CI identity add?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.