Skip to Content

Kubernetes Field Guide · Chapter 11 of 16

Namespaces, RBAC and network policies

A default cluster trusts everything: any pod can reach any other, and anyone with credentials may be able to do far too much. Learn the four layers that fix that: namespaces and quotas, RBAC, pod security, and network policies.

  • 40 min
  • Advanced
  • Hands-on
  • Free

By , founding engineer running Kubernetes in production. Updated .

developerrole: viewnamespace: shopnamespace: paymentsget pods ✓Forbiddenfrontendapidbpaymentsfrontend to db: blocked by NetworkPolicyallowed
The chapter in one pictureRBAC decides who can do what. Network policies decide which pods can talk.

By the end you can

0 of 5

Namespaces and quotas

A namespace groups resources and scopes names, RBAC and quotas. It is the unit you hand to a team or an environment. On its own it isolates nothing: pods in different namespaces can still talk to each other, and a cluster-wide permission still applies everywhere.

A ResourceQuota caps what one namespace can consume, which is also a cost control:

quota.yaml
apiVersion: v1
kind: ResourceQuota
metadata:
  name: team-a
  namespace: team-a
spec:
  hard:
    requests.cpu: "8"
    requests.memory: 16Gi
    limits.memory: 24Gi
    pods: "50"
    services.loadbalancers: "0"
The sum of all CPU requests in the namespace may not exceed 8 cores.
No team can create a billed cloud load balancer by accident.
Caps runaway scaling. With a quota on CPU or memory, every pod must set requests, so pair it with a LimitRange that sets defaults.

RBAC: who can do what

Role-based access control has four objects. A Role lists allowed verbs on resources in one namespace; a ClusterRole does the same cluster-wide or for cluster-scoped things like nodes. A RoleBinding or ClusterRoleBinding grants a role to users, groups or service accounts. Everything not granted is denied, and there are no deny rules.

Step through it

Every request passes the same three gates

  1. kubectl or CIa request
  2. Authenticationwho are you?
  3. AuthorizationRBAC: allowed?
  4. AdmissionPod Security, policies
  5. etcdstored

Step 0 of 5

Press Play, or step through with Next.

rbac.yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: deployer
  namespace: team-a
rules:
  - apiGroups: ["apps"]
    resources: ["deployments"]
    verbs: ["get", "patch"]
  - apiGroups: [""]
    resources: ["pods"]
    verbs: ["get", "list"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: ci-deployer
  namespace: team-a
subjects:
  - kind: ServiceAccount
    name: ci-deployer
    namespace: team-a
roleRef:
  kind: Role
  name: deployer
  apiGroup: rbac.authorization.k8s.io
Deployments live in the apps API group. Core objects like pods use "".
get, list, watch, create, update, patch, delete. list on Secrets reveals every value.
Who receives the role: here, the service account a CI pipeline uses.

Ask the cluster the same questions it asks itself:

Interactive

kubectl auth can-i, simulated

For people, bind the built-in view, edit and admin ClusterRoles with a RoleBinding in one namespace. Treat cluster-admin, and the escalate, bind and impersonate verbs, as root.

Service accounts and workload identity

Pods authenticate to the API server as a service account. Each namespace has a default one, and its token is mounted into every pod unless you turn that off. Most apps never call the Kubernetes API, so set automountServiceAccountToken: false and give the few that do their own account and Role.

For cloud access, never put static keys in Secrets. Map service accounts to cloud identities: EKS Pod Identity or IRSA on AWS, Workload Identity on Azure and GKE. Pods get short-lived credentials for exactly one role.

Pod security

A container running as root with every Linux capability is one kernel bug away from the node. Pod Security Admission enforces one of three standards per namespace with a label:

  • privileged: anything goes. Only for system components that need it.
  • baseline: blocks the known escalations (privileged mode, host networking, hostPath).
  • restricted: also requires non-root, no privilege escalation, dropped capabilities and a seccomp profile. The target for your apps.
pod spec meeting restricted
spec:
  automountServiceAccountToken: false
  securityContext:
    runAsNonRoot: true
    runAsUser: 10001
    seccompProfile:
      type: RuntimeDefault
  containers:
    - name: api
      image: ghcr.io/example/api:2.3.0
      securityContext:
        allowPrivilegeEscalation: false
        readOnlyRootFilesystem: true
        capabilities:
          drop: ["ALL"]
Refuse to start as root. The image must define a non-root user, or set runAsUser.
An attacker cannot drop tools into the container. Mount an emptyDir where the app must write.
Removes Linux capabilities such as changing file ownership or binding raw sockets.

Network policies

By default every pod can reach every other pod in the cluster. A compromised frontend can talk straight to your database. Network policies fix that, but only if your network plugin enforces them (Calico, Cilium and K3s's built-in controller do).

Interactive

Network policies: who can reach whom

FromToResult
Policies only add allowed paths. Once any policy selects a pod, everything not allowed to it is denied.
netpol.yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny-ingress
  namespace: team-a
spec:
  podSelector: {}
  policyTypes: ["Ingress"]
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: api-from-frontend
  namespace: team-a
spec:
  podSelector:
    matchLabels:
      app: api
  ingress:
    - from:
        - podSelector:
            matchLabels:
              app: frontend
      ports:
        - port: 8080
Selects every pod in the namespace. With no ingress rules, all incoming traffic is denied.
Only pods labelled app=frontend, in the same namespace. Add a namespaceSelector to allow other namespaces.
Controls incoming traffic only. Egress default-deny also blocks DNS unless you allow port 53 to CoreDNS.

Defence in depth: putting it together

No single control stops a determined attacker. Each one assumes the previous one can fail, and cuts the path at a different step. Start with every defence off, then switch them on one at a time.

Interactive · Attack path

Your frontend is compromised. How far does it go?

    Hands-on: lock down a namespace

    Live lab · no install

    Lock down a namespace

    RBAC, Pod Security and network policies, each tested from the inside.

    kind-learn
    1. Tasks0/8
    2. Create a namespace that enforces "restricted"
      kubectl create namespace team-a
      kubectl label namespace team-a pod-security.kubernetes.io/enforce=restricted
    3. Give CI its own identity and Role

      rbac.yaml lets ci-deployer patch Deployments and read pods in team-a, nothing else.

      kubectl -n team-a create serviceaccount ci-deployer
      kubectl apply -f rbac.yaml
    4. Test its permissions
      kubectl auth can-i patch deployments -n team-a --as system:serviceaccount:team-a:ci-deployer
      kubectl auth can-i get secrets -n team-a --as system:serviceaccount:team-a:ci-deployer
    5. Act as CI and get refused

      The same --as flag works on any command.

      kubectl get secrets -n team-a --as system:serviceaccount:team-a:ci-deployer
    6. Try a pod that breaks the standard
      kubectl -n team-a run web --image=nginx:1.27

      Rejected at admission, before anything ran. Each clause names the field to set.

    7. Deploy apps that meet it

      apps.yaml has an api and two client pods, each with the securityContext the standard asks for.

      kubectl apply -f apps.yaml
      kubectl -n team-a rollout status deploy/api
    8. Show that every pod can reach the api
      kubectl -n team-a exec other -- wget -qO- -T 3 http://api:8080

      By default the pod network is flat: anything can talk to anything.

    9. Default deny, then allow only the frontend
      kubectl apply -f netpol.yaml
      kubectl -n team-a exec frontend -- wget -qO- -T 3 http://api:8080
      kubectl -n team-a exec other -- wget -qO- -T 3 http://api:8080
    10. Lab complete. Keep experimenting, or press Reset to start again.
    ↑↓ history · Tab complete · Ctrl+C stop
    Cluster map live
    • ready
    • starting / not ready
    • failing
    • terminating
    Prefer your own machine? The same steps on a local cluster

    Create a namespace that enforces the restricted standard, and a CI service account with the Role above:

    Terminal
    kubectl create namespace team-a
    kubectl label namespace team-a pod-security.kubernetes.io/enforce=restricted
    kubectl -n team-a create serviceaccount ci-deployer
    kubectl apply -f rbac.yaml
    kubectl auth can-i patch deployments -n team-a --as system:serviceaccount:team-a:ci-deployer
    kubectl auth can-i get secrets -n team-a --as system:serviceaccount:team-a:ci-deployer
    yes
    no
    --as
    Impersonate the service account to test its permissions. Requires impersonate rights, which cluster admins have.

    Now try to run a container that does not meet the standard:

    Terminal
    kubectl -n team-a run web --image=nginx:1.27
    Error from server (Forbidden): pods "web" is forbidden: violates PodSecurity "restricted:latest": allowPrivilegeEscalation != false (container "web" must set securityContext.allowPrivilegeEscalation=false), unrestricted capabilities (container "web" must set securityContext.capabilities.drop=["ALL"]), runAsNonRoot != true (pod or container "web" must set securityContext.runAsNonRoot=true), seccompProfile (pod or container "web" must set securityContext.seccompProfile.type to "RuntimeDefault" or "Localhost")
    Forbidden
    Rejected at admission: the pod was never created. Each clause names the field to fix.

    Mini mission

    Default deny, then allow one path

    In a new namespace netlab, run an nginx pod labelled app=api with a Service, and two client pods labelled app=frontend and app=other. Allow only the frontend to reach the api.

    Reveal one safe solution
    Terminal
    kubectl create namespace netlab
    kubectl -n netlab run api --image=nginx:1.27 --labels=app=api --expose --port=80
    kubectl -n netlab run frontend --image=busybox:1.37 --labels=app=frontend -- sleep 3600
    kubectl -n netlab run other --image=busybox:1.37 --labels=app=other -- sleep 3600
    kubectl -n netlab apply -f - <<'EOF'
    apiVersion: networking.k8s.io/v1
    kind: NetworkPolicy
    metadata:
      name: api-from-frontend
    spec:
      podSelector:
        matchLabels:
          app: api
      ingress:
        - from:
            - podSelector:
                matchLabels:
                  app: frontend
          ports:
            - port: 80
    EOF
    kubectl -n netlab exec frontend -- wget -qO- -T 3 http://api | head -n 4
    kubectl -n netlab exec other -- wget -qO- -T 3 http://api
    

    The frontend gets the nginx page; other times out. Selecting the api pod with any policy was enough to deny everything else to it. Clean up with kubectl delete namespace netlab team-a.

    Check yourself

    Quiz

    0 of 4 answered

    1. 1. Is a namespace a security boundary by itself?
    2. 2. A CI pipeline only needs to update one Deployment's image. What should it get?
    3. 3. How should a pod on EKS read from S3?
    4. 4. You add a default-deny ingress policy to a namespace. What breaks?

    Further reading