Learn Kubernetes · 11/14

Security Fundamentals: Locking Down Your Cluster

9 min read

Welcome, Cluster Admiral! 🛳️

Ready to stop treating your Kubernetes cluster like a free-for-all party and start running a tight ship? You're in the right place. This guide will walk you through the fundamentals of Kubernetes security. We'll skip the fluff and focus on the essential tools you'll use daily to lock down your applications.

Let's transform your cluster from a chaotic town square into a secure, well-governed city.


1. Role-Based Access Control (RBAC): Users, Roles, and Bindings 💂‍♀️

The Problem: By default, anyone with access to your cluster can be a superuser, which is as terrifying as it sounds. In a team environment, you need to control who can do what. Developers shouldn't be able to delete production databases, and CI/CD systems shouldn't have free rein over the entire cluster.

The Solution: Role-Based Access Control (RBAC) is Kubernetes' way of managing permissions. It lets you define granular rules about what actions are allowed on which resources. Think of it as a bouncer for your cluster's API.

RBAC is built on three core concepts:

  • Subjects (The "Who"): These are the entities that perform actions. They can be:
    • Users: Human operators.
    • Groups: A collection of users.
    • ServiceAccounts: Non-human accounts used by applications inside your pods.
  • Roles (The "What"): A Role is a set of permissions. It defines which actions (verbs like get, list, create, delete) are allowed on specific resources (like pods, deployments, secrets).
    • A Role is namespaced, meaning it only applies to resources within a single namespace.
    • A ClusterRole is the non-namespaced version, used for cluster-wide resources (like nodes) or for granting permissions across all namespaces.
  • Bindings (The "Link"): A binding connects a subject (who) to a role (what).
    • A RoleBinding grants the permissions of a Role to a subject within a specific namespace.
    • A ClusterRoleBinding grants the permissions of a ClusterRole to a subject across the entire cluster.

🧠 Fun Fact: If you don't apply any RBAC rules, it might seem like everything is wide open. But the moment you apply even one policy to a pod, that pod becomes isolated, and all traffic is denied by default unless you explicitly allow it. It's an all-or-nothing security model!

Hands-On Example: Read-Only Developer Access

Let's give a developer named "jane" read-only access to pods in the default namespace.

Step 1: Define the Role

First, we create a Role that specifies the allowed actions. Save this as pod-reader-role.yaml.

yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  namespace: default
  name: pod-reader
rules:
- apiGroups: [""] # "" indicates the core API group
  resources: ["pods"]
  verbs: ["get", "watch", "list"]
  • rules: This section lists the permissions.
  • apiGroups: The core Kubernetes resources live in the "" group.
  • resources: We're granting access to pods.
  • verbs: We're allowing only read-only actions.

Step 2: Create the RoleBinding

Now, we bind the pod-reader role to our user, "jane". Save this as jane-pod-reader-binding.yaml.

yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: read-pods-jane
  namespace: default
subjects:
- kind: User
  name: jane # The name is case-sensitive
  apiGroup: rbac.authorization.k8s.io
roleRef:
  kind: Role
  name: pod-reader # This must match the name of the Role
  apiGroup: rbac.authorization.k8s.io
  • subjects: This specifies who gets the permissions.
  • roleRef: This points to the Role we created.

Step 3: Apply Them to the Cluster

bash
kubectl apply -f pod-reader-role.yaml
kubectl apply -f jane-pod-reader-binding.yaml

And just like that, Jane can now list and view pods in the default namespace, but she can't create, delete, or modify anything else. You've just implemented the principle of least privilege! 🎉


2. Service Accounts: Giving Identity to Your Pods 🤖

The Problem: Your applications running in pods often need to interact with the Kubernetes API. For example, a monitoring tool might need to list all the pods in a namespace. How can it do this securely without hardcoding credentials into the container image?

The Solution: ServiceAccounts! A ServiceAccount provides an identity for processes that run inside a Pod. They are Kubernetes' way of managing identities for non-human, in-cluster workloads.

Here’s the magic:

  1. When you create a pod, it's automatically assigned a ServiceAccount (the default one in the namespace, if you don't specify another).
  2. Kubernetes automatically creates a short-lived, rotating token for this ServiceAccount.
  3. This token is mounted into the pod's filesystem as a projected volume.
  4. Your application can then use this token to authenticate with the Kubernetes API server.

🧠 Imagination Time: Think of a ServiceAccount as an employee ID card for your application. The application can show this card to the Kubernetes API server to prove its identity. The permissions on that ID card are determined by the Roles and RoleBindings attached to it—a perfect link back to RBAC!

Hands-On Example: A CI/CD Deployer

Let's create a ServiceAccount for a CI/CD pipeline that only has permission to update Deployments in the production namespace.

Step 1: Create the ServiceAccount

Save this as cicd-sa.yaml.

yaml
apiVersion: v1
kind: ServiceAccount
metadata:
  name: cicd-deployer
  namespace: production

Step 2: Create the Role

This role will only allow getting, listing, and patching deployments. Save as deployer-role.yaml.

yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  namespace: production
  name: deployment-patcher
rules:
- apiGroups: ["apps"]
  resources: ["deployments"]
  verbs: ["get", "list", "watch", "patch"]

Step 3: Create the RoleBinding

Now, we bind the deployment-patcher role to our new cicd-deployer service account. Save as deployer-binding.yaml.

yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: cicd-deployer-binding
  namespace: production
subjects:
- kind: ServiceAccount
  name: cicd-deployer
  namespace: production
roleRef:
  kind: Role
  name: deployment-patcher
  apiGroup: rbac.authorization.k8s.io

Step 4: Apply to the Cluster and Use It

bash
# Assuming the 'production' namespace exists
kubectl apply -f cicd-sa.yaml
kubectl apply -f deployer-role.yaml
kubectl apply -f deployer-binding.yaml

Now, in your pod spec for your CI/CD runner, you'd add serviceAccountName: cicd-deployer to assign this identity.


3. Security Contexts: Running Containers as Non-Root Users 🏃‍♂️

The Problem: Many container images are configured to run their main process as the root user (UID 0). If an attacker compromises an application running as root inside a container, they have root privileges within that container. This gives them a powerful launchpad to try to escape the container and attack the host node. This is a huge, unnecessary risk.

The Solution: SecurityContext! A SecurityContext is a set of fields in your pod or container manifest that defines privilege and access control settings. It's your primary tool for hardening the runtime security of your containers.

The most important and frequently used settings are:

  • runAsNonRoot: true: A simple boolean that tells Kubernetes to fail if the container tries to start as the root user. This is your first line of defense.
  • runAsUser: <UID>: Forces the container to run as a specific User ID. A value above 1000 is a good practice.
  • runAsGroup: <GID>: Forces the container to run with a specific Group ID.

You can apply a SecurityContext at the Pod level (applies to all containers in the pod) or at the Container level (overrides the pod-level settings).

🔥 Funny Exaggeration: Running your container as root is like making your new intern the CEO on their first day. They have the keys to everything, and while they probably won't burn the building down, why take the chance?

Hands-On Example: Forcing a Non-Root User

Let's create a pod and force its container to run as user 1001.

Save this as non-root-pod.yaml.

yaml
apiVersion: v1
kind: Pod
metadata:
  name: secure-pod-demo
spec:
  securityContext:
    runAsNonRoot: true
    runAsUser: 1001
    runAsGroup: 3000
    fsGroup: 2000
  containers:
  - name: my-secure-app
    image: busybox:1.28
    command: [ "sh", "-c", "sleep 1h" ]
    securityContext:
      allowPrivilegeEscalation: false
      capabilities:
        drop:
        - "ALL"
  • Pod-Level securityContext:
    • runAsNonRoot: true: The pod will fail to start if the image's default user is root and runAsUser isn't set.
    • runAsUser: 1001: All containers in this pod will run as UID 1001.
    • fsGroup: 2000: This makes any mounted volumes owned by group ID 2000, ensuring the container can write to them if needed.
  • Container-Level securityContext:
    • allowPrivilegeEscalation: false: Prevents a process from gaining more privileges than its parent.
    • capabilities.drop: ["ALL"]: Drops all Linux capabilities, adhering to the principle of least privilege.

Apply it and check the user:

bash
kubectl apply -f non-root-pod.yaml

# Wait for the pod to be running, then check the user ID
kubectl exec -it secure-pod-demo -- id
# Expected output: uid=1001 gid=3000 groups=2000,3000

Success! You've significantly reduced the attack surface of this pod.


4. Network Policies: Restricting Pod-to-Pod Communication (Firewalling) 🔥

The Problem: By default, Kubernetes has a flat network model. This means any pod can communicate with any other pod in the cluster, regardless of namespace. If an attacker compromises your frontend web server pod, they can immediately start scanning your network and attacking your backend services and databases.

The Solution: NetworkPolicy! A NetworkPolicy resource acts like a firewall for your pods. It allows you to define rules that control how groups of pods are allowed to communicate with each other and other network endpoints.

Key concepts:

  • Pod Selector: Policies are applied to pods using labels. The podSelector field chooses which pods the policy applies to.
  • Ingress: These are rules for incoming traffic.
  • Egress: These are rules for outgoing traffic.
  • Default Deny: If any policy selects a pod for a certain traffic type (e.g., ingress), all traffic of that type is denied unless it's explicitly allowed by a rule.

⚠️ Important Prerequisite: NetworkPolicy is implemented by the network plugin (CNI) in your cluster. If your CNI (like Calico, Cilium, or Weave Net) doesn't support it, your policies will be silently ignored.

Hands-On Example: A Classic Three-Tier App

Imagine you have a frontend, a backend, and a database. The rules should be:

  1. Frontend can only talk to the backend.
  2. Backend can talk to the database.
  3. The database cannot talk to anyone (egress) and can only receive traffic from the backend (ingress).

Let's implement the policy for the database pod. Assume it has the label app: database.

Save this as db-network-policy.yaml.

yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: db-allow-backend
  namespace: my-app
spec:
  podSelector:
    matchLabels:
      app: database
  policyTypes:
  - Ingress
  - Egress
  ingress:
  - from:
    - podSelector:
        matchLabels:
          app: backend
    ports:
    - protocol: TCP
      port: 5432
  egress: [] # An empty list means deny all egress traffic
  • podSelector: This policy applies to all pods with the label app: database.
  • policyTypes: We are defining rules for both Ingress and Egress traffic.
  • ingress: Allows incoming traffic only from pods with the label app: backend on TCP port 5432.
  • egress: []: We specify an empty egress rule. Because the pod is now selected by a policy that defines egress rules, the default becomes "deny all." This effectively blocks the database from initiating any outbound connections.

Apply it to your cluster:

bash
kubectl apply -f db-network-policy.yaml

Now, even if your frontend is compromised, it cannot connect directly to the database, providing a crucial layer of network segmentation.


📚 Extra Reading & References

Challenge

Challenge Instructions

You are a security engineer tasked with deploying a new data processing application within a Kubernetes cluster. Your goal is to apply the principle of least privilege by creating a comprehensive set of security configurations using RBAC, Service Accounts, Security Contexts, and Network Policies. All resources must be created in the secure-data namespace.

Your Task:

Create a single YAML file containing five distinct Kubernetes resource manifests, separated by ---, to achieve the following setup:

1. Identity and Permissions (ServiceAccount & RBAC):

  • ServiceAccount: Create a ServiceAccount named data-processor-sa for the application pods.
  • Role: Create a Role named configmap-reader that only grants get and list permissions on configmaps resources.
  • RoleBinding: Create a RoleBinding named bind-configmap-reader to grant the configmap-reader role to the data-processor-sa ServiceAccount.

2. Application Pod Hardening (SecurityContext):

  • Deployment: Create a Deployment named data-processor-deployment. The pod template within this deployment must have the label app: data-processor.
    • Assign the data-processor-sa ServiceAccount to the pods.
    • Define a pod-level securityContext that ensures all containers in the pod run with user ID 3000 and group ID 3000.
    • For the application container (using image processor:latest), define a container-level securityContext that explicitly disables privilege escalation and drops all Linux capabilities.

3. Network Isolation (NetworkPolicy):

  • NetworkPolicy: Create a NetworkPolicy named isolate-database-access.
    • This policy must apply to pods with the label app: database.
    • It must define a single ingress rule: allow traffic only from pods with the label app: data-processor on TCP port 5432.

Expected result

Your submission should be a single, valid YAML string containing five Kubernetes resource manifests, each separated by --- and configured for the secure-data namespace.

The final YAML should define:

  1. A ServiceAccount with metadata.name set to data-processor-sa.
  2. A Role with metadata.name set to configmap-reader, containing a rule that specifies verbs: ["get", "list"] and resources: ["configmaps"].
  3. A RoleBinding with metadata.name set to bind-configmap-reader, linking the data-processor-sa ServiceAccount to the configmap-reader Role.
  4. A Deployment named data-processor-deployment. Its pod template must:
    • Reference the data-processor-sa via spec.template.spec.serviceAccountName.
    • Include a pod-level securityContext with runAsUser: 3000 and runAsGroup: 3000.
    • Include a container-level securityContext with allowPrivilegeEscalation: false and a capabilities block that drops ["ALL"].
  5. A NetworkPolicy named isolate-database-access that:
    • Uses a podSelector to target pods with the label app: database.
    • Defines an ingress rule allowing traffic on port: 5432 from a podSelector that matches the label app: data-processor.
yaml

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.