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

CKS cheat sheet: Kubernetes security commands

By updated

Improve this page

Logo Kubernetes

The CKS is a hands-on exam in which you secure Kubernetes clusters. This page sorts the essential commands by exam domain, on Kubernetes 1.37. For the exam format, the domains and the study plan, see Prepare for the CKS.

What you will learn

  • Find the exam framework, with the source and date of each value.
  • Prepare your session and move to the host that each task designates.
  • Apply, domain by domain, the commands that keep coming back: NetworkPolicy, RBAC, AppArmor, seccomp, Pod Security Admission, Secrets encryption, image scanning, audit and Falco.
  • Diagnose the most frequent failures quickly with the troubleshooting table.

The exam framework

Two lines of this table shape your preparation more than the others. The CKA must have been passed before you take the CKS, without needing to be still active on the day you register. And the required score is 67%, one point more than the CKA and the CKAD (66%).

These values come from the Linux Foundation and were collected on November 14, 2026. If one of the source pages says something different when you read this, that page prevails.

ItemValue as of November 14, 2026Source
Duration2 hoursCKA, CKAD and CKS FAQ
Passing score67%CKA, CKAD and CKS FAQ
Validity2 yearsCKS product page
Retakeone retake included, when you are eligibleCKS product page
PrerequisiteCKA passed, not necessarily still activeLinux Foundation announcement
Kubernetes version1.37CKS product page and CKS v1.37 curriculum
Price of the exam alone445 USDCKS product page
Time to take the exam after purchase12 monthsCKS product page

The "Kubernetes version" line is the one that moves. According to the FAQ, the exam environment aligns with the latest minor version about 4 to 8 weeks after its release. Read the product page again before you start studying: one version of difference can change the behavior of some commands on this page.

Need-to-command table

This table is the entry point during the exam: you start from the task statement, find the command here, and the following sections give the full variant. The k in the examples is the alias for kubectl, defined in the next section. All the commands assume that you are already connected to the host indicated by the task.

NeedCommand
Block all incoming traffick apply -f deny-all-ingress.yaml
Create a Role to read podsk create role pod-reader --verb=get,list --resource=pods
Test a ServiceAccount's permissionsk auth can-i get pods --as=system:serviceaccount:ns:sa
Apply PSA restrictedk label ns <ns> pod-security.kubernetes.io/enforce=restricted
Scan an imagetrivy image --severity CRITICAL,HIGH nginx:1.30.5@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edb
CIS Benchmark auditkube-bench run --targets master
View the audit logscat /var/log/kubernetes/audit/audit.log | jq 'select(.verb=="create")'
Spot the Falco alertstail -f /var/log/falco/falco.log
Check that etcd encryption is configuredcat /etc/kubernetes/manifests/kube-apiserver.yaml | grep encryption
Get the digest of an imageskopeo inspect docker://nginx:1.30.5 | jq -r '.Digest'

Session shortcuts

On the task hosts, kubectl, the k alias and completion are already ready according to the official instructions: do not waste time setting them up. Only your personal shortcuts are up to you, to be set again after each ssh connection if you want them. On your practice cluster, these lines take thirty seconds to type and pay for themselves on every exercise.

The $do variable abbreviates --dry-run=client -o yaml, the combination that generates a manifest without creating anything. It is the most cost-effective shortcut of the exam, since almost every security resource is written in YAML. Completion must be explicitly attached to the alias, otherwise it only works on kubectl.

Terminal window
# Core aliases
alias k=kubectl
alias kn='kubectl config set-context --current --namespace'
export do="--dry-run=client -o yaml"
# Autocompletion
source <(kubectl completion bash)
complete -F __start_kubectl k
# Check where kubectl points
kubectl config current-context

Cluster Setup (15%)

This domain covers the initial configuration of the cluster: network isolation, compliance with benchmarks and TLS exposure. NetworkPolicies take the main place here, with a constant logic: deny everything by default, then reopen precisely what the application needs. A NetworkPolicy only has an effect if the cluster's network plugin implements it.

NetworkPolicy deny-all Ingress

This manifest selects all the Pods of the namespace and declares no ingress rule, which cuts all incoming traffic.

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: deny-all-ingress
namespace: production
spec:
podSelector: {}
policyTypes:
- Ingress

The result is that no traffic reaches the Pods of the namespace any more. The trap comes from podSelector: {}, which designates all the Pods: with no ingress rule, everything is blocked.

NetworkPolicy deny-all Egress

Same principle in the other direction: the Pods can no longer initiate any outgoing connection, including to the cluster's internal services.

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: deny-all-egress
namespace: production
spec:
podSelector: {}
policyTypes:
- Egress

This policy also blocks DNS. Add a rule that allows port 53 to CoreDNS if the application must resolve names.

NetworkPolicy: allow a specific flow

Once the global deny is in place, each legitimate flow is reopened by a dedicated policy: here, only the Pods carrying the label app: frontend reach port 8080 of the backend.

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-frontend-to-backend
namespace: production
spec:
podSelector:
matchLabels:
app: backend
policyTypes:
- Ingress
ingress:
- from:
- podSelector:
matchLabels:
app: frontend
ports:
- protocol: TCP
port: 8080

kube-bench, CIS audit

kube-bench runs the CIS Benchmark checks on a node and classifies each test as PASS, FAIL or WARN. The target is given explicitly, because the control plane checks and the worker node checks are different.

Terminal window
kube-bench run --targets master
kube-bench run --targets node
kube-bench run --json > cis-results.json

These commands check compliance with the CIS Benchmark. FAIL results often require you to edit the control plane manifests, in /etc/kubernetes/manifests/.

TLS Ingress, Secret

A Secret of type tls expects exactly two keys, tls.crt and tls.key: this is the format Ingresses require to terminate encryption.

Terminal window
openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
-keyout tls.key -out tls.crt -subj "/CN=app.example.com"
kubectl create secret tls app-tls --cert=tls.crt --key=tls.key -n production

Cluster Hardening (15%)

This domain is about hardening access to the Kubernetes API: who can do what, with which identity, and what the Pods themselves are allowed to request. RBAC makes up most of it, completed by mastery of ServiceAccounts and by checking the API server's startup parameters. The rule that guides every answer is least privilege.

RBAC, create a Role

A Role grants verbs in a single namespace. Its counterpart ClusterRole carries the same rights cluster-wide and also covers resources that have no namespace, such as nodes.

Terminal window
k create role pod-reader --verb=get,list,watch --resource=pods -n production
k create clusterrole node-viewer --verb=get,list --resource=nodes

These two commands limit permissions to the strict minimum: read access, on a single resource.

RBAC, bind to a ServiceAccount

A role has no effect until a binding attaches it to an identity: the binding is what actually activates the permissions.

Terminal window
k create rolebinding app-pod-reader \
--role=pod-reader \
--serviceaccount=production:app-sa \
-n production

The --serviceaccount option expects the namespace:name format.

RBAC, test permissions

The --as option makes the request be evaluated under another identity, without fetching any token. It is the fastest way to prove that an RBAC fix has really taken effect.

Terminal window
k auth can-i create pods -n production --as=system:serviceaccount:production:app-sa
k auth can-i --list --as=system:serviceaccount:production:app-sa -n production

These commands check that a ServiceAccount does not have too many rights. Always test with --as before considering the task done.

Identify excessive permissions

The cluster-admin role grants all rights on everything: listing who holds it is the first audit to run on an unfamiliar cluster.

Terminal window
# Who has cluster-admin?
kubectl get clusterrolebindings -o json | \
jq '.items[] | select(.roleRef.name=="cluster-admin") | {name: .metadata.name, subjects: .subjects}'

ServiceAccount, disable automount

By default, Kubernetes mounts an API access token in every Pod. An application that does not call the API has no need for it, and the token then becomes a key handed to whoever gets a shell in the container.

apiVersion: v1
kind: Pod
metadata:
name: secure-pod
spec:
serviceAccountName: restricted-sa
automountServiceAccountToken: false
containers:
- name: app
image: nginx:1.30.5@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edb

With automountServiceAccountToken: false, the Pod can no longer call the Kubernetes API with a mounted token. Without this field, the token is mounted automatically.

API Server, check the flags

The API server runs as a static Pod: its configuration is read and fixed directly in the node's manifest, and the kubelet restarts it as soon as the file changes.

Terminal window
cat /etc/kubernetes/manifests/kube-apiserver.yaml | grep -E "anonymous-auth|authorization-mode|admission-plugins"

The expected values are --anonymous-auth=false, --authorization-mode=Node,RBAC and --enable-admission-plugins=NodeRestriction.


System Hardening (10%)

This domain goes down to the kernel level: it is about restricting what a container can ask of the operating system. Seccomp filters system calls, AppArmor restricts access to files and capabilities, and the securityContext gathers the Kubernetes safeguards. These three mechanisms add up, and nothing is applied until you declare it.

Seccomp, RuntimeDefault

The RuntimeDefault profile applies the list of blocked system calls provided by the container engine. It covers most of the risk without requiring you to write a custom profile.

apiVersion: v1
kind: Pod
metadata:
name: seccomp-pod
spec:
securityContext:
seccompProfile:
type: RuntimeDefault
containers:
- name: app
image: nginx:1.30.5@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edb

This profile filters dangerous system calls such as ptrace or mount. Without a declared profile, the Pod runs as Unconfined: no system call is filtered, unless the kubelet runs with seccompDefault: true (the --seccomp-default option, stable since Kubernetes 1.27), which applies RuntimeDefault to every Pod that has no profile.

AppArmor, appArmorProfile field

The profile must be already loaded on the node before the Pod is created, otherwise the Pod does not start. The securityContext.appArmorProfile field has been stable since Kubernetes 1.31 (AppArmor tutorial on kubernetes.io). The Localhost type designates a profile loaded on the node, RuntimeDefault the runtime's own.

apiVersion: v1
kind: Pod
metadata:
name: apparmor-pod
spec:
securityContext:
appArmorProfile:
type: Localhost
localhostProfile: k8s-nginx
containers:
- name: app
image: nginx:1.30.5@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edb

To verify, list the profiles loaded on the node, then read the profile actually applied in the container.

Terminal window
# On the node: loaded profiles
aa-status
cat /sys/kernel/security/apparmor/profiles
# Profile applied to the container's main process
kubectl exec apparmor-pod -- cat /proc/1/attr/current

A compatibility note: older manifests carry the annotation container.apparmor.security.beta.kubernetes.io/<container>: localhost/<profile>, deprecated since 1.30. Recognize it when reading an existing manifest, but write the appArmorProfile field. The lesson AppArmor in Kubernetes (in French) details both syntaxes.

SecurityContext, complete hardened Pod

This manifest gathers everything the restricted level of Pod Security Admission requires. Remember it as it stands: it is the basis of most hardening questions. The securityContext exists at two levels, Pod and container, and the fields are not interchangeable between them.

apiVersion: v1
kind: Pod
metadata:
name: hardened-pod
spec:
securityContext:
runAsNonRoot: true
runAsUser: 1000
seccompProfile:
type: RuntimeDefault
containers:
- name: app
image: nginx:1.30.5@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edb
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop:
- ALL
volumeMounts:
- name: tmp
mountPath: /tmp
volumes:
- name: tmp
emptyDir: {}

Four fields are worth memorizing: runAsNonRoot: true, allowPrivilegeEscalation: false, readOnlyRootFilesystem: true and capabilities.drop: ["ALL"]. With the nginx image of this example, the read-only file system needs more volumes than /tmp alone: exercise 5 also mounts /var/cache/nginx and /var/run.

Identify risky Pods

A privileged container has almost all the rights of the node. It is the first pattern to look for when a task asks you to spot the dangerous Pods of a cluster.

Terminal window
# Privileged Pods
kubectl get pods -A -o json | jq '.items[] | select(.spec.containers[].securityContext.privileged == true) | .metadata.namespace + "/" + .metadata.name'
# Root Pods
kubectl get pods -A -o json | jq '.items[] | select(.spec.securityContext.runAsNonRoot != true) | .metadata.namespace + "/" + .metadata.name'

Minimize Vulnerabilities (20%)

This domain, named "Minimize Microservice Vulnerabilities" in the official blueprint, is about preventing a dangerous configuration from entering the cluster, rather than fixing it afterwards. Pod Security Admission is the native mechanism that rejects non-compliant Pods at admission, OPA Gatekeeper covers the rules PSA cannot express, and etcd encryption protects the stored Secrets. These controls apply at creation time: they do not modify resources already in place.

Pod Security Admission, apply restricted

PSA is driven only by namespace labels: no extra resource to create. The enforce-version label pins the version of the applied standard; latest follows the cluster version.

Terminal window
kubectl label namespace production \
pod-security.kubernetes.io/enforce=restricted \
pod-security.kubernetes.io/enforce-version=latest

The three levels, from the most permissive to the strictest, are privileged (no restriction), baseline and restricted. The three modes are enforce (blocks), warn (warns) and audit (writes to the audit log).

Testing a non-compliant Pod

--dry-run=server submits the request to the API server and therefore really triggers the admission controls, unlike --dry-run=client, which stops on your workstation.

Terminal window
kubectl run test --image=nginx:1.30.5@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edb -n production --dry-run=server

With enforce=restricted, the expected output is Error from server (Forbidden): violates PodSecurity "restricted:latest".

Secrets, etcd encryption

Encryption at rest is enabled by an EncryptionConfiguration file referenced in the API server parameters. Without it, anyone who reads the etcd database reads your Secrets.

Terminal window
# Check whether it is configured
cat /etc/kubernetes/manifests/kube-apiserver.yaml | grep encryption
cat /etc/kubernetes/enc/enc.yaml

Secrets are base64-encoded by default, which is not encryption. The lesson Protecting the Secrets of a Kubernetes cluster (in French) explains encryption at rest, and exercise 24 of the CKS exercises has you write this file and check the result in etcd.

OPA Gatekeeper, Constraints

Gatekeeper works in two steps: a ConstraintTemplate defines the rule in Rego, a Constraint applies it to a given scope. These are the constraints that the command below lists.

Terminal window
kubectl get constraints
kubectl describe constraint no-latest-tag

Gatekeeper is used for custom admission policies, such as blocking the latest tag.


Supply Chain Security (20%)

This domain is about what you deploy, before it even runs: where the image comes from, which vulnerabilities it contains, and how to guarantee that the one that starts is the one you audited. Trivy answers the second question, the digest the third.

Trivy, scan an image

The scan reads the packages installed in the image and compares them with public vulnerability databases. Filtering on high severities keeps you from drowning in hundreds of results with no practical impact.

Terminal window
trivy image nginx:1.30.5@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edb
trivy image --severity CRITICAL,HIGH nginx:1.30.5@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edb
trivy image --ignore-unfixed nginx:1.30.5@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edb
trivy image --format json -o results.json nginx:1.30.5@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edb

These commands detect CVEs before deployment. The --ignore-unfixed option only shows the CVEs for which a fix exists. A scan only reports what is known: it proves neither the origin nor the integrity of the image, and that is the job of the digest and the signature.

Trivy, scan the cluster

The k8s mode queries the API to discover the running images and analyzes them all: an overview without listing the Pods by hand.

Terminal window
trivy k8s --report summary

Scan all the images in the cluster

This loop is the fallback when trivy k8s is not available. The sort -u avoids scanning the same image ten times when several Pods share it.

Terminal window
for img in $(kubectl get pods -A -o jsonpath='{.items[*].spec.containers[*].image}' | tr ' ' '\n' | sort -u); do
echo "=== $img ==="
trivy image --severity CRITICAL --quiet "$img"
done

Image digest, get the hash

A tag can be reassigned at any time to different content. The digest is the fingerprint of the content itself and therefore always designates the same image.

Terminal window
skopeo inspect docker://nginx:1.30.5 | jq -r '.Digest'

In a Pod, the canonical form keeps the tag readable and adds the digest, which protects against a tag being replaced by booby-trapped content:

image: nginx:1.30.5@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edb

Identify Pods without a digest

The regular expression keeps the images whose reference ends with a tag and no @sha256, in other words those whose content can change under your feet.

Terminal window
kubectl get pods -A -o json | jq '.items[] | select(.spec.containers[].image | test(":[^@]+$")) | .metadata.namespace + "/" + .metadata.name'

Runtime Security (20%)

This last domain, named "Monitoring, Logging and Runtime Security" in the official blueprint, is about what happens once the containers have started: tracing API calls, detecting abnormal behavior and reducing the attack surface at runtime. The audit logs answer the question "who did what", Falco the question "what abnormal thing is happening right now". Both are read from the node, not from kubectl.

Audit logs, analyze

Each line of the audit log is a complete JSON object: jq is therefore the reading tool, and the filter bears on the verb, the user or the response code depending on the case. The log path is that of the API server's --audit-log-path argument; the examples reuse the one from exercise 22.

Terminal window
# Secret creations
cat /var/log/kubernetes/audit/audit.log | jq 'select(.verb=="create" and .objectRef.resource=="secrets")'
# A user's actions
cat /var/log/kubernetes/audit/audit.log | jq 'select(.user.username=="suspect")'
# Failures
cat /var/log/kubernetes/audit/audit.log | jq 'select(.responseStatus.code >= 400)'

These filters serve post-incident investigation.

Create an audit policy

The rules are evaluated in order and the first one that matches sets the level retained. The order of the entries is therefore part of the expected answer: an exclusion placed after a broader rule has no effect.

/etc/kubernetes/audit/policy.yaml
apiVersion: audit.k8s.io/v1
kind: Policy
rules:
- level: Metadata
resources:
- group: ""
resources: ["secrets"]
- level: RequestResponse
resources:
- group: ""
resources: ["pods"]
- level: None
users: ["system:kube-proxy"]

The levels, from least to most verbose, are None, Metadata, Request and RequestResponse.

Falco, read the alerts

Falco watches the node's system calls and alerts as soon as a behavior matches one of its rules. Remember the nuance: it reports, it does not block.

Terminal window
tail -f /var/log/falco/falco.log
grep "Critical\|Error\|Warning" /var/log/falco/falco.log
systemctl status falco

Falco detects, for example, a shell launched in a container or access to a sensitive file.

Immutability, read-only file system

A read-only file system prevents a tool from being installed or a binary from being modified after an intrusion. In return, you must explicitly open the temporary directories the application needs.

securityContext:
readOnlyRootFilesystem: true
volumeMounts:
- name: tmp
mountPath: /tmp
volumes:
- name: tmp
emptyDir: {}

The attacker can no longer modify the binaries. Since the application has to write somewhere, add emptyDir volumes for its working directories.


Commands to know by heart

These commands must come out without thinking: every hesitation costs minutes in a two-hour exam. They are written in imperative form whenever possible, with no YAML file, because that is the fastest way to create a simple resource. The values between angle brackets are replaced by those of the task.

Terminal window
# NetworkPolicy
k get netpol -A
k apply -f deny-all.yaml
# RBAC
k create role <name> --verb=get,list --resource=pods
k create rolebinding <name> --role=<role> --serviceaccount=<ns>:<sa>
k auth can-i <verb> <resource> --as=system:serviceaccount:<ns>:<sa>
# PSA
k label ns <ns> pod-security.kubernetes.io/enforce=restricted
# Scan
trivy image --severity CRITICAL,HIGH <image>
kube-bench run --targets master
# Audit/Falco
cat /var/log/kubernetes/audit/audit.log | jq '...'
tail -f /var/log/falco/falco.log
# AppArmor/Seccomp
aa-status
ls /var/lib/kubelet/seccomp/

What to find fast in the docs

Do not waste time memorizing: find the syntax in the allowed documentation or with kubectl explain. The list below gives the points you should be able to locate in under a minute.

  • Full syntax of a NetworkPolicy (k explain networkpolicy.spec)
  • Fields of the securityContext (k explain pod.spec.securityContext)
  • Format of the etcd EncryptionConfiguration
  • ImagePolicyWebhook options
  • Custom Falco rules
  • Rego syntax of a Gatekeeper ConstraintTemplate

Quick troubleshooting

These six symptoms show up as soon as you practice the exercises. For each one, the indicated command confirms the cause in a few seconds, before you set off on a false lead.

ProblemCommand
Pod rejected by PSAk run test --dry-run=server
NetworkPolicy inactivek describe netpol <name>, then check that the network plugin enforces them
Empty audit logsgrep audit /etc/kubernetes/manifests/kube-apiserver.yaml
Falco silentsystemctl status falco
API Server downjournalctl -u kubelet + check the YAML
kube-bench FAILkube-bench run --targets master

Key takeaways

  1. Put a deny-all in every namespace, then open the flows one by one with precise NetworkPolicies.
  2. Apply least privilege in RBAC and grant cluster-admin only to administrators.
  3. Set automountServiceAccountToken: false whenever a Pod does not call the API: Kubernetes mounts the token by default.
  4. Harden the securityContext with drop ALL, readOnlyRootFilesystem: true and runAsNonRoot: true.
  5. Apply the PSA restricted level on production namespaces.
  6. Enable Secret encryption in etcd and keep strict RBAC on Secrets.
  7. Scan with Trivy at CRITICAL and HIGH before any deployment, and reference images with @sha256:...: a scan says nothing about the origin of an image, and a tag can change under the same name.
  8. Enable the audit logs to investigate after the fact, and watch the Falco alerts knowing that it reports without blocking.

Knowledge check

Seven questions about hardening reflexes, the exact scope of a NetworkPolicy, and what an image scan does not prove.

Knowledge check

Check what you have learned with this interactive quiz

7 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