Dev.to Security ๐Ÿ” Cybersecurity ๐Ÿ‘ 0 ๐Ÿ“– 4 min read

Blocking AI Agent Privilege Escalation in Kubernetes Before Apply Time

Teams deploying autonomous coding assistants, Model Context Protocol (MCP) tool servers, and debug bots inside Kubernetes often grant those pods broad ServiceAccount roles or relaxed container settings so prototyping run

Blocking AI Agent Privilege Escalation in Kubernetes Before Apply Time

Teams deploying autonomous coding assistants, Model Context Protocol (MCP) tool servers, and debug bots inside Kubernetes often grant those pods broad ServiceAccount roles or relaxed container settings so prototyping runs smoothly. When an indirect prompt injection inside a repository ticket or external API response steers that agent, the attacker does not need a kernel zero-day exploit. The compromised workload uses its legitimate Kubernetes credentials (pods/exec, secret listing, or hostPID and CAP_SYS_ADMIN flags) to pivot across the cluster at machine speed.

Running a deterministic, zero-dependency static manifest gate (KubeScope, tested on Python 3.13) catches eight common privilege-escalation and container-escape vectors before kubectl apply ever reaches the cluster, returning exit code 2 in under 300 ms inside CI/CD checks.

Why agent workloads accumulate cluster-admin paths

Traditional microservices usually map to fixed API routes reviewed by platform teams. Agentic workloads decide which commands, shells, or Kubernetes calls to run dynamically at runtime, which pushes developers toward permissive defaults:

  1. Mounting default long-lived ServiceAccount credentials paired with wildcard roles (*/*) or pods/exec permissions across namespaces so an automated troubleshooter can inspect failing pods.
  2. Attaching host namespaces (hostPID: true, hostNetwork: true) or CAP_SYS_ADMIN so sandboxed tool runners can spawn nested containers or trace processes.
  3. Relying on runtime container isolation while leaving secrets get and list open in scope, exposing database credentials and third-party API keys to any injected tool call.

Reviewing raw templates manually misses these paths easily once Helm charts or Kustomize overlays merge values at deploy time.

Architecture: failing dangerous manifests before admission

Pre-apply Kubernetes RBAC and Pod escape gate workflow

Placing a deterministic Python gate (KubeScopeAuditor) directly after Helm/Kustomize rendering inspects the exact JSON that would hit the Kubernetes API (Deployment pod templates, Pod specs, Role, and ClusterRole manifests). Clean manifests return exit code 0; any violation prints structured JSON findings and exits with 2 to fail the pull request immediately.

Catching four escalation vectors in an agent deployment

Consider a rendered JSON manifest for a prototype MCP runner (Deployment/mcp-tool-runner in namespace ai-agents) paired with an overly helpful helper role (ClusterRole/agent-cluster-helper):

{
  "items": [
    {
      "kind": "Deployment",
      "metadata": {"name": "mcp-tool-runner", "namespace": "ai-agents"},
      "spec": {
        "template": {
          "spec": {
            "hostPID": true,
            "containers": [
              {
                "name": "agent-sandbox",
                "image": "python:3.12-slim",
                "securityContext": {
                  "privileged": false,
                  "capabilities": {"add": ["CAP_SYS_ADMIN"]}
                }
              }
            ]
          }
        }
      }
    },
    {
      "kind": "ClusterRole",
      "metadata": {"name": "agent-cluster-helper"},
      "rules": [
        {"apiGroups": [""], "resources": ["pods/exec"], "verbs": ["create"]},
        {"apiGroups": [""], "resources": ["secrets"], "verbs": ["get", "list"]}
      ]
    }
  ]
}

Passing that rendered manifest through python -m kubescope.cli --json manifest.json detects all four escalation vectors in 287 ms and halts the build with exit code 2:

[!] KubeScope found 4 privilege escalation vectors:
[
  {
    "resource": "Deployment/mcp-tool-runner",
    "namespace": "ai-agents",
    "rule": "HOST_PID_ESCAPE",
    "severity": "CRITICAL",
    "description": "hostPID is true: Pod can inspect and kill host processes"
  },
  {
    "resource": "Deployment/mcp-tool-runner",
    "namespace": "ai-agents",
    "rule": "DANGEROUS_CAPABILITY",
    "severity": "CRITICAL",
    "description": "Container 'agent-sandbox' grants 'CAP_SYS_ADMIN'"
  },
  {
    "resource": "ClusterRole/agent-cluster-helper",
    "namespace": "default",
    "rule": "POD_EXEC_PRIV_ESC",
    "severity": "HIGH",
    "description": "Role permits pods/exec which allows lateral arbitrary command execution"
  },
  {
    "resource": "ClusterRole/agent-cluster-helper",
    "namespace": "default",
    "rule": "SECRET_ENUMERATION",
    "severity": "HIGH",
    "description": "Role allows reading all secrets in scope"
  }
]

Stripping hostPID and CAP_SYS_ADMIN, setting allowPrivilegeEscalation: false and readOnlyRootFilesystem: true, and narrowing the RBAC binding to a namespace-scoped Role allowing only get and list on pods clears the check in 293 ms (exit code 0):

[+] All manifests passed KubeScope security baseline.

Eight checks you can enforce without external dependencies

Because the auditor runs purely on Python's standard library (dependencies = [] in pyproject.toml), minimal CI containers can enforce all eight rules without installing heavyweight policy binaries (3 core unit tests execute in 0.001s):

Rule ID Severity Trigger condition
HOST_PID_ESCAPE CRITICAL spec.hostPID set to true
HOST_NETWORK_ESCAPE HIGH spec.hostNetwork set to true
HOST_IPC_ESCAPE HIGH spec.hostIPC set to true
PRIVILEGED_CONTAINER CRITICAL Container securityContext.privileged set to true
DANGEROUS_CAPABILITY CRITICAL capabilities.add includes CAP_SYS_ADMIN, SYS_ADMIN, or ALL
WILDCARD_ADMIN_PERMISSIONS CRITICAL ClusterRole or Role grants * on both resources and verbs
POD_EXEC_PRIV_ESC HIGH Role permits create or * on pods/exec
SECRET_ENUMERATION HIGH Role permits get, list, or * on secrets

Where static manifest linting stops and runtime controls take over

Static pre-apply gates form the outer fence, yet inspecting the underlying auditor source reveals four engineering limits you need to compensate for in production:

  1. JSON-only stdin/file parsing (without BOM): cli.py reads rendered JSON via open(args.json, "r"). PowerShell Set-Content -Encoding UTF8 writes a UTF-8 Byte Order Mark that causes json.load to raise Unexpected UTF-8 BOM, so Windows runners must export BOM-free UTF-8 (kubectl ... -o json or Helm/Kustomize JSON pipelines work cleanly).
  2. No binding graph traversal yet: auditor.py evaluates Role and ClusterRole objects directly; it does not trace RoleBinding or ClusterRoleBinding subjects across hops or check secondary verbs such as impersonate, bind, escalate, or hostPath volume mounts. Notice too that cluster-scoped objects lacking metadata.namespace default to "namespace": "default" in report JSON.
  3. Uniform exit gate across severities: Although KubeScopeAuditor accepts fail_on_critical, cli.py exits with code 2 for both CRITICAL and HIGH findings.
  4. Runtime token and Pod Security Admission enforcement: Static YAML checks cannot revoke a valid projected token after an indirect prompt injection. Pair pre-apply checks with Kubernetes Pod Security Admission (restricted profile on AI agent namespaces), short-lived audience-bound projected ServiceAccount tokens (expirationSeconds), and API audit logging plus eBPF alerts (Falco or Tetragon) when an agent container reads token paths unexpectedly.

Next step

Export one rendered AI-agent namespace (kubectl get deployments,pods,roles,clusterroles -n ai-agents -o json) into your CI pull-request pipeline and block any merge that grants pods/exec, wildcard permissions, secrets read verbs, or host namespace sharing. If an agent genuinely needs cluster telemetry, put a small read-only broker API in front of Kubernetes instead of handing raw ServiceAccount tokens to the pod.

Drafted with AI-assisted editing from verified code and test runs in KubeScope.

๐Ÿ“ฐ Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes โ€” full credit and traffic to the original publisher.