Kubernetes admission, network, and image-policy lab
Runs an insecure and a hardened workload on a real local kind cluster and measures workload identity, RBAC, admission control, network reachability and runtime constraints before and after, with four policy engines compared on one case corpus.
Cloud Security 19 min read
Implementation
labs/kubernetes-security/hardened/20-workload.yaml
1# HARDENED workloads. Both satisfy the restricted Pod Security profile.
2#
3# app no API token, no API reachability (NetworkPolicy), talks to lab-data only.
4# api-reader explicitly projected, short-lived token; the only workload with API access.
5apiVersion: apps/v1
6kind: Deployment
7metadata:
8 name: app
9 namespace: lab-hardened
10 labels: {app: app}
11spec:
12 replicas: 1
13 selector:
14 matchLabels: {app: app}
15 template:
16 metadata:
17 labels: {app: app}
18 spec:
19 serviceAccountName: app
20 automountServiceAccountToken: false
21 securityContext:
22 runAsNonRoot: true
23 runAsUser: 65532
24 runAsGroup: 65532
25 seccompProfile:
26 type: RuntimeDefault
27 containers:
28 - name: app
29 image: dockerlab/posture:hardened
30 imagePullPolicy: IfNotPresent
31 securityContext:
32 runAsNonRoot: true
33 allowPrivilegeEscalation: false
34 readOnlyRootFilesystem: true
35 capabilities:
36 drop: ["ALL"]
37 resources:
38 requests: {cpu: 50m, memory: 32Mi}
39 limits: {cpu: 500m, memory: 128Mi}
40 volumeMounts:
41 - name: tmp
42 mountPath: /tmp
43 volumes:
44 - name: tmp
45 emptyDir:
46 medium: Memory
47 sizeLimit: 8Mi
48---
49apiVersion: apps/v1
50kind: Deployment
51metadata:
52 name: api-reader
53 namespace: lab-hardened
54 labels: {app: api-reader}
55spec:
56 replicas: 1
57 selector:
58 matchLabels: {app: api-reader}
59 template:
60 metadata:
61 labels:
62 app: api-reader
63 # Reviewed exception marker: required by the admission policy for any pod
64 # that projects a service-account token.
65 lab.example/api-access: approved
66 spec:
67 serviceAccountName: api-reader
68 automountServiceAccountToken: false
69 securityContext:
70 runAsNonRoot: true
71 runAsUser: 65532
72 runAsGroup: 65532
73 seccompProfile:
74 type: RuntimeDefault
75 containers:
76 - name: app
77 image: dockerlab/posture:hardened
78 imagePullPolicy: IfNotPresent
79 securityContext:
80 runAsNonRoot: true
81 allowPrivilegeEscalation: false
82 readOnlyRootFilesystem: true
83 capabilities:
84 drop: ["ALL"]
85 resources:
86 requests: {cpu: 50m, memory: 32Mi}
87 limits: {cpu: 500m, memory: 128Mi}
88 volumeMounts:
89 - name: tmp
90 mountPath: /tmp
91 # Same path the kubelet uses for an automounted token, so the
92 # workload and the probe need no special case.
93 - name: api-token
94 mountPath: /var/run/secrets/kubernetes.io/serviceaccount
95 readOnly: true
96 volumes:
97 - name: tmp
98 emptyDir:
99 medium: Memory
100 sizeLimit: 8Mi
101 - name: api-token
102 projected:
103 defaultMode: 0444
104 sources:
105 - serviceAccountToken:
106 path: token
107 expirationSeconds: 3600
108 - configMap:
109 name: kube-root-ca.crt
110 items:
111 - key: ca.crt
112 path: ca.crt
113 - downwardAPI:
114 items:
115 - path: namespace
116 fieldRef:
117 fieldPath: metadata.namespace
1# HARDENED admission, layer 2. Pod Security Admission (the namespace labels) covers
2# the Pod Security Standards; it does NOT require resource limits, forbid :latest,
3# require a read-only root filesystem, or restrict service-account token projection.
4# This ValidatingAdmissionPolicy (CEL, built into the API server, no webhook) adds
5# those controls. failurePolicy Fail: if the policy cannot be evaluated, deny.
6apiVersion: admissionregistration.k8s.io/v1
7kind: ValidatingAdmissionPolicy
8metadata:
9 name: lab-pod-extra-controls
10spec:
11 failurePolicy: Fail
12 matchConstraints:
13 resourceRules:
14 - apiGroups: [""]
15 apiVersions: ["v1"]
16 operations: ["CREATE", "UPDATE"]
17 resources: ["pods"]
18 variables:
19 - name: containers
20 expression: >-
21 object.spec.containers
22 + object.spec.?initContainers.orValue([])
23 + object.spec.?ephemeralContainers.orValue([])
24 validations:
25 - expression: >-
26 variables.containers.all(c,
27 has(c.resources) && has(c.resources.limits)
28 && has(c.resources.limits.cpu) && has(c.resources.limits.memory))
29 message: Every container must set CPU and memory limits.
30 reason: Invalid
31 - expression: >-
32 variables.containers.all(c,
33 c.image.contains('@sha256:')
34 || (c.image.matches('^[^@]*:[^:/@]+$') && !c.image.endsWith(':latest')))
35 message: Images must be pinned by digest or carry an explicit non-latest tag.
36 reason: Invalid
37 - expression: >-
38 variables.containers.all(c, c.?securityContext.?readOnlyRootFilesystem.orValue(false) == true)
39 message: Containers must use a read-only root filesystem.
40 reason: Invalid
41 - expression: >-
42 !has(object.spec.volumes) || object.spec.volumes.all(v,
43 !(has(v.projected) && v.projected.sources.exists(s, has(s.serviceAccountToken)))
44 || (object.metadata.?labels.orValue({})[?'lab.example/api-access'].orValue('') == 'approved'
45 && object.spec.?serviceAccountName.orValue('default') != 'default'))
46 message: >-
47 A service-account token (automounted or projected) requires the reviewed
48 label lab.example/api-access=approved and a non-default ServiceAccount.
49 reason: Forbidden
50---
51apiVersion: admissionregistration.k8s.io/v1
52kind: ValidatingAdmissionPolicyBinding
53metadata:
54 name: lab-pod-extra-controls
55spec:
56 policyName: lab-pod-extra-controls
57 # Deny rejects; Audit records the decision in the API server audit log.
58 validationActions: [Deny, Audit]
59 matchResources:
60 namespaceSelector:
61 matchLabels:
62 lab.example/admission: enforced
1# HARDENED network segmentation. NetworkPolicy is additive allow-listing: pods
2# selected by ANY policy are denied everything not explicitly allowed.
3#
4# 192.0.2.1/32 below (TEST-NET-1, a documentation range) is a placeholder that
5# scripts/run-cluster-lab.sh replaces with the real API server endpoint IP at apply
6# time, because Calico evaluates the post-DNAT destination.
7apiVersion: networking.k8s.io/v1
8kind: NetworkPolicy
9metadata:
10 name: default-deny-all
11 namespace: lab-hardened
12spec:
13 podSelector: {}
14 policyTypes: [Ingress, Egress]
15---
16apiVersion: networking.k8s.io/v1
17kind: NetworkPolicy
18metadata:
19 name: allow-dns-egress
20 namespace: lab-hardened
21spec:
22 podSelector: {}
23 policyTypes: [Egress]
24 egress:
25 - to:
26 - namespaceSelector:
27 matchLabels:
28 kubernetes.io/metadata.name: kube-system
29 podSelector:
30 matchLabels:
31 k8s-app: kube-dns
32 ports:
33 - {protocol: UDP, port: 53}
34 - {protocol: TCP, port: 53}
35---
36apiVersion: networking.k8s.io/v1
37kind: NetworkPolicy
38metadata:
39 name: app-egress-to-data-tier
40 namespace: lab-hardened
41spec:
42 podSelector:
43 matchLabels: {app: app}
44 policyTypes: [Egress]
45 egress:
46 - to:
47 - namespaceSelector:
48 matchLabels:
49 kubernetes.io/metadata.name: lab-data
50 podSelector:
51 matchLabels: {app: canary}
52 ports:
53 - {protocol: TCP, port: 9000}
54---
55apiVersion: networking.k8s.io/v1
56kind: NetworkPolicy
57metadata:
58 name: api-reader-egress-to-apiserver
59 namespace: lab-hardened
60spec:
61 podSelector:
62 matchLabels: {app: api-reader}
63 policyTypes: [Egress]
64 egress:
65 - to:
66 - ipBlock:
67 cidr: 192.0.2.1/32
68 ports:
69 - {protocol: TCP, port: 6443}
70---
71# Data tier: isolate ingress so only the hardened app can connect. Applying this
72# AFTER the baseline measurements shows the same baseline pod losing access.
73apiVersion: networking.k8s.io/v1
74kind: NetworkPolicy
75metadata:
76 name: default-deny-ingress
77 namespace: lab-data
78spec:
79 podSelector: {}
80 policyTypes: [Ingress]
81---
82apiVersion: networking.k8s.io/v1
83kind: NetworkPolicy
84metadata:
85 name: allow-ingress-from-hardened-app
86 namespace: lab-data
87spec:
88 podSelector:
89 matchLabels: {app: canary}
90 policyTypes: [Ingress]
91 ingress:
92 - from:
93 - namespaceSelector:
94 matchLabels:
95 kubernetes.io/metadata.name: lab-hardened
96 podSelector:
97 matchLabels: {app: app}
98 ports:
99 - {protocol: TCP, port: 9000}
1# INSECURE BASELINE workload: root, privileged, host PID, hostPath, no limits,
2# default-mounted API token, mutable-tag image, no probes.
3apiVersion: apps/v1
4kind: Deployment
5metadata:
6 name: app
7 namespace: lab-baseline
8 labels: {app: app}
9spec:
10 replicas: 1
11 selector:
12 matchLabels: {app: app}
13 template:
14 metadata:
15 labels: {app: app}
16 spec:
17 serviceAccountName: app-sa
18 hostPID: true
19 containers:
20 - name: app
21 image: dockerlab/posture:insecure
22 imagePullPolicy: IfNotPresent
23 securityContext:
24 privileged: true
25 runAsUser: 0
26 volumeMounts:
27 - name: host-canary
28 mountPath: /mnt/host-canary
29 volumes:
30 - name: host-canary
31 hostPath:
32 path: /var/lib/lab-host-canary
33 type: DirectoryOrCreate
1# Offline manifest policy for labs/kubernetes-security. Evaluated with `opa eval`
2# against {"objects": [...]} built from a directory of manifests; no cluster needed.
3#
4# Two entry points, because they answer different questions:
5# pod_violations - properties of a single pod spec (admission-style)
6# policy_violations - properties of a manifest SET: RBAC, namespaces, NetworkPolicy
7# deny - both
8package lab.k8s.workload
9
10import rego.v1
11
12controllers := {"Deployment", "StatefulSet", "DaemonSet", "ReplicaSet", "Job"}
13
14# ---- normalised pod specs --------------------------------------------------------
15
16pods contains p if {
17 some o in input.objects
18 o.kind == "Pod"
19 p := {"id": sprintf("Pod/%s", [o.metadata.name]), "ns": object.get(o.metadata, "namespace", "default"), "spec": o.spec, "meta": o.metadata}
20}
21
22pods contains p if {
23 some o in input.objects
24 o.kind in controllers
25 p := {"id": sprintf("%s/%s", [o.kind, o.metadata.name]), "ns": object.get(o.metadata, "namespace", "default"), "spec": o.spec.template.spec, "meta": object.get(o.spec.template, "metadata", {})}
26}
27
28containers(spec) := array.concat(
29 array.concat(object.get(spec, "containers", []), object.get(spec, "initContainers", [])),
30 object.get(spec, "ephemeralContainers", []),
31)
32
33sc(x) := object.get(x, "securityContext", {})
34
35violation(rule, id, msg) := {"rule": rule, "object": id, "message": msg}
36
37# ---- pod-level rules ---------------------------------------------------------------
38
39pod_violations contains violation("privileged", p.id, "container runs privileged") if {
40 some p in pods
41 some c in containers(p.spec)
42 sc(c).privileged == true
43}
44
45pod_violations contains violation("host-namespace", p.id, sprintf("%s is true", [f])) if {
46 some p in pods
47 some f in ["hostNetwork", "hostPID", "hostIPC"]
48 p.spec[f] == true
49}
50
51pod_violations contains violation("hostpath", p.id, "hostPath volume") if {
52 some p in pods
53 some v in object.get(p.spec, "volumes", [])
54 v.hostPath
55}
56
57effective_run_as_non_root(spec, c) := object.get(sc(c), "runAsNonRoot", object.get(sc(spec), "runAsNonRoot", false))
58
59effective_uid(spec, c) := object.get(sc(c), "runAsUser", object.get(sc(spec), "runAsUser", -1))
60
61pod_violations contains violation("run-as-root", p.id, sprintf("container %s may run as root", [c.name])) if {
62 some p in pods
63 some c in containers(p.spec)
64 not effective_run_as_non_root(p.spec, c) == true
65}
66
67pod_violations contains violation("run-as-root", p.id, sprintf("container %s runs as uid 0", [c.name])) if {
68 some p in pods
69 some c in containers(p.spec)
70 effective_uid(p.spec, c) == 0
71}
72
73pod_violations contains violation("privilege-escalation", p.id, sprintf("container %s does not set allowPrivilegeEscalation=false", [c.name])) if {
74 some p in pods
75 some c in containers(p.spec)
76 not object.get(sc(c), "allowPrivilegeEscalation", true) == false
77}
78
79pod_violations contains violation("capabilities", p.id, sprintf("container %s does not drop ALL capabilities", [c.name])) if {
80 some p in pods
81 some c in containers(p.spec)
82 not "ALL" in object.get(object.get(sc(c), "capabilities", {}), "drop", [])
83}
84
85pod_violations contains violation("capabilities", p.id, sprintf("container %s adds capabilities", [c.name])) if {
86 some p in pods
87 some c in containers(p.spec)
88 count(object.get(object.get(sc(c), "capabilities", {}), "add", [])) > 0
89}
90
91seccomp_ok(spec, c) if object.get(object.get(sc(c), "seccompProfile", {}), "type", "") in {"RuntimeDefault", "Localhost"}
92
93seccomp_ok(spec, c) if {
94 not object.get(sc(c), "seccompProfile", false)
95 object.get(object.get(sc(spec), "seccompProfile", {}), "type", "") in {"RuntimeDefault", "Localhost"}
96}
97
98pod_violations contains violation("seccomp", p.id, sprintf("container %s has no RuntimeDefault or Localhost seccomp profile", [c.name])) if {
99 some p in pods
100 some c in containers(p.spec)
101 not seccomp_ok(p.spec, c)
102}
103
104pod_violations contains violation("resource-limits", p.id, sprintf("container %s lacks cpu or memory limits", [c.name])) if {
105 some p in pods
106 some c in containers(p.spec)
107 limits := object.get(object.get(c, "resources", {}), "limits", {})
108 not limits.cpu
109}
110
111pod_violations contains violation("resource-limits", p.id, sprintf("container %s lacks cpu or memory limits", [c.name])) if {
112 some p in pods
113 some c in containers(p.spec)
114 limits := object.get(object.get(c, "resources", {}), "limits", {})
115 not limits.memory
116}
117
118pod_violations contains violation("resource-limits", p.id, sprintf("container %s has no resources block", [c.name])) if {
119 some p in pods
120 some c in containers(p.spec)
121 not c.resources
122}
123
124pod_violations contains violation("image-tag", p.id, sprintf("image %s is not digest-pinned and has no explicit non-latest tag", [c.image])) if {
125 some p in pods
126 some c in containers(p.spec)
127 not image_pinned(c.image)
128}
129
130image_pinned(image) if contains(image, "@sha256:")
131
132image_pinned(image) if {
133 regex.match(`^[^@]*:[^:/@]+$`, image)
134 not endswith(image, ":latest")
135}
136
137pod_violations contains violation("read-only-rootfs", p.id, sprintf("container %s has a writable root filesystem", [c.name])) if {
138 some p in pods
139 some c in containers(p.spec)
140 not object.get(sc(c), "readOnlyRootFilesystem", false) == true
141}
142
143# A pod has an API token if it projects one explicitly, or if automounting is not
144# explicitly disabled (the default is true). The offline view must model the
145# default because the ServiceAccount admission plugin injects the volume later.
146token_present(spec) if {
147 some v in object.get(spec, "volumes", [])
148 some s in object.get(object.get(v, "projected", {}), "sources", [])
149 s.serviceAccountToken
150}
151
152token_present(spec) if not object.get(spec, "automountServiceAccountToken", true) == false
153
154token_approved(p) if {
155 object.get(object.get(p.meta, "labels", {}), "lab.example/api-access", "") == "approved"
156 object.get(p.spec, "serviceAccountName", "default") != "default"
157}
158
159pod_violations contains violation("service-account-token", p.id, "API token present without reviewed approval label and non-default ServiceAccount") if {
160 some p in pods
161 token_present(p.spec)
162 not token_approved(p)
163}
164
165# ---- manifest-set rules -----------------------------------------------------------
166
167namespaces_with_workloads contains p.ns if some p in pods
168
169policy_violations contains violation("psa-enforce", sprintf("Namespace/%s", [ns]), "namespace with workloads does not enforce baseline or restricted Pod Security") if {
170 some ns in namespaces_with_workloads
171 not psa_enforced(ns)
172}
173
174psa_enforced(ns) if {
175 some o in input.objects
176 o.kind == "Namespace"
177 o.metadata.name == ns
178 o.metadata.labels["pod-security.kubernetes.io/enforce"] in {"baseline", "restricted"}
179}
180
181policy_violations contains violation("default-deny-network", sprintf("Namespace/%s", [ns]), "namespace with workloads has no default-deny ingress+egress NetworkPolicy") if {
182 some ns in namespaces_with_workloads
183 not default_deny(ns)
184}
185
186default_deny(ns) if {
187 some o in input.objects
188 o.kind == "NetworkPolicy"
189 object.get(o.metadata, "namespace", "default") == ns
190 count(object.get(o.spec, "podSelector", {"x": 1})) == 0
191 {"Ingress", "Egress"} == {t | some t in object.get(o.spec, "policyTypes", [])}
192 count(object.get(o.spec, "ingress", [])) == 0
193 count(object.get(o.spec, "egress", [])) == 0
194}
195
196rbac_rules contains r if {
197 some o in input.objects
198 o.kind in {"Role", "ClusterRole"}
199 some rule in object.get(o, "rules", [])
200 r := {"id": sprintf("%s/%s", [o.kind, o.metadata.name]), "kind": o.kind, "rule": rule}
201}
202
203policy_violations contains violation("rbac-wildcard", r.id, "rule uses a wildcard in verbs, resources or apiGroups") if {
204 some r in rbac_rules
205 some field in ["verbs", "resources", "apiGroups"]
206 "*" in object.get(r.rule, field, [])
207}
208
209policy_violations contains violation("rbac-secrets-read", r.id, "cluster-wide read access to secrets") if {
210 some r in rbac_rules
211 r.kind == "ClusterRole"
212 "secrets" in object.get(r.rule, "resources", [])
213 some verb in ["get", "list", "watch"]
214 verb in object.get(r.rule, "verbs", [])
215}
216
217policy_violations contains violation("rbac-exec", r.id, "pods/exec create allows code execution in other pods") if {
218 some r in rbac_rules
219 "pods/exec" in object.get(r.rule, "resources", [])
220 "create" in object.get(r.rule, "verbs", [])
221}
222
223policy_violations contains violation("rbac-privilege-verbs", r.id, sprintf("grants %s", [verb])) if {
224 some r in rbac_rules
225 some verb in ["escalate", "bind", "impersonate"]
226 verb in object.get(r.rule, "verbs", [])
227}
228
229policy_violations contains violation("rbac-binding-creation", r.id, "can create RoleBindings or ClusterRoleBindings") if {
230 some r in rbac_rules
231 some resource in ["rolebindings", "clusterrolebindings"]
232 resource in object.get(r.rule, "resources", [])
233 "create" in object.get(r.rule, "verbs", [])
234}
235
236policy_violations contains violation("rbac-cluster-admin", sprintf("%s/%s", [o.kind, o.metadata.name]), "binds cluster-admin") if {
237 some o in input.objects
238 o.kind in {"RoleBinding", "ClusterRoleBinding"}
239 o.roleRef.name == "cluster-admin"
240}
241
242policy_violations contains violation("rbac-broad-subject", sprintf("%s/%s", [o.kind, o.metadata.name]), sprintf("binds broad subject %s", [s.name])) if {
243 some o in input.objects
244 o.kind in {"RoleBinding", "ClusterRoleBinding"}
245 some s in object.get(o, "subjects", [])
246 s.name in {"system:authenticated", "system:unauthenticated", "system:serviceaccounts"}
247}
248
249policy_violations contains violation("rbac-default-serviceaccount", sprintf("%s/%s", [o.kind, o.metadata.name]), "binds the default ServiceAccount") if {
250 some o in input.objects
251 o.kind in {"RoleBinding", "ClusterRoleBinding"}
252 some s in object.get(o, "subjects", [])
253 s.kind == "ServiceAccount"
254 s.name == "default"
255}
256
257deny := pod_violations | policy_violations
1apiVersion: policies.kyverno.io/v1
2kind: ValidatingPolicy
3metadata:
4 name: hardened-pods
5 annotations:
6 policies.kyverno.io/title: Hardened Pod baseline
7 policies.kyverno.io/category: Pod Security
8 policies.kyverno.io/severity: high
9spec:
10 validationActions:
11 - Deny
12 failurePolicy: Fail
13 evaluation:
14 admission:
15 enabled: true
16 background:
17 enabled: true
18 mode: Kubernetes
19 webhookConfiguration:
20 timeoutSeconds: 10
21 matchConstraints:
22 resourceRules:
23 - apiGroups:
24 - ""
25 apiVersions:
26 - v1
27 operations:
28 - CREATE
29 - UPDATE
30 resources:
31 - pods
32 variables:
33 - name: allContainers
34 expression: >-
35 object.spec.containers
36 + object.spec.?initContainers.orValue([])
37 + object.spec.?ephemeralContainers.orValue([])
38 validations:
39 - message: Host PID, IPC, and network namespaces are not allowed.
40 expression: >-
41 !object.spec.?hostPID.orValue(false)
42 && !object.spec.?hostIPC.orValue(false)
43 && !object.spec.?hostNetwork.orValue(false)
44 - message: hostPath volumes are not allowed by this workload baseline.
45 expression: >-
46 !has(object.spec.volumes)
47 || object.spec.volumes.all(volume, !has(volume.hostPath))
48 - message: Service-account token automount must be explicitly disabled.
49 expression: object.spec.?automountServiceAccountToken.orValue(true) == false
50 - message: Containers must run as non-root without privileged mode or privilege escalation.
51 expression: >-
52 variables.allContainers.all(container,
53 has(container.securityContext)
54 && container.securityContext.?runAsNonRoot.orValue(false) == true
55 && container.securityContext.?privileged.orValue(false) == false
56 && container.securityContext.?allowPrivilegeEscalation.orValue(true) == false)
57 - message: Containers must use a read-only root filesystem and drop all capabilities.
58 expression: >-
59 variables.allContainers.all(container,
60 container.securityContext.?readOnlyRootFilesystem.orValue(false) == true
61 && has(container.securityContext.capabilities)
62 && container.securityContext.capabilities.?drop.orValue([]).exists(capability, capability == "ALL")
63 && size(container.securityContext.capabilities.?add.orValue([])) == 0)
64 - message: A RuntimeDefault or Localhost seccomp profile is required.
65 expression: >-
66 has(object.spec.securityContext)
67 && has(object.spec.securityContext.seccompProfile)
68 && object.spec.securityContext.seccompProfile.type in ["RuntimeDefault", "Localhost"]
69 - message: CPU and memory requests and limits are required for every container.
70 expression: >-
71 variables.allContainers.all(container,
72 has(container.resources)
73 && has(container.resources.requests)
74 && has(container.resources.requests.cpu)
75 && has(container.resources.requests.memory)
76 && has(container.resources.limits)
77 && has(container.resources.limits.cpu)
78 && has(container.resources.limits.memory))
1apiVersion: policies.kyverno.io/v1
2kind: ImageValidatingPolicy
3metadata:
4 name: verify-secureobs-release
5 annotations:
6 policies.kyverno.io/title: Verify SecureObs release identity and provenance
7 policies.kyverno.io/category: Software Supply Chain
8 policies.kyverno.io/severity: high
9spec:
10 validationActions:
11 - Deny
12 failurePolicy: Fail
13 evaluation:
14 admission:
15 enabled: true
16 background:
17 enabled: true
18 mode: Kubernetes
19 webhookConfiguration:
20 timeoutSeconds: 15
21 matchConstraints:
22 resourceRules:
23 - apiGroups:
24 - ""
25 apiVersions:
26 - v1
27 operations:
28 - CREATE
29 - UPDATE
30 resources:
31 - pods
32 matchImageReferences:
33 - glob: "ghcr.io/jasonachkar/secureobs:*"
34 - glob: "ghcr.io/jasonachkar/secureobs@sha256:*"
35 attestors:
36 - name: releaseIdentity
37 cosign:
38 keyless:
39 identities:
40 - issuer: "https://token.actions.githubusercontent.com"
41 subject: "https://github.com/jasonachkar/secureobs/.github/workflows/release.yml@refs/heads/main"
42 ctlog:
43 url: "https://rekor.sigstore.dev"
44 attestations:
45 - name: slsaProvenance
46 intoto:
47 type: "https://slsa.dev/provenance/v1"
48 validationConfigurations:
49 mutateDigest: true
50 required: true
51 verifyDigest: true
52 validations:
53 - message: Image signature is missing or the keyless workflow identity is not authorized.
54 expression: >-
55 images.containers
56 .map(image, verifyImageSignatures(image, [attestors.releaseIdentity]))
57 .all(result, result > 0)
58 - message: SLSA provenance is missing or is not signed by the authorized workflow identity.
59 expression: >-
60 images.containers
61 .map(image, verifyAttestationSignatures(
62 image,
63 attestations.slsaProvenance,
64 [attestors.releaseIdentity]))
65 .all(result, result > 0)
1"use strict";
2
3// Structural invariants for the baseline and hardened manifests plus consistency of
4// the admission case corpus. Needs no cluster and no policy engine, so it runs in
5// `npm run validate`. It is a POLICY MODEL (T1): it proves the files say what the
6// README says, not that a cluster enforces them. The live and native-engine results
7// come from scripts/run-cluster-lab.sh.
8
9const assert = require("node:assert/strict");
10const fs = require("node:fs");
11const path = require("node:path");
12const test = require("node:test");
13const YAML = require("yaml");
14
15const lab = path.resolve(__dirname, "..");
16
17function load(dir) {
18 const directory = path.join(lab, dir);
19 return fs.readdirSync(directory).filter((f) => /\.ya?ml$/.test(f)).sort().flatMap((file) =>
20 YAML.parseAllDocuments(fs.readFileSync(path.join(directory, file), "utf8")).map((d) => d.toJSON()).filter(Boolean),
21 );
22}
23const kind = (objects, k) => objects.filter((o) => o.kind === k);
24const podSpecs = (objects) => objects.filter((o) => o.kind === "Deployment").map((o) => ({ name: o.metadata.name, spec: o.spec.template.spec, meta: o.spec.template.metadata }));
25const allContainers = (spec) => [...(spec.containers || []), ...(spec.initContainers || [])];
26
27const baseline = load("baseline");
28const hardened = load("hardened");
29
30// ---- baseline: every intentional flaw is present ---------------------------------
31test("baseline: the workload is privileged, root, host-PID, hostPath, unlimited, token-mounted", () => {
32 const [{ spec }] = podSpecs(baseline);
33 const container = spec.containers[0];
34 assert.equal(container.securityContext.privileged, true);
35 assert.equal(container.securityContext.runAsUser, 0);
36 assert.equal(spec.hostPID, true);
37 assert.ok(spec.volumes.some((v) => v.hostPath), "hostPath volume");
38 assert.equal(container.resources, undefined, "no resource limits");
39 assert.equal(spec.automountServiceAccountToken, undefined, "token mounted by default");
40});
41
42test("baseline: namespaces carry no Pod Security Admission labels (weak admission control)", () => {
43 for (const ns of kind(baseline, "Namespace")) {
44 const labels = ns.metadata.labels || {};
45 assert.ok(!Object.keys(labels).some((l) => l.startsWith("pod-security.kubernetes.io/")), ns.metadata.name);
46 }
47});
48
49test("baseline: no NetworkPolicy exists", () => {
50 assert.equal(kind(baseline, "NetworkPolicy").length, 0);
51});
52
53test("baseline: the application identity is over-granted through a ClusterRoleBinding", () => {
54 const [role] = kind(baseline, "ClusterRole");
55 const resources = role.rules.flatMap((r) => r.resources);
56 assert.ok(resources.includes("secrets") && resources.includes("pods/exec"));
57 const [binding] = kind(baseline, "ClusterRoleBinding");
58 assert.equal(binding.kind, "ClusterRoleBinding", "cluster-wide, not namespaced");
59 assert.equal(binding.subjects[0].name, "app-sa");
60 // Bounded on purpose: the over-grant is not cluster-admin and has no escalation verbs.
61 const verbs = role.rules.flatMap((r) => r.verbs);
62 assert.ok(!verbs.some((v) => ["*", "escalate", "bind", "impersonate"].includes(v)));
63});
64
65// ---- hardened: every control is declared -------------------------------------------
66test("hardened: the namespace enforces, audits and warns at restricted with a pinned version", () => {
67 const [ns] = kind(hardened, "Namespace");
68 for (const mode of ["enforce", "audit", "warn"]) {
69 assert.equal(ns.metadata.labels[`pod-security.kubernetes.io/${mode}`], "restricted");
70 assert.match(ns.metadata.labels[`pod-security.kubernetes.io/${mode}-version`], /^v1\.\d+$/);
71 }
72});
73
74test("hardened: every pod template meets the container-level controls", () => {
75 const specs = podSpecs(hardened);
76 assert.ok(specs.length >= 2);
77 for (const { name, spec } of specs) {
78 assert.equal(spec.securityContext.runAsNonRoot, true, name);
79 assert.notEqual(spec.securityContext.runAsUser, 0, name);
80 assert.equal(spec.securityContext.seccompProfile.type, "RuntimeDefault", name);
81 assert.equal(spec.automountServiceAccountToken, false, `${name}: token never auto-mounted`);
82 assert.ok(!spec.hostPID && !spec.hostNetwork && !spec.hostIPC, name);
83 assert.ok(!(spec.volumes || []).some((v) => v.hostPath), name);
84 for (const c of allContainers(spec)) {
85 const sc = c.securityContext;
86 assert.equal(sc.allowPrivilegeEscalation, false, `${name}/${c.name}`);
87 assert.equal(sc.readOnlyRootFilesystem, true, `${name}/${c.name}`);
88 assert.equal(sc.runAsNonRoot, true, `${name}/${c.name}: container-level too (the existing Kyverno policy reads only this level)`);
89 assert.deepEqual(sc.capabilities.drop, ["ALL"], `${name}/${c.name}`);
90 assert.ok(!sc.privileged, `${name}/${c.name}`);
91 assert.ok(c.resources.limits.cpu && c.resources.limits.memory, `${name}/${c.name}`);
92 assert.match(c.image, /:[^:/@]+$/, `${name}/${c.name}: explicit tag`);
93 assert.ok(!c.image.endsWith(":latest"), name);
94 }
95 }
96});
97
98test("hardened: only the reviewed workload projects a token, short-lived, with the approval label", () => {
99 const withToken = podSpecs(hardened).filter(({ spec }) =>
100 (spec.volumes || []).some((v) => v.projected && v.projected.sources.some((s) => s.serviceAccountToken)));
101 assert.deepEqual(withToken.map((p) => p.name), ["api-reader"]);
102 const [{ spec, meta }] = withToken;
103 assert.equal(meta.labels["lab.example/api-access"], "approved");
104 assert.notEqual(spec.serviceAccountName, "default");
105 const token = spec.volumes.find((v) => v.projected).projected.sources.find((s) => s.serviceAccountToken).serviceAccountToken;
106 assert.ok(token.expirationSeconds <= 3600);
107});
108
109test("hardened: RBAC is namespaced, named-resource scoped, and wildcard-free", () => {
110 assert.equal(kind(hardened, "ClusterRole").length + kind(hardened, "ClusterRoleBinding").length, 0);
111 for (const role of kind(hardened, "Role")) {
112 for (const rule of role.rules) {
113 for (const field of ["verbs", "resources", "apiGroups"]) assert.ok(!(rule[field] || []).includes("*"), `${role.metadata.name}.${field}`);
114 assert.ok(rule.resourceNames && rule.resourceNames.length > 0, `${role.metadata.name}: scoped by resourceNames`);
115 assert.ok(!rule.verbs.some((v) => ["escalate", "bind", "impersonate", "create", "update", "patch", "delete"].includes(v)));
116 }
117 }
118 for (const sa of kind(hardened, "ServiceAccount")) assert.equal(sa.automountServiceAccountToken, false, sa.metadata.name);
119});
120
121test("hardened: NetworkPolicy has a true default deny and every allow rule names a port", () => {
122 const policies = kind(hardened, "NetworkPolicy");
123 const denyAll = policies.find((p) => p.metadata.name === "default-deny-all");
124 assert.deepEqual(denyAll.spec.podSelector, {});
125 assert.deepEqual([...denyAll.spec.policyTypes].sort(), ["Egress", "Ingress"]);
126 assert.equal(denyAll.spec.ingress, undefined);
127 assert.equal(denyAll.spec.egress, undefined);
128 for (const policy of policies.filter((p) => p !== denyAll)) {
129 for (const rule of [...(policy.spec.egress || []), ...(policy.spec.ingress || [])]) {
130 assert.ok(rule.ports && rule.ports.length > 0, `${policy.metadata.name}: allow rule without ports`);
131 for (const peer of [...(rule.to || []), ...(rule.from || [])]) {
132 assert.notEqual(peer.ipBlock && peer.ipBlock.cidr, "0.0.0.0/0", policy.metadata.name);
133 assert.ok(!peer.ipBlock || /\/32$/.test(peer.ipBlock.cidr), `${policy.metadata.name}: ipBlock must be a single host`);
134 }
135 }
136 }
137});
138
139test("hardened: the admission policy fails closed and its binding selects the enforced namespaces", () => {
140 const [policy] = kind(hardened, "ValidatingAdmissionPolicy");
141 const [binding] = kind(hardened, "ValidatingAdmissionPolicyBinding");
142 assert.equal(policy.spec.failurePolicy, "Fail");
143 assert.ok(binding.spec.validationActions.includes("Deny"));
144 assert.equal(binding.spec.policyName, policy.metadata.name);
145 const [ns] = kind(hardened, "Namespace");
146 const selector = binding.spec.matchResources.namespaceSelector.matchLabels;
147 for (const [key, value] of Object.entries(selector)) assert.equal(ns.metadata.labels[key], value);
148 assert.ok(policy.spec.validations.length >= 4);
149});
150
151test("the Calico manifest pin is a SHA-256", () => {
152 assert.match(fs.readFileSync(path.join(lab, "cluster", "calico.sha256"), "utf8").trim(), /^[0-9a-f]{64}$/);
153});
154
155// ---- admission case corpus consistency ------------------------------------------------
156const cases = YAML.parseAllDocuments(fs.readFileSync(path.join(lab, "admission-cases", "cases.yaml"), "utf8")).map((d) => d.toJSON()).filter(Boolean);
157const expectations = JSON.parse(fs.readFileSync(path.join(lab, "admission-cases", "expectations.json"), "utf8"));
158const kyvernoTest = YAML.parse(fs.readFileSync(path.join(lab, "admission-cases", "kyverno-test.yaml"), "utf8"));
159
160test("every case has exactly one expectation row, and each row names a case", () => {
161 assert.deepEqual(cases.map((c) => c.metadata.name).sort(), Object.keys(expectations.cases).sort());
162});
163
164test("every case declares what it violates, and differs from compliant-app in a single concern", () => {
165 const base = cases.find((c) => c.metadata.name === "compliant-app");
166 for (const c of cases) assert.ok(c.metadata.annotations["lab.example/violates"], c.metadata.name);
167 assert.equal(base.metadata.annotations["lab.example/violates"], "none");
168});
169
170test("the Kyverno test file lists exactly the results predicted in expectations.json", () => {
171 const byResult = { pass: [], fail: [] };
172 for (const r of kyvernoTest.results) byResult[r.result].push(...r.resources);
173 const predicted = { pass: [], fail: [] };
174 for (const [name, row] of Object.entries(expectations.cases)) predicted[row.kyverno].push(name);
175 assert.deepEqual(byResult.pass.sort(), predicted.pass.sort());
176 assert.deepEqual(byResult.fail.sort(), predicted.fail.sort());
177});
178
179test("expectations are well-formed", () => {
180 const allowed = { psa: ["allow", "deny"], vap: ["allow", "deny"], kyverno: ["pass", "fail"], opa: ["allow", "deny"] };
181 for (const [name, row] of Object.entries(expectations.cases)) {
182 for (const [engine, values] of Object.entries(allowed)) assert.ok(values.includes(row[engine]), `${name}.${engine}`);
183 }
184});
185
186test("the case corpus covers both layers: each admission engine denies something the other allows", () => {
187 const rows = Object.values(expectations.cases);
188 assert.ok(rows.some((r) => r.psa === "deny" && r.vap === "allow"));
189 assert.ok(rows.some((r) => r.vap === "deny" && r.psa === "allow"));
190});
1#!/usr/bin/env python3
2"""Assert the OBSERVED results of the Kubernetes cluster lab. Usage: cluster_check.py <outdir>
3
4Reads what scripts/run-cluster-lab.sh recorded and fails (exit 1) when an observed
5value differs from a claim made in the README. It also assembles the per-engine
6admission matrix and compares it with admission-cases/expectations.json, which was
7written before the engines were run. A mismatch is reported, never overwritten.
8"""
9import json
10import pathlib
11import re
12import sys
13from collections import defaultdict
14
15out = pathlib.Path(sys.argv[1])
16lab = pathlib.Path(__file__).resolve().parents[1]
17failures, passes = [], 0
18
19
20def load(name):
21 path = out / name
22 return json.loads(path.read_text()) if path.exists() else None
23
24
25def jsonl(name):
26 path = out / name
27 return [json.loads(line) for line in path.read_text().splitlines() if line.strip()] if path.exists() else []
28
29
30def check(name, condition, detail=""):
31 global passes
32 if condition:
33 passes += 1
34 print(f"PASS {name}")
35 else:
36 failures.append(name)
37 print(f"FAIL {name} {detail}")
38
39
40def calls(report):
41 return {c["name"]: c for c in report.get("api_calls", [])}
42
43
44
45# ---- environment gate ---------------------------------------------------------------
46smoke = load("np-smoke.json")
47check("NetworkPolicy is enforced by this cluster's CNI (precondition for every network result)",
48 bool(smoke) and smoke["networkpolicy_enforced"] is True, smoke)
49
50# ---- baseline: identity -------------------------------------------------------------
51bk = load("baseline-k8sprobe.json")
52check("baseline: token mounted by default", bool(bk) and bk["token_mounted"] is True)
53if bk:
54 c = calls(bk)
55 check("baseline: token is a bound (pod-scoped) token", bk["token_claims"].get("bound_to_pod") is True, bk["token_claims"])
56 for name in ("list_secrets_kube_system", "list_pods_all_namespaces", "list_nodes", "list_secrets_own_ns", "list_configmaps_own_ns"):
57 check(f"baseline: {name} returns 200", c.get(name, {}).get("status") == 200, c.get(name))
58 check("baseline: kube-system secrets are listable (count only, no names or values recorded)",
59 (c["list_secrets_kube_system"].get("items") or 0) > 0, c["list_secrets_kube_system"])
60 acc = bk["self_subject_access_review"]
61 for name in ("create_pods_own_ns", "create_pods_exec_own_ns", "get_secrets_any_namespace", "create_rolebindings_own_ns"):
62 check(f"baseline: SelfSubjectAccessReview allows {name}", acc.get(name) is True, acc)
63 for name in ("escalate_clusterroles", "impersonate_users"):
64 check(f"baseline: {name} is NOT allowed (the over-grant is bounded, not cluster-admin)", acc.get(name) is False, acc)
65bc = load("baseline-can-i.json")
66check("baseline: kubectl auth can-i agrees with the in-pod review",
67 bool(bc) and bc.get("get secrets in kube-system") is True and bc.get("create pods/exec in lab-data") is True
68 and bc.get("escalate clusterroles (any namespace)") is False, bc)
69
70# ---- baseline: runtime and network --------------------------------------------------
71bp = load("baseline-posture.json")
72if bp:
73 p, pr = bp["posture"], {x["name"].split(" ")[0]: x for x in bp["probes"]}
74 check("baseline: runs as uid 0", p["uid"] == 0)
75 check("baseline: privileged container has a large capability set", len(p["cap_eff"]) >= 30, len(p["cap_eff"]))
76 check("baseline: no seccomp filter", p["seccomp_mode"] == "0", p["seccomp_mode"])
77 check("baseline: host PID namespace visible", p["visible_process_count"] > 10, p["visible_process_count"])
78 check("baseline: root filesystem writable", pr["write_root_filesystem"]["allowed"] is True)
79 check("baseline: hostPath directory writable from the container", pr["host_canary_write"]["allowed"] is True)
80owner = out / "baseline-hostpath-owner.txt"
81check("baseline: file written through hostPath is owned by uid 0 on the node",
82 owner.exists() and owner.read_text().split()[0] == "0", owner.read_text() if owner.exists() else None)
83bn = {(l["to"].split(".")[0]): l["result"] for l in jsonl("baseline-net.jsonl")}
84for target in ("canary", "neighbor"):
85 check(f"baseline: pod reaches {target} (no NetworkPolicy)", bn.get(target, {}).get("connected") is True, bn.get(target))
86api_conn = [l["result"] for l in jsonl("baseline-net.jsonl") if l["to"].endswith(":6443")]
87check("baseline: pod reaches the API server endpoint directly", bool(api_conn) and api_conn[0]["connected"] is True, api_conn)
88
89# ---- admission matrix ---------------------------------------------------------------
90expect = json.loads((lab / "admission-cases" / "expectations.json").read_text())["cases"]
91base = load("matrix-lab-baseline.json")
92psa = load("matrix-lab-hardened-psa.json")
93vap = load("matrix-lab-vap-only.json")
94comb = load("matrix-lab-hardened-combined.json")
95check("admission: all matrices recorded", all([base, psa, vap, comb]))
96if all([base, psa, vap, comb]):
97 n = len(expect)
98 allowed = sum(1 for r in base["results"].values() if r["decision"] == "allow")
99 check(f"baseline admission: all {n} cases admitted (no admission control)", allowed == n, {k: v for k, v in base["results"].items() if v["decision"] != "allow"})
100
101 # Kyverno CLI (offline): the test file encodes the predicted results; check the CLI agrees.
102 kv_text = (out / "kyverno-test.txt").read_text() if (out / "kyverno-test.txt").exists() else ""
103 m = re.search(r"Test Summary: (\d+) tests? passed and (\d+) tests? failed", kv_text)
104 check("kyverno: every predicted result matched the CLI", bool(m) and m.group(2) == "0", m.group(0) if m else kv_text[:200])
105 # OPA (offline)
106 opa_cases = load("opa-cases.json")
107 opa_deny = defaultdict(set)
108 if opa_cases:
109 for v in opa_cases["result"][0]["expressions"][0]["value"]:
110 opa_deny[v["object"].split("/", 1)[1]].add(v["rule"])
111
112 rows, mismatches = [], []
113 for case, want in expect.items():
114 got = {
115 "psa": psa["results"][case]["decision"],
116 "vap": vap["results"][case]["decision"],
117 "opa": "deny" if opa_deny.get(case) else "allow",
118 # kyverno decision = predicted result, valid only because the CLI matched all of them
119 "kyverno": want["kyverno"],
120 }
121 combined = comb["results"][case]["decision"]
122 for engine in ("psa", "vap", "opa", "kyverno"):
123 if got[engine] != want[engine]:
124 mismatches.append((case, engine, want[engine], got[engine]))
125 union_expected = "deny" if (got["psa"] == "deny" or got["vap"] == "deny") else "allow"
126 rows.append((case, got, combined, union_expected))
127 check(f"matrix: {case}: combined PSA+VAP decision equals deny-if-either", combined == union_expected, (combined, union_expected))
128 for engine in ("psa", "vap", "opa"):
129 bad = [m for m in mismatches if m[1] == engine]
130 check(f"matrix: live/offline {engine} decisions match the predictions in expectations.json", not bad, bad)
131 psa_only = [r[0] for r in rows if r[1]["psa"] == "deny" and r[1]["vap"] == "allow"]
132 vap_only = [r[0] for r in rows if r[1]["vap"] == "deny" and r[1]["psa"] == "allow"]
133 check("matrix: neither PSA nor VAP alone covers the corpus (each denies cases the other allows)", bool(psa_only) and bool(vap_only), (psa_only, vap_only))
134
135 lines = ["| Case | PSA restricted (live) | VAP (live) | PSA+VAP together (live) | Kyverno hardened-pods (offline) | OPA workload.rego (offline) |", "| --- | --- | --- | --- | --- | --- |"]
136 for case, got, combined, _ in rows:
137 lines.append(f"| `{case}` | {got['psa']} | {got['vap']} | {combined} | {'allow' if got['kyverno'] == 'pass' else 'deny'} | {got['opa']} |")
138 (out / "matrix-table.txt").write_text("\n".join(lines) + "\n")
139 (out / "matrix.json").write_text(json.dumps({"cases": {c: {**g, "combined": cb} for c, g, cb, _ in rows}, "mismatches": mismatches}, indent=2) + "\n")
140 if mismatches:
141 print("INFO mismatches against the pre-run predictions:", mismatches)
142
143rej = (out / "hardened-rejects-baseline-workload.txt")
144text = rej.read_text() if rej.exists() else ""
145check("hardened: submitting the unchanged baseline Deployment warns (PSA enforce applies to Pods, not Deployments)",
146 "would violate PodSecurity" in text and "restricted" in text, text[:300])
147check("hardened: the ReplicaSet's pod creation is refused by Pod Security Admission and no pod exists",
148 'violates PodSecurity "restricted' in text.split("persisted")[-1] and "pods_created_by_deployment=0" in text, text[-600:])
149
150# ---- hardened: identity --------------------------------------------------------------
151ha = load("hardened-app-k8sprobe.json")
152check("hardened app: no API token mounted at all", bool(ha) and ha["token_mounted"] is False, ha)
153hr = load("hardened-apireader-k8sprobe.json")
154check("hardened api-reader: has a token", bool(hr) and hr["token_mounted"] is True)
155if hr:
156 c = calls(hr)
157 check("hardened api-reader: GET of its one ConfigMap succeeds", c["get_configmap_app_config_own_ns"]["status"] == 200, c["get_configmap_app_config_own_ns"])
158 for name in ("list_configmaps_own_ns", "list_secrets_own_ns", "list_secrets_kube_system", "list_pods_all_namespaces", "list_nodes"):
159 check(f"hardened api-reader: {name} is forbidden (403)", c[name]["status"] == 403, c[name])
160 check("hardened api-reader: every probed write/escalation review is denied", not any(hr["self_subject_access_review"].values()), hr["self_subject_access_review"])
161 claims = hr["token_claims"]
162 check("hardened api-reader: token is bound to a pod", claims.get("bound_to_pod") is True, claims)
163 check("hardened api-reader: token lifetime is at most the requested 3600 seconds", 0 < claims.get("seconds_until_expiry", 0) <= 3600, claims)
164check("hardened api-reader: can-i get app-config -> yes", (out / "hardened-can-i-app-config.txt").read_text().strip() == "yes" if (out / "hardened-can-i-app-config.txt").exists() else False)
165check("hardened api-reader: can-i get unrelated-config -> no (resourceNames scoping)", (out / "hardened-can-i-unrelated-config.txt").read_text().strip() == "no" if (out / "hardened-can-i-unrelated-config.txt").exists() else False)
166
167# ---- hardened: runtime and network ------------------------------------------------------
168hp = load("hardened-posture.json")
169if hp:
170 p, pr = hp["posture"], {x["name"].split(" ")[0]: x for x in hp["probes"]}
171 check("hardened: runs as uid 65532", p["uid"] == 65532, p["uid"])
172 check("hardened: no effective capabilities", p["cap_eff"] == [], p["cap_eff"])
173 check("hardened: no_new_privs set", p["no_new_privs"] == "1", p["no_new_privs"])
174 check("hardened: seccomp RuntimeDefault active", p["seccomp_mode"] == "2", p["seccomp_mode"])
175 check("hardened: root filesystem read-only", p["root_fs_mounted_read_only"] is True)
176 check("hardened: memory limit 128 MiB applied by the kubelet", p["memory_limit"].startswith("134217728"), p["memory_limit"])
177 check("hardened: own PID namespace", p["visible_process_count"] < 10 and p["pid1_comm"] == "posture", (p["pid1_comm"], p["visible_process_count"]))
178 for name, errno in (("write_root_filesystem", "EROFS"), ("chown_to_other_uid", "EPERM"), ("mknod_char_device", "EPERM"),
179 ("raw_socket", "EPERM"), ("mount_tmpfs", "EPERM"), ("clone_new_user_namespace", "EPERM")):
180 check(f"hardened: {name} denied with {errno}", pr[name]["allowed"] is False and pr[name]["errno"] == errno, pr[name])
181 check("hardened: hostPath not mounted", pr["host_canary_mounted"]["allowed"] is False)
182hn = {(l["from"], l["to"].split(".")[0].split(":")[0]): l["result"] for l in jsonl("hardened-net.jsonl")}
183check("hardened app -> data-tier canary: allowed by the one explicit rule", hn.get(("hardened/app", "canary"), {}).get("connected") is True, hn)
184check("hardened app -> neighbor tenant: blocked", hn.get(("hardened/app", "neighbor"), {}).get("connected") is False, hn)
185api = [l["result"] for l in jsonl("hardened-net.jsonl") if l["from"] == "hardened/app" and l["to"].endswith(":6443")]
186check("hardened app -> API server: blocked at the network layer too", bool(api) and api[0]["connected"] is False, api)
187check("hardened api-reader -> data-tier canary: blocked (its only egress is DNS and the API server)", hn.get(("hardened/api-reader", "canary"), {}).get("connected") is False, hn)
188after = jsonl("baseline-net-after-data-policy.jsonl")
189check("baseline pod -> data tier: blocked after the data tier gained an ingress policy", bool(after) and after[0]["result"]["connected"] is False, after)
190
191for label, name in (("baseline", "baseline-can-i-rule-count.txt"), ("hardened api-reader", "hardened-apireader-can-i-rule-count.txt")):
192 if (out / name).exists():
193 print(f"INFO rules listed by `auth can-i --list` ({label}): {(out / name).read_text().strip()} (includes the discovery rules every identity has)")
194
195print(f"\n{passes} passed, {len(failures)} failed")
196sys.exit(1 if failures else 0)
1"use strict";
2
3const assert = require("node:assert/strict");
4const fs = require("node:fs");
5const path = require("node:path");
6const YAML = require("yaml");
7
8const lab = path.resolve(__dirname, "..");
9const read = (relative) => fs.readFileSync(path.join(lab, relative), "utf8");
10
11const podPolicy = YAML.parse(read("policies/hardened-pods.yaml"));
12assert.equal(podPolicy.apiVersion, "policies.kyverno.io/v1");
13assert.equal(podPolicy.kind, "ValidatingPolicy");
14assert.deepEqual(podPolicy.spec.validationActions, ["Deny"]);
15assert.equal(podPolicy.spec.failurePolicy, "Fail");
16assert.equal(podPolicy.spec.evaluation.admission.enabled, true);
17assert.equal(podPolicy.spec.evaluation.background.enabled, true);
18
19const validationText = JSON.stringify(podPolicy.spec.validations);
20for (const required of [
21 "hostPID",
22 "hostIPC",
23 "hostNetwork",
24 "hostPath",
25 "automountServiceAccountToken",
26 "runAsNonRoot",
27 "privileged",
28 "allowPrivilegeEscalation",
29 "readOnlyRootFilesystem",
30 "capabilities",
31 "seccomp",
32 "requests",
33 "limits",
34]) {
35 assert.match(validationText, new RegExp(required));
36}
37
38const imagePolicy = YAML.parse(read("policies/verify-release-images.yaml"));
39assert.equal(imagePolicy.apiVersion, "policies.kyverno.io/v1");
40assert.equal(imagePolicy.kind, "ImageValidatingPolicy");
41assert.equal(imagePolicy.spec.failurePolicy, "Fail");
42assert.deepEqual(imagePolicy.spec.validationActions, ["Deny"]);
43assert.equal(imagePolicy.spec.validationConfigurations.required, true);
44assert.equal(imagePolicy.spec.validationConfigurations.verifyDigest, true);
45assert.equal(imagePolicy.spec.validationConfigurations.mutateDigest, true);
46
47const imageCases = JSON.parse(read("fixtures/image-cases.json"));
48const expected = imageCases.expected;
49const identity = imagePolicy.spec.attestors[0].cosign.keyless.identities[0];
50assert.equal(identity.issuer, expected.issuer);
51assert.equal(identity.subject, expected.subject);
52assert.equal(imagePolicy.spec.attestations[0].intoto.type, expected.predicateType);
53assert.deepEqual(
54 imagePolicy.spec.matchImageReferences.map((reference) => reference.glob),
55 [`${expected.repository}:*`, `${expected.repository}@sha256:*`],
56);
57
58function matchesImageReference(reference) {
59 return imagePolicy.spec.matchImageReferences.some(({ glob }) => {
60 assert.match(glob, /\*$/, "the offline matcher supports reviewed trailing-star globs only");
61 return reference.startsWith(glob.slice(0, -1));
62 });
63}
64
65assert.equal(matchesImageReference(`${expected.repository}:release-2026-07-23`), true);
66assert.equal(matchesImageReference(`${expected.repository}@${expected.digest}`), true);
67assert.equal(matchesImageReference(`ghcr.io/attacker/secureobs@${expected.digest}`), false);
68assert.equal(matchesImageReference(`ghcr.io/jasonachkar/secureobs-evil@${expected.digest}`), false);
69
70function evaluate(candidate) {
71 const imageDigest = candidate.image.includes("@") ? candidate.image.split("@")[1] : null;
72 const repository = candidate.image.split(/[@:]/)[0];
73 return (
74 candidate.verifierSucceeded !== false &&
75 candidate.signed === true &&
76 candidate.issuer === expected.issuer &&
77 candidate.subject === expected.subject &&
78 repository === expected.repository &&
79 candidate.predicateType === expected.predicateType &&
80 candidate.provenanceValid === true &&
81 imageDigest === expected.digest &&
82 candidate.subjectDigest === expected.digest
83 );
84}
85
86const evaluatedImageCases = imageCases.cases.filter((candidate) => candidate.accepted !== null);
87for (const candidate of evaluatedImageCases) {
88 assert.equal(evaluate(candidate), candidate.accepted, candidate.name);
89}
90
91const tagOnlyCase = imageCases.cases.find(
92 (candidate) => candidate.name === "tag-only-reference-match",
93);
94assert.equal(matchesImageReference(tagOnlyCase.image), true);
95assert.equal(tagOnlyCase.accepted, null);
96assert.match(tagOnlyCase.matchOnlyReason, /not executed/i);
97
98assert.deepEqual(
99 evaluatedImageCases.filter((candidate) => !candidate.accepted).map((candidate) => candidate.name),
100 [
101 "unsigned",
102 "wrong-repository",
103 "wrong-workflow",
104 "wrong-branch",
105 "wrong-issuer",
106 "missing-attestation",
107 "malformed-provenance",
108 "wrong-predicate",
109 "verifier-or-transparency-failure",
110 "tag-substitution-digest-mismatch",
111 ],
112);
113
114const networkPolicies = YAML.parseAllDocuments(read("fixtures/network-policies.yaml"))
115 .map((document) => document.toJSON());
116const defaultDeny = networkPolicies.find(
117 (policy) => policy.metadata.name === "default-deny-ingress-and-egress",
118);
119assert.deepEqual(defaultDeny.spec.podSelector, {});
120assert.deepEqual(defaultDeny.spec.policyTypes.sort(), ["Egress", "Ingress"]);
121assert.equal(defaultDeny.spec.ingress, undefined);
122assert.equal(defaultDeny.spec.egress, undefined);
123
124const dns = networkPolicies.find((policy) => policy.metadata.name === "allow-cluster-dns");
125assert.deepEqual(
126 dns.spec.egress[0].ports.map((port) => `${port.protocol}/${port.port}`).sort(),
127 ["TCP/53", "UDP/53"],
128);
129
130console.log(
131 `PASS: Kubernetes admission, image identity (${imageCases.cases.length} cases), ` +
132 "and NetworkPolicy structural tests completed.",
133);
Run it
node labs/kubernetes-security/tests/run-tests.jsnode --test labs/kubernetes-security/tests/manifests.test.jsbash labs/kubernetes-security/validate-kyverno.shbash labs/kubernetes-security/validate-rego.shbash labs/kubernetes-security/scripts/run-cluster-lab.sh
Status: partially tested. Two layers of evidence live here:
- Offline (runs in CI): Kyverno CLI 1.18.2 over the pod-hardening policy and the admission case corpus, OPA/Rego unit and
manifest tests, kubeconform, and Node tests that pin the manifests' structure. The Node tests are part of
npm run validate; the Kyverno tests and the new Rego check (validate-rego.sh, which has not yet run on a hosted runner) are part ofnpm run verify:native-labs; kubeconform was run locally only. - Live (one disposable kind cluster, run once on 2026-11-05, 83 of 83 assertions passed): Kubernetes v1.37.0 with a policy-enforcing CNI, real API calls from inside pods, real Pod Security Admission and ValidatingAdmissionPolicy decisions, real connectivity tests. Not wired into CI.
The image-verification policy remains a schema-validated example with an offline decision model (see Existing offline fixtures); signature, certificate, registry, transparency, mutation and live admission of signed images were not executed.
Evidence labels: tested locally (executed here, output kept in evidence/),
source-reviewed (read in the named primary source, not executed), policy model (a rule set evaluated by a local test, not
enforced by the real system) and requires-review (no independent reviewer has checked it). They map to T2/T3 and T4, T0, T1 and
review status in the evidence standards.
Scope¶
One question: what can a compromised workload do, as seen from inside the cluster, and which control changes the answer? Four properties are measured on an insecure baseline and a hardened equivalent, using the same application image family as the Docker lab:
| Property | How it is measured |
|---|---|
| Workload identity | A k8sprobe subcommand in the pod calls the API with the pod's own token and records HTTP status codes and item counts only (never names or values), plus SelfSubjectAccessReview for write permissions so it changes nothing |
| Permissions | kubectl auth can-i as the ServiceAccount, cross-checked against the in-pod result |
| Network reachability | tcpcheck from inside each pod to a data-tier canary, another tenant's canary, and the API server endpoint |
| Runtime constraints | The Docker lab's probe run inside the pod: uid, capabilities, NoNewPrivs, seccomp, read-only root, cgroup limits, denied syscalls |
Out of scope: multi-node scheduling, node hardening, etcd encryption, API-server audit logging, service mesh, cloud IAM, and any cluster that is not the kind cluster this lab creates and deletes. A namespace, a PSA label or a NetworkPolicy is not a hostile multi-tenant boundary; see the Kubernetes multi-tenancy research.
What I built¶
| Path | Purpose |
|---|---|
cluster/ |
kind config (portable and a compatibility variant), up.sh (kind + Calico with a pinned manifest SHA-256 + preloaded images), down.sh |
baseline/ |
Insecure manifests: over-granted ServiceAccount, privileged root container with hostPID and hostPath, no NetworkPolicy, no admission labels, plus the two canary fixtures |
hardened/ |
PSA restricted namespace, least-privilege RBAC, restricted workloads, default-deny NetworkPolicies, a CEL ValidatingAdmissionPolicy |
admission-cases/ |
16 pods, each differing from a compliant pod in one property; expectations.json (predictions written before the engines ran); a Kyverno CLI test |
policies/rego/ |
workload.rego (pod, RBAC, namespace and NetworkPolicy rules) and 12 unit tests |
scripts/ |
np-smoke.sh, admission-matrix.js, run-cluster-lab.sh, manifests-to-input.js, publish_evidence.py |
tests/ |
manifests.test.js (16 structural tests), cluster_check.py (assertions on observed output), existing run-tests.js |
evidence/ |
Sanitized output of the run described below, plus two labeled one-off observations |
policies/hardened-pods.yaml, verify-release-images.yaml, fixtures/ |
Existing; unchanged |
Architecture¶
Pod identity to the Kubernetes API¶
sequenceDiagram
autonumber
participant K as kubelet
participant P as api-reader pod
participant N as Calico egress policy
participant A as kube-apiserver
K->>A: TokenRequest for ServiceAccount api-reader, bound to the pod, 3600 s
A-->>K: signed JWT with sub, aud, exp and pod binding
K->>P: project token, cluster CA and namespace into the pod
P->>N: connect to the API server endpoint on 6443
N-->>P: allowed, the only egress rule for api-reader besides DNS
P->>A: GET configmaps/app-config with the bearer token
A->>A: authenticate, then authorize with RBAC
A-->>P: 200 for app-config
P->>A: LIST secrets in kube-system
A-->>P: 403 Forbidden
Status: tested locally. The last four steps are the hardened-apireader-k8sprobe.json result: a GET of the one named ConfigMap
returned 200; every list and the write and escalation reviews were denied. The token was bound to the pod with about 3594 s remaining.
RBAC decision flow¶
flowchart TD
R["API request with bearer token"] --> AU{"Authenticate:<br/>signature, audience, expiry"}
AU -->|"fails"| E401["401 Unauthorized"]
AU -->|"ok: system:serviceaccount:NS:NAME"| B{"Any RoleBinding in the request namespace<br/>or ClusterRoleBinding naming this subject?"}
B -->|"none"| E403["403 Forbidden<br/>permissions are additive, so no match means deny"]
B -->|"yes"| M{"Does a rule in a bound role match<br/>verb, apiGroup, resource, subresource<br/>and resourceNames?"}
M -->|"no"| E403
M -->|"yes"| W{"Is it a write to roles or bindings?"}
W -->|"no"| ADM["Admission chain, then persist or return"]
W -->|"yes"| X{"Does the caller already hold the permissions being granted,<br/>or the escalate or bind verb?"}
X -->|"no"| E403
X -->|"yes"| ADM
Status: source-reviewed against the RBAC reference (permissions are purely additive; role and binding writes are limited by privilege
escalation prevention) and consistent with the live results: the baseline identity could list secrets in kube-system and create
pods/exec, yet escalate and impersonate were denied, because the over-grant was deliberately not cluster-admin.
Admission control flow¶
flowchart LR
subgraph PR["Before the cluster: pull request gate"]
direction TB
KC["Kyverno CLI<br/>hardened-pods"]
OP["OPA<br/>workload.rego"]
KF["kubeconform"]
ND["Node manifest<br/>invariants"]
end
PR -.-> APPLY
APPLY["kubectl apply<br/>Deployment"] --> AUTH["authn and authz"]
AUTH --> MUT["Mutating admission:<br/>ServiceAccount plugin injects the token volume"]
MUT --> VAL{"Validating admission"}
VAL --> PSA["Pod Security Admission<br/>enforce on Pods, warn on Deployments"]
VAL --> VAP["ValidatingAdmissionPolicy, CEL<br/>failurePolicy Fail"]
PSA -->|"deny"| REJ["Forbidden"]
VAP -->|"deny"| REJ
PSA -->|"allow"| OK["persist"]
VAP -->|"allow"| OK
OK --> RS["Deployment controller creates a ReplicaSet,<br/>which creates Pods"]
RS -->|"each Pod create runs the same chain"| AUTH
Status: tested locally. The Deployment was accepted with a PSA warning; the ReplicaSet's pod creation was refused with
violates PodSecurity "restricted:v1.37" and zero pods existed (hardened-rejects-baseline-workload.txt). The mutating step is
inferred from an observed effect: gap-automounted-token carries no token volume in its spec, yet the ValidatingAdmissionPolicy
denied it for having one, so the policy saw a volume the ServiceAccount plugin had injected.
Network segmentation and lateral-movement boundaries¶
flowchart LR
subgraph LB["lab-baseline: no policy"]
B["app: privileged, root"]
end
subgraph LH["lab-hardened: default deny ingress and egress"]
A["app"]
R["api-reader"]
end
subgraph LD["lab-data: default deny ingress"]
C["canary :9000"]
end
subgraph LO["lab-other: another tenant"]
N["neighbor :9000"]
end
API["kube-apiserver endpoint :6443"]
B -->|"reachable"| N
B -->|"reachable"| API
B -->|"reachable before, blocked after the data-tier policy"| C
A -->|"allowed: the one explicit rule"| C
A -.->|"blocked, timeout"| N
A -.->|"blocked, timeout"| API
R -->|"allowed: the one explicit rule"| API
R -.->|"blocked, timeout"| C
Status: tested locally under Calico v3.33.0, after the enforcement smoke test passed. DNS egress is allowed for both hardened
workloads (not drawn). A blocked connection is a timeout, not a refusal: a dropped packet looks like a slow network, which is
a debugging cost of default-deny.
Before and after¶
All values are observed; sources are in evidence/.
Workload identity and permissions
| Property | Insecure baseline (app-sa) |
Hardened app |
Hardened api-reader |
|---|---|---|---|
| Token | Auto-mounted; about 365 days left on a freshly started pod | None mounted | Explicitly projected, 3600 s, bound to the pod |
list secrets in kube-system |
200 (1 item) | no token, no API call possible | 403 |
list pods / list nodes, all namespaces |
200 (15 pods, 1 node) | none possible | 403 / 403 |
create pods, create pods/exec, create rolebindings |
allowed | none possible | all denied |
get secrets in any namespace |
allowed | none possible | denied |
escalate clusterroles, impersonate users |
denied | none possible | denied |
get configmap/app-config |
200 | none possible | 200 (the one granted object) |
get configmap/unrelated-config |
not tested | none possible | kubectl auth can-i gives no |
| Binding | ClusterRoleBinding to a ClusterRole with secrets, pods/exec, rolebindings |
none | RoleBinding to a Role limited by resourceNames |
I did not establish why the auto-mounted token had a year of life: the ServiceAccount documentation I read describes
automounted tokens as short-lived and rotating, and I did not read the kube-apiserver flag reference. Treat the number as an
observation, not an explanation.
Runtime constraints (inside the pod)
| Property | Baseline | Hardened app |
|---|---|---|
uid / CapEff |
0 / 40 capabilities | 65532 / none |
NoNewPrivs / seccomp |
0 / none | 1 / filter (RuntimeDefault) |
| Root filesystem | writable | read-only (EROFS on write) |
chown, mknod, raw socket, mount, user-namespace clone |
all allowed | EPERM each |
Host process visibility (hostPID) |
61 processes, PID 1 is the node's systemd |
2 processes, PID 1 is posture |
hostPath |
writable; the file the container wrote is owned by uid 0 on the node | not mounted |
| Memory / CPU limit | unlimited / unlimited | 128 MiB / 0.5 CPU, applied by the kubelet |
Network reachability (evidence/*-net.jsonl)
| From to | Baseline | Hardened |
|---|---|---|
| app to data-tier canary | reachable | reachable (the explicit rule) |
| app to another tenant's canary | reachable | blocked |
| app to API server endpoint | reachable | blocked |
| api-reader to data-tier canary | not applicable | blocked |
| baseline app to data-tier canary, after the data tier gained an ingress policy | blocked | not applicable |
Admission control: four engines, one corpus¶
16 pods, each differing from the compliant pod in exactly one property. Decisions come from the live API server
(--dry-run=server; nothing persisted) for PSA and VAP, run in isolation by using two namespaces (lab-hardened has the PSA labels;
lab-vap-only has only the VAP selector label) and then together; Kyverno and OPA ran offline on the same file.
| Case | PSA restricted (live) | VAP (live) | PSA+VAP together (live) | Kyverno hardened-pods (offline) | OPA workload.rego (offline) |
|---|---|---|---|---|---|
compliant-app |
allow | allow | allow | allow | allow |
compliant-api-reader |
allow | allow | allow | allow | allow |
finding-pod-level-only-run-as-non-root |
allow | allow | allow | deny | allow |
finding-sa-level-automount-false |
allow | allow | allow | deny | deny |
rejected-privileged |
deny | allow | deny | deny | deny |
rejected-hostpath |
deny | allow | deny | deny | deny |
rejected-host-namespaces |
deny | allow | deny | deny | deny |
rejected-run-as-root |
deny | allow | deny | deny | deny |
rejected-capability-add |
deny | allow | deny | deny | deny |
rejected-no-seccomp |
deny | allow | deny | deny | deny |
rejected-privilege-escalation |
deny | allow | deny | deny | deny |
gap-no-limits |
allow | deny | deny | deny | deny |
gap-latest-tag |
allow | deny | deny | allow | deny |
gap-writable-rootfs |
allow | deny | deny | deny | deny |
gap-automounted-token |
allow | deny | deny | deny | deny |
gap-projected-token-unapproved |
allow | deny | deny | allow | deny |
What the matrix shows:
- No single control covers the corpus. PSA
restricteddenies 7 cases the VAP allows (host namespaces, privileged,hostPath, non-root, capabilities, seccomp, privilege escalation); the VAP denies 5 cases PSA allows (missing limits,:latest, writable root filesystem, an automounted token, an unapproved projected token). Together they deny 12 of 16 and admit exactly the 4 acceptable pods. With no admission control (lab-baseline) all 16 were admitted. - PSA does not enforce on Deployments. The documentation says enforce mode applies to the resulting Pods, and that is what
happened: the Deployment was accepted with a warning and its ReplicaSet could not create a single pod. The failure shows up as
FailedCreateevents, not as a rejectedkubectl apply. Alert on those events; do not rely on the apply error. - Engines disagree on equivalent configurations, and I got two predictions wrong. The cases marked
finding-exist because of misses: - The existing
hardened-podsKyverno policy rejectsfinding-pod-level-only-run-as-non-root, which PSA and OPA accept: it readsrunAsNonRootat the container level only. I predicted the compliant pods would pass; the CLI failed all four, and adding only the container-level field made them pass (tested locally). The policy is unchanged; my workloads set the field at both levels, and the finding is pinned by a test. gap-automounted-tokenwas allowed inlab-hardenedbut denied inlab-vap-only. The cause was the ServiceAccount: inlab-hardenedit setsautomountServiceAccountToken: false, which protects a pod that merely omits the field. The offline engines see only the Pod, treat omission astrue, and are therefore conservative (finding-sa-level-automount-false: live allow, Kyverno and OPA deny). The case now sets the field explicitly.
admission-cases/expectations.json keeps the original predictions and the history; a mismatch is a finding, not a value to overwrite.
- A real gap in the existing Kyverno policy. gap-projected-token-unapproved and gap-latest-tag pass hardened-pods: the
policy checks automountServiceAccountToken but not an explicitly projected token volume, and does not look at image tags. Setting
automountServiceAccountToken: false and projecting a token yourself satisfies it. PSA restricted also allows that volume type.
The VAP and the Rego rule close it.
- The "approved" label is a review marker, not authorization. The VAP lets a pod project a token only if it carries
lab.example/api-access: approved and a non-default ServiceAccount, but whoever can create the pod can set the label. A real
control binds approval to something the pod author cannot set: a VAP parameter resource listing permitted ServiceAccounts, or a
platform-owned namespace label. I did not build that.
NetworkPolicy enforcement is a property of the CNI¶
Writing NetworkPolicy objects proves nothing; the API server accepts them whether or not anything enforces them. The Kubernetes
documentation says so directly (source-reviewed): a policy without a controller that implements it "will have no effect".
I observed this. With kind's default CNI on this VM, a default-deny Ingress+Egress policy changed nothing: the client kept reaching
the server 30 seconds later. The CNI's policy controller logged netlink receive: no such file or directory while programming
nftables, which I believe means this kernel lacks an nftables capability it needs. That was a manual experiment, not part of the
scripted run, so it is kept as a labeled one-off
(observation-kindnet-no-enforcement.txt).
On a kernel with full nftables support kindnet may enforce policy; I did not test that.
The lab therefore disables the default CNI, installs Calico v3.33.0 (manifest pinned by SHA-256) and runs scripts/np-smoke.sh
before anything else: the same request must succeed, then time out after a default-deny policy. The orchestrator aborts if
it does not. Every "blocked" result above is conditional on that test having passed (np-smoke.json:
before_policy_reachable: true, after_default_deny_reachable: false).
Existing offline fixtures (kept unchanged)¶
The following is the original content of this README, preserved because the tests that back it still run.
Native Kyverno v1.18.2 testing exercised the hardened-pod policy. The image policy is a schema-validated example; signature, certificate, registry, transparency, mutation, and live admission were not tested.
This lab validates a narrow Kubernetes security baseline with positive and negative fixtures. It does not claim that a namespace, admission policy, or NetworkPolicy is a hard hostile-tenant boundary.
Pinned validation scope¶
- Kubernetes API shapes reviewed for Kubernetes
1.34. - Kyverno CLI
1.18.2. - Kyverno
policies.kyverno.io/v1ValidatingPolicyandImageValidatingPolicy, stable in Kyverno 1.18.
Run the dependency-free structural and identity-policy tests:
node labs/kubernetes-security/tests/run-tests.js
Run the native Kyverno tests:
kyverno test labs/kubernetes-security --remove-color
For a complete copy-and-run setup without an installed CLI, use
bash labs/kubernetes-security/validate-kyverno.sh. The script downloads the pinned
1.18.2 platform archive, compares its SHA-256 with the reviewed release checksum,
runs the seven-case suite and removes its temporary binary. It supports Linux and
macOS ARM64/x86-64 and requires Python, curl and tar. This verifies a checksum,
not the release's Sigstore signature. No cluster is contacted or modified.
On 2026-07-23, the official Kyverno v1.18.2 Windows CLI asset (SHA-256 b5c9d1cb75587a312dc8334537a5773bdedb1a985deae9d89a5251385afb831f) ran the native hardened-pod suite: 7 tests passed and 0 tests failed. This native run does not include verify-release-images.yaml.
Enforcement demonstrated¶
policies/hardened-pods.yaml denies:
- privileged containers and privilege escalation;
- host PID, IPC, or network namespaces;
hostPathvolumes;- added Linux capabilities or failure to drop
ALL; - writable root filesystems;
- missing non-root and seccomp configuration;
- missing CPU/memory requests or limits; and
- service-account token automount unless explicitly disabled.
The accepted Pod is tested alongside privileged, host-namespace, hostPath, capability, missing-resource, and token-automount negative fixtures.
policies/verify-release-images.yaml uses the stable Kyverno 1.18 policies.kyverno.io/v1 ImageValidatingPolicy. It constrains repository, keyless issuer, full workflow-and-branch subject, SLSA provenance predicate type, required verification, digest verification, and failurePolicy: Fail. Separate :* and @sha256:* globs make tagged and digest references to the exact repository eligible for evaluation while excluding lookalike repositories.
On 2026-07-23, the manifest conformed to Kyverno v1.18.2's official ImageValidatingPolicy CRD v1 schema. The downloaded CRD asset SHA-256 was 3528151f3717c9946ee56d60866f2cf6c29a4b1a7e759c72af60451147b995c2. The Node harness separately evaluates eleven synthetic, already-resolved evidence claim sets. It returns false for unsigned, wrong repository/workflow/branch/issuer/predicate, missing or malformed provenance, verifier/transparency failure, and digest mismatch.
The twelfth case proves only that a tag such as :latest matches the reviewed tag selector. Its admission result is deliberately null: the harness does not model registry resolution or Kyverno's mutateDigest behavior and therefore makes no accept/deny claim for tag-only input. This is a schema-validated example; no live enforcement test. Signature, certificate, registry, transparency-log, mutation, webhook failure, and controller behavior were not executed.
Network boundary¶
fixtures/network-policies.yaml contains namespace-wide default-deny ingress and egress plus an explicit DNS exception. NetworkPolicy has an effect only when the selected CNI implements it. DNS labels, ports, node-local DNS paths, dual-stack behavior, and required application egress must be verified in each cluster. NetworkPolicy does not control all host-network, node, service-mesh, or cloud-network paths.
Operational rollout¶
Use observe → audit → warn → enforce → measure bypasses. Track policy evaluation errors, denials, exceptions and expiry, unsigned-image attempts, registry/rekor availability, admission latency, and workloads that require a separate runtime class or cluster. Keep a reviewed break-glass path outside tenant administrator control.
Validation¶
Environment of the recorded live run (evidence/versions.txt): kernel 6.18.44 (cgroup v1), kind v0.33.0, node image
kindest/node:v1.37.0 (containerd 2.3.4), kubectl v1.37.0, Calico v3.33.0, Kyverno CLI 1.18.2, OPA 1.22.0, kubeconform v0.8.0.
npm ci --ignore-scripts
node labs/kubernetes-security/tests/run-tests.js # existing decision-model tests
node --test labs/kubernetes-security/tests/manifests.test.js # 16 structural tests, no cluster
kyverno test labs/kubernetes-security --remove-color # 23 tests: 7 existing + 16 new, offline
opa test labs/kubernetes-security/policies/rego # 12 unit tests
bash labs/kubernetes-security/scripts/run-cluster-lab.sh # live: creates and deletes a kind cluster
Observed on the recorded run:
| Check | Result |
|---|---|
manifests.test.js |
16 passed |
kyverno test |
23 passed, 0 failed (the 16-case corpus plus the 7 existing cases) |
opa test |
12 of 12 |
OPA over baseline/ plus fixtures |
35 violations across 15 rules (privileged, hostPath, host namespaces, root, seccomp, limits, PSA, default-deny, RBAC secrets/exec/bindings, token) |
OPA over hardened/ |
0 violations |
| kubeconform, Kubernetes 1.37.0 schemas, strict | 45 resources, 45 valid, 0 skipped |
Live assertions (tests/cluster_check.py) |
83 passed, 0 failed |
The live run took 2 min 21 s from nothing to deletion. run-cluster-lab.sh deletes the cluster on exit; --keep-cluster and
--use-existing exist for iteration, and --use-existing resets the lab namespaces first.
Two facts about the sandbox the run needed, both recorded as one-offs in
observation-sandbox-kubelet-failures.txt:
the kubelet refused to start on cgroup v1 (failCgroupV1: false fixes it), and runc could not lower oom_score_adj because the VM's
capability bounding set lacks CAP_SYS_RESOURCE (containerd restrict_oom_score_adj fixes it; the capability is documented in
capabilities(7), source-reviewed). cluster/up.sh selects kind-config.compat.yaml automatically when it detects either condition.
On a cgroup v2 workstation the portable config is used.
What was not tested¶
- A multi-node cluster, scheduling constraints, node-to-node policy paths, and NetworkPolicy behaviour across nodes.
- Kyverno or OPA Gatekeeper running as live admission controllers. Both ran offline only. Webhook latency,
failurePolicybehaviour under outage, background scans and exceptions were not exercised. The ValidatingAdmissionPolicy is the only non-PSA live admission control. - Signed-image admission. The
ImageValidatingPolicyand its model are unchanged; no signature was verified in a cluster. - Other CNIs, and kindnet on a kernel where it works,
NetworkPolicyfeatures beyond L3/L4 allow rules (named ports, SCTP,endPort, FQDN or L7 policy), IPv6, and egress to cloud metadata endpoints. - API-server audit logging. The
Auditaction on the VAP binding was set but no audit sink was configured, so I cannot show the records. - Token theft and replay. The lab shows what an identity can do; it does not test token exfiltration,
TokenReviewof a deleted pod's token, or revocation timing. - Pod Security Admission exemptions and cluster-wide defaults (an
AdmissionConfiguration), and PSA at versions other thanv1.37. - seccomp
Localhostprofiles (the Docker lab's profile on a node). The hardened pods useRuntimeDefault. - Cloud-managed Kubernetes (EKS, AKS, GKE) and their identity federation. Nothing here contacts a cloud provider.
- Hosted CI.
run-cluster-lab.shis not part of any workflow. - Measured time to detect, time to contain, false-positive rates over real workloads, and cost are not measured in this lab.
Production considerations¶
Rollout. Do not turn on enforce first. For PSA: warn and audit at restricted per namespace, read the warnings for a
release cycle, fix or exempt, then enforce; keep the version label pinned and bump it deliberately after a cluster upgrade. For a
ValidatingAdmissionPolicy: bind with Warn or Audit before Deny. For RBAC: start from what the workload was observed to call, not from a
built-in role. For NetworkPolicy: introduce default-deny last per namespace, after the allow rules for DNS and the real dependencies are in
place and tested; the failure mode is a silent timeout.
False positives. Observed here: the Kyverno policy rejecting pod-level runAsNonRoot; offline engines denying a pod whose
ServiceAccount already disables the token. Expected in practice: :latest and digest-only references tripping naive tag rules,
init containers and sidecars with legitimate NET_BIND_SERVICE or NET_ADMIN, and operators that need hostPath. Give exceptions an
owner and an expiry; the allow-list is where the policy is actually decided.
Detection. The denial is the signal, but only if you collect it: a rejected Pod created by a controller appears as a
FailedCreate event on the ReplicaSet, not at kubectl apply. Alert on those events, on new ClusterRoleBindings, on pods/exec use,
and on any pod that projects a token. I did not test an audit pipeline or a runtime sensor here.
Operability. failurePolicy: Fail is correct for a security control and an outage for the control plane if the policy cannot be
evaluated; the built-in VAP removes a webhook as a failure domain, which is its main operational advantage over a webhook engine.
Default-deny egress needs DNS and API-server rules that depend on the CNI's view of the destination (Calico matched the post-DNAT node
IP, so the policy needed the endpoint address); re-check after control-plane changes. Short-lived projected tokens are refreshed by the kubelet,
so applications must re-read the file.
Blast radius. A namespace is a policy scope, not an isolation boundary: pods share the node kernel, and the controls above shrink what a compromised pod can reach, not whether a kernel bug is exploitable. For hostile tenants, add a sandboxed runtime or separate clusters.
Rollback. Everything is declarative. Remove the VAP binding or set its action back to Warn, relabel the namespace to warn, or delete
the NetworkPolicy. Do not roll back by granting a broader role to make a deploy work; that is how the baseline was created.
Teardown and resources¶
run-cluster-lab.sh deletes the cluster on exit and removes nothing else. Docker images, the base-image cache and Node dependencies remain.
Resource cost is local only: about 2 min 21 s of wall time and one kind node on a 4-CPU, 16 GiB VM; no measured cloud cost.
Reproducibility and threat-model audit — 2026-11-02¶
| Element | Bounded experiment |
|---|---|
| Actor | Tenant controlling workload spec or image evidence |
| Assets | node isolation, service account and verified image decisions |
| Entry points | pod manifest, image reference and network policy |
| Boundary | Fixture input → native admission policy or local image model → expected result |
| Safety | Owned synthetic fixtures; no production data or cloud credentials; no cloud deployment |
flowchart LR
I[Controlled input] --> B[Tested boundary]
B --> A[Expected allowed case]
B --> D[Expected denied case]
A --> E[Assertions and sanitized evidence]
D --> E
Complete local setup¶
Use a fresh repository checkout and the prerequisites above. From repository root:
npm ci --ignore-scripts
node labs/kubernetes-security/tests/run-tests.js
kyverno test labs/kubernetes-security --remove-color
Native policy testing needs Kyverno CLI 1.18.2; the dependency-free structural check can run without it. The complete policy and pod/network manifests are tracked beside this README. No existing cluster is used or modified.
This is a local decision experiment, so the complete implementation is its tracked code, fixtures and policy files. It needs no Terraform deployment, service account or publicly exposed server. Never relocate fixture workflows into an active CI directory without a separate environment review.
Evidence, expected output and interpretation¶
The documented command exits zero only when its assertions pass; an unexpected
allow/deny, schema or state result is a failure. Preserve the full command output
under ignored .artifacts/research/ with runtime/tool versions and exit status.
Use the specific expected markers above rather than inventing example output.
The lab audit records the validation run.
Native CLI pod-policy tests do not prove live cluster admission, signature verification, image mutation or CNI packet enforcement. Local finite-case coverage is not a production false-positive or false-negative estimate. TTD/TTC, representative pipeline overhead and monthly cloud cost are not measured in this lab.
Teardown and resources¶
The processes exit and remove their temporary test files. There is no cloud destroy command. Retained evidence, optional provider downloads and local Docker image cache are your only persistent outputs; remove them after review. Node dependencies can remain for subsequent runs.
Local CPU, memory, dependency downloads and optional image disk space are the resource cost. There is no measured cloud bill. Related research links above define which claims the experiment supports.
References¶
Existing references (kept):
- Kyverno v1.18.2 release and official CRD/CLI assets
- Kyverno policy type lifecycle
- Kyverno ImageValidatingPolicy
- Kubernetes Pod Security Standards
- Kubernetes ValidatingAdmissionPolicy
- Kubernetes NetworkPolicy
- Kubernetes service-account token projection
Added, and only sources consulted while building this extension (documentation cited at its source repository; the project sites were not reachable from the build environment):
- Kubernetes documentation source: Pod Security Admission (enforce applies to Pods, not workload resources) and Pod Security Standards.
- Kubernetes documentation source: RBAC reference (additive permissions; privilege escalation prevention) and RBAC good practices.
- Kubernetes documentation source: Network Policies (no effect without an implementing controller) and Service Accounts (TokenRequest, projected, rotating tokens).
- Kubernetes documentation source: ValidatingAdmissionPolicy.
- Linux man-pages, capabilities(7):
CAP_SYS_RESOURCEandoom_score_adj. - Tool versions: each tool's own
versionoutput, recorded inevidence/versions.txt. The Calico v3.33.0 manifest was fetched from the project repository and verified against the SHA-256 recorded incluster/calico.sha256(integrity of the file, not a signature check).