Container and Kubernetes Security Questions
Securing containerized and orchestrated workloads. Covers container image scanning and hardening, Kubernetes security (RBAC, network policies, pod security, secrets), runtime protection, and cloud-native security patterns. The specific attack surface and controls introduced by containers and orchestration platforms.
How would you implement least privilege for Kubernetes service accounts using RBAC and OPA Gatekeeper? Describe how to design roles, bind them safely, write admission control policies to prevent privilege escalation, and a rollout plan to retrofit an existing cluster with minimal disruption.
Sample Answer
Approach (brief): apply least privilege by designing narrow Roles (namespaced) / ClusterRoles only when needed, avoid wildcard verbs/resources, bind to specific ServiceAccounts, and enforce via OPA Gatekeeper admission policies that (a) block privilege escalation patterns and (b) audit existing bindings before enforcing. Rollout incrementally with discovery, audit, remediation, and gradual enforcement.
Example Role and safe binding:
# namespaced role granting only read access to ConfigMaps
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: configmap-reader
namespace: payments
rules:
- apiGroups: [""]
resources: ["configmaps"]
verbs: ["get","list","watch"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: payments-cm-reader-binding
namespace: payments
subjects:
- kind: ServiceAccount
name: payments-sa
roleRef:
kind: Role
name: configmap-reader
apiGroup: rbac.authorization.k8s.io
Key design principles:
- Principle of least privilege: only required verbs/resources and minimal scope (namespace vs cluster).
- Prefer Roles over ClusterRoles unless cross-namespace or cluster-wide required.
- Use dedicated ServiceAccounts per component, avoid reusing default SA.
- Set automountServiceAccountToken: false for pods that don’t need it.
- Use namespacing and naming conventions (svc-<app>-sa) to track ownership.
Gatekeeper / OPA policies (examples):
- Deny Role/ClusterRole rules with "*" verbs/resources.
- Deny RoleBinding/ClusterRoleBinding that bind ClusterRole "cluster-admin" or wildcard subjects.
- Prevent creation of RoleBindings that elevate namespace SAs to cluster-wide roles.
- Ensure automountServiceAccountToken is false for pods without RBAC needs.
Sample Rego constraint (deny wildcard permissions & cluster-admin bindings):
package rbac.restrictions
deny[msg] {
input.review.kind.kind == "Role"
some i
r := input.review.object.rules[i]
any_wildcard(r)
msg := sprintf("Role %v contains wildcard verbs/resources", [input.review.object.metadata.name])
}
any_wildcard(r) {
r.verbs[_] == "*"
}
any_wildcard(r) {
r.resources[_] == "*"
}
deny[msg] {
input.review.kind.kind == "ClusterRoleBinding"
input.review.object.roleRef.name == "cluster-admin"
msg := "Binding to cluster-admin is forbidden"
}
Gatekeeper setup: create ConstraintTemplate wrapping above Rego and a Constraint that targets Role/ClusterRoleBinding. Start with enforcementAction: dryrun (audit) then deny.
Prevent privilege escalation patterns to catch:
- RoleBindings that reference ClusterRoles (binding namespace SA to cluster role).
- ClusterRoleBindings to service accounts in namespaces (unless approved).
- Roles with escalation verbs (bind, impersonate, create clusterroles).
- Use policy to deny verbs: "bind", "escalate", "impersonate" on sensitive resources.
Rollout plan (minimal disruption):
-
Discovery (1–2 weeks)
- Audit current RBAC: list Roles/ClusterRoles, RoleBindings/ClusterRoleBindings, and ServiceAccounts. Map which SAs are used by pods.
- Run risk scoring: identify high-risk bindings (cluster-admin, wildcards, impersonate/bind verbs).
- Use kube-rbac-proxy or custom scripts to produce dependency maps.
-
Audit phase with Gatekeeper dry-run (2 weeks)
- Deploy Gatekeeper with constraints in dryrun to collect violations.
- Notify owners (via labels/annotations recorded in audit) and create tickets for remediation.
-
Remediation & least-privilege design (2–4 weeks, iterative)
- For each app, define required actions and create narrow Roles.
- Replace broad bindings: create new Roles/RoleBindings, update pod specs to use dedicated SAs.
- Use feature flags / rollout windows for teams; allow exceptions with timeboxed approval via an exception CRD.
-
Enforcement (gradual)
- Flip constraints from dryrun to deny for low-risk/green areas (non-prod namespaces first).
- Monitor audit logs, kube-apiserver denies, and app behavior.
- Progress to production namespaces after verification.
-
Harden defaults & automation
- Enforce automountServiceAccountToken: false via PodSecurityPolicy/PodSecurity admission (or Gatekeeper).
- Add CI checks: prevent merging manifests that create wildcard RBAC or cluster-admin bindings.
- Periodic audits and alerting for new violations.
Rollback & safety:
- Start in dry-run; use short windows for converting to deny and have runbooks to revert constraints.
- Keep emergency 'rbac-exception' process: a short-lived ClusterRoleBinding allowed by Ops with strict TTL and audit.
- Use feature flags and health probes: if denials cause failures, temporarily allow the binding and create remediation ticket.
Monitoring & SLOs:
- Track number of denied admissions, number of wildcard/broad bindings, time-to-remediate violations.
- Alert if a new cluster-admin binding is created.
- Incorporate in incident runbooks to check RBAC denials when pods fail to start or API calls fail.
Why this works:
- Narrow roles and scoped bindings reduce blast radius.
- Gatekeeper provides centralized, auditable policy enforcement and a safe dry-run path.
- Incremental rollout with discovery and owner involvement minimizes disruption while raising cluster security posture.
What is an SBOM (Software Bill of Materials) for a container image? Describe the key elements an SBOM should contain and explain how SRE teams can use SBOMs to reduce supply chain risk.
Sample Answer
An SBOM (Software Bill of Materials) for a container image is a machine-readable inventory that lists all components (OS packages, language libraries, build tools, and metadata) included in that image and their relationships. It provides provenance and version information so teams can trace what’s actually running.
Key elements an SBOM should contain:
- Component list: package/name/version for OS packages, language libs, and binaries
- Component types and relationships: runtime vs build-time, dependency graph
- Provenance: source repository, build timestamp, builder image, cryptographic hashes
- Licenses and authorship: license info for compliance
- Vulnerability references: known CVEs mapped to components (if available)
- SBOM format/metadata: SPDX/CycloneDX version, tooling that produced it
How SRE teams use SBOMs to reduce supply-chain risk:
- Rapid impact analysis: when a CVE is published, quickly identify affected services by matching SBOM components and prioritize patch/rollback.
- Faster patching & mitigation: automate alerts from CI/CD and orchestration (K8s) to trigger rebuilds or network mitigations for impacted images.
- Auditability & compliance: verify images deployed in prod match approved SBOMs; detect drift or unauthorised components.
- Incident response: speed root-cause by knowing exact dependency tree and provenance to decide containment or remediation.
- Preventive controls: enforce SBOM generation in CI, block builds with banned licenses or high-risk components, and integrate SBOM checks into admission controllers.
This makes supply-chain issues visible, measurable, and automatable—key for maintaining reliable, secure production systems.
Describe the difference between static image scanning (build-time) and runtime vulnerability detection. Give examples of tools for each category and when each should be used in an SRE practice.
Sample Answer
Static image scanning (build-time) vs. runtime vulnerability detection address different stages of the software lifecycle and different threat surfaces.
Static image scanning (build-time)
- What: Analyze container images/artifacts for known vulnerable packages, misconfigurations, secrets before deployment.
- Tools: Trivy, Clair, Anchore, Snyk CLI.
- When to use (SRE): Integrate into CI/CD pipelines as a gate (fail builds on high severity), maintain SBOM/inventory, enforce baseline compliance, and reduce blast radius by fixing issues early.
- Pros/cons: Fast, deterministic, prevents known issues; cannot detect exploit attempts, zero-day behavior, or runtime configuration drift.
Runtime vulnerability detection
- What: Monitor running hosts/containers for suspicious behavior, exploit attempts, anomalous syscalls, in-memory attacks, or newly discovered vulnerabilities that couldn’t be caught at build-time.
- Tools: Falco, Sysdig Secure, Aqua Runtime, Datadog Runtime Security, eBPF-based detectors.
- When to use (SRE): Continuous protection in production, incident detection and response, detecting lateral movement or compromised workloads, compensating controls for legacy images or emergency patches.
- Pros/cons: Detects active threats and drift; can produce more alerts, needs tuning, may have performance impact.
Practical SRE approach
- Use both: enforce build-time scanning in CI/CD and SBOMs, plus runtime detection for production safety. Prioritize triage (severity, exploitability, exposure) and automate remediation where safe (quarantine, rollback, rebuild). Regularly tune rules to reduce noise and run retrospectives after incidents to close gaps.
Compare and contrast three approaches to storing secrets for applications running in Kubernetes: (1) Kubernetes Secrets (base64), (2) envelope-encrypted secrets with KMS, and (3) an external secret store like HashiCorp Vault. Describe strengths and weaknesses of each.
Sample Answer
Situation: As an SRE, choosing a secrets strategy balances security, operational complexity, and reliability. Below I compare three common approaches and when to pick each.
- Kubernetes Secrets (base64)
- What: Secrets stored as API objects in etcd encoded with base64 (not encrypted by default).
- Strengths: Simple to use, native Kubernetes RBAC integration, easy CI/CD and mounting into pods as env or files, low operational overhead.
- Weaknesses: Base64 is not encryption — if etcd or node access is compromised, secrets are exposed. Backups and logs can leak them. Limited auditing and rotation workflows out of the box.
- Good when: Low-compliance workloads, small teams, or as short-lived bootstrap secrets.
- Envelope-encrypted secrets with KMS
- What: Encrypt secret data before storing in etcd using a KMS (cloud KMS or HSM) for envelope keys.
- Strengths: Strong at-rest protection (etcd stores ciphertext), centralized key management, easier compliance, automatic key rotation in KMS, minimal runtime changes for apps.
- Weaknesses: Adds dependency on KMS availability and network; more complex to configure (encryption config, IAM). Still leaves plaintext in memory of components that decrypt (kubelet, controllers) and needs careful backup handling and audit config.
- Good when: Want improved at-rest security without introducing a separate secret service; cloud-native environments.
- External secret store (HashiCorp Vault)
- What: Dedicated secret manager with dynamic secrets, leasing, fine-grained policies, and audit logs.
- Strengths: Strong security model: dynamic credentials, short TTLs, detailed auditing, secret revocation, multiple auth methods (Kubernetes auth), secret versioning, and secret engines for databases/cloud APIs.
- Weaknesses: Operational overhead: highly-available deployment, unsealing, backup/DR, network latency, and learning curve. Adds another critical dependency and requires RBAC/policy integration.
- Good when: High compliance, frequent rotation, dynamic credentials, or multi-cluster/multi-cloud needs.
SRE considerations and recommendation:
- For strict security/compliance or dynamic secrets choose Vault (or cloud secret manager) with Kubernetes auth and sidecar/CSI drivers to inject secrets securely.
- For pragmatic cloud setups, enable KMS-backed etcd encryption plus RBAC/audit; still consider external store for dynamic secrets.
- Never rely on base64-only in production; if used, enforce RBAC, network hardening, encrypted etcd, and shortest possible secret lifetimes.
- Automate rotation, monitoring (access/audit logs), and test secret loss/rotation in DR drills.
Design a highly available and performant admission webhook service that validates image signatures and SBOMs for every pod creation. Address scaling (concurrency, caching), resilience (timeouts, circuit breakers), data sources (signature transparency logs), and how to avoid introducing a single point of failure in the API server flow.
Sample Answer
Requirements:
- Functional: synchronous validating admission webhook that rejects/accepts Pod creation based on image signature and SBOM verification.
- Non-functional: 99.99% availability for admission path, <50ms median added latency, graceful degradation if verification backend unavailable, horizontally scalable, auditable decisions.
High-level architecture:
API Server → kube-admission-webhook (sidecarless) fronting a pool of webhook servers behind a Service/Endpoint slice → verification workers + caches → external data sources (signature CT logs, SBOM stores, OCI registries, KMS/attestation) → async auditor & metrics pipeline.
Core components & responsibilities:
- Lightweight webhook front-end (stateless)
- Receives AdmissionReview, extracts images/SBOM refs, performs fast local checks.
- Configured with conservative timeout (e.g., 200ms) and short circuit policy.
- Verification service (horizontally autoscaled)
- Performs cryptographic signature verification, SBOM policy evaluation, queries CT logs.
- Use gRPC with connection pooling for low latency.
- Multi-layer caches
- L1 in-memory LRU per-node/process for recent verification results (image digest → verdict + TTL).
- L2 shared distributed cache (Redis or memcached with replication) keyed by image digest + policy version to survive process restarts and scale.
- Async auditor & recheck queue
- Persist decisions to audit log and event store; background reconciler re-verifies when cache TTLs expire or CT logs change.
- Data sources
- Read-only replicas of signature transparency logs (local mirrors or caching proxies), SBOM indexers, and push-based change feeds (webhooks) to invalidate caches.
Scaling & concurrency:
- Keep front-end minimal to allow high concurrency; delegate heavy crypto to worker pool and hardware acceleration (HSMs or KMS).
- Horizontal autoscaling based on request rate, CPU, and queue latency; use pooled gRPC workers to avoid per-request TLS/KMS handshake overhead.
- Use per-image deduplication: coalesce concurrent verification requests for same digest (singleflight pattern).
Resilience:
- Timeouts & circuit breakers: per-call timeouts (e.g., 150ms), retry with exponential backoff for transient errors, circuit breaker to fail fast and return configurable fallback (e.g., "allow with alert" or "deny safe-mode") based on policy/SLO.
- Graceful degradation: if verification backends down, webhook can operate in fail-open for non-critical namespaces or fail-closed for high-security namespaces using policy flags.
- Health checks & readiness probes: keep webhook out of Service endpoints when unhealthy to avoid API server timeouts.
- Avoid single point of failure: run N replicas across AZs, use Kubernetes MutatingWebhookConfiguration/ValidatingWebhookConfiguration with multiple service endpoints; keep local caches so single cache outage doesn't block every request.
- Observe admission flow limits: set admission webhook timeout in API server (configurable) and keep webhook response time well under it.
Security & correctness:
- Verify by image digest, not tag. Tie SBOM to digest. Validate signatures against trusted root set rotated via automatic rollouts.
- Harden RPC channels (mTLS) and enforce authn/z.
Monitoring & SLOs:
- Metrics: latency p50/p99, verification errors, cache hit ratio, circuit breaker state, recheck queue depth.
- Alerts on elevated p99 latency, cache miss surge, backend errors.
- Define SLO: e.g., 99.99% calls <200ms; error budget drives fail-open behavior.
Trade-offs:
- Strict fail-closed maximizes security but risks availability; hybrid per-namespace policies mitigate risk.
- Strong caching reduces verification cost but increases window where revocations/CT updates aren't enforced — mitigate via short TTLs and pushed invalidations.
Example patterns:
- singleflight to coalesce verifications
- cache key = imageDigest|policyVersion|certFingerprint
- async audit reconciler re-evaluates on CT log append events
This design balances low-latency admission, high availability, and security through caching, coalescing, resilient calls, and clear fallback policies.
Unlock Full Question Bank
Get access to all 48 Container and Kubernetes Security interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.