Harden a Kubernetes workload with Pod Security, NetworkPolicies and a non-root image
This article was first published on the Rokkhe blog on Hashnode. It was drafted with AI assistance and reviewed and edited by the Rokkhe team; all commands and sources were checked against Kubernetes and NSA/CISA documen
This article was first published on the Rokkhe blog on Hashnode. It was drafted with AI assistance and reviewed and edited by the Rokkhe team; all commands and sources were checked against Kubernetes and NSA/CISA documentation.
One namespace, one Deployment, official Kubernetes and NSA/CISA guidance. 17 November 2026, Asia/Dhaka. By the Rokkhe research team.
You do not have to harden an entire cluster this afternoon. You can harden one workload: the Deployment you actually ship, in a namespace you control. Kubernetes already has a built-in admission controller for Pod Security Standards, and NetworkPolicies are a stable API. The NSA/CISA Kubernetes Hardening Guidance (version 1.2, August 2022) recommends the same ideas: run with least privilege, reject privileged features, and limit network paths.
The steps below assume you have kubectl context on a non-production cluster, and permission to change one namespace. Apply them to production only after you have seen what the Restricted profile rejects.
This is post 7 of the Rokkhe hardening series. Post 1 locked down the CI pipeline that builds your image, and post 6 tested the API that usually runs inside a workload like this one.
TL;DR
- Label the namespace so Pod Security Admission enforces the
restrictedprofile, after a day ofwarnorauditif you need a dry run. - Set a
securityContextthat runs as a non-root user, drops capabilities, and mounts the root filesystem read-only where the app allows it. - Add a default-deny NetworkPolicy, then allow only the ingress and egress the app needs.
- Pin the container image by digest, not by a floating
latesttag. - Use
kubectlto apply, describe and, if needed, roll back. Nothing here is an exploit.
Harden the workload first, not the whole cluster
Cluster-wide controls (control-plane flags, etcd encryption, admission webhooks for the whole fleet) matter, and they are also easy to stall on. A single namespace still gives you:
- A clear blast radius: if the policy is too strict, one application is noisy, not every team.
- A template you can copy into the next namespace.
- Alignment with the official Pod Security Admission model, which is namespace-scoped.
Create a playground namespace if you do not already have one:
kubectl create namespace app-harden-demo
kubectl config set-context --current --namespace=app-harden-demo
Enforce Pod Security Admission at Restricted
Kubernetes defines three Pod Security Standard levels: privileged, baseline, and restricted. restricted is the one that βfollows current Pod hardening best practices.β Admission can enforce (reject the Pod), warn, or audit.
Start with warn, so you see what would break:
kubectl label namespace app-harden-demo \
pod-security.kubernetes.io/warn=restricted \
pod-security.kubernetes.io/warn-version=latest \
--overwrite
Deploy or re-roll the application, and read the warnings. Fix the Pod template until they stop. Then enforce:
kubectl label namespace app-harden-demo \
pod-security.kubernetes.io/enforce=restricted \
pod-security.kubernetes.io/enforce-version=latest \
--overwrite
Admission evaluates new Pods. Workloads that are already running are not retroactively evicted by this label; they pick the policy up on the next create or replacement. Plan a rolling restart after you enforce, then confirm the new Pods are actually admitted:
kubectl rollout restart deployment/app
kubectl rollout status deployment/app
kubectl get pods -n app-harden-demo
If a Pod is rejected, kubectl describe and the event log will usually name the field (for example, a missing securityContext or a disallowed volume type). Fix the template; do not quietly drop the namespace back to privileged.
Run as non-root, drop capabilities, make the root filesystem read-only
A Restricted-friendly container template looks like this. Adjust runAsUser / runAsGroup to the numeric user your image already defines (many images use a non-root UID in their Dockerfile; if yours does not, change the image first rather than forcing a user the process cannot run as).
apiVersion: apps/v1
kind: Deployment
metadata:
name: app
namespace: app-harden-demo
spec:
replicas: 2
selector:
matchLabels:
app: app
template:
metadata:
labels:
app: app
spec:
automountServiceAccountToken: false
securityContext:
runAsNonRoot: true
runAsUser: 65532
runAsGroup: 65532
fsGroup: 65532
seccompProfile:
type: RuntimeDefault
containers:
- name: app
image: ghcr.io/example/app@sha256:DIGEST
ports:
- containerPort: 8080
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop: ["ALL"]
volumeMounts:
- name: tmp
mountPath: /tmp
resources:
requests:
cpu: "100m"
memory: "128Mi"
limits:
cpu: "500m"
memory: "256Mi"
volumes:
- name: tmp
emptyDir: {}
Points that match official guidance:
-
runAsNonRoot: trueand an explicit UID, so the container cannot run as root. -
allowPrivilegeEscalation: falseandcapabilities.drop: ["ALL"]. -
seccompProfile: RuntimeDefault. - A read-only root filesystem, with an
emptyDirfor/tmpif the process must write. -
automountServiceAccountToken: falseunless the Pod truly calls the Kubernetes API. If it does, use a dedicated ServiceAccount with a tight Role, not the default account in the namespace.
NSA/CISA also recommend immutable filesystems and avoiding hostPath, hostNetwork, hostPID and hostIPC. The Restricted profile already rejects those host namespaces and privileged containers. Do not add them back with exemptions without a written reason.
Add a default-deny NetworkPolicy, then allow what you need
A NetworkPolicy is enforced only if your cluster has a policy-capable CNI (Calico, Cilium, a cloud providerβs implementation, and others). If policies have no effect, fix that before you rely on them.
A conservative starting point is default-deny for the namespace, then a second policy that allows the traffic you need. Kubernetes documents this pattern.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny-all
namespace: app-harden-demo
spec:
podSelector: {}
policyTypes: ["Ingress", "Egress"]
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-app
namespace: app-harden-demo
spec:
podSelector:
matchLabels:
app: app
policyTypes: ["Ingress", "Egress"]
ingress:
- from:
- podSelector:
matchLabels:
role: frontend
ports:
- protocol: TCP
port: 8080
egress:
- to:
- namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: kube-system
ports:
- protocol: UDP
port: 53
- protocol: TCP
port: 53
- to:
- podSelector:
matchLabels:
app: database
ports:
- protocol: TCP
port: 5432
Replace the frontend, DNS and database rules with the peers you actually have. If the app must reach an external API, add an egress rule for that destination rather than opening all outbound traffic. Test with a temporary debug Pod only if your policy allows it, and delete that Pod when you are done.
kubectl apply -f networkpolicy.yaml
kubectl get networkpolicy -n app-harden-demo
kubectl describe networkpolicy allow-app -n app-harden-demo
Scan and pin the image you actually run
image: org/app:latest is a moving target. Pin a digest:
# After you have pulled a reviewed image:
docker image inspect --format '{{index .RepoDigests 0}}' ghcr.io/example/app:1.4.2
Put that @sha256:β¦ in the Deployment, the same way post 1 pinned Actions. Scan the image with the scanner your organisation already uses before you promote it. NSA/CISA lead with βscan containers and Podsβ; the exact tool is your choice, the habit is not.
Also drop unnecessary base packages from the image, and prefer a distroless or minimal image if the runtime supports it. That is packaging work, not a Kubernetes API change, and it reduces what an attacker can run if the process is compromised.
Apply, test, and see what breaks
A practical order:
- Warn-mode Pod Security, fix the template, then enforce.
- Add
securityContextand a pinned digest; rolling-restart; confirm readiness probes still pass. - Apply default-deny and the allow policies; confirm the app still reaches its database and still serves its frontend.
- From another namespace, confirm you can no longer reach the Pod on 8080 unless a policy allows it.
If the Restricted profile rejects a sidecar you do not control (a vendor agent that wants to run as root), isolate that sidecar in a different namespace with a weaker profile, or take the exception to the vendor. Do not weaken the application namespace to accommodate it without recording the exception.
Rollback is ordinary Kubernetes:
kubectl rollout undo deployment/app -n app-harden-demo
# Policies and labels can be removed if you must, but treat that as an incident, not a habit.
Checklist
- [ ] Namespace has
pod-security.kubernetes.io/enforce=restricted. - [ ] The Pod runs as a non-root UID, with
allowPrivilegeEscalation: falseand capabilities dropped. - [ ] Root filesystem is read-only, or a written exception exists.
- [ ] The ServiceAccount token is not auto-mounted unless the app calls the Kubernetes API.
- [ ] A default-deny NetworkPolicy is in place, plus explicit allow rules.
- [ ] The container image is pinned by digest and has been scanned.
- [ ] A rolling restart succeeded after enforcement; probes are green.
- [ ] Rollback (
kubectl rollout undo) was tested in the demo namespace.
FAQ
Is Baseline enough?
Baseline already blocks many known privilege-escalation paths. Restricted is the official βcurrent hardeningβ profile. Prefer Restricted, and use Baseline only as a short migration step with warn/audit on Restricted.
Our CNI does not enforce NetworkPolicy. Are the YAML files useful?
They document intent, but they are not a control until a policy-capable plugin is in place. Fix the plugin, then apply the policies.
Will readOnlyRootFilesystem break our app?
If the process writes to /tmp or a cache, give it an emptyDir. If it writes into its own image layer, that is a reason to change the app, not a reason to skip the control forever.
Does this replace cluster hardening?
No. It is the workload slice of NSA/CISAβs guidance. Control-plane access, etcd, and node hardening remain separate work.
Sources
- Kubernetes Docs, Pod Security Standards
- Kubernetes Docs, Pod Security Admission
- Kubernetes Docs, Network Policies
- NSA/CISA, Kubernetes Hardening Guidance, version 1.2 (August 2022)
Next in the series
Next up: Stop prompt injection in your LLM app: a practical OWASP LLM Top 10 checklist.
Previous: Test your API against the OWASP API Security Top 10 2023. Start of the series: Pin your GitHub Actions by commit SHA and lock workflow permissions.
Rokkhe is an AI pentesting and security-operations workspace. Learn more at rokkhe.com.
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.