DevOps.Academy
CoursesCurriculumInterview prepPricing
◔My learningSign in
DevOps.Academy

Free, hands-on DevOps lessons. Made with care in India.

System status

Learn

All coursesLinux roadmapCurriculumInterview questionsCheat sheetsMy learning

Academy

PricingCertificates

Legal

PrivacyTermsContact

devops.rajeev.pro

Kubernetes & HelmLesson 8 of 16
Your progress · 0%
On this page
  1. RBAC
  2. Network policies
  3. Pod Security admission
↖ Course roadmap
Lesson 8 · Security

Security: RBAC, network policies, Pod Security

Three layers of cluster security: who may do what (RBAC), which Pods may talk to which (NetworkPolicies), and what a Pod may do on its node (Pod Security admission), each shown working and failing.

35 min read · intermediate · hands-on

By the end of this lesson you'll be able to

0 of 4 complete
Lab status

Verified lab: RBAC allow and deny, NetworkPolicies blocking and allowing traffic (VPC CNI network policy support enabled), and Pod Security admission rejecting a privileged Pod, on the course's EKS cluster. The output shown is real.
Code walkthrough: EKS access entries (explained; the lab's admin access came from one).
Cloud lab: none needed for RBAC and Pod Security. NetworkPolicies need a CNI that enforces them (kind's default does not).

A fresh cluster is trusting: anyone with admin credentials can do anything, every Pod can reach every other Pod, and a Pod can ask to run as root with full access to its node. This lesson closes those three doors and shows each one blocking something for real.

RBAC

Role-based access control decides what an identity may do to which resources. It's deny by default: nothing is allowed until a binding says so. Three objects:

Read it left to right: who, the link, what, on which resources. A missing verb or resource means no.

Read it left to right: who, the link, what, on which resources. A missing verb or resource means no.
# 08-rbac.yaml
apiVersion: v1
kind: ServiceAccount # an identity for Pods (or for testing, as here)
metadata:
  name: viewer
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role # a set of permissions, in one namespace
metadata:
  name: pod-reader
rules:
  - apiGroups: [""]
    resources: ["pods", "pods/log"]
    verbs: ["get", "list", "watch"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding # who gets the Role
metadata:
  name: viewer-reads-pods
subjects:
  - kind: ServiceAccount
    name: viewer
    namespace: default
roleRef:
  kind: Role
  name: pod-reader
  apiGroup: rbac.authorization.k8s.io

kubectl auth can-i asks the API server what an identity may do, without trying it:

$ kubectl auth can-i list pods --as=system:serviceaccount:default:viewer
yes
$ kubectl auth can-i delete pods --as=system:serviceaccount:default:viewer
no
$ kubectl auth can-i list secrets --as=system:serviceaccount:default:viewer
no
$ kubectl delete pod -l app=shop-web --as=system:serviceaccount:default:viewer
Error from server (Forbidden): pods "shop-web-55d49ccc4b-5xkmp" is forbidden: User "system:serviceaccount:default:viewer" cannot delete resource "pods" in API group "" in the namespace "default"
kubectl auth can-i list pods --as=system:serviceaccount:default:viewer
  • kubectltalk to a Kubernetes cluster
kubectl delete pod -l app=shop-web --as=system:serviceaccount:default:viewer
  • deletedelete an object
  • -lonly objects with this label

The viewer can list Pods, can't delete them, and can't read Secrets, which matters after lesson 6. Role/RoleBinding work in one namespace; ClusterRole/ClusterRoleBinding work cluster-wide. Grant the smallest set of verbs that does the job, and never give Pods cluster-admin.

On EKS, people authenticate with AWS IAM and are mapped to Kubernetes permissions through access entries (the course's Terraform gave the cluster creator admin this way). Pods that need AWS APIs get IAM roles through EKS Pod Identity, as the load balancer controller did in lesson 5. IAM for AWS, RBAC for Kubernetes.

Network policies

By default every Pod accepts connections from anywhere in the cluster. A NetworkPolicy limits that. The common pattern: deny everything, then allow exactly what's needed.

The wall is default-deny-ingress; the gap is allow-frontend-to-web. Everything else times out.

The wall is default-deny-ingress; the gap is allow-frontend-to-web. Everything else times out.
# 08-netpol.yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny-ingress
spec:
  podSelector: {} # every Pod in the namespace
  policyTypes: ["Ingress"] # ...accepts no incoming connections
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-frontend-to-web
spec:
  podSelector:
    matchLabels:
      app: shop-web
  policyTypes: ["Ingress"]
  ingress:
    - from:
        - podSelector:
            matchLabels:
              role: frontend # only Pods with this label
      ports:
        - port: 8080
# before: any Pod can call shop-web
$ kubectl run anon --image=busybox:1.37 --restart=Never --rm -i --quiet -- wget -qO- -T 5 http://shop-web/api
{"version": "v1", "pod": "shop-web-55d49ccc4b-vrdz4", "greeting": "Namaste from a ConfigMap", "uptime_seconds": 308}
$ kubectl apply -f 08-netpol.yaml
networkpolicy.networking.k8s.io/default-deny-ingress created
networkpolicy.networking.k8s.io/allow-frontend-to-web created
# after: a Pod without the role=frontend label
$ kubectl run anon --image=busybox:1.37 --restart=Never --rm -i --quiet -- wget -qO- -T 5 http://shop-web/api
wget: download timed out
pod default/anon terminated (Error)
# after: a Pod labelled role=frontend
$ kubectl run front --image=busybox:1.37 --labels=role=frontend --restart=Never --rm -i --quiet -- wget -qO- -T 5 http://shop-web/api
{"version": "v1", "pod": "shop-web-55d49ccc4b-mp85d", "greeting": "Namaste from a ConfigMap", "uptime_seconds": 346}
kubectl run anon --image=busybox:1.37 --restart=Never --rm -i --quiet -- wget -qO- -T 5 http://shop-web/api
  • kubectltalk to a Kubernetes cluster
  • --image=busybox:1.37container image
kubectl apply -f 08-netpol.yaml
  • applycreate or update from a file
  • -ffrom this file

Blocked traffic times out rather than being refused: the packets are dropped, and a timeout is the signature of a NetworkPolicy. Two practical notes:

  • Policies are only enforced if the network plugin supports them. On EKS the VPC CNI does when enableNetworkPolicy is on (the course cluster set it). Without enforcement, policies are silently ignored.
  • A default-deny also blocks load balancers sending traffic to Pods. Allow them too, or your Ingress breaks; the lab removed the policies afterwards for that reason.

Pod Security admission

A Pod spec can ask for dangerous things: privileged: true gives it almost full control of the node. Pod Security admission, built into Kubernetes, enforces one of three standards per namespace through a label: privileged (anything goes), baseline (blocks the worst) and restricted (hardened).

The label on the namespace picks the level; admission rejects a Pod before it is ever stored or scheduled.

The label on the namespace picks the level; admission rejects a Pod before it is ever stored or scheduled.
$ kubectl create namespace secure
namespace/secure created
$ kubectl label namespace secure pod-security.kubernetes.io/enforce=restricted
namespace/secure labeled
$ kubectl apply -n secure -f 08-privileged.yaml
Error from server (Forbidden): error when creating "08-privileged.yaml": pods "root-shell" is forbidden: violates PodSecurity "restricted:latest": privileged (container "shell" must not set securityContext.privileged=true), ...
$ kubectl apply -n secure -f 08-restricted.yaml
pod/safe-web created
$ kubectl get pods -n secure
NAME       READY   STATUS    RESTARTS   AGE
safe-web   1/1     Running   0          10s
kubectl create namespace secure
  • kubectltalk to a Kubernetes cluster
  • createcreate an object
kubectl apply -n secure -f 08-privileged.yaml
  • applycreate or update from a file
  • -nin this namespace
  • -ffrom this file
kubectl get pods -n secure
  • getlist objects

(The error goes on to list every rule the Pod broke; it's cut after the first.) What made safe-web acceptable:

# 08-restricted.yaml (excerpt)
spec:
  securityContext:
    runAsNonRoot: true
    seccompProfile:
      type: RuntimeDefault
  containers:
    - name: web
      securityContext:
        allowPrivilegeEscalation: false
        capabilities:
          drop: ["ALL"]

shop-web passed because its image already runs as user 10001 (lesson 2). Images that need root fail the restricted standard, a good reason to fix them early. Start new namespaces with enforce=baseline and warn=restricted, then tighten.

⌘
Mini mission

Lock down a namespace in three layers

Create a viewer service account that can only read Pods and prove with kubectl auth can-i that it can't delete them. Apply a default-deny policy plus an allow rule for role=frontend and test with two Pods. Label a namespace restricted and show a privileged Pod being rejected.

Input: 08-rbac.yaml, 08-netpol.yaml, 08-privileged.yaml and 08-restricted.yamlOutput: ~/security.txt
Reveal one safe solution
$ kubectl apply -f 08-rbac.yaml
$ for v in "list pods" "delete pods" "list secrets"; do echo "$v: $(kubectl auth can-i $v --as=system:serviceaccount:default:viewer)"; done > ~/security.txt
$ kubectl apply -f 08-netpol.yaml
$ kubectl run anon --image=busybox:1.37 --restart=Never --rm -i -- wget -qO- -T 5 http://shop-web/api >> ~/security.txt 2>&1
$ kubectl run front --image=busybox:1.37 --labels=role=frontend --restart=Never --rm -i -- wget -qO- -T 5 http://shop-web/api >> ~/security.txt
$ kubectl delete -f 08-netpol.yaml
kubectl apply -f 08-rbac.yaml
  • kubectltalk to a Kubernetes cluster
  • applycreate or update from a file
  • -ffrom this file
for v in "list pods" "delete pods" "list secrets"; do echo "$v: $(kubectl auth can-i $v --as=system:serviceaccount:default:viewer)"; done > ~/security.txt
  • forloop over a list
  • dostart of what the loop runs each time
  • echoprint text
  • doneend of the loop
  • >write output to a file, replacing it
kubectl run anon --image=busybox:1.37 --restart=Never --rm -i -- wget -qO- -T 5 http://shop-web/api >> ~/security.txt 2>&1
  • --image=busybox:1.37container image
  • >>append output to a file
  • 2>&1send errors to the same place as output
kubectl delete -f 08-netpol.yaml
  • deletedelete an object

Expect yes, no, no, a timeout for anon and JSON for front. If anon still gets through on kind, its default CNI doesn't enforce policies: install Calico or Cilium, or use EKS.

Try it yourself

0 of 5 steps done

Run each task in your own account or terminal, then tick it off.

Knowledge check

Quick check

Question 1 of 3

A RoleBinding grants a service account a Role in namespace default. Can it read pods in kube-system?

Go deeper

Official reading for this lesson

  • DocsUsing RBAC authorizationKubernetes ↗
  • DocsNetwork policiesKubernetes ↗
  • DocsPod Security StandardsKubernetes ↗
  • DocsAmazon EKS access entriesAWS Docs ↗
  • DocsNetwork policies with the Amazon VPC CNIAWS Docs ↗

Or get every quiz answer right and it completes itself.

Something unclear, wrong or out of date in this lesson? Tell me, and I'll fix it.

← PreviousResource management: requests, limits, namespaces, quotasNext lesson →Monitoring, logging and troubleshooting