Cluster Hardening: RBAC, Pod Security and Network Policy
Run a real Kubernetes v1.37 control plane on 127.0.0.1, then compare a least-privilege Role with a broad binding, watch Pod Security Admission reject non-compliant pods, prove that Secrets are encrypted in etcd, write default-deny network policies, and check the API server against the CIS Kubernetes Benchmark with kube-bench before and after hardening.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: Download the binaries
- Step 2: Start the control plane
- Step 3: Least privilege for a CI service account
- Step 4: Enforce the Restricted Pod Security Standard
- Step 5: Check that Secrets are encrypted at rest
- Step 6: Default-deny network policies
- Step 7: Check the API server against the CIS Benchmark
- Check your understanding
- Apply it
- Review prompt
Lessons of Container & Kubernetes Security
- What Containers Isolate and What They Do Not Concept · 15 min
- Hardening and Scanning Images Lab · 25 min
- Cluster Hardening: RBAC, Pod Security and Network Policy Lab · 30 min
- Admission Control for Trusted Workloads Worked example · 20 min
- Runtime Detection and Cluster Audit Logs Lab · 25 min
- Container & Kubernetes Security Check Knowledge check · 6 questions
What you will learn
- Harden a Kubernetes cluster with least-privilege RBAC, Pod Security Standards, network policies and sound secret handling, verified against the CIS Kubernetes Benchmark.
Prerequisites: Kubernetes Fundamentals
01. Goal and setup
You will harden a cluster and collect the evidence an auditor would ask for: least-privilege access for a CI service account, the Restricted Pod Security Standard, Secrets encrypted at rest, default-deny network policies, and a benchmark run that shows what still fails.
Most of this needs only the control plane, so the lab runs one on 127.0.0.1: etcd (the key-value store that holds all cluster state), kube-apiserver, kube-controller-manager and kube-scheduler. There are no nodes, so pods are checked and stored but never start. Proving that network policies block traffic needs nodes and a network plugin; that step is marked as not reproducible here.
You need: Linux on amd64, bash, curl, openssl, about 600 MB of disk, and free ports 18379, 18380 and 18443. Tested versions: Kubernetes v1.37.2, etcd v3.6.16, kube-bench 0.16.0.
k8s-sec-lab/
├── get-bins.sh, bin/ step 1: Kubernetes v1.37.2 and etcd v3.6.16
├── audit-policy.yaml step 2: what the API server records
├── start-cp.sh, stop-cp.sh step 2: start and stop the control plane
├── pki/, data/, logs/ created by start-cp.sh (logs/audit.log)
├── tokens.csv, encryption.yaml, kubeconfig created by start-cp.sh
└── rbac.yaml, pss.yaml, pod-*.yaml, netpol.yaml, kube-bench/ steps 3 to 702. Step 1: Download the binaries
Save the script in a new folder k8s-sec-lab/ and run it. It checks every file against its published SHA-256 sum.
#!/usr/bin/env bash
# get-bins.sh: download pinned control-plane binaries (Linux amd64) and check them.
set -euo pipefail
mkdir -p bin && cd bin
K=v1.37.2; E=v3.6.16
for b in kube-apiserver kube-controller-manager kube-scheduler kubectl; do
curl -sSLO "https://dl.k8s.io/release/$K/bin/linux/amd64/$b"
echo "$(curl -sSL "https://dl.k8s.io/release/$K/bin/linux/amd64/$b.sha256") $b" \
| sha256sum -c
done
ETCD=etcd-$E-linux-amd64
curl -sSLO "https://github.com/etcd-io/etcd/releases/download/$E/$ETCD.tar.gz"
curl -sSL "https://github.com/etcd-io/etcd/releases/download/$E/SHA256SUMS" \
| grep " $ETCD.tar.gz$" | sha256sum -c
tar xzf "$ETCD.tar.gz" --strip-components=1 "$ETCD/etcd" "$ETCD/etcdctl"
rm "$ETCD.tar.gz"
chmod +x kube-* kubectl
./kubectl version --client | head -1
./etcd --version | head -1chmod +x get-bins.sh
./get-bins.shkube-apiserver: OK
kube-controller-manager: OK
kube-scheduler: OK
kubectl: OK
etcd-v3.6.16-linux-amd64.tar.gz: OK
Client Version: v1.37.2
etcd Version: 3.6.1603. Step 2: Start the control plane
The audit policy tells the API server what to record; lesson 05 explains it. The start script creates a service-account signing key, static tokens for four identities (you as lab-admin, a developer alice, and two controllers) and an encryption key for Secrets. Static tokens suit a lab, not a real cluster.
apiVersion: audit.k8s.io/v1
kind: Policy
omitStages: [RequestReceived]
rules:
# 1. Secrets, ConfigMaps, TokenRequests and TokenReviews: who touched which object,
# never the Secret values or the bearer tokens in the bodies.
- level: Metadata
resources:
- group: ""
resources: [secrets, configmaps, serviceaccounts/token]
- group: authentication.k8s.io
resources: [tokenreviews]
# 2. Interactive access into pods: who, which pod, which command.
- level: Metadata
resources:
- group: ""
resources: [pods/exec, pods/attach, pods/portforward]
# 3. Bodies that normally hold no Secret values: the image of a debug container, and
# the whole role binding after a change (the response, not only the patch).
- level: Request
resources:
- group: ""
resources: [pods/ephemeralcontainers]
- level: RequestResponse
verbs: [create, update, patch]
resources:
- group: rbac.authorization.k8s.io
resources: [rolebindings, clusterrolebindings]
# 4. Noise: health checks, leader-election leases, control-plane reads.
- level: None
nonResourceURLs: ["/readyz*", "/livez*", "/healthz*", "/version"]
- level: None
resources:
- group: coordination.k8s.io
resources: [leases]
- level: None
users: [system:apiserver, system:kube-controller-manager, system:kube-scheduler]
verbs: [get, list, watch]
- level: None
userGroups: ["system:serviceaccounts:kube-system"]
verbs: [get, list, watch]
# 5. Changes keep the request body: who changed what, and to what.
- level: Request
verbs: [create, update, patch, delete, deletecollection]
# 6. Everything else: metadata only.
- level: Metadata#!/usr/bin/env bash
# start-cp.sh: a Kubernetes control plane on 127.0.0.1 with no nodes. Lab use only.
set -euo pipefail
cd "$(dirname "$0")"
B=$PWD/bin # absolute paths, so kube-bench can recognise the processes
for port in 18379 18380 18443; do # refuse to start next to another control plane
if (exec 3<>/dev/tcp/127.0.0.1/$port) 2>/dev/null; then
echo "port $port is already in use: run ./stop-cp.sh first"; exit 1
fi
done
mkdir -p pki data logs
# 1. Keys and credentials, created on the first run only.
[ -f pki/sa.key ] || openssl genrsa -out pki/sa.key 2048 2>/dev/null
[ -f tokens.csv ] || cat > tokens.csv <<CSV
lab-admin-token,lab-admin,1000,system:masters
lab-alice-token,alice,1001,developers
lab-kcm-token,system:kube-controller-manager,1002,
lab-sched-token,system:kube-scheduler,1003,
CSV
[ -f encryption.yaml ] || cat > encryption.yaml <<YAML
apiVersion: apiserver.config.k8s.io/v1
kind: EncryptionConfiguration
resources:
- resources: [secrets]
providers:
- secretbox:
keys:
- name: key1
secret: $(head -c 32 /dev/urandom | base64)
- identity: {}
YAML
# 2. etcd, plain HTTP on loopback (a real cluster uses TLS and client certs).
$B/etcd --name lab --data-dir data/etcd \
--listen-client-urls http://127.0.0.1:18379 \
--advertise-client-urls http://127.0.0.1:18379 \
--listen-peer-urls http://127.0.0.1:18380 \
--initial-advertise-peer-urls http://127.0.0.1:18380 \
--initial-cluster lab=http://127.0.0.1:18380 > logs/etcd.log 2>&1 &
echo $! > etcd.pid
until $B/etcdctl --endpoints=127.0.0.1:18379 endpoint health >/dev/null 2>&1; do
sleep 0.5
done
# 3. kube-apiserver with RBAC, audit logging and encryption at rest.
$B/kube-apiserver --bind-address=127.0.0.1 --secure-port=18443 \
--advertise-address=127.0.0.1 --endpoint-reconciler-type=none --cert-dir=pki \
--etcd-servers=http://127.0.0.1:18379 \
--service-account-issuer=https://kubernetes.default.svc \
--service-account-key-file=pki/sa.key \
--service-account-signing-key-file=pki/sa.key \
--service-cluster-ip-range=10.96.0.0/16 \
--anonymous-auth=false --token-auth-file=tokens.csv \
--authorization-mode=Node,RBAC \
--audit-policy-file=audit-policy.yaml --audit-log-path=logs/audit.log \
--encryption-provider-config=encryption.yaml \
${APISERVER_EXTRA_FLAGS:-} > logs/apiserver.log 2>&1 &
echo $! > apiserver.pid
for i in $(seq 30); do [ -f pki/apiserver.crt ] && break; sleep 1; done
# 4. One kubeconfig per identity: you (lab-admin, alice) and two controllers.
kc() { # kc <file> <user> <token>
local k="$B/kubectl --kubeconfig=$1 config"
$k set-cluster lab --server=https://127.0.0.1:18443 \
--certificate-authority=pki/apiserver.crt --embed-certs >/dev/null
$k set-credentials "$2" --token="$3" >/dev/null
$k set-context "$2" --cluster=lab --user="$2" >/dev/null
$k use-context "$2" >/dev/null
}
kc kubeconfig alice lab-alice-token
kc kubeconfig lab-admin lab-admin-token
kc kcm.kubeconfig kcm lab-kcm-token
kc sched.kubeconfig sched lab-sched-token
export KUBECONFIG=$PWD/kubeconfig
for i in $(seq 60); do
$B/kubectl get --raw /readyz >/dev/null 2>&1 && break
kill -0 "$(cat apiserver.pid)" 2>/dev/null || { tail -3 logs/apiserver.log; exit 1; }
sleep 1
done
# 5. Controller manager (namespaces, service accounts, aggregated roles) and scheduler.
$B/kube-controller-manager --kubeconfig=kcm.kubeconfig --secure-port=0 \
--leader-elect=false \
--controllers=*,-kube-apiserver-serving-clustertrustbundle-publisher-controller \
--use-service-account-credentials --root-ca-file=pki/apiserver.crt \
> logs/controller-manager.log 2>&1 &
echo $! > kcm.pid
$B/kube-scheduler --kubeconfig=sched.kubeconfig --secure-port=0 --leader-elect=false \
> logs/scheduler.log 2>&1 &
echo $! > scheduler.pid
until $B/kubectl get serviceaccount default >/dev/null 2>&1; do sleep 1; done
echo "control plane ready on https://127.0.0.1:18443"#!/usr/bin/env bash
# stop-cp.sh: stop the processes that start-cp.sh started, by PID, and wait.
cd "$(dirname "$0")"
for p in scheduler kcm apiserver etcd; do
[ -f $p.pid ] || continue
pid=$(cat $p.pid)
kill "$pid" 2>/dev/null && while kill -0 "$pid" 2>/dev/null; do sleep 0.2; done
echo "stopped $p"
rm -f $p.pid
donechmod +x start-cp.sh stop-cp.sh
./start-cp.sh
export KUBECONFIG=$PWD/kubeconfig PATH=$PWD/bin:$PATH
kubectl version | grep Server
kubectl auth whoamicontrol plane ready on https://127.0.0.1:18443
Server Version: v1.37.2
ATTRIBUTE VALUE
Username lab-admin
UID 1000
Groups [system:masters system:authenticated]04. Step 3: Least privilege for a CI service account
Kubernetes RBAC (role-based access control) has four objects. A Role lists allowed verbs on resources in one namespace; a ClusterRole does the same cluster-wide or as a reusable template. A RoleBinding grants a Role or ClusterRole to users, groups or service accounts inside one namespace; a ClusterRoleBinding grants it everywhere. RBAC has no label selectors: a binding grants its role on every object of the listed resources in its scope. A service account is the identity a workload or pipeline uses. Here the CI job only rolls out Deployments in shop. For comparison, ci-broad gets the built-in edit ClusterRole through a RoleBinding, a shortcut many teams take.
apiVersion: v1
kind: Namespace
metadata:
name: shop
---
apiVersion: v1
kind: ServiceAccount
metadata:
name: ci-deployer
namespace: shop
automountServiceAccountToken: false
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: deployment-updater
namespace: shop
rules:
- apiGroups: ["apps"]
resources: ["deployments"]
verbs: ["get", "list", "watch", "patch", "update"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: ci-deployer-updates-deployments
namespace: shop
subjects:
- kind: ServiceAccount
name: ci-deployer
namespace: shop
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: Role
name: deployment-updaterkubectl apply -f rbac.yaml
kubectl -n shop create serviceaccount ci-broad
kubectl -n shop create rolebinding ci-broad-edit --clusterrole=edit \
--serviceaccount=shop:ci-broad
can() { kubectl auth can-i $1 -n "${3:-shop}" --as=system:serviceaccount:shop:$2; }
printf '%-32s %-12s %s\n' "can it ... in shop?" ci-deployer ci-broad
for c in "patch deployments" "get secrets" "create pods" \
"create pods --subresource=exec" "get pods --subresource=exec" \
"create rolebindings"; do
printf '%-32s %-12s %s\n' "$c" "$(can "$c" ci-deployer)" "$(can "$c" ci-broad)"
done
echo "ci-deployer, patch deployments in default: $(can "patch deployments" \
ci-deployer default)"namespace/shop created
serviceaccount/ci-deployer created
role.rbac.authorization.k8s.io/deployment-updater created
rolebinding.rbac.authorization.k8s.io/ci-deployer-updates-deployments created
serviceaccount/ci-broad created
rolebinding.rbac.authorization.k8s.io/ci-broad-edit created
can it ... in shop? ci-deployer ci-broad
patch deployments yes yes
get secrets no yes
create pods no yes
create pods --subresource=exec no yes
get pods --subresource=exec no yes
create rolebindings no no
ci-deployer, patch deployments in default: noBoth accounts can do the job, but edit also reads Secrets, creates pods and opens shells in them. Subresources go in --subresource: create pods/exec would ask about a pod named exec, and answer no for an account that can open shells. kubectl exec first tries a WebSocket, which needs get as well as create, so check both. Creating pods is broader than it looks: a pod can mount any Secret and any service account token in its namespace. In ATT&CK terms, a stolen token for ci-broad enables Unsecured Credentials: Container API (T1552.007). Neither account can create RoleBindings, which would let it grant itself more (Additional Container Cluster Roles, T1098.006); a RoleBinding to cluster-admin could, because it gives full control of the namespace, Secrets and RoleBindings included.
Now prove the result with the account's real credentials. kubectl create token issues a short-lived token, better for CI than a long-lived token Secret; automountServiceAccountToken: false keeps the token out of pods that do not need it.
TOKEN=$(kubectl -n shop create token ci-deployer --duration=10m)
kubectl --token="$TOKEN" -n shop get deployments
kubectl --token="$TOKEN" -n shop get secrets 2>&1 | fold -s -w 80No resources found in shop namespace.
Error from server (Forbidden): secrets is forbidden: User
"system:serviceaccount:shop:ci-deployer" cannot list resource "secrets" in API
group "" in the namespace "shop"05. Step 4: Enforce the Restricted Pod Security Standard
The Pod Security Standards define three levels. Privileged allows everything, for system components that need it. Baseline blocks known privilege escalations such as privileged containers, host namespaces and hostPath volumes. Restricted adds current hardening practice: non-root users, allowPrivilegeEscalation: false, all capabilities dropped and a seccomp profile set. It allows only common volume types such as configMap, emptyDir, secret and persistentVolumeClaim, and it does not require a read-only root file system; you add that yourself. Pod Security Admission applies a level per namespace through labels, in three modes: enforce rejects, warn warns the client and audit annotates the audit event. Pin a version for each mode; without one, a mode uses latest, which changes with upgrades.
apiVersion: v1
kind: Namespace
metadata:
name: payments
labels:
pod-security.kubernetes.io/enforce: restricted
pod-security.kubernetes.io/enforce-version: v1.37
pod-security.kubernetes.io/warn: restricted
pod-security.kubernetes.io/warn-version: v1.37
pod-security.kubernetes.io/audit: restricted
pod-security.kubernetes.io/audit-version: v1.37apiVersion: v1
kind: Pod
metadata:
name: web-default
namespace: payments
spec:
containers:
- name: web
image: docker.io/library/alpine:3.20
command: ["sleep", "3600"]apiVersion: v1
kind: Pod
metadata:
name: web-restricted
namespace: payments
spec:
automountServiceAccountToken: false
securityContext:
runAsNonRoot: true
runAsUser: 65532
runAsGroup: 65532
seccompProfile:
type: RuntimeDefault
containers:
- name: web
image: docker.io/library/alpine:3.20
command: ["sleep", "3600"]
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop: ["ALL"]
volumeMounts:
- name: tmp
mountPath: /tmp
volumes:
- name: tmp
emptyDir: {}kubectl apply -f pss.yaml
kubectl apply -f pod-default.yaml 2>&1 | fold -s -w 80
kubectl apply -f pod-restricted.yaml
sed -e 's/web-restricted/web-hostnet/' -e '/^spec:/a\ hostNetwork: true' \
pod-restricted.yaml | kubectl apply -f - 2>&1 | fold -s -w 80
kubectl -n payments get pods -o custom-columns=NAME:.metadata.name,STATUS:.status.phasenamespace/payments created
Error from server (Forbidden): error when creating "pod-default.yaml": pods
"web-default" is forbidden: violates PodSecurity "restricted:v1.37":
allowPrivilegeEscalation != false (container "web" must set
securityContext.allowPrivilegeEscalation=false), unrestricted capabilities
(container "web" must set securityContext.capabilities.drop=["ALL"]),
runAsNonRoot != true (pod or container "web" must set
securityContext.runAsNonRoot=true), seccompProfile (pod or container "web" must
set securityContext.seccompProfile.type to "RuntimeDefault" or "Localhost")
pod/web-restricted created
Error from server (Forbidden): error when creating "STDIN": pods "web-hostnet"
is forbidden: violates PodSecurity "restricted:v1.37": host namespaces
(hostNetwork=true)
NAME STATUS
web-restricted PendingThe default pod is rejected with the exact fields to fix. The compliant pod is accepted and stays Pending because there is no node. The hostNetwork copy is rejected although everything else complies, because host namespaces are already forbidden at Baseline. Enforcement checks pods, not the Deployments that create them.
kubectl -n payments create deployment legacy --image=docker.io/library/alpine:3.20 \
-- sleep 3600 2>&1 | cut -c1-80
sleep 5
kubectl -n payments get deployment,replicaset
kubectl -n payments get events --field-selector reason=FailedCreate \
-o jsonpath='{.items[0].message}' | cut -c1-80Warning: would violate PodSecurity "restricted:v1.37": allowPrivilegeEscalation
deployment.apps/legacy created
NAME READY UP-TO-DATE AVAILABLE AGE
deployment.apps/legacy 0/1 0 0 6s
NAME DESIRED CURRENT READY AGE
replicaset.apps/legacy-8496c9d584 1 0 0 6s
Error creating: pods "legacy-8496c9d584-q9ptv" is forbidden: violates PodSecuritThe Deployment is created with a warning, and its ReplicaSet keeps failing to create pods. Watch for FailedCreate events when you switch a namespace to enforce; labelling it first with only warn and audit shows the violations without breaking anything.
06. Step 5: Check that Secrets are encrypted at rest
A Secret is only base64-encoded in the API. Encryption at rest protects the copy in etcd and in its backups. The start script wrote encryption.yaml, which encrypts Secrets with the secretbox provider and a local key, and lists identity (no encryption) second so that older, unencrypted data can still be read. Read the raw values straight from etcd.
kubectl -n shop create secret generic db-credentials \
--from-literal=password=lab-only-S3cret
kubectl -n shop create configmap db-settings --from-literal=host=db.shop.svc
V=$(kubectl -n shop get secret db-credentials -o jsonpath='{.data.password}')
echo "API returns: $V, which decodes to: $(echo "$V" | base64 -d)"
raw() { etcdctl --endpoints=127.0.0.1:18379 get "$1" --print-value-only; }
SEC=/registry/secrets/shop/db-credentials CM=/registry/configmaps/shop/db-settings
echo "etcd, Secret starts with: $(raw $SEC | head -c 26)"
echo "etcd, Secret lines with the password: $(raw $SEC | grep -a -c lab-only-S3cret)"
echo "etcd, ConfigMap lines with the host: $(raw $CM | grep -a -c db.shop.svc)"secret/db-credentials created
configmap/db-settings created
API returns: bGFiLW9ubHktUzNjcmV0, which decodes to: lab-only-S3cret
etcd, Secret starts with: k8s:enc:secretbox:v1:key1:
etcd, Secret lines with the password: 0
etcd, ConfigMap lines with the host: 1The API returns base64, which anyone can decode, so access to get and list on Secrets is the real control. In etcd the Secret starts with k8s:enc:secretbox:v1:key1:, the provider and key name, and the password does not appear, while the ConfigMap is readable. The key, though, sits in a file on the control plane host; for production the Kubernetes documentation recommends a KMS v2 provider, which keeps it in an external key service. Encryption happens when an object is written, so Secrets that existed before you enabled it stay unencrypted until they are written again. kubectl apply stores a full copy of the manifest, values included, in an annotation, so create Secrets with kubectl create secret or sync them from an external store such as the Secrets Store CSI Driver. In pods, prefer a mounted file to an environment variable: environment variables are copied to every child process and are easily printed in logs.
07. Step 6: Default-deny network policies
By default any pod can reach any other pod. A NetworkPolicy selects pods and lists the traffic they may send (egress) or receive (ingress); once a policy selects a pod for a direction, everything not allowed in that direction is dropped. Start with deny-all, then allow DNS and the one real flow.
# 1. Deny all ingress and egress traffic for every pod in the namespace.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny
namespace: payments
spec:
podSelector: {}
policyTypes: [Ingress, Egress]
---
# 2. Allow DNS lookups, but only to the cluster DNS pods.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-dns
namespace: payments
spec:
podSelector: {}
policyTypes: [Egress]
egress:
- to:
- namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: kube-system
podSelector:
matchLabels:
k8s-app: kube-dns
ports:
- {protocol: UDP, port: 53}
- {protocol: TCP, port: 53}
---
# 3. Let pods labelled app=web receive traffic on 8080 from the ingress namespace.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: web-from-ingress
namespace: payments
spec:
podSelector:
matchLabels:
app: web
policyTypes: [Ingress]
ingress:
- from:
- namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: ingress
ports:
- {protocol: TCP, port: 8080}kubectl apply -f netpol.yaml
kubectl -n payments get networkpolicy -o custom-columns=NAME:.metadata.name,\
SELECTOR:.spec.podSelector.matchLabels,TYPES:.spec.policyTypesnetworkpolicy.networking.k8s.io/default-deny created
networkpolicy.networking.k8s.io/allow-dns created
networkpolicy.networking.k8s.io/web-from-ingress created
NAME SELECTOR TYPES
allow-dns <none> [Egress]
default-deny <none> [Ingress Egress]
web-from-ingress map[app:web] [Ingress]The API server stores the policies but does not enforce them; the network plugin (CNI) on each node does, so enforcement cannot be shown here. kind's default plugin enforces policies from kind v0.24; elsewhere, install Calico or Cilium. The Kubernetes task Declare Network Policy shows the check to repeat on a cluster: a client pod without an allowed label runs wget --spider --timeout=1 nginx and times out.
Connecting to nginx (10.100.0.16:80)
wget: download timed out08. Step 7: Check the API server against the CIS Benchmark
The CIS Kubernetes Benchmark, from the Center for Internet Security, lists recommended settings for each component. kube-bench implements its checks by reading the flags of running processes and their configuration files. Version 0.16.0 maps Kubernetes only up to 1.34, so name its newest profile, cis-1.12, explicitly. Run nine API server checks.
KB=0.16.0
U=https://github.com/aquasecurity/kube-bench/releases/download/v$KB
curl -sSLO $U/kube-bench_${KB}_linux_amd64.tar.gz
curl -sSL $U/kube-bench_${KB}_checksums.txt \
| grep " kube-bench_${KB}_linux_amd64.tar.gz$" | sha256sum -c
mkdir -p kube-bench && tar xzf kube-bench_${KB}_linux_amd64.tar.gz -C kube-bench
rm kube-bench_${KB}_linux_amd64.tar.gz
kube-bench/kube-bench versionkube-bench_0.16.0_linux_amd64.tar.gz: OK
0.16.0CHECKS=1.2.1,1.2.2,1.2.6,1.2.8,1.2.15,1.2.16,1.2.17,1.2.23,1.2.27
kube-bench/kube-bench run --targets master --benchmark cis-1.12 \
--config-dir kube-bench/cfg --check "$CHECKS" --noremediations --nototals \
| grep -E '^\[(PASS|FAIL|WARN)\]|checks (PASS|FAIL)' \
| sed -E 's/Ensure that the //; s/ \((Automated|Manual)\)$//'[PASS] 1.2.1 --anonymous-auth argument is set to false
[FAIL] 1.2.2 --token-auth-file parameter is not set
[PASS] 1.2.6 --authorization-mode argument is not set to AlwaysAllow
[PASS] 1.2.8 --authorization-mode argument includes RBAC
[FAIL] 1.2.15 --profiling argument is set to false
[PASS] 1.2.16 --audit-log-path argument is set
[FAIL] 1.2.17 --audit-log-maxage argument is set to 30 or as appropriate
[FAIL] 1.2.23 --etcd-certfile and --etcd-keyfile arguments are set as appropriate
[PASS] 1.2.27 --encryption-provider-config argument is set as appropriate
5 checks PASS
4 checks FAILFix the two that are only flags: turn off the profiling endpoint and give the audit log a rotation policy. start-cp.sh passes APISERVER_EXTRA_FLAGS to the API server.
./stop-cp.sh
export APISERVER_EXTRA_FLAGS="--profiling=false --audit-log-maxage=30 \
--audit-log-maxbackup=10 --audit-log-maxsize=100"
./start-cp.shstopped scheduler
stopped kcm
stopped apiserver
stopped etcd
control plane ready on https://127.0.0.1:18443CHECKS=1.2.1,1.2.2,1.2.6,1.2.8,1.2.15,1.2.16,1.2.17,1.2.23,1.2.27
kube-bench/kube-bench run --targets master --benchmark cis-1.12 \
--config-dir kube-bench/cfg --check "$CHECKS" --noremediations --nototals \
| grep -E '^\[(PASS|FAIL|WARN)\]|checks (PASS|FAIL)' \
| sed -E 's/Ensure that the //; s/ \((Automated|Manual)\)$//'[PASS] 1.2.1 --anonymous-auth argument is set to false
[FAIL] 1.2.2 --token-auth-file parameter is not set
[PASS] 1.2.6 --authorization-mode argument is not set to AlwaysAllow
[PASS] 1.2.8 --authorization-mode argument includes RBAC
[PASS] 1.2.15 --profiling argument is set to false
[PASS] 1.2.16 --audit-log-path argument is set
[PASS] 1.2.17 --audit-log-maxage argument is set to 30 or as appropriate
[FAIL] 1.2.23 --etcd-certfile and --etcd-keyfile arguments are set as appropriate
[PASS] 1.2.27 --encryption-provider-config argument is set as appropriate
7 checks PASS
2 checks FAILTwo failures remain, and both are true. Static tokens (1.2.2) cannot be revoked without a restart; a real cluster uses client certificates or an OIDC provider. etcd without TLS and client certificates (1.2.23 checks the API server side of this) lets anyone who reaches its port read every object. Record them as lab exceptions with a reason. Node checks (--targets node) need a kubelet; on kind, run kube-bench as the Job from its repository. Leave the control plane running for lesson 04, or stop it with ./stop-cp.sh.
09. Check your understanding
10. Apply it
Carry this into the skill project on your kind cluster:
- Label the application namespace with
enforce: restricted(pinned to v1.37) after a week inwarnandaudit, and fix every manifest until noFailedCreateevents appear. - Apply
default-denyplus the allow rules your application needs, then test each allowed and each blocked flow with a client pod and keep the results. - Replace any
editorcluster-adminbinding used by CI with a Role likedeployment-updater, and prove it withkubectl auth can-i --list --as=.... Check shell access separately withcan-i create pods --subresource=exec, and the same forget. - Run kube-bench as a Job on the node and write down each remaining FAIL with a fix or an accepted reason.
11. Review prompt
Without looking back:
- What does a RoleBinding to a ClusterRole grant, and where?
- Why does
create podsin a namespace reach Secrets thatget secretsdenies? - Which three modes does Pod Security Admission have, and which one stops a Deployment's pods but not the Deployment itself?
- What does
k8s:enc:secretbox:v1:key1:at the start of an etcd value tell you, and what does it not protect against? - Why can the API server accept a NetworkPolicy that has no effect?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.