Cloud Native › Kubernetes

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.

Kubernetes NetworkPolicy, RBAC, and SecurityContext isolation

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, and SecurityContext, backed by hands-on runs on kind and Calico.

All commands and outputs below ran on a local 2-node kind cluster (Kubernetes v1.37.0, kubectl v1.36.1, containerd 2.3.4, CNI Calico v3.29.3) inside an isolated lab-d4-sec namespace using nginx:1.27-alpine and busybox:1.36. Egress policies, 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:

  1. 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.
  2. Auto-mounted API tokens and overbroad RBAC: By default, Kubernetes mounts /var/run/secrets/kubernetes.io/serviceaccount/token inside every Pod. If that ServiceAccount is bound to a broad Role or ClusterRole, a compromised container can read Secret objects or delete sibling Pods.
  3. Unrestricted container runtime privileges: If an image omits a non-root USER and the Pod omits a securityContext, 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 layerCore resource or settingEnforced byThreat mitigatedDefault behavior if omitted
NetworkNetworkPolicyCNI plugin (Calico, Cilium, etc.)Unauthorized Pod-to-Pod lateral movementAll Ingress and Egress traffic allowed
Control-plane APIServiceAccount, Role, RoleBinding, automountServiceAccountTokenkube-apiserverCompromised Pod reading Secrets or mutating workloadsToken auto-mounted (API actions denied until granted)
Runtime & kernelPod/Container securityContextkubelet + container runtime (containerd)Root execution, privilege escalation, rootfs tamperingRuns 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 Linux PR_SET_NO_NEW_PRIVS flag so setuid binaries can’t grant higher privileges than the parent process.
  • capabilities.drop: ["ALL"]: Strips every default Linux capability (such as CAP_NET_RAW and CAP_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 dedicated emptyDir volumes.
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):

  • Egress NetworkPolicy: Add Egress to policyTypes when you need to restrict outbound connections from Pods. Always include an explicit allow rule for CoreDNS (UDP and TCP port 53 in kube-system), or every service lookup inside the namespace will time out.
  • Pod Security Admission (PSA): Apply pod-security.kubernetes.io/enforce: restricted to a namespace so kube-apiserver rejects Pods missing runAsNonRoot, allowPrivilegeEscalation: false, capabilities.drop: ["ALL"], or a valid seccompProfile before 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: true without 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 by emptyDir mounts.
  • Deploying default-deny-ingress without 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 ClusterRoleBinding out 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 apply accepts NetworkPolicy manifests even when your cluster’s CNI does not enforce them. For example, kind’s default kindnet CNI silently ignores NetworkPolicy objects, so always verify blocking behavior from an unauthorized Pod.

Before rolling these three layers into production, run through five checks:

  1. Verify CNI enforcement: Confirm your CNI (Calico, Cilium, etc.) enforces NetworkPolicy by testing that an unauthorized Pod actually times out after applying default-deny-ingress.
  2. Isolate ServiceAccount per workload: Avoid granting permissions to the default ServiceAccount, create dedicated namespace-scoped Role bindings, and default to automountServiceAccountToken: false for Pods that don’t call the Kubernetes API.
  3. Audit RBAC with kubectl auth can-i --as: Include can-i checks in CI or change reviews to confirm sensitive actions (list secrets, delete pods, cross-namespace reads) return no.
  4. Stage hardened SecurityContext profiles first: Test runAsNonRoot: true, capabilities.drop: ["ALL"], readOnlyRootFilesystem: true, and seccompProfile: RuntimeDefault in staging to identify every path that needs an emptyDir mount.
  5. Roll out PSA with warn and audit before enforce: Label existing namespaces with pod-security.kubernetes.io/warn: restricted and audit: restricted first, fix reported manifests, and switch to enforce once warnings reach zero.

References

If you want to control traffic flow at the IP address or port level (OSI layer 3 or 4), NetworkPolicies allow you to specify rules for traffic flow within your cluster, and also between Pods and the outside world. Your cluster must use a network plugin that supports NetworkPolicy enforcement.
Role-based access control (RBAC) is a method of regulating access to computer or network resources based on the roles of individual users within your organization. RBAC authorization uses the rbac.authorization.k8s.io API group to drive authorization decisions, allowing you to dynamically configure policies through the Kubernetes API. To enable RBAC, start the API server with the --authorization-config flag set to a file that includes the RBAC authorizer; for example:
A security context defines privilege and access control settings for a Pod or Container. Security context settings include, but are not limited to: Discretionary Access Control: Permission to access an object, like a file, is based on user ID (UID) and group ID (GID). Security Enhanced Linux (SELinux): Objects are assigned security labels. Running as privileged or unprivileged. Linux Capabilities: Give a process some privileges, but not all the privileges of the root user.
Feature state: Stable since Kubernetes v1.36 More information about this feature This is a stable feature in Kubernetes, and has been since version v1.36. It was first available in the v1.28 release. You can no longer disable or opt out of this feature or behavior (it is locked); if you explicitly set a value for the associated feature gate UserNamespacesSupport, Kubernetes ignores it but does not report any error.
This post is licensed under CC BY 4.0 by the author.