# Security Basics — Kubernetes

Source: https://www.skillbyai.com/en/kubernetes/s-security

> RBAC, pod security, network policies, supply chain.

## Layers of defence

**RBAC** grants users and service accounts only the permissions they need (Roles in a namespace, avoid cluster-admin). Pod **securityContext** settings harden containers: `runAsNonRoot`, `readOnlyRootFilesystem`, `allowPrivilegeEscalation: false`, dropping Linux capabilities; Pod Security Admission can enforce the "restricted" profile per namespace. **NetworkPolicies** restrict which pods may talk to which (the default is allow-all; your network plugin must support policies). Scan and sign images, pin them by digest, and keep the cluster and nodes patched.

## A hardened container and a default-deny policy

Not applied to a live cluster in this course; check field names against the API reference for your version.

```yaml
securityContext:
  runAsNonRoot: true
  runAsUser: 10001
  readOnlyRootFilesystem: true
  allowPrivilegeEscalation: false
  capabilities: {drop: ["ALL"]}
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata: {name: default-deny-ingress, namespace: shop-prod}
spec:
  podSelector: {}          # all pods in the namespace
  policyTypes: [Ingress]   # no ingress rules listed = deny all incoming traffic
```

## Start namespaces at default-deny

Add a default-deny NetworkPolicy, then allow only the flows each app needs.

**Quiz:** What is the default network behaviour between pods without NetworkPolicies?

- [ ] Only same-node traffic is allowed
- [ ] All traffic is blocked
- [x] All pods can talk to all pods
- [ ] Only DNS is allowed

*Answer:* All pods can talk to all pods. Policies are needed to restrict traffic.
