Kubernetes Security
Implement Kubernetes security best practices with Pod Security Standards, runAsNonRoot, readOnlyRootFilesystem, NetworkPolicies, and secrets.
Securing a Kubernetes cluster requires defense-in-depth across the 4C's of cloud native security: Cloud, Cluster, Container, and Code. Modern Kubernetes enforces security boundaries through Pod Security Standards (PSA/PSS), container security contexts, non-root execution, immutable filesystems, and strict network segmentation via NetworkPolicies.
Pod Security Standards (PSS) and Admission
In modern Kubernetes, the deprecated PodSecurityPolicy (PSP) has been replaced by the built-in Pod Security Admission (PSA) controller, which enforces three cumulative Pod Security Standards at the namespace level:
| Standard Level | Description | Key Restrictions | Typical Use Case |
|---|---|---|---|
| Privileged | Completely unrestricted | Allows root execution, host namespaces (hostPID, hostNetwork), and raw capabilities |
CNI plugins, storage drivers, system node daemons |
| Baseline | Minimally restrictive | Prevents known privilege escalations; blocks host ports and raw access | General microservices, internal line-of-business apps |
| Restricted | Hardened best practices | Requires runAsNonRoot, readOnlyRootFilesystem, drops all capabilities except NET_BIND_SERVICE, enforces seccomp |
Production workloads, multi-tenant clusters, PCI/HIPAA environments |
Hardened Deployment and NetworkPolicy Manifests
1. Hardened Pod SecurityContext Manifest
apiVersion: apps/v1
kind: Deployment
metadata:
name: secure-auth-api
namespace: secure-apps
spec:
replicas: 3
selector:
matchLabels:
app: secure-auth-api
template:
metadata:
labels:
app: secure-auth-api
spec:
securityContext:
runAsNonRoot: true
runAsUser: 10001
runAsGroup: 10001
fsGroup: 10001
seccompProfile:
type: RuntimeDefault
containers:
- name: secure-auth-api
image: secure-auth-api:1.4.0
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop:
- ALL
volumeMounts:
- name: tmp-volume
mountPath: /tmp
volumes:
- name: tmp-volume
emptyDir: {}
2. Default-Deny NetworkPolicy Manifest
By default, all Pods in a Kubernetes cluster can communicate with each other freely. The following NetworkPolicy isolates database Pods, allowing ingress only from authenticated API Pods on port 5432:
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: isolate-database
namespace: secure-apps
spec:
podSelector:
matchLabels:
app: customer-database
policyTypes:
- Ingress
- Egress
ingress:
- from:
- podSelector:
matchLabels:
app: secure-auth-api
ports:
- protocol: TCP
port: 5432
egress: [] # No egress allowed
Security Operations and Auditing with kubectl
# Enforce Restricted Pod Security Standard on a namespace
kubectl label --overwrite namespace secure-apps \
pod-security.kubernetes.io/enforce=restricted \
pod-security.kubernetes.io/enforce-version=latest \
pod-security.kubernetes.io/warn=restricted
# Audit active NetworkPolicies in a namespace
kubectl get networkpolicies -n secure-apps
# Test Pod execution permissions under restricted security
kubectl auth can-i create pods --as=developer -n secure-apps
Common Mistakes
- Running containers as root (UID 0): Omitting
runAsNonRoot: truelets compromised processes exploit container escapes or host kernel vulnerabilities with full administrative privileges. - Granting broad Linux capabilities: Leaving default Linux capabilities enabled gives containers access to low-level kernel primitives (such as
CAP_SYS_ADMINor raw packet sniffing). - Omitting NetworkPolicies (Flat Network): Operating a flat network allows an attacker compromising an exposed frontend Pod to pivot laterally to internal Redis caches and databases.
- Storing unencrypted secrets in Git: Committing base64-encoded Kubernetes Secrets to source control leads to credential leakage. Use tools like HashiCorp Vault, External Secrets Operator, or Sealed Secrets.
Best Practices
- Enforce
pod-security.kubernetes.io/enforce=restrictedon all application namespaces. - Always declare
securityContextwithrunAsNonRoot: true,allowPrivilegeEscalation: false, andreadOnlyRootFilesystem: true. - Implement a default-deny
NetworkPolicyon every production namespace and explicitly allow required traffic flows. - Disable auto-mounting of Kubernetes API tokens (
automountServiceAccountToken: false) unless the Pod explicitly requires Kubernetes API access.
Interview Questions
1. What replaced PodSecurityPolicies (PSP) in Kubernetes and how does it work?
PodSecurityPolicy was deprecated and removed in Kubernetes 1.25. It was replaced by the built-in Pod Security Admission (PSA) controller, which enforces three standard levels (Privileged, Baseline, Restricted) configured via namespace labels (pod-security.kubernetes.io/enforce).
2. What is the difference between Baseline and Restricted Pod Security Standards?
Baseline prevents known privilege escalation vectors (blocks host namespaces, host networking, host paths, and privileged execution) while remaining easy to adopt without app changes. Restricted enforces strict container hardening, requiring non-root execution (runAsNonRoot), dropping all Linux capabilities, enforcing readOnlyRootFilesystem, and setting seccompProfile: RuntimeDefault.
3. How does a default-deny NetworkPolicy work?
A default-deny NetworkPolicy selects all Pods in a namespace (podSelector: {}) and declares policyTypes: [Ingress, Egress] with empty ingress and egress rule arrays. Kubernetes immediately drops all unsolicited inbound and outbound network traffic across the namespace until explicit allow rules are created.
4. Why should you set readOnlyRootFilesystem: true?
Setting readOnlyRootFilesystem: true prevents an attacker who exploits an application vulnerability (such as remote code execution) from downloading malicious payloads, installing crypto miners, modifying configuration binaries, or tampering with system binaries inside the container.
5. What does allowPrivilegeEscalation: false do?
allowPrivilegeEscalation: false maps directly to the Linux kernel no_new_privs flag. It guarantees that child processes created within the container cannot gain more privileges than their parent process, preventing attacks using setuid binaries (such as sudo or passwd).
6. Why should you set automountServiceAccountToken: false on application Pods?
By default, Kubernetes mounts a JWT API token at /var/run/secrets/kubernetes.io/serviceaccount/token inside every container. If the application is compromised, an attacker can extract this token and query the Kubernetes API server. Disabling token mounting blocks this lateral movement vector for workloads that do not need to call the Kubernetes API.
Summary
- Pod Security Admission enforces
Privileged,Baseline, andRestrictedprofiles via namespace labels. - Container security contexts must drop all Linux capabilities and run as non-root users.
- NetworkPolicies eliminate flat networks by segmenting ingress and egress microservice traffic.
- Never commit raw Kubernetes Secrets to source control repositories.
Continue Learning
Previous: Rolling Update and Rollback | Next: RBAC
Was this guide helpful?
CodeWithVenu is free to read, with no paywall. If this guide saved you time or helped you prepare, a small voluntary contribution helps me write more practical tutorials, architecture guides, and interview-prep content.