-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA256 NEFARIOUSPLAN-CANONICAL-V1 {"body_md":"## The attacker writes through the front door\n\nJupyter 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.\n\nThe 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:\n\n```python\nallowed_envs = model[\"env\"].keys() if self.client_envs == [\"*\"] else self.client_envs\nenv.update(\n {\n key: value\n for key, value in model[\"env\"].items()\n if key.startswith(\"KERNEL_\") or key in allowed_envs\n }\n)\n```\n\n`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.\n\nThe patched handler adds two guards inside the loop:\n\n```python\nfor key, value in model[\"env\"].items():\n if key.startswith(\"KERNEL_\") or key in allowed_envs:\n if not isinstance(value, str):\n raise tornado.web.HTTPError(400, ...)\n if len(value) > MAX_ENV_VALUE_LENGTH:\n raise tornado.web.HTTPError(400, ...)\n env[key] = value\n```\n\nThe 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.\n\n## The launcher decoded the attacker's escapes before Jinja saw them\n\nThe 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`:\n\n```python\nfor name, value in os.environ.items():\n if name.startswith(\"KERNEL_\"):\n keywords[name.lower()] = yaml.safe_load(value)\n```\n\n`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.\n\n`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\n\n```\n\"/tmp\\\"\\n\\nsecurityContext:\\n runAsUser: 0\\n\"\n```\n\nas the value of `KERNEL_WORKING_DIR`, `yaml.safe_load` returns the Python string\n\n```\n/tmp\"\n\nsecurityContext:\n runAsUser: 0\n\n```\n\nwith 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.\n\nThe 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:\n\n```python\nfor name, value in os.environ.items():\n if name.startswith(\"KERNEL_\"):\n if name in YAML_PARSED_KERNEL_VARS:\n parsed = yaml.safe_load(value)\n if not isinstance(parsed, list) or not all(\n isinstance(item, dict) for item in parsed\n ):\n sys.exit(f\"ERROR - {name} must be a YAML list of mappings ...\")\n keywords[name.lower()] = parsed\n else:\n keywords[name.lower()] = value\n```\n\n`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.\n\n## The template has no YAML escape\n\nThe template `etc/kernel-launchers/kubernetes/scripts/kernel-pod.yaml.j2` is rendered with this Jinja Environment:\n\n```python\nj_env = Environment(\n loader=FileSystemLoader(os.path.dirname(__file__)),\n trim_blocks=True,\n lstrip_blocks=True,\n autoescape=select_autoescape(\n disabled_extensions=(\"j2\", \"yaml\"),\n default_for_string=True,\n default=True,\n ),\n)\n```\n\n`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.\n\nThe template inlines variables as quoted YAML scalars:\n\n```yaml\napiVersion: v1\nkind: Pod\nmetadata:\n name: \"{{ kernel_pod_name }}\"\n namespace: \"{{ kernel_namespace }}\"\nspec:\n ...\n containers:\n - image: \"{{ kernel_image }}\"\n name: \"{{ kernel_pod_name }}\"\n ...\n {% if kernel_working_dir %}\n workingDir: \"{{ kernel_working_dir }}\"\n {% endif %}\n```\n\nAfter rendering with the decoded `KERNEL_WORKING_DIR` from the previous section, the `workingDir:` line becomes:\n\n```yaml\n workingDir: \"/tmp\"\n\nsecurityContext:\n runAsUser: 0\n\n\"\n```\n\nThe 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.\n\nThe patch adds a six-line filter and applies it to every interpolation in the template:\n\n```python\ndef yaml_safe_str(value):\n \"\"\"Escape a value for safe inclusion in a YAML template.\"\"\"\n if isinstance(value, str):\n return yaml.dump(value, default_style='\"', width=10000).strip()\n if isinstance(value, (dict, list)):\n return yaml.dump(value, default_flow_style=True, width=10000).strip()\n return yaml.dump(value, width=10000).replace(\"\\n...\", \"\").strip()\n```\n\n```diff\n- name: \"{{ kernel_pod_name }}\"\n- namespace: \"{{ kernel_namespace }}\"\n+ name: {{ kernel_pod_name | yaml_safe }}\n+ namespace: {{ kernel_namespace | yaml_safe }}\n```\n\nThe 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.\n\n## The iterator creates every document the launcher renders\n\nAfter Jinja renders the manifest, the launcher reparses it and iterates:\n\n```python\nk8s_objs = yaml.safe_load_all(k8s_yaml)\nfor k8s_obj in k8s_objs:\n if k8s_obj.get(\"kind\"):\n if k8s_obj[\"kind\"] == \"Pod\":\n pod_template = extend_pod_env(k8s_obj)\n if pod_template_file is None:\n pod_created = client.CoreV1Api(client.ApiClient()).create_namespaced_pod(\n body=k8s_obj, namespace=kernel_namespace\n )\n elif k8s_obj[\"kind\"] == \"Secret\":\n client.CoreV1Api(client.ApiClient()).create_namespaced_secret(\n body=k8s_obj, namespace=kernel_namespace\n )\n elif k8s_obj[\"kind\"] == \"PersistentVolumeClaim\":\n ...\n```\n\nThe 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.\n\nThe shaped attack is one POST request whose `env.KERNEL_WORKING_DIR` carries a value of approximately the form\n\n```\n/tmp\n...\n---\napiVersion: v1\nkind: Pod\nmetadata:\n name: kernel-escape\nspec:\n serviceAccountName: default\n hostNetwork: true\n containers:\n - name: x\n image: alpine\n command: [\"/bin/sh\", \"-c\", \"chroot /host /bin/sh -c '...'\"]\n securityContext:\n privileged: true\n volumeMounts:\n - name: host\n mountPath: /host\n volumes:\n - name: host\n hostPath:\n path: /\n...\n```\n\nwith 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.\n\nThe patch's third layer makes that loop refuse this shape:\n\n```python\nALLOWED_K8S_KINDS = {\"Pod\", \"Secret\", \"PersistentVolumeClaim\",\n \"PersistentVolume\", \"Service\", \"ConfigMap\"}\nMAX_DOCUMENTS_PER_KIND = 1\n...\nfor k8s_obj in k8s_objs:\n kind = k8s_obj.get(\"kind\")\n if kind not in ALLOWED_K8S_KINDS:\n sys.exit(f\"ERROR - Unexpected resource kind '{kind}' ...\")\n kind_counts[kind] = kind_counts.get(kind, 0) + 1\nfor kind, count in kind_counts.items():\n if count > MAX_DOCUMENTS_PER_KIND:\n sys.exit(f\"ERROR - Rendered manifest contains {count} '{kind}' documents ...\")\n```\n\nAllowlist 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.\n\n## Kubernetes was the wrong layer to validate this\n\nThe pre-patch source had a comment positioned above the `generate_kernel_pod_yaml` call:\n\n```python\n# jinja2 template substitutes template variables with None though keywords doesn't\n# contain corresponding item. Therefore, no need to check if any are left unsubstituted.\n# Kubernetes API server will validate the pod spec instead.\nk8s_yaml = j_env.get_template(KERNEL_POD_TEMPLATE_PATH).render(**keywords)\n```\n\nThe 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.\"\n\nThe 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.\"\n\nThis 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.\n\n## The patch ships three defense layers\n\nThe commit message for `2258a41` is explicit:\n\n> L1: Replace yaml.safe_load() on scalar env vars with raw string usage. Only KERNEL_VOLUME_MOUNTS and KERNEL_VOLUMES retain YAML parsing.\n>\n> L2: Add a yaml_safe Jinja2 filter using PyYAML's own dump() to produce properly escaped YAML scalars. Applied to every template variable.\n>\n> L3: Post-render validation ensures rendered manifests contain only expected resource kinds and document counts.\n\nL1 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.\n\nL2 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.\n\nL3 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.\n\nThe 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.\n\n## What was actually missing\n\nThe 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.\n\nEach 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.\n\nPoC: [github.com/advisories/GHSA-cfw7-6c5v-2wjq](https://github.com/advisories/GHSA-cfw7-6c5v-2wjq)","closing_line":"The patch ships three defense layers. The first one is the bug. The other two are insurance against the day someone reintroduces it.","hook_md":"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.`\n\nThe 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.\n\nCVE-2026-44182 is the gap between \"Kubernetes will validate this\" and what Kubernetes was actually being asked to validate.","post_id":551,"slug":"jupyter-enterprise-gateway-cve-2026-44182-launcher-decoded-the-payload","title":"CVE-2026-44182: Jupyter Enterprise Gateway's Launcher Decoded the Attacker's YAML Before Rendering It","type":"initial","unreadable_sentence":"The patch ships three defense layers. The first one is the entire CVE. The other two are insurance against the day someone reintroduces it."} -----BEGIN PGP SIGNATURE----- iHUEARYIAB0WIQRf0htP5+SjynlxywneZjl4jgkQJgUCaqRN1QAKCRDeZjl4jgkQ JsaOAP9Sxugt+tLgKnvdt+Ac7URFaXwA5Vfki83W8zGY/p9kWQD/bkZ0sNTXCxTP Haxd1EjdsLwgFwATrEIQGx5NVNseEAU= =6Glw -----END PGP SIGNATURE-----