Created on 2026-12-04
Kubernetes Hardening L5: Admission Control in 2026 with CEL Policies and Kyverno
TL;DR: Stop writing external HTTP webhooks for basic pod validation and mutation. In 2026, Kubernetes admission control belongs inside kube-apiserver first: use Pod Security Admission (PSA) (enforce=restricted) as your zero-config floor, enforce synchronous guardrails and defaults in-process using ValidatingAdmissionPolicy (GA in 1.30) and MutatingAdmissionPolicy (GA in 1.36) written in Common Expression Language (CEL), and reserve Kyverno 1.16+ (CNCF Graduated) for capabilities that genuinely require external calls or background controllers - specifically ImageValidatingPolicy (cosign/SLSA verification) and GeneratingPolicy (stamping out default-deny NetworkPolicies per namespace). For every webhook that remains, lock its ingress port exclusively to kube-apiserver via NetworkPolicy so you never repeat the IngressNightmare (CVE-2025-1974) RCE vector.
Why External Webhooks Are No Longer the Default
Between 2019 and 2023, hardening a Kubernetes cluster meant installing two or three admission webhook controllers and routing every Pod, Deployment, Service, and Ingress creation over the cluster network as a serialized AdmissionReview JSON payload.
In production, webhook-heavy architectures failed in three predictable ways:
- Cold-boot cluster deadlocks. If a webhook configured with
failurePolicy: Failmatchedkube-systempods or Node leases and the cluster lost power,kube-apiserverblocked CNI DaemonSet and CoreDNS scheduling because the webhook pods were not running yet - and the webhook pods could not start because the CNI was blocked. - Control-plane tail latency. Each external webhook hop adds roughly 5 to 50ms+ of network, TLS, and JSON serialization overhead to matching API requests; chaining multiple mutating and validating webhooks compounds tail latency and throttles deployment controllers during large node drains.
- Webhooks are network attack surface. An admission webhook is an HTTPS server running inside your cluster, often holding broad RBAC permissions. In March 2025, IngressNightmare (CVE-2025-1974) demonstrated that an unauthenticated admission webhook endpoint exposed on the pod network (
ingress-nginx) allowed any compromised container in the cluster to send a craftedAdmissionReviewrequest, achieve remote code execution inside the controller pod, and dump cluster-wideSecrets.
The 2026 Layered Admission Architecture
Modern Kubernetes moves the majority of synchronous admission logic directly into the kube-apiserver binary using compiled Common Expression Language (CEL) abstract syntax trees (ASTs). External webhooks are now used surgically for supply-chain cryptography and cross-resource automation.

| Layer | Engine | Execution Model | Primary Responsibility |
|---|---|---|---|
| Layer 1: Pod Security Floor | Pod Security Admission (PSA) (Built-in) | In-process (kube-apiserver) |
Enforces the upstream baseline and restricted Pod Security Standards (blocks privileged containers, root UIDs, host namespaces, and unsafe capabilities). |
| Layer 2: Synchronous Guardrails & Defaults | MutatingAdmissionPolicy (GA 1.36) & ValidatingAdmissionPolicy (GA 1.30) | In-process CEL (kube-apiserver) |
Sub-millisecond mutation (defaulting automountServiceAccountToken: false on ServiceAccount creation, and seccompProfile: RuntimeDefault / hostUsers: false on non-host-namespace Pods) and validation (blocking :latest, unapproved registries, hostPath, auto-mounted kube-api-access-* tokens, or reserved label spoofing). |
| Layer 3: Supply Chain & Lifecycle Automation | Kyverno 1.16+ or OPA Gatekeeper (CNCF Graduated under OPA) |
Hardened Webhook + Background Controller | Verifying Sigstore / cosign signatures and in-toto (CNCF Graduated) SLSA provenance (ImageValidatingPolicy), generating per-namespace default-deny NetworkPolicies (GeneratingPolicy), and producing PolicyReport CRDs. |
Layer 1: Pod Security Admission (PSA)
Pod Security Admission is compiled directly into kube-apiserver and evaluates pods against the three upstream Pod Security Standards (privileged, baseline, restricted) across three modes (enforce, audit, warn).
Every application namespace should enforce the restricted profile, which requires runAsNonRoot: true, allowPrivilegeEscalation: false, dropping ALL Linux capabilities (allowing only NET_BIND_SERVICE if explicitly needed), a RuntimeDefault or Localhost seccomp profile, and safe volume types:
apiVersion: v1
kind: Namespace
metadata:
name: payments
labels:
pod-security.kubernetes.io/enforce: restricted
pod-security.kubernetes.io/enforce-version: v1.36
pod-security.kubernetes.io/audit: restricted
pod-security.kubernetes.io/audit-version: v1.36
pod-security.kubernetes.io/warn: restricted
pod-security.kubernetes.io/warn-version: v1.36
Cluster-Wide PSA Defaults on Bare Metal
Relying solely on namespace labels has a gap: if an engineer or Helm chart creates a new namespace and forgets the pod-security.kubernetes.io/enforce label, PSA defaults to privileged (unrestricted).
On self-hosted bare metal, close this gap at the API server level by passing --admission-control-config-file=/etc/kubernetes/admission-config.yaml to kube-apiserver. This sets restricted as the cluster-wide floor for every namespace except explicitly exempted system namespaces:
# /etc/kubernetes/admission-config.yaml
apiVersion: apiserver.config.k8s.io/v1
kind: AdmissionConfiguration
plugins:
- name: PodSecurity
configuration:
apiVersion: pod-security.admission.config.k8s.io/v1
kind: PodSecurityConfiguration
# Pin PSA version to the target cluster minor release (v1.36) in production
# so control-plane upgrades never introduce surprise admission rejections unannounced
defaults:
enforce: "restricted"
enforce-version: "v1.36"
audit: "restricted"
audit-version: "v1.36"
warn: "restricted"
warn-version: "v1.36"
exemptions:
usernames: []
runtimeClasses: []
namespaces:
- kube-system
- cilium
- spire-system
- kyverno
- cert-manager
On managed clusters (EKS, GKE Standard, AKS) where you cannot edit --admission-control-config-file on the managed API server, use an in-process MutatingAdmissionPolicy matching Namespace creation to inject the pod-security.kubernetes.io/enforce: restricted labels automatically whenever a non-system namespace is created.
Layer 2: In-Process CEL (MutatingAdmissionPolicy and ValidatingAdmissionPolicy)
With ValidatingAdmissionPolicy (GA since Kubernetes 1.30) and MutatingAdmissionPolicy (promoted to GA in Kubernetes 1.36), kube-apiserver compiles CEL expressions and executes them in memory with strict CPU/memory cost budgets.
Auto-Hardening Workloads with MutatingAdmissionPolicy (GA 1.36)
One subtle admission-ordering trap catches teams migrating from webhooks to MutatingAdmissionPolicy: the built-in ServiceAccount admission plugin runs before MutatingAdmissionPolicy on Pod CREATE. If you mutate Pod.spec.automountServiceAccountToken: false inside a Pod-targeted MAP, the ServiceAccount plugin has already mounted the kube-api-access-* projected volume onto the Pod spec, so flipping the boolean afterward does not strip the token!
To disable default token mounts cleanly with in-process CEL, split your mutations across two targeted MutatingAdmissionPolicy resources (and enforce a ValidatingAdmissionPolicy backstop below):
- Target
ServiceAccountCREATE(and optionallyDeployment/StatefulSet/Jobpod templates) to defaultautomountServiceAccountToken: falsebefore any Pod hits theServiceAccountplugin. - Target
PodCREATEto defaultseccompProfile: RuntimeDefaultandhostUsers: false- always guardinghostUsers: falseagainsthostNetwork,hostPID, andhostIPC(because Kubernetes rejects any pod combining host namespaces with a pod user namespace):
apiVersion: admissionregistration.k8s.io/v1
kind: MutatingAdmissionPolicy
metadata:
name: default-sa-no-automount
spec:
matchConstraints:
resourceRules:
- apiGroups: [""]
apiVersions: ["v1"]
operations: ["CREATE"]
resources: ["serviceaccounts"]
matchConditions:
- name: exclude-system-namespaces
expression: '!(object.metadata.namespace in ["kube-system", "cilium", "spire-system", "kyverno"])'
failurePolicy: Fail
reinvocationPolicy: Never
mutations:
# Default ServiceAccount.automountServiceAccountToken to false unless the enclosing Namespace carries a platform-admin opt-in label
- patchType: ApplyConfiguration
applyConfiguration:
expression: >
!(namespaceObject != null &&
has(namespaceObject.metadata.labels) &&
"security.bard.sh/allow-automount-sa-token" in namespaceObject.metadata.labels &&
namespaceObject.metadata.labels["security.bard.sh/allow-automount-sa-token"] == "true") &&
!has(object.automountServiceAccountToken)
? Object{
automountServiceAccountToken: false
}
: Object{}
---
apiVersion: admissionregistration.k8s.io/v1
kind: MutatingAdmissionPolicyBinding
metadata:
name: default-sa-no-automount-binding
spec:
policyName: default-sa-no-automount
---
apiVersion: admissionregistration.k8s.io/v1
kind: MutatingAdmissionPolicy
metadata:
name: inject-pod-security-defaults
spec:
matchConstraints:
resourceRules:
- apiGroups: [""]
apiVersions: ["v1"]
operations: ["CREATE"]
resources: ["pods"]
matchConditions:
- name: exclude-system-namespaces
expression: '!(object.metadata.namespace in ["kube-system", "cilium", "spire-system", "kyverno"])'
failurePolicy: Fail
reinvocationPolicy: Never
mutations:
# 1. Default seccompProfile to RuntimeDefault at the Pod level if unset
- patchType: ApplyConfiguration
applyConfiguration:
expression: >
!has(object.spec.securityContext) || !has(object.spec.securityContext.seccompProfile)
? Object{
spec: Object.spec{
securityContext: Object.spec.securityContext{
seccompProfile: Object.spec.securityContext.seccompProfile{
type: "RuntimeDefault"
}
}
}
}
: Object{}
# 2. Enable Linux user namespaces (hostUsers: false, GA in 1.36) only when no host namespaces are requested
- patchType: ApplyConfiguration
applyConfiguration:
expression: >
!has(object.spec.hostUsers) &&
(!has(object.spec.hostNetwork) || !object.spec.hostNetwork) &&
(!has(object.spec.hostPID) || !object.spec.hostPID) &&
(!has(object.spec.hostIPC) || !object.spec.hostIPC) &&
!(namespaceObject != null &&
has(namespaceObject.metadata.labels) &&
"security.bard.sh/allow-host-users" in namespaceObject.metadata.labels &&
namespaceObject.metadata.labels["security.bard.sh/allow-host-users"] == "true")
? Object{
spec: Object.spec{
hostUsers: false
}
}
: Object{}
---
apiVersion: admissionregistration.k8s.io/v1
kind: MutatingAdmissionPolicyBinding
metadata:
name: inject-pod-security-defaults-binding
spec:
policyName: inject-pod-security-defaults
Enforcing Guardrails with ValidatingAdmissionPolicy (GA 1.30)
Next, pair those mutations with an in-process ValidatingAdmissionPolicy that blocks supply-chain, token-mount, and isolation anti-patterns across every container (containers, initContainers, and ephemeralContainers). Notice that resourceRules.resources explicitly includes both "pods" and "pods/ephemeralcontainers" so kubectl debug (UPDATE on the ephemeralcontainers subresource) cannot slip an unpinned or untrusted debug image past admission:
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicy
metadata:
name: workload-supply-chain-and-isolation-guardrails
spec:
failurePolicy: Fail
matchConstraints:
resourceRules:
- apiGroups: [""]
apiVersions: ["v1"]
operations: ["CREATE", "UPDATE"]
resources: ["pods", "pods/ephemeralcontainers"]
matchConditions:
- name: skip-system-control-plane
expression: '!(object.metadata.namespace in ["kube-system", "cilium", "spire-system", "kyverno"])'
variables:
- name: allContainers
expression: 'object.spec.containers + (has(object.spec.initContainers) ? object.spec.initContainers : []) + (has(object.spec.ephemeralContainers) ? object.spec.ephemeralContainers : [])'
- name: approvedRegistries
expression: '["ghcr.io/bard-sh/", "registry.bard.sh/"]'
validations:
# 1. Block mutable :latest tags and require immutable @sha256: digests
- expression: 'variables.allContainers.all(c, c.image.contains("@sha256:") && !c.image.endsWith(":latest"))'
message: 'Every container image must be pinned to an immutable @sha256: digest and must not use :latest.'
reason: Invalid
# 2. Allow pulls only from approved internal/corporate registries
- expression: 'variables.allContainers.all(c, variables.approvedRegistries.exists(r, c.image.startsWith(r)))'
message: 'Container images must originate from ghcr.io/bard-sh/ or registry.bard.sh/.'
reason: Forbidden
# 3. Forbid hostPath volumes completely in tenant namespaces
- expression: '!has(object.spec.volumes) || object.spec.volumes.all(v, !has(v.hostPath))'
message: 'hostPath volumes are forbidden. Use CSI ephemeral volumes or PersistentVolumeClaims.'
reason: Forbidden
# 4. Prevent tenants from spoofing reserved Cilium or platform security labels
- expression: '!has(object.metadata.labels) || object.metadata.labels.all(k, !k.startsWith("security.bard.sh/admin-"))'
message: 'Tenants cannot set reserved security.bard.sh/admin-* labels.'
reason: Forbidden
# 5. Block auto-mounted default kube-api-access-* tokens unless opted in on the cluster-scoped Namespace
- expression: >
(namespaceObject != null &&
has(namespaceObject.metadata.labels) &&
"security.bard.sh/allow-automount-sa-token" in namespaceObject.metadata.labels &&
namespaceObject.metadata.labels["security.bard.sh/allow-automount-sa-token"] == "true") ||
!has(object.spec.volumes) ||
object.spec.volumes.all(v, !v.name.startsWith("kube-api-access-"))
message: 'Default kube-api-access-* ServiceAccount token volumes are forbidden unless the Namespace carries platform-admin label security.bard.sh/allow-automount-sa-token="true".'
reason: Forbidden
---
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicyBinding
metadata:
name: workload-guardrails-enforce
spec:
policyName: workload-supply-chain-and-isolation-guardrails
validationActions:
- Deny
- Audit
Important: Never gate security exceptions on tenant-editable Pod or ServiceAccount annotations (a developer could simply add that annotation to their own
DeploymentorPodto bypass both the MAP and VAP). Anchor opt-in flags on cluster-scopednamespaceObject.metadata.labels- which tenant namespace roles cannot edit - or use dedicated platform-adminValidatingAdmissionPolicyBinding/ KyvernoPolicyExceptionresources for single-workload exceptions.
- Bonus Layer 2 pattern - tenant secret path boundaries for OpenBao / Vault: If you sync secrets via External Secrets Operator (
ESO) from OpenBao (OpenSSF Sandbox) or HashiCorp Vault using a sharedClusterSecretStore, attach an in-processValidatingAdmissionPolicyonexternal-secrets.io/v1ExternalSecretobjects verifying that everyspec.data[].remoteRef.key(andspec.dataFrom[].extract.key/find.path) starts withobject.metadata.namespace + "/"so one team cannot request another tenant's secret path.
Layer 3: Kyverno 1.16+ and CEL Policy Types
In-process ValidatingAdmissionPolicy cannot make outbound network calls (by design, to keep kube-apiserver fast and deterministic) and cannot create new Kubernetes resources in response to events. That is where Kyverno enters the stack.
Starting in Kyverno 1.14 and graduating to the stable policies.kyverno.io/v1 API in Kyverno 1.16+, the project replaced the legacy monolithic ClusterPolicy (which relied on custom JMESPath syntax) with discrete, CEL-native policy CRDs:
ValidatingPolicy&NamespacedValidatingPolicy- CEL validation with support for external data lookups (contextAPI calls to Kubernetes resources or OCI registries) and automated translation into nativeValidatingAdmissionPolicy.ImageValidatingPolicy- Dedicated CEL policy for verifying Sigstore / cosign signatures, Notary Project / Notation (CNCF Incubating) signatures, SBOMs, and in-toto SLSA provenance attestations against OCI registries.MutatingPolicy- CEL-based mutations requiring external context.GeneratingPolicy- Event-driven controller that automatically creates and reconciles companion resources (such as default-denyNetworkPolicies,ResourceQuotas, orRoleBindings) whenever a trigger resource like aNamespaceis created.DeletingPolicy- Automated TTL-based garbage collection of ephemeral resources or expired exceptions.
Example 1: Verifying Keyless Cosign Signatures & SLSA Provenance with ImageValidatingPolicy
Using the stable policies.kyverno.io/v1 schema, verify signatures and SLSA v1 in-toto provenance across containers, initContainers, and ephemeralContainers. Note that ctlog sits alongside keyless under cosign, in-toto attestations declare intoto.type, and CEL identifiers use camelCase (hyphens parse as subtraction in CEL):
apiVersion: policies.kyverno.io/v1
kind: ImageValidatingPolicy
metadata:
name: verify-bard-signed-images
spec:
validationActions: [Deny]
failurePolicy: Fail
matchConstraints:
resourceRules:
- apiGroups: [""]
apiVersions: ["v1"]
operations: ["CREATE", "UPDATE"]
resources: ["pods", "pods/ephemeralcontainers"]
matchConditions:
- name: production-namespaces-only
expression: 'object.metadata.namespace in ["payments", "checkout", "identity"]'
images:
- name: allImages
expression: >
object.spec.containers.map(c, c.image) +
(has(object.spec.initContainers) ? object.spec.initContainers.map(c, c.image) : []) +
(has(object.spec.ephemeralContainers) ? object.spec.ephemeralContainers.map(c, c.image) : [])
attestors:
- name: githubActionsKeyless
cosign:
keyless:
identities:
- issuer: "https://token.actions.githubusercontent.com"
subjectRegExp: "^https://github.com/bard-sh/.+/.github/workflows/release.yml@refs/tags/v.+$"
ctlog:
url: "https://rekor.sigstore.dev"
attestations:
- name: slsaProvenance
intoto:
type: "https://slsa.dev/provenance/v1"
validations:
- expression: >
images.allImages.all(img,
verifyImageSignatures(img, [attestors.githubActionsKeyless]) > 0 &&
verifyAttestationSignatures(img, attestations.slsaProvenance, [attestors.githubActionsKeyless]) > 0
)
message: "Container image failed keyless Sigstore cosign signature or SLSA v1 provenance verification."
Example 2: Auto-Generating Default-Deny NetworkPolicies with GeneratingPolicy
Whenever a team provisions a new namespace, it should start with zero network trust (default-deny ingress and egress, permitting only CoreDNS resolution) from millisecond one. In policies.kyverno.io/v1, GeneratingPolicy uses spec.evaluation.synchronize.enabled and pure CEL generator.Apply(...) calls:
apiVersion: policies.kyverno.io/v1
kind: GeneratingPolicy
metadata:
name: generate-namespace-default-deny
spec:
evaluation:
synchronize:
enabled: true
matchConstraints:
resourceRules:
- apiGroups: [""]
apiVersions: ["v1"]
operations: ["CREATE", "UPDATE"]
resources: ["namespaces"]
matchConditions:
- name: exclude-system-namespaces
expression: '!(object.metadata.name in ["kube-system", "cilium", "spire-system", "kyverno"])'
variables:
- name: targetNs
expression: 'object.metadata.name'
- name: defaultDenyNetPol
expression: >-
[
{
"apiVersion": dyn("networking.k8s.io/v1"),
"kind": dyn("NetworkPolicy"),
"metadata": dyn({
"name": "default-deny-all"
}),
"spec": dyn({
"podSelector": dyn({}),
"policyTypes": dyn(["Ingress", "Egress"]),
"egress": dyn([
{
"to": [
{
"namespaceSelector": {
"matchLabels": {
"kubernetes.io/metadata.name": "kube-system"
}
},
"podSelector": {
"matchLabels": {
"k8s-app": "kube-dns"
}
}
}
],
"ports": [
{"protocol": "UDP", "port": 53},
{"protocol": "TCP", "port": 53}
]
}
])
})
}
]
generate:
- expression: 'generator.Apply(variables.targetNs, variables.defaultDenyNetPol)'
Because spec.evaluation.synchronize.enabled: true is set, if a developer with namespace RBAC deletes or modifies default-deny-all, Kyverno's background controller immediately restores it.
Kyverno vs OPA Gatekeeper vs Kubewarden
| Criteria | Native VAP / MAP (Upstream K8s) | Kyverno 1.16+ | OPA Gatekeeper | Kubewarden (CNCF Sandbox) |
|---|---|---|---|---|
| Policy Language | CEL (in-process) | CEL + YAML | Rego + CEL (via VAP generation) | Rust / Go / Rego compiled to WebAssembly (Wasm) |
| Execution Location | Inside kube-apiserver memory |
Webhook + background controller (can also generate native VAPs) | Webhook + audit controller (can also generate native VAPs) | Webhook executing isolated Wasm modules |
Resource Generation (GeneratingPolicy) |
No | Yes (First-class) | No | No |
| Native OCI Image Signature Verification | No | Yes (ImageValidatingPolicy) |
Via external Ratify (CNCF Sandbox) provider |
Yes (Wasm host capabilities) |
| Best Fit | Mandatory first choice for synchronous pod and object checks | Kubernetes-native platform teams needing image verification, generation, and PolicyReports |
Organizations standardized on Rego across Terraform, Envoy, and API gateways | Teams wanting polyglot policies (Rust/Go) compiled to signed Wasm artifacts |
Managed vs Self-Hosted Bare Metal Comparison
| Admission Dimension | AWS EKS | GCP GKE | Azure AKS | Self-Hosted Bare Metal |
|---|---|---|---|---|
| Built-In Provider Floor | Standard mode: none by default. EKS Auto Mode hardens node/compute defaults. | GKE Autopilot pre-enforces strong admission blocks (no privileged pods, hostPath, or hostNetwork). |
AKS Automatic pre-configures admission guardrails. | You: Configure AdmissionConfiguration (PodSecurity: restricted) on kube-apiserver. |
| In-Process VAP / MAP | Supported on K8s 1.30+ (VAP) / 1.36+ (MAP) | Supported on K8s 1.30+ (VAP) / 1.36+ (MAP) | Supported on K8s 1.30+ (VAP) / 1.36+ (MAP) | Full control via kube-apiserver flags and API resources |
| Managed Policy Add-On | Self-managed Kyverno / Gatekeeper (or EKS add-on marketplace) | Policy Controller (managed Gatekeeper) | Azure Policy for AKS (managed Gatekeeper add-on) | Self-managed Kyverno via GitOps |
| Image Signature Enforcement | Self-managed Kyverno ImageValidatingPolicy or Notation |
GKE Binary Authorization (managed attestation enforcement) | Ratify + Azure Policy or Kyverno | Kyverno ImageValidatingPolicy + Harbor (CNCF Graduated) |
Hardening the Admission Layer Itself: Lessons from IngressNightmare
Every external admission webhook you keep in the cluster is a privileged network service. If you deploy Kyverno, Gatekeeper, or cert-manager webhooks without hardening their network and failure boundaries, your security tools become either an availability single point of failure or an exploit vector.

Tip: Upstream
ingress-nginxwas retired around March 2026 following the IngressNightmare (CVE-2025-1974) webhook vulnerability class. If you still runingress-nginx, migrating to a Gateway API implementation - such as Cilium (CNCF Graduated), Envoy Gateway (CNCF Graduatedunder Envoy), or Istio (CNCF Graduated) - eliminates the retired ingress admission webhook entirely.
Apply four mandatory controls to every remaining webhook server in your cluster:
1. Lock Webhook Ingress Strictly to kube-apiserver
No application pod in any tenant namespace ever has a legitimate reason to open a TCP connection to the Kyverno or Gatekeeper webhook port (9443 / 8443). Only kube-apiserver needs to reach it. Enforce this invariant with a Cilium CiliumNetworkPolicy using the reserved kube-apiserver entity:
apiVersion: cilium.io/v2
kind: CiliumNetworkPolicy
metadata:
name: lock-kyverno-webhook-to-apiserver
namespace: kyverno
spec:
endpointSelector:
matchLabels:
app.kubernetes.io/component: admission-controller
ingress:
- fromEntities:
- kube-apiserver
toPorts:
- ports:
- port: "9443"
protocol: TCP
On self-hosted bare metal, you can layer mutual TLS client authentication on top of this network policy by configuring ValidatingAdmissionWebhook / MutatingAdmissionWebhook client credentials inside --admission-control-config-file on kube-apiserver. Managed control planes (EKS, GKE, AKS) do not expose --admission-control-config-file for custom webhook client certificates, making strict Cilium ingress filtering mandatory.
2. Combine failurePolicy: Fail with Critical Namespace Exclusions
A security policy configured with failurePolicy: Ignore is only an advisory check: an attacker who can trigger a high-rate query spike or crash the webhook pod can bypass admission enforcement while the webhook restarts.
Always set failurePolicy: Fail on security-critical policies, and explicitly exclude kube-system, cilium, spire-system, and kyverno via namespaceSelector (with immutable kubernetes.io/metadata.name labels) so node networking, DNS, and the webhook pods themselves can always boot after a cluster-wide power loss.
3. Run Dedicated HA Admission Replicas with system-cluster-critical
Never run an admission webhook with replicas: 1. Run at least 3 replicas of kyverno-admission-controller spread across failure domains via topologySpreadConstraints, assign priorityClassName: system-cluster-critical so the Kubelet never evicts the webhook before application pods under memory pressure, and define a PodDisruptionBudget with minAvailable: 2. In the Kyverno Helm chart, container arguments (extraArgs as a YAML map) and resources belong under admissionController.container:
# kyverno-values-prod-ha.yaml (Production Helm Configuration)
admissionController:
replicas: 3
priorityClassName: system-cluster-critical
podDisruptionBudget:
enabled: true
minAvailable: 2
container:
# Cache verified @sha256 image signatures in memory for 60m to prevent registry rate-limiting during node drains
extraArgs:
imageVerifyCacheTTLDuration: "60m"
maxAPICallResponseLength: "2000000"
resources:
requests:
cpu: 500m
memory: 512Mi
limits:
cpu: "2"
memory: 1Gi
topologySpreadConstraints:
- maxSkew: 1
topologyKey: topology.kubernetes.io/zone
whenUnsatisfiable: DoNotSchedule
labelSelector:
matchLabels:
app.kubernetes.io/component: admission-controller
config:
# Exclude critical bootstrap namespaces so CNI, DNS, and SPIRE can always start after a cold boot
webhooks:
namespaceSelector:
matchExpressions:
- key: kubernetes.io/metadata.name
operator: NotIn
values:
- kube-system
- cilium
- spire-system
- kyverno
4. Bound timeoutSeconds Tightly
The Kubernetes default webhook timeout is 10 seconds. If an external OCI registry slows down during an ImageValidatingPolicy check, a 10-second block can saturate kube-apiserver inflight request queues. Set timeoutSeconds: 5 on standard webhooks, and use a local pull-through registry mirror (Harbor) on bare metal so signature and attestation checks resolve over the local datacenter LAN in milliseconds.
Safe Rollout (Audit + Warn -> Deny) and CI Testing
Never deploy a new admission rule directly in Deny mode against a live production cluster. Follow a three-stage rollout pipeline:
Stage 1: Shift-Left Verification in Git CI
Test every ValidatingAdmissionPolicy and Kyverno policy against both compliant and non-compliant fixture manifests in GitHub Actions or GitLab CI before merging:
# Execute Kyverno CLI unit test suite against VAP, MAP, and Kyverno 1.16 CEL policies
kyverno test ./policies/tests/ --detailed-results
# Or if using OPA Gatekeeper / VAP with gator:
gator verify ./policies/gatekeeper-suites/
Stage 2: Canary in Audit and Warn Mode
Deploy the ValidatingAdmissionPolicyBinding with validationActions: [Audit, Warn] for 7 days. Developers see immediate Warning: banners on kubectl apply and in Argo CD (CNCF Graduated) / Flux (CNCF Graduated) sync logs, while your platform team monitors kube-apiserver metrics and audit annotations for non-compliant requests and CEL evaluation errors without breaking production rollouts:
# Track policy check rates, enforcement actions, and CEL runtime errors across bindings
sum by (policy, policy_binding, enforcement_action, error_type) (
rate(apiserver_validating_admission_policy_check_total[5m])
)
Stage 3: Flip to Deny
Once audit annotations and apiserver_validating_admission_policy_check_total show zero violations and zero error_type failures across all namespaces for 7 days, update the binding to validationActions: [Deny, Audit].
Operational Pitfalls to Watch For
- Matching only
Deploymentinstead ofPod: A common mistake when writing custom policies is matchingapps/v1Deploymentswhile forgettingPods,Jobs,CronJobs,StatefulSets, andDaemonSets. An attacker with RBAC permissions to create a barePodorJobcompletely bypasses a policy that only inspectsDeployments. Always enforce security invariants onv1/Pod(andpods/ephemeralcontainers) in addition to any controller-level defaults. - Forgetting
pods/ephemeralcontainersinresourceRules: Even if your CEL expression concatenatesobject.spec.ephemeralContainers,kube-apiserverwill never invoke your policy onkubectl debugunlessresourceRules.resourcesexplicitly includes"pods/ephemeralcontainers". - CEL cost budget exhaustion on huge objects:
kube-apiserverenforces a per-validation runtime cost budget on CEL expressions to prevent denial-of-service from nestedO(N^2)list comprehensions. Avoid deeply nested.all()loops over large ConfigMap or annotation maps; test complex CEL expressions against realistic 50-container Pod specs before rollout.
Day-1 Verification & Operational Runbook
Run these checks to verify PSA coverage and webhook safety across your cluster:
# 1. List namespaces missing pod-security.kubernetes.io/enforce
kubectl get ns -o json | jq -r '
.items[]
| select(.metadata.labels["pod-security.kubernetes.io/enforce"] == null)
| .metadata.name
'
# 2. Audit admission webhooks configured with fail-open failurePolicy: Ignore
kubectl get validatingwebhookconfigurations,mutatingwebhookconfigurations -o json | jq -r '
.items[]
| .metadata.name as $cfg
| .webhooks[]
| select(.failurePolicy == "Ignore")
| "\($cfg)/\(.name)"
'
- Respect admission ordering for SA token mounts: Remember that
ServiceAccountadmission executes beforeMutatingAdmissionPolicyon PodCREATE. DefaultautomountServiceAccountToken: falseonServiceAccountcreation (or controller pod templates) and enforce a VAP backstop rejectingkube-api-access-*volumes. - Require a clean 7-day soak before
Deny: Monitorapiserver_validating_admission_policy_check_totalbypolicy,policy_binding,enforcement_action, anderror_type(alongside Kubernetes audit annotations) until violations and CEL runtime errors stay at zero for a full release cycle. - Verify webhook network isolation after upgrades: Confirm
lock-kyverno-webhook-to-apiserver(or equivalentCiliumNetworkPolicy) still matches your admission controller pod labels and blocks direct connections to port9443from tenant namespaces.
Series Navigation
- Series Overview: Kubernetes Hardening Layer by Layer: Managed Cloud vs Bare Metal (Series Overview)
- Previous: Kubernetes Hardening L4b: Pod and Workload Identity on Cloud vs Bare Metal with SPIFFE/SPIRE
- Next: Kubernetes Hardening L6: Container Runtime Isolation, User Namespaces, and MicroVM Sandboxes (coming in Batch 3)