# 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.

Course: [Kubernetes & Helm](https://devops.rajeev.pro/courses/kubernetes), lesson 8. About 35 minutes, intermediate. Source: https://devops.rajeev.pro/courses/kubernetes/08-security

## What you will learn

- Grant a service account read-only access with a Role and RoleBinding, and test it with kubectl auth can-i
- Block all incoming traffic with a default-deny NetworkPolicy, then allow one client
- Enforce the restricted Pod Security standard on a namespace and see a privileged Pod rejected
- Explain how IAM and Kubernetes RBAC meet on EKS

> **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. <br />**Code walkthrough:** EKS access entries (explained; the lab's admin access came from one). <br />**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:

> **Figure.** Inside namespace default, four boxes linked left to right. 1, the subject: ServiceAccount viewer, known to the API server as system:serviceaccount:default:viewer. 2, RoleBinding viewer-reads-pods, which names the subject and points to a Role. 3, Role pod-reader, which lists verbs get, list and watch. 4, the resources pods and pods/log. Below, three kubectl auth can-i answers for the viewer: list pods yes; delete pods no, the API server returns Forbidden; list secrets no, because secrets are not in the Role. A note says Role and RoleBinding work in one namespace, ClusterRole and ClusterRoleBinding cluster-wide.
>
> Read it left to right: who, the link, what, on which resources. A missing verb or resource means no.

```yaml
# 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:

```text
$ 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"
```

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.

> **Figure.** Namespace default with a dashed wall labelled default-deny-ingress in front of the three shop-web Pods (app=shop-web, port 8080). Pod front, labelled role=frontend, passes through a gap in the wall and gets the JSON reply from shop-web. Pod anon, with no label, is stopped at the wall: wget download timed out. On the right, the two policies: default-deny-ingress selects every Pod and allows no ingress; allow-frontend-to-web lets Pods with role=frontend reach app=shop-web on port 8080. A warning: the load balancer is blocked too unless it gets its own allow rule.
>
> The wall is default-deny-ingress; the gap is allow-frontend-to-web. Everything else times out.

```yaml
# 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
```

```text
# 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}
```

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).

> **Figure.** Left: three standards stacked from loosest to strictest. Privileged: anything goes, for system add-ons. Baseline: blocks privileged containers, host network, PID and IPC, hostPath volumes, host ports and extra capabilities. Restricted: baseline plus must run as non-root, drop all capabilities, disallow privilege escalation and use the RuntimeDefault seccomp profile. Right: kubectl apply in namespace secure, labelled enforce=restricted, goes to Pod Security admission in the API server. Pod root-shell with privileged true is rejected: Forbidden, violates PodSecurity restricted:latest. Pod safe-web, non-root with all capabilities dropped, is admitted and runs 1/1.
>
> The label on the namespace picks the level; admission rejects a Pod before it is ever stored or scheduled.

```text
$ 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
```

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

```yaml
# 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.

## 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.

- You need: 08-rbac.yaml, 08-netpol.yaml, 08-privileged.yaml and 08-restricted.yaml
- You'll have: ~/security.txt

```sh
$ 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
```

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

- Apply the viewer RBAC and run `kubectl auth can-i` for list, delete and secrets.
- Try to delete a Pod as the viewer service account and read the error.
- Apply the two NetworkPolicies and call shop-web from a Pod with and without the role=frontend label.
- Label a namespace with the restricted standard and apply the privileged Pod.
- Do the mini mission and keep `~/security.txt`.

## Quiz

1. A RoleBinding grants a service account a Role in namespace default. Can it read pods in kube-system?
   - Yes, roles are global
   - **No; a Role and RoleBinding apply only in their own namespace. Cluster-wide access needs a ClusterRole and ClusterRoleBinding** (answer)
   - Only if it is an admin
   Why: RBAC is deny by default and namespaced unless you use the Cluster* versions.

2. You apply a default-deny ingress NetworkPolicy. What happens to traffic between Pods in that namespace?
   - Nothing changes
   - **All incoming connections to Pods in the namespace are blocked until another policy allows them** (answer)
   - Only traffic from other namespaces is blocked
   Why: An empty podSelector selects every Pod. With policyTypes Ingress and no rules, nothing may connect in. The lab's anon Pod timed out.

3. What does the restricted Pod Security standard block?
   - All Pods
   - **Pods that run privileged, as root, with extra capabilities or without a seccomp profile, among others** (answer)
   - Pods without labels
   Why: Restricted is the hardened profile. The lab's privileged Pod was refused at admission; safe-web, non-root with all capabilities dropped, ran.

## Resources

- [Using RBAC authorization](https://kubernetes.io/docs/reference/access-authn-authz/rbac/) (Kubernetes)
- [Network policies](https://kubernetes.io/docs/concepts/services-networking/network-policies/) (Kubernetes)
- [Pod Security Standards](https://kubernetes.io/docs/concepts/security/pod-security-standards/) (Kubernetes)
- [Amazon EKS access entries](https://docs.aws.amazon.com/eks/latest/userguide/access-entries.html) (AWS Docs)
- [Network policies with the Amazon VPC CNI](https://docs.aws.amazon.com/eks/latest/userguide/cni-network-policy.html) (AWS Docs)
