Apply Kubernetes Security
Harden Kubernetes clusters by enforcing RBAC least privilege, network policies, pod security standards, and encrypted secrets — preventing privilege escalation, lateral movement, and container escape.
Why This Is Best Practice
Adopted by: OWASP Kubernetes Security Cheat Sheet and CIS Kubernetes Benchmark v1.8 are the authoritative references. NSA/CISA released "Kubernetes Hardening Guidance" (2022) as official federal guidance. Google GKE Autopilot, AWS EKS default node groups, and Azure AKS enforce pod security admission and RBAC by default. Kubernetes Pod Security Standards (PSS) replaced PodSecurityPolicy in K8s 1.25 and are now the built-in hardening mechanism.
Impact: The 2022 Tesla cryptojacking incident and the 2020 SolarWinds supply chain attack both involved misconfigured Kubernetes clusters with over-permissive RBAC. Palo Alto Unit 42 (2022) found 65% of Kubernetes clusters in production had at least one container running as root. NSA/CISA guidance found that default Kubernetes configurations grant excessive permissions that enable cluster-wide lateral movement from a single compromised pod.
Why best: Default Kubernetes configuration prioritizes compatibility over security — default service accounts have API access, pods can communicate freely, and secrets are stored as base64 (not encrypted). Applying RBAC least privilege, network policies, and pod security standards systematically closes these gaps vs. relying on application-level controls alone.
Sources: OWASP Kubernetes Security Cheat Sheet; CIS Kubernetes Benchmark v1.8; NSA/CISA Kubernetes Hardening Guidance (2022); Kubernetes Pod Security Standards documentation
Steps
Enforce Pod Security Standards at the namespace level:
# Apply restricted policy to production namespace
kubectl label namespace production \
pod-security.kubernetes.io/enforce=restricted \
pod-security.kubernetes.io/enforce-version=latest \
pod-security.kubernetes.io/warn=restricted \
pod-security.kubernetes.io/audit=restricted
# Pod spec that passes restricted standard
apiVersion: v1
kind: Pod
spec:
securityContext:
runAsNonRoot: true
runAsUser: 1000
seccompProfile:
type: RuntimeDefault
containers:
- name: app
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop: ["ALL"]
resources:
limits:
cpu: "500m"
memory: "256Mi"
requests:
cpu: "100m"
memory: "128Mi"
Apply RBAC least privilege — never use cluster-admin for workloads:
# Role: namespace-scoped, specific resources and verbs only
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: app-reader
namespace: production
rules:
- apiGroups: [""]
resources: ["configmaps"]
verbs: ["get", "list"]
# NOT: resources: ["*"], verbs: ["*"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: app-reader-binding
namespace: production
subjects:
- kind: ServiceAccount
name: myapp-sa
namespace: production
roleRef:
kind: Role
name: app-reader
apiGroup: rbac.authorization.k8s.io
# Disable default service account auto-mount in pod spec
spec:
automountServiceAccountToken: false
Implement network policies — deny by default, allow by exception:
# Default deny all ingress and egress in namespace
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny-all
namespace: production
spec:
podSelector: {}
policyTypes:
- Ingress
- Egress
---
# Allow only frontend → backend on port 8080
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-frontend-to-backend
namespace: production
spec:
podSelector:
matchLabels:
app: backend
ingress:
- from:
- podSelector:
matchLabels:
app: frontend
ports:
- protocol: TCP
port: 8080
Use Kubernetes Secrets with encryption at rest — never store credentials in ConfigMaps or pod env from literals:
# Enable encryption at rest in kube-apiserver (add to --encryption-provider-config)
# encryption-config.yaml:
apiVersion: apiserver.config.k8s.io/v1
kind: EncryptionConfiguration
resources:
- resources:
- secrets
providers:
- aescbc:
keys:
- name: key1
secret: <base64-encoded-32-byte-key>
- identity: {}
# Reference secrets as volumes, not env vars (avoids exposure in pod spec)
spec:
volumes:
- name: db-creds
secret:
secretName: database-credentials
containers:
- name: app
volumeMounts:
- name: db-creds
mountPath: "/etc/secrets"
readOnly: true
For production: use External Secrets Operator with AWS Secrets Manager, HashiCorp Vault, or GCP Secret Manager instead of native K8s Secrets.
Scan images in CI and enforce admission with an OPA/Gatekeeper policy:
# Trivy operator — scans images automatically within cluster
kubectl apply -f https://raw.githubusercontent.com/aquasecurity/trivy-operator/main/deploy/static/trivy-operator.yaml
# Check scan results
kubectl get vulnerabilityreports -n production
# OPA Gatekeeper constraint: require specific image registry
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sAllowedRepos
metadata:
name: require-internal-registry
spec:
match:
kinds:
- apiGroups: [""]
kinds: ["Pod"]
parameters:
repos:
- "registry.internal.company.com/"
Audit cluster configuration with kube-bench:
# Run CIS benchmark against current node
kubectl apply -f https://raw.githubusercontent.com/aquasecurity/kube-bench/main/job.yaml
kubectl logs job/kube-bench
# Or locally
kube-bench run --targets node,master,etcd,policies
Rules
- Never bind
cluster-admin to a service account used by an application workload.
- Disable
automountServiceAccountToken: false on every pod that doesn't call the Kubernetes API.
- Network policies require a CNI plugin that enforces them (Calico, Cilium, Weave) — vanilla kubenet ignores NetworkPolicy objects.
- etcd must be encrypted at rest and accessible only to the API server — direct etcd access bypasses all RBAC.
Common Mistakes
securityContext at pod level vs container level — runAsNonRoot must be set at both levels; container-level overrides pod-level.
- Storing secrets as environment variables — environment variables appear in
kubectl describe pod and process listings; use volume mounts.
- No resource limits — a pod without limits can starve the node; resource limits are also required for
restricted pod security standard.
- Using
hostNetwork: true or hostPID: true — gives the container access to the host network stack and process namespace, defeating isolation.
1---2name: apply-kubernetes-security3description: Use when deploying workloads to Kubernetes — configuring RBAC, network policies, pod security standards, secrets management, and admission controls to prevent privilege escalation and lateral movement.4source: 'OWASP Kubernetes Security Cheat Sheet (owasp.org/www-project-cheat-sheets); CIS Kubernetes Benchmark; NIST SP 800-190; Kubernetes Pod Security Standards documentation'5tags: [security, owasp, kubernetes, rbac, containers, devops, developer]6metadata:7 source: https://skillmd.com/skills/jeffreytse/apply-kubernetes-security8---910# Apply Kubernetes Security1112Harden Kubernetes clusters by enforcing RBAC least privilege, network policies, pod security standards, and encrypted secrets — preventing privilege escalation, lateral movement, and container escape.1314## Why This Is Best Practice1516**Adopted by:** OWASP Kubernetes Security Cheat Sheet and CIS Kubernetes Benchmark v1.8 are the authoritative references. NSA/CISA released "Kubernetes Hardening Guidance" (2022) as official federal guidance. Google GKE Autopilot, AWS EKS default node groups, and Azure AKS enforce pod security admission and RBAC by default. Kubernetes Pod Security Standards (PSS) replaced PodSecurityPolicy in K8s 1.25 and are now the built-in hardening mechanism.17**Impact:** The 2022 Tesla cryptojacking incident and the 2020 SolarWinds supply chain attack both involved misconfigured Kubernetes clusters with over-permissive RBAC. Palo Alto Unit 42 (2022) found 65% of Kubernetes clusters in production had at least one container running as root. NSA/CISA guidance found that default Kubernetes configurations grant excessive permissions that enable cluster-wide lateral movement from a single compromised pod.18**Why best:** Default Kubernetes configuration prioritizes compatibility over security — default service accounts have API access, pods can communicate freely, and secrets are stored as base64 (not encrypted). Applying RBAC least privilege, network policies, and pod security standards systematically closes these gaps vs. relying on application-level controls alone.1920Sources: OWASP Kubernetes Security Cheat Sheet; CIS Kubernetes Benchmark v1.8; NSA/CISA Kubernetes Hardening Guidance (2022); Kubernetes Pod Security Standards documentation2122## Steps23241. **Enforce Pod Security Standards at the namespace level**:2526 ```bash27 # Apply restricted policy to production namespace28 kubectl label namespace production \29 pod-security.kubernetes.io/enforce=restricted \30 pod-security.kubernetes.io/enforce-version=latest \31 pod-security.kubernetes.io/warn=restricted \32 pod-security.kubernetes.io/audit=restricted33 ```3435 ```yaml36 # Pod spec that passes restricted standard37 apiVersion: v138 kind: Pod39 spec:40 securityContext:41 runAsNonRoot: true42 runAsUser: 100043 seccompProfile:44 type: RuntimeDefault45 containers:46 - name: app47 securityContext:48 allowPrivilegeEscalation: false49 readOnlyRootFilesystem: true50 capabilities:51 drop: ["ALL"]52 resources:53 limits:54 cpu: "500m"55 memory: "256Mi"56 requests:57 cpu: "100m"58 memory: "128Mi"59 ```60612. **Apply RBAC least privilege — never use `cluster-admin` for workloads**:6263 ```yaml64 # Role: namespace-scoped, specific resources and verbs only65 apiVersion: rbac.authorization.k8s.io/v166 kind: Role67 metadata:68 name: app-reader69 namespace: production70 rules:71 - apiGroups: [""]72 resources: ["configmaps"]73 verbs: ["get", "list"]74 # NOT: resources: ["*"], verbs: ["*"]75 ---76 apiVersion: rbac.authorization.k8s.io/v177 kind: RoleBinding78 metadata:79 name: app-reader-binding80 namespace: production81 subjects:82 - kind: ServiceAccount83 name: myapp-sa84 namespace: production85 roleRef:86 kind: Role87 name: app-reader88 apiGroup: rbac.authorization.k8s.io89 ```9091 ```yaml92 # Disable default service account auto-mount in pod spec93 spec:94 automountServiceAccountToken: false95 ```96973. **Implement network policies — deny by default, allow by exception**:9899 ```yaml100 # Default deny all ingress and egress in namespace101 apiVersion: networking.k8s.io/v1102 kind: NetworkPolicy103 metadata:104 name: default-deny-all105 namespace: production106 spec:107 podSelector: {}108 policyTypes:109 - Ingress110 - Egress111 ---112 # Allow only frontend → backend on port 8080113 apiVersion: networking.k8s.io/v1114 kind: NetworkPolicy115 metadata:116 name: allow-frontend-to-backend117 namespace: production118 spec:119 podSelector:120 matchLabels:121 app: backend122 ingress:123 - from:124 - podSelector:125 matchLabels:126 app: frontend127 ports:128 - protocol: TCP129 port: 8080130 ```1311324. **Use Kubernetes Secrets with encryption at rest — never store credentials in ConfigMaps or pod env from literals**:133134 ```bash135 # Enable encryption at rest in kube-apiserver (add to --encryption-provider-config)136 # encryption-config.yaml:137 apiVersion: apiserver.config.k8s.io/v1138 kind: EncryptionConfiguration139 resources:140 - resources:141 - secrets142 providers:143 - aescbc:144 keys:145 - name: key1146 secret: <base64-encoded-32-byte-key>147 - identity: {}148 ```149150 ```yaml151 # Reference secrets as volumes, not env vars (avoids exposure in pod spec)152 spec:153 volumes:154 - name: db-creds155 secret:156 secretName: database-credentials157 containers:158 - name: app159 volumeMounts:160 - name: db-creds161 mountPath: "/etc/secrets"162 readOnly: true163 ```164165 For production: use External Secrets Operator with AWS Secrets Manager, HashiCorp Vault, or GCP Secret Manager instead of native K8s Secrets.1661675. **Scan images in CI and enforce admission with an OPA/Gatekeeper policy**:168169 ```bash170 # Trivy operator — scans images automatically within cluster171 kubectl apply -f https://raw.githubusercontent.com/aquasecurity/trivy-operator/main/deploy/static/trivy-operator.yaml172173 # Check scan results174 kubectl get vulnerabilityreports -n production175 ```176177 ```yaml178 # OPA Gatekeeper constraint: require specific image registry179 apiVersion: constraints.gatekeeper.sh/v1beta1180 kind: K8sAllowedRepos181 metadata:182 name: require-internal-registry183 spec:184 match:185 kinds:186 - apiGroups: [""]187 kinds: ["Pod"]188 parameters:189 repos:190 - "registry.internal.company.com/"191 ```1921936. **Audit cluster configuration with kube-bench**:194195 ```bash196 # Run CIS benchmark against current node197 kubectl apply -f https://raw.githubusercontent.com/aquasecurity/kube-bench/main/job.yaml198 kubectl logs job/kube-bench199200 # Or locally201 kube-bench run --targets node,master,etcd,policies202 ```203204## Rules205206- Never bind `cluster-admin` to a service account used by an application workload.207- Disable `automountServiceAccountToken: false` on every pod that doesn't call the Kubernetes API.208- Network policies require a CNI plugin that enforces them (Calico, Cilium, Weave) — vanilla kubenet ignores NetworkPolicy objects.209- etcd must be encrypted at rest and accessible only to the API server — direct etcd access bypasses all RBAC.210211## Common Mistakes212213- **`securityContext` at pod level vs container level** — `runAsNonRoot` must be set at both levels; container-level overrides pod-level.214- **Storing secrets as environment variables** — environment variables appear in `kubectl describe pod` and process listings; use volume mounts.215- **No resource limits** — a pod without limits can starve the node; resource limits are also required for `restricted` pod security standard.216- **Using `hostNetwork: true` or `hostPID: true`** — gives the container access to the host network stack and process namespace, defeating isolation.