//nefariousplan

CVE-2026-44182: Jupyter Enterprise Gateway's Launcher Decoded the Attacker's YAML Before Rendering It

vendor

pattern

cve

proof of concept

The kernel launcher in Jupyter Enterprise Gateway 3.2 has a comment above its template-rendering call. The comment reads, in full: Kubernetes API server will validate the pod spec instead.

The Kubernetes API server does validate pod specs. It validates them one document at a time, against the Pod schema. A privileged Pod with a hostPath volume at / mounted into the kernel namespace's service account is a perfectly valid pod spec.

CVE-2026-44182 is the gap between "Kubernetes will validate this" and what Kubernetes was actually being asked to validate.

The attacker writes through the front door

Jupyter Enterprise Gateway is the supported way to run Jupyter kernels on Kubernetes. A multi-tenant gateway receives kernel-start requests from notebook clients, spawns each kernel as a Pod in a configured namespace, and proxies the kernel protocol back to the requesting tenant. Tenants authenticate to the gateway with a token. Once authenticated, the API lets them describe the kernel they want.

The endpoint is POST /api/kernels. The handler is MainKernelHandler.post in enterprise_gateway/services/kernels/handlers.py. Pre-patch (3.2.x), the env-merge logic is six lines:

allowed_envs = model["env"].keys() if self.client_envs == ["*"] else self.client_envs
env.update(
    {
        key: value
        for key, value in model["env"].items()
        if key.startswith("KERNEL_") or key in allowed_envs
    }
)

value is whatever the client put in the JSON body. There is no isinstance(value, str) check. There is no length cap. There is no character-class restriction. Any tenant with a kernel-spawn token can attach an arbitrary string to any name starting with KERNEL_. The handler hands env to the kernel manager, which spawns the launcher process with that environment.

The patched handler adds two guards inside the loop:

for key, value in model["env"].items():
    if key.startswith("KERNEL_") or key in allowed_envs:
        if not isinstance(value, str):
            raise tornado.web.HTTPError(400, ...)
        if len(value) > MAX_ENV_VALUE_LENGTH:
            raise tornado.web.HTTPError(400, ...)
        env[key] = value

The type check rejects clients that POST a JSON object as the env value. The length check caps payloads at 4096 bytes. Both are downstream of the actual bug; neither would have prevented the demonstrated attack, since a 4 KB string is more than enough to render two pods. They are belt-and-suspenders against variants.

The launcher decoded the attacker's escapes before Jinja saw them

The launcher runs inside the cluster with a service account that holds create pods on the kernel namespace. Its first job is to build a Kubernetes manifest from the env vars in its own environment. The loop, pre-patch, in etc/kernel-launchers/kubernetes/scripts/launch_kubernetes.py:

for name, value in os.environ.items():
    if name.startswith("KERNEL_"):
        keywords[name.lower()] = yaml.safe_load(value)

yaml.safe_load(value) is not parsing. The value is a string that arrived through HTTP, was packed into a JSON body, was extracted by the handler, was passed through the kernel manager, and is now being read out of the launcher's process environment. By the time the launcher sees it, it is a flat byte sequence with no remaining YAML semantics.

yaml.safe_load does not know that. It is given a string. It treats the string as a YAML document and parses it. YAML's scalar rules include double-quoted strings with backslash escapes. If a tenant sends the bytes

"/tmp\"\n\nsecurityContext:\n  runAsUser: 0\n"

as the value of KERNEL_WORKING_DIR, yaml.safe_load returns the Python string

/tmp"

securityContext:
  runAsUser: 0

with a real embedded quote, real newlines, and real indentation. The decoder ran first. Whatever escapes the tenant chose to write into the request body, the launcher decoded into raw bytes before any other code touched them.

The line existed because two of Enterprise Gateway's environment variables, KERNEL_VOLUMES and KERNEL_VOLUME_MOUNTS, legitimately carry YAML lists of volume specs. The author wrote one loop to handle two classes of variable, the structured pair and the dozens of scalar variables, and chose to do so by YAML-decoding all of them. The patched code special-cases the two structured names and treats every other KERNEL_* as a raw string:

for name, value in os.environ.items():
    if name.startswith("KERNEL_"):
        if name in YAML_PARSED_KERNEL_VARS:
            parsed = yaml.safe_load(value)
            if not isinstance(parsed, list) or not all(
                isinstance(item, dict) for item in parsed
            ):
                sys.exit(f"ERROR - {name} must be a YAML list of mappings ...")
            keywords[name.lower()] = parsed
        else:
            keywords[name.lower()] = value

YAML_PARSED_KERNEL_VARS = {"KERNEL_VOLUME_MOUNTS", "KERNEL_VOLUMES"}. Two names. The cost of the original generality was that every attacker-controlled value got a free YAML escape decoder before reaching the template.

The template has no YAML escape

The template etc/kernel-launchers/kubernetes/scripts/kernel-pod.yaml.j2 is rendered with this Jinja Environment:

j_env = Environment(
    loader=FileSystemLoader(os.path.dirname(__file__)),
    trim_blocks=True,
    lstrip_blocks=True,
    autoescape=select_autoescape(
        disabled_extensions=("j2", "yaml"),
        default_for_string=True,
        default=True,
    ),
)

disabled_extensions=("j2", "yaml") means Jinja's HTML autoescape is intentionally turned off for files with these extensions. The author recognized that HTML escape is the wrong tool for YAML output. & and < are not the characters that break YAML. They removed HTML escape and added nothing in its place.

The template inlines variables as quoted YAML scalars:

apiVersion: v1
kind: Pod
metadata:
  name: "{{ kernel_pod_name }}"
  namespace: "{{ kernel_namespace }}"
spec:
  ...
  containers:
  - image: "{{ kernel_image }}"
    name: "{{ kernel_pod_name }}"
    ...
    {% if kernel_working_dir %}
    workingDir: "{{ kernel_working_dir }}"
    {% endif %}

After rendering with the decoded KERNEL_WORKING_DIR from the previous section, the workingDir: line becomes:

    workingDir: "/tmp"

securityContext:
  runAsUser: 0

"

The opening quote at column 16. The closing quote, fifty bytes later, at column 0, after a freshly indented securityContext: key the tenant authored. The intervening newlines and indentation are what yaml.safe_load decoded out of the request.

The patch adds a six-line filter and applies it to every interpolation in the template:

def yaml_safe_str(value):
    """Escape a value for safe inclusion in a YAML template."""
    if isinstance(value, str):
        return yaml.dump(value, default_style='"', width=10000).strip()
    if isinstance(value, (dict, list)):
        return yaml.dump(value, default_flow_style=True, width=10000).strip()
    return yaml.dump(value, width=10000).replace("\n...", "").strip()
-  name: "{{ kernel_pod_name }}"
-  namespace: "{{ kernel_namespace }}"
+  name: {{ kernel_pod_name | yaml_safe }}
+  namespace: {{ kernel_namespace | yaml_safe }}

The filter uses PyYAML's own serializer to emit a YAML-quoted scalar with backslash-escapes for control characters. PyYAML knew how to escape YAML. The template had never asked it.

The iterator creates every document the launcher renders

After Jinja renders the manifest, the launcher reparses it and iterates:

k8s_objs = yaml.safe_load_all(k8s_yaml)
for k8s_obj in k8s_objs:
    if k8s_obj.get("kind"):
        if k8s_obj["kind"] == "Pod":
            pod_template = extend_pod_env(k8s_obj)
            if pod_template_file is None:
                pod_created = client.CoreV1Api(client.ApiClient()).create_namespaced_pod(
                    body=k8s_obj, namespace=kernel_namespace
                )
        elif k8s_obj["kind"] == "Secret":
            client.CoreV1Api(client.ApiClient()).create_namespaced_secret(
                body=k8s_obj, namespace=kernel_namespace
            )
        elif k8s_obj["kind"] == "PersistentVolumeClaim":
            ...

The dispatch loop was written to support a template that might one day emit multiple resource types, a Pod plus a Secret plus a PVC, for a single kernel. It is generic. It does not assert that the rendered YAML produces exactly one Pod and nothing else.

The shaped attack is one POST request whose env.KERNEL_WORKING_DIR carries a value of approximately the form

/tmp
...
---
apiVersion: v1
kind: Pod
metadata:
  name: kernel-escape
spec:
  serviceAccountName: default
  hostNetwork: true
  containers:
  - name: x
    image: alpine
    command: ["/bin/sh", "-c", "chroot /host /bin/sh -c '...'"]
    securityContext:
      privileged: true
    volumeMounts:
    - name: host
      mountPath: /host
  volumes:
  - name: host
    hostPath:
      path: /
...

with the document boundaries and indentation YAML-encoded in the request body so that yaml.safe_load will decode them. The rendered manifest now contains the original kind: Pod document plus the injected one. The loop calls create_namespaced_pod twice. The second Pod runs privileged: true, mounts the node's root filesystem, and executes arbitrary commands in the host's namespace. The kernel namespace's service account creates it because the kernel namespace's service account is, by construction, the identity Enterprise Gateway uses to create kernel pods.

The patch's third layer makes that loop refuse this shape:

ALLOWED_K8S_KINDS = {"Pod", "Secret", "PersistentVolumeClaim",
                     "PersistentVolume", "Service", "ConfigMap"}
MAX_DOCUMENTS_PER_KIND = 1
...
for k8s_obj in k8s_objs:
    kind = k8s_obj.get("kind")
    if kind not in ALLOWED_K8S_KINDS:
        sys.exit(f"ERROR - Unexpected resource kind '{kind}' ...")
    kind_counts[kind] = kind_counts.get(kind, 0) + 1
for kind, count in kind_counts.items():
    if count > MAX_DOCUMENTS_PER_KIND:
        sys.exit(f"ERROR - Rendered manifest contains {count} '{kind}' documents ...")

Allowlist of kinds. One document per kind. The rendered manifest is checked against the shape the template was ever supposed to emit, not against the shape that happens to be a valid Kubernetes resource.

Kubernetes was the wrong layer to validate this

The pre-patch source had a comment positioned above the generate_kernel_pod_yaml call:

# jinja2 template substitutes template variables with None though keywords doesn't
# contain corresponding item. Therefore, no need to check if any are left unsubstituted.
# Kubernetes API server will validate the pod spec instead.
k8s_yaml = j_env.get_template(KERNEL_POD_TEMPLATE_PATH).render(**keywords)

The third sentence is the structural reason for the bug. The author explicitly outsourced validation to a downstream layer. Kubernetes is the canonical layer for validating pod specs, it owns the schema. But the layer Enterprise Gateway needed validation at was not the schema. It was the boundary between "this is the Pod the gateway meant to create" and "this is whatever the attacker chose to render through the template."

The Kubernetes API server cannot see that boundary. It receives one request body at a time. Each body is, individually, a valid Pod or Secret or PVC. The fact that the gateway was supposed to send one Pod and is actually sending two is not the kind of fact the API server is in a position to detect. The schema validator owns "is this a legal pod spec." It does not own "is this the pod spec the caller intended."

This is the shape of content-is-command applied to a control-plane API. The kernel manifest is, by construction, a stream the gateway treats as command, kubectl-style. The decoded escape sequences inside KERNEL_WORKING_DIR are content the gateway accepted as data. The boundary between content and command lived inside the launcher and was implemented as yaml.safe_load(value), which collapses it. Earlier exhibits in the catalog put external content into shell interpreters, SQL interpreters, template-engine interpreters; CVE-2026-44182 puts external content into a Kubernetes manifest interpreter that the launcher then walks document by document, instantiating each.

The patch ships three defense layers

The commit message for 2258a41 is explicit:

L1: Replace yaml.safe_load() on scalar env vars with raw string usage. Only KERNEL_VOLUME_MOUNTS and KERNEL_VOLUMES retain YAML parsing.

L2: Add a yaml_safe Jinja2 filter using PyYAML's own dump() to produce properly escaped YAML scalars. Applied to every template variable.

L3: Post-render validation ensures rendered manifests contain only expected resource kinds and document counts.

L1 is the entire demonstrated chain. Without yaml.safe_load(value) running on KERNEL_WORKING_DIR, the attacker's \n reaches Jinja as the literal two bytes \ and n. Jinja inlines those two bytes between the quotes in the template. yaml.safe_load_all on the rendered manifest sees workingDir: "/tmp\nsecurityContext: ...", a single quoted string containing the literal characters of the would-be exploit payload, which Kubernetes then rejects as an invalid working directory. No second document, no injected Pod.

L2 closes a sibling hole. The two variables that legitimately carry YAML, KERNEL_VOLUMES and KERNEL_VOLUME_MOUNTS, still pass through yaml.safe_load because they have to: the template iterates them as Python lists. A tenant who supplies a list element that is a dict with attacker-chosen keys, say {"name": "x", "mountPath": "/host\nsecurityContext:\n privileged: true"}, gets that dict rendered into the template via - {{ volume_mount }}. The yaml_safe filter walks the dict through PyYAML's serializer, emitting {name: x, mountPath: "/host\nsecurityContext:\n privileged: true"} as a flow mapping, with the inner string YAML-quoted. The escape characters survive as escape characters; the YAML parser sees a single scalar value, not a structural injection.

L3 catches the shape after rendering. Even if some future variable carries structured input that legitimately needs YAML parsing, and even if some future template author forgets to apply the yaml_safe filter to a single interpolation, the launcher refuses to act on a rendered manifest whose kinds it did not expect or whose document count exceeds one per kind. The chokepoint the original comment outsourced to the Kubernetes API server has been put back inside the launcher, where the boundary it is checking can actually be observed.

The author of the patch did not trust L1 to stay correct against future code churn. The author of the patch did not trust L2 to be applied to every variable in every template, including templates that have not been written yet. The author of the patch wrote L3 specifically so that future regressions of L1 or L2 would not be CVEs.

What was actually missing

The patch is three layers because the original implementation collapsed three trust boundaries onto one line. yaml.safe_load(value) did the work of decoding tenant input, while presenting at code review as parsing. The Jinja2 environment had HTML autoescape and the author correctly turned it off, while leaving the actual sink, YAML, with no escape at all. The for k8s_obj in k8s_objs loop dispatched on kind and called the create-namespaced-X API for whichever kind it found, while the comment two lines above the template render outsourced "is this the manifest the gateway intended" to a layer that cannot see the intention.

Each of these is a defensible local decision. Together they form the bug. The patch shipped three defense layers because the author of the patch knew that fixing one would not be evidence that the others were not bugs.

PoC: github.com/advisories/GHSA-cfw7-6c5v-2wjq

The patch ships three defense layers. The first one is the bug. The other two are insurance against the day someone reintroduces it.