Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 38 ยท Container and Serverless Security

Kubernetes Security Basics

Learn the core Kubernetes security controls: RBAC, pod security settings, network policies, secrets, admission control and API server hardening, with runnable checks.

Kubernetes schedules containers across many machines and exposes a powerful API to manage them. That power is also the risk: whoever controls the API controls every workload, and a single over-privileged pod can become a stepping stone to the whole cluster. Managed services such as EKS, AKS and GKE take over part of the job (the control plane), but the settings of your workloads, your roles and your network rules are still your responsibility under the shared responsibility model.

This lesson walks through the five controls that matter most: authentication and RBAC, pod security settings, network policies, secrets and admission control. The YAML and kubectl commands are read-only examples. The runnable code is a Python stand-in that checks a pod specification the way a policy engine would, with no cluster required.

Only test clusters you own or are authorised to assess. Never probe somebody else's Kubernetes API, even if it appears to be open.

The Kubernetes attack surface

flowchart TD
    U["Users and CI systems"] -->|"authenticate"| API["API server"]
    API --> ADM["Admission controllers"]
    ADM --> ETCD[("etcd: cluster state and secrets")]
    API --> K["kubelet on each node"]
    K --> P1["Pod A"]
    K --> P2["Pod B"]
    P1 -. "pod-to-pod traffic" .-> P2

Four things to protect: the API server, etcd, the nodes (kubelets) and the pod network.

Typical attack paths are: a stolen kubeconfig or service account token, a pod running with too many privileges, a flat network where any pod can talk to any other, secrets readable by too many people and an exposed dashboard or kubelet port.

RBAC: least privilege for the API

Role-based access control (RBAC) decides who may do what to which resources. It has four objects:

  • Role and ClusterRole list permissions (verbs on resources). A Role works in one namespace, a ClusterRole across the cluster.
  • RoleBinding and ClusterRoleBinding attach a role to a user, group or service account.

A least-privilege role that only lets a CI job read pods in the staging namespace looks like this (read-only example):

YAML
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  namespace: staging
  name: pod-reader
rules:
  - apiGroups: [""]
    resources: ["pods", "pods/log"]
    verbs: ["get", "list", "watch"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  namespace: staging
  name: ci-reads-pods
subjects:
  - kind: ServiceAccount
    name: ci-runner
    namespace: staging
roleRef:
  kind: Role
  name: pod-reader
  apiGroup: rbac.authorization.k8s.io

Warning signs in RBAC: wildcards (verbs: ["*"]), binding cluster-admin to a service account, access to secrets or pods/exec for ordinary users, and the permission to create RoleBindings (which lets a user grant themselves more). Every pod gets a service account token by default; set automountServiceAccountToken: false for workloads that never call the API.

Try it: an RBAC permission checker

This stand-in models roles as data and answers "can this subject do this?". It shows how rules combine and why wildcards are dangerous.

Python Simulate RBAC decisions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Kubernetes RBAC is additive and deny-by-default: there are no deny rules, so the only way to remove access is to remove a grant. That is why overly broad roles are hard to fix later.

Pod security settings

A pod's securityContext controls what the container may do on the node. The important settings:

Setting Safe value Why
privileged false A privileged container has almost full access to the host
runAsNonRoot true Blocks root inside the container
allowPrivilegeEscalation false Stops setuid tricks
readOnlyRootFilesystem true Limits what malware can write
capabilities.drop ["ALL"] Remove Linux capabilities, add back only what is needed
hostNetwork, hostPID, hostPath not used Share the node's network, processes or files with the pod
seccompProfile RuntimeDefault Filters dangerous system calls

Kubernetes ships the Pod Security Standards with three levels: privileged, baseline and restricted. The built-in Pod Security Admission controller enforces a level per namespace through a label such as pod-security.kubernetes.io/enforce: restricted.

Try it: a pod spec auditor

Python Check a pod spec against the restricted profile

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Mounting the container runtime socket (/var/run/docker.sock) is among the worst findings, because anything that can talk to the socket can start new privileged containers on the node.

Network policies

By default every pod can reach every other pod. A NetworkPolicy switches a namespace to deny-by-default and then opens only the flows you need. The network plugin (CNI) must support policies; Calico and Cilium do. This read-only example denies all ingress, then allows the web pods to reach the api pods on port 8080:

YAML
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny-ingress
  namespace: shop
spec:
  podSelector: {}
  policyTypes: ["Ingress"]
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: web-to-api
  namespace: shop
spec:
  podSelector:
    matchLabels: { app: api }
  ingress:
    - from:
        - podSelector:
            matchLabels: { app: web }
      ports:
        - port: 8080

Also restrict egress so a compromised pod cannot call out to the internet or to the cloud metadata address. More network-level controls are in network protection.

Secrets, admission and the control plane

  • Secrets are base64-encoded, not encrypted, unless you enable encryption at rest for etcd or use an external secret manager through a CSI driver. Limit who can get them and prefer short-lived credentials. See secrets scanning and management.
  • Admission controllers inspect requests before objects are stored. Policy engines such as OPA Gatekeeper and Kyverno add custom rules, for example "images must come from our registry and be signed". See policy as code.
  • Control plane hardening: keep the API server off the public internet or restrict it by IP, disable anonymous access, enable audit logging, use short-lived credentials from your identity provider and keep Kubernetes upgraded.
  • Nodes: use a minimal container-optimised OS, protect the kubelet API and keep nodes patched.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A role needs to let a CI job read pod logs in one namespace. What is the best fit?

    Least privilege means the narrowest verbs, resources and scope that do the job: one namespace, read-only verbs.
  2. 2. Why is mounting /var/run/docker.sock into a pod dangerous?

    The socket is the container runtime's control channel. Access to it is effectively root on the node.
  3. 3. What does a default-deny NetworkPolicy do?

    A policy with an empty pod selector and no allow rules denies the selected traffic type; further policies then add allowed flows.
  4. 4. Kubernetes Secrets are, by default:

    Base64 is an encoding, not encryption. Protect Secrets with etcd encryption, an external secret manager and narrow RBAC.

Summary

  • Protect the API server, etcd, nodes and the pod network; managed services only take over part of this.
  • Use RBAC with namespaced roles, no wildcards and no casual cluster-admin.
  • Enforce the restricted Pod Security Standard: non-root, no privilege escalation, dropped capabilities, no host mounts.
  • Start networks as deny-by-default and open only needed flows, including egress.
  • Treat Secrets as sensitive data and use admission policies to enforce the rules automatically.

Next: Container Runtime and Registry Security