← [Раздел 07](README.md) · [Главная](../README.md)

# Kubernetes security

## Цель

Освоить базовую **безопасность Kubernetes (K8s)**: RBAC, secrets, pod security, admission control и типичные misconfiguration — без глубокого кластерного администрирования.

## Предварительно

- [container-hardening.md](container-hardening.md).
- K8s objects: Pod, Deployment, Service, Namespace.

## Время

~35 минут чтения + checklist audit namespace

---

## K8s attack surface

| Layer | Examples |
|-------|----------|
| **API server** | Unauthorized API calls |
| **etcd** | Secrets at rest |
| **Kubelet** | Node compromise |
| **Workloads** | Vulnerable app, excessive RBAC |
| **Supply chain** | Malicious images |

Managed K8s (EKS/GKE/AKS): control plane частично на провайдере; **вы** отвечаете за RBAC workloads, networking, images.

## RBAC in Kubernetes

**Role** / **ClusterRole** — permissions on resources.

**RoleBinding** — who gets role in namespace.

| Anti-pattern | Fix |
|--------------|-----|
| `cluster-admin` for devs | Namespace-scoped roles |
| Default SA with automount token | Disable if unused |
| Shared `deploy` SA all apps | One SA per app + IAM map |

### Principle

```
Subject (User/SA) → RoleBinding → Role → verbs on resources
```

Example intent: CI SA can `deploy` in `staging`; read-only in `prod` via separate pipeline.

## Service accounts

| Field | Security |
|-------|----------|
| `automountServiceAccountToken: false` | No default API access |
| Dedicated SA per Deployment | Blast radius |
| Cloud IAM binding (IRSA) | No static cloud keys |

## Secrets management

K8s **Secret** — base64 encoded, **not encrypted** by default in etcd unless encryption at rest enabled.

| Level | Approach |
|-------|----------|
| Basic | Enable etcd encryption, RBAC on secrets |
| Better | External Secrets Operator → Vault/AWS SM |
| Best | Short-lived dynamic creds |

Never commit manifests with real Secret data — use Sealed Secrets / SOPS.

## Pod Security

Apply [container hardening](container-hardening.md) via:

- **Pod Security Admission** (built-in): enforce `restricted` namespace label
- Legacy: PodSecurityPolicy (deprecated)

```yaml
# Namespace label (concept)
pod-security.kubernetes.io/enforce: restricted
```

## Network policies

Default allow-all pod traffic is common.

**NetworkPolicy** example intent:

- `frontend` → `backend:8080` only
- `backend` → `postgres:5432` only
- deny all else

Test with `kubectl exec` netcat from wrong pod — should fail.

## Admission controllers

Gate objects **before** persist:

| Controller | Function |
|------------|----------|
| **OPA Gatekeeper / Kyverno** | Policy as code (no latest tag, require labels) |
| **Image signature verify** | Cosign policy |
| **Resource limits** | Require CPU/mem limits |

Example policies:

- Reject `:latest` image tag
- Require `runAsNonRoot`
- Block `hostPath` mounts

## API server access

| Practice | Why |
|----------|-----|
| Private endpoint | No public K8s API |
| Authorized IPs / VPN | Reduce scan surface |
| Audit logging | Who applied what ([logs](../08-runtime-monitoring/logging-audit-trail.md)) |

## etcd and backups

Encrypt backups; restrict access; test restore — secrets in backup.

## Multi-tenancy

| Isolation | Mechanism |
|-----------|-----------|
| Soft | Namespace + RBAC + quotas |
| Hard | Separate clusters per env/customer |

Don't rely on namespace alone for strong isolation.

## Tools for assessment

| Tool | Purpose |
|------|---------|
| **kube-bench** | CIS benchmark |
| **kube-hunter** | Penetration probes |
| **kubescape** | NSA/CISA framework |
| **Polaris** | Config validation |

Run read-only in staging first.

## Incident in cluster (sketch)

1. Isolate namespace (NetworkPolicy deny all)
2. Capture logs, exec history, image digest
3. Rotate SA tokens, cloud creds
4. Replace nodes if rootkit suspected

Full runbook — [incident response](../08-runtime-monitoring/incident-response.md).

## K8s security checklist

- [ ] RBAC least privilege, no cluster-admin for apps
- [ ] Pod Security restricted/baseline enforced
- [ ] NetworkPolicy default deny template
- [ ] Secrets externalized or encrypted etcd
- [ ] Admission policies (tags, non-root, resources)
- [ ] Image scan + signed images (maturity)
- [ ] Audit logs to SIEM
- [ ] Separate clusters or strong isolation prod/dev

---

## Самопроверка

1. Чем K8s RBAC отличается от cloud IAM?
2. Почему Secret в YAML в git — плохо даже base64?
3. Что делает Pod Security Admission?
4. Зачем NetworkPolicy если есть cloud firewall?

## Дальше

[Terraform security](terraform-security.md)
