Skip to content
Tech Interview Prep
Technical interview guide

Container & Workload Security

Securing what runs inside containers and the runtime environment around them: images, runtime behavior, and isolation.

Minutes to read
4
Practice MCQs
25
Interview Q&A
25
Edition
v5
Editorial status
Reviewed

Scope: Kubernetes v1.37 documentation and NIST SP 800-190 guidance current 2026-08-31.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-2

Harden a typical Kubernetes web application pod.

Answer

What I'd say first (90 seconds)

Assume a first-party image I can rebuild, a CNI that actually enforces NetworkPolicy (Calico, Cilium, Antrea: plain flannel accepts the object and ignores it), and a namespace I can label. I harden in layers, each assuming the previous one held:

  1. Identity. automountServiceAccountToken: false unless the app calls the API server. The mounted token is a bearer credential readable at /var/run/secrets/kubernetes.io/serviceaccount/token by anything that gets code execution in the process.
  2. Image. Pin by digest. web:1.4 is a mutable pointer; the digest is the content.
  3. Process. runAsNonRoot: true with an explicit runAsUser, allowPrivilegeEscalation: false, capabilities.drop: ["ALL"], seccompProfile: RuntimeDefault.
  4. Filesystem. readOnlyRootFilesystem: true plus explicit emptyDir mounts for the paths the app writes.
  5. Blast radius. Default-deny NetworkPolicy, then allow DNS and named backends.
  6. Detection. Audit logs, runtime alerts, and the exit codes below.
YAML
spec:
  automountServiceAccountToken: false
  securityContext:
    runAsNonRoot: true
    runAsUser: 10001
    runAsGroup: 10001
    fsGroup: 10001
    seccompProfile: {type: RuntimeDefault}
  containers:
    - name: web
      image: registry.example.com/web@sha256:<digest>
      ports: [{containerPort: 8080}]
      securityContext:
        allowPrivilegeEscalation: false
        readOnlyRootFilesystem: true
        capabilities: {drop: ["ALL"]}
      resources:
        requests: {cpu: 100m, memory: 128Mi}
        limits:   {memory: 256Mi}          # no CPU limit
      volumeMounts:
        - {name: tmp,   mountPath: /tmp}
        - {name: cache, mountPath: /var/cache/nginx}
      readinessProbe: {httpGet: {path: /healthz, port: 8080}, periodSeconds: 5}
      livenessProbe:  {httpGet: {path: /livez,  port: 8080}, periodSeconds: 10, failureThreshold: 3}
  volumes:
    - {name: tmp,   emptyDir: {sizeLimit: 64Mi}}
    - {name: cache, emptyDir: {sizeLimit: 256Mi}}

runAsUser is explicit because runAsNonRoot alone makes the kubelet inspect the image's USER; if the image has none, the pod fails with CreateContainerConfigError before it ever starts. Kubernetes sets net.ipv4.ip_unprivileged_port_start=0 in containers by default (since 1.22), so a non-root process can bind :80 without NET_BIND_SERVICE. Pod Security Admission's restricted profile enforces most of the above at the namespace level: run warn and audit first, then enforce.

What each control actually buys, and what it costs

controlblocksfirst thing that breaks
runAsNonRoot + runAsUseruid 0 in the containerimage with USER root → CreateContainerConfigError
allowPrivilegeEscalation: falsesetuid binaries, file capabilitiesentrypoints that sudo or exec a setuid helper
drop: ["ALL"]CAP_NET_RAW, CAP_CHOWN, CAP_SYS_ADMINimages that chown their data dir at startup
readOnlyRootFilesystemwrites to image layersanything writing /tmp, /var/run, a pid file → EROFS
seccompProfile: RuntimeDefault~44 syscalls incl. ptrace, bpf, mount, kexec_loaddebuggers and some JITs → EPERM
automountServiceAccountToken: falseAPI credential in the podin-cluster API calls → 401
default-deny NetworkPolicylateral movement, metadata serviceDNS resolution, if egress to kube-dns isn't allowed

Failure modes and how I spot them

  • readOnlyRootFilesystem too tight. CrashLoopBackOff, EROFS in kubectl logs --previous. Fix by adding the emptyDir, not by turning the flag off.
  • Memory limit too low. Exit code 137, kubectl describe pod shows Last State: Terminated, Reason: OOMKilled. Watch container_memory_working_set_bytes against the limit.
  • CPU limit too low. No crash: p99 latency climbs and container_cpu_cfs_throttled_seconds_total rises. This is why I set a memory limit and leave CPU unlimited.
  • Liveness probe that checks a dependency. One slow backend restarts every replica at once and takes the service down. Readiness should check dependencies; liveness should check only the process.
  • NetworkPolicy that isn't enforced. The object exists, kubectl get netpol looks right, and a test pod still reaches the backend: the CNI doesn't implement it. Verify with an actual connection attempt, not with kubectl get.

When I'd relax it

If the image is third-party and I can't rebuild it, readOnlyRootFilesystem and drop: ["ALL"] will break it. Then I isolate it in its own namespace with a permissive Pod Security label, keep the network policy and runtime detection, and treat the missing controls as accepted risk rather than pretending they're on. seccompProfile: Localhost is stricter than RuntimeDefault but you own the syscall list per kernel version: worth it only for a workload you can test against every node image you run.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-3

Roll out the Restricted Pod Security Standard to existing namespaces.

Answer

Core answer (first 90 seconds)

Assume Kubernetes 1.25+, where Pod Security Admission is GA, and cluster-admin access. I would not flip enforce on day one. The rollout is: audit and warn first, fix workloads at their source, then enforce namespace by namespace, with exceptions handled by the API server's exemption mechanism rather than by weakening the policy.

Step 1: audit and warn, pinned. Label the pilot namespace with audit and warn only, and pin the version to the cluster minor so a control-plane upgrade doesn't silently tighten the policy:

Shell
kubectl label ns payments \
  pod-security.kubernetes.io/audit=restricted \
  pod-security.kubernetes.io/warn=restricted \
  pod-security.kubernetes.io/audit-version=v1.29 \
  pod-security.kubernetes.io/warn-version=v1.29

warn prints a Warning: to whoever creates the pod; audit records the violation in the audit log under the annotation pod-security.kubernetes.io/audit-violations. That log is the inventory: no guessing which workloads break.

Step 2: fix at the source. Restricted requires, per container: runAsNonRoot: true, allowPrivilegeEscalation: false, capabilities.drop: ["ALL"], and seccompProfile.type: RuntimeDefault (or Localhost); it forbids privileged, hostPath, hostNetwork, hostPort, hostPID, hostIPC.

Restricted requiresCommon breakageFix
runAsNonRoot: trueimage runs as UID 0set runAsUser non-zero, or rebuild with USER
allowPrivilegeEscalation: falseunset by defaultset it explicitly
capabilities.drop: [ALL]NET_BIND_SERVICE addeddrop ALL, add back only what baseline permits
seccompProfile.typeunsetset RuntimeDefault at pod or container level
no hostPath/hostNetworkCNI, monitoring agentsdedicated namespace or RuntimeClass exemption

Step 3: enforce. Once the audit log is quiet for a namespace, flip it:

Shell
kubectl label ns payments \
  pod-security.kubernetes.io/enforce=restricted \
  pod-security.kubernetes.io/enforce-version=v1.29

Step 4: exceptions. The API server's --admission-control-config-file supports exemptions by namespaces, runtimeClasses and usernames. Use a runtimeClasses entry (e.g. a gvisor class) or a dedicated namespace for the agents that genuinely need host access. That is one reviewable file, cluster-wide; per-user exemptions are not.

Failure modes and how I detect them

  1. Controller recreates the pod. Editing a running pod to add a securityContext is futile: the ReplicaSet/DaemonSet/StatefulSet controller replaces it from the template. Detect with kubectl get events -A --field-selector reason=FailedCreate, which shows Error creating: pods "web-7d9..." is forbidden: violates PodSecurity "restricted:v1.29": allowPrivilegeEscalation != false. Fix the template, not the pod.

  2. Mutating webhook injects a non-compliant container. Mutating admission webhooks run before PSA validation, so a sidecar injector (Istio, Linkerd, a Vault agent) that adds a container without seccompProfile rejects every pod in the namespace. The violation names the injected container: containers "istio-proxy" must set securityContext.seccompProfile.type to "RuntimeDefault" or "Localhost". Upgrade the injector or set its container securityContext.

  3. Version drift. enforce-version defaults to latest, which tracks the cluster minor. After a control-plane upgrade the policy can tighten and pods that passed yesterday are rejected on their next restart. Detect a spike in FailedCreate events right after an upgrade; pin the version and advance it deliberately.

I would move low-risk namespaces first, watch the rejection rate per namespace, and only then widen.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-1

Design a secure container image build and release pipeline.

Answer

Assumptions I'd state first: Kubernetes runtime, an OCI registry that supports tag immutability (ECR, Artifact Registry, GHCR), CI runners you can make ephemeral, and admission control you own (Kyverno or Sigstore policy-controller). If any of those is false, the design changes: say which one and I'll adapt.

The answer: four gates, each binding the next to a digest, not a tag.

1. Build on an ephemeral runner. BuildKit (the default builder since Docker Engine 23.0) with --secret mounts so credentials never land in a layer, and multi-stage so build tooling never reaches the runtime image. Ephemeral matters because a persistent builder caches layers: a compromised build writes a layer that a later build silently reuses. A fresh runner starts from a known state.

Dockerfile
# syntax=docker/dockerfile:1.7
FROM node:20.11-bookworm-slim AS build
WORKDIR /app
COPY package.json package-lock.json ./
RUN --mount=type=secret,id=npmrc,target=/root/.npmrc \
    --mount=type=cache,target=/root/.npm \
    npm ci --omit=dev

FROM gcr.io/distroless/nodejs20-debian12:nonroot
COPY --from=build /app /app
CMD ["/app/server.js"]   # distroless nodejs already sets node as ENTRYPOINT

The secret is mounted into the RUN only; it is not in any layer, so docker history cannot recover it.

2. Produce evidence. docker buildx build --provenance=true --sbom=true emits SLSA provenance and an SBOM as OCI attestations next to the image. Scan the final image (Trivy or Grype), not just the source tree: the base image is where most CVEs live.

3. Sign the digest. cosign sign keyless via Fulcio/Rekor, or with a KMS key. Sign repo@sha256:..., never the tag.

4. Admit on the digest. Policy verifies signature, builder identity, and that the deployed reference is a digest.

Why digest-binding works: a trace. CI pushes registry/app:1.4.2, which resolves to sha256:9f2c…. The manifest references the tag. An attacker with a leaked push token pushes a different image to the same tag; it now resolves to sha256:4b81…. Admission that checks the tag string passes both. Admission that checks registry/app@sha256:9f2c… rejects the second, because a digest is the hash of the manifest content: you cannot change the image without changing the digest. Detection: alert when the resolved digest for an unchanged tag changes between deploys.

Failure modes and what they cost.

  • Compromised signing identity. Detection: cosign verify fails, or a signature appears from an unexpected OIDC issuer/builder identity. Response: revoke the identity, rebuild from source, re-sign, redeploy. Minutes to hours. Rebuild alone is not enough; the bad signature must be revoked too.
  • Base-image CVE disclosed after deploy. Detection: scheduled rescan of deployed digests (daily), alert on new HIGH/CRITICAL. Cost: rebuild + re-sign + redeploy, roughly 10–30 minutes if the pipeline is fast.

Trade-offs. Keyless signing needs network access to Fulcio/Rekor; air-gapped builds need a private trust root (self-hosted Sigstore or a KMS key). Digest-only admission breaks kubectl set image workflows and forces a promotion step, so teams often allow tags in dev namespaces and digests in prod. Rebuild-vs-revoke is a real fork: a dependency CVE is fixed by rebuild; a compromised identity requires revocation and re-signing everything it touched.

When not to: a single-team internal tool with no external consumers gets most of the value from a signed digest plus a scan. Full SLSA L3 provenance and admission policy is friction without a threat model to justify it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

Design container registry security and operations.

Answer

Assumptions I'd state up front: one primary registry (ECR, Harbor, or Artifact Registry), CI with OIDC federation, multi-region prod, and clusters that pull through an admission controller. If any of those is false the design shifts, so I'd confirm them first.

I split the problem in two: who can write to the registry, and what the cluster will accept. Everything else follows from those.

Write side. No long-lived robot credentials. CI exchanges its OIDC token for a registry token scoped to a single repository with a short TTL: ECR's GetAuthorizationToken caps at 12 hours, so I'd mint per-push tokens rather than reuse one. Four roles, each repository-scoped: read (pull-only, bound to prod node identity), build-push (CI, push to one repo, no delete), promotion (copies a digest between repos, never rebuilds), admin (policy and deletion, MFA, break-glass, every action audited).

Read side: the part that actually enforces trust. A tag is a mutable pointer; a digest is the content address of the manifest. Signing binds a signature to the digest, so an admission controller running cosign verify rejects a re-pushed tag whose content changed. Immutable-tag rules (ECR tag immutability, Harbor immutable tag rules) stop the overwrite at the registry, but admission is the real gate: the registry can't see your cluster's policy.

Quarantine as a gate, not a flag. Scan-on-push writes into quarantine/<repo>. A promotion job copies the digest into release/<repo> only when the scan and signature policy pass. Prod RBAC grants pull on release/ only, so a failing image is unreachable rather than merely labelled. That's the difference between a dashboard and a control.

DecisionOption AOption BDeciding criterion
SigningKeyless (Fulcio/Rekor)Long-lived KMS keyKeyless if you need transparency-log detection; KMS if air-gapped
PinningDigest in manifestsImmutable tagsDigest if admission verifies signatures; tags only for human ergonomics
ReplicationRegistry-native, whole repoManifest-only copyWhole repo: signatures are separate OCI artifacts

Failure modes and how I'd detect them.

  • Tag mutation: admission denies the pull; cosign verify fails with a digest mismatch. Alert on the denial, not the push.
  • GC deletes an in-use blob: registry GC removes blobs with no referencing manifest. Delete a manifest a running node still needs and you get ImagePullBackOff with manifest unknown. Mitigation: retention keeps tagged manifests, GC only touches untagged manifests older than 14 days.
  • Signing-key compromise: keyless signing writes every signature to Rekor, so an entry from an unexpected identity is the detection signal. With a KMS key you have no such log: you rotate and re-sign.
  • Replication gap: digests survive replication because they're content-addressed, but a cosign signature lives as a separate OCI artifact tagged sha256-<digest>.sig in the same repository. Replicate manifests only and the DR region pulls fine but fails verification.

Sizing the retention policy. At 500 pushes/day and 90-day retention, that's 45,000 manifests; at ~200 MB compressed per image, roughly 9 TB before dedup. Untagged layers are the bulk of waste, so GC untagged-after-14-days is where the space comes back.

Decommissioning: legal hold beats retention policy, so a hold tag must be excluded from GC; and before deleting a repository, confirm no admission policy or running deployment still references its digests.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

Handle a critical vulnerability in a widely deployed base image.

Answer

What I'd say in the first two minutes

Three questions before any action: which base image digest is actually running, is the vulnerable code path reachable from untrusted input, and is there a public exploit? Assume a distro base (debian:12-slim, ubuntu:22.04) pinned by digest in the manifests, built in CI, deployed on Kubernetes.

The core answer: you do not patch running containers. You build a new image from a fixed base, push it, redeploy, and block the old digest at admission. Priority is reachability × privilege, not CVSS alone.

Why digests are the unit of work. A tag is mutable; the digest is what the kubelet actually pulled. debian:12-slim today and next week are different digests. If you rebuild and the digest is unchanged, the node's image cache serves the old layers and your "redeploy" changed nothing. So the first command enumerates what is running:

Shell
kubectl get pods -A -o jsonpath='{range .items[*]}{.spec.nodeName}{"\t"}{.status.containerStatuses[*].imageID}{"\n"}{end}' | sort -u

That maps node → imageID and shows which nodes hold the vulnerable digest.

Prioritization. For distro CVEs the fix is usually a patch-revision bump, not an upstream version change: glibc 2.35-0ubuntu3.3 → 2.35-0ubuntu3.4. The upstream version string is identical, so version-based allowlists and naive scanners miss it; you have to compare the full package revision.

ReachabilityPrivilegeExploitAction
Untrusted input reaches the pathprivileged / hostPIDpublic PoChours
Local-only (needs existing code exec)unprivilegednonedays
Not reachableanynonescheduled, with a deadline

A local privilege-escalation CVE like glibc's GLIBC_TUNABLES bug (CVE-2023-4911, CVSS 7.8) only matters if an attacker can already run code in the container, so a privileged: true pod with an exposed app is a different priority from a batch job with no ingress.

Patch vs replace. Patch when the distro has backported the fix and your Dockerfile is thin: bump the base tag, rebuild, done. Replace when the base is EOL, the fix needs a major version, or you are carrying a fat base you do not need: moving to distroless or a newer distro removes the package entirely. Rebuilding every downstream image is the wrong call when the vulnerable package is not in the final layer (a multi-stage build drops it) or the workload is genuinely unreachable and a compensating control exists, but that still gets a deadline, not an exception that lives forever.

Failure modes and how to detect them.

  1. Stale node cache. imagePullPolicy: IfNotPresent plus an unchanged digest means the old image runs. Detect by diffing status.containerStatuses[].imageID against the new digest per node.
  2. Jobs and CronJobs pinned by tag. They keep spawning old pods after your Deployment rollout:
Shell
kubectl get cronjobs -A -o jsonpath='{range .items[*]}{.metadata.namespace}{"/"}{.metadata.name}{"\t"}{.spec.jobTemplate.spec.template.spec.containers[*].image}{"\n"}{end}'
  1. Build cache serving stale base layers. docker build reuses the cached base layer; use --pull (or --no-cache for the base stage) or the new image is byte-identical to the old.
  2. Admission control only blocks new pods. Running pods keep running; you need a rollout, not just a policy.
  3. Scanner DB lag. Trivy/Grype may not carry the fixed revision yet, so a clean scan is not proof.

Rollout. Progressive: 1% → 10% → 50% → 100%, with rollback on error-rate or latency regression. Verify old digests are gone before declaring done. Illustrative arithmetic: 400 services × 6 min rebuild = 40 CI-hours; across 20 parallel runners that is ~2 hours wall-clock, which is why the rebuild fan-out, not the patch, is the bottleneck.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Handle an image-signing key or builder identity compromise.

Answer

Assumptions: Kubernetes admission enforces signatures (Kyverno verifyImages or Sigstore Policy Controller ClusterImagePolicy); images are signed keyless via Sigstore (Fulcio + Rekor) using a CI OIDC identity; registry stores immutable digests. If you use a long-lived cosign key, the same steps apply but revocation is manual.

First 60-120 seconds: I would freeze promotion, revoke the builder identity at the IdP (OIDC trust policy, SPIFFE registration, or cloud IAM role), and preserve Rekor, registry, and audit logs. Then scope the window: query Rekor for entries from that identity, list digests signed, and inventory running pods by digest. Contain by blocking those digests at admission, not by deleting registry images. Rebuild from verified source with a new identity, re-sign, and update admission trust roots.

Why admission-time digest blocking beats registry deletion: registry deletion is destructive, breaks running pods on restart, and does not stop already-pulled images. Admission blocks new pods and can alert on existing ones. Example Kyverno policy: verifyImages with attestors and imageReferences by digest. Or Sigstore Policy Controller ClusterImagePolicy matching glob: "*" and identities with subject and issuer.

Trade-offs: keyless vs long-lived key. Fulcio issues short-lived certs (10 minutes in the public good instance). Revoking the OIDC identity stops new certs; existing certs expire in 10 minutes. Long-lived keys require CRL/rotation and have longer exposure. Quarantining all images from the builder stops deployment and may cause outage; trusting unchanged digests risks running a compromised image. Use digest inventory to prioritize: if 3 images in the last 24h, quarantine all; if 300, risk-based.

Failure modes: revocation propagates slowly. If the admission webhook caches successful verifications for 5 minutes and the registry CDN caches manifests for 10 minutes, a compromised image can still be pulled and admitted for up to 15 minutes after revocation. Detection: alert on cosign verify success with a revoked identity, or admission webhook logs showing successful verification after revocation. Operational cost: blocking by digest may block legitimate rebuilds; allowlist new digests. Another failure: rotating the builder identity but not updating the admission policy trust root, so new images are rejected. Detection: admission webhook logs show no matching trust root.

Artefact: trace of cosign verify. cosign verify --certificate-identity=ci@example.com --certificate-oidc-issuer=https://token.actions.githubusercontent.com $IMAGE checks signature, cert identity, issuer, and Rekor inclusion. cosign verify-attestation --type slsaprovenance --certificate-identity=ci@example.com --certificate-oidc-issuer=https://token.actions.githubusercontent.com $IMAGE checks provenance. cosign tree $IMAGE lists signatures and attestations. If the identity is revoked, these fail once the cert expires or the admission policy rejects.

Table: revocation options.

OptionLatencyCostWhen
Revoke OIDC identityUp to 10 min cert TTL + 5 min admission cacheNo key rotation; existing certs expireKeyless Sigstore with short-lived Fulcio certs
Rotate long-lived cosign keyManual CRL/trust-root update; hours to daysRe-sign or rebuild all imagesShared key, offline signing, no OIDC
Quarantine all builder imagesImmediate blockMay stop all deploysSmall blast radius, few digests
Trust unchanged digestsNoneRisk running compromised imageOnly if digest inventory proves no compromise

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

Secure Secrets consumed by Kubernetes workloads.

Answer

Clarify first. Is this a credential that has to be a string, or can the workload assume an identity? On EKS, GKE or AKS the answer is usually identity: IRSA, Workload Identity Federation, or Azure Workload Identity give the pod a short-lived, audience-scoped token that the cloud STS exchanges for credentials. No static secret exists, so there is nothing to rotate. Everything below is for the residue (a third-party API key, a database password) that genuinely has to be stored.

Core answer. A Kubernetes Secret is base64-encoded, not encrypted. By default it lands in etcd in plaintext and is readable by anyone holding get on secrets in that namespace. So the work is three things: keep plaintext out of etcd and off the node where you can, make the credential short-lived so rotation stops being a project, and shrink the blast radius when one leaks.

Why the consumption path matters. An env var is the worst option. It is copied into the process environment, inherited by every child process, visible in /proc/<pid>/environ to same-UID processes, and captured verbatim in core dumps and crash handlers. It also never updates: changing the Secret requires a pod restart. A volume mount is better: it is a tmpfs, so it never touches disk, and kubelet re-syncs it (default sync period 1 minute, plus the config-map/secret cache TTL), though the app must re-read the file. defaultMode defaults to 0644; set 0400, or 0440 with fsGroup if the container is non-root, because the files are root-owned otherwise.

YAML
volumes:
- name: db
  secret:
    secretName: db-creds
    defaultMode: 0400
containers:
- name: app
  volumeMounts:
  - { name: db, mountPath: /etc/db, readOnly: true }

Where the plaintext actually lives.

PathPlaintext at restRotationLeak surface
env varprocess environ, child procs, dumpspod restart/proc, logs, core dumps
secret volumetmpfs on the nodekubelet sync ~1 min, app re-readsnode root, privileged pod
CSI driver (Vault / AWS Secrets Manager)tmpfs, never in etcdrotation reconcilernode root, provider audit log

etcd and the node. Encryption at rest is an EncryptionConfiguration with a KMS v2 provider (GA in 1.29; KMS v1 is deprecated). It protects etcd and its backups: it does nothing against an API read, which is RBAC's job. Restrict get on secrets, and remember list is a full dump of the namespace. Pod creation is equivalent to reading every secret in the namespace, and pods/exec is equivalent to reading whatever that pod mounts, so both belong in the same RBAC conversation. On the node, kubelet materializes the secret under /var/lib/kubelet/pods/<uid>/volumes/kubernetes.io~secret/; root or any privileged pod on that node can read it.

Failure modes, and how you'd know.

  • Secret committed to git or baked into an image: caught by gitleaks/trufflehog in CI and image scanning; cost is rotating the credential and rewriting history.
  • Over-broad RBAC (list secrets): caught by an audit-policy rule logging secret access at RequestResponse; cost is every secret in the namespace.
  • Node compromise: caught by a Falco rule on reads of /var/lib/kubelet/pods/*/volumes/kubernetes.io~secret; cost is every secret on that node.
  • Unencrypted etcd backup: caught by config review, not runtime; cost is offline read of the whole cluster.

Rotation. A static password rotated quarterly has a 90-day exposure window. A bound service account token defaults to a 1-hour TTL and is audience-scoped, so a leaked token is dead within the hour. When you must rotate a static secret, both old and new are valid for the rollout duration: that overlap is the window you are actually defending.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

Give a pod access to a cloud API without static credentials.

Answer

Core answer

Assume EKS, a pod that needs to call S3, and no static keys anywhere. The answer is workload identity federation: the pod gets a short-lived token minted by the cluster, the cloud STS exchanges it for temporary credentials scoped to a role, and nothing long-lived is ever stored.

Concretely on EKS (IRSA): create an IAM role whose trust policy trusts the cluster's OIDC provider, gated on the exact namespace and service account. Annotate the KSA with the role ARN. The EKS pod identity webhook injects AWS_ROLE_ARN and AWS_WEB_IDENTITY_TOKEN_FILE and mounts a projected token; the AWS SDK calls sts:AssumeRoleWithWebIdentity and refreshes before expiry.

Trust policy:

JSON
{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Principal": {"Federated": "arn:aws:iam::111122223333:oidc-provider/oidc.eks.us-east-1.amazonaws.com/id/EXAMPLED539D4633E53DE1B716D3041E"},
    "Action": "sts:AssumeRoleWithWebIdentity",
    "Condition": {
      "StringEquals": {
        "oidc.eks.us-east-1.amazonaws.com/id/EXAMPLED539D4633E53DE1B716D3041E:sub": "system:serviceaccount:payments:api",
        "oidc.eks.us-east-1.amazonaws.com/id/EXAMPLED539D4633E53DE1B716D3041E:aud": "sts.amazonaws.com"
      }
    }
  }]
}

The :sub condition is the whole security boundary. Drop it and every service account in the cluster can assume the role.

Trace: pod starts → webhook mounts a projected token at /var/run/secrets/eks.amazonaws.com/serviceaccount/token (Kubernetes default TTL 3600s; EKS's webhook requests 86400s) → SDK reads AWS_WEB_IDENTITY_TOKEN_FILE → AssumeRoleWithWebIdentity → STS returns credentials valid up to 1 hour → SDK refreshes before expiry.

Alternatives

OptionIsolationCredential lifetimeWhen to use
IRSA (EKS)per service account1h STS credsEKS, AWS APIs
GKE Workload Identityper KSA1h GCP tokenGKE, GCP APIs
Azure Workload Identityper KSA1h Entra tokenAKS, Azure APIs
Vault + CSI/agentper pod, any cloudlease TTL (e.g. 1h)multi-cloud, non-cloud secrets
Node instance profilewhole nodenode lifetimesingle-tenant nodes only

GKE: annotate the KSA iam.gke.io/gcp-service-account: gsa@project.iam.gserviceaccount.com, then grant roles/iam.workloadIdentityUser to serviceAccount:PROJECT.svc.id.goog[ns/ksa]. Azure: a federated identity credential with issuer = the AKS OIDC URL, subject = system:serviceaccount:ns:ksa, audience api://AzureADTokenExchange, and the pod labeled azure.workload.identity/use: "true".

Don't use node roles when pods from different teams share a node: every pod inherits the node's permissions. Don't add a secrets vault if you're already on a managed cluster with native federation; you're adding a component for no isolation gain.

Failure modes

  • Trust policy missing :sub → any SA assumes the role. Detect: aws iam get-role --role-name X --query 'Role.AssumeRolePolicyDocument', and CloudTrail AssumeRoleWithWebIdentity events with an unexpected sub.
  • automountServiceAccountToken defaults to true → the pod also carries a Kubernetes API token. Set it false on the SA unless the pod talks to the API server.
  • Cluster rebuilt → new OIDC issuer URL → InvalidIdentityToken. Detect: STS errors in pod logs after cluster recreation; re-point the trust policy.
  • Wrong namespace/SA in :sub → AccessDenied on assume. Detect: the error names the actual sub presented.

What changes the decision

If the workload runs outside a managed cluster, or needs secrets from a non-cloud system, Vault's Kubernetes auth is the better fit. If you can't enable the cluster OIDC provider, you're back to a rotated secret: worse, but sometimes the only path.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

Design network isolation for a multi-tier Kubernetes application.

Answer

Assumptions: Kubernetes 1.29, Calico or Cilium, one namespace per tier, Postgres in-cluster on 5432, and the API tier reaches the Kubernetes API server but nothing else on the control plane. Plain Flannel implements no NetworkPolicy, so this design is a no-op there until a policy-capable CNI is installed.

The answer in one line: default-deny both directions in every tier namespace, then allow DNS, frontend to API on TCP 8080, API to Postgres on TCP 5432, and telemetry.

Why default-deny is the whole trick: NetworkPolicy has no deny verb, it is additive only. A pod is selected for a direction as soon as any policy in its namespace matches it, and selection flips that direction to default-deny; what stays allowed is the union of from/to peers across every policy matching that pod. Peers are label matches resolved by the CNI at connection setup, not by the API server. A policy only ever selects pods in its own namespace, so one in frontend can name api pods as peers but cannot select them, which is why this is one object per namespace and not one cluster-wide statement. Inside a from element each entry is OR'd; namespaceSelector and podSelector in the same entry are AND'd. Since 1.22 the API server stamps every namespace with kubernetes.io/metadata.name, so namespace selection does not depend on your own labels.

YAML
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata: {name: default-deny, namespace: api}
spec:
  podSelector: {}
  policyTypes: [Ingress, Egress]
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata: {name: api-policy, namespace: api}
spec:
  podSelector: {matchLabels: {tier: api}}
  policyTypes: [Ingress, Egress]
  ingress:
  - from:
    - namespaceSelector: {matchLabels: {kubernetes.io/metadata.name: frontend}}
      podSelector: {matchLabels: {tier: frontend}}
    ports: [{protocol: TCP, port: 8080}]
  egress:
  - to:  # DNS, or every lookup hangs
    - namespaceSelector: {matchLabels: {kubernetes.io/metadata.name: kube-system}}
      podSelector: {matchLabels: {k8s-app: kube-dns}}
    ports: [{protocol: UDP, port: 53}, {protocol: TCP, port: 53}]
  - to:  # the one backend this tier owns
    - namespaceSelector: {matchLabels: {kubernetes.io/metadata.name: db}}
      podSelector: {matchLabels: {tier: db}}
    ports: [{protocol: TCP, port: 5432}]

The empty podSelector in the first object is what denies everything else in that namespace.

Peers and ports to settle before touching YAML:

FromToPort
frontendapiTCP 8080
apidbTCP 5432
all tierskube-dns in kube-systemUDP and TCP 53
all tiersotel collectorTCP 4317
anything169.254.0.0/16none, this is IMDS
anythingkubelet 10250, etcd 2379/2380, API 6443none

Prove it from each identity instead of reading YAML:

kubectl -n frontend exec deploy/web -- nc -zv -w2 api 8080      # succeeded
kubectl -n frontend exec deploy/web -- nc -zv -w2 db 5432       # timed out
kubectl -n frontend exec deploy/web -- curl -m2 -s -o /dev/null -w '%{http_code}' http://169.254.169.254/latest/meta-data/
kubectl -n api exec deploy/api -- nslookup kubernetes.default   # must answer
cilium monitor --type drop     # or: hubble observe --verdict DROPPED

The signature matters: a policy drop looks like a timeout, while a refused connection means the packet arrived and nothing was listening. A timeout on 5432 is policy, a refusal is the app. If a forbidden probe succeeds, the CNI is not enforcing what you think. Cilium's default mode only enforces on endpoints a policy already selects; enable-policy: always applies default-deny cluster-wide.

Alternatives, and when each wins:

ApproachGainsCost
per-namespace L3/4 NetworkPolicynative, no sidecarno L7, no user identity; the label set is the trust boundary
mesh mTLS plus AuthorizationPolicy (Istio)cryptographic workload identity, L7 rulessidecars; without PeerAuthentication STRICT plaintext still passes
Cilium L7 or Calico EnterpriseHTTP method and path rules in eBPFCNI lock-in, per-request policy cost
separate clusters or node pools plus cloud security groupssurvives CNI bugscost and ops; wins when tiers differ in compliance scope or owner

On a single-tenant cluster where every workload is equally trusted and no tier holds regulated data, default-deny egress plus the DNS allow gets most of the value; per-tier micromanagement there mostly buys outages.

Failure modes to plan for:

  • DNS cut. A default-deny egress missing the kube-dns rule makes every lookup hang until the resolver timeout. Detect with nslookup from a pod and a flat coredns_dns_requests_total for that namespace.
  • Policy selects nothing. A typo'd label, or the object created in the wrong namespace. Diff kubectl get pods --show-labels against the selector; cilium endpoint list shows each endpoint's identity and policy state.
  • Label forgery. Any workload with pods/patch can add tier: frontend and inherit the frontend allows. Reject writes to reserved labels with Kyverno or Gatekeeper, audit pod patches, or stop using labels as the trust boundary.
  • hostNetwork pods. They sit in the node's network namespace and escape pod-level policy in most CNIs. Test with a hostNetwork pod probing 5432.

None of this authenticates a user. Keep application authorization and, for cross-tier traffic, mTLS: L3/4 policy answers which pod, never which person.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Introduce default-deny egress without breaking production.

Answer

Assumptions I'd state first. The CNI enforces egress policy: the API server accepts a NetworkPolicy on clusters that ignore it entirely, and those fail open. I can see per-connection drops before I deny anything. DNS, workload identity and registries are production dependencies, not background traffic.

Core. Three phases: observe, deny in the shape of what you observed, ratchet per workload.

Observe from flow data, not manifests. Owners describe intent; flows show what the process actually dials. Group by namespace and pod labels, record destination port and protocol.

Deny is one object per namespace:

YAML
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata: {name: default-deny-egress, namespace: checkout}
spec:
  podSelector: {}
  policyTypes: [Egress]
  egress: []

policyTypes: [Egress] is load-bearing. Drop it and the policy defaults to ingress-only: egress stays wide open while the manifest looks like a lock. Then allow back the smallest set, DNS first, targeted at the DNS pods by label in kube-system rather than the ClusterIP, so recreating the service doesn't break the rule.

Why DNS bites first. Drop port 53/udp and lookups stall instead of failing fast. kubelet writes ndots:5 and a three-domain search path into resolv.conf, so api.stripe.com is tried first as api.stripe.com.checkout.svc.cluster.local, then .svc.cluster.local, then .cluster.local, then absolutely: four queries. glibc's resolver defaults, timeout:5 and attempts:2, make an unanswered query cost 5 seconds, then 10. A startup probe with a 2-second timeout fails before the app logs any network error, so you get CrashLoopBackOff and start debugging the image. Allow 53/tcp too: responses over 512 bytes fall back to TCP, and a UDP-only rule breaks large record sets intermittently. If NodeLocal DNSCache is deployed, pods query 169.254.20.25 rather than the ClusterIP, and a rule written against kube-dns silently breaks on the caching nodes.

Block metadata by default. 169.254.169.254 (IMDS) and 169.254.170.2 (ECS task metadata) belong in the deny set. Workloads that need cloud credentials use IRSA or workload identity, which projects a service-account token through the API server and never touches IMDS. Highest-value rule in the whole policy: without it, one SSRF in any pod is credential theft.

Selectors widen the allow silently. Inside a single from element, namespaceSelector and podSelector are ANDed; separate elements are ORed. A bare namespaceSelector matching env: prod allows every pod in every prod namespace. Audit the effective allow set per pod, not the YAML you meant to write.

Failure modes and the signal that catches each.

FailureSymptomDetection
DNS denied5-10s stalls, readiness never passes, CrashLoopBackOff with flat CPUdrops to port 53 in the CNI flow log or policy-deny counter
CNI doesn't enforcenothing breaks, zero denials, looks like successprobe a test pod to 1.1.1.1:443; if it connects, the policy is decorative
Failure masked by retrieslatency up, error rate flat, no pagep99 per dependency, and confirm deny rate returns to zero after rollback
Endpoint IP change30-60% errors on a subset of nodes one TTL after deploydestination IPs in SYN drops that aren't in the allow list

Alternatives. CIDR allows are brittle against CDN-backed endpoints; Cilium's toFQDNs matches the DNS answer instead, at the cost of a first-query race while the proxy learns the response. An egress gateway (Istio's, or Cilium's) centralizes policy and adds SNI filtering, at the cost of a shared hop that can fail closed. A forward proxy only works if every SDK honours HTTP_PROXY, and most don't.

Rollout, exceptions, decision point. Order namespaces by external dependency count, lowest first, with one non-critical production namespace before anything customer-facing. Exceptions live in git with an owner and expiry date, reconciled by CI; an exception with no expiry fails the build. Keep create/update on NetworkPolicy and the CNI's CRDs with the platform team: anyone who can label a namespace can widen a selector-based allow. Decision point: if the enforcement probe fails, stop and fix the CNI. Otherwise you've deployed a document, not a control.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

How do you detect and prevent container breakout vulnerabilities such as hostPath escapes and cgroup manipulations?

Answer

Assumptions first: Kubernetes with containerd, cgroup v2 on the nodes, and I control the node image and admission. If the fleet is still on cgroup v1, the release_agent escape below is live and that changes the priority order.

Every container breakout I've dealt with reduces to one of three things. The container can reach a host resource it shouldn't: a mounted runtime socket, a hostPath, the host PID namespace. Or it holds a capability that lets it reconfigure the kernel, almost always CAP_SYS_ADMIN. Or it's driving a kernel bug through a syscall the runtime permits. Prevention is removing the first two and shrinking the third; detection has to be runtime, because admission control can't stop a zero-day.

The core prevention is the restricted Pod Security Standard, enforced per namespace with pod-security.kubernetes.io/enforce: restricted. What that actually gives you at the container level:

YAML
securityContext:
  runAsNonRoot: true
  runAsUser: 1000
  allowPrivilegeEscalation: false   # sets no_new_privs
  readOnlyRootFilesystem: true
  capabilities:
    drop: ["ALL"]
  seccompProfile:
    type: RuntimeDefault

plus pod-level hostPID: false, hostIPC: false, hostNetwork: false, no hostPath volumes, and automountServiceAccountToken: false. Dropping ALL capabilities is the load-bearing part: without CAP_SYS_ADMIN you can't mount a cgroup hierarchy, can't write /proc/sys/kernel/core_pattern, can't call pivot_root. allowPrivilegeEscalation: false sets no_new_privs, so a setuid binary or a file capability inside the image can't hand back what you dropped.

Here's why CAP_SYS_ADMIN plus a writable cgroup v1 mount is fatal: the release_agent escape, which is the canonical hostPath-free breakout:

  1. mount -t cgroup -o rdma cgroup /tmp/cgrp: mount any v1 controller not already mounted in the container's namespace.
  2. mkdir /tmp/cgrp/x, then echo 1 > /tmp/cgrp/x/notify_on_release.
  3. Read the container's own cgroup path on the host out of /proc/self/cgroup: say /sys/fs/cgroup/rdma/docker/<id>.
  4. echo "/sys/fs/cgroup/rdma/docker/<id>/cmd" > /tmp/cgrp/release_agent, and write the payload to that path.
  5. Put a process into /tmp/cgrp/x/cgroup.procs and let it exit. The kernel runs release_agent as root in the host's initial namespaces.

On cgroup v2 there is no release_agent file, which is one reason the v2 migration is worth doing on its own.

For detection, static admission is the wrong tool. I'd run eBPF at the node boundary, Tetragon or Falco, and alert on four things: a mount or pivot_root syscall from a process whose cgroup is a container cgroup; a write to /proc/sys/kernel/core_pattern or any release_agent path; a process whose PID namespace is the host's (/proc/<pid>/ns/pid matches /proc/1/ns/pid) while its cgroup says container; and execs out of /dev/shm or /tmp inside a container. Then reconcile: list containers from containerd and diff against the kubelet's pod list. A container the kubelet didn't create is what a hijacked docker.sock or containerd.sock looks like. On the API side, audit-log pod creates and updates carrying hostPath, privileged, or hostPID, and execs into privileged pods.

Failure modes worth naming. RuntimeDefault seccomp allows the large majority of syscalls; a bug in any of them, io_uring and netfilter have both been that bug, is not blocked by seccomp, so it is not a boundary against kernel exploits. That's what gVisor or Kata buy you, at the cost of syscall compatibility and real performance overhead. User namespaces (hostUsers: false) map container root to an unprivileged host UID and blunt the impact of a successful escape, but they break images that chown files as root or bind low ports. And restricted PSS breaks CNI, CSI and node-exporter DaemonSets: put those in their own namespace at baseline with a short, reviewed exception list, because the real risk is exception drift, not the first exception. Last blind spot: if the attacker kills the eBPF agent or auditd, you lose the telemetry that would have caught them, so ship logs off-node and alert on agent heartbeat loss.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

Evaluate a request for a privileged DaemonSet.

Answer

Core answer

Start by asking what the DaemonSet actually does on the node. "It needs privileged" is almost never the requirement; the requirement is one specific kernel-level operation. My default is no, and I only move off it when the requester names that operation and I can show no narrower primitive reaches it.

Three questions decide it:

  1. What syscall, device, or host path does it touch?
  2. Does a capability, a device plugin, a read-only hostPath, or a host namespace alone cover it?
  3. If not, what compensating controls make the residual risk acceptable?

What privileged actually grants

privileged: true is not "more permissions": it is a specific set of changes the runtime makes:

  • every capability lands in the bounding, permitted and effective sets (CAP_SYS_ADMIN, CAP_SYS_MODULE, CAP_SYS_PTRACE, CAP_NET_ADMIN, CAP_BPF)
  • the device cgroup allows all devices, so every /dev/* node is reachable
  • seccomp and AppArmor default to Unconfined
  • /sys and /proc/sys are mounted read-write, and the usual masked and read-only paths are not applied

That combination is node root. A privileged pod can load a kernel module, write to /sys/kernel, ptrace any host process, and read the kubelet's own credentials.

Mapping the request to a narrower primitive

RequestNarrower primitiveResidual gap
Load eBPF programsCAP_BPF + CAP_PERFMON (kernel ≥ 5.8)none for most tracing
Read host logshostPath /var/log, readOnly: truenone
See or signal host processeshostPID: trueptrace still needs CAP_SYS_PTRACE
Configure node networkingCAP_NET_ADMIN + hostNetwork: truenone for tc/iptables
Access a GPU or NICdevice plugin, device cgroupnone
Set a sysctlsecurityContext.sysctls with the specific keyunsafe keys need kubelet --allowed-unsafe-sysctls

If the answer is still "privileged", the artefact I want is the hardened manifest:

YAML
# checked against Kubernetes 1.29
spec:
  template:
    spec:
      nodeSelector: { node-role: infra }
      tolerations: [{ key: infra, operator: Exists, effect: NoSchedule }]
      automountServiceAccountToken: false
      hostNetwork: false
      containers:
      - name: agent
        securityContext:
          privileged: true
          seccompProfile: { type: RuntimeDefault }  # privileged defaults to Unconfined
        volumeMounts:
        - { name: hostlog, mountPath: /host/log, readOnly: true }

The namespace carries pod-security.kubernetes.io/enforce: privileged. Because that label permits privileged for every pod in the namespace, it has to be a dedicated namespace, not kube-system. A ValidatingAdmissionPolicy (GA in 1.30) or a Kyverno rule then pins the image digest and service account so nothing else can use that namespace.

Failure modes and how you see them

  • Pod compromise is node root. Detection: audit-log pods/exec into the DaemonSet, the Falco default rule "Terminal shell in container", unexpected child processes from the agent binary.
  • Mounting the runtime socket (/run/containerd/containerd.sock) turns a container escape into full node control. Detection: auditd watch on the socket, file-integrity monitoring.
  • hostNetwork reaches the AWS metadata endpoint at 169.254.169.254 and the node's IAM role. Detection: VPC flow logs to that address; enforce IMDSv2.
  • Drift: someone adds hostNetwork or a new hostPath in a later PR. Detection: the admission policy denies the change, and a periodic diff of the live DaemonSet against the reviewed manifest catches anything that slipped through.

Blast radius is worth measuring once, not asserting. Run the agent on a single canary node and try to read /etc/shadow, write to /sys/kernel, and hit the metadata endpoint. Record which succeed. That list is the exception's real cost, and it is what you take to the review.

Cost and exit

Dedicated nodes with a taint cost idle capacity and a second upgrade path. Time-bound the exception with an annotation plus a scheduled review, and keep a RuntimeClass (gVisor or Kata) migration as the removal plan.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

Prevent Kubernetes workload creators from escalating privilege.

Answer

Say this first (about 90 seconds). Two assumptions decide the answer: the namespace where a user can create workloads holds no powerful identities, and the user lacks the non-pod escalation verbs (bind, escalate, impersonate, approving CSRs, get nodes/proxy, create serviceaccounts/token). If those hold, pod admission policy is a second layer. If they don't, no pod-level control saves you.

The core point: RBAC authorizes the verb, not the consequence. create pods does not mean "can start a container": it means "can pick an identity, a filesystem and a network position". A Pod spec chooses:

  • identity: serviceAccountName, defaulting to default, whose bound token is projected into the pod;
  • data: any Secret, ConfigMap or PVC in the same namespace;
  • kernel and node: privileged, hostPID, hostNetwork, hostPath, added capabilities;
  • network position: the cloud metadata endpoint at 169.254.169.254, plus every in-cluster API that token can reach.

Nothing in the authorizer compares those choices against the creator's own permissions. Upstream documents the built-in edit ClusterRole exactly this way: it allows reading Secrets and running Pods as any ServiceAccount in the namespace, so it can be used to reach the API access level of any ServiceAccount there.

Trace, five steps. alice holds only create,get,list on pods in namespace dev. The one non-default SА there, batch-writer, may create Jobs in prod.

  1. alice applies a pod whose spec sets serviceAccountName: batch-writer.
  2. Admission allows it. Pod Security Admission constrains privilege, not identity.
  3. The kubelet projects a bound token into the pod; default TTL is one hour, renewed for the pod's lifetime.
  4. curl -H "Authorization: Bearer $(cat /var/run/secrets/kubernetes.io/serviceaccount/token)" -H 'Content-Type: application/json' -d @job.json https://kubernetes.default.svc/apis/batch/v1/namespaces/prod/jobs
  5. prod now runs a Job alice could never have created herself.

Break steps 1-2 and the chain dies without touching alice's Role: keep only worthless service accounts in dev, and enforce an allowlist with ValidatingAdmissionPolicy (CEL, GA in 1.30) so any other serviceAccountName never admits. That is the real argument for a namespace per team: it bounds which identities are reachable, not which verbs are granted.

controlstopsdoes not stopcost when wrong
pod-security.kubernetes.io/enforce: restrictedprivileged, hostPath, hostNetwork/PID/IPC, added caps, rootmounting a powerful SA's token; any non-pod vectorimages needing root or port 80 fail admission: run the audit and warn labels first, enforce later
SA allowlist via ValidatingAdmissionPolicy, Gatekeeper or Kyvernostep 1 of the tracenothing extrawebhook engines add availability risk; failurePolicy: Ignore silently stops enforcing
automountServiceAccountToken: false plus per-workload SAsambient token theftpods that genuinely need the API401s inside pods: fix with a scoped Role, not by re-enabling
namespace per teamblast radius of SAs and Secretsanyone who can patch namespace labels can drop enforcementmore RBAC objects to keep reviewed

Failure modes and how you catch them. (1) Namespace label downgrade: alert on update/patch of namespaces by anyone outside the platform group, and on the enforce label changing value. (2) nodes/proxy: a get on that subresource reaches the kubelet API through the apiserver, so it is node-level no matter which namespace the RoleBinding sits in. Do not grant it. (3) create on the serviceaccounts/token subresource mints a token for any SA in the namespace; watch it explicitly. (4) Executing into someone else's pod: log pods/exec at RequestResponse and use Falco's "Terminal shell in container" rule for the runtime view. (5) Cloud metadata: on EC2, IMDSv2 with hop limit 1 rejects the pod because the veth adds a hop; on GKE, Workload Identity plus metadata concealment.

For the pod-spec vectors themselves, keep audit at Request level for pods but RequestResponse for pods/exec, rolebindings and CSR approvals, then alert on any submitted pod with privileged: true or a hostPath volume in a namespace not labelled privileged. RequestResponse on every pod is too much volume to retain: that scoping is the price of the control.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Secure an admission webhook used for workload policy.

Answer

Assumptions: a cluster where the webhook enforces workload policy (no :latest, required limits, allowed registries), and a mistake either blocks every workload or lets bad ones through. The answer: scope the webhook narrowly, set its failure mode explicitly per control, and prove it survives its own outage.

YAML
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingWebhookConfiguration
metadata:
  name: workload-policy
webhooks:
- name: policy.example.com
  admissionReviewVersions: ["v1"]   # required since 1.16
  sideEffects: None                  # required since 1.15
  failurePolicy: Fail                # default is Ignore — set it explicitly
  matchPolicy: Equivalent            # default
  timeoutSeconds: 5                  # default 10, max 30
  namespaceSelector:
    matchExpressions:
    - key: kubernetes.io/metadata.name
      operator: NotIn
      values: ["kube-system", "policy-system"]
  rules:
  - apiGroups: [""]
    apiVersions: ["v1"]
    operations: ["CREATE", "UPDATE"]
    resources: ["pods"]
    scope: Namespaced
  clientConfig:
    service: {name: policy-webhook, namespace: policy-system, path: /validate, port: 443}
    caBundle: <base64 CA>

Why each field. failurePolicy defaults to Ignore, so a control that must block has to set Fail explicitly: leaving it unset silently turns a blocking policy into an advisory one. Fail is right when the control's absence is worse than an outage (a webhook that blocks privileged pods); Ignore is right when the webhook is advisory or a false block takes down the cluster. Decide per control, not per webhook: run two webhooks with different policies rather than one with a compromise setting. timeoutSeconds: 5 matters because the API server blocks the request for that long; a 10s timeout on a webhook matching every pod create is a 10s stall on every pod create when the webhook is slow. There is no retry: on timeout or error the API server applies failurePolicy immediately.

Self-deadlock, concretely. If the webhook's rules match the namespace where its own Deployment lives, and the webhook is down, the API server cannot create the replacement pod, so the webhook never recovers. The namespaceSelector above breaks the cycle. kubernetes.io/metadata.name is a built-in label on every namespace since 1.21, so you don't label namespaces yourself. Test it by scaling the webhook Deployment to 0 and confirming pods still schedule elsewhere.

Bounded dependencies. The admission call is synchronous and inside the API server's request path. Any network call the webhook makes (policy database, external registry, another API) adds latency and a new failure mode. Keep the decision local: sync policy into a ConfigMap or in-process cache via a controller and answer from memory. If you must call out, set a client timeout well under timeoutSeconds and a circuit breaker.

Conversion. matchPolicy: Equivalent means a client sending v1beta1 is converted to v1 before the call. Test by sending the same object in both versions and confirming the same decision.

Failure modes and detection.

FailureSymptomDetection
Webhook down, FailPod creates rejected with failed calling webhookapiserver_admission_webhook_rejection_count non-zero
Webhook slowPod-create latency rises to timeoutSecondsapiserver_admission_webhook_admission_duration_seconds p99
Cert expiredx509: certificate signed by unknown authorityCert-expiry alert; rotate caBundle with the serving cert
Self-deadlockWebhook pods can't be createdNamespace excluded; scale-to-0 test

Emergency bypass. A documented, narrower bypass than disabling all admission: a label like policy.example.com/bypass: "true" on a namespace, added during an incident and recorded in the audit log. Disabling the whole webhook is the last resort.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

Isolate mutually untrusted tenants on Kubernetes.

Answer

Short answer: A namespace is an organizational boundary, not a security boundary. On a shared cluster, isolate tenants with four layers: admission (Pod Security Admission at restricted), identity (tenant-scoped RBAC and no auto-mounted service account tokens), network (default-deny NetworkPolicy on a CNI that actually enforces it), and resources (ResourceQuota/LimitRange). When the threat model includes kernel exploits, noisy neighbors, or a regulator, move up to dedicated nodes, a sandboxed runtime, or separate clusters.

Assumptions I'd state first: tenants can create pods and namespaces, they are mutually untrusted, and the cluster is multi-tenant on shared nodes unless I say otherwise.

Why namespaces alone fail. A pod in namespace A reaches a pod in namespace B by default: Kubernetes has no implicit network isolation. A tenant who can create a pod can also mount any ServiceAccount in its namespace, read mounted Secrets, and, if admission allows it, use hostPath, hostNetwork, or hostPID to touch the node. The namespace is a label; the real boundary is whatever admission, RBAC, network policy, and the runtime enforce.

The four levers and what each closes.

Admission. Label the namespace pod-security.kubernetes.io/enforce: restricted. Restricted requires runAsNonRoot, allowPrivilegeEscalation: false, drops all capabilities, requires a seccompProfile of RuntimeDefault, and forbids hostPath, hostNetwork, hostPID, hostIPC, and privileged containers. That closes the "tenant pod reaches the node" path. (PSA is GA in 1.25; PodSecurityPolicy was removed in the same release.)

Identity. Set automountServiceAccountToken: false on the namespace's default ServiceAccount, and give each workload its own SA with a minimal Role. Bound tokens issued via TokenRequest default to a 3600-second expiry and are audience- and object-scoped, so a stolen token is short-lived. RBAC is namespaced via Role/RoleBinding; keep ClusterRoleBindings out of tenant hands.

Network. Apply a default-deny policy:

YAML
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny
  namespace: tenant-acme
spec:
  podSelector: {}
  policyTypes: ["Ingress", "Egress"]

This denies all ingress and egress for every pod in the namespace until another policy allows it. It only works if the CNI enforces policy: Calico and Cilium do; kubenet and kindnet do not.

Resources. A ResourceQuota caps pods, requests.cpu, and limits.cpu; a LimitRange supplies defaults so a tenant can't schedule unbounded pods.

Going further. Dedicated nodes with a taint (tenant=acme:NoSchedule) plus matching tolerations and nodeAffinity isolate CPU, memory, and disk contention. A sandboxed runtime changes the kernel boundary: gVisor (runsc) implements the syscall surface in userspace so a guest kernel bug doesn't reach the host kernel; Kata Containers runs each pod in a lightweight VM with its own kernel. Both cost throughput and add per-pod overhead. Separate clusters isolate the control plane, API server, admission, and kernel entirely: the right call when a regulator or a hard multi-tenancy requirement is in play.

Failure modes and how to detect them.

  • NetworkPolicy present but unenforced. Detection: run a canary pod in tenant A that curls a Service in tenant B; if it connects, the CNI isn't enforcing. kubectl get networkpolicy shows objects, not enforcement.
  • Egress to the cloud metadata endpoint 169.254.169.254. A pod without egress policy can steal node IAM credentials. Detection: VPC flow logs showing that destination, or a policy that blocks link-local.
  • Service account token theft. If RBAC lets a tenant read Secrets or mount another SA, tokens leak. Detection: API audit log entries where a system:serviceaccount: principal acts outside its namespace.
  • Noisy neighbor. Detection: container_cpu_cfs_throttled_seconds_total climbing on a co-tenant's pods, or node memory-pressure evictions.
  • Shared-kernel escape. Detection: runtime security (Falco) alerts on unexpected privileged syscalls, or seccomp audit events.

The decision. Same kernel, cooperative-ish tenants, low regulatory load: namespaces + PSA + RBAC + default-deny + quotas. Noisy neighbors or node-level data: dedicated nodes. Untrusted code on a shared kernel: sandboxed runtime. Regulated or hard multi-tenancy: separate clusters.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-17

Decide whether a workload needs a sandboxed RuntimeClass.

Answer

Short answer: default to no. A sandboxed RuntimeClass earns its cost when you run code whose compromise you must survive (multi-tenant CI runners, user-supplied functions, third-party or generated code) on nodes that also host workloads you trust. If every workload on the node is first-party and equally trusted, runc plus seccomp, dropped capabilities, non-root and a read-only rootfs is the cheaper boundary, and a sandbox buys you little.

Three assumptions decide it: who can get code onto the node, what a kernel escape would reach (cloud identity, other tenants' data, the node's kubelet credentials), and whether the workload needs GPU, raw sockets or unusual syscalls.

Why the shared-kernel boundary is weak

Every runc container on a node is a process on the same kernel. Namespaces, cgroups, seccomp, capabilities and AppArmor/SELinux constrain what that process can ask the kernel to do; they do not stop a kernel bug from doing something else. A container escape is a kernel LPE, and the container's syscall surface is the attack surface. Docker's default seccomp profile denies a few dozen syscalls out of roughly 350: the rest are reachable, and a privileged container or CAP_SYS_ADMIN removes most of the constraint. So the question is not "is the container configured well" but "how much do I lose if the kernel is wrong".

How the two mainstream sandboxes change that

  • gVisor (runsc): a user-space kernel (the sentry) implements the Linux syscall surface in Go, and the host kernel only sees a small fixed set of syscalls from the sentry. An escape has to break the sentry and the host kernel. Cost: syscall-heavy paths (many small file I/O ops, fork/exec, some io_uring and AF_PACKET paths) run slower; unimplemented syscalls return ENOSYS; /proc and /sys are partly synthetic; GPU needs nvproxy.
  • Kata Containers: each pod gets a lightweight VM (QEMU, Cloud Hypervisor or Firecracker) with its own guest kernel, so isolation is hardware virtualization. Cost: VM boot adds latency to pod start, each pod carries a guest kernel's memory, and GPU/device passthrough goes through VFIO. Needs nested virtualization on cloud instances.

Decision table

Signalrunc is enoughsandboxed RuntimeClass
Who authors the codeyour team, reviewedtenants, users, generated
Blast radius of escapeone node, low-value datacloud identity, other tenants
GPU / special devicesrequiredgVisor nvproxy or Kata VFIO: verify first
Compliancenone specificPCI/HIPAA tenant isolation

Wiring it up (RuntimeClass is node.k8s.io/v1, GA since Kubernetes 1.20)

YAML
apiVersion: node.k8s.io/v1
kind: RuntimeClass
metadata: {name: gvisor}
handler: runsc            # must match containerd's runtime handler
overhead:
  podFixed: {cpu: 250m, memory: 64Mi}
scheduling:
  nodeSelector: {sandbox: gvisor}

Pods opt in with spec.runtimeClassName: gvisor. Selection is opt-in, so enforce it: a ValidatingAdmissionPolicy (or Gatekeeper/Kyverno) that rejects pods in tenant namespaces without the field, plus the nodeSelector above so they only land on nodes with the handler installed.

Failure modes and how you see them

  • Unsupported syscall under gVisor: app exits with ENOSYS/EPERM at startup or on a rare path. Detect: run the workload's full integration suite under runsc in CI, not just smoke tests; watch runsc logs.
  • Kata VM won't boot: pod stuck in ContainerCreating, kubelet event failed to create containerd task. Detect: alert on pods pending > 2 min in sandbox namespaces.
  • Scheduling dead-end: runtimeClassName set but no node matches nodeSelector; pods Pending with FailedScheduling. Same alert catches it.
  • Latency regression: p99 up on syscall-heavy paths. Detect: A/B the same deployment with and without runtimeClassName on one node pool before rollout.
  • Density loss: podFixed overhead is charged to every pod. On a 64 GiB node, 256 MiB pods go from 256 to 204 per node (65536/320) at 64 MiB overhead: about 20% fewer. Budget for it.

Sandboxing is one layer. Keep non-root, dropped capabilities, network policy, image provenance and short-lived workload identity: a sandbox does not make an overprivileged cloud identity or a malicious image safe.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Protect Kubernetes worker nodes that run application containers.

Answer

Assumptions first. This assumes you own the node image and the kubelet config: self-managed nodes, or managed node groups where you supply the AMI and the kubelet flags. On Fargate or Autopilot you don't own either, and the node layer collapses into admission control and network policy.

The core answer. A worker node is a shared-kernel boundary. Every pod on it runs on one kernel, so a container escape is a node compromise, and a node compromise is every secret mounted by every pod on that node. Three moves, in order of payoff:

  1. Make the node disposable. Bake an image, disable SSH, patch by replacing the node, not by logging in.
  2. Narrow the kubelet's identity. The kubelet holds a client cert; what that cert can do is the blast radius of a node compromise.
  3. Constrain what runs on it. Pod Security Admission at restricted, seccomp RuntimeDefault, and a RuntimeClass for anything you don't trust.

Kubelet flags that matter. The defaults are wrong for a hardened node:

flagdefaultset towhat it stops
--anonymous-authtruefalseunauthenticated requests to :10250
--authorization-modeAlwaysAllowWebhookkubelet deciding its own authorization
--read-only-port102550unauthenticated pod spec, env and log reads
--rotate-certificatesfalsetruea client cert that never expires
--protect-kernel-defaultsfalsetruekubelet starting with unsafe sysctls
--seccomp-defaultfalsetruepods with no seccomp profile

What NodeRestriction actually buys you. Trace a compromised kubelet on worker-7. Its cert is CN system:node:worker-7, group system:nodes. With the Node authorizer and the NodeRestriction admission plugin on, it can read Secrets and ConfigMaps only for pods with spec.nodeName: worker-7, can write only its own Node object, and cannot set labels under the node-restriction.kubernetes.io/ prefix, so it can't relabel itself to attract pods that assume a trusted node. Without NodeRestriction, that same cert is a cluster-wide read of every secret on every node. That is the whole argument for turning it on.

Metadata is the shortcut. A pod with SSRF reaches 169.254.169.254 and, on a node with an instance role, gets that role's credentials. On AWS set HttpTokens=required (IMDSv2) and hop limit 1; GCP and Azure require a header, which raises the bar but is not a boundary. Detection: VPC flow logs showing pod-CIDR traffic to the metadata address.

Failure modes and how you see them. A denied get secrets from system:node:* in the audit log is a node probing outside its own pods: that is your compromise signal, not noise. A drain that hangs is a PodDisruptionBudget reporting DISRUPTIONSALLOWED 0; kubectl drain will wait forever. And the one people get wrong: after a node compromise you do not clean up in place. The kernel may be rootkitted. Cordon, snapshot the disk, terminate the instance, replace it.

Trade-offs. Immutable replacement beats in-place patching because the image is known-good and drift-free, but it costs a full node roll per patch and is painful for nodes holding local PVs or long-lived DaemonSet state. gVisor and Kata Containers buy stronger isolation than runc at a cost: gVisor intercepts syscalls in userspace and some syscall-heavy workloads slow down badly or hit unimplemented calls; Kata runs a VM per pod with tens of MB of memory overhead and slower starts. Route only the untrusted workload through a RuntimeClass. Disk encryption protects a detached disk, not a running node, the keys are in memory, so treat it as compliance, not runtime defence.

Cadence. Kubernetes supports the three most recent minor versions and ships patches roughly monthly, so a node image needs rebuilding and rolling within about 30 days of a fix. Example: 100 nodes, 5 concurrent drains, ~4 minutes each including graceful termination and reschedule, is about 80 minutes of rolling. Cheap enough that "we'll patch in place later" is not a real argument.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Design resource controls against noisy or compromised workloads.

Answer

The 90-second answer

Assume a multi-tenant Kubernetes cluster on shared nodes, with workloads that are either buggy or actively hostile, and platform components (kubelet, CNI, CoreDNS, ingress) that must survive them. Three layers.

Bound each workload so its worst case is finite. Requests decide scheduling and eviction rank; limits decide enforcement. A CPU limit is enforced by CFS quota, so a runaway thread is throttled, not evicted. A memory limit is enforced by the cgroup OOM killer, so a leak kills and restarts the container. An ephemeral-storage limit evicts the pod. --pod-max-pids (default -1, unlimited) bounds a fork bomb. Bandwidth annotations bound the network. GPUs are integer resources (nvidia.com/gpu) with no sharing by default; MIG or MPS if you must share.

Make the cluster refuse work it can't bound. LimitRange injects default request and limit at admission, so a pod that specifies nothing doesn't silently become BestEffort. ResourceQuota caps aggregate requests, limits, pod count and object count per namespace. PriorityClass plus preemption keeps platform pods schedulable. HPA maxReplicas and Cluster Autoscaler max nodes bound growth upward; quota is the hard stop.

Make failure ordered and observable. Eviction order is BestEffort → Burstable over requests → Guaranteed. Preemption takes lowest-priority victims first and never touches preemptionPolicy: Never pods.

Mechanism: the controls are not interchangeable

  • CPU limit → throttle. cpu.cfs_period_us defaults to 100000 µs (100 ms). A 200m limit sets cpu.cfs_quota_us to 20000 µs. A thread wanting 100% CPU runs 20 ms, then is throttled for the remaining 80 ms of every period: 20% throughput, p99 latency climbs, no eviction.
  • Memory limit → OOM kill. The cgroup OOM killer kills a process when usage reaches the limit; kubelet restarts it per restartPolicy. A container at its 256Mi request leaking 1 MiB/s reaches a 512Mi limit in ~256 s.
  • Node pressure → eviction. kubelet's hard eviction defaults: memory.available<100Mi, nodefs.available<10%, imagefs.available<15%, nodefs.inodesFree<5%. Victims are ranked by QoS class, then priority, then usage above requests.
  • Preemption → scheduling, not enforcement. The scheduler picks a node, then evicts lower-priority pods to fit, preferring victims whose PDBs stay satisfied.

Artefacts

YAML
apiVersion: v1
kind: LimitRange
metadata: {name: defaults, namespace: batch}
spec:
  limits:
  - type: Container
    default:        {cpu: 500m, memory: 512Mi, ephemeral-storage: 1Gi}
    defaultRequest: {cpu: 200m, memory: 256Mi, ephemeral-storage: 256Mi}
    maxLimitRequestRatio: {cpu: 10, memory: 4}
---
apiVersion: v1
kind: ResourceQuota
metadata: {name: batch-quota, namespace: batch}
spec:
  hard:
    requests.cpu: "20"
    requests.memory: 40Gi
    limits.cpu: "40"
    limits.memory: 80Gi
    pods: "50"
    count/jobs.batch: "20"
---
apiVersion: scheduling.k8s.io/v1
kind: PriorityClass
metadata: {name: batch-low}
value: 100
globalDefault: false
preemptionPolicy: Never
FailureMechanismSignalControl
CPU hogCFS quota throttlecontainer_cpu_cfs_throttled_seconds_total / container_cpu_cfs_periods_totalCPU limit
Memory leakcgroup OOM killkube_pod_container_status_last_terminated_reason{reason="OOMKilled"}memory limit
Fork bombPID exhaustionnode pid.available pressure, container_processes spike--pod-max-pids
Disk fillnodefs pressurenodefs.available, container_fs_usage_bytesephemeral-storage limit, quota
Quota abuseadmission rejectionkube_resourcequota{type="used"} vs hard, 403 on createResourceQuota
Noisy networklink saturationCNI bandwidth dropskubernetes.io/ingress-bandwidth

Load-test each row (burst, leak, fork bomb, disk fill) and confirm the control trips and the workload recovers.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Secure persistent storage for container workloads.

Answer

What I'd say in the first two minutes

"Secure persistent storage" is really four questions: is the data encrypted at rest, can another tenant reach it, who is allowed to create the volume, and what happens when it's deleted. I'd assume a multi-tenant cluster on managed Kubernetes with a CSI driver, and data regulated enough that deletion has to be provable.

My core answer: tenants never create StorageClasses or PersistentVolumes. The platform ships a small set of pre-approved StorageClasses that pin the provisioner, the encryption key, the reclaim policy and the binding mode; tenants only create PVCs against them. Then three admission controls: Pod Security Admission at restricted (which forbids hostPath), RBAC denying create on storageclasses and persistentvolumes to everyone but the platform team, and a policy that rejects tenant-supplied CSI parameters or mountOptions.

The StorageClass that does the work

YAML
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
  name: db-encrypted-retain
provisioner: ebs.csi.aws.com
parameters:
  type: gp3
  encrypted: "true"
  kmsKeyId: arn:aws:kms:us-east-1:111122223333:key/abcd
reclaimPolicy: Retain
allowVolumeExpansion: true
volumeBindingMode: WaitForFirstConsumer

encrypted + kmsKeyId push encryption to the EBS layer, so the key never lives in the cluster and a stolen disk or leaked snapshot is unreadable. Retain means deleting the PVC leaves the PV in Released and the volume intact. WaitForFirstConsumer stops the provisioner creating a volume in a zone the pod can't be scheduled into. allowVolumeExpansion lets you grow in place.

Access mode is where cross-tenant leaks happen

YAML
spec:
  accessModes: ["ReadWriteOncePod"]
  storageClassName: db-encrypted-retain
  resources: { requests: { storage: 100Gi } }

ReadWriteOncePod (GA in 1.29) is enforced by the kubelet: a second pod mounting the same PVC fails with a FailedMount event naming the first pod. Plain ReadWriteOnce is node-scoped, so two pods on the same node can both mount it: that's the leak people miss.

If the app runs non-root, set securityContext.fsGroup and fsGroupChangePolicy: OnRootMismatch. The default is Always, which re-chowns the whole tree on every mount; on a volume with millions of files that is minutes added to pod start, and it's the usual cause of "the pod takes four minutes to come up after a reschedule."

Deletion trace. kubectl delete pvc pgdata → PVC gone, PV goes Bound → Released, EBS volume still exists and still bills. Deleting the PV does not delete the backing volume under Retain: you delete it in the cloud API. That's the point, and it's also the orphaned-volume bill you need a GC job for.

Trade-offs. Delete is right for scratch and CI; Retain for anything an auditor will ask about. Storage-layer KMS protects against disk theft and snapshot leakage but not against a compromised pod that has the volume mounted: only client-side encryption does that, at the cost of key management in the app. RWX (NFS/CephFS) is what people reach for with multiple replicas, but it's a shared filesystem with no per-pod isolation; prefer ReadWriteOncePod and one writer.

Failure modes. VolumeSnapshotContent is cluster-scoped, so a tenant with create on volumesnapshots can restore content they shouldn't: detect via audit logs on snapshot create, prevent by scoping VolumeSnapshotClass and RBAC. The CSI node plugin runs privileged, mounts hostPath /var/lib/kubelet, and needs mountPropagation: Bidirectional; anyone who can edit that DaemonSet owns every volume on the node, so pin its image with admission policy. And CSI credentials live in Secrets: without an EncryptionConfiguration (aescbc or KMS v2) they sit plaintext in etcd. Check the apiserver flag.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Patch Kubernetes worker nodes without weakening workload security.

Answer

Assumptions: self-managed or Cluster-API nodes, not a managed pool where the vendor owns the kubelet. Workloads have PDBs. The node image is pulled by digest.

Core answer (say this in the first two minutes). A worker patch is a node replacement, not a package upgrade. Build an image with the patched kernel, kubelet, container runtime and CNI, roll it as surge capacity, and let the eviction API, not a human, set the pace through PodDisruptionBudgets. Draining protects availability. The security risk sits elsewhere: a replacement node can come back weaker than the one it retires. A host image that ships SELinux permissive, a kubelet config without seccompDefault: true, a CNI that serves NetworkPolicy objects but never enforces them: none of that shows up in a drain, and each one leaves a workload less isolated than before. So the rule is: a new node carries traffic only after it passes assertions that were run against the old node too, and it never sits schedulable-but-unverified in between. If the image also bumps the kubelet, keep it at or below the API server version: a kubelet may be up to three minors behind, never ahead.

Why eviction, not deletion. kubectl drain cordons the node (spec.unschedulable, which adds the node.kubernetes.io/unschedulable:NoSchedule taint) and evicts each pod through the policy/v1 Eviction subresource. The API server checks the PDB and returns 429 rather than let a Deployment drop under its budget; the owning controller, not the drain, chooses where the replacement lands. PDB v1beta1 was removed in 1.25, so a fleet still holding old manifests fails on the first drain.

Trace of the gate: kubectl drain node-17 --ignore-daemonsets --delete-emptydir-data --timeout=10m, with Deployment api at replicas 3 and PDB minAvailable: 2; node-17 hosts two of the three.

  1. First eviction: currentHealthy is 3, so disruptionsAllowed = 3 - 2 = 1. Allowed. The pod gets a deletion timestamp, the container gets SIGTERM and terminationGracePeriodSeconds (default 30) to exit.
  2. Second eviction, seconds later: that pod is gone, its replacement is still pulling the image, so currentHealthy = 2 and disruptionsAllowed = 0. The API server answers 429 TooManyRequests, and kubectl retries with backoff.
  3. Once the replacement passes readiness, currentHealthy returns to 3 and the retry succeeds.

Drain wall-clock is therefore set by replacement readiness, not by the 30-second grace period. At 240 nodes, 10 concurrent drains, ~9 minutes each: 24 batches, about 3.6 hours. The last vulnerable node stays exposed for that whole window, which is what sizes your surge.

What a new node must prove before it takes traffic. Pending CSRs get approved by a human or by an approver that only signs node names you created: the kubelet authenticates as system:node:<name> in system:nodes, and NodeRestriction stops it from labelling itself with node-restriction.kubernetes.io/ keys or touching another node's pods. Then check:

assertioncheckfail signal
seccomp defaultgrep Seccomp /proc/1/status in a pod with no seccompProfileSeccomp: 0: the image lost seccompDefault: true
pod admissionapply a pod violating pod-security.kubernetes.io/enforce: restrictedthe pod is admitted
network policycanary pod connects across namespaces under default denythe connection succeeds
host MACgetenforce, aa-statusPermissive where the old node was Enforcing

Failure modes worth rehearsing. A CrashLooping pod pushes currentHealthy under minAvailable; with the default unhealthyPodEvictionPolicy: IfHealthyBudget the drain hangs indefinitely: kubectl get pdb -A shows ALLOWED 0, and AlwaysAllow is the fix. Reusing a hostname without deleting the old Node object lets the kubelet adopt it, labels and all; compare the Node's creationTimestamp against the image build. With serverTLSBootstrap: true and no approver, kubectl logs and exec fail with x509 errors until the kubelet-serving CSR is signed.

Emergency path. For active exploitation, cordon the pool and delete pods rather than drain them (kubectl drain --disable-eviction skips the PDB entirely): time-boxed, with a named owner and an expiry date. Rollback means pausing the rollout and keeping the already-patched nodes; re-imaging a node back to the vulnerable kernel is not a rollback.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

Design runtime detection for containerized production workloads.

Answer

Assumptions first. Linux nodes on kernel 5.4+ so eBPF CO-RE works, Kubernetes, you can run a privileged DaemonSet, and admission control already rejects the obvious bad pods. If the kernel is older or you don't own the node image, the sensor story changes and you fall back to auditd: say that before drawing anything.

The 90-second answer. Runtime detection is a per-workload allowlist of what a container legitimately does, enforced by an eBPF sensor that sees syscalls in kernel context, with everything outside the allowlist treated as a signal. You are not detecting "malicious"; you are detecting "this image digest under this service account has never done this before."

Mechanism. eBPF programs attach to kprobes and tracepoints on execve, openat and connect, and to LSM hooks for privilege changes. Filtering happens in the kernel, so only matching events cross the ring buffer to userspace. The agent then joins each event with container ID, pod, namespace, image digest and service account: that join is what turns a raw syscall into a finding. A bare execve is noise; execve /bin/sh in a pod whose digest has never run a shell is a finding.

YAML
- rule: Shell spawned in container
  desc: Interactive shell in a workload that never runs one
  condition: >
    spawned_process and container
    and proc.name in (bash, sh, dash, ash)
    and not proc.pname in (cron, supervisord)
  output: >
    shell (user=%user.name container=%container.name
    image=%container.image.repository cmd=%proc.cmdline parent=%proc.pname)
  priority: WARNING
  tags: [container, shell]

Baselines. Build one per (namespace, service account, image digest), not per cluster. Learn from 7 days of production traffic, freeze, and re-learn only when the digest changes. A cluster-wide baseline is either so loose it misses everything or so tight it pages on every deploy.

SignalSensorWhy it mattersCost
shell / package-tool execeBPF execve kprobepost-exploitation step~0
write outside approved pathseBPF openat + LSMpersistence, config tamperlow
new listenereBPF bind/connectreverse shell, C2low
token / secret file readeBPF openatcredential theftlow
privileged pod, hostPIDadmission + auditsensor evasion~0
K8s API verbsaudit log at Metadata levellateral movementlog volume

Trade-offs. eBPF (Tetragon, Falco's modern eBPF driver) filters in kernel and carries container context; auditd is universal but has no container context and drops events at high syscall rates. Detect-only (Falco) versus detect-and-enforce (Tetragon can SIGKILL on a match): enforcement stops the attack, but one false positive kills a production pod, so start detect-only and promote individual rules to enforce after they run clean for a release cycle. Metadata-only versus payload capture: argv, env and file paths are cheap and high-value; file contents and stdin are expensive and privacy-sensitive, so capture them only under a targeted rule with a time-boxed window.

Failure modes. Living-off-the-land: the attacker uses a binary already in the allowlist, e.g. curl in a workload that legitimately curls. Detect by alerting on new parent/child pairs, not binary names. Sensor blind spots: a privileged pod with hostPID, or a kernel module load, can hide from or disable the sensor. Alert on privileged admission and treat a missing agent heartbeat as a signal. Event loss: the ring buffer overflows under burst; watch the drop counter and alert on any non-zero value. Baseline poisoning: if the learning window runs while compromised, the attack becomes "normal". Pin baselines to digest and review the diff on every re-learn.

Cost. A node with 40 pods at roughly 3,000 syscalls/s each is 120k syscalls/s. Tracing all of them costs on the order of 3–5% CPU on that node: measure it on your own hardware, because that number decides whether you can afford it. Restricting the probe to execve/openat/connect drops the event rate to a few hundred per second and the cost under 1%.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

Design observability and metrics for container security.

Answer

Core answer (first 90 seconds)

Assume Kubernetes on containerd, images signed with Sigstore/cosign, admission control via Kyverno or OPA Gatekeeper, runtime detection via eBPF (Tetragon) or Falco, and kube-apiserver audit logs shipped off-cluster. The decision that matters: container security telemetry is three planes (build/provenance, admission/policy, runtime behavior) and they are only useful when joined on the immutable image digest. A tag is mutable; the digest is what actually ran. So at admission, resolve tag→digest and stamp the pod with labels: digest, signature identity, build ID, SBOM reference. Every runtime event then carries pod UID → digest → provenance. Without that join you get three alert streams nobody can correlate, which is the usual failure.

What to measure

Measure exposure and response, not alert counts.

signalmetricthreshold / note
signature coverage% running pods with verified signature + digestalert below 99%
exploitable exposuredeployed CVEs in CISA KEV and reachablecount, not raw CVE total
policyadmission denials, exemption count and ageexemption older than 30 days = review
runtimeTetragon/Falco rule hits per workloadrate, grouped by workload
responseMTTD, containment timecontainment under 15 min for confirmed compromise
sensor healthnodes reporting runtime eventsalert if any node silent over 10 min

Trade-offs

eBPF (Tetragon) runs roughly 1–3% CPU overhead and needs a recent kernel; Falco's kernel module needs a privileged DaemonSet, which is itself a risk you are trying to detect. Run admission in audit mode first: measure the false-positive rate for a week, then enforce. Blocking on day one breaks deploys and gets the policy switched off. Cardinality: per-pod labels explode Prometheus; aggregate by workload and namespace, keep digest only on the alert path.

Failure modes and detection

  • Sensor gap: a node loses the agent and everything looks clean. Detect by DaemonSet desired vs ready plus a per-node heartbeat; a silent node is an alert, not a non-event.
  • Alert fatigue: 10k Falco events a day, none triaged. Detect by acknowledged-to-fired ratio; if it is near zero, the rules are noise.
  • Log tampering: a node-level attacker deletes logs. Ship off-node, append-only, and alert on gaps in the audit stream.
  • Stale nodes: kubelet behind, unpatched. Track node version drift against the cluster baseline.

Worked trace (hypothetical)

An unsigned image is deployed. Admission is in audit mode, so it logs but admits. The pod starts with digest D. Tetragon sees exec of xmrig at t+40s. The join resolves D → build ID → no signature. Alert fires with workload, namespace, node, digest, signature=absent, process=xmrig. Containment: cordon the node, capture memory, replace the node. MTTD 40s, containment 12 min.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

Respond to a compromised Kubernetes pod.

Answer

Clarify first, then assume

Two things change the playbook: what the detection actually is (a runtime alert such as Falco's "Terminal shell in container", an egress anomaly in the API audit log, or a scanner hit), and whether the cluster is managed. My stated assumptions: EKS, one runtime alert on pod prod/app-7d9f, cluster-admin access, no memory-forensics tooling, control-plane audit logging already enabled.

The assumption that drives the ordering: a pod's two dangerous assets are its identity and its network reach, and neither dies when you delete the pod. A bound ServiceAccount token is a JWT with a 1-hour default lifetime, rotated by the kubelet at 80% of that. kubectl delete pod does not invalidate it. Delete first and you lose the container's writable layer and process memory while leaving a live credential behind. So: revoke, isolate, preserve, then kill.

Cut identity and network (first 5 minutes, non-destructive)

kubectl get pod app-7d9f -n prod -o jsonpath='{.metadata.uid} {.status.containerStatuses[0].imageID}'
kubectl auth can-i --list --as=system:serviceaccount:prod:app-sa
kubectl delete sa app-sa -n prod            # bound tokens stop authenticating
kubectl delete secret app-sa-token -n prod  # legacy long-lived token
kubectl apply -f default-deny-egress.yaml   # block 169.254.169.254 and node CIDR

The auth can-i --list is how you scope the identity instead of guessing. For a cloud workload identity (IRSA, GKE/Azure Workload Identity), the STS session defaults to 1 hour and outlives the SA deletion, so instead of chasing sessions, attach a Deny policy conditioned on aws:TokenIssueTime earlier than the incident start: existing sessions die, new ones work.

Two caveats worth saying aloud. NetworkPolicy is enforced by the CNI, not by kube-proxy: on a cluster without Calico, Cilium or equivalent, your default-deny does nothing. And IMDSv2 does not help here, because a compromised pod can perform the PUT itself.

Preserve (minutes 5-15)

Copy the pod spec and events to a separate account: the container's overlayfs upper dir and process memory are destroyed when the container is removed, and kubectl logs --previous only exists after a restart. kubectl debug -it pod/app-7d9f --image=busybox --target=app lets you look at the live process tree, but the attacker can see you do it.

Scope the blast radius

Read the pod spec for mounts and privilege, then map to a ceiling:

What you findHow far the attacker getsMove
Only the pod's own SANamespace-scoped reads/writesRotate namespace secrets, rebuild pod
hostPath of /run/containerd/containerd.sock or /var/run/docker.sockNode root; every secret of every pod on the nodeCordon, drain, rebuild node, rotate all secrets it hosted
privileged: true, CAP_SYS_ADMIN, or hostPIDNode kernel, escape via cgroup release_agentSame, and treat node identity as burned
Cloud workload identityCloud APIs as that roleCloudTrail for the role ARN; Deny by TokenIssueTime
hostNetworkNode network position; can reach kubelet on 10250 and IMDS on 169.254.169.254Node rebuild if kubelet read endpoints were called

Read the audit trail

The attacker's API calls appear as user.username: system:serviceaccount:prod:app-sa. At RequestResponse level you also get request bodies, which is how you learn which Secret it read:

jq 'select(.user.username=="system:serviceaccount:prod:app-sa")
    | {verb, res:.objectRef.resource, name:.objectRef.name, t:.requestReceivedTimestamp}' audit.log

On EKS, control-plane audit logging is opt-in per cluster, so check that the log exists before promising answers from it.

Trade-off: when isolation beats preservation

Decide on one question: does the attacker hold a path to a higher trust boundary? A mounted runtime socket, privileged, hostPID, or a cloud role with successful STS calls in the last hour means yes, isolate immediately and accept losing volatile evidence, because rebuilding a node is cheaper than a compromised cloud account. If the pod only ever held its own SA, spend the fifteen minutes snapshotting first.

Rebuild and rotate

Rebuild from a pinned image digest through the pipeline, never rollout restart on the same tag. Rotate everything the SA could read, everything on the shared node, and the cloud role. Check co-resident pods using the same SA before declaring the node clean, and validate the fix with a negative path: confirm the old token now gets 401 and the old STS session gets AccessDenied.

Failure modes to name: deleting the pod before revoking; assuming NetworkPolicy is enforced; assuming audit logs exist; rotating the SA but not the cloud role.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Test container and workload security before release.

Answer

Assumptions first: Kubernetes 1.25+ (Pod Security Admission is stable), a CNI that actually enforces NetworkPolicy (Calico or Cilium. Flannel does not), an admission controller, and images signed with cosign. If any of those is missing, say so up front; the plan changes.

The answer: test in four layers, cheapest first, and at each layer hunt the specific bypass instead of re-running the happy path.

1. Artifact. Verify the digest, not the tag: tags are mutable, so myapp:1.4 can point at a different layer set tomorrow. cosign verify --key ... against the digest, then check the SBOM (Syft or Trivy) for Critical CVEs that have a fix. Trade-off: blocking on every CVE makes the pipeline unusable, so gate on fixable Critical/High and let the rest through with a tracked exception. Digest pinning also breaks automated patching: without a re-pin job you ship stale bases.

2. Admission. Submit manifests that should be rejected and assert the rejection. The restricted Pod Security level requires exactly this:

YAML
securityContext:
  runAsNonRoot: true
  allowPrivilegeEscalation: false
  seccompProfile: {type: RuntimeDefault}
  capabilities: {drop: ["ALL"]}

A namespace with no pod-security.kubernetes.io/enforce label defaults to privileged, so an unlabeled namespace is itself a finding. Also test hostNetwork/hostPID/hostIPC (all default false), a /var/run/docker.sock hostPath mount, and automountServiceAccountToken (defaults true: set false where the pod never calls the API).

3. Network and identity. Apply default-deny NetworkPolicy, then prove it: DNS to kube-dns, the cloud metadata endpoint at 169.254.169.254, and a cross-namespace service. On AWS, IMDSv2 needs a PUT to get a token, so a plain GET failing is not proof: test the token path. Check projected service-account token audiences, and that the pod's cloud identity (IRSA, Workload Identity) cannot assume roles outside its scope.

4. Runtime. Falco or equivalent, driven by controlled triggers: a shell inside a container, a write to /etc, an egress connection to a non-allowlisted IP. Measure alert-to-ticket latency, not just that the rule fired.

Failure modes and what they cost:

FailureBlast radiusDetection
Webhook down, failurePolicy: Fail (the default)Every pod create cluster-wide stalls for timeoutSeconds (default 10s), then failsapiserver audit log, webhook error-rate metric
Webhook down, failurePolicy: IgnorePolicy silently bypassed cluster-wideAudit log only: no user-visible symptom
No resource limitsPod is BestEffort; a fork bomb OOMs the node and evicts neighbourscontainer_memory_working_set_bytes, kubelet eviction events
Evidence lost on restartContainer filesystem is ephemeral; kubectl exec output dies with the podPost-incident, when the artifact is already gone

That last row is why you copy evidence out (kubectl debug --copy-to, or a PVC) before triggering anything destructive.

Rollback: keep the previous admission policy and image digest pinned so a revert is one apply, and retain fixtures per supported Kubernetes version. A policy that passes on 1.28 may not on 1.30.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

Walk me through hardening the Kubernetes control plane: API server and controller-manager configuration, who can reach the API server, protecting etcd and control-plane credentials, and detecting a workload abusing its service account token.

Answer

Core (first 90 seconds). The API server is the only component that talks to etcd, and etcd holds every Secret, service account token and RBAC binding in the cluster. So control-plane hardening is three questions: what the API server will accept, who can reach it, and what happens when a workload's identity is used against it. Start from the defaults, because most of them are permissive.

ComponentSettingDefaultEffect if left alone
kube-apiserver--anonymous-auth=falsetrueunauthenticated requests become system:anonymous; one stray RBAC binding grants them
kube-apiserver--authorization-mode=Node,RBACAlwaysAllowthe binary default authorizes everything; kubeadm overrides it
kube-apiserver--profiling=falsetrue/debug/pprof hands out heap and CPU profiles
kube-apiserver--audit-policy-fileunsetno audit log at all
kube-controller-manager--use-service-account-credentials=truefalseevery controller shares one credential
kube-controller-manager, scheduler--bind-address=127.0.0.10.0.0.0metrics and health ports exposed on the network
etcd--client-cert-auth=truefalseanyone who reaches 2379 reads every Secret

Also enable NodeRestriction (kubeadm does) so a kubelet can only modify its own Node object and pods bound to it, and set --tls-min-version=VersionTLS12 at minimum. On kubelets, --anonymous-auth defaults to true and --authorization-mode to AlwaysAllow, which makes port 10250 a full bypass of everything above.

Reachability and identity. Control-plane endpoints belong on a private subnet; on managed clusters where the endpoint is public, restrict it to authorized networks. For humans, OIDC with short-lived tokens rather than client certs valid for a year. Never bind anyone to system:masters: that group is hardcoded in the API server's authorizer chain and RBAC cannot revoke it. In RBAC, treat escalate, bind and impersonate as privilege-escalation verbs, and check what anonymous can do with kubectl auth can-i --list --as=system:anonymous.

etcd and credentials. etcd is the crown jewels: client and peer certificate auth, TLS, loopback or a dedicated network, and encryption at rest through --encryption-provider-config using the KMS v2 provider rather than aescbc, whose key sits on the same disk as the data. Backups are encrypted and handled as cluster-admin material.

Service account tokens. Since 1.24 new pods get bound tokens from the TokenRequest API: audience-scoped, one hour by default, rotated by the kubelet at 80% of lifetime, and validated against the service account's UID. Legacy secret-backed tokens never expire; find them with kubectl get secrets --field-selector type=kubernetes.io/service-account-token -A and delete them. Set automountServiceAccountToken: false unless the workload actually calls the API.

Detection and containment. Audit is the primary signal. A policy logging RequestResponse for secrets, serviceaccounts/token and RBAC writes, and Metadata for pods/exec and pods/portforward, catches the common abuse path. Worked trace: a pod in team-a with an automounted token is exploited through an SSRF; the attacker reads /var/run/secrets/kubernetes.io/serviceaccount/token and calls GET /api/v1/namespaces/team-a/secrets from inside the cluster. The audit entry shows user system:serviceaccount:team-a:app with a curl user agent, a service account that has never called the API before. Containment: delete the pod, delete the RoleBindings, delete the ServiceAccount object, which invalidates outstanding bound tokens because they are checked against its UID. Rotating --service-account-signing-key-file invalidates every token in the cluster and answers a leaked signing key, not one stolen token.

Failure modes. Bound tokens are not network-bound: a stolen one works from anywhere with reach to 6443, so short expiry and audience are the only limits. Audit logs written to node disk are lost with the node and readable by anyone with node access, so ship them off-cluster. A compromised controller-manager or scheduler credential is worse than a workload token, because those identities mutate the objects that define every workload.

Curated: · Written: · Reviewed:

Difficulty: Hard