Kubernetes Hardening L4b: Pod and Workload Identity on Cloud vs Bare Metal with SPIFFE/SPIRE
TL;DR
Static AWS access keys, GCP service account JSON files, and long-lived database passwords stored in Kubernetes Secrets are waiting to be exfiltrated. Every modern workload should authenticate using short-lived, audience-bound cryptographic identities.
Start by setting automountServiceAccountToken: false by default and mounting bound projected ServiceAccount tokens only where needed.
On managed clouds, use EKS Pod Identity (with ABAC session tags, cluster-scoped trust conditions, and IMDS blocked), GKE Workload Identity Federation (with direct IAM principal bindings), or AKS Microsoft Entra Workload ID.
On bare metal, either publish your kube-apiserver OIDC discovery endpoints for external federation or deploy SPIFFE/SPIRE (CNCF Graduated) with TPM 2.0 node attestation (tpm_devid), the csi.spiffe.io CSI driver, and OpenBao (OpenSSF Sandbox) to mint dynamic database and object-storage leases on demand.
The Baseline: Bound Projected ServiceAccount Tokens
Prior to Kubernetes 1.21, every ServiceAccount automatically generated a Secret containing a JWT signed by the cluster's service account key with no expiration date, no audience restriction, and no binding to a specific pod.
Worse, Kubernetes mounted that immortal token at /var/run/secrets/kubernetes.io/serviceaccount/token inside every single pod by default. If an attacker exploited a Server-Side Request Forgery (SSRF) or local file inclusion bug in a frontend pod, they walked away with a permanent bearer token for kube-apiserver.
Modern Kubernetes replaces those legacy tokens with Bound ServiceAccount Tokens issued via the TokenRequest API and mounted as projected volumes (while the LegacyServiceAccountTokenCleanUp controller automatically purges unused legacy Secret tokens).
Bound tokens enforce three cryptographic properties:
- Time-bound: Tokens default to a 1-hour lifetime (
expirationSeconds: 3600), and the Kubelet automatically rotates the file on disk when it reaches 80% of its TTL. - Audience-bound (
aud): You mint a token specifically for its target consumer (for example,pods.eks.amazonaws.comorhttps://openbao.bard.sh). If an attacker steals a token minted forhttps://openbao.bard.shand replays it against kube-apiserver, the API server rejects it immediately because theaudclaim does not match the API server's audience. - Pod-bound: The JWT payload embeds a private
kubernetes.ioclaim recording the exactpod.name,pod.uid, andnode.name.
Turn Off automountServiceAccountToken by Default
Most application pods never talk to kube-apiserver. Mounting a token with the default API server audience in those pods hands attackers free cluster reconnaissance (kubectl auth can-i --list) after a container compromise.
Enforce three baseline rules across every namespace:
- Patch the default ServiceAccount in every namespace with
automountServiceAccountToken: false, and never run workloads underdefault. - Create one dedicated ServiceAccount per microservice (
checkout-api,ledger-worker) withautomountServiceAccountToken: false. - When a workload needs to authenticate to a cloud provider or secrets broker, mount an explicit
serviceAccountTokenprojected volume scoped to the target audience and a short expiration (15 to 30 minutes):
apiVersion: v1
kind: ServiceAccount
metadata:
name: checkout-api
namespace: payments
automountServiceAccountToken: false
---
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: checkout-api-pdb
namespace: payments
spec:
minAvailable: 2
selector:
matchLabels:
app.kubernetes.io/name: checkout-api
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: checkout-api
namespace: payments
spec:
replicas: 3
revisionHistoryLimit: 5
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: 1
maxUnavailable: 0
selector:
matchLabels:
app.kubernetes.io/name: checkout-api
template:
metadata:
labels:
app.kubernetes.io/name: checkout-api
spec:
serviceAccountName: checkout-api
automountServiceAccountToken: false
hostUsers: false
terminationGracePeriodSeconds: 30
topologySpreadConstraints:
- maxSkew: 1
topologyKey: topology.kubernetes.io/zone
whenUnsatisfiable: DoNotSchedule
labelSelector:
matchLabels:
app.kubernetes.io/name: checkout-api
securityContext:
runAsNonRoot: true
runAsUser: 65532
runAsGroup: 65532
fsGroup: 65532
seccompProfile:
type: RuntimeDefault
containers:
- name: app
image: ghcr.io/bard-sh/checkout-api@sha256:9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop: ["ALL"]
resources:
requests:
cpu: 250m
memory: 256Mi
limits:
cpu: "1"
memory: 256Mi
readinessProbe:
httpGet:
path: /readyz
port: 8080
initialDelaySeconds: 3
periodSeconds: 5
volumeMounts:
- name: vault-bound-token
mountPath: /var/run/secrets/tokens
readOnly: true
volumes:
- name: vault-bound-token
projected:
sources:
- serviceAccountToken:
path: openbao-token
expirationSeconds: 1800
audience: https://openbao.bard.sh
Managed Cloud Workload Identity: EKS, GKE, and AKS
Every major cloud provider now natively exchanges Kubernetes bound projected tokens for short-lived cloud IAM credentials. However, the architecture and operational trade-offs differ significantly across AWS, GCP, and Azure.
AWS EKS: Why EKS Pod Identity Replaces IRSA
AWS introduced IAM Roles for Service Accounts (IRSA) in 2019 by wiring the cluster's public OIDC discovery endpoint into IAM. While IRSA worked, it suffered from painful scaling bottlenecks at multi-cluster scale:
- Trust policy coupling: Every IAM role had to hardcode the exact OIDC provider ARN (
oidc.eks.eu-central-1.amazonaws.com/id/EXAMPLED539D4633E53DE1B716D3041E) in its AssumeRoleWithWebIdentity condition. Sharing a role across dozens of ephemeral clusters hit IAM's maximum trust policy character limit and pushed large fleets toward AWS IAM's default quota of 100 OIDC providers per account (adjustable up to 700). - Role sprawl: Because IRSA could not dynamically parameterize IAM policies by namespace or pod name, platform teams had to provision hundreds of nearly identical IAM roles via Terraform whenever a new namespace spun up.
EKS Pod Identity eliminates both problems. Instead of relying on an external OIDC provider per cluster, EKS runs the eks-pod-identity-agent DaemonSet on each node listening on link-local address 169.254.170.23:80.
When an AWS SDK inside a pod requests credentials, it sends its projected token (aud: pods.eks.amazonaws.com) to the local agent, which calls the EKS Auth API (AssumeRoleForPodIdentity).
Crucially, EKS Pod Identity automatically attaches verified IAM session tags (eks-cluster-arn, eks-cluster-name, kubernetes-namespace, kubernetes-service-account, kubernetes-pod-name) to the assumed STS session. You can now write a single Attribute-Based Access Control (ABAC) IAM role that trusts pods.eks.amazonaws.com and dynamically scopes S3 prefixes or DynamoDB partition keys to the pod's namespace.
Always constrain the role's trust policy with aws:SourceAccount and aws:SourceArn (or aws:RequestTag/eks-cluster-arn with a production cluster ARN pattern for multi-cluster fleets). Without a condition block, any non-production EKS cluster in the same AWS account whose administrator creates a Pod Identity association can assume the production role (a classic confused-deputy escalation):
data "aws_caller_identity" "current" { }
data "aws_iam_policy_document" "pod_identity_trust" {
statement {
effect = "Allow"
actions = [ "sts:AssumeRole" , "sts:TagSession" ]
principals {
type = "Service"
identifiers = [ "pods.eks.amazonaws.com" ]
}
# Prevent cross-account and cross-cluster confused-deputy role assumption
condition {
test = "StringEquals"
variable = "aws:SourceAccount"
values = [ data.aws_caller_identity.current.account_id ]
}
condition {
test = "ArnEquals"
variable = "aws:SourceArn"
values = [ aws_eks_cluster.prod.arn ]
}
}
}
resource "aws_iam_role" "tenant_s3_writer" {
name = "eks-tenant-s3-writer"
assume_role_policy = data.aws_iam_policy_document.pod_identity_trust.json
}
# ABAC Policy: Pod can only read/write the S3 prefix matching its exact Kubernetes namespace
resource "aws_iam_role_policy" "tenant_s3_abac" {
name = "namespace-scoped-s3"
role = aws_iam_role.tenant_s3_writer.id
policy = jsonencode ( {
Version = "2012-10-17"
Statement = [ {
Effect = "Allow"
Action = [ "s3:GetObject" , "s3:PutObject" ]
Resource = "arn:aws:s3:::bard-prod-tenant-artifacts/$${aws:PrincipalTag/kubernetes-namespace}/*"
} ]
} )
}
resource "aws_eks_pod_identity_association" "checkout" {
cluster_name = aws_eks_cluster.prod.name
namespace = "payments"
service_account = "checkout-api"
role_arn = aws_iam_role.tenant_s3_writer.arn
}
GCP GKE: Direct Principal Binding Without GSA Sprawl
When Workload Identity Federation for GKE first launched, you had to create a Google Service Account (GSA) in IAM, grant IAM roles to the GSA, grant roles/iam.workloadIdentityUser on the GSA to the Kubernetes ServiceAccount (KSA), and annotate the KSA with iam.gke.io/gcp-service-account. Large organizations quickly hit Google Cloud's per-project GSA quota limits.
Today, GKE supports Direct IAM Principal Binding. You do not need to create a GSA at all. Every GKE cluster automatically registers a project-wide Workload Identity Pool (PROJECT_ID.svc.id.goog), and the node-local gke-metadata-server intercepts requests from pods to 169.254.169.254.
You bind GCP IAM permissions directly to the Kubernetes ServiceAccount principal URI:
resource "google_storage_bucket_iam_member" "checkout_bucket_access" {
bucket = google_storage_bucket.invoices.name
role = "roles/storage.objectUser"
# Direct KSA binding - zero GCP Service Account (GSA) required
member = "principal://iam.googleapis.com/projects/${data.google_project.current.number}/locations/global/workloadIdentityPools/${var.project_id}.svc.id.goog/subject/ns/payments/sa/checkout-api"
}
Azure AKS: Microsoft Entra Workload ID
On AKS, the legacy aad-pod-identity project (which intercepted IMDS traffic using iptables rules and a privileged Node Managed Identity daemon) is deprecated and retired. Its replacement, Microsoft Entra Workload ID, uses standard OIDC federation.
Enable --enable-oidc-issuer and --enable-workload-identity on the AKS cluster, annotate your Kubernetes ServiceAccount with azure.workload.identity/client-id, and label the pod azure.workload.identity/use: "true".
The AKS mutating webhook injects a projected token (aud: api://AzureADTokenExchange), which the Azure Identity SDK exchanges directly against a FederatedIdentityCredential configured on a User-Assigned Managed Identity for subject: system:serviceaccount:payments:checkout-api.
Blocking Cloud IMDS (169.254.169.254): Close the Node Role Escape Hatch
Deploying EKS Pod Identity or AKS Entra Workload ID does not automatically block pods from reaching the EC2 or Azure VM Instance Metadata Service (169.254.169.254 on IPv4 across cloud providers, plus fd00:ec2::254 specifically on AWS EC2 IPv6). If a pod without workload identity sends an HTTP request to http://169.254.169.254/latest/meta-data/iam/security-credentials/, it receives the temporary IAM credentials of the underlying worker node (which typically holds permissions to pull from ECR, attach EBS volumes, or modify ENIs).
Warning: Do not apply a blanket Cilium egressDeny rule for 169.254.169.254/32 on GKE clusters using GKE Workload Identity Federation. On GKE, the node-local gke-metadata-server intercepts pod traffic to 169.254.169.254 in order to serve scoped KSA tokens (and already conceals the underlying Compute Engine node metadata server from workloads).
Apply the Cilium egressDeny policy below on EKS, AKS, and bare-metal clusters, and ensure GKE node pools have Workload Identity Federation enabled (--workload-metadata=GKE_METADATA).
Always enforce a two-layer IMDS block on EKS and AKS worker nodes:
- Enforce IMDSv2 with
http_put_response_hop_limit = 1on EC2 launch templates. IMDSv2 requires a session-oriented PUT request to mint a token, and setting the IP TTL hop limit to 1 causes the Linux kernel to drop the response before it can traverse the veth router hop into a container network namespace (note: pods running withhostNetwork: truebypass this hop check). - Drop
169.254.169.254/32(and AWS EC2'sfd00:ec2::254/128on IPv6-enabled EKS clusters) in your CNI. On Cilium (CNCF Graduated), deploy a cluster-wide egressDeny guardrail that no tenant NetworkPolicy can override (omitfd00:ec2::254/128on AKS or IPv4-only clusters, and verify any infra controllers outsidekube-systemsuch as Karpenter already use Pod Identity before enforcing):
apiVersion: cilium.io/v2
kind: CiliumClusterwideNetworkPolicy
metadata:
name: block-cloud-imds
spec:
endpointSelector:
matchExpressions:
- key: io.kubernetes.pod.namespace
operator: NotIn
values: ["kube-system"]
enableDefaultDeny:
ingress: false
egress: false
egressDeny:
- toCIDR:
- 169.254.169.254/32
# AWS EC2 IPv6 IMDS endpoint (applicable to AWS EKS only)
- fd00:ec2::254/128
Managed vs Self-Hosted Bare Metal Comparison
| Capability | AWS EKS (Pod Identity) | GCP GKE (WIF) | Azure AKS (Entra WI) | Bare Metal: OIDC Federation | Bare Metal: SPIFFE/SPIRE |
|---|---|---|---|---|---|
| Identity Token Format | Projected SA JWT (pods.eks.amazonaws.com) |
GKE Metadata Server token | Projected SA JWT (api://AzureADTokenExchange) |
Projected SA JWT (--service-account-issuer) |
X.509-SVID (mTLS) + JWT-SVID (spiffe://...) |
| Control-Plane Dependency | EKS Auth API + Node DaemonSet (169.254.170.23) |
Node-local gke-metadata-server | AKS OIDC Issuer + Mutating Webhook | Publicly reachable .well-known/openid-configuration + JWKS |
SPIRE Server + SPIRE Agent DaemonSet + csi.spiffe.io |
| Hardware Node Attestation | AWS Nitro hypervisor (implicit) | GCP Shielded VM (implicit) | Azu
Comments
No comments yet. Start the discussion.