Kubernetes NetworkPolicy, RBAC, and SecurityContext isolation
Lock down default-open Kubernetes clusters with NetworkPolicy, least-privilege RBAC, and hardened SecurityContext, verified on kind and Calico.
A default Kubernetes cluster lets every Pod reach every other Pod, mounts a ServiceAccount token into every Pod, and runs containers as root unless you restrict them. This post walks through isolating traffic, API permissions, and container execution using
NetworkPolicy, RBAC, andSecurityContext, backed by hands-on runs onkindand Calico.
All commands and outputs below ran on a local 2-node
kindcluster (Kubernetesv1.37.0,kubectl v1.36.1,containerd 2.3.4, CNICalico v3.29.3) inside an isolatedlab-d4-secnamespace usingnginx:1.27-alpineandbusybox:1.36.Egresspolicies, Pod Security Admission (PSA), and User Namespaces (hostUsers: false, GA in Kubernetes 1.36) were not executed in this lab and are included strictly as official-documentation references.
Three default security gaps in Kubernetes
Switching a container image to a non-root user on a single Docker host is a solid first step, as covered in Hardening Docker images with non-root users and Trivy scans. Once workloads move into Kubernetes, two more boundaries open up alongside process privileges:
- Flat Pod-to-Pod networking: Without a
NetworkPolicy, any Pod in the cluster can connect directly to any other Pod’s port. If a web frontend or batch job is compromised, the attacker can move laterally straight to internal databases or admin endpoints. - Auto-mounted API tokens and overbroad RBAC: By default, Kubernetes mounts
/var/run/secrets/kubernetes.io/serviceaccount/tokeninside every Pod. If that ServiceAccount is bound to a broadRoleorClusterRole, a compromised container can readSecretobjects or delete sibling Pods. - Unrestricted container runtime privileges: If an image omits a non-root
USERand the Pod omits asecurityContext, the container runs as UID 0 (root) with default Linux capabilities and a writable root filesystem.
Because each gap lives at a different layer, no single setting covers all three. Here is how the three controls divide the work:
| Isolation layer | Core resource or setting | Enforced by | Threat mitigated | Default behavior if omitted |
|---|---|---|---|---|
| Network | NetworkPolicy | CNI plugin (Calico, Cilium, etc.) | Unauthorized Pod-to-Pod lateral movement | All Ingress and Egress traffic allowed |
| Control-plane API | ServiceAccount, Role, RoleBinding, automountServiceAccountToken | kube-apiserver | Compromised Pod reading Secrets or mutating workloads | Token auto-mounted (API actions denied until granted) |
| Runtime & kernel | Pod/Container securityContext | kubelet + container runtime (containerd) | Root execution, privilege escalation, rootfs tampering | Runs as image default UID (often 0) with writable rootfs |
Isolating Pod ingress traffic with NetworkPolicy
Kubernetes NetworkPolicy uses an allow-list model. If no NetworkPolicy selects a Pod, that Pod accepts all traffic. As soon as at least one policy with policyTypes: [Ingress] selects the Pod, every ingress packet not explicitly allowed by a matching rule is dropped. When multiple policies select the same Pod, their allow rules combine as a logical union (OR).
The safest baseline is a namespace-wide default-deny-ingress policy with an empty podSelector: {}, paired with explicit allow policies for each service path. In this test, db-svc fronts a db Pod (role=db), while api (role=api) is allowed on TCP 80 and rogue (role=rogue) is blocked.
flowchart TD
API["api Pod (role=api)"] -->|"Allow TCP 80"| SVC["db-svc (ClusterIP)"]
ROGUE["rogue Pod (role=rogue)"] -.->|"Blocked by default-deny"| DROP["Packet dropped (Timeout)"]
SVC -->|"Passes Calico policy"| DB["db Pod (role=db)"]
First, deploy db, db-svc, api, and rogue into lab-d4-sec to observe the default open behavior. For details on how ClusterIP and CoreDNS resolve db-svc to the backend Pod IP, see How Kubernetes Services and CoreDNS route traffic to Pods.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# 01-netpol-workloads.yaml (apply after creating namespace lab-d4-sec)
apiVersion: v1
kind: Pod
metadata:
name: db
namespace: lab-d4-sec
labels:
role: db
spec:
containers:
- name: nginx
image: nginx:1.27-alpine
ports:
- containerPort: 80
---
apiVersion: v1
kind: Service
metadata:
name: db-svc
namespace: lab-d4-sec
spec:
selector:
role: db
ports:
- protocol: TCP
port: 80
targetPort: 80
---
apiVersion: v1
kind: Pod
metadata:
name: api
namespace: lab-d4-sec
labels:
role: api
spec:
containers:
- name: client
image: busybox:1.36
command: ["sleep", "3600"]
---
apiVersion: v1
kind: Pod
metadata:
name: rogue
namespace: lab-d4-sec
labels:
role: rogue
spec:
containers:
- name: client
image: busybox:1.36
command: ["sleep", "3600"]
Before applying any policy, running wget -S -O /dev/null -T 3 http://db-svc from both api and rogue returns HTTP/1.1 200 OK (exit code 0). Now apply default-deny-ingress and allow-api-to-db:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# 02-netpol-rules.yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny-ingress
namespace: lab-d4-sec
spec:
podSelector: {}
policyTypes:
- Ingress
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-api-to-db
namespace: lab-d4-sec
spec:
podSelector:
matchLabels:
role: db
policyTypes:
- Ingress
ingress:
- from:
- podSelector:
matchLabels:
role: api
ports:
- protocol: TCP
port: 80
Once Calico v3.29.3 programs the dataplane rules, repeating the exact same wget command splits the two callers cleanly:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# [Before policy] both api -> db-svc and rogue -> db-svc succeed
Connecting to db-svc (10.96.111.20:80)
HTTP/1.1 200 OK
Server: nginx/1.27.5
Content-Length: 615
'/dev/null' saved
exit=0
# [After policy] api -> db-svc (allowed)
Connecting to db-svc (10.96.111.20:80)
HTTP/1.1 200 OK
Server: nginx/1.27.5
Content-Length: 615
'/dev/null' saved
exit=0
# [After policy] rogue -> db-svc (blocked)
Connecting to db-svc (10.96.111.20:80)
wget: download timed out
command terminated with exit code 1
Notice that rogue hits a timeout rather than Connection refused. Calico drops disallowed packets silently, so the client retries TCP SYN until its timeout expires.
Restricting API access with RBAC and ServiceAccount tokens
Network isolation doesn’t stop a compromised Pod from calling the Kubernetes API server if it holds a valid token and permissions. RBAC (rbac.authorization.k8s.io/v1) is deny-by-default and grants additive permissions by binding a subject (ServiceAccount) to a rule set (Role or ClusterRole) via a RoleBinding or ClusterRoleBinding.
Keep permissions scoped to the narrowest boundary: Role and RoleBinding apply only inside a single namespace, whereas ClusterRole and ClusterRoleBinding span the whole cluster. For application Pods that never talk to the Kubernetes API, set automountServiceAccountToken: false so the token file isn’t mounted into the container at all.
The manifest below creates a dedicated pod-reader-sa ServiceAccount with read-only get and list access on pods in lab-d4-sec, alongside a Pod with token auto-mounting disabled:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# 03-rbac.yaml
apiVersion: v1
kind: ServiceAccount
metadata:
name: pod-reader-sa
namespace: lab-d4-sec
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: pod-reader-role
namespace: lab-d4-sec
rules:
- apiGroups: [""]
resources: ["pods"]
verbs: ["get", "list"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: pod-reader-binding
namespace: lab-d4-sec
subjects:
- kind: ServiceAccount
name: pod-reader-sa
namespace: lab-d4-sec
roleRef:
kind: Role
name: pod-reader-role
apiGroup: rbac.authorization.k8s.io
---
apiVersion: v1
kind: Pod
metadata:
name: sa-token-disabled
namespace: lab-d4-sec
spec:
serviceAccountName: pod-reader-sa
automountServiceAccountToken: false
containers:
- name: app
image: busybox:1.36
command: ["sleep", "3600"]
You can verify exact RBAC decisions against kube-apiserver with kubectl auth can-i --as without deploying test clients:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
$ kubectl auth can-i list pods --as=system:serviceaccount:lab-d4-sec:pod-reader-sa -n lab-d4-sec
yes # exit=0
$ kubectl auth can-i get pods --as=system:serviceaccount:lab-d4-sec:pod-reader-sa -n lab-d4-sec
yes # exit=0
$ kubectl auth can-i list secrets --as=system:serviceaccount:lab-d4-sec:pod-reader-sa -n lab-d4-sec
no # exit=1
$ kubectl auth can-i delete pods --as=system:serviceaccount:lab-d4-sec:pod-reader-sa -n lab-d4-sec
no # exit=1
$ kubectl auth can-i list pods --as=system:serviceaccount:lab-d4-sec:pod-reader-sa -n default
no # exit=1
Reading pods inside lab-d4-sec succeeds (yes), while listing secrets, deleting pods, and listing pods in default all return no (exit code 1).
Comparing a default-configured Pod with automountServiceAccountToken omitted (sa-token-default, identical to the default behavior on the earlier api Pod) against sa-token-disabled confirms the token file is absent when auto-mounting is turned off:
1
2
3
4
5
6
7
8
9
10
# Default Pod (sa-token-default)
$ kubectl exec -n lab-d4-sec sa-token-default -- ls -la /var/run/secrets/kubernetes.io/serviceaccount/
lrwxrwxrwx 1 root root 13 Dec 5 14:58 ca.crt -> ..data/ca.crt
lrwxrwxrwx 1 root root 16 Dec 5 14:58 namespace -> ..data/namespace
lrwxrwxrwx 1 root root 12 Dec 5 14:58 token -> ..data/token
# automountServiceAccountToken: false (sa-token-disabled)
$ kubectl exec -n lab-d4-sec sa-token-disabled -- ls -la /var/run/secrets/kubernetes.io/serviceaccount/token
ls: /var/run/secrets/kubernetes.io/serviceaccount/token: No such file or directory
command terminated with exit code 1
You can also set automountServiceAccountToken: false directly on the ServiceAccount object. When both the ServiceAccount and the Pod specify the field, the Pod setting takes precedence.
Hardening container execution with SecurityContext
The third layer limits what a container process can do against the Linux kernel and filesystem. Before starting a container, kubelet checks the image metadata against the Pod’s securityContext and refuses to create the container if a rule fails.
Deploying nginx:1.27-alpine (which defaults to root) with runAsNonRoot: true demonstrates this kubelet-level gate:
1
2
3
4
5
6
7
8
9
10
11
12
# 04-secctx-fail.yaml
apiVersion: v1
kind: Pod
metadata:
name: secctx-root-blocked
namespace: lab-d4-sec
spec:
containers:
- name: nginx
image: nginx:1.27-alpine
securityContext:
runAsNonRoot: true
Checking the Pod status and events shows kubelet halting startup immediately with CreateContainerConfigError:
1
2
3
4
5
6
$ kubectl get pod secctx-root-blocked -n lab-d4-sec
NAME READY STATUS RESTARTS AGE
secctx-root-blocked 0/1 CreateContainerConfigError 0 4s
# Event message
Warning Failed pod/secctx-root-blocked Error: container has runAsNonRoot and image will run as root
For production workloads, combine non-root execution with four additional runtime controls:
allowPrivilegeEscalation: false: Sets the LinuxPR_SET_NO_NEW_PRIVSflag sosetuidbinaries can’t grant higher privileges than the parent process.capabilities.drop: ["ALL"]: Strips every default Linux capability (such asCAP_NET_RAWandCAP_CHOWN).seccompProfile.type: RuntimeDefault: Applies the container runtime’s default syscall filter to block dangerous system calls.readOnlyRootFilesystem: true: Mounts the container’s root filesystem read-only and exposes writable scratch paths (like/tmp) via dedicatedemptyDirvolumes.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# 05-secctx-hardened.yaml
apiVersion: v1
kind: Pod
metadata:
name: secctx-hardened
namespace: lab-d4-sec
spec:
automountServiceAccountToken: false
securityContext:
seccompProfile:
type: RuntimeDefault
containers:
- name: app
image: busybox:1.36
command: ["sleep", "3600"]
securityContext:
runAsNonRoot: true
runAsUser: 1000
runAsGroup: 1000
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop:
- ALL
volumeMounts:
- name: tmp-vol
mountPath: /tmp
volumes:
- name: tmp-vol
emptyDir: {}
Inspecting the running secctx-hardened container confirms every kernel flag and filesystem boundary took effect:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
$ kubectl exec -n lab-d4-sec secctx-hardened -- sh -c 'id; grep -E "^(CapInh|CapPrm|CapEff|CapBnd|NoNewPrivs|Seccomp):" /proc/self/status'
uid=1000 gid=1000 groups=1000
CapInh: 0000000000000000
CapPrm: 0000000000000000
CapEff: 0000000000000000
CapBnd: 0000000000000000
NoNewPrivs: 1
Seccomp: 2
$ kubectl exec -n lab-d4-sec secctx-hardened -- touch /test-ro
touch: /test-ro: Read-only file system
command terminated with exit code 1
$ kubectl exec -n lab-d4-sec secctx-hardened -- sh -c 'touch /tmp/ok && ls -l /tmp/ok'
-rw-r--r-- 1 1000 1000 0 Dec 5 14:58 /tmp/ok
# exit=0
All capability masks (CapInh, CapPrm, CapEff, CapBnd) are zeroed out, NoNewPrivs is 1, and Seccomp is 2 (filter mode). Writing to /test-ro fails with Read-only file system, while writing to the emptyDir-backed /tmp/ok succeeds.
Cluster-wide extensions and when not to tighten blindly
The three controls tested above form the per-workload baseline. Once those are in place, official Kubernetes documentation defines three broader mechanisms worth pairing with them (these three were not run in this lab and are summarized from official specs):
EgressNetworkPolicy: AddEgresstopolicyTypeswhen you need to restrict outbound connections from Pods. Always include an explicit allow rule for CoreDNS (UDP and TCP port 53 inkube-system), or every service lookup inside the namespace will time out.- Pod Security Admission (PSA): Apply
pod-security.kubernetes.io/enforce: restrictedto a namespace sokube-apiserverrejects Pods missingrunAsNonRoot,allowPrivilegeEscalation: false,capabilities.drop: ["ALL"], or a validseccompProfilebefore scheduling. - User Namespaces (
hostUsers: false): Promoted to GA in Kubernetes 1.36, User Namespaces remap container UIDs and GIDs to unprivileged host UID ranges. Even if a process escapes a container running as UID 0 internally, it doesn’t map to host root.
Tightening policies without checking runtime dependencies can cause immediate outages. Avoid three common anti-patterns:
- Enabling
readOnlyRootFilesystem: truewithout mapping writable paths: Processes such as Nginx (/var/cache/nginx,/var/run), JVMs (/tmp, heap dumps), or embedded servlet containers fail at startup unless their writable directories are backed byemptyDirmounts. - Deploying
default-deny-ingresswithout allowing probes and scrapers: Blocking traffic from your Ingress/Gateway controller or Prometheus namespace breaks external routing and metrics scraping at the same time. - Reaching for
ClusterRoleBindingout of convenience: Binding a cluster-wide role to a single-namespace workload turns one compromised Pod into a cluster-wide incident.
Production pitfalls and checklist
Warning:
kubectl applyacceptsNetworkPolicymanifests even when your cluster’s CNI does not enforce them. For example,kind’s defaultkindnetCNI silently ignoresNetworkPolicyobjects, so always verify blocking behavior from an unauthorized Pod.
Before rolling these three layers into production, run through five checks:
- Verify CNI enforcement: Confirm your CNI (Calico, Cilium, etc.) enforces
NetworkPolicyby testing that an unauthorized Pod actually times out after applyingdefault-deny-ingress. - Isolate
ServiceAccountper workload: Avoid granting permissions to thedefaultServiceAccount, create dedicated namespace-scopedRolebindings, and default toautomountServiceAccountToken: falsefor Pods that don’t call the Kubernetes API. - Audit RBAC with
kubectl auth can-i --as: Includecan-ichecks in CI or change reviews to confirm sensitive actions (list secrets,delete pods, cross-namespace reads) returnno. - Stage hardened
SecurityContextprofiles first: TestrunAsNonRoot: true,capabilities.drop: ["ALL"],readOnlyRootFilesystem: true, andseccompProfile: RuntimeDefaultin staging to identify every path that needs anemptyDirmount. - Roll out PSA with
warnandauditbeforeenforce: Label existing namespaces withpod-security.kubernetes.io/warn: restrictedandaudit: restrictedfirst, fix reported manifests, and switch toenforceonce warnings reach zero.