Admission Control: Gatekeeper, Kyverno and Built-In Policies
Pod Security Admission enforces one fixed set of rules. Organisations need more: images only from the internal registry and signed, no latest tags, resource limits on everything, required labels for cost and ownership, no Services of type LoadBalancer in some namespaces, no hostPath even for the platform team without an exception. Admission control is where such rules run: every create or update request passes through admission plugins after authentication and authorization and before the object is stored. That makes admission the last place to stop a bad object, and it makes the admission layer itself a target: an attacker who can switch it off, or find a field it doesn't look at, gets the bad object in anyway. Admission Control & Policies explains the mechanics, In the Cluster: Kyverno & Gatekeeper the policy engines, and Admission Control: Kyverno & policy-controller image signatures; this lesson is the reviewer's view.
The options
| Mechanism | Rules written in | Notes |
|---|---|---|
| Pod Security Admission | fixed levels | built in, per namespace (Pod Security) |
| ValidatingAdmissionPolicy | CEL expressions, in the API server | built in (GA since Kubernetes 1.30), no webhook to run or lose; mutating counterpart newer |
| OPA Gatekeeper | Rego, in ConstraintTemplates + Constraints | webhook; audit mode reports existing violations |
| Kyverno | YAML policies (validate, mutate, generate, verify images), CEL in newer versions | webhook; also a CLI to test policies offline |
| Custom webhooks | any language | most flexible, most to maintain |
How admission is bypassed, and why it matters
Reviewers should look for these weaknesses, because attackers do:
- Fail-open webhooks:
failurePolicy: Ignoremeans that if the webhook is down or slow, requests are admitted unchecked. An attacker who can disrupt the policy engine's pods (or simply waits for an upgrade window) gets a gap. - Exempted namespaces: webhooks commonly skip
kube-systemand the engine's own namespace. Anyone who may create pods there is outside the rules. - Fields the policy forgets: a rule that checks
spec.containersbut notinitContainersorephemeralContainers(added bykubectl debug), or that checks Pods but not the pod templates inside Deployments (then violations surface late), or the reverse. - RBAC on the policies themselves: whoever can edit
ValidatingWebhookConfiguration, Constraints or Kyverno policies can turn them off (RBAC Review).
An admission engine with a classic gap
The program runs three policies over incoming Pod requests in two versions: as first written (checking containers only, fail-open, kube-system exempt) and as fixed (all container lists, fail-closed, no broad exemption). Requests and names are from the lab cluster.
def containers(pod, all_lists):
keys = ["containers", "initContainers", "ephemeralContainers"] if all_lists else ["containers"]
return [c for k in keys for c in pod["spec"].get(k, [])]
def p_registry(pod, all_lists):
return [f"image {c['image']} not from registry.lab.test" for c in containers(pod, all_lists)
if not c["image"].startswith("registry.lab.test/")]
def p_digest(pod, all_lists):
return [f"image {c['image']} not pinned by digest" for c in containers(pod, all_lists) if "@sha256:" not in c["image"]]
def p_privileged(pod, all_lists):
return [f"{c['name']} is privileged" for c in containers(pod, all_lists) if c.get("securityContext", {}).get("privileged")]
def admit(req, cfg):
if req["ns"] in cfg["exempt_namespaces"]:
return "ADMITTED (namespace exempt)"
if not cfg["webhook_up"]:
return "ADMITTED (webhook down, failurePolicy Ignore)" if cfg["fail_open"] else "REJECTED (webhook unavailable, failurePolicy Fail)"
errors = [e for p in (p_registry, p_digest, p_privileged) for e in p(req["pod"], cfg["all_lists"])]
return "REJECTED: " + "; ".join(errors) if errors else "ADMITTED"
GOOD = "registry.lab.test/shop/web@sha256:4f2c9a7e1b3d5f6a8c0e2d4b6a8f0c1e3d5b7a9c0e2f4d6b8a0c2e4f6a8b0c1d"
requests = [
("web pod", {"ns": "shop", "pod": {"spec": {"containers": [{"name": "web", "image": GOOD}]}}}),
("public image", {"ns": "shop", "pod": {"spec": {"containers": [{"name": "x", "image": "docker.io/library/nginx:latest"}]}}}),
("privileged initContainer", {"ns": "shop", "pod": {"spec": {
"initContainers": [{"name": "setup", "image": "docker.io/someone/tools:1", "securityContext": {"privileged": True}}],
"containers": [{"name": "web", "image": GOOD}]}}}),
("pod in kube-system", {"ns": "kube-system", "pod": {"spec": {"containers": [
{"name": "x", "image": "docker.io/someone/tools:1", "securityContext": {"privileged": True}}]}}}),
]
configs = {
"as first written": {"all_lists": False, "exempt_namespaces": {"kube-system"}, "fail_open": True, "webhook_up": True},
"fixed": {"all_lists": True, "exempt_namespaces": set(), "fail_open": False, "webhook_up": True},
}
for cname, cfg in configs.items():
print(f"== {cname}")
for label, req in requests:
print(f" {label:25} {admit(req, cfg)}")
print("== as first written, while the policy engine is being upgraded")
cfg = dict(configs["as first written"], webhook_up=False)
print(f" {'public image':25} {admit(requests[1][1], cfg)}")== as first written
web pod ADMITTED
public image REJECTED: image docker.io/library/nginx:latest not from registry.lab.test; image docker.io/library/nginx:latest not pinned by digest
privileged initContainer ADMITTED
pod in kube-system ADMITTED (namespace exempt)
== fixed
web pod ADMITTED
public image REJECTED: image docker.io/library/nginx:latest not from registry.lab.test; image docker.io/library/nginx:latest not pinned by digest
privileged initContainer REJECTED: image docker.io/someone/tools:1 not from registry.lab.test; image docker.io/someone/tools:1 not pinned by digest; setup is privileged
pod in kube-system REJECTED: image docker.io/someone/tools:1 not from registry.lab.test; image docker.io/someone/tools:1 not pinned by digest; x is privileged
== as first written, while the policy engine is being upgraded
public image ADMITTED (webhook down, failurePolicy Ignore)
As first written, the policies catch the obvious case and miss two: a privileged pull from a public registry hidden in an init container, and anything in kube-system. While the webhook is down, the fail-open configuration admits everything. The fixed version checks every container list, exempts nothing broadly (system components get narrow, named exceptions instead) and fails closed, rejecting the privileged kube-system pod too. Failing closed has a cost: if the policy engine is down, nobody can create pods, so it must run highly available, with its own namespace carefully exempted from itself only.
The same rule in Kyverno and in CEL
A Kyverno policy for the registry rule, written to cover all container lists with =() equality anchors (the field is checked only when it is present):
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata: {name: internal-registry-only}
spec:
background: true
rules:
- name: images-from-registry-lab-test
match: {any: [{resources: {kinds: [Pod]}}]}
validate:
failureAction: Enforce
message: "Images must come from registry.lab.test."
pattern:
spec:
=(initContainers): [{image: "registry.lab.test/*"}]
=(ephemeralContainers): [{image: "registry.lab.test/*"}]
containers: [{image: "registry.lab.test/*"}]And as a built-in ValidatingAdmissionPolicy with a CEL expression (bound to namespaces with a ValidatingAdmissionPolicyBinding, not shown):
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicy
metadata: {name: internal-registry-only}
spec:
failurePolicy: Fail
matchConstraints:
resourceRules: [{apiGroups: [""], apiVersions: [v1], operations: [CREATE, UPDATE], resources: [pods, pods/ephemeralcontainers]}]
validations:
- expression: >-
(object.spec.containers + object.spec.?initContainers.orValue([]) + object.spec.?ephemeralContainers.orValue([]))
.all(c, c.image.startsWith('registry.lab.test/'))
message: Images must come from registry.lab.test.Two details matter for the bypass list above. kubectl debug adds ephemeral containers through the pods/ephemeralcontainers subresource, so the built-in policy must match that subresource explicitly (Kyverno's webhook includes it by default for Pod rules). And Kyverno keeps moving: the per-rule failureAction replaced the deprecated spec.validationFailureAction, and Kyverno 1.18 marks ClusterPolicy itself deprecated in favour of CEL-based ValidatingPolicy. Both are written from the documented formats; test them with kyverno apply/kyverno test or a dry-run cluster before enforcing, as Secrets & Policy as Code shows with real runs.
How admission weaknesses are detected
- Configuration: list
ValidatingWebhookConfiguration/MutatingWebhookConfigurationobjects and checkfailurePolicy,namespaceSelector/objectSelectorexemptions,timeoutSeconds, and which resources and operations they match. - Policy tests: a test suite with known-bad objects for every bypass class above (init and ephemeral containers, pod templates, each exempt namespace), run in CI against the policies.
- Audit: Gatekeeper and Kyverno background scans report existing objects that violate policies (created before the policy, or during an outage); API server audit logs show changes to webhook configurations and policies.
How it is fixed
- Fail closed for security policies, run the engine with several replicas and a PodDisruptionBudget, and alert when it is unhealthy.
- Exempt by exact service account or workload, not whole namespaces; restrict who can create pods in exempt places.
- Write policies against all pod-spec container lists, and match both Pods and workload templates (Kyverno auto-generates rules for controllers).
- Protect the policies with RBAC and alert on every change to them.
- Prefer built-in ValidatingAdmissionPolicy for simple rules: no webhook to go down.
Pitfalls
- Testing only the happy path of a policy; bypasses live in the fields nobody thought of.
Auditmode left on forever "until we fix the violations".- Mutating policies that fix bad specs silently: convenient, but they hide what developers wrote, and validation should still run after mutation.
Practice
1. In the "as first written" config, set webhook_up to False and fail_open to False. What happens to the web pod, and what is the operational lesson?
REJECTED (webhook unavailable, failurePolicy Fail): even good pods can't be created. Fail-closed policies need a highly available engine, and an emergency procedure that is itself audited.
2. Which request would be admitted by the fixed config if you added "kube-system" back to the exemptions?
The privileged pod in kube-system with a public image. Narrow the exemption to the named system workloads (by service account or label) and restrict pod creation in kube-system with RBAC.
3. Why do policies need to look at ephemeralContainers?
kubectl debug adds them to running pods through the pods/ephemeralcontainers subresource; a policy that ignores them lets anyone with that permission attach an unchecked container (any image, any security context the other layers allow) to a production pod.
Test yourself
What does failurePolicy: Ignore mean for a security webhook?
- Violations are ignored
- If the webhook can't be reached, requests are admitted unchecked
- It only logs
- It blocks all requests
How did the privileged init container get past the first version of the policies?
- It used a digest
- The policies only checked spec.containers
- It was in kube-system
- PSA allowed it
What is an advantage of ValidatingAdmissionPolicy over webhooks?
- It supports Rego
- It runs inside the API server, so there is no webhook service to go down
- It mutates objects
- It needs no RBAC