Stage 6, Part 1 of 9, RBAC, ServiceAccounts & Security

Text
Part 1: Core Theory

The source doc has no Part 1 heading here; these sections are grouped as Part 1.

 PART 1: CORE THEORY

1. The Kubernetes Security Model

Kubernetes security is built on three pillars that are independent and must all be configured correctly. A failure in any one breaks the whole chain.

The Three Pillars

text
┌─────────────────────────────────────────────────────────────┐
│                    KUBERNETES SECURITY MODEL                │
│                                                             │
│  ┌─────────────────────────────────────────────────────┐   │
│  │  AUTHENTICATION (AuthN)                             │   │
│  │  "Who are you?"                                     │   │
│  │  → Certificates, tokens, OIDC, webhooks             │   │
│  └──────────────────────┬──────────────────────────────┘   │
│                         │                                   │
│                         ▼                                   │
│  ┌─────────────────────────────────────────────────────┐   │
│  │  AUTHORIZATION (AuthZ)                              │   │
│  │  "What can you do?"                                 │   │
│  │  → RBAC, ABAC, Node, Webhook                        │   │
│  └──────────────────────┬──────────────────────────────┘   │
│                         │                                   │
│                         ▼                                   │
│  ┌─────────────────────────────────────────────────────┐   │
│  │  ADMISSION CONTROL                                  │   │
│  │  "Should we allow this?"                            │   │
│  │  → Mutating → Validating webhooks/policies          │   │
│  └─────────────────────────────────────────────────────┘   │
└─────────────────────────────────────────────────────────────┘

Key Principles

PrincipleMeaning
Zero-TrustNo implicit trust; verify everything
Least PrivilegeMinimum permissions necessary
Defense in DepthMultiple independent layers
Separation of DutiesNo single role has all power

2. Authentication

Authentication verifies the identity of the caller. The API server supports several methods.

Authentication Methods

MethodUse Case
X.509 Client CertificatesHuman admins, kubelet
ServiceAccount TokensWorkloads inside the cluster
OIDCEnterprise SSO (Okta, Azure AD, Google)
Webhook Token AuthenticationExternal auth service
Authenticating ProxyHeader-based (for proxies)
Bootstrap TokensNode bootstrap
Static Token FileLegacy (deprecated)

X.509 Client Certificates

The most common method for admins and kubelets. The Common Name (CN) becomes the username; Organization (O) becomes the group.

text
Subject: CN=alice, O=developers, O=engineering
         │         │
         │         └── Groups: [developers, engineering]
         └── Username: alice

The API server verifies the certificate is signed by its CA.

ServiceAccount Tokens

Every Pod can have a ServiceAccount. Kubernetes mints a JWT token for it.

Pre-1.21: Static, never-expiring tokens.
1.21+ (projected tokens): Time-limited, audience-bound, auto-rotated.

yaml
apiVersion: v1
kind: Pod
metadata:
  name: my-pod
spec:
  serviceAccountName: my-sa
  containers:
  - name: app
    image: myapp
    volumeMounts:
    - name: token
      mountPath: /var/run/secrets/kubernetes.io/serviceaccount
      readOnly: true
  volumes:
  - name: token
    projected:
      sources:
      - serviceAccountToken:
          path: token
          expirationSeconds: 3600
          audience: https://kubernetes.default.svc

The token is mounted at /var/run/secrets/kubernetes.io/serviceaccount/token.

Key fact: By default, every Pod gets a ServiceAccount token. This is a security concern for Pods that don't need cluster API access. Disable with automountServiceAccountToken: false.

OIDC (OpenID Connect)

Enterprise SSO integration. The API server validates tokens from an OIDC provider.

yaml
# kube-apiserver flags
--oidc-issuer-url=https://accounts.google.com
--oidc-client-id=kubernetes
--oidc-username-claim=email
--oidc-groups-claim=groups

Anonymous Requests

By default, unauthenticated requests are treated as system:anonymous (group system:unauthenticated). This is normally denied by RBAC, but can be explicitly allowed.

Security tip: Disable anonymous auth unless you have a specific reason:

text
--anonymous-auth=false

Username Conventions

PrefixMeaning
system:Kubernetes internal
system:serviceaccount:<ns>:<name>ServiceAccount
system:node:<name>Kubelet
system:apiserverAPI server
(no prefix)External user

Authentication Best Practices

PracticeWhy
Use OIDC for humansCentralized, auditable
Rotate client certificatesShort-lived, limited blast radius
Disable static tokensDeprecated, hard to rotate
Disable anonymous authPrevent unauthorized access
Use bound ServiceAccount tokensAuto-rotated, audience-scoped
Audit all authenticationDetect anomalies

3. Authorization

Once authenticated, Kubernetes checks if the user is authorized to perform the requested action.

Authorization Modes

ModeDescriptionUse Case
RBACRole-Based Access ControlDefault, recommended
ABACAttribute-Based Access ControlLegacy, file-based
NodeNode authorizerKubelet authorization
WebhookExternal authorizationCustom policies
AlwaysAllowEverything is allowed❌ Never in production
AlwaysDenyEverything is deniedTesting

Multiple Authorization Modes

The API server checks modes in order and uses the first one that makes a decision. If RBAC denies, but Webhook allows, the request is allowed (Webhook is checked last).

Common configuration:

text
--authorization-mode=Node,RBAC

The RBAC Verb Set

VerbAction
getRead one resource
listList resources
watchWatch for changes
createCreate new
updateUpdate existing (full)
patchUpdate (partial)
deleteDelete one
deletecollectionDelete many

The RBAC Resource Set

ResourceExample
podsCore Pod resources
pods/logPod subresource (logs)
pods/execPod subresource (exec)
deploymentsApps group
secretsSensitive
nodesCluster-level
configmapsNon-sensitive config

4. RBAC

RBAC (Role-Based Access Control) is the default and recommended authorization mode in Kubernetes. It grants permissions via Roles and Bindings.

The Four Objects

ObjectScopePurpose
RoleNamespacePermissions within a namespace
ClusterRoleClusterPermissions cluster-wide
RoleBindingNamespaceBind Role or ClusterRole to subjects
ClusterRoleBindingClusterBind ClusterRole to subjects cluster-wide

Role (Namespace-Scoped)

yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  namespace: production
  name: pod-reader
rules:
- apiGroups: [""]
  resources: ["pods"]
  verbs: ["get", "list", "watch"]
- apiGroups: [""]
  resources: ["pods/log"]
  verbs: ["get"]

ClusterRole (Cluster-Scoped)

yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: node-reader
rules:
- apiGroups: [""]
  resources: ["nodes"]
  verbs: ["get", "list", "watch"]

RoleBinding

yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: alice-pod-reader
  namespace: production
subjects:
- kind: User
  name: alice
  apiGroup: rbac.authorization.k8s.io
roleRef:
  kind: Role
  name: pod-reader
  apiGroup: rbac.authorization.k8s.io

ClusterRoleBinding

yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: alice-node-reader
subjects:
- kind: User
  name: alice
  apiGroup: rbac.authorization.k8s.io
roleRef:
  kind: ClusterRole
  name: node-reader
  apiGroup: rbac.authorization.k8s.io

Subjects

KindExample
Useralice, [email protected]
Groupdevelopers, system:masters
ServiceAccountdefault/my-sa (namespace/name)

The Secret to RBAC: Bindings vs Permissions

RoleBindings cannot grant permissions the Role doesn't have. You can bind a ClusterRole to a namespace using a RoleBinding — this grants the ClusterRole's permissions within that namespace only.

Example: Bind cluster-admin ClusterRole to a RoleBinding in namespace production → the user has admin permissions within production only.

Default ClusterRoles

Kubernetes ships with built-in ClusterRoles:

ClusterRolePurpose
cluster-adminFull cluster access
adminNamespace admin (most resources)
editEdit most resources (no RBAC)
viewRead-only (no Secrets)

Default ServiceAccounts

Each namespace has a default ServiceAccount. Pods that don't specify one use it.

Security tip: Don't grant permissions to default; create per-workload ServiceAccounts.

RBAC Decision Logic

When a request comes in:

  1. Gather all Roles/ClusterRoles bound to the user via RoleBindings/ClusterRoleBindings.
  2. Check if any rule allows the request.
  3. If yes → allow. If no → deny.

Key insight: RBAC is additive. There are no deny rules. You can only grant permissions, not remove them.

RBAC Verbs and Resources (Common Combinations)

NeedRole Rule
Read Podsresources: ["pods"], verbs: ["get", "list", "watch"]
Read Pod logsresources: ["pods/log"], verbs: ["get"]
Exec into Podsresources: ["pods/exec"], verbs: ["create"]
Port forwardresources: ["pods/portforward"], verbs: ["create"]
List Secretsresources: ["secrets"], verbs: ["list"]
Deployresources: ["deployments"], verbs: ["create", "update"]
Delete namespaceresources: ["namespaces"], verbs: ["delete"]

RBAC Anti-Patterns

Anti-PatternRisk
cluster-admin for humansFull cluster compromise
Wildcard verbs (*)Unintended permissions
Wildcard resources (*)Unintended scope
Binding cluster-admin via RoleBindingNamespace-wide admin
default ServiceAccount with permissionsEvery Pod gets it
No RBAC auditingDrift, unused perms

RBAC Verification

bash
# Check what you can do
kubectl auth can-i --list

# Check specific permission
kubectl auth can-i create pods
kubectl auth can-i delete deployments -n production

# Check as another user
kubectl auth can-i list secrets --as=system:serviceaccount:default:my-sa
kubectl auth can-i list secrets --as=alice

# Check cluster-wide
kubectl auth can-i list pods --all-namespaces

The kubectl who-can Plugin

bash
# Install krew plugin
kubectl krew install who-can

# Check who can do something
kubectl who-can list secrets
kubectl who-can delete pods -n production

5. ServiceAccounts

A ServiceAccount is an identity for processes running in Pods. It's how Pods authenticate to the Kubernetes API.

Creating a ServiceAccount

yaml
apiVersion: v1
kind: ServiceAccount
metadata:
  name: my-app-sa
  namespace: production
bash
kubectl create serviceaccount my-app-sa -n production

Using a ServiceAccount in a Pod

yaml
apiVersion: v1
kind: Pod
metadata:
  name: my-app
spec:
  serviceAccountName: my-app-sa
  automountServiceAccountToken: false    # Best practice
  containers:
  - name: app
    image: my-app:1.0

The ServiceAccount Token

Pre-1.21 (legacy): Static Secret-backed tokens.
1.21+ (projected): Time-limited, audience-bound tokens.

The token is mounted at:

text
/var/run/secrets/kubernetes.io/serviceaccount/token
/var/run/secrets/kubernetes.io/serviceaccount/ca.crt
/var/run/secrets/kubernetes.io/serviceaccount/namespace

Disabling Auto-Mounting

By default, every Pod gets a ServiceAccount token. If your Pod doesn't need to call the Kubernetes API:

yaml
spec:
  automountServiceAccountToken: false

Or disable at the ServiceAccount level:

yaml
apiVersion: v1
kind: ServiceAccount
metadata:
  name: no-api-sa
automountServiceAccountToken: false

Why this matters: A leaked token allows an attacker to make API calls with the Pod's identity. If the Pod doesn't need the API, don't give it a token.

Binding a ServiceAccount to RBAC

ServiceAccounts can be subjects in RoleBindings:

yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: my-app-pod-reader
  namespace: production
subjects:
- kind: ServiceAccount
  name: my-app-sa
  namespace: production
roleRef:
  kind: Role
  name: pod-reader
  apiGroup: rbac.authorization.k8s.io

Workload Identity (Cloud)

ServiceAccounts are also used for cloud identity:

These allow Pods to assume cloud IAM roles without static credentials.

Best Practices

PracticeWhy
One ServiceAccount per workloadLeast privilege
Disable auto-mount when not neededReduce attack surface
Use projected tokensAuto-rotated
Bind to minimal RBACLeast privilege
Audit ServiceAccount usageDetect anomalies
Never use defaultShared across namespace
Use workload identityNo static cloud credentials

1:1 copy of the class Google Doc, code in code blocks.