Skip to content
Français
Account: not signed in, sync available My learning
Select theme
Français

CKS exercises: timed security practice

By updated

Improve this page

Logo Kubernetes

These exercises train the hardening gestures the CKS asks for: network isolation, RBAC, Pod hardening, supply chain, audit and admission. The 26 exercises run on an ordinary test cluster, except three that need root access to a node. The section "Practicing the objectives that need a prepared environment" points to the lessons and their labs for the objectives that require a tool, a registry or a service mesh. Time yourself and aim for 80% success. A hands-on mock exam of 16 tasks in 120 minutes follows the capstone, to check that you can keep the pace of the real exam.

CKS reflexes

Set up your environment before you start. These shortcuts come from the Session shortcuts section of the cheat sheet, with two practical additions: the kgp alias lists the Pods of the current namespace, and the now variable bundles the --force --grace-period=0 options, which delete a Pod without waiting for its grace period:

Terminal window
# Essential aliases
alias k=kubectl
alias kn='kubectl config set-context --current --namespace'
alias kgp='kubectl get pods'
export do="--dry-run=client -o yaml"
export now="--force --grace-period=0"
# Autocompletion
source <(kubectl completion bash)
complete -F __start_kubectl k
# Working namespace
kubectl create ns cks-exercises
kn cks-exercises

Block 1, core CKS exam tasks (15 exercises)

These exercises cover the universal tasks of the CKS, which you can do in any Kubernetes cluster.


Exercise 1: NetworkPolicy Deny All

Target time: 4 minutes

ContextNamespace cks-exercises
TaskCreate a NetworkPolicy deny-all that blocks all ingress and egress traffic for every Pod in the namespace
Validationkubectl describe netpol deny-all shows podSelector: {} and policyTypes: [Ingress, Egress]
Solution
Terminal window
kubectl apply -f - <<'EOF'
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: deny-all
namespace: cks-exercises
spec:
podSelector: {}
policyTypes:
- Ingress
- Egress
EOF
# Validation
kubectl get netpol deny-all -n cks-exercises
kubectl describe netpol deny-all -n cks-exercises

The podSelector: {} selector picks every Pod in the namespace, and with no ingress or egress rule, everything is blocked by default.


Exercise 2: NetworkPolicy Allow Specific (with a Service)

Target time: 6 minutes

ContextNamespace cks-exercises, ingress denied by default (ingress-only deny-all)
TaskCreate a Deployment api (nginx:1.30.5, label app=api), a Service api-svc on port 80, and a NetworkPolicy allow-frontend that only lets the app=frontend Pods reach the Service
Validationkubectl exec frontend -- wget -qO- --timeout=2 api-svc succeeds, kubectl exec other -- wget ... fails
Solution
Terminal window
# The deny-all of exercise 1 also blocks egress, DNS included: replace it with its ingress-only version
kubectl delete netpol deny-all -n cks-exercises --ignore-not-found
kubectl apply -f - <<'EOF'
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: deny-all-ingress
namespace: cks-exercises
spec:
podSelector: {}
policyTypes:
- Ingress
EOF
# Deployment api with an explicit label
kubectl create deploy api --image=nginx:1.30.5@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edb -n cks-exercises
kubectl label deploy api -n cks-exercises app=api
kubectl patch deploy api -n cks-exercises -p '{"spec":{"template":{"metadata":{"labels":{"app":"api"}}}}}'
# Service in front of api
kubectl expose deploy api --port=80 --name=api-svc -n cks-exercises
# NetworkPolicy allowing frontend to reach api
kubectl apply -f - <<'EOF'
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-frontend
namespace: cks-exercises
spec:
podSelector:
matchLabels:
app: api
policyTypes:
- Ingress
ingress:
- from:
- podSelector:
matchLabels:
app: frontend
ports:
- protocol: TCP
port: 80
EOF
# Test Pods
kubectl run frontend --image=busybox:1.37@sha256:a7dbc319b1438115a207e11930dc4bb3e643dcb3ec0bdd694bb36cd8fad289ec --labels="app=frontend" -n cks-exercises -- sleep 3600
kubectl run other --image=busybox:1.37@sha256:a7dbc319b1438115a207e11930dc4bb3e643dcb3ec0bdd694bb36cd8fad289ec -n cks-exercises -- sleep 3600
# Validation (wait for the Pods to be Running)
kubectl exec frontend -n cks-exercises -- wget -qO- --timeout=2 api-svc
# must succeed: frontend's egress is not restricted
kubectl exec other -n cks-exercises -- wget -qO- --timeout=2 api-svc 2>&1
# must time out

The allow-frontend NetworkPolicy opens an exception to the default deny, for inbound traffic to the app=api Pods only. NetworkPolicies are additive: a flow allowed by one policy goes through, even if another policy denies everything else.


Exercise 3: Read-only RBAC

Target time: 5 minutes

ContextNamespace cks-exercises
TaskCreate a ServiceAccount readonly-sa, a Role pod-reader (get, list on pods), and bind the two together
Validationkubectl auth can-i list pods -n cks-exercises --as=system:serviceaccount:cks-exercises:readonly-sa returns yes, delete returns no
Solution
Terminal window
# ServiceAccount
kubectl create sa readonly-sa -n cks-exercises
# Role
kubectl create role pod-reader \
--verb=get,list \
--resource=pods \
-n cks-exercises
# RoleBinding
kubectl create rolebinding readonly-binding \
--role=pod-reader \
--serviceaccount=cks-exercises:readonly-sa \
-n cks-exercises
# Validation
kubectl auth can-i list pods -n cks-exercises \
--as=system:serviceaccount:cks-exercises:readonly-sa
# yes
kubectl auth can-i delete pods -n cks-exercises \
--as=system:serviceaccount:cks-exercises:readonly-sa
# no
kubectl auth can-i list secrets -n cks-exercises \
--as=system:serviceaccount:cks-exercises:readonly-sa
# no

Exercise 4: Disable the automounted token

Target time: 4 minutes

ContextServiceAccount readonly-sa already created
TaskCreate a Pod no-token-pod (nginx:1.30.5) that uses readonly-sa with automountServiceAccountToken: false
Validationkubectl exec no-token-pod -- ls /var/run/secrets/kubernetes.io/serviceaccount returns "No such file"
Solution
Terminal window
kubectl apply -f - <<'EOF'
apiVersion: v1
kind: Pod
metadata:
name: no-token-pod
namespace: cks-exercises
spec:
serviceAccountName: readonly-sa
automountServiceAccountToken: false
containers:
- name: nginx
image: nginx:1.30.5@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edb
EOF
# Validation
kubectl exec no-token-pod -n cks-exercises -- ls /var/run/secrets/kubernetes.io/serviceaccount 2>&1
# No such file or directory
# Double-check in the YAML
kubectl get pod no-token-pod -n cks-exercises -o yaml | grep automount

Exercise 5: Complete restrictive SecurityContext

Target time: 6 minutes

ContextNamespace cks-exercises
TaskCreate a Pod hardened-pod (nginx:1.30.5) with: runAsNonRoot, runAsUser 1000, allowPrivilegeEscalation false, readOnlyRootFilesystem true, capabilities drop ALL
Constraintnginx needs emptyDir volumes for /tmp, /var/cache/nginx, /var/run
Validationkubectl exec hardened-pod -- id returns uid=1000, the Pod is Running
Solution
Terminal window
kubectl apply -f - <<'EOF'
apiVersion: v1
kind: Pod
metadata:
name: hardened-pod
namespace: cks-exercises
spec:
securityContext:
runAsNonRoot: true
runAsUser: 1000
runAsGroup: 1000
containers:
- name: nginx
image: nginx:1.30.5@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edb
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop:
- ALL
volumeMounts:
- name: tmp
mountPath: /tmp
- name: cache
mountPath: /var/cache/nginx
- name: run
mountPath: /var/run
volumes:
- name: tmp
emptyDir: {}
- name: cache
emptyDir: {}
- name: run
emptyDir: {}
EOF
# Validation
kubectl get pod hardened-pod -n cks-exercises
kubectl exec hardened-pod -n cks-exercises -- id
# uid=1000 gid=1000

With readOnlyRootFilesystem: true, an image like nginx needs writable volumes for its working directories, otherwise it does not start.


Exercise 6: Seccomp RuntimeDefault

Target time: 3 minutes

ContextNamespace cks-exercises
TaskCreate a Pod seccomp-pod (nginx:1.30.5) with the RuntimeDefault Seccomp profile
Validationkubectl get pod seccomp-pod -o jsonpath='{.spec.securityContext.seccompProfile.type}' returns RuntimeDefault
Solution
Terminal window
kubectl apply -f - <<'EOF'
apiVersion: v1
kind: Pod
metadata:
name: seccomp-pod
namespace: cks-exercises
spec:
securityContext:
seccompProfile:
type: RuntimeDefault
containers:
- name: nginx
image: nginx:1.30.5@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edb
EOF
# Validation
kubectl get pod seccomp-pod -n cks-exercises -o jsonpath='{.spec.securityContext.seccompProfile.type}'
# RuntimeDefault

Exercise 7: Pod Security Admission, restricted

Target time: 5 minutes

ContextNew namespace psa-test
TaskCreate a namespace psa-test with PSA enforce=restricted (version latest), then test it with a non-compliant Pod and a compliant Pod
ValidationThe non-compliant Pod is rejected, the compliant Pod starts
Solution
Terminal window
# Create the namespace with PSA
kubectl create ns psa-test
kubectl label namespace psa-test \
pod-security.kubernetes.io/enforce=restricted \
pod-security.kubernetes.io/enforce-version=latest
# Check the labels
kubectl get ns psa-test --show-labels
# Test a non-compliant Pod
kubectl run non-compliant --image=nginx:1.30.5@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edb -n psa-test 2>&1
# Error from server (Forbidden): violates PodSecurity "restricted:latest"
# Compliant Pod (every restricted criterion)
kubectl apply -f - <<'EOF'
apiVersion: v1
kind: Pod
metadata:
name: compliant-pod
namespace: psa-test
spec:
securityContext:
runAsNonRoot: true
runAsUser: 1000
seccompProfile:
type: RuntimeDefault
containers:
- name: app
image: busybox:1.37@sha256:a7dbc319b1438115a207e11930dc4bb3e643dcb3ec0bdd694bb36cd8fad289ec
command: ['sh', '-c', 'sleep 3600']
securityContext:
allowPrivilegeEscalation: false
capabilities:
drop: ["ALL"]
EOF
# Validation
kubectl get pod compliant-pod -n psa-test

The restricted level requires runAsNonRoot, a seccompProfile, capabilities.drop: ["ALL"] and allowPrivilegeEscalation: false.

The enforce-version label chooses which version of the Pod Security Standards is applied. With latest, the namespace follows the cluster version: it is the right setting as long as you want the current rules. Pinning a version, for example v1.37, freezes the rules at that version and prevents a cluster upgrade from suddenly rejecting Pods that passed the day before.


Exercise 8: Secret as a read-only volume

Target time: 4 minutes

ContextNamespace cks-exercises
TaskCreate a Secret app-secret (API_KEY=secret123), then a Pod secret-pod (busybox:1.37) that mounts this Secret in /etc/secrets read-only
Validationkubectl exec secret-pod -- cat /etc/secrets/API_KEY returns secret123, writing is impossible
Solution
Terminal window
# Create the Secret
kubectl create secret generic app-secret \
--from-literal=API_KEY=secret123 \
-n cks-exercises
# Pod with a read-only mount
kubectl apply -f - <<'EOF'
apiVersion: v1
kind: Pod
metadata:
name: secret-pod
namespace: cks-exercises
spec:
containers:
- name: app
image: busybox:1.37@sha256:a7dbc319b1438115a207e11930dc4bb3e643dcb3ec0bdd694bb36cd8fad289ec
command: ['sh', '-c', 'cat /etc/secrets/API_KEY && sleep 3600']
volumeMounts:
- name: secrets
mountPath: /etc/secrets
readOnly: true
volumes:
- name: secrets
secret:
secretName: app-secret
EOF
# Validation
kubectl exec secret-pod -n cks-exercises -- cat /etc/secrets/API_KEY
# secret123
kubectl exec secret-pod -n cks-exercises -- touch /etc/secrets/test 2>&1
# Read-only file system

Exercise 9: Identify privileged Pods

Target time: 5 minutes

ContextWhole cluster
TaskList every Pod in the cluster that has privileged: true or allowPrivilegeEscalation: true
ValidationA working command that returns namespace/pod
Solution
Terminal window
# Pods with privileged: true
kubectl get pods -A -o json | jq -r '
.items[] |
select(
.spec.containers[]?.securityContext?.privileged == true
) |
"\(.metadata.namespace)/\(.metadata.name)"
'
# Pods with a container that does not forbid privilege escalation (missing field = allowed)
kubectl get pods -A -o json | jq -r '
.items[] |
select(
.spec.containers[]?.securityContext?.allowPrivilegeEscalation != false
) |
"\(.metadata.namespace)/\(.metadata.name)"
' | sort -u

In jq, a missing field is null. That is why allowPrivilegeEscalation != false also catches the containers that did not declare the field, whereas Kubernetes allows it by default.


Exercise 10: Image pinned by digest

Target time: 5 minutes

ContextNamespace cks-exercises
TaskGet the SHA256 digest of nginx:1.30.5, then create a Pod pinned-pod that uses the image with that digest
Validationkubectl get pod pinned-pod -o jsonpath='{.spec.containers[0].image}' contains @sha256:
Solution
Terminal window
# Get the digest (several methods depending on the available tools)
# Option 1: read the imageID of a running Pod
kubectl run digest-check --image=nginx:1.30.5 --restart=Never -n cks-exercises
kubectl get pod digest-check -n cks-exercises -o jsonpath='{.status.containerStatuses[0].imageID}'
# Option 2: crane (if installed)
crane digest nginx:1.30.5
# Option 3: skopeo (if installed)
skopeo inspect docker://nginx:1.30.5 | jq -r '.Digest'
# Option 4: docker pull + inspect
docker pull nginx:1.30.5
docker inspect nginx:1.30.5 --format='{{index .RepoDigests 0}}'
# Digest of nginx:1.30.5 used throughout this page, usable as is.
# Yours will differ if the tag has been republished since: that is the whole point.
# nginx@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edb
kubectl apply -f - <<'EOF'
apiVersion: v1
kind: Pod
metadata:
name: pinned-pod
namespace: cks-exercises
spec:
containers:
- name: nginx
# Replace with the digest you just obtained
image: nginx:1.30.5@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edb
EOF
# Validation
kubectl get pod pinned-pod -n cks-exercises -o jsonpath='{.spec.containers[0].image}'
# Must contain @sha256:

A digest always designates the same content, whereas a tag can be reassigned to another image.


Exercise 11: Identify non-immutable images

Target time: 5 minutes

ContextWhole cluster
TaskList every image in the cluster that uses the :latest tag or no tag at all (so implicitly latest)
ValidationA working command that returns namespace/pod: image
Solution
Terminal window
# Images with :latest or without a tag
kubectl get pods -A -o json | jq -r '
.items[] |
. as $pod |
.spec.containers[] |
select(.image | (test(":latest$") or (test(":") | not))) |
"\($pod.metadata.namespace)/\($pod.metadata.name): \(.image)"
'
# Alternative that includes initContainers too
kubectl get pods -A -o json | jq -r '
.items[] |
. as $pod |
(.spec.containers + (.spec.initContainers // []))[] |
select(.image | (test(":latest$") or (test(":") | not))) |
"\($pod.metadata.namespace)/\($pod.metadata.name): \(.image)"
' | sort -u

These images carry a drift risk: their content can change without the manifest changing. Prefer versioned tags, or better, digests.


Exercise 12: Secure an existing Pod

Target time: 8 minutes

ContextPod insecure-app with security problems
TaskIdentify the problems and create a secured version secure-app
Validationkubectl get pod secure-app is Running, every restrictive SecurityContext setting applied

Create the problematic Pod first:

Terminal window
kubectl apply -f - <<'EOF'
apiVersion: v1
kind: Pod
metadata:
name: insecure-app
namespace: cks-exercises
spec:
containers:
- name: app
image: nginx:1.30.5@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edb
securityContext:
privileged: true
EOF
Solution

Problems identified:

  1. privileged: true, almost every right of the node
  2. No allowPrivilegeEscalation: false, privilege escalation is still allowed
  3. No runAsNonRoot
  4. No readOnlyRootFilesystem
  5. Capabilities not dropped
  6. No Seccomp profile

Secured version:

Terminal window
kubectl apply -f - <<'EOF'
apiVersion: v1
kind: Pod
metadata:
name: secure-app
namespace: cks-exercises
spec:
securityContext:
runAsNonRoot: true
runAsUser: 1000
runAsGroup: 1000
seccompProfile:
type: RuntimeDefault
containers:
- name: app
image: nginx:1.30.5@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edb
securityContext:
privileged: false
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop:
- ALL
volumeMounts:
- name: tmp
mountPath: /tmp
- name: cache
mountPath: /var/cache/nginx
- name: run
mountPath: /var/run
volumes:
- name: tmp
emptyDir: {}
- name: cache
emptyDir: {}
- name: run
emptyDir: {}
EOF
# Validation
kubectl get pod secure-app -n cks-exercises
kubectl get pod secure-app -n cks-exercises -o jsonpath='{.spec.securityContext}'

Exercise 13: Complete namespace isolation

Target time: 10 minutes

ContextNew namespace production
TaskCreate production with: (1) PSA restricted enforced, (2) a deny-all NetworkPolicy, (3) a SA app-sa without automount, (4) a Role that reads ConfigMaps, (5) a compliant Pod that uses this SA
Validationkubectl auth can-i list configmaps -n production --as=system:serviceaccount:production:app-sa = yes, secrets = no
Solution
Terminal window
# 1. Namespace with PSA
kubectl create ns production
kubectl label namespace production \
pod-security.kubernetes.io/enforce=restricted \
pod-security.kubernetes.io/enforce-version=latest
# 2. NetworkPolicy deny-all
kubectl apply -f - <<'EOF'
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: deny-all
namespace: production
spec:
podSelector: {}
policyTypes:
- Ingress
- Egress
EOF
# 3. ServiceAccount without automount
kubectl create sa app-sa -n production
kubectl patch sa app-sa -n production -p '{"automountServiceAccountToken": false}'
# 4. ConfigMap reader Role + binding
kubectl create role configmap-reader \
--verb=get,list \
--resource=configmaps \
-n production
kubectl create rolebinding app-configmap-binding \
--role=configmap-reader \
--serviceaccount=production:app-sa \
-n production
# 5. Pod compliant with PSA restricted
kubectl apply -f - <<'EOF'
apiVersion: v1
kind: Pod
metadata:
name: prod-app
namespace: production
spec:
serviceAccountName: app-sa
automountServiceAccountToken: false
securityContext:
runAsNonRoot: true
runAsUser: 1000
seccompProfile:
type: RuntimeDefault
containers:
- name: app
image: busybox:1.37@sha256:a7dbc319b1438115a207e11930dc4bb3e643dcb3ec0bdd694bb36cd8fad289ec
command: ['sh', '-c', 'sleep 3600']
securityContext:
allowPrivilegeEscalation: false
capabilities:
drop: ["ALL"]
EOF
# Validation
kubectl get ns production --show-labels
kubectl get netpol -n production
kubectl auth can-i list configmaps -n production --as=system:serviceaccount:production:app-sa
# yes
kubectl auth can-i list secrets -n production --as=system:serviceaccount:production:app-sa
# no
kubectl get pod prod-app -n production

Exercise 14: TLS Ingress (with a backend)

Target time: 6 minutes

ContextNamespace cks-exercises
TaskCreate a Deployment web (nginx:1.30.5), a Service web-svc, a self-signed TLS Secret for secure.example.com, and an Ingress that uses this Secret
Validationkubectl describe ingress secure-ingress shows the TLS configuration
Solution
Terminal window
# Backend
kubectl create deploy web --image=nginx:1.30.5@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edb -n cks-exercises
kubectl expose deploy web --port=80 --name=web-svc -n cks-exercises
# Self-signed certificate
openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
-keyout /tmp/tls.key -out /tmp/tls.crt \
-subj "/CN=secure.example.com"
# TLS Secret
kubectl create secret tls secure-tls \
--cert=/tmp/tls.crt \
--key=/tmp/tls.key \
-n cks-exercises
# Ingress
kubectl apply -f - <<'EOF'
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: secure-ingress
namespace: cks-exercises
spec:
ingressClassName: nginx
tls:
- hosts:
- secure.example.com
secretName: secure-tls
rules:
- host: secure.example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: web-svc
port:
number: 80
EOF
# Validation
kubectl describe ingress secure-ingress -n cks-exercises | grep -A3 TLS
# Clean up the temporary files
rm /tmp/tls.key /tmp/tls.crt

Exercise 15: Identify cluster-admin ClusterRoleBindings

Target time: 5 minutes

ContextWhole cluster
TaskList every ServiceAccount bound by a ClusterRoleBinding to cluster-admin
ValidationA command that returns namespace/sa
Solution
Terminal window
# Method 1: full jq
kubectl get clusterrolebindings -o json | jq -r '
.items[] |
select(.roleRef.name == "cluster-admin") |
.subjects[]? |
select(.kind == "ServiceAccount") |
"\(.namespace)/\(.name)"
'
# Method 2: simple grep for a quick check
kubectl get clusterrolebindings -o wide | grep cluster-admin
# Method 3: detail per binding
kubectl get clusterrolebindings -o json | jq -r '
.items[] |
select(.roleRef.name == "cluster-admin") |
"Binding: \(.metadata.name)\nSubjects: \(.subjects // [] | map("\(.kind)/\(.namespace // "cluster")/\(.name)") | join(", "))\n"
'

A ServiceAccount bound to cluster-admin has all rights over the whole cluster: audit this list regularly.


Block 2, Tools and audit (3 exercises)

These exercises need additional tools. They are less universal but relevant to your preparation.


Exercise 16: Scan an image with Trivy

Target time: 4 minutes

ContextTrivy installed
TaskScan nginx:1.24 and list the CRITICAL and HIGH vulnerabilities
ValidationTrivy output with a table of vulnerabilities
Solution
Terminal window
# Scan with a severity filter
trivy image --severity HIGH,CRITICAL nginx:1.24@sha256:f6daac2445b0ce70e64d77442ccf62839f3f1b4c24bf6746a857eff014e798c8
# Same scan, with the table format made explicit
trivy image --severity HIGH,CRITICAL --format table nginx:1.24@sha256:f6daac2445b0ce70e64d77442ccf62839f3f1b4c24bf6746a857eff014e798c8
# Count the vulnerabilities (careful: results vary with the date)
trivy image --severity CRITICAL --format json nginx:1.24@sha256:f6daac2445b0ce70e64d77442ccf62839f3f1b4c24bf6746a857eff014e798c8 | jq '[.Results[]?.Vulnerabilities // [] | length] | add'

The number of vulnerabilities varies with the CVE database of the day: the goal is to know how to use Trivy, not to get an exact count.


Exercise 17: Analyze the Kubernetes audit logs

Target time: 6 minutes

ContextAccess to the control plane audit logs
TaskFilter the Secret creations of the last 10 minutes, with the associated user
ConstraintThe exercise depends on a cluster with audit logs enabled (typical path: /var/log/kubernetes/audit/audit.log)
ValidationA timestamp/user/namespace/secret list
Solution
Terminal window
# On the control plane (ssh if needed)
AUDIT_LOG="/var/log/kubernetes/audit/audit.log"
# Check that the file exists
ls -la $AUDIT_LOG
# Filter Secret creations
cat $AUDIT_LOG | jq -r '
select(
.verb == "create" and
.objectRef.resource == "secrets"
) |
{
timestamp: .requestReceivedTimestamp,
user: .user.username,
namespace: .objectRef.namespace,
name: .objectRef.name
}
'
# With a time filter (last 10 minutes)
# The log timestamps in UTC: compare with a UTC time
SINCE=$(date -u -d "10 minutes ago" +%Y-%m-%dT%H:%M:%SZ 2>/dev/null || date -u -v-10M +%Y-%m-%dT%H:%M:%SZ)
cat $AUDIT_LOG | jq --arg since "$SINCE" -r '
select(
.verb == "create" and
.objectRef.resource == "secrets" and
.requestReceivedTimestamp >= $since
) |
"\(.requestReceivedTimestamp) \(.user.username) \(.objectRef.namespace)/\(.objectRef.name)"
'

These filters only return a result if auditing is configured on the API server (see exercise 22), and the log path varies with the installation.


Exercise 18: Simplified security audit

Target time: 8 minutes

ContextNamespace cks-exercises with several Pods
TaskProduce a list of the Pods without a restrictive SecurityContext (privileged, no readOnlyRootFilesystem, allowPrivilegeEscalation true)
ValidationA namespace/pod list with the problem identified
Solution
Terminal window
NS="cks-exercises"
echo "=== Pods without a restrictive SecurityContext in $NS ==="
# Privileged Pods
echo "-- Privileged:"
kubectl get pods -n $NS -o json | jq -r '
.items[] |
select(.spec.containers[]?.securityContext?.privileged == true) |
.metadata.name
'
# Pods without readOnlyRootFilesystem
echo "-- Without readOnlyRootFilesystem:"
kubectl get pods -n $NS -o json | jq -r '
.items[] |
select(.spec.containers[]?.securityContext?.readOnlyRootFilesystem != true) |
.metadata.name
' | sort -u
# Pods with allowPrivilegeEscalation (explicit or implicit)
echo "-- With allowPrivilegeEscalation possible:"
kubectl get pods -n $NS -o json | jq -r '
.items[] |
select(.spec.containers[]?.securityContext?.allowPrivilegeEscalation != false) |
.metadata.name
' | sort -u
# NetworkPolicies in place
echo ""
echo "=== Active NetworkPolicies ==="
kubectl get netpol -n $NS

Block 3, Advanced runtime (2 bonus exercises)

These exercises are more specialized and depend on the environment: audit logs enabled, kube-bench installed. Useful to go deeper, lower priority than block 1.


Exercise 19: Shell detection with audit logs (without Falco)

Target time: 5 minutes

ContextAudit logs enabled
TaskUse the audit logs to detect kubectl exec calls into Pods
ValidationFind the recent exec calls in the logs
Solution
Terminal window
# Filter the exec calls in the audit logs
cat /var/log/kubernetes/audit/audit.log | jq -r '
select(
.verb == "create" and
.objectRef.subresource == "exec"
) |
"\(.requestReceivedTimestamp) \(.user.username) exec into \(.objectRef.namespace)/\(.objectRef.name)"
'
# Alternative: if responseStatus is logged
cat /var/log/kubernetes/audit/audit.log | jq -r '
select(.objectRef.subresource == "exec") |
"\(.requestReceivedTimestamp) \(.verb) \(.user.username) → \(.objectRef.namespace)/\(.objectRef.name)"
'

Falco can also detect an exec, but the audit logs are enough once they are configured.


Exercise 20: kube-bench check (analysis)

Target time: 6 minutes

Contextkube-bench installed, control plane access
TaskRun kube-bench on the control plane and identify the FAIL checks of section 1.1 (control plane configuration files)
ValidationA list of the FAIL checks with their IDs
Solution
Terminal window
# Run kube-bench (on the control plane)
kube-bench run --targets master
# Filter section 1.1
kube-bench run --targets master --group 1.1 2>/dev/null | grep -E "^\[(FAIL|WARN)\]"
# Example output:
# [FAIL] 1.1.1 Ensure that the API server pod specification file permissions are set to 600 or more restrictive
# [FAIL] 1.1.2 Ensure that the API server pod specification file ownership is set to root:root
# Manual check of one control
ls -la /etc/kubernetes/manifests/kube-apiserver.yaml

Apply kube-bench remediations with discernment: some can break the cluster. This exercise is about analysis, not automatic correction.


Block 4, Curriculum objectives without third-party tools (6 exercises)

These six exercises cover CKS curriculum objectives that the first twenty do not train, and that you can practice without third-party tools: AppArmor, audit policy, binary verification, Validating Admission Policy, RuntimeClass and encryption of Secrets at rest. Each exercise points to the Kubernetes documentation page that describes the gesture. Exercises 21, 22 and 24 need root access to a node (the control plane for exercises 22 and 24); exercises 23, 25 and 26 run from your workstation.


Exercise 21: AppArmor with appArmorProfile

Target time: 6 minutes

ContextDebian or Ubuntu node where AppArmor is active (aa-enabled answers Yes), namespace cks-exercises
TaskLoad the profile k8s-apparmor-example-deny-write on the node, then create a Pod apparmor-pod (busybox:1.37) that applies it through the securityContext.appArmorProfile field
Validationkubectl exec apparmor-pod -- touch /tmp/test fails with Permission denied

The exercise does not run on a kind node, which shares the host kernel: use a virtual machine. The profile comes from the AppArmor tutorial on kubernetes.io.

Solution
Terminal window
# On the node: load the profile
sudo apparmor_parser -q <<'EOF'
#include <tunables/global>
profile k8s-apparmor-example-deny-write flags=(attach_disconnected) {
#include <abstractions/base>
file,
# Deny every file write
deny /** w,
}
EOF
sudo aa-status | grep k8s-apparmor-example-deny-write
# From the workstation: the Pod with the appArmorProfile field
kubectl apply -f - <<'EOF'
apiVersion: v1
kind: Pod
metadata:
name: apparmor-pod
namespace: cks-exercises
spec:
securityContext:
appArmorProfile:
type: Localhost
localhostProfile: k8s-apparmor-example-deny-write
containers:
- name: app
image: busybox:1.37@sha256:a7dbc319b1438115a207e11930dc4bb3e643dcb3ec0bdd694bb36cd8fad289ec
command: ['sh', '-c', 'sleep 3600']
EOF
# Validation
kubectl exec apparmor-pod -n cks-exercises -- cat /proc/1/attr/current
# k8s-apparmor-example-deny-write (enforce)
kubectl exec apparmor-pod -n cks-exercises -- touch /tmp/test
# touch: /tmp/test: Permission denied

The profile must be loaded on the node where the Pod lands: on a multi-node cluster, load it everywhere or pin the Pod to a node. If it is missing, the Pod does not start. For the annotation syntax of older manifests, see the AppArmor lesson (in French).


Exercise 22: Write an audit policy

Target time: 8 minutes

ContextControl plane node of a kubeadm cluster, root access, auditing not configured
TaskWrite /etc/kubernetes/audit/policy.yaml: Metadata level for Secrets and ConfigMaps, Request level for Pod creation and deletion, Metadata level for everything else, without the RequestReceived stage. Wire the policy into the API server, with the log at /var/log/kubernetes/audit/audit.log
ValidationAfter reading a Secret, jq shows a Metadata level line with no responseObject field
Solution
Terminal window
# On the control plane
sudo mkdir -p /etc/kubernetes/audit
sudo tee /etc/kubernetes/audit/policy.yaml > /dev/null <<'EOF'
apiVersion: audit.k8s.io/v1
kind: Policy
omitStages:
- "RequestReceived"
rules:
- level: Metadata
resources:
- group: ""
resources: ["secrets", "configmaps"]
- level: Request
resources:
- group: ""
resources: ["pods"]
verbs: ["create", "delete"]
- level: Metadata
EOF
# Backup OUTSIDE the manifests folder: the kubelet would run any YAML it finds there
sudo cp /etc/kubernetes/manifests/kube-apiserver.yaml /root/kube-apiserver.yaml.bak

In /etc/kubernetes/manifests/kube-apiserver.yaml, add two arguments to the command, one file or folder mount, and the matching hostPath volume, as described on the Auditing page of kubernetes.io:

- --audit-policy-file=/etc/kubernetes/audit/policy.yaml
- --audit-log-path=/var/log/kubernetes/audit/audit.log
# ... in volumeMounts:
- mountPath: /etc/kubernetes/audit/policy.yaml
name: audit-policy
readOnly: true
- mountPath: /var/log/kubernetes/audit/
name: audit-log
# ... in volumes:
- name: audit-policy
hostPath:
path: /etc/kubernetes/audit/policy.yaml
type: File
- name: audit-log
hostPath:
path: /var/log/kubernetes/audit/
type: DirectoryOrCreate
Terminal window
# Wait for the API server to restart, then read a Secret
kubectl get nodes
kubectl get secret -n kube-system
# Validation: Metadata level, never a response body
sudo jq -r 'select(.objectRef.resource=="secrets") | [.level, has("responseObject")] | @tsv' \
/var/log/kubernetes/audit/audit.log | sort -u
# Metadata false

Rules are evaluated in order and the first one that matches sets the level. The final rule without resources acts as a safety net for everything else: placed before the others, it would make them useless. If the API server does not restart, restore the backup and read its logs with sudo crictl logs on the node. The guided lab of the Audit Logs lesson walks through the same setup step by step.


Exercise 23: Verify a binary with sha256sum

Target time: 4 minutes

ContextAdmin workstation with access to dl.k8s.io
TaskDownload kubectl version v1.37.0 with its checksum, verify the binary, then prove that the verification fails on a tampered binary
Validationkubectl: OK and exit code 0 on the intact binary; kubectl: FAILED and exit code 1 after tampering
Solution
Terminal window
VER=v1.37.0
curl -LO "https://dl.k8s.io/release/${VER}/bin/linux/amd64/kubectl"
curl -LO "https://dl.k8s.io/release/${VER}/bin/linux/amd64/kubectl.sha256"
# Intact binary
echo "$(cat kubectl.sha256) kubectl" | sha256sum --check
# kubectl: OK
echo $?
# 0
# Tampered binary: a single appended byte is enough
printf 'x' >> kubectl
echo "$(cat kubectl.sha256) kubectl" | sha256sum --check
# kubectl: FAILED
# sha256sum: WARNING: 1 computed checksum did NOT match
echo $?
# 1
rm kubectl kubectl.sha256

The checksum is published next to the binary, under the same name with a .sha256 suffix (install kubectl on Linux). The format sha256sum --check expects is the checksum, two spaces, then the file name. If the task statement gives you the checksum directly, write echo "<checksum> <file>" | sha256sum --check.


Exercise 24: Encrypt Secrets at rest

Target time: 10 minutes

ContextControl plane node of a kubeadm cluster, root access, Secret db-pass created before encryption in cks-exercises
TaskEnable Secret encryption in etcd with the aescbc provider, keep identity last, and re-encrypt the Secrets already stored
Validationetcdctl get on the Secret key shows the prefix k8s:enc:aescbc:v1:key1 instead of plain text
Solution

On a kubeadm node, etcdctl and hexdump are not installed by default. The simplest way is to run etcdctl inside the etcd static Pod, which ships it and mounts the certificates: kubectl -n kube-system exec etcd-<node> -- etcdctl followed by the same --endpoints, --cacert, --cert and --key options, with no sudo and no ETCDCTL_API=3. The value then prints without hexdump, and the k8s:enc:aescbc:v1: prefix reads directly.

Terminal window
# Before: the Secret is readable in plain text in etcd
kubectl create secret generic db-pass --from-literal=password=s3cr3t -n cks-exercises
sudo ETCDCTL_API=3 etcdctl \
--endpoints=https://127.0.0.1:2379 \
--cacert=/etc/kubernetes/pki/etcd/ca.crt \
--cert=/etc/kubernetes/pki/etcd/server.crt \
--key=/etc/kubernetes/pki/etcd/server.key \
get /registry/secrets/cks-exercises/db-pass | hexdump -C
# s3cr3t is readable in the output
# 32-byte key, base64-encoded
KEY=$(head -c 32 /dev/urandom | base64)
sudo mkdir -p /etc/kubernetes/enc
sudo tee /etc/kubernetes/enc/enc.yaml > /dev/null <<EOF
apiVersion: apiserver.config.k8s.io/v1
kind: EncryptionConfiguration
resources:
- resources:
- secrets
providers:
- aescbc:
keys:
- name: key1
secret: ${KEY}
- identity: {}
EOF
sudo chmod 600 /etc/kubernetes/enc/enc.yaml
# Backup OUTSIDE the manifests folder
sudo cp /etc/kubernetes/manifests/kube-apiserver.yaml /root/kube-apiserver.yaml.bak

In /etc/kubernetes/manifests/kube-apiserver.yaml, add the argument, the mount and the hostPath volume, as described on the page Encrypting Confidential Data at Rest:

- --encryption-provider-config=/etc/kubernetes/enc/enc.yaml
# ... in volumeMounts:
- name: enc
mountPath: /etc/kubernetes/enc
readOnly: true
# ... in volumes:
- name: enc
hostPath:
path: /etc/kubernetes/enc
type: DirectoryOrCreate
Terminal window
# After the API server restarts: re-encrypt the existing Secrets
kubectl get secrets --all-namespaces -o json | kubectl replace -f -
# Validation: the prefix shows the provider and the key
sudo ETCDCTL_API=3 etcdctl \
--endpoints=https://127.0.0.1:2379 \
--cacert=/etc/kubernetes/pki/etcd/ca.crt \
--cert=/etc/kubernetes/pki/etcd/server.crt \
--key=/etc/kubernetes/pki/etcd/server.key \
get /registry/secrets/cks-exercises/db-pass | hexdump -C
# k8s:enc:aescbc:v1:key1

Provider order matters: the first one encrypts new writes, the following ones are used to read. With identity last, Secrets written before activation stay readable until the kubectl replace command rewrites them. Placed first, identity would turn encryption off. The kubernetes.io page advises against aescbc because CBC is vulnerable to padding oracle attacks, and invites you to consider a KMS provider, KMS v2 being the most robust in its table. Keep the key out of the repository: anyone who reads it decrypts etcd.


Exercise 25: Deny a Pod with no memory limit using a ValidatingAdmissionPolicy

Target time: 8 minutes

ContextCluster 1.37, namespace vap-test carrying the label vap=on
TaskCreate a ValidatingAdmissionPolicy require-memory-limit and its binding, which deny any Pod with a container that has no resources.limits.memory
ValidationA kubectl run without a limit is denied under --dry-run=server, the same Pod with a limit is accepted
Solution
Terminal window
kubectl create ns vap-test
kubectl label ns vap-test vap=on
kubectl apply -f - <<'EOF'
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicy
metadata:
name: require-memory-limit
spec:
failurePolicy: Fail
matchConstraints:
resourceRules:
- apiGroups: [""]
apiVersions: ["v1"]
operations: ["CREATE", "UPDATE"]
resources: ["pods"]
validations:
- expression: >-
object.spec.containers.all(c,
has(c.resources) && has(c.resources.limits) &&
'memory' in c.resources.limits)
message: "Every container must declare a memory limit"
---
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicyBinding
metadata:
name: require-memory-limit-binding
spec:
policyName: require-memory-limit
validationActions: [Deny]
matchResources:
namespaceSelector:
matchLabels:
vap: "on"
EOF
# Give the API server a few seconds to pick up the policy
# Denied: no limit
kubectl run no-limit -n vap-test --dry-run=server \
--image=busybox:1.37@sha256:a7dbc319b1438115a207e11930dc4bb3e643dcb3ec0bdd694bb36cd8fad289ec -- sleep 60
# Error from server (Invalid): ... ValidatingAdmissionPolicy 'require-memory-limit' with binding
# 'require-memory-limit-binding' denied request: Every container must declare a memory limit
# Accepted: with a limit
kubectl apply --dry-run=server -f - <<'EOF'
apiVersion: v1
kind: Pod
metadata:
name: with-limit
namespace: vap-test
spec:
containers:
- name: app
image: busybox:1.37@sha256:a7dbc319b1438115a207e11930dc4bb3e643dcb3ec0bdd694bb36cd8fad289ec
command: ['sh', '-c', 'sleep 60']
resources:
limits:
memory: 64Mi
EOF
# pod/with-limit created (server dry run)

The policy only applies to the namespaces the binding selects, and validationActions: [Deny] rejects the request instead of merely warning. The Validating Admission Policy page of kubernetes.io describes the format, and the lesson on this site (in French) details the validation actions. The policy and its binding have no namespace: remember to delete them during cleanup.


Exercise 26: Declare a RuntimeClass

Target time: 4 minutes

ContextAny cluster, namespace cks-exercises, no sandbox runtime installed
TaskDeclare a RuntimeClass gvisor whose handler is runsc, then write a Pod that uses it through runtimeClassName, without starting it
Validationkubectl get runtimeclass gvisor lists it, and kubectl apply --dry-run=server accepts the Pod
Solution
Terminal window
kubectl apply -f - <<'EOF'
apiVersion: node.k8s.io/v1
kind: RuntimeClass
metadata:
name: gvisor
handler: runsc
EOF
kubectl apply --dry-run=server -f - <<'EOF'
apiVersion: v1
kind: Pod
metadata:
name: sandboxed
namespace: cks-exercises
spec:
runtimeClassName: gvisor
containers:
- name: app
image: busybox:1.37@sha256:a7dbc319b1438115a207e11930dc4bb3e643dcb3ec0bdd694bb36cd8fad289ec
command: ['sh', '-c', 'sleep 3600']
EOF
# pod/sandboxed created (server dry run)
# Validation
kubectl get runtimeclass gvisor

The handler field must carry the name of a handler configured in the node's runtime (containerd or CRI-O). The --dry-run=server validates the declaration without starting anything: without a runsc handler on a node, a real Pod would not start, and the error would show up in its events. The API server does reject a Pod whose RuntimeClass does not exist, so create it first. The RuntimeClass page of kubernetes.io describes the field, and the lesson on runtime sandboxes continues with a real runtime.


Practicing the objectives that need a prepared environment

Some CKS objectives cannot be played in five minutes on a basic cluster: they need an installed tool, a registry, a service mesh or a configured node. For those, practice goes through the course lesson and its guided lab, which prepares the environment and checks the result. The table says, for each objective, where to work on it. A guided lab is launched from the lesson that hosts it, where its command appears.

Curriculum objectiveWhere to practiceExercise on this page
AppArmorAppArmor in Kubernetes (in French), lab "Confine a Pod with an AppArmor profile"21
Seccomp with a custom profileSeccomp (in French), lab "Forbid a system call to a container, and prove it from the inside"6 for RuntimeDefault
Audit policyAudit Logs, lab "Record who reads the Secrets, and only the metadata of the rest"22
API server hardeningCIS Benchmark, labs "Close the API server profiler without closing the API" and "Lower the failure count of a CIS audit, and prove it with a second audit"none
Native admission policiesValidating Admission Policy (in French), lab "Have the cluster itself reject an unpinned image, without a webhook"25
Kyverno and GatekeeperKyverno and Gatekeeper (in French), with no guided CKS lab wired so farnone
Image signing with cosignSign and verify an image with Cosign, lab "Sign an image, and prove the signature by having another one rejected"none
Static analysis with kubesec or kube-linterSupply Chain Security, section 5, whose guided lab covers trivy config, with no lab on kubesec or kube-linternone
Binary verificationSupply Chain Security, section 6, with no dedicated guided lab23
Secret encryption in etcdProtect the Secrets of a Kubernetes cluster (in French), with no guided lab24
RuntimeClass and sandboxingRuntime Sandboxes, lab "Isolate a Pod from the host kernel, and prove it by reading its version"26 for the declaration
Pod-to-Pod encryption (mTLS)mTLS pod-to-pod, lab "Require mTLS in a mesh, and prove it with a client left outside"none
Runtime detection with FalcoFalco, with no guided CKS lab wired so far19 for detection through the audit logs

For the rows marked "with no guided lab", the lesson and the cheat sheet are, for now, the only supports. These exercises, the capstone and the hands-on mock exam below, and the multiple-choice mock exam (in French) complement each other: they do not measure the same thing. A simulator such as Killer.sh remains useful to experience the interface of the real exam, which the labs do not reproduce; whether it is included depends on your offer (see Prepare for the CKS).

Capstone: open an enclave to a team you cannot trust

The exercises above harden one mechanism at a time. The capstone sets a whole situation: an outside team needs room in your cluster, and you must give it a space that stays safe even if the team is not. The cluster must refuse by itself what the team should not deploy, its identity must be able to do almost nothing, and nothing outside the enclave may reach what runs inside.

Allow 45 minutes, and do it after the exercises: it combines admission, RBAC and network isolation, while each has its own separate exercise above.

Are you ready for the CKS? The timed mock exam

Once the capstone is done, the mock exam puts you in conditions close to the real exam: all the tasks follow one another, with no hints, and it is up to you to manage the time. It has 16 tasks, split like the six domains of the official CKS v1.37 curriculum: 15% for Cluster Setup and for Cluster Hardening, 10% for System Hardening, 20% for each of the three other domains. It runs on a two-node kubeadm cluster, k8s-cp.lab and k8s-w1.lab, and the tasks are independent of one another.

It follows the mechanics of the real exam. You start from the base host, k8s-cp.lab, and each task names the host where you must do it: you connect with ssh, work, then return to the base with exit before the next task. Never run ssh from a task host. No context sets the namespace: each task gives its own, and a resource created in the wrong namespace does not count. As in the exam, kubectl, the k alias and completion are already set up on both hosts.

The score is read from the final state of the cluster, never from the commands typed. Each check, for example "the compromised Pod is removed, and only that one", is a state worth 5 points. There are 20 of them, because the four tasks worth 10 points (tasks 4, 8, 11 and 14) carry two. The pass mark is 67 out of 100, which is 14 states out of 20, as in the real exam (see the Linux Foundation FAQ on the CKA, CKAD and CKS). The lab gives no hint: you only discover the result at the end.

The lab tool, dsoxlab, does not time the exam. Plan 120 minutes in one sitting and start your own timer before the first task. With 16 tasks, that leaves 7.5 minutes per task on average.

This mock exam does not reproduce everything. The real exam chains one cluster per task, whereas here both hosts target the same cluster: the score reads the state of that cluster and does not check that you went through the right host. Respecting the mechanics is up to you, and that is what trains you. You also do not get the remote desktop of the real exam or its browser limited to the official documentation, and partial credit does not exist inside a state: it is passed or it is not.

Three curriculum objectives also stay outside the mock exam: Pod-to-Pod encryption with Istio, sandboxed runtimes with gVisor and detection with Falco. The control node has only 4 GB of memory, and the lab must validate within a limited time. The first two are practiced with their guided labs, listed in the table above, and Falco with its lesson. The detection task of the mock exam is solved without Falco.

After the exam, dsoxlab check lists, by its label, each state not reached, without saying why, and dsoxlab submit gives the score and the verdict against the pass mark of 67. For each missed task, go back to the lesson in the table below, then replay the mock exam later rather than right away: redoing the same tasks from memory no longer measures anything.

TaskWhat it testsLesson to review
1Deny all traffic by default, then open one flow and DNSNetworkPolicies
2Serve a site over HTTPS with an IngressIngress
3Fix the profiling controls of a CIS auditCIS Benchmark
4Reduce the rights of a service accountRBAC
5Run a Deployment with no API token mountedServiceAccounts
6Confine a Pod with an AppArmor profileAppArmor (in French)
7Deny a system call with seccompSeccomp (in French)
8Apply the restricted standard to a namespacePod Security Standards
9Replace an insecure application with a hardened versionSecurity Context
10Pass an API key through a Secret mounted read-onlySecrets
11Pin an image by digest and reject tagsSupply Chain Security and Validating Admission Policy (in French)
12Fix a Dockerfile flagged by trivy configSupply Chain Security
13Validate a signed image and reject the otherSign and verify an image with Cosign
14Log the reading of a Secret with the right audit policyAudit Logs
15Make a container's file system immutableSecurity Context
16Find and remove the compromised Pod, and only that oneDebug an application to inspect a Pod's processes, and Falco for tooled detection

Time summary

This table gives the target time of each exercise so you can plan your practice sessions. The last column says whether the exercise runs on its own (Yes) or depends on a previous exercise or on a particular environment (No).

#ExerciseBlockTimeIndependent
1NetworkPolicy Deny AllCore CKS4 minYes
2NetworkPolicy Allow SpecificCore CKS6 minYes
3Read-only RBACCore CKS5 minYes
4Disable the automounted tokenCore CKS4 minNo (Ex.3)
5Restrictive SecurityContextCore CKS6 minYes
6Seccomp RuntimeDefaultCore CKS3 minYes
7Pod Security AdmissionCore CKS5 minYes
8Read-only Secret volumeCore CKS4 minYes
9Identify privileged PodsCore CKS5 minYes
10Image pinned by digestCore CKS5 minYes
11Non-immutable imagesCore CKS5 minYes
12Secure an existing PodCore CKS8 minYes
13Namespace isolationCore CKS10 minYes
14TLS IngressCore CKS6 minYes
15cluster-admin ClusterRoleBindingsCore CKS5 minYes
16Trivy scanTools4 minYes
17Audit logsTools6 minNo (env.)
18Simplified security auditTools8 minYes
19Exec detection (audit)Advanced5 minNo (env.)
20kube-bench analysisAdvanced6 minNo (env.)
21AppArmor with appArmorProfileObjectives6 minNo (AppArmor node)
22Audit policyObjectives8 minNo (control plane)
23Verify a binary with sha256sumObjectives4 minYes
24Encrypt Secrets at restObjectives10 minNo (control plane)
25ValidatingAdmissionPolicyObjectives8 minYes
26Declare a RuntimeClassObjectives4 minYes

Block 1 (core CKS) takes about 81 minutes. Blocks 2 and 3 add about 29 minutes, block 4 about 40 minutes, for about 150 minutes across the 26 exercises. The capstone takes 45 minutes on its own, and the mock exam 120 minutes.

The CKS exam lasts 2 hours (120 min). Focus on block 1 first, then play block 4 to cover the objectives it leaves aside: together, blocks 1 and 4 exceed 2 hours, so do not chain them in one go. Blocks 2 and 3 let you go deeper once you have mastered the core. Keep the timed mock exam for the end: it is the only one that reproduces the duration and the sequence of the real exam.


Cleanup

Terminal window
kubectl delete ns cks-exercises
kubectl delete ns psa-test 2>/dev/null
kubectl delete ns production 2>/dev/null
# Exercises 25 and 26: resources without a namespace
kubectl delete ns vap-test 2>/dev/null
kubectl delete validatingadmissionpolicybinding require-memory-limit-binding 2>/dev/null
kubectl delete validatingadmissionpolicy require-memory-limit 2>/dev/null
kubectl delete runtimeclass gvisor 2>/dev/null

Exercises 21, 22 and 24 modify the node: unload the AppArmor profile by feeding its text back to sudo apparmor_parser -R, and restore the backup of kube-apiserver.yaml if you want to return the control plane to its initial state.


Key takeaways

  1. A deny-all NetworkPolicy is the first step of every production namespace.
  2. Minimal RBAC distinguishes Role (namespace) from ClusterRole (cluster), and is always checked with kubectl auth can-i.
  3. A restrictive SecurityContext combines runAsNonRoot, allowPrivilegeEscalation: false, readOnlyRootFilesystem and capabilities.drop: ["ALL"].
  4. The RuntimeDefault Seccomp profile is the standard profile for most workloads, and AppArmor is declared through securityContext.appArmorProfile.
  5. Pod Security Admission is driven by namespace labels, with enforce-version=latest to follow the cluster version.
  6. Disable automountServiceAccountToken unless the Pod calls the API.
  7. Prefer the digest over a mutable tag, and verify a binary with sha256sum --check.
  8. An audit policy is evaluated in order, a ValidatingAdmissionPolicy denies at admission, and the EncryptionConfiguration keeps identity last.
  9. The mock exam is scored on the final state of the cluster, with no hints. The pass mark is 67 out of 100, which is 14 states out of 20: keep a margin. Allow 120 minutes, which is 7.5 minutes per task.

Test your knowledge

Check that you have understood the essentials of this guide. The questions only cover what has just been explained here.

Knowledge check

Check what you have learned with this interactive quiz

6 questions
6 min
70% to pass

How it works

  • The timer starts when you click Start
  • Multiple choice, true/false and short answer questions
  • You can move between questions
  • Detailed results are shown at the end

Starts the quiz and the timer