← Back to blog

kubectl exec Security: Lock Down Shell Access to Pods

November 24, 2026
kubectl exec Security: Lock Down Shell Access to Pods

kubectl exec is safe only when the permission behind it is narrow, logged and held by as few identities as possible. The command itself is simple: it runs a process inside a container that is already running. The risk is that the RBAC rule that allows it is easy to write too broadly, and the credentials that reach it sit on every engineer's laptop. This guide covers how exec works, what an attacker or a careless user can do with it, how to scope and audit it, and how to keep the access files behind it protected.

Kubezilla Desktop
Manage Kubernetes Clusters With Confidence
Kubezilla Desktop keeps kubeconfigs in secure local storage while bringing cluster management tools into one native app.
Visit

TL;DR

  • pods/exec is its own RBAC subresource. A rule on pods does not cover it, and a rule without resourceNames opens every pod in the namespace.
  • Exec gives whoever holds it the container's environment variables, mounted files and tokens, so treat it as read access to secrets.
  • Exec calls are visible in API server audit logs, including the command, but RBAC alone cannot restrict which commands run in a session.
  • Grant exec to groups or ServiceAccounts through namespaced RoleBindings, keep it short-lived in production, and protect the kubeconfig that carries it.
  • A local-first desktop client with pod terminals keeps cluster credentials on your machine and out of a cloud sync.

Table of Contents

What kubectl exec actually does

Per the official kubectl reference, kubectl exec executes a command in a container. The form is kubectl exec (POD | TYPE/NAME) [-c CONTAINER] [flags] -- COMMAND [args...]. The -i flag passes stdin, -t allocates a TTY, and the double dash separates kubectl's flags from the command's own arguments. The -c flag picks a container in a multi-container pod.

Two common uses:

kubectl exec --stdin --tty shell-demo -- /bin/bash
kubectl exec shell-demo -- env

The first opens an interactive shell. The second runs one command and returns. Both come from the Kubernetes debugging documentation. The key detail for security is in a Kubernetes project blog post: exec starts a new process inside an existing container, so it runs with that container's identity, filesystem, network and mounted volumes. It does not create anything new. It borrows what the workload already has.

That borrowing is the whole problem. The container may hold a database password in an environment variable, a ServiceAccount token under /var/run/secrets, or a cloud credential. Whoever can exec can use them.

Why exec is a security boundary, not a convenience

Security frameworks treat exec as a named attack technique. Microsoft's Threat Matrix for Kubernetes lists "Exec into container": users with exec permission can run malicious commands in containers, and attackers can even use a legitimate OS image such as Ubuntu as a backdoor container. MITRE ATT&CK describes the same thing as Container Administration Command (T1609): an adversary with sufficient permissions can gain remote execution in a container through the API server, the kubelet or kubectl exec.

In practice, someone with exec on a pod can:

  • Print environment variables and read any Secret mounted into that pod.
  • Use the pod's ServiceAccount token to call the API with that account's rights.
  • Reach internal services that only that pod's network position can reach.
  • Copy data out. The Microsoft matrix's data collection entry notes that kubectl cp wraps exec by running a tar process, so blocking exec restricts kubectl cp too.

A Secret does not stop this. Encryption at rest changes how Secrets are written to etcd, not who can read them once they are mounted in a pod you can enter. If your threat model says "secrets are encrypted, so we are fine", exec is the gap in that argument.

How RBAC controls pods/exec

Access to exec is governed by Kubernetes RBAC (role-based access control, the system that maps users and groups to allowed API actions). Three details trip teams up.

It is a separate subresource

According to H2 Security's write-up on exec-only access, pods/exec is a subresource that a rule on pods does not cover. A rule on pods/exec without resourceNames allows exec into every pod in the namespace. So a Role that says "exec on pods/exec" for a developer in payments means a shell in every payments pod, including the one holding the payment provider key.

The same write-up recommends a narrow Role: get on the specific pod and create on pods/exec with resourceNames set, and deleting the binding when the task ends. Here is the shape of it:

apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: exec-debug-api-7d9f
  namespace: staging
rules:
  - apiGroups: [""]
    resources: ["pods"]
    resourceNames: ["api-7d9f"]
    verbs: ["get"]
  - apiGroups: [""]
    resources: ["pods/exec"]
    resourceNames: ["api-7d9f"]
    verbs: ["create"]

The verb changed with WebSockets

The same source explains that kubectl exec historically sent an HTTP POST, checked as create. Newer kubectl versions use a WebSocket whose handshake is an HTTP GET, so on clusters without the fix, get on pods/exec is enough to open a shell. Kubernetes Forensics says kubectl streams over WebSockets by default from Kubernetes 1.31. The practical rule: audit and review both get and create on pods/exec, and never assume a read-only role cannot open a shell.

kubectl exec verbs across transport changes

Scope it as tightly as the rest of RBAC

The official RBAC good practices advise assigning permissions at namespace level with RoleBindings, avoiding wildcard permissions, using cluster-admin only where specifically needed, and never adding users to the system:masters group, whose members bypass all RBAC checks and even authorization webhooks. MITRE's mitigation guidance points the same way: least-privilege RBAC with RoleBindings rather than ClusterRoleBindings.

A quick review you can run today:

  1. List every Role and ClusterRole that mentions pods/exec, pods/* or *.
  2. For each, check the bindings: who or what holds it, and in which namespaces.
  3. Replace wildcards with explicit resources, and add resourceNames where the target is known.
  4. Move exec for production out of standing access (see below).

Audit what people run

You cannot secure what you cannot see. Kubernetes Forensics explains how to detect exec, attach and port-forward in audit logs. An exec event appears with verb create (or get on WebSocket clients), stage ResponseStarted when the session opens, and response code 101 Switching Protocols on success. The command is visible as URL-encoded command= parameters in requestURI, even at Metadata audit level. A 403 marks a denied attempt.

Useful alerts to build from that:

SignalWhy it matters
Exec by a ServiceAccountWorkloads rarely need to open shells; this often means a stolen token
Exec into kube-systemControl-plane add-ons hold powerful credentials
Exec outside change windowsBreaks the normal pattern of who debugs when
Repeated 403s on pods/execSomeone is probing for access

There is one limit to know. The Kubernetes enhancement proposal KEP 6035 states that the API server records the caller's identity in the audit log, but that identity is never forwarded to the kubelet or container runtime. Runtime security tools therefore cannot attribute what happens inside the container to the Kubernetes user who opened the session. The proposal suggests propagating the audit ID, and it notes that code in the container can overwrite the related environment variable, so the ID is a correlation hint, not proof. Until that lands in your cluster, join audit events to runtime events by time, pod and session start.

Make exec safer in production

RBAC says who can open a session. It does not say what they can do once inside. The Kubernetes blog post on securing production debugging (March 2026) says exactly this: RBAC alone cannot restrict which commands run inside an exec session. Its recommendations are worth adopting as a baseline:

  • Use short-lived, identity-bound credentials, for example hardware-backed keys.
  • Put an access broker on top of RBAC that can require manual approval and restrict the commands allowed in a session.
  • Grant rights to groups or ServiceAccounts, never to individual users.

Add the container-side basics from MITRE's mitigations: read-only containers and minimal images. A distroless image with a read-only root filesystem gives an intruder very little to work with, and your own debugging moves to a different mechanism.

That mechanism is an ephemeral container. kubectl debug creates an ephemeral container or a modified copy of a pod to troubleshoot without altering the original workload. Our guide to Kubernetes ephemeral containers walks through the flow, and it pairs well with minimal images because the debugging tools arrive only when needed. Note that ephemeral containers have their own RBAC subresource, so scope that permission with the same care.

For admission control, KEP 6035 notes that exec permission already lets callers inject dangerous environment keys, so RBAC is the mitigation, and that admission controllers can inspect the proposed structured PodExecOptions.Env field. Microsoft's guidance also recommends admission controllers to restrict exec commands.

The part people forget: the kubeconfig on your laptop

Everything above assumes the credential that carries the exec right is protected. In most teams that credential lives in a kubeconfig file in ~/.kube, often copied between machines, pasted into chat to "get someone unblocked", or synced to a personal cloud folder. A stolen kubeconfig with exec rights is the same incident as a compromised account.

Three habits reduce the exposure:

  1. Keep one identity per person, bound to a group, so revoking is a single change.
  2. Prefer short-lived tokens over static ones. If automation needs a file, follow our guide to service account kubeconfigs so that account has only the rights it needs.
  3. Store the files where other software cannot read them casually. Our kubeconfig security guide covers permissions, rotation and what to do after a leak.

For reaching clusters that sit behind a bastion, an SSH tunnel keeps the API server off the public internet. We cover the mechanics and the certificate errors that come with them in Kubernetes SSH tunnels. For the broader picture, see our API access hardening guide and the piece on zero trust access for admins.

Where a desktop client fits

Most of the daily exec traffic is not an attacker. It is an engineer jumping between clusters, running kubectl config use-context, typing -n and -c flags from memory and opening the shell in the wrong namespace. Mistakes of that kind cause incidents as often as malice does.

Where a desktop client fits

Kubezilla Desktop is a native app for Linux, macOS and Windows with pod terminals, multi-cluster access and SSH tunneling in one interface. Kubeconfigs are stored securely on your own machine, with no cloud sync or telemetry, and the app is built in Rust for low memory use and fast startup. Opening a terminal into a chosen container from a list of pods means you pick the pod instead of typing its generated name, which removes a class of wrong-target errors. Our post on pod shells from a desktop client shows the five commands most people need and how the client speeds them up.

The client does not replace the controls above. Your RBAC still decides what a session may do, and your audit log still records it. What the client changes is where the credentials live and how much friction sits between you and the right pod.

Our view on exec access

We build Kubezilla Desktop for people who live in clusters all day, and the pattern we care about is simple: the safest exec session is one opened by the right person, into the right pod, with credentials that never left their machine.

That is why the app is local-first. Your kubeconfigs are stored securely on your device, there is no cloud sync and no telemetry, and remote clusters are reached directly or through SSH tunnels instead of VPN gymnastics. Fewer copies of a credential means fewer places for it to leak.

We also think speed is a security property. When the terminal opens in a native app that starts fast and shows every pod and container in a list, engineers stop reaching for broad shared contexts and cut-and-paste shortcuts. Combine that with narrow RBAC and audit alerts and exec stops being the scary part of your cluster.

Margus

Try it on your own clusters

If you manage several clusters and want pod terminals, logs, metrics, YAML editing, Helm and ArgoCD in one native app with your kubeconfigs kept on your own machine, Kubezilla Desktop is €5 per month. You can see what it does on the Kubezilla Desktop site.

Kubezilla Desktop

If you already work through a bastion, the app's SSH tunneling reaches the cluster directly without exposing the API server, which is the setup the hardening guides above recommend.

FAQ

What permission does kubectl exec need?

It needs create on the pods/exec subresource, and on newer clients that use WebSockets, get on pods/exec as well, plus get on the pod itself. A rule on pods alone does not grant it. Without resourceNames, the permission covers every pod in the namespace.

Can I see which commands people ran with kubectl exec?

Yes, in the API server audit log. A successful exec shows response code 101 and the command in the command= parameters of the request URI, even at Metadata level. The log shows the Kubernetes user, but runtime tools inside the node cannot yet tie in-container activity back to that user.

Does encrypting Secrets at rest protect them from exec?

No. Encryption at rest changes how Secrets are stored in etcd, not who can read them through the API or from inside a pod that has them mounted. Limiting pods/exec is the control that closes that path.

What should I use instead of exec for production debugging?

Use kubectl debug to attach an ephemeral container or work on a modified copy of the pod, so the original workload stays unchanged. Combine it with short-lived credentials and approval for production, as the Kubernetes project recommends.

Is blocking exec the same as blocking kubectl cp?

Practically, yes. Microsoft's threat matrix notes that kubectl cp wraps exec by running a tar process, so preventing exec into a container restricts kubectl cp as well.

Sources